diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs index 87a153f7b030d..8e79fceda4142 100644 --- a/.pnpmfile.cjs +++ b/.pnpmfile.cjs @@ -1,16 +1,22 @@ const fs = require("node:fs"); const path = require("node:path"); -// Our forks ship as tarballs in apps/mobile/deps. A pnpm patch on one is a second source of -// truth that the next tarball silently drops, so changes go to the fork (apps/mobile/deps/README.md). +// Our forks ship as tarballs in apps/mobile/deps and apps/web/deps. A pnpm patch on one is a +// second source of truth that the next tarball silently drops, so changes go to the fork (see +// the README beside each tarball). +const FORK_APPS = ["apps/mobile", "apps/web"]; + function forkTarballPatches(patchedDependencies) { - const manifestPath = path.join(__dirname, "apps/mobile/package.json"); - // Release staging installs a partial workspace without the mobile app. - if (!patchedDependencies || !fs.existsSync(manifestPath)) return []; - const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - const forks = Object.keys(dependencies).filter((name) => - String(dependencies[name]).startsWith("file:deps/"), - ); + if (!patchedDependencies) return []; + const forks = FORK_APPS.flatMap((app) => { + const manifestPath = path.join(__dirname, app, "package.json"); + // Release staging installs a partial workspace without every app. + if (!fs.existsSync(manifestPath)) return []; + const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + return Object.keys(dependencies).filter((name) => + String(dependencies[name]).startsWith("file:deps/"), + ); + }); return Object.keys(patchedDependencies).filter((key) => forks.some((name) => key === name || key.startsWith(`${name}@`)), ); @@ -23,7 +29,7 @@ module.exports = { if (forkPatches.length > 0) { throw new Error( `pnpm-workspace.yaml patches ${forkPatches.join(", ")}, which ships as a fork tarball in ` + - "apps/mobile/deps. Change the fork and replace the tarball instead (apps/mobile/deps/README.md).", + "an app's deps directory. Change the fork and replace the tarball instead (deps/README.md).", ); } // Windows installs need Linux x64 glibc binaries because WSL shares node_modules. diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 0ccce648bba61..ba09871ee1c5a 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import * as NetService from "@t3tools/shared/Net"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -173,6 +174,31 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( ); // Spawns the local backend as soon as the protocol, IPC, and legacy storage that every window needs exist. +/** + * The server reads T3CODE_FEATURE_FLAGS once at start, from the value cached at the last + * discovery. When the login shell now sets different flags, restart it so they apply. + */ +const restartOnFeatureFlagChange = Effect.fn("desktop.restartOnFeatureFlagChange")(function* ( + backend: DesktopBackendManager.DesktopBackendInstance, +) { + const state = yield* DesktopState.DesktopState; + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; + let startedWith = (yield* HostProcess.Environment).T3CODE_FEATURE_FLAGS; + yield* shellEnvironment.updates.pipe( + Stream.filter((snapshot) => snapshot.discovered), + Stream.runForEach( + Effect.fnUntraced(function* (snapshot) { + const flags = snapshot.environment.T3CODE_FEATURE_FLAGS ?? undefined; + if (flags === startedWith || (yield* Ref.get(state.quitting))) return; + startedWith = flags; + yield* logBootstrapInfo("restarting backend for changed T3CODE_FEATURE_FLAGS"); + yield* backend.stop(); + yield* backend.start; + }), + ), + ); +}); + const startLocalBackend = Effect.gen(function* () { const state = yield* DesktopState.DesktopState; const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -268,6 +294,7 @@ const startLocalBackend = Effect.gen(function* () { } yield* primaryBackend.start; yield* logBootstrapInfo("bootstrap backend start requested"); + yield* Effect.forkScoped(restartOnFeatureFlagChange(primaryBackend)); // The renderer asks for this token first; minting it at readiness saves a round trip. yield* Effect.forkScoped( (yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth).getBearerToken.pipe( diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 3e8b4967dfde5..929148fdbb32f 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -69,7 +69,7 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { // Stays up after a signal until the test lets it finish, like a server shutting down. const SLOW_SERVER = [ "#!/bin/sh", - "trap 'echo stopping >&3; read go; echo stopped >&3; exit 0' TERM HUP", + "trap 'echo stopping >&3; read go; echo \"stopped $go\" >&3; exit 7' TERM HUP", "echo ready", "while :; do sleep 0.05; done", "", @@ -101,9 +101,16 @@ const lines = (stream: NodeJS.ReadableStream) => { }; describe("renderCliShim", () => { - it.skipIf(!hasSetsid).each(["SIGTERM", "SIGHUP"] as const)( - "keeps the AppImage mounted until the server exits after %s to the process group", - async (signal) => { + // Ctrl-C, an SSH hangup, or a supervisor signals the process group. systemd's default KillMode + // also signals the mounter, and KillMode=mixed signals only the launcher. + it.skipIf(!hasSetsid).each([ + ["SIGTERM", "the process group"], + ["SIGHUP", "the process group"], + ["SIGTERM", "every process"], + ["SIGTERM", "the launcher"], + ] as const)( + "keeps the AppImage mounted until the server exits after %s to %s", + async (signal, target) => { const { root, shim } = fakeAppImage(true, SLOW_SERVER); const child = NodeChildProcess.spawn(shim, [], { detached: true, @@ -114,12 +121,12 @@ describe("renderCliShim", () => { try { const stdout = lines(child.stdout!); const events = lines(child.stdio[3] as NodeJS.ReadableStream); - const exited = new Promise((resolve) => child.on("close", resolve)); + const exited = new Promise((resolve) => child.on("close", resolve)); await stdout.until((line) => line === "ready"); mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8")); - // Ctrl-C in a terminal, a closed SSH session, or a service manager signals the whole group. - process.kill(-child.pid!, signal); + process.kill(target === "the launcher" ? child.pid! : -child.pid!, signal); + if (target === "every process") process.kill(mounter, signal); // The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and // HUP, so a mounter that also got the group signal unmounts before it answers this probe. process.kill(mounter, "SIGWINCH"); @@ -128,8 +135,8 @@ describe("renderCliShim", () => { await events.until((line) => line === "stopping"); child.stdin!.end("go\n"); - await exited; - expect(events.seen.slice(-2)).toEqual(["stopped", "unmounted"]); + expect(await exited).toBe(7); + expect(events.seen.slice(-2)).toEqual(["stopped go", "unmounted"]); } finally { for (const pid of [-child.pid!, mounter]) { if (pid === undefined) continue; @@ -156,6 +163,8 @@ describe("renderCliShim", () => { const result = run(shim, ["--version"]); expect(result.status).toBe(3); expect(result.stdout).toContain(`appimage=${appImage}`); + const closedStdin = NodeChildProcess.spawnSync("sh", ["-c", '"$0" --version <&-', shim]); + expect(closedStdin.status).toBe(3); }); it("keeps the install's T3 home under sudo, unless one is set", () => { diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index 217f3b327dc9e..0f7e605da6b36 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -91,11 +91,15 @@ export const renderCliShim = (input: { // Extract-and-run would make the runtime start the app instead of mounting it. "unset APPIMAGE_EXTRACT_AND_RUN", // Its own session keeps a group signal (Ctrl-C, SSH hangup) from unmounting it under the - // running server; the traps unmount it after. Without setsid the extract fallback runs. + // running server, and ignoring TERM survives a stop sent to every process (systemd's default). + // Without setsid the extract fallback runs. "work=$(mktemp -d) || exit 1", + "trap '' TERM", 'setsid "$app" --appimage-mount >"$work/mount" 2>/dev/null &', "mounter=$!", - `trap 'kill "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, + // It unmounts itself on TERM, which it now ignores, so the trap unmounts it. Lazily, like the + // runtime: the server's own children may still be exiting. + `trap '[ -z "$mount" ] || fusermount3 -uz "$mount" 2>/dev/null || fusermount -uz "$mount" 2>/dev/null; kill -HUP "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, "trap 'exit 130' INT TERM HUP", "mount=", 'while kill -0 "$mounter" 2>/dev/null; do', @@ -111,7 +115,24 @@ export const renderCliShim = (input: { "fi", // The runtime sets this when it launches the app; the CLI skips its path-keyed compile cache on it. 'export APPIMAGE="$app"', - run("$mount"), + // The shell must outlive the CLI to unmount, so it forwards TERM and HUP; the terminal sends + // Ctrl-C to the CLI directly. A background child would read /dev/null, so pass stdin on fd 9. + // With stdin closed, `exec 9<&0` would end the shell; `command` makes it a normal error. + "{ command exec 9<&0; } 2>/dev/null || exec 9/dev/null' TERM`, + `trap 'kill -HUP "$cli" 2>/dev/null' HUP`, + "trap '' INT", + "status=0", + 'wait "$cli" || status=$?', + // A trapped signal interrupts wait; wait again for the CLI's own exit status. + 'while kill -0 "$cli" 2>/dev/null; do', + " status=0", + ' wait "$cli" || status=$?', + "done", + 'exit "$status"', "", ].join("\n"); }; diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 9c12690f31351..5474583be9976 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -89,8 +89,7 @@ const WSL_FORWARDED_ENV_NAMES = [ "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", // Otherwise the WSL server keeps exporting to endpoints from the bootstrap. "T3CODE_OTEL_SDK_DISABLED", "OTEL_SDK_DISABLED", 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/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index f9ab0d6c3a054..620fd8f561fa8 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -123,8 +123,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", @@ -555,8 +554,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "JAVA_HOME", "PNPM_HOME", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { @@ -663,6 +661,8 @@ const CACHED_ENV_NAMES = [ "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", + // The server reads its flags once at start, before discovery can finish. + "T3CODE_FEATURE_FLAGS", ] as const; /** @public */ diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 464f7ab9929b0..a868851d5c9da 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -471,9 +471,6 @@ const config: ExpoConfig = { ], extra: { appVariant: APP_VARIANT, - secretsFeatureEnabled: ["1", "true"].includes( - process.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", - ), iosPersonalTeamBuild: isIosPersonalTeamBuild, relay: { url: repoEnv.T3CODE_RELAY_URL ?? null, diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 1208f3176935d..b4183cb3c8fcf 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -421,7 +421,7 @@ class T3WorkspaceNavigationView( } private fun expandedTabTitle(tab: String) = - if (tab == "pullRequests") "Pull Requests" else tabTitle(tab) + if (tab == "pullRequests") "Pull requests" else tabTitle(tab) @Composable private fun tabIconPainter(tab: String) = painterResource( diff --git a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx index 3251cb8773f03..f0604d6b4ceb6 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx @@ -10,7 +10,7 @@ import { useContext, useMemo, useState, type ComponentProps, type ReactNode } fr import { Platform, Pressable, ScrollView, StyleSheet, View } from "react-native"; import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; import { pullRequestImageSource } from "./pullRequestMediaSource"; -import { parseMarkdownDocument } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, parseMarkdownDocument } from "../../lib/markdownDocument"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; @@ -44,7 +44,7 @@ export function PullRequestDescription(props: { const document = parseMarkdownDocument(props.markdown); const content = pullRequestDescriptionContent( document, - splitPullRequestBody(props.markdown), + splitPullRequestBody(props.markdown, markdownReferenceDefinitions), messages, ); return { diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx index 3654cfd87bb42..c1852a6ee2601 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx @@ -17,7 +17,7 @@ import { createContext, useContext, useMemo, useState } from "react"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; +} from "@t3tools/client-runtime/pull-request-references"; import { sourceControlClients, type ReferenceAutolink, @@ -28,6 +28,7 @@ import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; import { markdownImageSources } from "../../lib/markdownImageSources"; +import { markdownReferenceDefinitions } from "../../lib/markdownDocument"; import { FilePreviewGallery, useFilePreviewGallery } from "../../components/ui/FilePreviewGallery"; import { pullRequestImageSource } from "./pullRequestMediaSource"; import { @@ -124,7 +125,10 @@ export function PullRequestMarkdown(props: { }) { const mediaContext = useContext(PullRequestMediaContext); const changeRequestUrl = useContext(ChangeRequestUrlContext); - const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]); + const segments = useMemo( + () => splitPullRequestBody(props.markdown, markdownReferenceDefinitions), + [props.markdown], + ); const [undoneTicks, setUndoneTicks] = useState(0); const gallery: FilePreviewItem[] = markdownImageSources( props.imageGroupMarkdown ?? props.markdown, diff --git a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts index 6500a79885a8d..7acb1640694f7 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts @@ -1,4 +1,4 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; import { describe, expect, it } from "vite-plus/test"; import { nativePullRequestMarkdown } from "./pullRequestAutolinks"; diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts index 6d6a1bfe4b624..74e21d39018ee 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import type { MarkdownNode } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, type MarkdownNode } from "../../lib/markdownDocument"; import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown"; import { pullRequestDescriptionContent } from "./pullRequestDescriptionContent"; @@ -15,6 +15,7 @@ describe("PR attachments", () => { } as MarkdownNode; const media = splitPullRequestBody( `${uri}\n\nhttps://drop.example.com/demo.mp4\n\nhttps://github.com/user-attachments/assets/123-abc`, + markdownReferenceDefinitions, ); expect(pullRequestDescriptionContent(document, media).attachments).toEqual([ { uri, caption: "Screenshot", kind: "image" }, @@ -30,6 +31,7 @@ describe("PR attachments", () => { it("collects videos from a before/after table", () => { const media = splitPullRequestBody( "\n\n\n
BeforeAfter
\n\nhttps://drop.example.com/before.mp4\n\n\n\nhttps://drop.example.com/after.mp4\n\n
", + markdownReferenceDefinitions, ); expect( pullRequestDescriptionContent({ type: "root" } as MarkdownNode, media).attachments, diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts index 105f4a1095009..5758e6b2ee84a 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts @@ -8,7 +8,7 @@ import { } from "@t3tools/client-runtime/pull-request-editing"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PullRequestDetail } from "@t3tools/contracts"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { AsyncResult } from "effect/reactivity"; import { useGT } from "gt-react-native"; import { useRef, useState } from "react"; diff --git a/apps/mobile/src/features/settings/CloudVoiceSection.tsx b/apps/mobile/src/features/settings/CloudVoiceSection.tsx index dceb42d86e457..3e782d2457fa3 100644 --- a/apps/mobile/src/features/settings/CloudVoiceSection.tsx +++ b/apps/mobile/src/features/settings/CloudVoiceSection.tsx @@ -2,6 +2,7 @@ import { T, useGT, useMessages } from "gt-react-native"; import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; import { setCloudSpeechKey } from "@t3tools/client-runtime/voice-input"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { configuredSecretSources, secretRequestReference, @@ -20,7 +21,6 @@ import { type VoiceTranscriptionDestination, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; -import Constants from "expo-constants"; import { AsyncResult } from "effect/reactivity"; import { type ReactNode, useState } from "react"; import { ScrollView, TextInput, View } from "react-native"; @@ -199,7 +199,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const [model, setModel] = useState(""); const [sourceId, setSourceId] = useState(null); const sources = - Constants.expoConfig?.extra?.secretsFeatureEnabled === true && + hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings.secretProviders, messages) : []; diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 8a2a7e83a6698..53b773dc7f9c4 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -106,10 +106,7 @@ import { settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import { - classifyMarkdownImageSource, - markdownImageSourceFragment, -} from "@t3tools/client-runtime/markdown-images"; +import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images"; import { contextCompactionTokenCounts, resolveViewedImageAsset, @@ -3743,20 +3740,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { /> ); } - if (imageSource._tag === "Blocked") { + if ( + media?.kind !== "image" || + !("resource" in media.source) || + media.source.resource._tag !== "media-file" + ) { return ; } return ( ); diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx index 82f5cc62a7b68..2f2bffa336402 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx @@ -82,9 +82,6 @@ vi.mock("expo/fetch", () => ({ fetch: vi.fn() })); vi.mock("react-native-svg", () => ({ parse: vi.fn(), SvgAst: () => null })); vi.mock("@t3tools/client-runtime/state/assets", () => ({ MISSING_FILE_ACCESS_MESSAGE: "" })); vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); -vi.mock("../../components/ui/FilePreviewGallery", () => ({ - useFilePreviewGallery: () => (source: unknown) => source, -})); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => {children}, })); @@ -96,11 +93,64 @@ vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() })); import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AtomRegistry } from "effect/reactivity"; import { fetch } from "expo/fetch"; import { parse } from "react-native-svg"; -import { MarkdownImageAvailableWidthContext, ThreadMarkdownImageView } from "./ThreadMarkdownImage"; +import { FilePreviewGallery } from "../../components/ui/FilePreviewGallery"; +import type { FilePreviewSource } from "../../components/ui/FilePreviewModal.types"; +import { useAssetUrlState } from "../../state/assets"; +import { + MarkdownImageAvailableWidthContext, + ThreadMarkdownImage, + ThreadMarkdownImageView, +} from "./ThreadMarkdownImage"; + +it("keeps the tapped workspace image fragment on its gallery page", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + const environmentId = EnvironmentId.make("environment-1"); + const threadId = ThreadId.make("thread-1"); + const resource = { _tag: "media-file", threadId, path: "/repo/./red.png" } as const; + const red = { kind: "image", environmentId, resource, srcFragment: "#detail" } as const; + const blue = { + kind: "image", + environmentId, + resource: { ...resource, path: "/repo/./blue.png" }, + } as const; + const openPreview = vi.fn<(source: FilePreviewSource) => void>(); + vi.mocked(useAssetUrlState).mockReturnValueOnce({ + _tag: "Success", + url: "https://example.test/red.png", + expiresAt: 0, + }); + try { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => harness.pressable.onPress?.({ nativeEvent: {} })); + expect(openPreview).toHaveBeenCalledWith( + expect.objectContaining({ + resource, + srcFragment: "#detail", + gallery: [expect.objectContaining(red), blue], + }), + ); + } finally { + await act(async () => root.unmount()); + } +}); it("keeps the frame size when the same image reports a different decoded width", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx index 8a7540625cc08..8e18d8445c85a 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx @@ -342,6 +342,7 @@ export function ThreadMarkdownImage(props: { gallery: undefined, environmentId: props.environmentId, resource: props.resource, + ...(props.srcFragment === undefined ? {} : { srcFragment: props.srcFragment }), }), ); }} diff --git a/apps/mobile/src/lib/composerContext.test.ts b/apps/mobile/src/lib/composerContext.test.ts index e2a5a015c61af..255666ebcf0b2 100644 --- a/apps/mobile/src/lib/composerContext.test.ts +++ b/apps/mobile/src/lib/composerContext.test.ts @@ -8,6 +8,7 @@ import { type ServerProviderSkill, } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, @@ -167,7 +168,7 @@ describe("mobile composer context", () => { const modelTokens = (text: string) => composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), new Set(), collectComposerModelTokens(text, known), ) @@ -256,7 +257,7 @@ describe("mobile composer context", () => { const skills = [babysit, disabled, agentOnly]; const tokens = composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ); expect(tokens.map((token) => token.source)).toEqual([ @@ -271,14 +272,14 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([]), ).map((token) => token.type), ).toEqual(["mention", "context", "context", "citation", "citation"]); expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([{ ...babysit, name: "HOME" }]), ) .filter((token) => token.type === "skill") @@ -292,7 +293,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(promoted), ) .filter((token) => token.type === "skill") @@ -301,7 +302,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ) .filter((token) => token.type === "skill") diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 754774c4f1306..219a61108fd51 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -40,6 +40,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; const isMessageContext = Schema.is(OrchestrationMessageContext); const decodeMessageContext = Schema.decodeUnknownOption(OrchestrationMessageContext); @@ -73,7 +74,7 @@ export function composerMentionPath(source: string, context?: OrchestrationMessa const record = context?.records.find((entry) => entry.contextId === reference.contextId); return record?.kind === "mention" && "path" in record ? record.path : null; } - const token = collectComposerInlineTokens(`${source} `)[0]; + const token = collectComposerInlineTokens(`${source} `, { findMath: markdownMathRanges })[0]; return token?.type === "mention" && token.source === source ? token.value : null; } @@ -222,7 +223,12 @@ export function composerContextEditorTokens( !references.some((ref) => token.start < ref.end && token.end > ref.start) && !citations.some((ref) => token.start < ref.end && token.end > ref.start), ); - const taken = [...inlineTokens, ...references, ...citations, ...composerMathRanges(text)]; + const taken = [ + ...inlineTokens, + ...references, + ...citations, + ...composerMathRanges(text, markdownMathRanges), + ]; const models = modelTokens.filter( (mention) => !taken.some((range) => mention.start < range.end && mention.end > range.start), ); diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index cd0bd8ae9890c..7c463ac0c3438 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -23,6 +23,7 @@ import { acquireAudioSession, activateAudioSession, releaseAudioSession } from " import { ThreadFeed } from "../features/threads/ThreadFeed"; import type { ThreadFeedEntry } from "./threadActivity"; import type { MarkdownImageRenderer } from "../native/SelectableMarkdownText"; +import type { FilePreviewItem, FilePreviewSource } from "../components/ui/FilePreviewModal.types"; const audio = vi.hoisted(() => ({ status: { @@ -203,12 +204,18 @@ vi.mock("../native/SelectableMarkdownText", () => ({ onLinkPress(href: string): void; renderImage?: MarkdownImageRenderer; }) => { - const embed = props.markdown.match(/!\[([^\]]*)\]\(([^)]+)\)/); + const embeds = [...props.markdown.matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)]; return createElement( "div", null, createElement("button", { onClick: () => props.onLinkPress("target.ts") }, props.markdown), - embed && props.renderImage?.({ href: embed[2]!, alt: embed[1]!, title: null }), + embeds.map(([, alt, href], index) => + createElement( + Fragment, + { key: index }, + props.renderImage?.({ href: href!, alt: alt!, title: null }), + ), + ), ); }, })); @@ -238,7 +245,9 @@ vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0 }), })); vi.mock("expo-haptics", () => ({ selectionAsync: async () => {} })); -vi.mock("expo-image", () => ({})); +vi.mock("expo-image", () => ({ Image: () => null })); +vi.mock("expo/fetch", () => ({})); +vi.mock("react-native-svg", () => ({})); vi.mock("uniwind", () => ({})); vi.mock("../components/ui/Dialog", () => ({})); vi.mock("../components/ui/Sheet", () => ({ @@ -254,13 +263,19 @@ vi.mock("../components/ui/NativePresentation", () => ({ vi.mock("../components/ui/Menu", () => ({ Menu: ({ children }: { children?: ReactNode }) => children, })); -vi.mock("../components/ui/FilePreviewGallery", () => ({ - FilePreviewGallery: ({ children }: { children?: ReactNode }) => children, - useFilePreviewGallery: () => (source: unknown) => source, -})); +function previewPath(item: FilePreviewItem) { + return "resource" in item && "path" in item.resource ? item.resource.path : null; +} + vi.mock("../components/ui/FilePreviewModal", () => ({ - FilePreviewModal: (props: { source: { name: string } | null }) => - props.source ? createElement("div", { "data-file-preview": props.source.name }) : null, + FilePreviewModal: ({ source }: { source: FilePreviewSource | null }) => + source + ? createElement("div", { + "data-file-preview": source.name, + "data-selected-path": previewPath(source), + "data-gallery": JSON.stringify(source.gallery?.map(previewPath)), + }) + : null, })); vi.mock("../components/ui/VideoPreviewModal", () => ({ VideoPreviewModal: () => null })); vi.mock("../components/ComposerContextSheet", () => ({})); @@ -313,10 +328,6 @@ vi.mock("../features/layout/AdaptiveWorkspaceLayout", () => ({ })); vi.mock("../features/threads/thread-workflow-opening", () => ({ useWorkflowOpening: () => null })); vi.mock("../features/threads/useFileChipShare", () => ({ useFileChipShare: () => vi.fn() })); -vi.mock("../features/threads/ThreadMarkdownImage", async () => { - const { createContext } = await import("react"); - return { MarkdownImageAvailableWidthContext: createContext(390) }; -}); vi.mock("../features/threads/ZoomableImagePressable", async () => { const { Pressable } = await import("react-native"); return { ZoomableImagePressable: Pressable }; @@ -1408,6 +1419,70 @@ describe("inline file previews", () => { }); describe("ThreadFeed previews", () => { + it("opens a tapped workspace image on its own gallery page, in message order", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const threadId = ThreadId.make("thread-1"); + const messageId = MessageId.make("message-1"); + const timestamp = "2026-10-20T00:00:00.000Z"; + const container = document.createElement("div"); + const root = createRoot(container); + try { + await act(async () => + root.render( + createElement(ThreadFeed, { + environmentId: EnvironmentId.make("environment-1"), + threadId, + detailRef: null, + threadTitle: "preview", + workspaceRoot: "/repo", + feed: [ + { + type: "message", + id: messageId, + createdAt: timestamp, + message: { + id: messageId, + role: "assistant", + text: "![Red](./red.png)\n\n![Blue](./blue.png)", + attachments: [], + createdAt: timestamp, + updatedAt: timestamp, + runId: null, + streaming: false, + visibility: "local", + sourceThreadId: threadId, + }, + }, + ], + queuedMessages: [], + dispatchingMessageId: null, + onEditPendingMessage: null, + contentPresentation: { kind: "ready" }, + latestRun: null, + activeWorkStartedAt: null, + listRef: { current: null }, + freeze: { value: false } as Parameters[0]["freeze"], + contentInsetEndAdjustment: { value: 0 } as Parameters< + typeof ThreadFeed + >[0]["contentInsetEndAdjustment"], + anchorMessageId: null, + keyboardOffset: 0, + }), + ), + ); + await act(async () => + container.querySelector(`[aria-label="Red"]`)!.click(), + ); + const preview = container.querySelector("[data-file-preview]"); + expect(preview?.getAttribute("data-selected-path")).toBe("/repo/./red.png"); + expect(preview?.getAttribute("data-gallery")).toBe( + JSON.stringify(["/repo/./red.png", "/repo/./blue.png"]), + ); + } finally { + await act(async () => root.unmount()); + } + }); + it("does not commit an open preview over a different thread", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const environmentId = EnvironmentId.make("environment-1"); diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index ef57536abe95f..7e8eba1d01b28 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { useComposerModelTokens } from "./useComposerModelTokens"; import { requireNativeView } from "expo"; @@ -169,11 +170,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx index 28f47c3b758ab..4a0f57e411020 100644 --- a/apps/mobile/src/native/T3ComposerEditor.native.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior"; import { useComposerModelTokens } from "./useComposerModelTokens"; @@ -156,11 +157,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 1c7ebb1a4aed5..cd5137a6d04ac 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -873,7 +873,6 @@ export function useThreadComposerState(input: { } // Resolve at send time because outbox delivery may be delayed. - // Steering uses "auto" so an ended turn queues a run instead of restoring the draft. // An approval redirect must steer the waiting turn instead of queueing behind it. const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior; const followUpAction = resolveComposerDispatchMode({ @@ -888,9 +887,7 @@ export function useThreadComposerState(input: { ? "queue" : followUpAction === "auto" ? null - : followUpAction === "queue" - ? "queue" - : "auto"; + : followUpAction; // A redirect belongs to the approval it answers; the armed session waits for the next message. const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey); diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 064427a3727f5..94247273e1ca0 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1100,6 +1100,60 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("a turn-end status refresh reads the branch remote and remote URL once", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["checkout", "-b", "feature/turn-end"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/turn-end"]); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + const count = (cmd: string) => gitCommands.filter((args) => args === cmd).length; + + // Turn end: local status, then the PR lookup for a branch that has no PR yet. + yield* manager.invalidateLocalStatus(repoDir); + yield* manager.localStatus({ cwd: repoDir }); + yield* manager.invalidateRemoteStatus(repoDir); + const remote = yield* manager.remoteStatus( + { cwd: repoDir }, + { refreshUpstream: false, refreshMissingPullRequest: true }, + ); + + expect(remote?.pr ?? null).toBeNull(); + expect(count("config --get branch.feature/turn-end.remote")).toBe(1); + expect(count("config --get-all remote.origin.url")).toBe(1); + + // The thread's PR backfill can reach the lookup before the status refresh does. + const backfillCommands: string[] = []; + const backfill = yield* makeManager({ gitCommands: backfillCommands }); + yield* backfill.manager.localStatus({ cwd: repoDir }); + yield* backfill.manager.branchPullRequest( + { cwd: repoDir, branch: "feature/turn-end" }, + { confirmTerminal: false }, + ); + yield* backfill.manager.remoteStatus( + { cwd: repoDir }, + { refreshUpstream: false, refreshMissingPullRequest: true }, + ); + expect( + backfillCommands.filter((args) => args === "config --get branch.feature/turn-end.remote") + .length, + ).toBe(1); + + // A fresh identity check reads git itself, not what local status just read. + yield* manager.invalidateLocalStatus(repoDir); + yield* manager.localStatus({ cwd: repoDir }); + gitCommands.length = 0; + yield* manager.branchPullRequest( + { cwd: repoDir, branch: "feature/turn-end" }, + { freshGitState: true }, + ); + expect(count("config --get-all remote.origin.url")).toBe(1); + }), + ); + it.effect("a git read in flight during a T3 git action does not outlive it", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 543b5de5505f5..db62af1f79b69 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -220,6 +220,8 @@ const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20); const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15); const PR_LOOKUP_CACHE_CAPACITY = 2_048; const PR_LOOKUP_GIT_STATE_TTL = Duration.minutes(5); +// Turn end looks up the PR ~0.5 s after local status; older reads are read again. +const LOCAL_STATUS_GIT_READS_HANDOFF_TTL = Duration.seconds(5); const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15); // Shared by every background caller (backfill, settlement, cleanup), so startup discovery // cannot fill the git and forge process slots that foreground work also needs. @@ -1289,7 +1291,7 @@ export const make = Effect.gen(function* () { Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); const hostingProvider = details.hasOriginRemote - ? yield* resolveHostingProvider(cwd, details.branch) + ? yield* resolveHostingProviderForLocalStatus(cwd, details.branch) : null; return { @@ -1333,7 +1335,30 @@ export const make = Effect.gen(function* () { cwd: string, ): shared is SharedPrLookupGitReads => shared !== null && shared.open && shared.cwd === cwd && prLookupEpoch(cwd) === shared.epoch; - const withPrLookupGitReads = (effect: Effect.Effect, cwd: string) => + // Branch remote and remote URLs that local status just read, reused by the PR lookups that + // follow it (turn end runs the status lookup and the thread's PR backfill) instead of reading again. + const localStatusGitReads = new Map< + string, + Pick + >(); + const recentLocalStatusGitReads = (cwd: string) => + Clock.currentTimeMillis.pipe( + Effect.map((now) => { + const handoff = localStatusGitReads.get(cwd); + if (handoff === undefined || handoff.epoch !== prLookupEpoch(cwd)) return undefined; + const isFresh = (entry: RememberedPrLookupValue) => + now - entry.readAtMs < Duration.toMillis(LOCAL_STATUS_GIT_READS_HANDOFF_TTL); + return { + configValues: new Map([...handoff.configValues].filter(([, entry]) => isFresh(entry))), + remoteUrls: new Map([...handoff.remoteUrls].filter(([, entry]) => isFresh(entry))), + }; + }), + ); + const openPrLookupGitReads = ( + effect: Effect.Effect, + cwd: string, + handoff: Pick | undefined, + ) => Effect.suspend(() => { const shared: SharedPrLookupGitReads = { open: true, @@ -1341,8 +1366,8 @@ export const make = Effect.gen(function* () { cwd, epoch: prLookupEpoch(cwd), remotes: undefined, - configValues: new Map(), - remoteUrls: new Map(), + configValues: handoff?.configValues ?? new Map(), + remoteUrls: handoff?.remoteUrls ?? new Map(), }; return effect.pipe( Effect.provideService(prLookupGitReads, shared), @@ -1357,9 +1382,15 @@ export const make = Effect.gen(function* () { ), ); }); + const withPrLookupGitReads = (effect: Effect.Effect, cwd: string) => + openPrLookupGitReads(effect, cwd, undefined); + const withRecentLocalStatusGitReads = (effect: Effect.Effect, cwd: string) => + Effect.flatMap(recentLocalStatusGitReads(cwd), (handoff) => + openPrLookupGitReads(effect, cwd, handoff), + ); const withActivePrLookupGitReads = (cwd: string, effect: Effect.Effect) => Effect.flatMap(prLookupGitReads, (shared) => - isActivePrLookupGitReads(shared, cwd) ? effect : withPrLookupGitReads(effect, cwd), + isActivePrLookupGitReads(shared, cwd) ? effect : withRecentLocalStatusGitReads(effect, cwd), ); const prLookupCacheKey = ( cwd: string, @@ -1781,6 +1812,32 @@ export const make = Effect.gen(function* () { .pipe(Effect.orElseSucceed(() => null)); return handle?.context?.provider ?? provider; }); + const resolveHostingProviderForLocalStatus = (cwd: string, branch: string | null) => + Effect.suspend(() => { + const reads: SharedPrLookupGitReads = { + open: true, + queriedProvider: false, + cwd, + epoch: prLookupEpoch(cwd), + remotes: undefined, + configValues: new Map(), + remoteUrls: new Map(), + }; + return resolveHostingProvider(cwd, branch).pipe( + Effect.provideService(prLookupGitReads, reads), + Effect.ensuring( + Effect.sync(() => { + reads.open = false; + localStatusGitReads.delete(cwd); + if (localStatusGitReads.size >= STATUS_RESULT_CACHE_CAPACITY) { + const oldestCwd = localStatusGitReads.keys().next().value; + if (oldestCwd !== undefined) localStatusGitReads.delete(oldestCwd); + } + localStatusGitReads.set(cwd, reads); + }), + ), + ); + }); const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* ( cwd: string, @@ -3093,6 +3150,16 @@ export const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ).pipe(Effect.map((parts) => parts.join("\u0000"))); + // A fresh identity check, which confirms terminal results, must read git itself. + const withBranchPullRequestGitReads = ( + effect: Effect.Effect, + cacheCwd: string, + _branch: string, + options: { readonly freshGitState: boolean }, + ) => + options.freshGitState + ? withPrLookupGitReads(effect, cacheCwd) + : withRecentLocalStatusGitReads(effect, cacheCwd); const lookupBranchPullRequest = Effect.fn("lookupBranchPullRequest")(function* ( cacheCwd: string, branch: string, @@ -3261,7 +3328,7 @@ export const make = Effect.gen(function* () { // Hosting CLIs may target upstream; the PR URL identifies its actual repository. repositoryKey: pullRequestRepositoryKey(latest.url), }; - }, withPrLookupGitReads); + }, withBranchPullRequestGitReads); const checkedOutPullRequestKey = (branch: string) => `branch.${branch}.t3-pull-request`; diff --git a/apps/server/src/git/sharedCheckoutGuard.test.ts b/apps/server/src/git/sharedCheckoutGuard.test.ts new file mode 100644 index 0000000000000..1723b29c10bb8 --- /dev/null +++ b/apps/server/src/git/sharedCheckoutGuard.test.ts @@ -0,0 +1,167 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as GitWorkflowService from "./GitWorkflowService.ts"; +import { assertCheckoutIdle, busyThreadsInCheckout } from "./sharedCheckoutGuard.ts"; + +const projectId = ProjectId.make("project-a"); +const otherProjectId = ProjectId.make("project-b"); +const nestedProjectId = ProjectId.make("project-nested"); +const childRepositoryProjectId = ProjectId.make("project-child-repository"); + +const thread = ( + title: string, + overrides: { + readonly projectId?: ProjectId; + readonly worktreePath?: string | null; + readonly activityRunStatus?: "preparing" | "starting" | "running" | "waiting" | null; + readonly archived?: boolean; + } = {}, +) => ({ + archived: overrides.archived ?? false, + id: ThreadId.make(title), + title, + projectId: overrides.projectId ?? projectId, + worktreePath: overrides.worktreePath ?? null, + activityRunStatus: + overrides.activityRunStatus === undefined ? "running" : overrides.activityRunStatus, +}); + +describe("busyThreadsInCheckout", () => { + it("finds running local threads in the project root checkout", () => { + const busy = busyThreadsInCheckout({ + checkoutPaths: ["/repo"], + projectIds: new Set([projectId]), + threads: [ + thread("local running"), + thread("local idle", { activityRunStatus: null }), + thread("worktree running", { worktreePath: "/worktrees/a" }), + thread("other project", { projectId: otherProjectId }), + ], + }); + + expect(busy.map(({ title }) => title)).toEqual(["local running"]); + }); + + it("finds running threads that share a worktree", () => { + const busy = busyThreadsInCheckout({ + checkoutPaths: ["/worktrees/a"], + projectIds: new Set(), + threads: [ + thread("same worktree", { worktreePath: "/worktrees/a", activityRunStatus: "waiting" }), + thread("other worktree", { worktreePath: "/worktrees/b" }), + thread("local running"), + ], + }); + + expect(busy.map(({ title }) => title)).toEqual(["same worktree"]); + }); +}); + +describe("assertCheckoutIdle", () => { + const guardLayer = (input: { + readonly repositoryRoot: string; + readonly threads: ReadonlyArray>; + readonly failWorktreeLookup?: boolean; + }) => + Layer.mergeAll( + Layer.mock(GitWorkflowService.GitWorkflowService)({ + repositoryRoot: (cwd) => + Effect.succeed(cwd.startsWith("/repo/child") ? "/repo/child" : input.repositoryRoot), + }), + Layer.mock(ProjectService.ProjectService)({ + snapshot: Effect.succeed({ + projects: [ + { id: projectId, workspaceRoot: "/repo" }, + { id: nestedProjectId, workspaceRoot: "/repo/packages/app" }, + { id: childRepositoryProjectId, workspaceRoot: "/repo/child" }, + { id: otherProjectId, workspaceRoot: "/other" }, + ], + } as never), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getShellSnapshot: (options) => + options?.worktreePath !== undefined && input.failWorktreeLookup + ? Effect.fail("worktree lookup failed" as never) + : Effect.succeed( + (() => { + const matching = input.threads.filter( + (candidate) => + (options?.projectId === undefined || + candidate.projectId === options.projectId) && + (options?.worktreePath === undefined || + candidate.worktreePath === options.worktreePath), + ); + return { + threads: matching.filter((candidate) => !candidate.archived), + archivedThreads: matching.filter((candidate) => candidate.archived), + } as never; + })(), + ), + }), + ); + + it.effect("refuses a switch from a subdirectory of a busy checkout", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo/src").pipe( + Effect.flip, + Effect.provide(guardLayer({ repositoryRoot: "/repo", threads: [thread("local running")] })), + ); + expect(error.detail).toContain("'local running'"); + }), + ); + + it.effect("keeps a busy thread when another lookup fails", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [thread("local running")], + failWorktreeLookup: true, + }), + ), + ); + expect(error.detail).toContain("'local running'"); + }), + ); + + it.effect("refuses a switch while a nested project or archived thread is working", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [ + thread("nested running", { projectId: nestedProjectId }), + thread("archived running", { archived: true }), + thread("other running", { projectId: otherProjectId }), + thread("child repository running", { projectId: childRepositoryProjectId }), + ], + }), + ), + ); + // Exactly these two: a third busy thread would read "and 1 more". + expect(error.detail).toMatch( + /^'(nested|archived) running' and '(nested|archived) running' are still working/, + ); + }), + ); + + it.effect("allows a switch when no thread is working", () => + assertCheckoutIdle("test", "/repo").pipe( + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [thread("local idle", { activityRunStatus: null })], + }), + ), + ), + ); +}); diff --git a/apps/server/src/git/sharedCheckoutGuard.ts b/apps/server/src/git/sharedCheckoutGuard.ts new file mode 100644 index 0000000000000..442ef14dc71e9 --- /dev/null +++ b/apps/server/src/git/sharedCheckoutGuard.ts @@ -0,0 +1,101 @@ +import { + GitCommandError, + type OrchestrationV2ThreadShell, + type ProjectId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; + +import * as GitWorkflowService from "./GitWorkflowService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; + +type CheckoutThread = Pick< + OrchestrationV2ThreadShell, + "id" | "title" | "projectId" | "worktreePath" | "activityRunStatus" +>; + +/** Threads with an active run whose working directory is one of `checkoutPaths`. */ +export function busyThreadsInCheckout(input: { + readonly checkoutPaths: ReadonlyArray; + readonly projectIds: ReadonlySet; + readonly threads: ReadonlyArray; +}): ReadonlyArray { + return input.threads.filter( + (thread) => + (thread.activityRunStatus ?? null) !== null && + (thread.worktreePath === null + ? input.projectIds.has(thread.projectId) + : input.checkoutPaths.includes(thread.worktreePath)), + ); +} + +function describeBusyCheckout(titles: ReadonlyArray): string { + const quoted = titles.map((title) => `'${title}'`); + const names = + quoted.length <= 2 + ? quoted.join(" and ") + : `${quoted.slice(0, 2).join(", ")} and ${quoted.length - 2} more`; + return `${names} ${quoted.length === 1 ? "is" : "are"} still working in this checkout. Wait for ${quoted.length === 1 ? "it" : "them"} to finish, or use a worktree for a separate branch.`; +} + +/** Switching a shared checkout's ref moves every thread working in it, mid-turn included. */ +export const assertCheckoutIdle = Effect.fn("sharedCheckoutGuard.assertCheckoutIdle")(function* ( + operation: string, + cwd: string, +) { + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const projectService = yield* ProjectService.ProjectService; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + // `git checkout` from a subdirectory moves the whole checkout; records may hold either spelling. + const root = yield* gitWorkflow.repositoryRoot(cwd).pipe(Effect.orElseSucceed(() => null)); + const checkoutPaths = [...new Set([cwd, ...(root === null ? [] : [root])])]; + const projects = yield* projectService.snapshot.pipe( + Effect.map((snapshot) => snapshot.projects), + Effect.orElseSucceed(() => []), + ); + // A project rooted inside the checkout shares it, as in a monorepo package, unless it is its + // own repository nested there. + const nested = yield* Effect.forEach( + projects.filter( + ({ workspaceRoot }) => + root !== null && + !checkoutPaths.includes(workspaceRoot) && + workspaceRoot.startsWith(`${root}/`), + ), + (project) => + gitWorkflow.repositoryRoot(project.workspaceRoot).pipe( + Effect.map((projectRoot) => (projectRoot === root ? [project] : [])), + Effect.orElseSucceed(() => []), + ), + { concurrency: "unbounded" }, + ); + const projectIds = new Set( + [ + ...projects.filter(({ workspaceRoot }) => checkoutPaths.includes(workspaceRoot)), + ...nested.flat(), + ].map(({ id }) => id), + ); + // Archiving does not stop a run, so archived threads can still be working. Each lookup fails + // open on its own, so one failure keeps what the others found. + const snapshots = yield* Effect.forEach( + [ + ...checkoutPaths.map((worktreePath) => threadManagement.getShellSnapshot({ worktreePath })), + ...[...projectIds].map((projectId) => threadManagement.getShellSnapshot({ projectId })), + ], + (snapshot) => snapshot.pipe(Effect.orElseSucceed(() => ({ threads: [], archivedThreads: [] }))), + { concurrency: "unbounded" }, + ); + const busy = busyThreadsInCheckout({ + checkoutPaths, + projectIds, + threads: snapshots.flatMap((snapshot) => [...snapshot.threads, ...snapshot.archivedThreads]), + }); + const titles = [...new Map(busy.map((thread) => [thread.id, thread.title])).values()]; + if (titles.length === 0) return; + return yield* new GitCommandError({ + operation, + command: "git checkout", + cwd, + detail: describeBusyCheckout(titles), + }); +}); diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index e8308b8480d02..6291f304e6efc 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -156,7 +156,9 @@ function makeService(input: { readonly projects: ReadonlyArray; readonly trackers: ReadonlyArray; readonly bindings?: Record; - readonly readBindings?: IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"]; + readonly readBindings?: ReturnType< + IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"] + >; }) { return IssueService.IssueService.pipe( Effect.provide( @@ -164,7 +166,7 @@ function makeService(input: { Layer.provide( Layer.mergeAll( Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: + list: () => input.readBindings ?? Effect.succeed( new Map( diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 27499b240d655..9b9b050ab6ad0 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -42,6 +42,7 @@ import { type IssueTrackerApi, type StandaloneIssueTrackerApi, type TrackerIssueDetail, + type TrackerIssueLink, } from "@t3tools/source-control-core/server/IssueTracker"; import { parseUrl } from "@t3tools/shared/url"; @@ -148,6 +149,7 @@ export class IssueService extends Context.Service< { readonly list: (input: IssueListInput) => Effect.Effect; readonly detail: (input: IssueRef) => Effect.Effect; + readonly linkMetadata: (input: IssueRef) => Effect.Effect; readonly comments: ( input: IssueCommentsPageInput, ) => Effect.Effect; @@ -249,7 +251,7 @@ const make = Effect.gen(function* () { ); if (shells.length === 0) return []; // One read per listing, not per project, and never cached so Settings changes apply. - const bound = yield* bindings.list.pipe( + const bound = yield* bindings.list(filter.projectId).pipe( // A failed read is not an unbound project: that would list the git host's issues alone. Effect.mapError( (cause) => @@ -524,6 +526,22 @@ const make = Effect.gen(function* () { ), ); + const linkMetadata: IssueService["Service"]["linkMetadata"] = (input) => + requireProject(input).pipe( + Effect.flatMap((project) => { + const read = project.api.getIssueLink ?? project.api.getIssue; + return read({ + cwd: project.project.workspaceRoot, + host: project.host, + scope: project.scope, + key: input.key, + }).pipe( + Effect.map(({ title, url, displayKey }) => ({ title, url, displayKey })), + Effect.mapError(toIssueError("detail")), + ); + }), + ); + const comments: IssueService["Service"]["comments"] = (input) => requireProject(input).pipe( Effect.flatMap((project) => @@ -796,6 +814,7 @@ const make = Effect.gen(function* () { return IssueService.of({ list, detail: traced("detail", detail), + linkMetadata: traced("linkMetadata", linkMetadata), comments: traced("comments", comments), templates: traced("templates", templates), candidates: interactive(traced("candidates", candidates)), diff --git a/apps/server/src/issue/IssueTrackerConnections.ts b/apps/server/src/issue/IssueTrackerConnections.ts index 390cc9701e858..704116fc65326 100644 --- a/apps/server/src/issue/IssueTrackerConnections.ts +++ b/apps/server/src/issue/IssueTrackerConnections.ts @@ -113,7 +113,7 @@ const make = Effect.gen(function* () { const list: IssueTrackerConnections["Service"]["list"] = Effect.all({ trackers: Effect.forEach(registry.standalone, current, { concurrency: 4 }), - bindings: bindings.list.pipe( + bindings: bindings.list().pipe( Effect.map((bound) => Object.fromEntries(bound)), // No single tracker is at fault; the first registered one carries the report. Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")), diff --git a/apps/server/src/issue/linkedThreads.ts b/apps/server/src/issue/linkedThreads.ts index c38b75c6b0944..03c337996f08a 100644 --- a/apps/server/src/issue/linkedThreads.ts +++ b/apps/server/src/issue/linkedThreads.ts @@ -15,6 +15,8 @@ const decodeLinkedThreads = Schema.decodeUnknownEffect(IssueLinkedThreadsResult) export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( function* (key: ThreadIssueKey) { const sql = yield* SqlClient.SqlClient; + // The CASE stops SQLite hoisting the side-chat check out of the link loop, + // where it would re-parse every thread's payload, not just matching ones. const rows = yield* sql<{ id: string; projectId: string; @@ -37,9 +39,11 @@ export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( t.updated_at AS "updatedAt" FROM orchestration_v2_projection_threads AS t JOIN json_each(t.payload_json, '$.issues') AS link - WHERE json_extract(link.value, '$.key') = ${key.key.trim()} - AND t.deleted_at IS NULL - AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 + WHERE t.deleted_at IS NULL + AND CASE WHEN json_extract(link.value, '$.key') = ${key.key.trim()} + THEN json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 + ELSE 0 + END ORDER BY "updatedAt" DESC, id ASC `.pipe(NodeSqliteClient.readOnly); const threads = rows diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 2dad1fe68ee6d..ccd41144a5ea8 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -617,7 +617,8 @@ describe("OrchestratorMcpService", () => { const childThreadId = ThreadId.make("thread:mcp-next-child"); const taskId = NodeId.make("node:mcp-next-task"); let finished = false; - let pendingRequest = false; + let firstRun = false; + let pendingRequest: "live" | "message" | null = null; const parentProjection = () => ({ thread: { id: parentThreadId }, @@ -640,19 +641,33 @@ describe("OrchestratorMcpService", () => { const childRun = () => ({ id: RunId.make("run:mcp-next-child"), ordinal: 1, - status: finished ? ("completed" as const) : ("running" as const), - delegatedTaskId: taskId, + status: finished && !firstRun ? ("completed" as const) : ("running" as const), + // A task's first run is untagged; the child's fork node names the task. + ...(firstRun ? {} : { delegatedTaskId: taskId }), }); const childProjection = () => ({ - thread: { id: childThreadId, title: "Child task" }, + thread: { + id: childThreadId, + title: "Child task", + forkedFrom: { type: "node", nodeId: taskId }, + }, runs: [childRun()], contextTransfers: [], messages: [], subagents: [], providerThreads: [], providerTurns: [], - runtimeRequests: pendingRequest ? [{ status: "pending" }] : [], + runtimeRequests: + pendingRequest === null + ? [] + : [ + { + kind: "user_input", + status: "pending", + responseCapability: { type: pendingRequest }, + }, + ], nodes: [], turnItems: [], }) as unknown as OrchestrationV2ThreadProjection; @@ -668,7 +683,7 @@ describe("OrchestratorMcpService", () => { Effect.succeed({ threadId: childThreadId, run: childRun() as unknown as OrchestrationV2ThreadProjection["runs"][number], - timedOut: !finished, + timedOut: !finished || firstRun, }), dispatch: () => Effect.succeed({} as never), }), @@ -705,13 +720,28 @@ describe("OrchestratorMcpService", () => { assert.equal(waiting.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); // A child waiting on a question or approval needs an answer, not a wake. - pendingRequest = true; + pendingRequest = "live"; const asking = yield* service.waitForThread(scope, { threadId: childThreadId }); assert.isTrue(asking.timedOut); assert.notProperty(asking, "next"); - pendingRequest = false; + // A question answered by message does not stop the child. + pendingRequest = "message"; + const working = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(working.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + pendingRequest = null; + + firstRun = true; + const first = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(first.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + + // An untagged run after the task has its result is no longer that task. finished = true; + const followUp = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.isTrue(followUp.timedOut); + assert.notProperty(followUp, "next"); + firstRun = false; + const completed = yield* service.taskStatus(scope, taskId); assert.equal(completed.status, "completed"); assert.notProperty(completed, "next"); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 07b137c61e354..4062c509812c4 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3298,6 +3298,7 @@ const make = Effect.gen(function* () { threadId, projectId: parent.thread.projectId, title, + ...(request.title?.trim() ? { titleRenamed: true } : {}), modelSelection: target.modelSelection, runtimeMode, interactionMode, @@ -3712,7 +3713,11 @@ const make = Effect.gen(function* () { }) .pipe(Effect.mapError(threadManagementFailure)); const status = result.run === null ? "idle" : runOutcome(result.run); - const taskId = result.run?.delegatedTaskId; + // A task's first run carries no task id; the child's untagged runs continue that task + // until it has a result. + const taskId = + result.run?.delegatedTaskId ?? + (target.thread.forkedFrom?.type === "node" ? target.thread.forkedFrom.nodeId : undefined); const ownedTask = result.timedOut && status !== "waiting" && @@ -3724,7 +3729,8 @@ const make = Effect.gen(function* () { task.origin === "app_owned" && task.threadId === parent.thread.id && task.childThreadId === input.threadId && - task.completionDelivery?.state !== "disposed", + task.completionDelivery?.state !== "disposed" && + (result.run?.delegatedTaskId !== undefined || task.result === null), ); // A child waiting on a question or approval needs an answer, not a wake. const childRequests = ownedTask @@ -3733,7 +3739,10 @@ const make = Effect.gen(function* () { .pipe(Effect.mapError(threadManagementFailure))).runtimeRequests : []; const wakesCaller = - ownedTask && !childRequests.some((request) => request.status === "pending"); + ownedTask && + !childRequests.some( + (request) => request.status === "pending" && request.responseCapability.type === "live", + ); return { threadId: input.threadId, runId: result.run?.id ?? null, diff --git a/apps/server/src/mcp/toolkits/issues/handlers.test.ts b/apps/server/src/mcp/toolkits/issues/handlers.test.ts index 143ba4a0c98a3..9867324f7fc23 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.test.ts @@ -158,6 +158,7 @@ const makeHarness = Effect.fn("makeIssuesToolkitHarness")(function* ( issueLayer ?? Layer.mock(IssueService.IssueService)({ detail: () => Effect.succeed(detail), + linkMetadata: () => Effect.succeed(detail), projectScope: (projectId) => Effect.succeed({ projectId, @@ -260,7 +261,7 @@ describe("issue toolkit handlers", () => { projectLayer, Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])), + list: () => Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])), }), Layer.succeed( IssueTrackerRegistry.IssueTrackerRegistry, @@ -314,9 +315,10 @@ describe("issue toolkit handlers", () => { projectLayer, Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: Effect.succeed( - new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), - ), + list: () => + Effect.succeed( + new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), + ), }), Layer.succeed( IssueTrackerRegistry.IssueTrackerRegistry, diff --git a/apps/server/src/mcp/toolkits/issues/handlers.ts b/apps/server/src/mcp/toolkits/issues/handlers.ts index b45b3d3dbd875..c09dbc356d61f 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.ts @@ -269,20 +269,20 @@ const make = Effect.gen(function* () { link_issue: writesThread((input) => Effect.gen(function* () { const thread = yield* requireThread(input.threadId); - const target = yield* resolveTarget({ + const target: ResolvedTarget = yield* resolveTarget({ ...input, projectId: input.projectId ?? thread.projectId, }); // Reading the issue proves it exists and names it for the thread's row. - const detail = yield* readIssue(target); - const url = target.url ?? detail.url; + const issue = target.issue ?? (yield* issues.linkMetadata(refOf(target))); + const url = target.url ?? issue.url; const { alreadyLinked } = yield* threadIssues .link({ threadId: thread.id, ref: refOf(target), url, - displayKey: detail.displayKey, - title: detail.title, + displayKey: issue.displayKey, + title: issue.title, source: "agent", }) .pipe(Effect.catchCause(linkFailure)); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index c13a8ab9353cc..d03b038ee0780 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -254,6 +254,7 @@ it.effect( expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required"); expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined(); expect(belowCeiling.launched[0]?.generateTitle).toBeUndefined(); + expect(belowCeiling.launched[0]?.titleRenamed).toBe(true); const titled = yield* launchWith("full-access", "full-access", { title: "Fix", @@ -261,6 +262,7 @@ it.effect( message: "Fix the bug", }); expect(titled.launched[0]).toMatchObject({ title: "Fix", generateTitle: true }); + expect(titled.launched[0]?.titleRenamed).toBeUndefined(); for (const message of [undefined, "", " \n "]) { const idleTitled = yield* launchWith("full-access", "full-access", { diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index c024a6e4439a5..0a54ab6652fc6 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -448,6 +448,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { projectId, title: input.title, ...(input.generateTitle === undefined ? {} : { generateTitle: input.generateTitle }), + ...(input.generateTitle === true ? {} : { titleRenamed: true }), modelSelection, runtimeMode: startedRuntimeMode, interactionMode, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index d79257944c8e9..348c2f38b0190 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -11857,6 +11857,8 @@ describe("AcpAdapterV2", () => { assert.deepInclude(late.providerThread.contextUsage, { usedTokens: 13101 }); // With no run left to receive it, only a session-scoped update reaches the projection. assert.isTrue(late.sessionScoped); + // It is written straight to the projection, so it must not revive the settled turn. + assert.equal(late.providerThread.status, "idle"); }).pipe(Effect.provide(layerTest), Effect.scoped), ); diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 079ac88211870..ec3e872d61c2b 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -924,10 +924,11 @@ export const layer: Layer.Layer< const repositoryScopesIfReadable: CheckpointServiceV2Shape["repositoryScopesIfReadable"] = Effect.fn("CheckpointService.repositoryScopes")( function* (input) { - const [workspace, submodules] = yield* Effect.all([ - workspaceFolders.forThread(input), - workspaceFolders.submodules(input), - ]); + const workspace = yield* workspaceFolders.forThread(input); + const submodules = yield* workspaceFolders.submodules({ + ...input, + folders: workspace.folders, + }); return yield* Effect.forEach( [...workspace.folders.filter((folder) => folder.isGitRepository), ...submodules], (folder) => diff --git a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts index 5211da2faf169..72471eb8cf944 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts @@ -37,7 +37,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH handoff.delivery.status === "pending", ); if (pending.length === 0 || (input.deferInline && input.inject === undefined)) - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; const budget = typeof input.budget === "number" ? input.budget : yield* input.budget; let coverage = pending .map( @@ -76,7 +76,8 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH budget, }); if (historyCost(selected.messages, selected.context) > budget) { - if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void }; + if (input.deferInline) + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; return yield* new ContextHandoffBudgetError(); } const omittedItemIds = new Set(selected.omittedItemIds); @@ -127,7 +128,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH }); if (injected) { yield* persist("injected"); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } } else { yield* persist("pending"); @@ -135,12 +136,13 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH if (input.deferInline) { // Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported. yield* Effect.forEach(pending, input.persist, { discard: true }); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } return { context: renderHistory(selected.messages, selected.context), delivered: persist("inline"), unsent: Effect.forEach(pending, input.persist, { discard: true }), + inlineHandoffs: pending, }; }, ); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index c637446d78827..6c805cfc4592f 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -390,8 +390,7 @@ export const layerExecutor: Layer.Layer< threadId: effect.threadId, messageId: message.id, ...(error.steerDeclined ? { steerFollowUpOfRunId: run.id } : {}), - ...(error.steerDeclined && - effect.request.steerFollowUpAfterRunOrdinal !== undefined + ...(effect.request.steerFollowUpAfterRunOrdinal !== undefined ? { steerFollowUpAfterRunOrdinal: effect.request.steerFollowUpAfterRunOrdinal, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index a58c7f8a49ea9..8a27bba63827b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -28,6 +28,7 @@ import { CommandId, type GuestMessageId, isCompactionCommandMessage, + isDeliveredProviderTurn, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, MessageId, @@ -1608,7 +1609,9 @@ function lastDeliveredRunForProviderThread( isHandoffSourceRun(run) && run.providerThreadId === providerThreadId && (run.status === "completed" || - projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId)), + projection.providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + )), ); } @@ -4051,6 +4054,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio id: command.threadId, projectId: command.projectId, title: command.title, + ...(command.titleRenamed === true ? { titleRenamed: true } : {}), providerInstanceId: command.modelSelection.instanceId, modelSelection: command.modelSelection, runtimeMode: command.runtimeMode, @@ -7437,7 +7441,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio !hasTitleSetBeforeFirstMessage(projection.thread, command.titleSeed); if ( !isNativeMaintenanceCommand(command) && - (seedsUntitledThread || (command.createdBy === "user" && (yield* onlyMaintenanceHistory))) + (seedsUntitledThread || + (command.createdBy === "user" && + // A draft opened by `/compact` is titled after it, so only a chosen title stays here. + projection.thread.titleRenamed !== true && + (yield* onlyMaintenanceHistory))) ) { const now = yield* DateTime.now; const thread: OrchestrationV2AppThread = { @@ -8077,10 +8085,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.creationSource === "provider" && !(yield* stopReachedRun(command, command.threadId, activeRun.id)); let steerFollowUpQueuePosition: number | undefined; - if ( - command.steerFollowUpOfRunId !== undefined && - command.steerFollowUpAfterRunOrdinal !== undefined - ) { + if (command.steerFollowUpAfterRunOrdinal !== undefined) { const afterRunOrdinal = command.steerFollowUpAfterRunOrdinal; const steerOrdinal = projection.turnItems.find( @@ -8241,7 +8246,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId: queued.id, providerInstanceId: queued.providerInstanceId, occurredAt: now, - payload: { ...queued, queuePosition: (queued.queuePosition ?? queued.ordinal) + 1 }, + payload: { + ...queued, + ...(heldRunsToRelease.includes(queued) ? { queueHeld: false } : {}), + queuePosition: (queued.queuePosition ?? queued.ordinal) + 1, + }, }); } } diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 86a4c6c77375d..cb2fb0e87ada4 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -433,7 +433,7 @@ it.effect("sql: lists only active threads with pull request links, oldest first" const store = yield* ProjectionStore.ProjectionStoreV2; yield* createThread("no-links"); yield* createThread("empty-links", { pullRequests: [] }); - yield* createThread("archived-link", { + const archived = yield* createThread("archived-link", { archivedAt: old, pullRequests: [pullRequestLink(1)], }); @@ -459,6 +459,12 @@ it.effect("sql: lists only active threads with pull request links, oldest first" (yield* store.getThreadsWithPullRequests(open)).map((thread) => thread.id), [open], ); + assert.deepEqual( + (yield* store.getThreadsWithPullRequests(undefined, { includeArchived: true })).map( + (thread) => thread.id, + ), + [settled, archived, open], + ); }).pipe(Effect.provide(layerSql)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ba91ba94d2520..6c8308706b651 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -684,6 +684,7 @@ export interface ProjectionStoreV2Shape { ) => Effect.Effect, ProjectionStoreV2Error>; readonly getThreadsWithPullRequests: ( threadId?: ThreadId, + options?: { readonly includeArchived?: boolean }, ) => Effect.Effect, ProjectionStoreV2Error>; /** Titles of the given threads that exist, archived ones included. */ readonly getThreadLinkMetadata: ( @@ -8972,12 +8973,12 @@ export const layer: Layer.Layer = const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] = Effect.fn("ProjectionStore.getThreadsWithPullRequests")( - function* (threadId) { + function* (threadId, options) { const rows = yield* sql` SELECT payload_json FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND thread_id = ${threadId}`} - AND json_extract(payload_json, '$.archivedAt') IS NULL + ${options?.includeArchived === true ? sql`` : sql`AND json_extract(payload_json, '$.archivedAt') IS NULL`} AND json_array_length(payload_json, '$.pullRequests') > 0 ORDER BY updated_at ASC, thread_id ASC `; diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index bcdcc3798131a..08aaa12b864bb 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, isCompactionCommandMessage, + isDeliveredProviderTurn, parseGoalCommand, RunId, RunAttemptId, @@ -32,6 +33,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import { @@ -173,7 +175,9 @@ const nativeSessionMissesKeptTurns = ( ): boolean => { const nativeId = providerThread.nativeThreadRef?.nativeId; if (nativeId === undefined) return false; - const acceptedAttemptIds = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttemptIds = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const accepted = projection.attempts.filter((attempt) => acceptedAttemptIds.has(attempt.id)); const runsById = new Map(projection.runs.map((source) => [source.id, source])); const ordinalOf = (attempt: OrchestrationV2RunAttempt) => @@ -1093,7 +1097,12 @@ export const layer: Layer.Layer< ...settledHandoffs.flatMap((handoff) => handoff.delivery?.omittedItemIds ?? []), ]); const deliveredAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); + const droppedAttemptIds = new Set( + projection.providerTurns + .filter((turn) => !isDeliveredProviderTurn(turn)) + .map((turn) => turn.runAttemptId), ); const acceptedAttempts = projection.attempts.filter( (source) => @@ -1165,7 +1174,9 @@ export const layer: Layer.Layer< (source) => source.ordinal < run.ordinal && source.providerThreadId === providerThread.id && - (source.status === "failed" || source.status === "interrupted") && + (source.status === "failed" || + source.status === "interrupted" || + (source.status === "cancelled" && droppedAttemptIds.has(source.activeAttemptId))) && !deliveredAttemptIds.has(source.activeAttemptId), ); const missedRunIds = new Set(missedRuns.map((source) => source.id)); @@ -1542,7 +1553,9 @@ export const layer: Layer.Layer< const rejectedHistory = yield* Effect.gen(function* () { if (session.driver !== "codex") return false; const acceptedAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns + .filter(isDeliveredProviderTurn) + .map((turn) => turn.runAttemptId), ); const previous = projection.runs.findLast( (source) => @@ -1611,7 +1624,9 @@ export const layer: Layer.Layer< // Dispatch prepares no import handoff for a session import: its history is in the native session. const importedNativeSession = projection.thread.historyOrigin === "v1_import" && - !projection.providerTurns.some((turn) => turn.providerThreadId === providerThread.id) && + !projection.providerTurns.some( + (turn) => turn.providerThreadId === providerThread.id && isDeliveredProviderTurn(turn), + ) && !projection.contextHandoffs.some( (handoff) => handoff.toProviderThreadId === providerThread.id && @@ -2020,6 +2035,10 @@ export const layer: Layer.Layer< ], }); }); + let inlineDeliveredHandoffs: ReadonlyArray = []; + let promptDroppedOnTerminal = false; + const inlineDeliveryLock = yield* Semaphore.make(1); + const retryHandoffIds = new Set(retryHandoff.handoffs.map((handoff) => handoff.id)); const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( function* (turnInput: Parameters[0], compact = false) { const delivery = yield* deliverContextHandoffs({ @@ -2046,6 +2065,15 @@ export const layer: Layer.Layer< sideChatHandoff === undefined || compact || goalCommand ? "" : sideChatHandoff.summaryText; + // Record inline handoffs before startTurn so an immediate dropped terminal can restore them. + inlineDeliveredHandoffs = [ + ...delivery.inlineHandoffs.map((handoff) => + retryHandoffIds.has(handoff.id) + ? { ...handoff, status: "superseded" as const } + : handoff, + ), + ...(sideChatContext === "" || sideChatHandoff === undefined ? [] : [sideChatHandoff]), + ]; const context = [delivery.context, sideChatContext, restartNote] .filter((part) => part !== "") .join("\n\n"); @@ -2096,31 +2124,39 @@ export const layer: Layer.Layer< : Effect.void, ), ); - // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. - const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; - yield* Effect.forEach( - [ - delivery.delivered, - ...(sideChatContext === "" || sideChatHandoff === undefined || nativeThreadId == null - ? [] - : [ - persistHandoff({ - ...sideChatHandoff, - toProviderThreadId: runningProviderThread.id, - delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, - }), - ]), - ], - (record) => - record.pipe( - Effect.catchCause(() => - Effect.logWarning("Failed to record accepted context handoff delivery", { - runId: run.id, - deliveryStatus: "pending", - }), - ), - ), - { discard: true }, + // Serialize acceptance writes against dropped-terminal restoration so neither overwrites the other. + yield* inlineDeliveryLock.withPermits(1)( + Effect.gen(function* () { + if (promptDroppedOnTerminal) return; + // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. + const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; + yield* Effect.forEach( + [ + delivery.delivered, + ...(sideChatContext === "" || + sideChatHandoff === undefined || + nativeThreadId == null + ? [] + : [ + persistHandoff({ + ...sideChatHandoff, + toProviderThreadId: runningProviderThread.id, + delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, + }), + ]), + ], + (record) => + record.pipe( + Effect.catchCause(() => + Effect.logWarning("Failed to record accepted context handoff delivery", { + runId: run.id, + deliveryStatus: "pending", + }), + ), + ), + { discard: true }, + ); + }), ); }, Effect.mapError((cause) => @@ -2181,6 +2217,13 @@ export const layer: Layer.Layer< hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest, loadRunInterruptReason: runControls.loadRunInterruptReason, hasWorkspaceMoved: runControls.hasWorkspaceMoved, + loadDroppedInlineHandoffs: () => + inlineDeliveryLock.withPermits(1)( + Effect.sync(() => { + promptDroppedOnTerminal = true; + return inlineDeliveredHandoffs; + }), + ), loadUnsettledWork: runControls.loadUnsettledWork, message: { messageId: message.id, diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index ceaf2fd5de54b..58918bdef612d 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -1,14 +1,15 @@ -import type { - NodeId, - OrchestrationV2ConversationMessage, - OrchestrationV2PendingBackgroundTask, - OrchestrationV2ProviderThread, - OrchestrationV2ProviderTurn, - OrchestrationV2RestartCancelledBackgroundWork, - OrchestrationV2Run, - OrchestrationV2RunAttempt, - OrchestrationV2Subagent, - OrchestrationV2TurnItem, +import { + isDeliveredProviderTurn, + type NodeId, + type OrchestrationV2ConversationMessage, + type OrchestrationV2PendingBackgroundTask, + type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2RestartCancelledBackgroundWork, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, + type OrchestrationV2Subagent, + type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; @@ -151,7 +152,7 @@ export function restartCancelledBackgroundWorkNote( type ProviderTurnState = Pick< OrchestrationV2ProviderTurn, - "runAttemptId" | "providerThreadId" | "status" + "runAttemptId" | "providerThreadId" | "status" | "promptDropped" >; export function isRestartNoteSource( @@ -307,12 +308,14 @@ export function delegatedTaskResultRun( /** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */ export function continuationFailedBeforePrompt( run: Pick, - providerTurns: ReadonlyArray>, + providerTurns: ReadonlyArray>, ): boolean { return ( run.status === "failed" && run.restartContinuationOfRunId !== undefined && - !providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) + !providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + ) ); } @@ -323,7 +326,9 @@ export function continuationStartRetryDelayMs( run: OrchestrationV2Run, projection: { readonly runs: ReadonlyArray; - readonly providerTurns: ReadonlyArray>; + readonly providerTurns: ReadonlyArray< + Pick + >; readonly turnItems: Parameters[1]; }, ): number | undefined { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index a23a3fdf87bff..1d13620b75623 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -8,6 +8,7 @@ import { NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2PendingBackgroundTask, @@ -3702,6 +3703,49 @@ it.effect.each([ }), ); +it.effect("restores dropped inline handoffs when ingestion fails before the terminal", () => + Effect.gen(function* () { + const key = "dropped-turn-ingest-error"; + const ids = backgroundScenarioIds(key); + const handoff = { id: `handoff:${key}` } as unknown as OrchestrationV2ContextHandoff; + const { finalEvents } = yield* captureRootRunTermination({ + key, + shouldFinalizeRun: () => Effect.succeed(true), + loadDroppedInlineHandoffs: () => Effect.succeed([handoff]), + events: () => + Stream.make({ + type: "provider_turn.updated" as const, + driver, + threadId: ids.threadId, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + runAttemptId: ids.attemptId, + ordinal: 1, + status: "failed", + promptDropped: true, + } as OrchestrationV2ProviderTurn, + }), + ingestNormalized: ({ event }) => + event.type === "provider_turn.updated" + ? Effect.fail( + new ProviderEventIngestor.ProviderEventPublishError({ + providerSessionId: ProviderSessionId.make(`session:${key}`), + eventCount: 1, + cause: new Error("SQLITE_FULL: database or disk is full"), + }), + ) + : Effect.succeed([]), + }); + assert.deepEqual( + finalEvents.flatMap((event) => + event.type === "context-handoff.updated" ? [event.payload.id] : [], + ), + [handoff.id], + ); + }), +); + it.effect("does not interrupt a provider when ingestion fails before the root turn is known", () => Effect.gen(function* () { const interrupts = yield* Ref.make(0); @@ -3989,6 +4033,7 @@ function captureRootRunTermination(input: { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; + readonly loadDroppedInlineHandoffs?: RunExecutionService.RunExecutionServiceV2StartRootRunInput["loadDroppedInlineHandoffs"]; readonly hasPendingBackgroundWorkForThread?: ProviderAdapter.ProviderAdapterV2SessionRuntime["hasPendingBackgroundWorkForThread"]; readonly seedOpenSubagent?: boolean; readonly events?: ( @@ -4235,6 +4280,9 @@ function captureRootRunTermination(input: { ...(input.hasWorkspaceMoved === undefined ? {} : { hasWorkspaceMoved: input.hasWorkspaceMoved }), + ...(input.loadDroppedInlineHandoffs === undefined + ? {} + : { loadDroppedInlineHandoffs: input.loadDroppedInlineHandoffs }), message: { messageId: MessageId.make(`message:${input.key}`), text: input.messageText ?? "interrupt projection", diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 1bc83f639d5ae..34cc31f98fa09 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -9,6 +9,7 @@ import { type NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderFailure, @@ -658,6 +659,11 @@ export interface RunExecutionServiceV2StartRootRunInput { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; + /** Restores inline context handoffs if the provider drops this turn's prompt before persisting it. */ + readonly loadDroppedInlineHandoffs?: () => Effect.Effect< + ReadonlyArray, + never + >; /** * Stored rows of a thread's unsettled work. Work a dead runtime left is ended from these, since * Stop may have settled it after the snapshots this run holds. @@ -736,6 +742,7 @@ export const layer: Layer.Layer< readonly abandonedProviderTurn?: OrchestrationV2ProviderTurn; // Stored root tool calls still open when the provider runtime was lost; nothing else ends them. readonly lostToolCalls?: ReadonlyArray; + readonly restoredHandoffs?: ReadonlyArray; readonly terminal: ProviderTerminalEvent; readonly completedAt?: DateTime.Utc; readonly failureItemPersisted: boolean; @@ -752,24 +759,35 @@ export const layer: Layer.Layer< status: input.terminal.status, completedAt, }; + const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); + const buildRestoredHandoffEvents = () => + input.terminal.promptDropped === true && + input.restoredHandoffs !== undefined && + input.restoredHandoffs.length > 0 + ? Effect.forEach(input.restoredHandoffs, (handoff) => + Effect.map(allocateEventId(), (id) => ({ + id, + type: "context-handoff.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: { ...handoff, updatedAt: completedAt }, + })), + ) + : Effect.succeed([]); const shouldFinalizeRun = input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun(); if (!shouldFinalizeRun) { - if (input.terminal.status === "interrupted") { - const hasUnpairedRequest = - input.hasUnpairedRunInterruptRequest === undefined - ? false - : yield* input.hasUnpairedRunInterruptRequest(); - if (hasUnpairedRequest) { - const reason = - input.loadRunInterruptReason === undefined - ? undefined - : yield* input.loadRunInterruptReason(); - yield* eventSink.writeWithEffects({ - effects: [], - events: [ + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); + const unpairedInterruptEvents = + input.terminal.status === "interrupted" && + (input.hasUnpairedRunInterruptRequest === undefined + ? false + : yield* input.hasUnpairedRunInterruptRequest()) + ? [ { - id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), + id: yield* allocateEventId(), type: "turn-item.updated" as const, threadId: input.run.threadId, runId: input.run.id, @@ -781,18 +799,25 @@ export const layer: Layer.Layer< run: input.run, rootNode: input.rootNode, providerThread: input.providerThread, - reason, + reason: + input.loadRunInterruptReason === undefined + ? undefined + : yield* input.loadRunInterruptReason(), completedAt, }), }, - ], - }); - yield* input.refreshAfterTurn; - } + ] + : []; + const earlyEvents = [...unpairedInterruptEvents, ...restoredHandoffEvents]; + if (earlyEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: earlyEvents, + }); + yield* input.refreshAfterTurn; } return false; } - const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); const reason = input.terminal.status === "interrupted" ? ((input.loadRunInterruptReason === undefined @@ -839,6 +864,7 @@ export const layer: Layer.Layer< status: finalProviderThreadStatus(input.terminal.threadDisposition), updatedAt: completedAt, }; + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); const runEventId = yield* allocateEventId(); const nodeEventId = yield* allocateEventId(); const providerThreadEventId = yield* allocateEventId(); @@ -1005,6 +1031,7 @@ export const layer: Layer.Layer< occurredAt: completedAt, payload: finalizedProviderThread, }, + ...restoredHandoffEvents, ], } satisfies Parameters[0]; if (input.writeIfRunCurrent !== undefined) { @@ -1031,6 +1058,13 @@ export const layer: Layer.Layer< effects: finalization.effects, }); if (!result.committed) { + if (restoredHandoffEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: restoredHandoffEvents, + }); + yield* input.refreshAfterTurn; + } return false; } } else { @@ -1275,44 +1309,55 @@ export const layer: Layer.Layer< } const providerThread = yield* Ref.get(latestProviderThread); const openSubagents = yield* Ref.get(openRunOwnedSubagents); - const writeTerminal = (settledTerminal: ProviderTerminalEvent) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { - shouldFinalizeRun: input.shouldFinalizeRun, - // Stop may commit between the ownership read and this - // terminal write. Gate the events and checkpoint together. - writeIfRunCurrent: { - activeAttemptId: input.attempt.id, - expectedStatus: "running" as const, - unlessInterruptRequested: settledTerminal !== terminal, - }, - }), - ...(input.hasUnpairedRunInterruptRequest === undefined - ? {} - : { - hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, - }), - ...(input.loadRunInterruptReason === undefined - ? {} - : { loadRunInterruptReason: input.loadRunInterruptReason }), - openRunOwnedSubagents: openSubagents, - openRunOwnedSubagentsTerminal: terminal, - ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), - terminal: settledTerminal, - failureItemPersisted: settledTerminal.status === "failed", - refreshAfterTurn, - }).pipe( - Effect.mapError( - (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + const writeTerminal = Effect.fnUntraced( + function* (settledTerminal: ProviderTerminalEvent) { + const restoredHandoffs = + settledTerminal.promptDropped === true && + input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; + return yield* writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { + shouldFinalizeRun: input.shouldFinalizeRun, + // Stop may commit between the ownership read and this + // terminal write. Gate the events and checkpoint together. + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running" as const, + unlessInterruptRequested: settledTerminal !== terminal, + }, + }), + ...(input.hasUnpairedRunInterruptRequest === undefined + ? {} + : { + hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, + }), + ...(input.loadRunInterruptReason === undefined + ? {} + : { loadRunInterruptReason: input.loadRunInterruptReason }), + openRunOwnedSubagents: openSubagents, + openRunOwnedSubagentsTerminal: terminal, + ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), + ...(restoredHandoffs === undefined ? {} : { restoredHandoffs }), + terminal: settledTerminal, + failureItemPersisted: settledTerminal.status === "failed", + refreshAfterTurn, + }); + }, + (effect) => + effect.pipe( + Effect.mapError( + (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + ), ), - ); + ); // A workspace handoff detaches the session and stops the turn that asked // for it: the run completes, while its native subagents still settle // as interrupted. The completed write refuses in the same transaction @@ -2116,6 +2161,13 @@ export const layer: Layer.Layer< : null; const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); const openSubagents = yield* Ref.get(openRunOwnedSubagents); + const droppedPrompt = + (yield* Ref.get(terminalEvent))?.promptDropped === true || + rootProviderTurn?.promptDropped === true; + const recoveredHandoffs = + droppedPrompt && input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; const lostToolCalls = runtimeLost ? yield* loadLostRootToolCalls.pipe( Effect.catchCauseIf( @@ -2141,18 +2193,24 @@ export const layer: Layer.Layer< }, openRunOwnedSubagents: openSubagents, ...(abandonedProviderTurn === null ? {} : { abandonedProviderTurn }), + ...(recoveredHandoffs === undefined + ? {} + : { restoredHandoffs: recoveredHandoffs }), lostToolCalls, completedAt, - terminal: makeFailedTerminalEvent( - makeProviderFailure({ - cause: squashed, - message: - knownProviderFailureMessage(squashed) ?? - userFacingDatabaseErrorMessage(squashed), - class: "unknown", - }), - latestItemOrdinal + 1, - ), + terminal: { + ...makeFailedTerminalEvent( + makeProviderFailure({ + cause: squashed, + message: + knownProviderFailureMessage(squashed) ?? + userFacingDatabaseErrorMessage(squashed), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + ...(droppedPrompt ? { promptDropped: true as const } : {}), + }, failureItemPersisted: false, refreshAfterTurn, }).pipe( diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index dd2d95cfc1b81..04257d91bc9a7 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1363,81 +1363,116 @@ it.effect("restarts the turn for an image when native steering takes text only", }), ); -it.effect("starts a steer that missed the turn on the saved next-turn selection", () => - Effect.gen(function* () { - const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - "steering-selection-follow-up", - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = yield* startFirstTurn; - const first = started[0]!; - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("steer"), - threadId, - messageId: MessageId.make("message:steer"), - text: "late steer", - attachments: [], - modelSelection: composerSelection, - dispatchMode: { type: "steer_active", targetRunId: first.runId }, - createdBy: "user", - creationSource: "web", - }); - const settled = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.id === first.runId && - event.payload.status === "waiting", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, +it.effect.each(["complete", "stop-before-end"] as const)( + "starts a steer that missed the turn in its place on the saved next-turn selection: %s", + (timing) => + Effect.gen(function* () { + const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + `steering-selection-follow-up-${timing}`, ); - const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver, - providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, - }); - yield* Queue.offer(events, { - type: "turn.terminal", - driver, - providerThreadId: turn.providerThreadId, - providerTurnId: turn.id, - runOrdinal: first.runOrdinal, - status: "completed", - failure: null, - threadDisposition: "reusable", - }); - yield* Fiber.join(settled); - yield* worker.drain(); - yield* orchestrator.resumeQueuedRuns; - yield* worker.drain(); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("steer"), + threadId, + messageId: MessageId.make("message:steer"), + text: "late steer", + attachments: [], + modelSelection: composerSelection, + dispatchMode: { type: "steer_active", targetRunId: first.runId }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("queued-later"), + threadId, + messageId: MessageId.make("message:queued-later"), + text: "queued later", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + if (timing === "stop-before-end") { + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + holdQueue: true, + }); + } + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "waiting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: first.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + yield* worker.drain(); + if (timing === "stop-before-end") { + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs + .filter((run) => run.status === "queued") + .toSorted((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0)); + assert.deepEqual( + queued.map((run) => [run.userMessageId, run.queueHeld === true]), + [ + [MessageId.make("message:steer"), false], + [MessageId.make("message:queued-later"), false], + ], + ); + return; + } + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, []); - assert.equal(started.length, 2); - assert.equal(started[1]?.message.messageId, MessageId.make("message:steer")); - assert.deepEqual(started[1]?.modelSelection, composerSelection); - assert.deepEqual(projection.thread.modelSelection, composerSelection); - const message = projection.turnItems.find( - (item) => - item.type === "user_message" && item.messageId === MessageId.make("message:steer"), - ); - assert.equal(message?.runId, started[1]!.runId); - assert.isAbove( - message!.ordinal, - Math.max( - ...projection.turnItems - .filter((item) => item.runId === first.runId) - .map((item) => item.ordinal), - ), - ); - }).pipe(Effect.provide(layer)); - }), + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, []); + assert.equal(started.length, 2); + assert.equal(started[1]?.message.messageId, MessageId.make("message:steer")); + assert.deepEqual(started[1]?.modelSelection, composerSelection); + assert.deepEqual(projection.thread.modelSelection, composerSelection); + const message = projection.turnItems.find( + (item) => + item.type === "user_message" && item.messageId === MessageId.make("message:steer"), + ); + assert.equal(message?.runId, started[1]!.runId); + assert.isAbove( + message!.ordinal, + Math.max( + ...projection.turnItems + .filter((item) => item.runId === first.runId) + .map((item) => item.ordinal), + ), + ); + }).pipe(Effect.provide(layer)); + }), ); const declinedSteerTimings = [ diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index e0ae516a190b5..0382415179bfc 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -103,6 +103,8 @@ export interface ThreadLaunchInput { readonly projectId: ProjectId; readonly title: string; readonly generateTitle?: boolean; + /** The caller chose `title`, so a first message keeps it. */ + readonly titleRenamed?: boolean; readonly modelSelection: ModelSelection; readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; @@ -1458,6 +1460,7 @@ const make = Effect.gen(function* () { threadId: candidateThreadId, projectId: input.projectId, title: input.title, + ...(input.titleRenamed === true ? { titleRenamed: true } : {}), modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index b20feef64eadd..07bb2d64d80a5 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -28,6 +28,8 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as PubSub from "effect/PubSub"; @@ -687,8 +689,24 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: const layerDependencies = Layer.mergeAll( Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)), + getShell: (projectId) => + Ref.get(snapshots).pipe( + Effect.map((snapshot) => + Option.fromNullishOr(snapshot.projects.find((project) => project.id === projectId)), + ), + ), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadsWithPullRequests: (_threadId, readOptions) => + Ref.get(snapshots).pipe( + Effect.map((snapshot) => + snapshot.threads + .filter( + (thread) => readOptions?.includeArchived === true || thread.archivedAt === null, + ) + .map((thread) => ({ ...thread, pullRequests: thread.pullRequests ?? [] })), + ), + ), ...options.projections, getSettlementCandidates: (threadId) => Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe( @@ -2109,6 +2127,103 @@ describe("ThreadSettlementServiceV2 worker", () => { }).pipe(Effect.provide(fixture.layer)); }), ); + + it.effect("a merge does not settle a local thread on the branch of another thread's PR", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const mergedLink = { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")), + snapshot: { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")).snapshot!, + state: "merged" as const, + mergedAt: NOW, + }, + }; + const owner = makeThread("pr-owner", { branch: "feature", pullRequests: [mergedLink] }); + const sibling = makeThread("local-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }); + const cachedSibling = makeThread("cached-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + branchPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 42, + url: "https://example.test/owner/repository/pull/42", + }, + }); + const legacyOwner = makeThread("legacy-owner", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + linkedPullRequest: cachedSibling.branchPullRequest, + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([owner, sibling, legacyOwner, cachedSibling]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: null, + }, + branchPullRequest: () => Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + expect( + [ + ...new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)), + ].toSorted(), + ).toEqual([legacyOwner.id, owner.id].toSorted()); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + it.effect("an archived thread's pull request does not settle a local thread on its branch", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const link = persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")); + const owner = makeThread("archived-owner", { + branch: "feature", + archivedAt: DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"), + pullRequests: [ + { ...link, snapshot: { ...link.snapshot!, state: "merged", mergedAt: NOW } }, + ], + }); + const sibling = makeThread("local-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([owner, sibling]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: null, + }, + branchPullRequest: () => Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + expect(yield* Ref.get(fixture.commands)).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); }); describe("ThreadSettlementServiceV2 terminals", () => { @@ -2141,12 +2256,29 @@ describe("ThreadSettlementServiceV2 terminals", () => { it.effect("runs the settle script in the thread's own worktree", () => Effect.gen(function* () { + const warnings: string[] = []; + const logger = Logger.make(({ logLevel, message }) => { + if (logLevel === "Warn") warnings.push(JSON.stringify(message)); + }); const shared = appThread("shared-checkout-thread", "settled"); const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed"); const worktree = appThread("worktree-thread", "settled", "/worktrees/thread"); + const scriptless = makeProject(ProjectId.make("scriptless-project")); + const missingScriptless = { + ...appThread("removed-worktree-scriptless-thread", "settled", "/worktrees/scriptless"), + projectId: scriptless.id, + }; + const teardown = { + id: "teardown", + name: "Teardown", + command: "docker compose down", + icon: "configure", + runOnWorktreeCreate: false, + runOnSettle: true, + } as const; const fixture = yield* makeHarness({ - snapshot: makeSnapshot([]), - currentThreads: [shared, missing, worktree], + snapshot: makeSnapshot([], [{ ...makeProject(), scripts: [teardown] }, scriptless]), + currentThreads: [shared, missing, missingScriptless, worktree], existingWorktreePaths: ["/worktrees/thread"], }); @@ -2155,12 +2287,23 @@ describe("ThreadSettlementServiceV2 terminals", () => { yield* startHarness(service, fixture.activation, fixture.snapshotReads); yield* fixture.publishEvent(settledEvent(shared)); yield* fixture.publishEvent(settledEvent(missing)); + yield* fixture.publishEvent(settledEvent(missingScriptless)); yield* fixture.publishEvent(settledEvent(worktree)); const run = yield* Queue.take(fixture.scriptRuns); assert.strictEqual(run.threadId, worktree.id); assert.strictEqual(run.worktreePath, "/worktrees/thread"); assert.strictEqual(run.trigger, "settle"); - }).pipe(Effect.provide(fixture.layer)); + // A removed worktree skips a configured settle script; the log is its only trace. + assert.strictEqual(warnings.length, 1); + assert.include(warnings[0], missing.id); + assert.include(warnings[0], "/worktrees/removed"); + }).pipe( + Effect.provide( + fixture.layer.pipe( + Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })), + ), + ), + ); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 6f05e0fd3c40c..ef0894f3ecbeb 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -3,6 +3,7 @@ import { isPullRequestWatchTask, turnItemUpdateCanEndBackgroundWork, } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import { resolveProjectScripts, settleProjectScript } from "@t3tools/shared/projectScripts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { @@ -20,6 +21,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; @@ -35,6 +37,10 @@ import * as TerminalManager from "../terminal/Manager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ProjectStore from "./ProjectStore.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { + legacyThreadPullRequestKey, + threadPullRequestKeyOf, +} from "../sourceControl/threadPullRequests.ts"; import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -87,6 +93,20 @@ function pullRequestMatchesProject( ); } +function branchPullRequestKey(pullRequest: GitManager.GitBranchPullRequest): string | null { + const parsed = sourceControlDefinitions.parseChangeRequestUrl(pullRequest.url)?.link; + if (parsed !== undefined && parsed.number === pullRequest.number) { + return threadPullRequestKeyOf(parsed); + } + const separator = pullRequest.repositoryKey?.indexOf("/") ?? -1; + if (pullRequest.repositoryKey == null || separator <= 0) return null; + return threadPullRequestKeyOf({ + host: pullRequest.repositoryKey.slice(0, separator), + repository: pullRequest.repositoryKey.slice(separator + 1), + number: pullRequest.number, + }); +} + type SettlementPullRequestLink = NonNullable< ProjectionStore.ProjectionSettlementCandidate["pullRequests"] >[number]; @@ -481,7 +501,7 @@ export const make = Effect.gen(function* () { const reference = thread.linkedPullRequest ?? thread.branchPullRequest; if (reference != null) { return JSON.stringify([ - "linked", + thread.linkedPullRequest != null ? "linked" : "branch-reference", reference.projectId, reference.repository, reference.number, @@ -496,6 +516,22 @@ export const make = Effect.gen(function* () { ); }; const groups = Map.groupBy(lookupCandidates, lookupKey); + // A thread with no link of its own does not settle from a pull request another thread links, + // archived threads included. + const explicitlyLinked = new Set( + groups.size === 0 + ? [] + : (yield* projections.getThreadsWithPullRequests(undefined, { + includeArchived: true, + })).flatMap((thread) => + visibleThreadPullRequests(thread.pullRequests ?? []).map(threadPullRequestKeyOf), + ), + ); + const ownedByAnotherThread = (pullRequest: GitManager.GitBranchPullRequest | null) => { + if (pullRequest === null || pullRequest.state === "open") return false; + const key = branchPullRequestKey(pullRequest); + return key !== null && explicitlyLinked.has(key); + }; // wouldSettle and pullRequestFor run per lookup group; the git and pull request reads they make carry the spans. const wouldSettle = Effect.fnUntraced(function* ( @@ -524,6 +560,13 @@ export const make = Effect.gen(function* () { ) { const thread = group[0]!; const reference = thread.linkedPullRequest ?? thread.branchPullRequest; + if ( + thread.linkedPullRequest == null && + reference != null && + explicitlyLinked.has(threadPullRequestKeyOf(legacyThreadPullRequestKey(reference))) + ) { + return undefined; + } if (reference != null) { // Only matching PR links settle from this merge event; unrelated links require fresh lookup. const matchesMerge = @@ -601,9 +644,14 @@ export const make = Effect.gen(function* () { { refresh, confirmTerminal: false }, ); noPullRequestRechecks.record(key, nowMs, remembered !== null); + if (ownedByAnotherThread(remembered)) return undefined; if (refresh || remembered === null || remembered.state === "open") return remembered; if (!(yield* wouldSettle(group, remembered))) return undefined; - return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { freshGitState: true }); + const fresh = yield* git.branchPullRequest( + { cwd, branch: thread.branch }, + { freshGitState: true }, + ); + return ownedByAnotherThread(fresh) ? undefined : fresh; }); // A merge, a shell close and a thread's own events read at once; only scheduled sweeps wait. @@ -712,7 +760,21 @@ export const make = Effect.gen(function* () { if (settled.deletedAt !== null || settled.settledOverride !== "settled") return; yield* terminals.closeOnSettle({ threadId }); const worktreePath = settled.worktreePath; - if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return; + if (worktreePath === null) return; + if (!(yield* fileSystem.exists(worktreePath))) { + // A settle script that tears something down would otherwise be skipped with no trace. + const project = Option.getOrUndefined(yield* projectStore.getShell(settled.projectId)); + if ( + project !== undefined && + settleProjectScript(resolveProjectScripts(yield* settingsService.getSettings, project)) + ) { + yield* Effect.logWarning( + "settle script skipped: the thread's worktree no longer exists", + { threadId, worktreePath }, + ); + } + return; + } // Recheck after closing and worktree I/O; only live, settled threads may run scripts. const thread = yield* projections.getThread(threadId); if (thread.deletedAt !== null || thread.settledOverride !== "settled") return; diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts index 20cd5aaa76236..1d39000ed3a9f 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts @@ -343,9 +343,19 @@ describe("ThreadTitleRegenerationService", () => { const threads = yield* ThreadManagement.ThreadManagementService; const outbox = yield* EffectOutbox.EffectOutboxV2; // An MCP launch names the thread, or leaves a placeholder, and sends no message. - for (const [key, title, expectedTitle, generates] of [ - ["preset", "[API] #4821 — retry webhook deliveries after a timeout", undefined, false], - ["placeholder", placeholderThreadTitle("Parent", 0), seed, true], + for (const [key, title, titleRenamed, compactFirst, expectedTitle, generates] of [ + [ + "preset", + "[API] #4821 - retry webhook deliveries after a timeout", + false, + false, + undefined, + false, + ], + ["placeholder", placeholderThreadTitle("Parent", 0), false, false, seed, true], + ["named like a placeholder", "Release thread 2", true, false, undefined, false], + ["named, then compacted", "Release notes", true, true, undefined, false], + ["draft titled by its /compact", "/compact", false, true, seed, true], ] as const) { const threadId = ThreadId.make(`thread:title:${key}`); yield* threads.dispatch({ @@ -354,6 +364,7 @@ describe("ThreadTitleRegenerationService", () => { threadId, projectId, title, + ...(titleRenamed ? { titleRenamed } : {}), modelSelection, runtimeMode: "full-access", interactionMode: "default", @@ -362,6 +373,21 @@ describe("ThreadTitleRegenerationService", () => { createdBy: "agent", creationSource: "mcp", }); + if (compactFirst) { + yield* threads.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`command:title:${key}:compact`), + threadId, + messageId: MessageId.make(`command:title:${key}:compact:message`), + text: "/compact", + titleSeed: "/compact", + attachments: [], + modelSelection, + dispatchMode: { type: "defer_start" }, + createdBy: "user", + creationSource: "web", + }); + } const requestId = CommandId.make(`command:title:${key}:message`); yield* threads.dispatch({ type: "message.dispatch", diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index ee048c2100592..ddf9259622599 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -118,6 +118,7 @@ function makeTestAdapter(input: { readonly failure?: ReturnType; readonly rejectedNativeThreads?: Ref.Ref>; readonly failedRunOrdinals?: ReadonlySet; + readonly promptDroppedRunOrdinals?: ReadonlySet; readonly brokenRunOrdinals?: ReadonlySet; readonly interruptedRunOrdinals?: ReadonlySet; readonly cancelledRunOrdinals?: ReadonlySet; @@ -410,6 +411,9 @@ function makeTestAdapter(input: { status: terminalStatus, startedAt: eventTime, completedAt: eventTime, + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, }, { @@ -462,6 +466,9 @@ function makeTestAdapter(input: { threadDisposition: input.brokenRunOrdinals?.has(turnInput.runOrdinal) ? "broken" : "reusable", + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, ]; const reportedUsage = input.tokenUsageByRunOrdinal?.[turnInput.runOrdinal]; @@ -6400,4 +6407,166 @@ describe("orchestration v2 provider switching", () => { ); }), ); + + it.effect.each([ + "same-provider-retry", + "cancelled-dropped", + "switch-away-and-return", + "persisted-failure", + ] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`); + const capturedTurns = yield* Ref.make>([]); + const dropped = variant !== "persisted-failure"; + const cancelled = variant === "cancelled-dropped"; + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { + 1: "Morning Codex summary.", + 3: "", + 4: "Recovered Codex answer.", + 5: "Recovered Codex after round-trip.", + }, + capturedTurns, + ...(cancelled + ? { cancelledRunOrdinals: new Set([3]) } + : { failedRunOrdinals: new Set([3]) }), + ...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}), + }), + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { + 2: "Afternoon Claude shipped b63 live draft.", + 4: "Extra Claude turn after dropped handoff.", + }, + capturedTurns, + }), + ]); + + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const testThreadId = ThreadId.make(`thread:dropped-handoff:${variant}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:create`), + threadId: testThreadId, + projectId, + title: `Dropped handoff ${variant}`, + modelSelection: CODEX_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + let step = 0; + const send = (text: string, modelSelection: ModelSelection) => + Effect.gen(function* () { + step += 1; + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:msg-${step}`), + threadId: testThreadId, + messageId: MessageId.make(`message:dropped-handoff:${variant}:${step}`), + text, + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* waitForIdle(testThreadId); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(testThreadId); + }); + + // Run 1: establish native session on Codex. + yield* send("Morning task", CODEX_MODEL_SELECTION); + // Run 2: switch to Claude and do real work. + yield* send("Build live draft b63", CLAUDE_MODEL_SELECTION); + // Run 3: switch back to Codex (delta handoff covering run 2); fails. + const afterRun3 = yield* send("Resume after failure", CODEX_MODEL_SELECTION); + const run3 = afterRun3.runs.find((run) => run.ordinal === 3)!; + assert.equal(run3.status, cancelled ? "cancelled" : "failed"); + const run3Handoff = afterRun3.contextHandoffs.find( + (handoff) => handoff.targetRunId === run3.id, + ); + assert.isDefined(run3Handoff); + assert.deepEqual(run3Handoff?.coveredRunOrdinals, { from: 2, to: 2 }); + + if (dropped) { + assert.isUndefined( + run3Handoff?.delivery, + "dropping the failed prompt must clear inline handoff delivery", + ); + const run3Turn = afterRun3.providerTurns.find( + (turn) => turn.runAttemptId === run3.activeAttemptId, + ); + assert.equal(run3Turn?.promptDropped, true); + } else { + assert.equal(run3Handoff?.delivery?.status, "inline"); + } + + if (variant === "same-provider-retry" || variant === "cancelled-dropped") { + // Run 4: stay on Codex; must re-deliver run 2's handoff. + const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION); + const turns = yield* Ref.get(capturedTurns); + const run4Turn = turns.at(-1)!; + assert.include(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run4Turn.text, "Resume after failure"); + assert.include(run4Turn.text, "User message:\nResume"); + const updatedHandoff = afterRun4.contextHandoffs.find( + (handoff) => handoff.id === run3Handoff!.id, + ); + assert.equal(updatedHandoff?.delivery?.status, "inline"); + } else if (variant === "switch-away-and-return") { + // Run 4: bounce back to Claude, then Run 5: return to Codex. + yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION); + const afterRun5 = yield* send("Back to Codex", CODEX_MODEL_SELECTION); + const run5 = afterRun5.runs.find((run) => run.ordinal === 5)!; + const run5Handoff = afterRun5.contextHandoffs.find( + (handoff) => handoff.targetRunId === run5.id, + ); + assert.isDefined(run5Handoff); + assert.deepEqual(run5Handoff?.coveredRunOrdinals, { from: 2, to: 4 }); + const run5Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.include(run5Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run5Turn.text, "Extra Claude turn after dropped handoff."); + } else { + // Control: run 3 persisted its prompt before failing, so run 4 must not re-send run 2. + yield* send("Resume", CODEX_MODEL_SELECTION); + const run4Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.notInclude(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + } + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: `dropped-handoff-${variant}`, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ); }); diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts index 857adb2c8e5c3..46b3b6b1e9936 100644 --- a/apps/server/src/os-jank.test.ts +++ b/apps/server/src/os-jank.test.ts @@ -149,44 +149,52 @@ effectIt.effect("keeps mise's PATH record with the login shell PATH", () => ), ); -effectIt.effect("hydrates a missing JAVA_HOME from the login shell and keeps an explicit one", () => - Effect.acquireUseRelease( - Effect.sync(() => - vi - .spyOn(NodeChildProcess, "execFileSync") - .mockReturnValue( - [ - "__T3CODE_ENV_PATH_START__", - "/opt/homebrew/bin", - "__T3CODE_ENV_PATH_END__", - "__T3CODE_ENV_JAVA_HOME_START__", - "/opt/homebrew/opt/openjdk@17", - "__T3CODE_ENV_JAVA_HOME_END__", - ].join("\n"), - ), +effectIt.effect( + "hydrates missing JAVA_HOME and feature flags from the login shell and keeps explicit ones", + () => + Effect.acquireUseRelease( + Effect.sync(() => + vi + .spyOn(NodeChildProcess, "execFileSync") + .mockReturnValue( + [ + "__T3CODE_ENV_PATH_START__", + "/opt/homebrew/bin", + "__T3CODE_ENV_PATH_END__", + "__T3CODE_ENV_JAVA_HOME_START__", + "/opt/homebrew/opt/openjdk@17", + "__T3CODE_ENV_JAVA_HOME_END__", + "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_START__", + "tanstack_source", + "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_END__", + ].join("\n"), + ), + ), + () => + Effect.gen(function* () { + const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + const explicit: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + JAVA_HOME: "/custom/jdk", + T3CODE_FEATURE_FLAGS: "", + }; + + for (const env of [missing, explicit]) { + yield* fixPath().pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, env), + Effect.provide(NodeServices.layer), + ); + } + + assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17"); + assert.equal(explicit.JAVA_HOME, "/custom/jdk"); + assert.equal(missing.T3CODE_FEATURE_FLAGS, "tanstack_source"); + assert.equal(explicit.T3CODE_FEATURE_FLAGS, ""); + }), + (probe) => Effect.sync(() => probe.mockRestore()), ), - () => - Effect.gen(function* () { - const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; - const explicit: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - JAVA_HOME: "/custom/jdk", - }; - - for (const env of [missing, explicit]) { - yield* fixPath().pipe( - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService(HostProcess.Environment, env), - Effect.provide(NodeServices.layer), - ); - } - - assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17"); - assert.equal(explicit.JAVA_HOME, "/custom/jdk"); - }), - (probe) => Effect.sync(() => probe.mockRestore()), - ), ); effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () => diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts index bc6528f91a5be..dc0c90a787123 100644 --- a/apps/server/src/os-jank.ts +++ b/apps/server/src/os-jank.ts @@ -32,7 +32,7 @@ function logPathHydrationWarning(message: string, error?: unknown): void { // __MISE_DIFF is mise's record of the PATH entries it added. It must travel // with the shell's PATH, or `mise x` can rebuild PATH behind a same-named // wrapper (`exec mise x claude -- claude`) that then re-runs itself forever. -const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME"] as const; +const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME", "T3CODE_FEATURE_FLAGS"] as const; const LOGIN_SHELL_TIMEOUT = Duration.seconds(5); const SLOW_LOGIN_SHELL_TIMEOUT_MS = 20_000; @@ -64,6 +64,10 @@ function applyLoginShellEnvironment( if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) { env.JAVA_HOME = shellEnvironment.JAVA_HOME; } + // A headless server (systemd, launchd) reads no profile, yet flags belong where users export them. + if (env.T3CODE_FEATURE_FLAGS === undefined && shellEnvironment.T3CODE_FEATURE_FLAGS) { + env.T3CODE_FEATURE_FLAGS = shellEnvironment.T3CODE_FEATURE_FLAGS; + } } function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void { diff --git a/apps/server/src/persistence/IssueTrackerBindings.ts b/apps/server/src/persistence/IssueTrackerBindings.ts index fbb0a398900d2..2f665b487e03f 100644 --- a/apps/server/src/persistence/IssueTrackerBindings.ts +++ b/apps/server/src/persistence/IssueTrackerBindings.ts @@ -26,7 +26,9 @@ const BindingRow = Schema.Struct({ export class IssueTrackerBindingsRepository extends Context.Service< IssueTrackerBindingsRepository, { - readonly list: Effect.Effect< + readonly list: ( + projectId?: ProjectId, + ) => Effect.Effect< ReadonlyMap, IssueTrackerBindingsRepositoryError >; @@ -56,32 +58,35 @@ function toSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const select = sql` + SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", + additional_scopes AS "additionalScopes" + FROM issue_tracker_bindings + `; const listRows = SqlSchema.findAll({ - Request: Schema.Void, + Request: Schema.UndefinedOr(ProjectId), Result: BindingRow, - execute: () => - sql` - SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", - additional_scopes AS "additionalScopes" - FROM issue_tracker_bindings - `, + execute: (projectId) => + projectId === undefined ? select : sql`${select} WHERE project_id = ${projectId}`, }); return IssueTrackerBindingsRepository.of({ - list: listRows(undefined).pipe( - Effect.map( - (rows) => - new Map( - rows.map( - ({ projectId, additionalScopes, ...binding }) => - [ - projectId, - additionalScopes.length === 0 ? binding : { ...binding, additionalScopes }, - ] as const, + list: Effect.fn("IssueTrackerBindingsRepository.list")((projectId?: ProjectId) => + listRows(projectId).pipe( + Effect.map( + (rows) => + new Map( + rows.map( + ({ projectId, additionalScopes, ...binding }) => + [ + projectId, + additionalScopes.length === 0 ? binding : { ...binding, additionalScopes }, + ] as const, + ), ), - ), + ), + Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), - Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), set: Effect.fn("IssueTrackerBindingsRepository.set")( function* (input) { diff --git a/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts b/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts index 3ea190f41d2ed..9e61347812e74 100644 --- a/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts +++ b/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts @@ -21,13 +21,19 @@ it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))( ); const projectId = ProjectId.make("web"); const binding = { tracker: IssueTrackerKind.make("linear"), scope: "ENG" }; - const read = () => bindings.list.pipe(Effect.map((all) => all.get(projectId))); + const read = () => bindings.list(projectId).pipe(Effect.map((rows) => rows.get(projectId))); assert.deepStrictEqual(yield* read(), binding); const multi = { ...binding, additionalScopes: ["OPS", "DOCS"] }; yield* bindings.set({ projectId, binding: multi, updatedAt: "2026-11-21" }); assert.deepStrictEqual(yield* read(), multi); yield* bindings.set({ projectId, binding, updatedAt: "2026-11-21" }); assert.deepStrictEqual(yield* read(), binding); + yield* sql` + INSERT INTO issue_tracker_bindings (project_id, tracker, scope, updated_at, additional_scopes) + VALUES ('other', 'linear', 'OPS', '2026-11-21', 'invalid') + `; + assert.deepStrictEqual(yield* read(), binding); + assert.strictEqual((yield* Effect.result(bindings.list()))._tag, "Failure"); }), ); }, diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 8ce873733d443..827d52bbda230 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -65,6 +65,7 @@ const layerTest = (input: { readonly onSpawn?: (command: ChildProcess.StandardCommand) => void; readonly onUnref?: () => void; readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined; + readonly existingPaths?: ReadonlyArray; }) => { const layerSpawner = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, @@ -92,6 +93,17 @@ const layerTest = (input: { NodeServices.layer, layerSpawner, input.path ? Layer.succeed(Path.Path, input.path) : Layer.empty, + // Reveal fixtures name paths that do not exist on the test host. + Layer.effect( + FileSystem.FileSystem, + Effect.map(FileSystem.FileSystem, (fileSystem) => ({ + ...fileSystem, + exists: (path: string) => + input.existingPaths?.includes(path) + ? Effect.succeed(true) + : fileSystem.exists(path), + })), + ).pipe(Layer.provide(NodeServices.layer)), ), ), ), @@ -571,6 +583,7 @@ for (const [replacement, verb, handler, target, expected] of [ layerTest({ platform: "win32", env: { PATH: "C:\\Windows", PATHEXT: ".EXE" }, + existingPaths: [target], onSpawn: (command) => { spawned = command; }, @@ -605,16 +618,13 @@ it.effect.skipIf(windowsHost)( yield* fileSystem.chmod(filePath, 0o755); } + const target = "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4"; let spawned: ChildProcess.StandardCommand | undefined; const result = yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; const kind = yield* launcher.resolveFileManagerRevealKind(); const editors = yield* launcher.resolveAvailableEditors(); - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4", - reveal: true, - }); + yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true }); return { kind, editors }; }).pipe( Effect.provide( @@ -625,6 +635,7 @@ it.effect.skipIf(windowsHost)( WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop", }, + existingPaths: [target], onSpawn: (command) => { spawned = command; }, @@ -687,6 +698,7 @@ it.effect.each([ layerTest({ platform: "win32", env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + existingPaths: ["C:/Users/t3/my project/a,b.ts"], onSpawn: (command) => spawned.push(command), spawnResult: (command) => (command.command.endsWith("reg.exe") ? registry : undefined), }), @@ -718,6 +730,38 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +// Explorer answers /select of a missing path by opening its default folder, not the parent. +it.effect("does not ask Explorer to select a file that does not exist", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + yield* fileSystem.writeFileString(path.join(binDir, "explorer.EXE"), ""); + const missing = path.join(binDir, "CLAUDE.md"); + const verbatim: Array]> = []; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher + .launchEditor({ editor: "file-manager", cwd: missing, reveal: true }) + .pipe(Effect.exit); + }).pipe( + Effect.provideService(WindowsVerbatimSpawn, (command, args) => + Effect.sync(() => verbatim.push([command, args])), + ), + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + spawnResult: (command) => + command.command.endsWith("reg.exe") ? { stdout: STOCK_FOLDER_VERB } : undefined, + }), + ), + ); + + assert.deepEqual(verbatim, []); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + for (const wsl of [false, true]) { it.effect.skipIf(windowsHost)( "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"), @@ -747,6 +791,7 @@ for (const wsl of [false, true]) { ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" } : {}), }, + existingPaths: [target], onSpawn: (command) => spawnedCommands.push(command), spawnResult: (command) => command.command === "xdg-mime" diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index caa6664a1ba80..b5ffaf82fcc10 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -6,6 +6,7 @@ import { ExternalLauncherBrowserSpawnError, ExternalLauncherCommandNotFoundError, ExternalLauncherEditorSpawnError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherUnknownEditorError, ExternalLauncherUnsupportedEditorError, ExternalLauncherUnsupportedTargetError, @@ -15,11 +16,7 @@ import { } from "@t3tools/contracts"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { - isCommandAvailable, - resolveSpawnCommand, - withPathDirectoryListings, -} from "@t3tools/shared/shell"; +import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -40,6 +37,7 @@ export { ExternalLauncherBrowserSpawnError, ExternalLauncherCommandNotFoundError, ExternalLauncherEditorSpawnError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherUnknownEditorError, ExternalLauncherUnsupportedEditorError, ExternalLauncherUnsupportedTargetError, @@ -503,7 +501,7 @@ const readEditorEnv = Effect.fn("externalLauncher.readEditorEnv")(function* () { const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () { const platform = yield* HostProcess.Platform; const env = yield* readEditorEnv(); - return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings); + return yield* buildAvailableEditors(platform, env); }); const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")( @@ -594,6 +592,13 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( } if (input.reveal === true) { + // Explorer answers /select of a missing path by opening its default folder, not the parent. + const exists = yield* (yield* FileSystem.FileSystem) + .exists(target) + .pipe(Effect.orElseSucceed(() => true)); + if (!exists) { + return yield* new ExternalLauncherRevealTargetMissingError({ editor: editorDef.id, target }); + } return yield* resolveFileManagerRevealLaunch(target, platform, env, command); } diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index e254e101cf93e..3dd649811f330 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -115,7 +115,10 @@ function xml(source: string, extension: string): XmlNode { if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); if ( (extension === ".docx" && node.name === "del") || - (odf && node.name === "annotation" && parent.name !== "semantics") + (odf && node.name === "annotation" && parent.name !== "semantics") || + (extension === ".odp" && + node.name === "page-thumbnail" && + stack.some((ancestor) => ancestor.name === "notes")) ) { parent.children.pop(); return; @@ -621,8 +624,19 @@ async function* document(path: string, extension: string): AsyncGenerator child.name === "notes"); + yield* paragraphs({ + ...part, + children: part.children.filter((child) => child !== notes), + }); + if (notes && hasCellText(notes)) { + yield "\nNotes:\n"; + yield* paragraphs(notes); + } } } } else if (extension === ".xlsx") { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index b107188136a3d..72f7e52a3cd41 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1139,9 +1139,20 @@ describe("question answer paths", () => { ext: "odp", parts: { "content.xml": - "\n First\n\t slide Second", + "" + + "\n First\n\t slide " + + "Overview" + + "Speaker only" + + "Second" + + "Slide previewThumbnail metadata" + + "" + + "Third" + + '' + + "", }, - expected: ["## Slide 1\nFirst slide\n\n## Slide 2\nSecond"], + expected: [ + "## Slide 1\nFirst slide\nOverview\nNotes:\nSpeaker only\n\n## Slide 2\nSecond\n\n## Slide 3\nThird\n\nNotes:\n42", + ], }, { ext: "ods", diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ffdbf593bb5df..1a74ac2991183 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -18,6 +18,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { EnvironmentHttpApi, type RepositoryIdentity } from "@t3tools/contracts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; @@ -1423,6 +1424,7 @@ const layerMakeServer = Layer.unwrap( Layer.provide(VcsProcess.layer), Layer.provideMerge(AgentScopeLive.layer), Layer.provideMerge(layerPlatformServices), + Layer.provideMerge(FeatureFlags.layer), Layer.provide(Layer.succeed(HostProcess.InvokedAs, invokedAs)), ); }), diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index c6f823d61f3c6..06616a914b1e9 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -75,16 +75,11 @@ function unsupportedProvider( // Binding context does not create a second provider-operation span. return SourceControlProvider.SourceControlProvider.of({ kind, - // Unknown hosts have no readable change requests; return none to avoid poll warnings on every refresh. - listChangeRequests: (input) => - kind === "unknown" - ? Effect.succeed([]) - : new SourceControlProviderError({ - provider: kind, - operation: "listChangeRequests", - cwd: input.cwd, - detail: `No ${kind} source control provider is registered.`, - }), + // Unknown hosts, and hosts whose forge a feature flag leaves out, have no readable change + // requests; return none to avoid poll warnings on every refresh. + listChangeRequests: Effect.fn("SourceControlProviderRegistry.unsupported.listChangeRequests")( + () => Effect.succeed([]), + ), getChangeRequest: (input) => new SourceControlProviderError({ provider: kind, diff --git a/apps/server/src/sourceControl/builtInDrivers.ts b/apps/server/src/sourceControl/builtInDrivers.ts index 0e994dcac4a7f..33aa77ffefd8f 100644 --- a/apps/server/src/sourceControl/builtInDrivers.ts +++ b/apps/server/src/sourceControl/builtInDrivers.ts @@ -3,6 +3,7 @@ import type { SourceControlDriverInstance, } from "@t3tools/source-control-core/server/driver"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -21,9 +22,21 @@ export class SourceControlDrivers extends Context.Service< ReadonlyArray >()("t3/sourceControl/builtInDrivers/SourceControlDrivers") {} -const make = Effect.forEach(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST, (driver) => - driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), -); +/** Drivers offered only while their feature flag is on. */ +const FLAGGED_DRIVERS: Readonly> = { + "tanstack-source": "tanstackSource", +}; + +const make = Effect.gen(function* () { + const flags = yield* FeatureFlags.FeatureFlags; + const drivers = BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.filter((driver) => { + const flag = FLAGGED_DRIVERS[driver.kind]; + return flag === undefined || flags[flag]; + }); + return yield* Effect.forEach(drivers, (driver) => + driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), + ); +}); export const layer = Layer.effect(SourceControlDrivers, make).pipe( Layer.provideMerge(ServerSourceControlHost.layer), diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.ts b/apps/server/src/sourceControl/sourceControlDefinitions.ts index c6a770a897f02..6dff3fe3c6962 100644 --- a/apps/server/src/sourceControl/sourceControlDefinitions.ts +++ b/apps/server/src/sourceControl/sourceControlDefinitions.ts @@ -1,7 +1,7 @@ import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver"; import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver"; import * as CursorOriginDriver from "@t3tools/source-control-cursor-origin/server/driver"; -import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; +import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; @@ -9,26 +9,21 @@ import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver"; import * as TanStackSourceDriver from "@t3tools/source-control-tanstack-source/server/driver"; /** - * TanStack Source is in private beta, so its forge exists only on a server started with - * `T3CODE_TANSTACK_SOURCE=1`. Read once at load: the registry below is a module constant. + * In the shared registry's order, which is the order hosts are listed and probed in. Feature + * flags leave some out; see `builtInDrivers.ts`. */ -const tanStackSourceEnabled = process.env.T3CODE_TANSTACK_SOURCE?.trim() === "1"; - -/** In the shared registry's order, which is the order hosts are listed and probed in. */ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ GitHubDriver.driver, CursorOriginDriver.driver, GitLabDriver.driver, GitCafeDriver.driver, - ...(tanStackSourceEnabled ? [TanStackSourceDriver.driver] : []), + TanStackSourceDriver.driver, ForgejoDriver.driver, BitbucketDriver.driver, AzureDevOpsDriver.driver, ]; -export const sourceControlDefinitions = makeBuiltInSourceControlDefinitions({ - tanStackSource: tanStackSourceEnabled, -}); +export const sourceControlDefinitions = builtInSourceControlDefinitions; /** A host CLI command that merges or closes a change request, such as `gh pr merge`. */ export const isChangeRequestCloseCommand = (command: string) => diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 61dac26a8c044..3a02d202be891 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -193,6 +193,43 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { }), ); + it.effect("does not walk a project's folders when t3.json ignores the whole project", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* makeTempDir; + for (const folder of ["api/.git", "src/web/.git", "notes"]) { + yield* fileSystem.makeDirectory(path.join(workspaceRoot, folder), { recursive: true }); + } + yield* fileSystem.writeFileString( + path.join(workspaceRoot, "t3.json"), + JSON.stringify({ ignoreRepositories: ["."] }), + ); + const probed: Array = []; + const counting = FileSystem.FileSystem.of({ + ...fileSystem, + readDirectory: (target, options) => { + probed.push(target); + return fileSystem.readDirectory(target, options); + }, + stat: (target) => { + probed.push(target); + return fileSystem.stat(target); + }, + }); + + const found = yield* WorkspaceFolders.discoverFolders(workspaceRoot).pipe( + Effect.provideService(FileSystem.FileSystem, counting), + ); + + assert.deepEqual(found, []); + assert.deepEqual( + probed.filter((target) => target !== workspaceRoot), + [], + ); + }), + ); + it.effect("keeps the folders someone added when a project holds more than fit", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -293,17 +330,21 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { folders: [], extraRoots: [], }); - assert.deepEqual(yield* workspaceFolders.submodules({ projectId, worktreePath: null }), [ - { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, - { - name: "deep", - path: path.join(workspaceRoot, "vendor", "lib", "deep"), - isGitRepository: true, - }, - ]); + const { folders } = yield* workspaceFolders.forThread({ projectId, worktreePath: null }); + assert.deepEqual( + yield* workspaceFolders.submodules({ projectId, worktreePath: null, folders }), + [ + { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, + { + name: "deep", + path: path.join(workspaceRoot, "vendor", "lib", "deep"), + isGitRepository: true, + }, + ], + ); // A worktree reaches its own submodules, named by where the project folder has them. assert.deepEqual( - yield* workspaceFolders.submodules({ projectId, worktreePath: worktree }), + yield* workspaceFolders.submodules({ projectId, worktreePath: worktree, folders: [] }), [ { name: "lib", diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 776f90ea6e5b0..0824c647ce360 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -64,6 +64,8 @@ export class WorkspaceFolders extends Context.Service< readonly submodules: (input: { readonly projectId: ProjectId; readonly worktreePath: string | null; + /** The thread's `forThread` folders; passed in so the project is walked once. */ + readonly folders: ReadonlyArray; }) => Effect.Effect, WorkspaceFoldersError>; readonly list: ( input: WorkspaceListFoldersInput, @@ -276,11 +278,7 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const { realPath, ownsHistory } = yield* folderProbes; - // Uncapped: the folders outside the project are dropped below, and must not use up the room. - const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); - if (Option.isNone(scan)) return []; - const root = scan.value.workspaceRoot; - const realRoot = yield* realPath(root); + const root = path.resolve(expandHomePath(workspaceRoot.trim(), yield* HostProcess.HomeDirectory)); const ignored = ( parseT3ProjectFile( yield* fileSystem @@ -288,6 +286,12 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* .pipe(Effect.orElseSucceed(() => "")), )?.ignoreRepositories ?? [] ).map((entry) => path.resolve(root, entry)); + // Everything the scan could find would be dropped, so skip the walk. + if (ignored.some((entry) => isWithinRoot(path, root, entry))) return []; + // Uncapped: the folders outside the project are dropped below, and must not use up the room. + const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); + if (Option.isNone(scan)) return []; + const realRoot = yield* realPath(root); const inside = yield* Effect.filter( scan.value.folders.filter( (folder) => @@ -506,7 +510,6 @@ const make = Effect.gen(function* () { const submodules: WorkspaceFolders["Service"]["submodules"] = Effect.fn( "WorkspaceFolders.submodules", )(function* (input) { - const { folders } = yield* forThread(input); // A worktree can outlive its project record; its submodules are then named by where they are. const projectRoot = yield* readProject(input.projectId).pipe( Effect.map((project) => path.resolve(project.workspaceRoot)), @@ -518,7 +521,7 @@ const make = Effect.gen(function* () { const identity = Option.getOrElse(projectRoot, () => root); return yield* submodulesOf([ { path: root, identity }, - ...folders.flatMap((folder) => + ...input.folders.flatMap((folder) => folder.isGitRepository ? [{ path: folder.path, identity: folder.repositoryPath ?? folder.path }] : [], diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 30f334953332d..10bb9cfbd835c 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -166,6 +166,7 @@ import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as ServerConfigModule from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as ServerSettings from "./serverSettings.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; @@ -908,6 +909,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(TaskFolders.TaskFolders)({}), Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}), Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}), + FeatureFlags.layerTest(), ); const layerConfigSources = Layer.mergeAll( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 25d64eb1fc177..d620055a1abcc 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,6 +1,7 @@ import { GitCommandError, OrchestrationDispatchCommandError } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. import * as NodeCrypto from "node:crypto"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; @@ -223,6 +224,7 @@ import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; +import { assertCheckoutIdle } from "./git/sharedCheckoutGuard.ts"; import { refreshPushedPullRequests } from "./git/refreshPushedPullRequests.ts"; import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts"; import * as ReviewService from "./review/ReviewService.ts"; @@ -1534,6 +1536,7 @@ export const layerWsRpc = ( const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery; const keybindings = yield* Keybindings.Keybindings; + const featureFlags = yield* FeatureFlags.FeatureFlags; const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService; const externalLauncher = yield* ExternalLauncher.ExternalLauncher; const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets; @@ -1922,6 +1925,10 @@ export const layerWsRpc = ( secretProviderSettings: true, secretReferences: true, secretRequestReferences: true, + featureFlags: { + secretProviders: featureFlags.secretProviders, + tanstackSource: featureFlags.tanstackSource, + }, ...Option.match(scratchWorkspaceRoot, { onNone: () => ({}), onSome: (root) => ({ scratchWorkspaceRoot: root }), @@ -3261,9 +3268,13 @@ export const layerWsRpc = ( ), [WS_METHODS.gitResolvePullRequest]: (input) => gitWorkflow.resolvePullRequest(input), [WS_METHODS.gitPreparePullRequestThread]: (input) => - gitWorkflow - .preparePullRequestThread(input) - .pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + (input.mode === "local" + ? assertCheckoutIdle("GitWorkflowService.preparePullRequestThread", input.cwd) + : Effect.void + ).pipe( + Effect.andThen(gitWorkflow.preparePullRequestThread(input)), + Effect.tap(() => refreshGitStatus(input.cwd)), + ), [WS_METHODS.vcsListRefs]: (input) => gitWorkflow.listRefs(input), [WS_METHODS.vcsCreateWorktree]: (input) => // A project that tracks repositories gets a task folder, as its new worktree threads do. @@ -3308,19 +3319,22 @@ export const layerWsRpc = ( ), ), [WS_METHODS.vcsCreateRef]: (input) => - gitWorkflow - .createRef(input) - .pipe( - Effect.tap(() => - input.switchRef - ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) - : refreshGitStatus(input.cwd), - ), + (input.switchRef + ? assertCheckoutIdle("GitWorkflowService.createRef", input.cwd) + : Effect.void + ).pipe( + Effect.andThen(gitWorkflow.createRef(input)), + Effect.tap(() => + input.switchRef + ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) + : refreshGitStatus(input.cwd), ), + ), [WS_METHODS.vcsSwitchRef]: (input) => - gitWorkflow - .switchRef(input) - .pipe(Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd))), + assertCheckoutIdle("GitWorkflowService.switchRef", input.cwd).pipe( + Effect.andThen(gitWorkflow.switchRef(input)), + Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd)), + ), [WS_METHODS.vcsInit]: (input) => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), diff --git a/apps/web/deps/README.md b/apps/web/deps/README.md new file mode 100644 index 0000000000000..26750d308c195 --- /dev/null +++ b/apps/web/deps/README.md @@ -0,0 +1,15 @@ +The Words tarball comes from the [`fork/t3-words` branch](https://github.com/pingdotgg/pierre/tree/fork/t3-words) of our fork of [pierrecomputer/pierre](https://github.com/pierrecomputer/pierre). Its `t3-fork.json` records the source commit and the upstream base. The fork adds opt-in options, all off by default so default output stays byte-identical to upstream: + +- `singleTilde: false`: only `~~` strikes. +- `windowsPaths`: backslashes in Windows drive paths stay. +- `codeMeta`: code fence info after the language becomes `data-meta`. +- `sourcePositions`: `data-sourcepos` byte ranges on list items, links, images, code blocks, math and directives. +- `directives`: the named remark-directive text and leaf directives. +- `escapeHtml`: raw HTML renders as escaped text. +- `leadingWhitespace`: spaces typed at the start of paragraph lines show, in `data-leading-whitespace` spans. +- `texDelimiters`: with `math`, `\(…\)` and `\[…\]` are math, as T3's llm-math reads them. +- `autolinkBoundaries`: end ASCII bare URLs before CJK/Arabic punctuation and keep trailing `_`/`~` when not closing emphasis. + +To replace it, commit the change on `fork/t3-words`, bump `packages/words/package.json` to the next `0.2.2-t3.N` and update `t3-fork.json`'s `source`, then run `moon run words:build` (or `node scripts/build.ts && tsdown`) and `npm pack` in `packages/words`. Name the archive with the first eight characters of the source commit, such as `pierre-words-0.2.2-t3.4-7c04b7f1.tgz`, update the path in `apps/web/package.json`, and run `vp i`. + +Change it through the fork, never with a pnpm patch: the next tarball would drop the patch without a trace. diff --git a/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz b/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz new file mode 100644 index 0000000000000..b6716f0395062 Binary files /dev/null and b/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz differ diff --git a/apps/web/package.json b/apps/web/package.json index 9e6f0f475b3d0..a60eb801260cf 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,6 +34,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:*", @@ -51,6 +52,7 @@ "@tiptap/extension-horizontal-rule": "^3.31.3", "@tiptap/extension-italic": "^3.31.3", "@tiptap/extension-list": "^3.31.3", + "@tiptap/extension-paragraph": "^3.31.3", "@tiptap/extension-strike": "^3.31.3", "@tiptap/extension-task-item": "^3.31.3", "@tiptap/extension-task-list": "^3.31.3", @@ -73,24 +75,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": { @@ -102,7 +96,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", @@ -112,7 +105,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", diff --git a/apps/web/src/components/BackgroundThreadAnnouncer.tsx b/apps/web/src/components/BackgroundThreadAnnouncer.tsx index 3176c8132eed9..649898cf2e5a5 100644 --- a/apps/web/src/components/BackgroundThreadAnnouncer.tsx +++ b/apps/web/src/components/BackgroundThreadAnnouncer.tsx @@ -14,6 +14,7 @@ import { type BackgroundThreadSnapshot, nextBackgroundThreadAnnouncement, resolveBackgroundThreadRequest, + resolveBackgroundThreadRunStatus, } from "./backgroundThreadAnnouncement"; const backgroundThreadLiveRegion = createLiveRegion(); @@ -51,7 +52,7 @@ export function startBackgroundThreadAnnouncements( title: thread.title, ...resolveBackgroundThreadRequest(thread), runId: thread.latestRun?.runId ?? null, - runStatus: thread.latestRun?.status ?? null, + runStatus: resolveBackgroundThreadRunStatus(thread), activeRunId: thread.runtime?.activeRunId ?? null, snoozed: effectiveSnoozed(thread, { now }), }); diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 0586a724b0c56..faca71b4a101f 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -2,7 +2,6 @@ import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/asset import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { type ReactElement } from "react"; -import remarkGfm from "remark-gfm"; import { describe, expect, it, vi } from "vite-plus/test"; import { commands, page, userEvent } from "vite-plus/test/browser"; @@ -15,11 +14,8 @@ import { selectActiveRightPanelSurface, useRightPanelStore, } from "../rightPanelStore"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import type { MarkdownExtensions } from "../markdown/wordsHast"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { HostImageUrlContext } from "./chat/hostImageUrl"; import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting"; @@ -28,14 +24,14 @@ const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ filesystemMetadata: vi.fn(), })); const parsedSources = vi.hoisted(() => [] as string[]); -vi.mock(import("mdast-util-from-markdown"), async (original) => { +vi.mock(import("../markdown/wordsHast"), async (original) => { const actual = await original(); return { ...actual, - fromMarkdown: ((source: string, ...rest: never[]) => { - parsedSources.push(String(source)); - return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest); - }) as typeof actual.fromMarkdown, + wordsHast: (source, options) => { + parsedSources.push(source); + return actual.wordsHast(source, options); + }, }; }); @@ -188,7 +184,7 @@ function buttonsLabelled(container: HTMLElement, label: string) { ); } -const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers]; +const USER_MESSAGE = { userMessage: true }; it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => { setup(); @@ -201,7 +197,7 @@ it("keeps decimal markers in nested user lists while documents keep their counte cwd={undefined} text={text} className="user-message-markdown" - extraRemarkPlugins={SOURCE_NUMBER_PLUGINS} + extensions={USER_MESSAGE} />
@@ -312,36 +308,24 @@ it("reuses the parse of a streaming reply's finished blocks when it remounts", a expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1); }); -it("reuses the parse of a remounted message that has stable extra plugins", async () => { +it("reuses the parse of a remounted message that has stable extensions", async () => { setup(); - const parsed = vi.fn(); - const countingPlugins = [() => () => void parsed()]; - const message = ( - - ); + const extensions = { userMessage: true }; + const message = ; { await using first = await render( - , + , ); await first.rerender(message); } await using screen = await render(message); await expect.element(screen.getByText("Cached text")).toBeVisible(); - expect(parsed).toHaveBeenCalledTimes(1); - const changed = vi.fn(); + const parses = () => parsedSources.filter((source) => source === "Cached text").length; + expect(parses()).toBe(1); await screen.rerender( - () => void changed()]} - />, + , ); - expect(changed).toHaveBeenCalledTimes(1); + expect(parses()).toBe(2); }); it("highlights a code block's own source when an earlier block of the same length was cached", async () => { @@ -399,6 +383,45 @@ describe("ChatMarkdown external link labels", () => { }); }); +describe("ChatMarkdown link tooltips", () => { + it("shows each link's address on one shared tooltip as the pointer moves between links", async () => { + setup(); + await using screen = await render( + , + ); + await userEvent.hover(screen.getByRole("link", { name: /First/ })); + await expect.element(page.getByText("https://example.com/a")).toBeVisible(); + await userEvent.hover(screen.getByRole("link", { name: /Second/ })); + await expect.element(page.getByText("https://example.org/b")).toBeVisible(); + expect(document.querySelectorAll('[data-slot="tooltip-popup"]')).toHaveLength(1); + }); +}); + +describe("ChatMarkdown details", () => { + it("opens collapsed details by click, and by keyboard without losing focus", async () => { + setup(); + await using screen = await render( + First\n\nHidden one\n\n\n\n
Second\n\nHidden two\n\n
" + } + />, + ); + await userEvent.click(screen.getByRole("button", { name: "First" })); + await expect.element(screen.getByText("Hidden one")).toBeVisible(); + await userEvent.tab(); + const second = screen.getByRole("button", { name: "Second" }); + await expect.element(second).toHaveFocus(); + await userEvent.keyboard("{Enter}"); + await expect.element(screen.getByText("Hidden two")).toBeVisible(); + await expect.element(screen.getByRole("button", { name: "Second" })).toHaveFocus(); + }); +}); + describe("ChatMarkdown streaming", () => { it("runs only a complete single-line shell block after a click", async () => { setup(); @@ -802,12 +825,12 @@ describe("ChatMarkdown copy", () => { "copies and selects user lines the same whether their typed indentation shows: $text", async (copy) => { setup(); - const copied = async (extraRemarkPlugins: typeof CHAT_USER_MARKDOWN_REMARK_PLUGINS) => { + const copied = async (extensions: MarkdownExtensions) => { await using screen = await renderText(copy.text, { className: "user-message-markdown", lineBreaks: true, parseRawHtml: false, - extraRemarkPlugins, + extensions, }); const range = document.createRange(); range.selectNodeContents(screen.container); @@ -824,9 +847,9 @@ describe("ChatMarkdown copy", () => { // A drag or anything else that reads the selection gets its text, not the copy payload. return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() }; }; - const shown = await copied(CHAT_USER_MARKDOWN_REMARK_PLUGINS); + const shown = await copied({ userMessage: true, leadingWhitespace: true }); // The user pipeline as it was before typed indentation was shown. - expect(shown).toEqual(await copied([[remarkGfm, { singleTilde: false }]])); + expect(shown).toEqual(await copied({ userMessage: true })); }, ); @@ -885,7 +908,7 @@ describe("ChatMarkdown copy", () => { setup(); await using screen = await renderText( source, - userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {}, + userMessage ? { extensions: USER_MESSAGE } : {}, ); const itemText = (shown: string) => [...screen.container.querySelectorAll("li")] diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 8c0d14520871d..979d1858cafc1 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -13,7 +13,7 @@ import { extractMarkdownLinkHrefs, inlineCodeFilePathCandidate, } from "@t3tools/shared/markdownLinks"; -import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList"; +import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskEdits"; import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path"; import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; import { @@ -21,14 +21,7 @@ import { AuthOrchestrationOperateScope, SOURCE_CONTROL_MEDIA_ASSET, } from "@t3tools/contracts"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - CHAT_MARKDOWN_REHYPE_PLUGINS, - chatMarkdownImageSource, - decodeMarkdownLinkEscapes, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; +import { chatMarkdownImageSource } from "@t3tools/shared/markdownHast"; import { useAtomValue } from "@effect/atom-react"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, @@ -94,27 +87,17 @@ import React, { useState, type ReactNode, } from "react"; -import type { - Components, - ExtraProps as ReactMarkdownExtraProps, - Options as ReactMarkdownOptions, -} from "react-markdown"; -import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; -import type { Pluggable, PluggableList } from "unified"; -import { defaultUrlTransform } from "react-markdown"; import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; import { AssistantCitationEmbed } from "./chat/AssistantCitationChip"; import { MarkdownThreadLink } from "./chat/MarkdownThreadLink"; -import { mathKind } from "@t3tools/shared/markdownMath"; -import remarkMath from "remark-math"; +import { artifactTemplateFromHastProperties } from "@t3tools/shared/codexArtifactTemplates"; import { - artifactTemplateFromHastProperties, + decodeMarkdownLinkEscapes, renderCodexInlineDirectivesAsMarkdown, -} from "@t3tools/shared/codexMarkdownDirectives"; +} from "../markdown/markdownText"; import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText"; -import { MarkdownMath } from "./chat/MarkdownMath"; import { resolveMarkdownMediaPreview, type ExpandedImagePreview, @@ -131,7 +114,7 @@ import { resolveExternalWebLinkHost, showExternalLinkContextMenu, } from "./chat/externalLinkContextMenu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./ui/shared-tooltip"; import { Button } from "./ui/button"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { recordVisitForThread } from "../browserHistoryStore"; @@ -214,6 +197,15 @@ import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; import { IssueLinkPreview, IssueLinkPreviewFallback } from "./issue/IssueLinkPreview"; import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock"; import { createMarkdownRenderer } from "./chat/markdownRenderer"; +import type { MarkdownExtensions, WordsHastOptions } from "../markdown/wordsHast"; +import { + type MarkdownIslandOptions, + renderHastWithIslands, + withProperties, +} from "./chat/markdownIslands"; +import type { Element as HastElement } from "hast"; +import { matchInlineSkills } from "@t3tools/shared/inlineSkills"; +import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions"; import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks"; import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock"; import { MarkdownTable } from "./chat/MarkdownTable"; @@ -230,9 +222,7 @@ import { import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink"; import { MarkdownFileLink } from "./chat/MarkdownFileLink"; import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic"; -import { rehypeChipPunctuation } from "./chat/markdownChipPunctuation"; -import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments"; -import { rehypeTextDirection } from "./chat/markdownTextDirection"; +import { handleMarkdownFragmentClick } from "./chat/markdownFragments"; import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic"; import { extractCodeBlock, @@ -268,8 +258,8 @@ interface ChatMarkdownProps { imageBaseDir?: string | undefined; workspaceMutationId?: string | null | undefined; onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; - /** Keep one list per configuration (a module constant): it keys the shared parse cache. */ - extraRemarkPlugins?: NonNullable; + /** Keep one object per configuration (a module constant): it keys the shared parse cache. */ + extensions?: MarkdownExtensions | undefined; renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined; /** Loads media a source control host keeps behind a credential through the server, which holds `cwd`'s; without it a private repository's uploads load unauthenticated and 404. */ @@ -289,7 +279,7 @@ export interface ChatMarkdownContextReference { } const EMPTY_MARKDOWN_SKILLS: ReadonlyArray = []; -const EMPTY_REMARK_PLUGINS: NonNullable = []; +const NO_EXTENSIONS: MarkdownExtensions = {}; const ARTIFACT_TEMPLATE_ICON_BY_KIND = { document: FileTextIcon, @@ -423,19 +413,29 @@ function normalizeMarkdownLinkHrefKey(href: string): string { : rewrittenHref; } -// Heading ids are added after sanitizing, which would prefix them a second time. -const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [ - ...CHAT_MARKDOWN_REHYPE_PLUGINS, - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +/** A component per element, with the hast node it renders, as react-markdown typed them. */ +type MarkdownComponents = { + [Tag in keyof React.JSX.IntrinsicElements]?: React.ComponentType< + React.JSX.IntrinsicElements[Tag] & { node?: HastElement | undefined } + >; +}; -const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [ - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +// react-markdown's defaultUrlTransform: relative URLs, and absolute ones with a safe protocol. +const SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp)$/i; +function safeUrl(value: string): string { + const colon = value.indexOf(":"); + const before = (character: string) => { + const at = value.indexOf(character); + return at !== -1 && colon > at; + }; + return colon === -1 || + before("/") || + before("?") || + before("#") || + SAFE_PROTOCOL.test(value.slice(0, colon)) + ? value + : ""; +} function markdownUrlTransform(href: string) { if (parseAssistantCitationHref(href)) return href; @@ -443,7 +443,7 @@ function markdownUrlTransform(href: string) { if (parseThreadLinkHref(href)) return href; if (isWindowsDrivePathHref(href)) return href; if (isLocalEditorFileHref(href)) return href; - return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); + return rewriteMarkdownFileUriHref(href) ?? safeUrl(href); } const NO_MARKDOWN_EDITORS: ReadonlyArray = []; @@ -486,11 +486,16 @@ const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId }).pipe(Atom.withLabel("markdown-server-config-fields")), ); -function fileLinkSourcesKey( +interface BlockFileLinkSources { + readonly hrefs: ReadonlyArray; + readonly spans: ReadonlyArray; +} + +function blockFileLinkSources( text: string, cwd: string | undefined, imageBaseDir: string | undefined, -): string { +): BlockFileLinkSources { const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) .filter((href) => !parseComposerContextHref(href)) .map(decodeMarkdownLinkEscapes) @@ -499,7 +504,47 @@ function fileLinkSourcesKey( const spans = extractInlineCodeSpans(text).filter((span) => resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), ); - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + return { hrefs, spans }; +} + +// Links and code spans never cross blocks: a streamed reply rescans only its open last block. +const MAX_CACHED_BLOCK_CHARS = 2_000_000; +const finishedBlockFileLinkSources = new Map(); +let cachedBlockChars = 0; + +function fileLinkSourcesKey( + text: string, + cwd: string | undefined, + imageBaseDir: string | undefined, + streamingBlocks: ReadonlyArray | null, +): string { + if (!streamingBlocks) { + const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir); + return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + } + const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000`; + const hrefs = new Set(); + const spans = new Set(); + const last = streamingBlocks.length - 1; + for (const [index, block] of streamingBlocks.entries()) { + // The last block still grows; caching each of its prefixes would only fill the cache. + const key = config + block; + let sources = index === last ? undefined : finishedBlockFileLinkSources.get(key); + if (!sources) { + sources = blockFileLinkSources(block, cwd, imageBaseDir); + if (index !== last) { + if (cachedBlockChars + key.length > MAX_CACHED_BLOCK_CHARS) { + finishedBlockFileLinkSources.clear(); + cachedBlockChars = 0; + } + finishedBlockFileLinkSources.set(key, sources); + cachedBlockChars += key.length; + } + } + for (const href of sources.hrefs) hrefs.add(href); + for (const span of sources.spans) spans.add(span); + } + return JSON.stringify([[...hrefs], [...spans]]); } function resolveFileLinkSources( @@ -525,27 +570,30 @@ function resolveFileLinkSources( return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; } -function useChatMarkdownState({ - text, - inline = false, - cwd, - agentDirectories, - threadRef, - pullRequestPanelRef, - environmentId: explicitEnvironmentId, - onTaskListChange, - isStreaming = false, - skills = EMPTY_MARKDOWN_SKILLS, - onUseArtifactTemplate, - onRunShellCommand, - imageBaseDir, - workspaceMutationId, - onImageExpand, - renderContextReference, - headingLevelOffset = 0, - sourceControlMedia = false, - sourceControlMediaRepository, -}: ChatMarkdownProps) { +function useChatMarkdownState( + { + text, + inline = false, + cwd, + agentDirectories, + threadRef, + pullRequestPanelRef, + environmentId: explicitEnvironmentId, + onTaskListChange, + isStreaming = false, + skills = EMPTY_MARKDOWN_SKILLS, + onUseArtifactTemplate, + onRunShellCommand, + imageBaseDir, + workspaceMutationId, + onImageExpand, + renderContextReference, + headingLevelOffset = 0, + sourceControlMedia = false, + sourceControlMediaRepository, + }: ChatMarkdownProps, + streamingBlocks: ReadonlyArray | null, +) { const gt = useGT(); const messages = useMessages(); const resolvedTheme = useRenderedAppearance(); @@ -743,7 +791,7 @@ function useChatMarkdownState({ // Keyed by the file links found, not the text, so streamed text that adds none keeps the // renderer context, and every block reading it, unchanged. // A template literal marks the key as a string, so the compiler memoizes the maps on its value. - const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir)}`; + const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); const resolveThreadPullRequest = ( @@ -1087,7 +1135,7 @@ function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) { return function MarkdownHeading({ node: _node, ...props - }: ComponentProps & ReactMarkdownExtraProps) { + }: ComponentProps & { node?: HastElement | undefined }) { const { headingLevelOffset } = use(ChatMarkdownRendererContext); return ( ; } - return ( - - - {href} - - ); + return ; } const label = nodeToPlainText(children); @@ -1533,18 +1576,9 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, code: function MarkdownCode({ node, children, className, ...props }) { - const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip, mathEnabled, inline } = - use(ChatMarkdownRendererContext); - const math = mathEnabled ? mathKind(className) : null; - if (math) { - return ( - - ); - } + const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use( + ChatMarkdownRendererContext, + ); if (node?.properties?.dataInlineCode != null) { const codeText = nodeToPlainText(children); const fileLinkMeta = @@ -1769,15 +1803,9 @@ const CHAT_MARKDOWN_COMPONENTS = { }, pre: function MarkdownPre({ node, children, ...props }) { const gt = useGT(); - const { - resolvedTheme, - diffThemeName, - expandMedia, - isStreaming, - onRunShellCommand, - inline, - mathEnabled, - } = use(ChatMarkdownRendererContext); + const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use( + ChatMarkdownRendererContext, + ); const text = use(ChatMarkdownTextContext); const codeBlock = extractCodeBlock(children); if (!codeBlock) { @@ -1785,15 +1813,6 @@ const CHAT_MARKDOWN_COMPONENTS = { } const language = extractFenceLanguage(codeBlock.className); - if ( - mathEnabled && - language === "math" && - (!isStreaming || - mathKind(codeBlock.className) === "display" || - isClosedCodeFence(node, text, codeBlock.code)) - ) { - return ; - } const fenceTitle = extractFenceTitle(extractPreCodeMeta(node)); const highlightedCode = ( ); }, -} satisfies Components; - -const REMARK_MATH: Pluggable = [remarkMath, { singleDollarTextMath: true }]; -// Shared lists, so every message with the same options shares a processor and its cache. -const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: CHAT_MARKDOWN_REMARK_PLUGINS, - breaks: CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - math: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS], - mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS], -} satisfies Record; - -const combinedPlugins = new WeakMap>(); +} satisfies MarkdownComponents; -// One combined list per pair, so a stable extra list shares a renderer and its parse cache. -const INSIGHT_REMARK_PLUGINS: PluggableList = [remarkAssistantInsights]; +const markdownOptions = new WeakMap>(); -function withExtraPlugins(shared: PluggableList, extra: PluggableList): PluggableList { - if (extra.length === 0) return shared; - let byShared = combinedPlugins.get(extra); - if (!byShared) combinedPlugins.set(extra, (byShared = new WeakMap())); - let combined = byShared.get(shared); - if (!combined) byShared.set(shared, (combined = [...shared, ...extra])); - return combined; +/** One options object per configuration, so equal messages share a renderer and its cache. */ +function wordsOptions( + extensions: MarkdownExtensions, + flags: Omit, +): WordsHastOptions { + let byFlags = markdownOptions.get(extensions); + if (!byFlags) markdownOptions.set(extensions, (byFlags = new Map())); + const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}`; + let options = byFlags.get(key); + if (!options) byFlags.set(key, (options = { ...flags, extensions })); + return options; } const markdownRenderers = new WeakMap< - PluggableList, - WeakMap> + WordsHastOptions, + ReturnType >(); -function markdownRenderer(remarkPlugins: PluggableList, rehypePlugins: PluggableList) { - let byRehype = markdownRenderers.get(remarkPlugins); - if (!byRehype) markdownRenderers.set(remarkPlugins, (byRehype = new WeakMap())); - let renderer = byRehype.get(rehypePlugins); +function markdownRenderer(markdown: WordsHastOptions) { + let renderer = markdownRenderers.get(markdown); if (!renderer) { renderer = createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components: CHAT_MARKDOWN_COMPONENTS, urlTransform: markdownUrlTransform, }); - byRehype.set(rehypePlugins, renderer); + markdownRenderers.set(markdown, renderer); } return renderer; } +type ChatMarkdownComponentState = ReturnType["componentState"]; + +function hastClassName(node: HastElement): string | undefined { + const { className } = node.properties; + return Array.isArray(className) ? className.join(" ") : (className as string | undefined); +} + +// Paragraphs and list items turn skill and model mentions in their text into chips, except in +// code and links, as SkillInlineText does. +function hastTextHasChip(node: HastElement, skills: ReadonlyArray): boolean { + return node.children.some((child) => + child.type === "text" + ? (skills.length > 0 && !matchInlineSkills(child.value, skills).next().done) || + collectComposerModelMentions(child.value).length > 0 + : child.type === "element" && + child.tagName !== "code" && + child.tagName !== "a" && + hastTextHasChip(child, skills), + ); +} + +const HEADING_LEVELS: Record = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 }; + +const markdownIslandOptionsByState = new WeakMap< + ChatMarkdownComponentState, + MarkdownIslandOptions +>(); + +/** Which elements need CHAT_MARKDOWN_COMPONENTS, and what the others' components add. */ +function markdownIslandOptions(state: ChatMarkdownComponentState): MarkdownIslandOptions { + const cached = markdownIslandOptionsByState.get(state); + if (cached) return cached; + const { + cwd, + headingLevelOffset, + imageBaseDir, + inlineCodeFileLinkMetaByText, + onTaskListChange, + skills, + } = state; + const options: MarkdownIslandOptions = { + components: CHAT_MARKDOWN_COMPONENTS, + variant: String(headingLevelOffset), + isIsland: (node) => { + switch (node.tagName) { + case "a": + case "img": + case "pre": + case "details": + case "table": + return true; + case "blockquote": + return GITHUB_ALERT_PRESENTATIONS[String(node.properties.dataAlert ?? "")] !== undefined; + case "div": + return artifactTemplateFromHastProperties(node.properties) !== null; + case "input": + return node.properties.type === "checkbox" && onTaskListChange !== undefined; + case "code": { + if (node.properties.dataInlineCode == null) return false; + const codeText = hastPlainTextDeep(node); + return ( + (inlineCodeFileLinkMetaByText.get(codeText.trim()) ?? + resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd)) != null + ); + } + case "p": + case "li": + return hastTextHasChip(node, skills); + default: + return false; + } + }, + staticElement: (node) => { + const level = HEADING_LEVELS[node.tagName]; + if (level !== undefined) { + return headingLevelOffset > 0 + ? withProperties(node, { ariaLevel: Math.min(level + headingLevelOffset, 6) }) + : node; + } + switch (node.tagName) { + case "ol": { + const itemValues = node.children.flatMap((child) => + child.type === "element" && child.tagName === "li" ? [child.properties.value] : [], + ); + const gutter = orderedListGutterStyle(itemValues, node.properties.start); + if (!gutter) return node; + const authored = typeof node.properties.style === "string" ? node.properties.style : ""; + return withProperties(node, { + style: `${authored}${authored ? ";" : ""}--list-gutter:${gutter["--list-gutter"]}`, + }); + } + case "li": + return hastClassName(node)?.includes("task-list-item") + ? withProperties(node, { dataListItemOffset: node.position?.start.offset }) + : node; + case "input": + return node.properties.type === "checkbox" + ? withProperties(node, { readOnly: true }) + : node; + default: + return node; + } + }, + }; + markdownIslandOptionsByState.set(state, options); + return options; +} + const MarkdownSource = memo(function MarkdownSource({ text, - remarkPlugins, - rehypePlugins, - shared, + markdown, cache, }: { text: string; - remarkPlugins: PluggableList; - rehypePlugins: PluggableList; - /** The plugins are one of the shared sets. */ - shared: boolean; + markdown: WordsHastOptions; /** The text will not change again; streamed text would only fill the cache with prefixes. */ cache: boolean; }) { - // Per-instance plugins, such as the incremental parser, set up their state on every render. - const render = shared - ? markdownRenderer(remarkPlugins, rehypePlugins) - : createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, - components: CHAT_MARKDOWN_COMPONENTS, - urlTransform: markdownUrlTransform, - }); - const element = render(text); + const render = markdownRenderer(markdown); + const entry = render.parse(text); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Caching during render would make React Compiler rebuild the element when `cache` flips. useEffect(() => { - if (shared && cache) render.remember(text, element); - }, [render, text, element, shared, cache]); - return {element}; + if (cache) render.remember(text, entry); + }, [render, text, entry, cache]); + const islandState = use(ChatMarkdownRendererContext); + return ( + + {islandState + ? renderHastWithIslands(entry.tree, markdownIslandOptions(islandState)) + : render.element(entry)} + + ); }); function ChatMarkdown({ @@ -1935,51 +2045,28 @@ function ChatMarkdown({ inline = false, lineBreaks = false, parseRawHtml = true, - extraRemarkPlugins = EMPTY_REMARK_PLUGINS, + extensions = NO_EXTENSIONS, renderInsights = false, ...props }: ChatMarkdownProps) { - const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = - useChatMarkdownState({ text, inline, ...props }); - const hasInsights = renderInsights && text.includes("★ Insight"); - // Streaming re-renders only the last block; offsets for task edits need the whole text. + // Streaming re-renders only the last block; offsets for task edits, and extensions that read + // the whole message, need the whole text. const streamingBlocks = - props.isStreaming === true && - !inline && - extraRemarkPlugins.length === 0 && - !props.onTaskListChange - ? splitMarkdownBlocks(text) + props.isStreaming === true && !inline && extensions === NO_EXTENSIONS && !props.onTaskListChange + ? (splitMarkdownBlocks(text) ?? [text]) : null; - const incrementalParsing = - props.isStreaming === true && - !hasInsights && - streamingBlocks === null && - extraRemarkPlugins.length === 0 && - /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text); + const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = + useChatMarkdownState({ text, inline, ...props }, streamingBlocks); const Root = inline ? "span" : "div"; const bindMarkdownRef = (node: HTMLElement | null) => { markdownRef.current = node; }; - const sharedRemarkPlugins = - CHAT_MARKDOWN_REMARK_PLUGIN_SETS[ - componentState.mathEnabled - ? lineBreaks - ? "mathBreaks" - : "math" - : lineBreaks - ? "breaks" - : "plain" - ]; - // The incremental parser keeps per-instance state, so its output is not shared. - const uncachedPlugins = incrementalParsing; - const remarkPlugins = incrementalParsing - ? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()] - : withExtraPlugins( - hasInsights - ? withExtraPlugins(INSIGHT_REMARK_PLUGINS, sharedRemarkPlugins) - : sharedRemarkPlugins, - extraRemarkPlugins, - ); + const markdown = wordsOptions(extensions, { + math: componentState.mathEnabled, + breaks: lineBreaks, + escapeHtml: !parseRawHtml, + insights: renderInsights && text.includes("★ Insight"), + }); const blocks = streamingBlocks ?? [text]; return ( @@ -1995,22 +2082,18 @@ function ChatMarkdown({ onCopy={handleCopy} > - {blocks.map((source, index) => ( - - ))} + + {blocks.map((source, index) => ( + + ))} + {localMediaPreview ? ( diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index ae6628ba6733c..cfd06a8864e0d 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -112,6 +112,19 @@ vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (i return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; }); +// Null runs the real compression; a test sets it to hold an image in preparation. +const compression = vi.hoisted(() => ({ gate: null as Promise | null })); +vi.mock(import("~/lib/imageCompression"), async (original) => { + const actual = await original(); + return { + ...actual, + prepareImageForAttachment: async (...args) => { + await compression.gate; + return actual.prepareImageForAttachment(...args); + }, + }; +}); + vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ ...(await original()), trackRpcRequestSent: () => {}, @@ -438,6 +451,96 @@ it("an interrupted image-only first send of a new thread says it may not have be expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); }); +it.each(["new", "existing"] as const)( + "Enter while an image compresses shows a cancellable banner, cancels on edit or Esc, and still sends after leaving a %s thread", + async (kind) => { + const thread = threadWithHistory(`upload-wait-${kind}`, 1); + const other = threadWithHistory(`upload-wait-other-${kind}`, 1); + using _environment = installFakeEnvironment(kind === "existing" ? [thread, other] : [other], { + acceptCommands: true, + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const draftId = DraftId.make(`draft-upload-wait-${kind}`); + if (kind === "new") { + useComposerDraftStore + .getState() + .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { + threadId: thread.id, + }); + } + using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + const router = getRouter( + createMemoryHistory({ + initialEntries: [kind === "new" ? `/draft/${draftId}` : `/${ENVIRONMENT_ID}/${thread.id}`], + }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + const compressed = Promise.withResolvers(); + compression.gate = compressed.promise; + using _compression = { [Symbol.dispose]: () => (compression.gate = null) }; + using _uploads = acceptAttachmentUploads(); + const editor = page.getByTestId("composer-editor"); + await expect.element(editor).toBeVisible(); + await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible(); + + await userEvent.click(editor); + const clipboardData = new DataTransfer(); + clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" })); + editor + .element() + .dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); + + // Enter arms the send and shows the banner plus a disabled spinner button. + await userEvent.keyboard("check image{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + const waitingButton = page.getByRole("button", { name: "Sending when ready", exact: true }); + await expect.element(waitingButton).toBeDisabled(); + await expect.element(waitingButton).toHaveAttribute("aria-busy", "true"); + + // Typing disarms the queued send and keeps the edit. + await userEvent.keyboard(" now"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + await expect.element(editor).toHaveTextContent("check image now"); + + // Enter arms again; Esc cancels cleanly. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await userEvent.keyboard("{Escape}"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + + // Enter arms again; leaving the thread still sends once the image is ready. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` }); + await expect.element(page.getByText(`Answer 0 for upload-wait-other-${kind}.`)).toBeVisible(); + + compressed.resolve(); + await vi.waitFor(() => { + if (kind === "new") { + expect(launch.calls).toHaveLength(1); + } else { + expect(dispatchedCommands()).toContainEqual( + expect.objectContaining({ + type: "message.dispatch", + threadId: thread.id, + attachments: [expect.objectContaining({ type: "image", id: "upload-1" })], + }), + ); + } + }); + launch.release(); + }, +); + it("opens the thread actions menu for an older settled thread the shell leaves out", async () => { const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const }; using _environment = installFakeEnvironment([thread]); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index f393e5ccdb07c..7f8504534adcd 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -60,7 +60,9 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; import { freshSessionBannerItem } from "./chat/ComposerFreshSession"; +import { heldComposerSendBannerItem } from "./chat/ComposerHeldSendBanner"; import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms"; +import { cancelHeldComposerSend, useComposerSendHeld } from "./chat/preparingComposerImages"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; import { useChatShortcuts } from "./chat/useChatShortcuts"; @@ -254,6 +256,7 @@ import { type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, + composerTargetKey, useComposerDraftStore, DraftId, } from "../composerDraftStore"; @@ -2665,7 +2668,16 @@ export default function ChatView(props: ChatViewProps) { // While a question or approval owns the composer, its text answers that, not the agent. const freshSessionCommandAvailable = freshSessionAvailable && activePendingApproval === null && pendingUserInputs.length === 0; - const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory); + const composerDraftTargetKey = composerTargetKey(composerDraftTarget); + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSendStable = useStableCallback(() => { + cancelHeldComposerSend(composerDraftTargetKey); + focusComposerStable(); + }); + const toggleKeepFullHistory = () => { + cancelHeldComposerSend(composerDraftTargetKey); + setKeepFullHistory(routeThreadKey, !keepFullHistory); + }; const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory); const armFreshSessionStable = useStableCallback(() => armFreshSession(routeThreadKey)); const handleRestoreThreadBranch = () => { @@ -2776,6 +2788,14 @@ export default function ChatView(props: ChatViewProps) { freshSessionPending && activePendingApproval === null ? [freshSessionBannerItem(() => disarmFreshSession(routeThreadKey), messages)] : []; + const heldSendItems = composerSendHeld + ? [ + heldComposerSendBannerItem( + { draftTarget: composerDraftTarget, onCancel: cancelHeldSendStable }, + messages, + ), + ] + : []; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ ...feedbackBannerItems, @@ -2785,6 +2805,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, ]; } @@ -2796,6 +2817,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, branchMismatchBannerItem( { diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index ca1db10dbdc10..d69c06751b527 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -677,6 +677,18 @@ it("reopens a long draft scrolled to its caret without taking focus", async () = expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1); }); +it("does not outline the line under a click made with the node-select modifier held", async () => { + await using screen = await mountEditor("ship it"); + const { editor } = screen; + const paragraph = editor.view.dom.querySelector("p")!; + const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control"; + await userEvent.keyboard(`{${mod}>}`); + await userEvent.click(paragraph); + await userEvent.keyboard(`{/${mod}}`); + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); + expect(getComputedStyle(paragraph).outlineStyle).toBe("none"); +}); + describe("Markdown markers around styled text", () => { it.each([ { keys: "{Backspace}", expected: "**** after" }, diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 9b758ee8b6777..c3fb7fad73ff8 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -14,6 +14,7 @@ import { type TiptapEditorHTMLElement, } from "@tiptap/core"; import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react"; +import { Paragraph } from "@tiptap/extension-paragraph"; import StarterKit from "@tiptap/starter-kit"; import { useGT } from "gt-react"; import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands"; @@ -876,7 +877,10 @@ function createComposerExtensions(richText: boolean) { italic: false, bold: false, strike: false, + paragraph: false, }), + // Ctrl/Cmd+click would node-select and outline the whole line (Wispr Flow holds Ctrl to dictate). + Paragraph.extend({ selectable: false }), ComposerUndoGroupingExtension, ComposerTextDirectionExtension, ComposerMentionExtension, @@ -1920,12 +1924,13 @@ function ComposerPromptEditorTiptapInner(
{ if ( event.key === "Control" || @@ -1970,7 +1975,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
diff --git a/apps/web/src/components/backgroundThreadAnnouncement.test.ts b/apps/web/src/components/backgroundThreadAnnouncement.test.ts index b2b6195d8f288..51d3c693f9904 100644 --- a/apps/web/src/components/backgroundThreadAnnouncement.test.ts +++ b/apps/web/src/components/backgroundThreadAnnouncement.test.ts @@ -7,6 +7,7 @@ import { type BackgroundThreadSnapshot, nextBackgroundThreadAnnouncement, resolveBackgroundThreadRequest, + resolveBackgroundThreadRunStatus, } from "./backgroundThreadAnnouncement"; const firstRun = RunId.make("run-1"); @@ -187,3 +188,72 @@ describe("resolveBackgroundThreadRequest", () => { ).toEqual(["Needs approval: Fix login redirect"]); }); }); + +describe("resolveBackgroundThreadRunStatus", () => { + const threadStatus = (overrides?: { + readonly status?: "completed" | "failed" | "interrupted"; + readonly pendingBackgroundTasks?: ReadonlyArray<{ + readonly taskId: string; + readonly kind: "command" | "monitor" | "subagent" | "background_task"; + readonly awaited?: true; + }>; + readonly latestRunBackgroundWake?: boolean; + readonly latestRunStopRequested?: boolean; + }) => { + const pendingBackgroundTasks = overrides?.pendingBackgroundTasks ?? []; + return resolveBackgroundThreadRunStatus({ + latestRun: { status: overrides?.status ?? "completed" }, + pendingBackgroundTasks, + source: { + pendingBackgroundTasks, + latestRunBackgroundWake: overrides?.latestRunBackgroundWake ?? false, + latestRunStopRequested: overrides?.latestRunStopRequested ?? false, + }, + }); + }; + + it("suppresses Done while awaited background work or a monitor wake holds completion, or when stop was requested", () => { + const heldCases = [ + { latestRunStopRequested: true }, + { pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" as const }] }, + { + pendingBackgroundTasks: [ + { taskId: "cmd-1", kind: "command" as const, awaited: true as const }, + ], + }, + { + latestRunBackgroundWake: true, + pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" as const }], + }, + ]; + for (const input of heldCases) { + expect(threadStatus(input)).toBeNull(); + } + }); + + it("keeps Done for unawaited background work and keeps non-completed outcomes", () => { + expect( + threadStatus({ + pendingBackgroundTasks: [{ taskId: "cmd-1", kind: "command" }], + }), + ).toBe("completed"); + expect( + threadStatus({ + latestRunBackgroundWake: false, + pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" }], + }), + ).toBe("completed"); + expect( + threadStatus({ + status: "failed", + pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" }], + }), + ).toBe("failed"); + expect( + threadStatus({ + status: "interrupted", + latestRunStopRequested: true, + }), + ).toBe("interrupted"); + }); +}); diff --git a/apps/web/src/components/backgroundThreadAnnouncement.ts b/apps/web/src/components/backgroundThreadAnnouncement.ts index e1c52adb662ad..48a334543c447 100644 --- a/apps/web/src/components/backgroundThreadAnnouncement.ts +++ b/apps/web/src/components/backgroundThreadAnnouncement.ts @@ -1,4 +1,8 @@ import type { OrchestrationV2RunStatus, RunId } from "@t3tools/contracts"; +import { + backgroundWorkHoldsCompletion, + monitorHoldsWakeCompletion, +} from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { msg } from "gt-react"; @@ -40,6 +44,27 @@ export function resolveBackgroundThreadRequest( return { request: null, requestId: null }; } +/** Suppresses Done announcements for stopped runs, awaited background work, and monitor wakes. */ +export function resolveBackgroundThreadRunStatus(thread: { + readonly latestRun: { readonly status: OrchestrationV2RunStatus } | null; + readonly pendingBackgroundTasks: SidebarThreadSummary["pendingBackgroundTasks"]; + readonly source: Pick< + SidebarThreadSummary["source"], + "latestRunBackgroundWake" | "latestRunStopRequested" | "pendingBackgroundTasks" + >; +}): OrchestrationV2RunStatus | null { + const status = thread.latestRun?.status ?? null; + if ( + status === "completed" && + (thread.source.latestRunStopRequested === true || + backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks) || + monitorHoldsWakeCompletion(thread.source)) + ) { + return null; + } + return status; +} + interface BackgroundThreadMemoryEntry { readonly request: BackgroundThreadSnapshot["request"]; readonly requestId: string | null; diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx index 0772a864c021e..afb51240b625e 100644 --- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx +++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx @@ -143,6 +143,7 @@ export function AssistantSelectionToolbar({ element: viewport, getActionElement: () => toolbarRef.current, restoreAfterScroll: true, + immediateMultiClick: true, onSelection: update, onDismiss: clear, }); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2c3bc34529ffd..6fb651c3471f6 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,6 +133,7 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, + isImageOnlyClipboardHtml, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -251,6 +252,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"; @@ -285,10 +287,13 @@ import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; 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"; @@ -728,8 +733,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); @@ -1266,21 +1281,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; @@ -2195,7 +2217,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 +2303,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 +2493,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 +2537,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptSuggestion: offeredPromptSuggestion, dismissPromptSuggestion, })(key, event, isTaskItem); + }; const { stashQueue, @@ -2614,7 +2646,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 +2744,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; @@ -2918,7 +2952,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (!pastedContext && activeThreadId && files.length > 0 && - shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) + shouldHandleComposerAttachmentPaste({ + files, + plainText, + bypassAutoAttachment, + htmlIsOnlyImage: + plainText.length > 0 && + isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + })) ) { event.preventDefault(); event.stopPropagation(); @@ -3510,6 +3551,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{ + if ( + event.key === "Escape" && + composerSendHeld && + !event.defaultPrevented && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + cancelHeldSend(); + } + }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3644,7 +3696,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) canOperateThread={canOperateThread} canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} - hasSendableContent={composerSendState.hasSendableContent} + hasSendableContent={hasMessageToSend} isEditingQueuedMessage={isEditingQueuedMessage} onInterrupt={handleInterruptPrimaryActionStable} > @@ -3654,6 +3706,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 +3716,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) else submitComposer(); }} > - {showResumeAction ? ( + {composerSendHeld || isSendBusy ? ( +
+ ); + } + return (
- } - className={MARKDOWN_FILE_LINK_CLASS_NAME} - data-markdown-copy={copyMarkdown} - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { - handleOpenInEditor(); - return; - } - if (useBrowserPrimaryAction) { - handleOpenInBrowser(); - return; - } - handleOpenInFilePreview(); - }} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) : ( - } - aria-label={gt("File options for {label}", { label })} - aria-haspopup="menu" - className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} - data-markdown-copy={copyMarkdown} - onClick={handleContextMenu} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) + const tooltipContent = ( + + ); + const sharedTooltip = useSharedTooltip({ + render: () => tooltipContent, + contentKey: `${iconPath}\u0000${targetPath}`, + variant: "code", + }); + const chip = hasPrimaryAction ? ( + } + className={MARKDOWN_FILE_LINK_CLASS_NAME} + data-markdown-copy={copyMarkdown} + onClick={(event) => { + event.preventDefault(); + event.stopPropagation(); + if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { + handleOpenInEditor(); + return; + } + if (useBrowserPrimaryAction) { + handleOpenInBrowser(); + return; } + handleOpenInFilePreview(); + }} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} + /> + + ) : ( + } + aria-label={gt("File options for {label}", { label })} + aria-haspopup="menu" + className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} + data-markdown-copy={copyMarkdown} + onClick={handleContextMenu} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} /> + + ); + if (sharedTooltip) return withSharedTooltip(chip, sharedTooltip); + return ( + + - + {tooltipContent} ); diff --git a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx b/apps/web/src/components/chat/MarkdownMath.browser.test.tsx deleted file mode 100644 index ec5b38541ddc4..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; - -import { render } from "../../../test/render"; -import "../../index.css"; - -import { MarkdownMath } from "./MarkdownMath"; - -it("keeps keyboard scrolling available as a streamed equation outgrows its viewport", async () => { - const equation = (tex: string, width = 180) => ( -
- - - -
- ); - await using screen = await render(equation("x")); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8")); - const scroller = screen.getByLabelText("Scroll display equation"); - await expect.element(scroller).toHaveAttribute("tabindex", "0"); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(scroller).toHaveFocus(); - await userEvent.keyboard("{ArrowRight}"); - await expect.element(scroller).not.toHaveProperty("scrollLeft", 0); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8", 1000)); - await expect.element(screen.getByLabelText("Scroll display equation")).not.toBeInTheDocument(); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); -}); diff --git a/apps/web/src/components/chat/MarkdownMath.tsx b/apps/web/src/components/chat/MarkdownMath.tsx deleted file mode 100644 index 8070d64ac3c18..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { useGT } from "gt-react"; -import { lazy, memo, Suspense, useLayoutEffect, useRef, useState } from "react"; - -import { observeResize } from "../../lib/observeResize"; - -import { RenderErrorBoundary } from "../RenderErrorBoundary"; - -const MathTypeset = lazy(() => import("./MathTypeset")); - -/** - * One formula from `remark-math`. Shows its TeX until KaTeX loads, and - * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying - * any part of a formula copies its whole TeX source. - */ -export const MarkdownMath = memo(function MarkdownMath(props: { - tex: string; - display: boolean; - focusable?: boolean; -}) { - const gt = useGT(); - const viewportRef = useRef(null); - const contentRef = useRef(null); - const [overflows, setOverflows] = useState(false); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes formula DOM width to make overflowing equations keyboard scrollable - useLayoutEffect(() => { - const viewport = viewportRef.current; - const content = contentRef.current; - if (!viewport || !content || props.focusable === false) return; - const measure = () => setOverflows(viewport.scrollWidth > viewport.clientWidth); - measure(); - // Typesetting and streamed TeX can change content width without resizing the viewport. - return observeResize([viewport, content], measure); - }, [props.focusable]); - const scrollable = props.focusable !== false && overflows; - const tex = props.tex.trim(); - const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`; - const fallback = {source}; - return ( - - - - - - - - - - - - ); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.test.ts b/apps/web/src/components/chat/MathTypeset.logic.test.ts deleted file mode 100644 index 634f5146475ac..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import katex from "katex"; -import { describe, expect, it } from "vite-plus/test"; - -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -describe("escapeLiteralPercents", () => { - it.each([ - ["\\text{3.18% yield}", "\\text{3.18\\% yield}"], - ["\\text{100%% yield}", "\\text{100\\%\\% yield}"], - ["6\\% + 2\\%", "6\\% + 2\\%"], - ["x\\\\%", "x\\\\\\%"], - ["x % note\n+ 1", "x % note\n+ 1"], - ["% note\n\\text{2%}", "% note\n\\text{2\\%}"], - ["x &= 1 % +9%\n\\text{2%}", "x &= 1 % +9%\n\\text{2\\%}"], - ["\\verb|50%|+\\text{2%}", "\\verb|50%|+\\text{2\\%}"], - ["\\verb*%a%b%+c%", "\\verb*%a%b\\%+c\\%"], - ["\\verb|50%+\\text{2%}", "\\verb|50%+\\text{2%}"], - ])("repairs %j", (tex, expected) => { - expect(escapeLiteralPercents(tex)).toBe(expected); - }); - - it("lets the reported multiline equation typeset", () => { - const tex = - "R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}"; - expect(() => katex.renderToString(tex, { throwOnError: true })).toThrow(); - expect(() => - katex.renderToString(escapeLiteralPercents(tex), { throwOnError: true }), - ).not.toThrow(); - }); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.ts b/apps/web/src/components/chat/MathTypeset.logic.ts deleted file mode 100644 index 04111ab4a70b4..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Escapes each `%` written right after other text, as in `\text{3.18% yield}`. - * A `%` at a line start or after whitespace stays a comment. Skips escapes and - * `\verb` like KaTeX's lexer, in one linear pass. - */ -export function escapeLiteralPercents(tex: string): string { - let repaired = ""; - let copied = 0; - let index = 0; - while (index < tex.length) { - const char = tex[index]; - if (char === "\\") { - if (tex.startsWith("\\verb", index)) { - const starred = tex[index + 5] === "*"; - const delimiter = tex[index + (starred ? 6 : 5)]; - if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) { - const bodyStart = index + (starred ? 7 : 6); - let close = bodyStart; - while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++; - // KaTeX rejects a \verb that does not close on its own line. - if (tex[close] !== delimiter) return tex; - index = close + 1; - continue; - } - } - // A control symbol such as `\%` or `\\` is two characters. - index += 2; - } else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) { - repaired += `${tex.slice(copied, index)}\\%`; - copied = ++index; - } else if (char === "%") { - const newline = tex.indexOf("\n", index); - index = newline === -1 ? tex.length : newline + 1; - } else { - index++; - } - } - return copied === 0 ? tex : repaired + tex.slice(copied); -} diff --git a/apps/web/src/components/chat/MathTypeset.tsx b/apps/web/src/components/chat/MathTypeset.tsx deleted file mode 100644 index 16d3dba409ee6..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import katex from "katex"; -import "katex/dist/katex.min.css"; -import type { ReactNode } from "react"; - -import { LRUCache } from "../../lib/lruCache"; -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -// Virtualized threads remount messages while scrolling; cached markup keeps -// that from typesetting the same formulas again. "" records a parse error. -const typesetCache = new LRUCache(1000, 4 * 1024 * 1024); - -function typeset(tex: string, display: boolean): string { - const key = `${display ? "display" : "inline"}:${tex}`; - const cached = typesetCache.get(key); - if (cached !== null) return cached; - const options = { - displayMode: display, - output: "htmlAndMathml" as const, - throwOnError: true, - // No \href, \url, \htmlClass, or other commands that emit active HTML. - trust: false, - strict: "ignore" as const, - maxSize: 20, - maxExpand: 1000, - }; - let html = ""; - try { - html = katex.renderToString(tex, options); - } catch { - const repaired = escapeLiteralPercents(tex); - if (repaired !== tex) { - try { - html = katex.renderToString(repaired, options); - } catch { - // Unfinished or unsupported TeX stays readable as its source. - } - } - } - typesetCache.set(key, html, (key.length + html.length) * 2); - return html; -} - -/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */ -export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) { - const html = typeset(props.tex, props.display); - if (!html) return props.fallback; - // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes. - return ; -} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 2e7721dddea18..d15a26ca43db0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -44,11 +44,10 @@ import { type PendingApproval, deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; -import type { Root } from "mdast"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; +import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; -import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; @@ -2128,49 +2127,22 @@ describe("compact reasoning math", () => { ["hard \nbreak\\\nagain", [["text", "hard break again"]]], ["
only html
", [["text", "Reasoning"]]], ])("keeps formulas while flattening compact reasoning previews: %j", (source, expected) => { - const tree = parseMarkdownWithMath(source); - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children.map((node) => [node.type, "value" in node ? node.value : null])).toEqual( - expected, - ); - }); - - it("stops reading the tree once the preview is full", () => { - const beyondCap = (): string => { - throw new Error("read beyond cap"); - }; - const head = "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 2); - const tree: Root = { - type: "root", - children: [ - { - type: "paragraph", - children: [ - { type: "text", value: head }, - { type: "strong", children: [{ type: "text", value: "yz beyond" }] }, - { - type: "inlineMath", - get value() { - return beyondCap(); - }, - }, - ], - }, - { - type: "paragraph", - children: [ - { - type: "text", - get value() { - return beyondCap(); - }, - }, - ], - }, - ], - }; - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children).toEqual([{ type: "text", value: `${head}yz` }]); + const tree = wordsHast(source, { + math: true, + breaks: false, + escapeHtml: false, + insights: false, + extensions: thoughtPreviewMarkdown("Reasoning"), + }); + expect( + tree.children.map((node) => + node.type === "text" + ? ["text", node.value] + : node.type === "element" && node.children[0]?.type === "element" + ? ["inlineMath", String(node.children[0].properties.ariaLabel).trim()] + : [node.type, null], + ), + ).toEqual(expected); }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 124062303e0cf..b00a48185b9db 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -14,7 +14,7 @@ import { IDLE_COMPACTION_TITLES, } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; -import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives"; +import { renderCodexDirectivesForCopy } from "~/markdown/markdownText"; import { commandDisplayText, commandProgramName, diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index d337e7a1b9b54..25c1fe59d5e6b 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -24,6 +24,7 @@ import type { SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { T, useGT, useMessages, Var } from "gt-react"; import { CheckIcon, @@ -36,7 +37,6 @@ import { } from "lucide-react"; import { useId, useRef, useState, type FormEvent } from "react"; -import { isSecretsFeatureEnabled } from "../../env"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; @@ -80,7 +80,7 @@ const NO_SOURCES: ReadonlyArray = []; function useSecretRequestSources(environmentId: EnvironmentId) { const config = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const messages = useMessages(); - return isSecretsFeatureEnabled + return hasFeatureFlag(config, "secretProviders") ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages) : NO_SOURCES; } diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 7ab6e361494ee..72fcf79013e87 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -1,4 +1,4 @@ -import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; +import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights"; import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup"; diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 88cdd61b58cc5..cd99aad44d080 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,10 +1,7 @@ import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { T, useGT, useMessages, Var } from "gt-react"; import { findRevealRef } from "./markdownFindContext"; import { @@ -1284,10 +1281,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop ); }); -const USER_MESSAGE_REMARK_PLUGINS = [ - ...CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -]; +const USER_MESSAGE_MARKDOWN: MarkdownExtensions = { userMessage: true, leadingWhitespace: true }; const UserMessageBody = memo(function UserMessageBody(props: { text: string; @@ -1308,7 +1302,7 @@ const UserMessageBody = memo(function UserMessageBody(props: { className="text-message-foreground user-message-markdown" lineBreaks parseRawHtml={false} - extraRemarkPlugins={USER_MESSAGE_REMARK_PLUGINS} + extensions={USER_MESSAGE_MARKDOWN} renderContextReference={props.renderContextReference} headingLevelOffset={MESSAGE_HEADING_LEVEL} /> diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts index dc279ea8cb164..894f58f45edb4 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts @@ -1,6 +1,5 @@ import { msg } from "gt-react"; -import type { PluggableList } from "unified"; -import type { Root, RootContent } from "mdast"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { resolveWorkEntryToolPresentation, toolGroupAction, @@ -209,67 +208,14 @@ export function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconNa export const THOUGHT_PREVIEW_SOURCE_MAX_LENGTH = 8_192; export const THOUGHT_PREVIEW_MAX_LENGTH = 2_048; -/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ -export function remarkThoughtPreview(fallback: string) { - return (tree: Root) => { - const children: RootContent[] = []; - let remaining = THOUGHT_PREVIEW_MAX_LENGTH; - 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 here or at the source limit must not leave half a surrogate pair. - return text.replace(/[\uD800-\uDBFF]$/, ""); - }; - const append = (value: string) => { - fragments.push(take(value)); - }; - const visit = (node: Root | RootContent) => { - if (remaining === 0 || node.type === "html" || node.type === "definition") return; - if (node.type === "math" || node.type === "inlineMath") { - flush(); - const value = take(node.value); - children.push({ - type: "inlineMath", - value, - position: node.position, - data: { - hName: "code", - hProperties: { className: ["language-math", "math-inline"] }, - hChildren: [{ type: "text", value }], - }, - }); - } else if ("alt" in node) append(node.alt ?? ""); - else if ("value" in node) append(node.value); - else if ("children" in node) { - for (const [index, child] of node.children.entries()) { - if (remaining === 0) break; - if ( - index && - ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type) - ) - append(" "); - visit(child); - } - } else if (node.type === "break") append(" "); - }; - visit(tree); - flush(); - const first = children[0]; - const last = children.at(-1); - if (first?.type === "text") first.value = first.value.trimStart(); - if (last?.type === "text") last.value = last.value.trimEnd(); - tree.children = children.some((child) => child.type !== "text" || child.value) - ? children - : [{ type: "text", value: fallback }]; - }; -} +const thoughtPreviews = new Map(); -export function thoughtPreviewPlugins(fallback: string): PluggableList { - return [[remarkThoughtPreview, fallback]]; +/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ +export function thoughtPreviewMarkdown(fallback: string): MarkdownExtensions { + let extensions = thoughtPreviews.get(fallback); + if (!extensions) { + extensions = { preview: { fallback, maxLength: THOUGHT_PREVIEW_MAX_LENGTH } }; + thoughtPreviews.set(fallback, extensions); + } + return extensions; } diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 8e7f03618e59d..4cd6fc0e8dee6 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -73,7 +73,7 @@ import { workEntryRawCommand, buildToolCallExpandedBody, workEntryIconName, - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, } from "./TimelineWorkEntryRow.logic"; @@ -590,10 +590,10 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { )} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ workEntry.toolLifecycleStatus === "inProgress" - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 745a7aff68fdf..c67c76bf4cca3 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -56,7 +56,7 @@ import { SimpleWorkEntryRow, } from "./TimelineWorkEntryRow"; import { - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, toolGroupSummaryIconName, workEntryIconName, @@ -640,7 +640,7 @@ export function LiveWorkEntryTimelineRow({ text={thoughtLine} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={thoughtPreviewPlugins(gt("Thought"))} + extensions={thoughtPreviewMarkdown(gt("Thought"))} />
} @@ -661,10 +661,10 @@ export function LiveWorkEntryTimelineRow({ text={(row.entry.detail ?? label).slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH)} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ row.active - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index 2a487b1f237de..f842566d7cd60 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -121,10 +121,26 @@ describe("composer attachment files", () => { ).toBe(true); }); - it("leaves an image-and-text clipboard to the text path under Paste as Text", () => { + it("leaves a Word image-and-text clipboard to the text path, with or without Paste as Text", () => { const image = new File(["png"], "image.png", { type: "image/png" }); const input = { files: [image], plainText: "Hello from Word", bypassAutoAttachment: true }; expect(shouldHandleComposerAttachmentPaste(input)).toBe(false); + // A plain paste of the same Word clipboard keeps the text too. + expect(shouldHandleComposerAttachmentPaste({ ...input, bypassAutoAttachment: false })).toBe( + false, + ); + // Firefox's Copy Image adds the image URL as text and only an as HTML; the image attaches. + expect( + shouldHandleComposerAttachmentPaste({ + files: [image], + plainText: "https://example.com/image.png", + htmlIsOnlyImage: true, + }), + ).toBe(true); + // Finder adds a copied file's name as text. + expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( + true, + ); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 041db7193d2e2..191c5841185ff 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -239,30 +239,46 @@ export function attachmentsToReleaseOnUploadCapabilityLoss( ); } +function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { + const names = new Set(files.map((file) => file.name)); + return text + .split(/\r?\n/) + .filter((line) => line.length > 0) + .every((line) => names.has(line)); +} + +/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ +export function isImageOnlyClipboardHtml(html: string): boolean { + if (html.length === 0) return false; + const body = new DOMParser().parseFromString(html, "text/html").body; + return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; +} + export function shouldHandleComposerAttachmentPaste(input: { readonly files: ReadonlyArray; readonly plainText: string; readonly bypassAutoAttachment?: boolean; + readonly htmlIsOnlyImage?: boolean; }): boolean { // Paste as Text keeps the text even when the source also put an image of it on the clipboard. if (input.bypassAutoAttachment && input.plainText.length > 0) return false; if ( - input.files.some((file) => { - if (isDngFile(file)) return true; - const classification = classifyComposerAttachmentFile(file); - return ( - classification === "image" || - classification === "unsupported-image" || - isSvgAttachment({ name: file.name, mimeType: file.type }) - ); - }) + input.files.some( + (file) => isDngFile(file) || isSvgAttachment({ name: file.name, mimeType: file.type }), + ) ) { return true; } - - if (input.plainText.length > 0) { - return false; + const hasImage = input.files.some((file) => { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; + }); + if (input.plainText.length === 0) { + return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } - - return input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); + // Rich text sources (Word, Pages) add a picture of the text. Copy Image adds the image URL as + // text beside an , and a Finder copy adds the file names. + return ( + hasImage && (input.htmlIsOnlyImage === true || isOnlyFileNames(input.plainText, input.files)) + ); } diff --git a/apps/web/src/components/chat/markdownIslands.test.ts b/apps/web/src/components/chat/markdownIslands.test.ts new file mode 100644 index 0000000000000..f328c9ea51251 --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.test.ts @@ -0,0 +1,50 @@ +import type { Root } from "hast"; +import { renderToStaticMarkup } from "react-dom/server"; +import { createElement, Fragment } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { renderHastWithIslands } from "./markdownIslands"; + +describe("renderHastWithIslands", () => { + it("writes SVG attributes by their SVG names in static HTML", () => { + const tree: Root = { + type: "root", + children: [ + { + type: "element", + tagName: "p", + properties: {}, + children: [ + { + type: "element", + tagName: "svg", + properties: { viewBox: "0 0 1 1" }, + children: [ + { + type: "element", + tagName: "text", + properties: { fontSize: "700", strokeWidth: "2" }, + children: [{ type: "text", value: "x" }], + }, + ], + }, + ], + }, + ], + }; + const html = renderToStaticMarkup( + createElement( + Fragment, + null, + renderHastWithIslands(tree, { + components: {}, + variant: "", + isIsland: () => false, + staticElement: (node) => node, + }), + ), + ); + expect(html).toContain('x'); + expect(html).toContain('viewBox="0 0 1 1"'); + }); +}); diff --git a/apps/web/src/components/chat/markdownIslands.ts b/apps/web/src/components/chat/markdownIslands.ts new file mode 100644 index 0000000000000..8c434daf099ce --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.ts @@ -0,0 +1,214 @@ +import type { Element, ElementContent, Properties, Root, RootContent } from "hast"; +import { find, html as htmlSchema, svg as svgSchema } from "property-information"; +import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; +import { createElement, Fragment as ReactFragment, type ReactNode } from "react"; +import { Fragment, jsx, jsxs } from "react/jsx-runtime"; + +export interface MarkdownIslandOptions { + readonly components: Partial; + /** Elements that need their React component; everything else renders as static HTML. */ + readonly isIsland: (node: Element) => boolean; + /** What a static element's component would have added, or the node itself when nothing. */ + readonly staticElement: (node: Element) => Element; + /** Separates static HTML that `staticElement` renders differently, such as a heading offset. */ + readonly variant: string; +} + +const VOID_ELEMENTS = new Set( + "area base br col embed hr img input link meta source track wbr".split(" "), +); + +const jsxOptions = (components: Partial) => + ({ + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + }) as const; + +// Static HTML depends only on the cached, immutable tree and the variant. +const innerHtmlCache = new WeakMap(); + +function transformStatic( + node: ElementContent, + staticElement: MarkdownIslandOptions["staticElement"], +): ElementContent { + if (node.type !== "element") return node; + const element = staticElement(node); + let children: ElementContent[] | undefined; + for (let index = 0; index < element.children.length; index++) { + const child = element.children[index]!; + const next = transformStatic(child, staticElement); + if (next !== child) { + children ??= element.children.slice(); + children[index] = next; + } + } + return children ? { ...element, children } : element; +} + +function innerHtml(node: Element, options: MarkdownIslandOptions): string { + const cached = innerHtmlCache.get(node); + if (cached?.variant === options.variant) return cached.html; + let html = ""; + for (const child of node.children) { + html += serialize(transformStatic(child, options.staticElement)); + } + innerHtmlCache.set(node, { variant: options.variant, html }); + return html; +} + +interface AttributeInfo { + readonly name: string; + readonly boolean: boolean; + readonly separator: string; +} + +const attributeInfo = new Map(); + +// SVG names its attributes differently (`fontSize` is `font-size`), so its lookups key apart. +function infoFor(property: string, inSvg: boolean): AttributeInfo { + const key = inSvg ? `svg:${property}` : property; + let info = attributeInfo.get(key); + if (!info) { + const found = find(inSvg ? svgSchema : htmlSchema, property); + info = { + name: found.attribute, + boolean: found.boolean || found.overloadedBoolean, + separator: found.commaSeparated ? ", " : " ", + }; + attributeInfo.set(key, info); + } + return info; +} + +const escapeText = (value: string) => + value.includes("&") || value.includes("<") || value.includes(">") + ? value.replace(/&/g, "&").replace(//g, ">") + : value; +const escapeAttribute = (value: string) => + value.includes("&") || value.includes('"') + ? value.replace(/&/g, "&").replace(/"/g, """) + : value; + +/** HTML for the elements and text this pipeline builds; the DOM matches hast-util-to-html's. */ +function serialize(node: ElementContent, inSvg = false): string { + if (node.type === "text") return escapeText(node.value); + if (node.type !== "element") return ""; + const svg = inSvg || node.tagName === "svg"; + let html = `<${node.tagName}`; + const { properties } = node; + for (const key in properties) { + const value = properties[key]; + if (value === null || value === undefined || value === false || Number.isNaN(value)) continue; + const info = infoFor(key, svg); + if (info.boolean && value) { + html += ` ${info.name}`; + continue; + } + const text = Array.isArray(value) + ? value.join(info.separator) + : value === true + ? "" + : String(value); + html += ` ${info.name}="${escapeAttribute(text)}"`; + } + html += ">"; + if (VOID_ELEMENTS.has(node.tagName)) return html; + for (const child of node.children) html += serialize(child, svg); + return `${html}`; +} + +/** React props for an element, converted as hast-util-to-jsx-runtime converts them. */ +function shallowProps(node: Element, components: Partial): Record { + const element = toJsxRuntime( + { ...node, children: [] }, + { ...jsxOptions(components), components: {}, passNode: false }, + ) as { props: Record }; + const { children: _children, ...props } = element.props; + return props; +} + +interface Plan { + readonly islands: Set; + /** Elements with an island somewhere below them. */ + readonly ancestors: Set; +} + +function renderContent( + node: RootContent, + key: number, + options: MarkdownIslandOptions, + plan: Plan, +): ReactNode { + if (node.type === "text") return node.value; + if (node.type !== "element") return null; + if (plan.islands.has(node)) { + return createElement( + ReactFragment, + { key }, + toJsxRuntime(node, jsxOptions(options.components)), + ); + } + const element = options.staticElement(node); + const props: Record = { ...shallowProps(element, options.components), key }; + if (plan.ancestors.has(node)) { + return createElement( + element.tagName, + props, + ...element.children.map((child, index) => renderContent(child, index, options, plan)), + ); + } + if (element.children.length > 0 && !VOID_ELEMENTS.has(element.tagName)) { + props.dangerouslySetInnerHTML = { __html: innerHtml(node, options) }; + } + return createElement(element.tagName, props); +} + +/** + * Renders a hast tree with React only on the path to elements that need a component: subtrees + * without one become static HTML, which the browser builds without React reconciling each node. + */ +export function renderHastWithIslands(tree: Root, options: MarkdownIslandOptions): ReactNode { + // The same elements again let React skip the block; islands still follow their context. + let signature = options.variant; + const plan: Plan = { islands: new Set(), ancestors: new Set() }; + const visit = (node: Root | Element): boolean => { + let below = false; + for (const child of node.children) { + if (child.type !== "element") continue; + const island = options.isIsland(child); + signature += island ? "1" : "0"; + if (island) { + plan.islands.add(child); + below = true; + continue; + } + if (visit(child)) { + plan.ancestors.add(child); + below = true; + } + } + return below; + }; + visit(tree); + const cached = renderedTrees.get(tree); + if (cached?.signature === signature && cached.components === options.components) { + return cached.node; + } + const node = tree.children.map((child, index) => renderContent(child, index, options, plan)); + renderedTrees.set(tree, { signature, components: options.components, node }); + return node; +} + +const renderedTrees = new WeakMap< + Root, + { signature: string; components: Partial; node: ReactNode } +>(); + +export function withProperties(node: Element, properties: Properties): Element { + return { ...node, properties: { ...node.properties, ...properties } }; +} diff --git a/apps/web/src/components/chat/markdownRenderer.test.tsx b/apps/web/src/components/chat/markdownRenderer.test.tsx index f15fe49584aea..a9a60c545b37b 100644 --- a/apps/web/src/components/chat/markdownRenderer.test.tsx +++ b/apps/web/src/components/chat/markdownRenderer.test.tsx @@ -1,88 +1,41 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; import { describe, expect, it } from "vite-plus/test"; -import { createIncrementalMarkdownPlugin } from "../../markdown-incremental"; import { createMarkdownRenderer } from "./markdownRenderer"; // Visible in the markup, so every URL attribute must pass through it. const urlTransform = (url: string) => `${url}#seen`; describe("createMarkdownRenderer", () => { - const render = createMarkdownRenderer({ - remarkPlugins: CHAT_MARKDOWN_REMARK_PLUGINS, - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, + const renderer = createMarkdownRenderer({ + markdown: { math: false, breaks: false, escapeHtml: false, insights: false, extensions: {} }, components: {}, urlTransform, }); + const render = (text: string) => renderer.element(renderer.parse(text)); + const renderAndRemember = (text: string) => { + const entry = renderer.parse(text); + renderer.remember(text, entry); + return renderer.element(entry); + }; - it.each([ - '# Title\n\nText with `code`, **bold**, [a link](https://example.com "t") and https://bare.example.com.', - "![shot](./shot.png) and [file](file:///C:/repo/a.ts) and [bad](javascript:alert(1))", - "
More\n\nHidden bold \n\n
", - "| a | b |\n| - | - |\n|
| [x](#frag) |\n\n- [ ] task\n- [x] done", - '```ts title="a.ts"\nconst a = 1;\n```\n\n> [!WARNING]\n> careful bare', - "Footnote[^1] and ~~strike~~\n\n[^1]: the note", - // Each GFM construct the parser skips when its text cannot match, next to one that can. - "Mail me@example.com, see www.example.com and HTTPS://example.com/a, not [x](https://y.z).", - "a.b-c_d+e@x.io and @user\n\n`me@x.io` ", - "A table without pipes\n:--", - "> | quoted |\n> | - |\n> | body |\n\n- [ ] open\n- [X] done", - "Escaped www\\.example.com and me@example.com", - "\ufeffA byte order mark\n\n| a |\n| - |\n| b |", - "> - | a |\r\n> | - |\r\n> | me@x.io |\r\n\n-\t[ ] tab\n\n ~~lazy~~", - ])("renders what react-markdown renders: %j", (source) => { - const expected = renderToStaticMarkup( - - {source} - , + it("passes every URL attribute through the transform", () => { + const html = renderToStaticMarkup( + render('![shot](./shot.png) and [a link](https://example.com "t") and '), ); - const element = render(source); - expect(renderToStaticMarkup(element)).toBe(expected); - render.remember(source, element); - expect(render(source)).toBe(element); + expect(html).toContain('src="./shot.png#seen"'); + expect(html).toContain('href="https://example.com#seen"'); + expect(html).toContain('src="b.png#seen"'); }); - it("renders what react-markdown renders while a reply streams through the incremental parser", () => { - const reply = - "```ts\nconst a = 1;\n```\n\n| a | b |\n| - | - |\n| me@x.io | www.x.io |\n\nDone ~~now~~."; - // As ChatMarkdown streams: one incremental plugin for the reply, a fresh renderer per update. - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 1; end <= reply.length; end++) { - const source = reply.slice(0, end); - const streamed = createMarkdownRenderer({ - remarkPlugins: [...CHAT_MARKDOWN_REMARK_PLUGINS, incremental], - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, - components: {}, - urlTransform, - })(source); - expect(renderToStaticMarkup(streamed)).toBe( - renderToStaticMarkup( - - {source} - , - ), - ); - } + it("reuses a remembered message's element", () => { + const element = renderAndRemember("# Title\n\nText with `code` and **bold**."); + expect(render("# Title\n\nText with `code` and **bold**.")).toBe(element); }); it("keeps cached messages when one far larger than the cache is rendered", () => { - const element = render("Kept *message*"); - render.remember("Kept *message*", element); - const large = "x".repeat(600_000); - render.remember(large, render(large)); + const element = renderAndRemember("Kept *message*"); + renderAndRemember("x".repeat(600_000)); expect(render("Kept *message*")).toBe(element); }); }); diff --git a/apps/web/src/components/chat/markdownRenderer.ts b/apps/web/src/components/chat/markdownRenderer.ts index 9637d68e8f158..c2aa499a9583d 100644 --- a/apps/web/src/components/chat/markdownRenderer.ts +++ b/apps/web/src/components/chat/markdownRenderer.ts @@ -3,18 +3,13 @@ import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; import { urlAttributes } from "html-url-attributes"; import type { ReactElement } from "react"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { type PluggableList, unified } from "unified"; -import { VFile } from "vfile"; -import { remarkParseWithoutUnusedSyntax } from "./markdownSyntaxGates"; +import { wordsHast, type WordsHastOptions } from "../../markdown/wordsHast"; export type MarkdownUrlTransform = (url: string, key: string, node: Element) => string; interface MarkdownRendererOptions { - readonly remarkPlugins: PluggableList; - readonly rehypePlugins: PluggableList; + readonly markdown: WordsHastOptions; readonly components: Partial; readonly urlTransform: MarkdownUrlTransform; } @@ -23,7 +18,11 @@ interface MarkdownRendererOptions { // reuses one instead of parsing again. Parsing is most of the cost of rendering markdown. // An element and the hast it keeps hold about 20 bytes per source character, so ~10 MB. const MAX_CACHED_CHARS = 500_000; -const rendered = new Map(); +interface Rendered { + readonly tree: Root; + element?: ReactElement; +} +const rendered = new Map(); let cachedChars = 0; let nextRendererId = 0; @@ -31,10 +30,10 @@ let nextRendererId = 0; const ENTRY_OVERHEAD_CHARS = 200; const entrySize = (key: string) => key.length + ENTRY_OVERHEAD_CHARS; -function remember(key: string, element: ReactElement) { +function remember(key: string, entry: Rendered) { // One huge message would otherwise evict everything else. if (entrySize(key) > MAX_CACHED_CHARS / 4) return; - rendered.set(key, element); + rendered.set(key, entry); cachedChars += entrySize(key); for (const oldest of rendered.keys()) { if (cachedChars <= MAX_CACHED_CHARS) break; @@ -43,32 +42,18 @@ function remember(key: string, element: ReactElement) { } } -/** Renders markdown as react-markdown does, with one processor per plugin set. */ +/** Renders markdown with Words, keeping one parse cache per option set. */ export function createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components, urlTransform, }: MarkdownRendererOptions) { - const processor = unified() - .use(remarkParse) - .use(remarkParseWithoutUnusedSyntax) - .use(remarkPlugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(rehypePlugins) - .freeze(); const keyPrefix = `${nextRendererId++}\u0000`; - // Literal raw HTML that survived the rehype plugins, and URL attributes, as react-markdown treats them. + // URL attributes, as react-markdown transformed them. const prepare = (node: Nodes) => { if (!("children" in node)) return; - const { children } = node; - for (let index = 0; index < children.length; index++) { - const child = children[index]!; - if (child.type === "raw") { - children[index] = { type: "text", value: child.value }; - continue; - } + for (const child of node.children) { if (child.type !== "element") continue; const { properties } = child; for (const key in properties) { @@ -82,7 +67,7 @@ export function createMarkdownRenderer({ } }; - const render = (text: string): ReactElement => { + const parse = (text: string): Rendered => { const key = keyPrefix + text; const cached = rendered.get(key); if (cached !== undefined) { @@ -91,24 +76,27 @@ export function createMarkdownRenderer({ rendered.set(key, cached); return cached; } - const file = new VFile(text); - const tree = processor.runSync(processor.parse(file), file) as Root; + const tree = wordsHast(text, markdown); prepare(tree); - return toJsxRuntime(tree, { - Fragment, - components, - ignoreInvalidStyle: true, - jsx, - jsxs, - passKeys: true, - passNode: true, - }); + return { tree }; }; - return Object.assign(render, { - remember(text: string, element: ReactElement) { + return { + /** A cached entry, or a fresh one that `remember` can keep. Cached trees are shared, so callers must not change them. */ + parse, + element: (entry: Rendered): ReactElement => + (entry.element ??= toJsxRuntime(entry.tree, { + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + })), + remember(text: string, entry: Rendered) { const key = keyPrefix + text; - if (!rendered.has(key)) remember(key, element); + if (!rendered.has(key)) remember(key, entry); }, - }); + }; } diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.ts similarity index 81% rename from apps/web/src/components/chat/markdownStreamBlocks.test.tsx rename to apps/web/src/components/chat/markdownStreamBlocks.test.ts index 38ecff7666508..b89940489ec32 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.ts @@ -1,32 +1,19 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkMath from "remark-math"; -import type { PluggableList } from "unified"; +import { toHtml } from "hast-util-to-html"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; -import { rehypeHeadingIds } from "./markdownFragments"; - -const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. const renderMarkdown = (source: string, math = false) => - renderToStaticMarkup( - - {source} - , + toHtml( + wordsHast(source, { + math, + breaks: false, + escapeHtml: false, + insights: source.includes("★ Insight"), + extensions: {}, + }), ) .replace(/>\s+<") .trim(); diff --git a/apps/web/src/components/chat/markdownSyntaxGates.ts b/apps/web/src/components/chat/markdownSyntaxGates.ts deleted file mode 100644 index 57587a51b9d13..0000000000000 --- a/apps/web/src/components/chat/markdownSyntaxGates.ts +++ /dev/null @@ -1,204 +0,0 @@ -import type { Nodes as MdastNodes } from "mdast"; -import { - type Extension as MdastExtension, - fromMarkdown, - type Options as FromMarkdownOptions, - type Transform, -} from "mdast-util-from-markdown"; -import { combineExtensions } from "micromark-util-combine-extensions"; -import type { Construct, Extension, TokenizeContext } from "micromark-util-types"; -import type { Processor } from "unified"; - -// A table needs a delimiter row: dashes with a `|` or `:`, after any `>` or indent. -// One character class per pattern: overlapping ones backtrack quadratically on a run of dashes. -const DELIMITER_LINE = /^[ \t>|:-]+$/gm; -const isDelimiterRow = (line: string) => line.includes("-") && /[|:]/.test(line); -const NEXT_LINE = /[^\r\n]*(?:\r\n?|\n)([^\r\n]*)/y; - -function hasDelimiterRow(text: string) { - for (const [line] of text.matchAll(DELIMITER_LINE)) if (isDelimiterRow(line)) return true; - return false; -} -const PROTOCOL = /https?:\/\//iy; -const WWW = /www\./iy; -const EMAIL_ATEXT = /[\w+.-]*@/y; - -const matchesAt = (pattern: RegExp, text: string, offset: number) => { - pattern.lastIndex = offset; - return pattern.test(text); -}; - -interface Gate { - readonly names: ReadonlyArray; - /** False when the construct cannot match anywhere in the text. */ - readonly inText: (text: string) => boolean; - /** False when it cannot start at this offset, which keeps micromark from trying it there. */ - readonly at?: (context: TokenizeContext, text: string, offset: number) => boolean; -} - -// micromark tries these at every candidate character: email autolinks at every word, tables -// at every line. That is most of what GFM adds to a parse, and most texts cannot match them. -const GATES: ReadonlyArray = [ - { - names: ["emailAutolink"], - inText: (text) => text.includes("@"), - at: (_, text, offset) => matchesAt(EMAIL_ATEXT, text, offset), - }, - { - names: ["protocolAutolink"], - inText: (text) => /https?:\/\//i.test(text), - at: (_, text, offset) => matchesAt(PROTOCOL, text, offset), - }, - { - names: ["wwwAutolink"], - inText: (text) => /www\./i.test(text), - at: (_, text, offset) => matchesAt(WWW, text, offset), - }, - { - names: ["table"], - inText: hasDelimiterRow, - at: (context, text, offset) => { - NEXT_LINE.lastIndex = offset; - const nextLine = NEXT_LINE.exec(text)?.[1]; - return (nextLine !== undefined && hasDelimiterRow(nextLine)) || continuesTable(context); - }, - }, - { names: ["strikethrough"], inText: (text) => text.includes("~") }, - { - names: ["gfmFootnoteCall", "gfmPotentialFootnoteCall", "gfmFootnoteDefinition"], - inText: (text) => text.includes("[^"), - }, - { names: ["tasklistCheck"], inText: (text) => /\[[\sxX]\]/.test(text) }, -]; - -// A body row follows the head or another row. Mirrors `start` in micromark-extension-gfm-table's -// lib/syntax.js: recheck it when that package changes. -function continuesTable({ events }: TokenizeContext) { - let index = events.length - 1; - while (index > -1 && /^(?:lineEnding|linePrefix)$/.test(events[index]![1].type)) index--; - // The table extension's token types are not in micromark's map unless its types are loaded. - const tail: string | undefined = events[index]?.[1].type; - return tail === "tableHead" || tail === "tableRow"; -} - -let parsing = ""; -const gated = new WeakMap(); - -function gatedConstruct(construct: Construct, gate: Gate): Construct { - const at = gate.at; - if (!at) return construct; - let wrapped = gated.get(construct); - if (!wrapped) { - const { previous, tokenize } = construct; - wrapped = { - ...construct, - tokenize(effects, ok, nok) { - return at(this, parsing, this.now().offset) ? tokenize.call(this, effects, ok, nok) : nok; - }, - ...(previous && { - previous(code) { - return previous.call(this, code) && at(this, parsing, this.now().offset); - }, - }), - }; - gated.set(construct, wrapped); - } - return wrapped; -} - -type ConstructMap = Record; - -function gateExtension(extension: Extension, absent: ReadonlySet): Extension { - const gateOf = (name: string | undefined) => - GATES.find((gate) => name && gate.names.includes(name)); - const result: Record = {}; - for (const [field, value] of Object.entries(extension)) { - if (field === "disable" || field === "attentionMarkers" || !value) { - result[field] = value; - continue; - } - const map: ConstructMap = {}; - for (const [code, entry] of Object.entries(value as ConstructMap)) { - const kept = (Array.isArray(entry) ? entry : [entry]).flatMap((construct) => { - const gate = construct && gateOf(construct.name); - if (!construct || !gate) return construct ? [construct] : []; - return absent.has(gate) ? [] : [gatedConstruct(construct, gate)]; - }); - if (kept.length > 0) map[code] = Array.isArray(entry) ? kept : kept[0]; - } - result[field] = map; - } - return result as Extension; -} - -type MdastExtensions = NonNullable; - -// Merged once, as mdast-util-from-markdown merges them on every call: lists in order, handlers by key. -function mergeMdastExtensions(extensions: MdastExtensions): MdastExtension { - const merged = { - canContainEols: [] as string[], - enter: {}, - exit: {}, - transforms: [] as Transform[], - }; - for (const extension of extensions.flat()) { - merged.canContainEols.push(...(extension.canContainEols ?? [])); - Object.assign(merged.enter, extension.enter); - Object.assign(merged.exit, extension.exit); - // GFM looks for autolink literals again in the decoded text outside links, so `www\.x.io` - // links too. Most texts have URLs only in link destinations and code, where it finds nothing. - for (const transform of extension.transforms ?? []) { - merged.transforms.push( - extension.enter?.literalAutolink - ? (tree) => (hasAutolinkText(tree) ? transform(tree) : undefined) - : transform, - ); - } - } - return merged; -} - -const AUTOLINK_TEXT = /@|https?:\/\/|www\./i; - -function hasAutolinkText(node: MdastNodes): boolean { - if (node.type === "text") return AUTOLINK_TEXT.test(node.value); - if (node.type === "link" || node.type === "linkReference" || !("children" in node)) return false; - return node.children.some(hasAutolinkText); -} - -/** - * Parses as remark-parse does, without the syntax extension constructs that cannot match the - * text. Same tree, in about half the time. - */ -function attachParserWithoutUnusedSyntax(this: Processor) { - const data = this.data(); - const byMask = new Map(); - let mdastExtensions: MdastExtension[] | undefined; - this.parser = (document) => { - let mask = 0; - GATES.forEach((gate, index) => { - if (!gate.inText(document)) mask |= 1 << index; - }); - let extensions = byMask.get(mask); - if (!extensions) { - const absent = new Set(GATES.filter((_, index) => mask & (1 << index))); - extensions = [ - combineExtensions( - (data.micromarkExtensions ?? []).map((extension) => gateExtension(extension, absent)), - ), - ]; - byMask.set(mask, extensions); - } - mdastExtensions ??= [mergeMdastExtensions(data.fromMarkdownExtensions ?? [])]; - const outer = parsing; - // Gates read micromark offsets, which skip a leading byte order mark. - parsing = document.charCodeAt(0) === 0xfeff ? document.slice(1) : document; - try { - return fromMarkdown(document, { ...data.settings, extensions, mdastExtensions }); - } finally { - parsing = outer; - } - }; -} - -export const remarkParseWithoutUnusedSyntax = attachParserWithoutUnusedSyntax; diff --git a/apps/web/src/components/chat/markdownTextDirection.ts b/apps/web/src/components/chat/markdownTextDirection.ts index ffdbde76c1148..a4c78d3342754 100644 --- a/apps/web/src/components/chat/markdownTextDirection.ts +++ b/apps/web/src/components/chat/markdownTextDirection.ts @@ -1,4 +1,4 @@ -import { textDirection } from "~/textDirection"; +import { LETTER, RTL_LETTER, textDirection } from "~/textDirection"; type HastNode = { type?: string; @@ -57,11 +57,32 @@ function isolateInlineCode(node: HastNode): void { */ export function rehypeTextDirection() { return (tree: HastNode) => { - for (const block of tree.children ?? []) { - if (block.type !== "element" || block.tagName === "pre") continue; - const dir = textDirection(proseText(block)); - if (dir) block.properties = { ...block.properties, dir }; - } + blockTextDirections(tree); isolateInlineCode(tree); }; } + +/** Each top-level block's direction, from its prose; an RTL letter decides as textDirection does. */ +function blockTextDirections(tree: HastNode) { + for (const block of tree.children ?? []) { + if (block.type !== "element" || block.tagName === "pre") continue; + const dir = scriptOf(block) === "rtl" ? textDirection(proseText(block)) : scriptOf(block); + if (dir) block.properties = { ...block.properties, dir }; + } +} + +/** "rtl" when any prose letter is right-to-left; otherwise what textDirection would say. */ +function scriptOf(node: HastNode): "rtl" | "ltr" | undefined { + let found: "ltr" | undefined; + const visit = (current: HastNode): boolean => { + if (current.type === "text") { + const value = current.value ?? ""; + if (RTL_LETTER.test(value)) return true; + if (!found && LETTER.test(value)) found = "ltr"; + return false; + } + if (current.tagName === "code") return false; + return (current.children ?? []).some(visit); + }; + return visit(node) ? "rtl" : found; +} diff --git a/apps/web/src/components/chat/preparingComposerImages.test.ts b/apps/web/src/components/chat/preparingComposerImages.test.ts new file mode 100644 index 0000000000000..29a0f80f52386 --- /dev/null +++ b/apps/web/src/components/chat/preparingComposerImages.test.ts @@ -0,0 +1,58 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { EnvironmentId, ProviderDriverKind, ThreadId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; + +import { composerTargetKey, useComposerDraftStore } from "../../composerDraftStore"; +import { + addPreparingComposerImages, + cancelHeldComposerSend, + cancelPreparingComposerImages, + holdComposerSend, + joinPreparedImagesToDraft, + removePreparingComposerImages, +} from "./preparingComposerImages"; + +function preparingImage(id: string) { + return { id, name: `${id}.png`, file: new File(["png"], `${id}.png`), hidden: false }; +} + +it("holds a message send until its images join the draft, and cancels on edit, cancel, or new paste", async () => { + const draftTarget = scopeThreadRef(EnvironmentId.make("environment-held"), ThreadId.make("held")); + const target = composerTargetKey(draftTarget); + const drafts = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => { + cancelPreparingComposerImages(target); + drafts.clearComposerContent(draftTarget); + }, + }; + drafts.setPrompt(draftTarget, "check"); + expect(holdComposerSend(draftTarget)).toBeNull(); + + // Two pastes compress separately; the first joining the draft is not an edit. + addPreparingComposerImages(target, [preparingImage("first")]); + addPreparingComposerImages(target, [preparingImage("second")]); + const held = holdComposerSend(draftTarget); + await expect(holdComposerSend(draftTarget)).resolves.toEqual({ status: "cancelled" }); + removePreparingComposerImages(target, new Set(["first"])); + joinPreparedImagesToDraft(() => drafts.setPrompt(draftTarget, "check first")); + removePreparingComposerImages(target, new Set(["second"])); + await expect(held).resolves.toEqual({ status: "ready" }); + + for (const cancel of [ + () => drafts.setPrompt(draftTarget, "check again"), + () => + drafts.setProviderModelOptions(draftTarget, ProviderDriverKind.make("codex"), [ + { id: "reasoningEffort", value: "high" }, + ]), + () => cancelHeldComposerSend(target), + () => addPreparingComposerImages(target, [preparingImage("added-mid-wait")]), + () => removePreparingComposerImages(target, new Set(["later"]), { cancelSubmission: true }), + ]) { + addPreparingComposerImages(target, [preparingImage("later")]); + const cancelled = holdComposerSend(draftTarget); + cancel(); + await expect(cancelled).resolves.toEqual({ status: "cancelled" }); + cancelPreparingComposerImages(target); + } +}); diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 47d24ab5f7a89..951e7f661221c 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -3,7 +3,13 @@ import type { ScopedThreadRef } from "@t3tools/contracts"; import { useEffect, useRef } from "react"; import { create } from "zustand"; +import { + composerTargetKey, + type ComposerThreadTarget, + useComposerDraftStore, +} from "../../composerDraftStore"; import { useStableCallback } from "../../hooks/useStableCallback"; +import { composerDraftContentChanged } from "./composerSend.logic"; export interface PreparingComposerImage { readonly id: string; @@ -69,6 +75,9 @@ export function addPreparingComposerImages( targetKey: string, images: ReadonlyArray, ): void { + if (images.length > 0) { + heldSends.get(targetKey)?.({ status: "cancelled" }); + } usePreparingComposerImageStore.setState((state) => ({ byTargetKey: { ...state.byTargetKey, @@ -116,8 +125,89 @@ export function removePreparingComposerImages( // Bumped on cancel so a send held for the cancelled images is dropped rather than released. const cancelGenerations = new Map(); +export type HeldComposerSendResult = + | { readonly status: "ready" } + | { readonly status: "cancelled" }; + +const heldSends = new Map void>(); +const useHeldSendStore = create<{ readonly targetKeys: Readonly> }>(() => ({ + targetKeys: {}, +})); +let preparedImagesJoiningDraft = false; + function invalidatePendingSubmit(targetKey: string) { cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1); + heldSends.get(targetKey)?.({ status: "cancelled" }); +} + +/** Whether a send from the target's draft is waiting on its images to finish preparing. */ +export function useComposerSendHeld(targetKey: string): boolean { + return useHeldSendStore((state) => state.targetKeys[targetKey] === true); +} + +export function cancelHeldComposerSend(targetKey: string): void { + heldSends.get(targetKey)?.({ status: "cancelled" }); +} + +/** Inserts finished images into the draft without counting as an edit to a held send. */ +export function joinPreparedImagesToDraft(insert: () => T): T { + preparedImagesJoiningDraft = true; + try { + return insert(); + } finally { + preparedImagesJoiningDraft = false; + } +} + +/** + * Holds a send made while the draft still has images compressing. Resolves ready once they join + * the draft, or cancelled if the draft is edited or the send cancelled. Null means nothing needs + * to wait. Lives outside the composer so leaving the thread still completes the send. + */ +export function holdComposerSend( + draftTarget: ComposerThreadTarget, +): Promise | null { + const targetKey = composerTargetKey(draftTarget); + if (countPreparingComposerImages(targetKey) === 0) return null; + if (heldSends.has(targetKey)) return Promise.resolve({ status: "cancelled" }); + return new Promise((resolve) => { + let draft = useComposerDraftStore.getState().getComposerDraft(draftTarget); + const settle = (result: HeldComposerSendResult) => { + if (heldSends.get(targetKey) !== settle) return; + heldSends.delete(targetKey); + stopWatchingImages(); + stopWatchingDraft(); + useHeldSendStore.setState((state) => { + const targetKeys = { ...state.targetKeys }; + delete targetKeys[targetKey]; + return { targetKeys }; + }); + resolve(result); + }; + heldSends.set(targetKey, settle); + const stopWatchingImages = usePreparingComposerImageStore.subscribe((state) => { + if (state.byTargetKey[targetKey]) return; + // Let joinPreparedImagesToDraft finish inserting compressed images in this tick first. + queueMicrotask(() => settle({ status: "ready" })); + }); + const stopWatchingDraft = useComposerDraftStore.subscribe((state) => { + const next = state.getComposerDraft(draftTarget); + if ( + !preparedImagesJoiningDraft && + (composerDraftContentChanged(draft, next) || + draft?.modelSelectionByProvider !== next?.modelSelectionByProvider || + draft?.activeProvider !== next?.activeProvider || + draft?.runtimeMode !== next?.runtimeMode || + draft?.interactionMode !== next?.interactionMode) + ) { + settle({ status: "cancelled" }); + } + draft = next; + }); + useHeldSendStore.setState((state) => ({ + targetKeys: { ...state.targetKeys, [targetKey]: true }, + })); + }); } /** Drops every image still preparing for the target, so its compression result is discarded. */ diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts index c8ce0b31b9c9e..fe6a3ba5d3056 100644 --- a/apps/web/src/components/chat/threadFindHighlights.ts +++ b/apps/web/src/components/chat/threadFindHighlights.ts @@ -1,6 +1,6 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { useEffect, useEffectEvent, useRef } from "react"; -import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; +import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindBlockTags"; import { observeResize } from "~/lib/observeResize"; diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 151a02d88175e..57f6229c99526 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -4,10 +4,9 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { Nodes } from "mdast"; -import remarkGfm from "remark-gfm"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Nodes } from "hast"; + +import { markdownTree } from "~/markdown/wordsHast"; import type { MessagesTimelineRow } from "./MessagesTimeline.logic"; @@ -58,50 +57,49 @@ function resolveFinalAssistantTextForTurn( return finalAssistantText; } -const markdownPreviewParser = unified().use(remarkParse).use(remarkGfm).freeze(); - -const INLINE_PARENT_TYPES = new Set([ - "paragraph", - "heading", - "tableCell", - "emphasis", +// Elements whose children run together; every other element is separated by a space. +const INLINE_PARENTS = new Set([ + "p", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "td", + "th", + "em", "strong", - "delete", - "link", - "linkReference", + "del", + "a", + "code", + "span", + "sup", + "sub", ]); function markdownNodeText(node: Nodes): string { - if (node.type === "html") { - return node.value - .replace(/|$)/g, "") - .replace(/<\/?([a-z][\w-]*)(?:[^"'<>]|"[^"]*"|'[^']*')*>/gi, (_, tag: string) => - /^(?:address|article|aside|blockquote|br|dd|details|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|summary|table|tbody|td|th|thead|tr|ul)$/i.test( - tag, - ) - ? " " - : "", - ); - } - if (node.type === "break") return " "; - if ("value" in node) return node.value; - if (node.type === "image" || node.type === "imageReference") return node.alt ?? ""; - if (!("children" in node)) return ""; - const separator = INLINE_PARENT_TYPES.has(node.type) ? "" : " "; + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "br") return " "; + if (node.type === "element" && node.tagName === "img") return String(node.properties.alt ?? ""); + if (node.type !== "element" && node.type !== "root") return ""; + const separator = node.type === "element" && INLINE_PARENTS.has(node.tagName) ? "" : " "; const text = node.children.map(markdownNodeText).join(separator); // A thread autolink's only text is its URL. - return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text; + return node.type === "element" && node.tagName === "a" && parseThreadLinkHref(text) !== null + ? "a thread" + : text; } /** Markdown as one line of the text it renders, without markup or link targets. */ export function markdownPlainText(markdown: string): string { - return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); + return markdownNodeText(markdownTree(markdown)).replace(/\s+/g, " ").trim(); } // The tooltip shows a few lines; bound parsing work for long messages and streaming responses. function markdownMinimapPreview(markdown: string | null) { if (markdown === null) return null; - const compact = markdownNodeText(markdownPreviewParser.parse(markdown.slice(0, 1_500))) + const compact = markdownNodeText(markdownTree(markdown.slice(0, 1_500))) .replace(/\s+/g, " ") .trim(); return compact.length > 0 ? compact : null; diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts index cfd8fde657713..08b362b866e1a 100644 --- a/apps/web/src/components/chat/useComposerAttachmentIntake.ts +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -57,6 +57,7 @@ import { addPreparingComposerImages, getPreparingComposerImages, isPreparingComposerImage, + joinPreparedImagesToDraft, movedPreparingImageThread, removePreparingComposerImages, } from "./preparingComposerImages"; @@ -338,16 +339,19 @@ export function useComposerAttachmentIntake(input: { })); const unrestoredImageNames: string[] = []; const draftStore = useComposerDraftStore.getState(); - const storedImageIds = new Set( - movedThread - ? draftStore.addImages(movedThread, nextImages, { - onCapacityExceeded: (image) => unrestoredImageNames.push(image.name), - }) - : nextImages.length === 1 && nextImages[0] - ? addComposerImage(nextImages[0]) - : nextImages.length > 1 - ? addComposerImagesToDraft(nextImages) - : [], + const storedImageIds = joinPreparedImagesToDraft( + () => + new Set( + movedThread + ? draftStore.addImages(movedThread, nextImages, { + onCapacityExceeded: (image) => unrestoredImageNames.push(image.name), + }) + : nextImages.length === 1 && nextImages[0] + ? addComposerImage(nextImages[0]) + : nextImages.length > 1 + ? addComposerImagesToDraft(nextImages) + : [], + ), ); // Keep the placeholders until the draft decides whether the recovered images fit, // so a held send can be cancelled before the last placeholder disappears. @@ -365,10 +369,12 @@ export function useComposerAttachmentIntake(input: { } if (storedImages.length > 0 && imageAttachmentsGetChips && !movedThread) { insertedAny = - insertAttachmentReferences( - storedImages.map(imageContextReference), - undefined, - pendingInsertion, + joinPreparedImagesToDraft(() => + insertAttachmentReferences( + storedImages.map(imageContextReference), + undefined, + pendingInsertion, + ), ) || insertedAny; } // Only failures are reported here. Success must not pass `null`: by diff --git a/apps/web/src/components/chat/useComposerSelection.ts b/apps/web/src/components/chat/useComposerSelection.ts index 77fdd4a459df2..af8c3a3007fb0 100644 --- a/apps/web/src/components/chat/useComposerSelection.ts +++ b/apps/web/src/components/chat/useComposerSelection.ts @@ -25,10 +25,12 @@ import { threadHasStarted, } from "../../lib/chatThreadActions"; import { + composerTargetKey, type DraftThreadEnvMode, isSameModel, useComposerDraftStore, } from "../../composerDraftStore"; +import { cancelHeldComposerSend } from "./preparingComposerImages"; import { getStartedThreadModelChangeBlockReason, deriveLockedProvider, @@ -96,6 +98,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { const handleRuntimeModeChange = (mode: RuntimeMode) => { if (mode === runtimeMode) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); setComposerDraftRuntimeMode(composerDraftTarget, mode); if (isLocalDraftThread) { setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); @@ -135,6 +138,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { options?: { focusComposer?: boolean }, ) => { if (!activeThread) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId); const resolvedDriverKind = entry?.driver ?? null; if ( @@ -240,6 +244,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { const onProviderModelSelectStable = useStableCallback(onProviderModelSelect); const onEnvModeChange = (mode: DraftThreadEnvMode) => { if (multipleModelSelections !== null) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); if (canOverrideServerThreadEnvMode) { if (activeThread) setPendingServerThreadEnvModeEntry({ threadId: activeThread.id, mode }); scheduleComposerFocus(); @@ -263,6 +268,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { // re-renders the branch toolbar and thread details panel with it. const activeThreadId = activeThread?.id; const onStartFromOriginChange = (nextStartFromOrigin: boolean) => { + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); if (canOverrideServerThreadEnvMode && activeThreadId !== undefined) { setPendingServerThreadStartFromOriginByThreadId((current) => current[activeThreadId] === nextStartFromOrigin diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index d89a9d79febc6..bc38e5001dde1 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -77,6 +77,7 @@ import { restoreFailedDraftThread, checkoutPullRequestUrlToLink, composerDraftHasUserContent, + composerTargetKey, type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, @@ -119,6 +120,7 @@ import { startAttachmentUpload, } from "../../lib/attachmentUploadQueue"; import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { countPreparingComposerImages, holdComposerSend } from "./preparingComposerImages"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; import { useLinkedEnvironments } from "../../state/peerLinks"; import { readEnvironmentScope } from "../../state/session"; @@ -428,12 +430,13 @@ export function useComposerSend(input: ComposerSendInput) { e?.preventDefault(); // What the user pressed send on; uploads below can take a while, and a redirect must not // decline approvals for a draft that changed meanwhile. - const promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; + let promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; if ( usageLimitsOffered && usageLimitsKey !== null && !directAnnotation && !draftHasNonPromptContent(composerDraftTarget) && + countPreparingComposerImages(composerTargetKey(composerDraftTarget)) === 0 && isUsageLimitsCommand(promptAtSend) ) { if (openUsageLimits()) { @@ -446,9 +449,11 @@ export function useComposerSend(input: ComposerSendInput) { return; } - const sendCtx = detachedOverride + // Read before any wait; the composer on screen may belong to another thread after it. + let sendCtx = detachedOverride ? detachedOverride.sendContext : composerRef.current?.getSendContext(); + const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; // `/side` beats an open question and a plan follow-up, which would send the text to main. const sideChatCommand = sendCtx && !directAnnotation && !queuedRunEdit.isEditing @@ -544,6 +549,27 @@ export function useComposerSend(input: ComposerSendInput) { ); return; } + const heldForImages = directAnnotation ? null : holdComposerSend(composerDraftTarget); + if (heldForImages) { + if ((await heldForImages).status === "cancelled") return; + const draftAfterHold = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + if (!draftAfterHold) return; + // A dictation sent after leaving the thread carries its transcript outside the draft. + promptAtSend = detachedOverride ? detachedOverride.prompt : draftAfterHold.prompt; + if (sendCtx) { + sendCtx = { + ...sendCtx, + prompt: promptAtSend, + images: draftAfterHold.images, + files: draftAfterHold.files, + terminalContexts: draftAfterHold.terminalContexts, + previewAnnotations: draftAfterHold.previewAnnotations, + reviewComments: draftAfterHold.reviewComments, + threadContexts: draftAfterHold.threadContexts, + environmentContexts: draftAfterHold.environmentContexts, + }; + } + } const startDraftAttachmentUploads = ( attachments: ReadonlyArray, ) => { @@ -1038,7 +1064,6 @@ export function useComposerSend(input: ComposerSendInput) { effort: ctxSelectedPromptEffort, text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, }); - const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; if ( isCurrentRouteThread() && composerRef.current?.validateProviderInput(outgoingMessageText) === false @@ -1092,6 +1117,7 @@ export function useComposerSend(input: ComposerSendInput) { if (turnUsesAttachmentUploads) startDraftAttachmentUploads(composerAttachmentsSnapshot); if ( + isCurrentRouteThread() && multipleModelSelections === null && shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) && activeThreadKey @@ -1307,7 +1333,7 @@ export function useComposerSend(input: ComposerSendInput) { } if (sendQueuesBehindSetup) { setSetupQueueSendThreadKey(activeThreadKey); - } else { + } else if (isCurrentRouteThread()) { beginLocalDispatch({ preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree), submissionIntent: @@ -1723,7 +1749,7 @@ export function useComposerSend(input: ComposerSendInput) { setDockedDraftHeroThreadKey((currentThreadKey) => currentThreadKey === activeThreadKey ? null : currentThreadKey, ); - if (!sendQueuesBehindSetup) resetLocalDispatch(); + if (!sendQueuesBehindSetup && isCurrentRouteThread()) resetLocalDispatch(); } }; diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index c020113815dfa..2c27cfb8d80d1 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -132,7 +132,7 @@ import { shouldShowFileExplorer, workspaceAssetResource, } from "./filePreviewMode"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions"; import { revisionedQuery } from "~/state/revisionedQuery"; import { diff --git a/apps/web/src/components/files/NotebookPreview.tsx b/apps/web/src/components/files/NotebookPreview.tsx index 35d0203818850..c2104ad2ddec6 100644 --- a/apps/web/src/components/files/NotebookPreview.tsx +++ b/apps/web/src/components/files/NotebookPreview.tsx @@ -2,8 +2,8 @@ import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { T, useGT, useMessages } from "gt-react"; import { useEffect, useRef, useState } from "react"; -import type { Root, RootContent } from "mdast"; import ChatMarkdown from "~/components/ChatMarkdown"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { Button } from "~/components/ui/button"; import ReadOnlySourcePreview from "./ReadOnlySourcePreview"; import DocumentPages from "./DocumentPages"; @@ -11,24 +11,7 @@ import { FileSurfaceNotice } from "./fileSurfaceChrome"; import type { OfficeWorkerResult } from "./officePreviewProtocol"; // Saved notebooks must not load URLs or turn authored links into app actions. -function inertNotebookMarkdown() { - function clean(nodes: RootContent[]): RootContent[] { - return nodes.flatMap((node): RootContent[] => { - if (node.type === "html" || node.type === "definition") return []; - if (node.type === "image" || node.type === "imageReference") - return [{ type: "text", value: node.alt ?? "" }]; - if (node.type === "link" || node.type === "linkReference") return clean(node.children); - if (node.type === "inlineCode") return [{ type: "text", value: node.value }]; - if (node.type === "code" && node.lang === "mermaid") return [{ ...node, lang: "text" }]; - if ("children" in node) node.children = clean(node.children) as typeof node.children; - return [node]; - }); - } - return (tree: Root) => { - tree.children = clean(tree.children) as Root["children"]; - }; -} -const NOTEBOOK_PLUGINS = [inertNotebookMarkdown]; +const NOTEBOOK_MARKDOWN: MarkdownExtensions = { inert: true }; function NotebookSource(props: { readonly name: string; readonly text: string }) { const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16)); @@ -129,7 +112,7 @@ export default function NotebookPreview(props: { text={cell.source} cwd={undefined} parseRawHtml={false} - extraRemarkPlugins={NOTEBOOK_PLUGINS} + extensions={NOTEBOOK_MARKDOWN} className="px-4 py-3" /> ) : cell.source.trim() ? ( diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1e0fa7680c405..cbf9de56dbbb2 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -112,7 +112,7 @@ import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState"; import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab"; import { openOnHostLabel } from "./pullRequestLinkContextMenu"; import { PullRequestMarkdownContext } from "./PullRequestMarkdown"; -import { pullRequestMarkdownPlugins } from "./pullRequestMarkdown.logic"; +import { pullRequestMarkdownExtensions } from "./pullRequestMarkdown.logic"; import { PullRequestComposer } from "./PullRequestComposer"; import { PullRequestSummaryTab } from "./PullRequestSummaryTab"; import { PullRequestTimelineTab } from "./PullRequestTimelineTab"; @@ -298,7 +298,7 @@ function pullRequestMarkdownContext( threadRef: ScopedThreadRef | null, ) { return { - remarkPlugins: pullRequestMarkdownPlugins(detail), + extensions: pullRequestMarkdownExtensions(detail), lineBreaks: sourceControlClients.find(detail?.provider ?? "")?.hardLineBreaks ?? false, threadRef, repository: detail?.repository ?? null, diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx index fae5270d27123..f1cd6b6ba6708 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx @@ -24,7 +24,7 @@ async function renderBody( ) { const { repository = null, text = "first line\nsecond line", ...props } = options; const context = { - remarkPlugins: [], + extensions: {}, lineBreaks: sourceControlClients.get(host).hardLineBreaks ?? false, threadRef: null, repository, diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx index 071e8dbe45d17..82012eae8f0a7 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx @@ -9,7 +9,7 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import { createContext, useContext } from "react"; -import type { PluggableList } from "unified"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; import { cn } from "~/lib/utils"; @@ -21,7 +21,7 @@ import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequest export const PullRequestMarkdownContext = createContext<{ /** Stable per repository, so comments share one renderer and its parse cache. */ - remarkPlugins: PluggableList; + extensions: MarkdownExtensions; lineBreaks: boolean; threadRef: ScopedThreadRef | null; /** The change request's `owner/name`, which can differ from the checkout the body renders in. */ @@ -129,7 +129,7 @@ function PullRequestBodySegmentView({ threadRef={threadRef} pullRequestPanelRef={threadRef ?? listPanelRef} environmentId={environmentId} - {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})} + {...(context ? { extensions: context.extensions } : {})} lineBreaks={lineBreaks} sourceControlMedia sourceControlMediaRepository={repository} diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index dd4cf2f811c72..1f409d282ecc3 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -87,7 +87,7 @@ import { startDescriptionSave, type DescriptionDraft, } from "@t3tools/client-runtime/pull-request-editing"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { PullRequestMarkdown } from "./PullRequestMarkdown"; import { PullRequestCommentBody } from "./PullRequestCommentBody"; import { PullRequestMoreReplies } from "./PullRequestMoreReplies"; diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 4f25b26f3276e..3d0ae22b15017 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -1280,6 +1280,15 @@ describe("adding a remark to the chat", () => { }); expect(context?.text).toBe("octocat: This leaks the token.\n\n```html\n\n```"); + // A stray backtick before the comment opens no code span across the paragraphs. + const stray = buildPullRequestCommentContext(pullRequest, { + kind: "comment", + comment: remark( + "c2", + "Avoid `foo.\n\n\nSee `bar` and `` a ` ``.", + ), + }); + expect(stray?.text).toBe("octocat: Avoid `foo.\n\nSee `bar` and `` a ` ``."); }); it("keeps comments inside a quoted fence as code", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index 238038730b93f..d98ec3ff114ec 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -5,8 +5,9 @@ import { resolvePullRequestReviewAnchor, } from "@t3tools/shared/pullRequestAnchor"; import { stripInlineContextReferences } from "~/lib/composerContextReferences"; -import type { Nodes as MdastNodes } from "mdast"; -import { fromMarkdown } from "mdast-util-from-markdown"; +import type { Nodes } from "hast"; + +import { markdownHtmlComments, markdownTree } from "~/markdown/wordsHast"; import { sourceControlClients, type ChangeRequestTerminology, @@ -693,27 +694,18 @@ export function pagePullRequestConversationItems( function readableBody(raw: string): string | null { if (visibleBody(raw) === null) return null; const body = raw.replace(/\r\n?/gu, "\n"); - const cuts: Array<[number, number]> = []; - const visit = (node: MdastNodes) => { - if (node.type === "html" && node.position?.start.offset !== undefined) { - cuts.push([node.position.start.offset, node.position.end.offset ?? body.length]); - } - if ("children" in node) for (const child of node.children) visit(child); - }; - visit(fromMarkdown(body)); let readable = ""; let from = 0; - for (const [start, end] of cuts) { + for (const { start, end } of markdownHtmlComments(body)) { + // A comment opened inside another one ends with it. + if (start < from) continue; readable += body.slice(from, start); - // An HTML block can carry markup around its comment; only the comment itself is hidden. - const html = body.slice(start, end).replace(/|$)/gu, ""); // A line that was all comment is dropped rather than left as a blank one. const ownLine = /(?:^|\n)[ \t>]*$/u.test(readable) && /^[ \t]*(?:\n|$)/u.test(body.slice(end)); - if (ownLine && html.trim() === "") { + if (ownLine) { readable = readable.replace(/[ \t>]*$/u, ""); from = end + (/^[ \t]*\n/u.exec(body.slice(end))?.[0].length ?? 0); } else { - readable += html; from = end; } } @@ -740,11 +732,12 @@ const LINK_EXCERPT_LENGTH = 280; /** The words of a markdown body, without markup, HTML or images, for a short preview. */ function markdownExcerpt(body: string): string | null { const words: string[] = []; - const visit = (node: MdastNodes) => { - if (node.type === "text" || node.type === "inlineCode") words.push(node.value); - if (node.type !== "code" && "children" in node) for (const child of node.children) visit(child); + const visit = (node: Nodes) => { + if (node.type === "text") words.push(node.value); + if (node.type === "element" && node.tagName === "pre") return; + if ("children" in node) for (const child of node.children) visit(child); }; - visit(fromMarkdown(body)); + visit(markdownTree(body, { skipHtml: true })); // GitHub's alert marker (`> [!NOTE]`) parses as text but reads as markup. const text = words .join(" ") diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts index 1655427b2d4e9..7c4ffac84b8a5 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts @@ -1,45 +1,44 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Element, Root } from "hast"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { pullRequestCommentPreview, - pullRequestMarkdownPlugins, - remarkPullRequestAutolinks, + pullRequestMarkdownExtensions, } from "./pullRequestMarkdown.logic"; -type Node = { - type: string; - value?: string; - url?: string; - data?: { hProperties?: Record }; - children?: Node[]; -}; - function links(markdown: string) { - const autolinks = changeRequestReferenceAutolinker({ + const extensions = pullRequestMarkdownExtensions({ provider: "github", url: "https://github.com/team/repo/pull/8", - })!; - const tree = unified().use(remarkParse).parse(markdown) as Node; - remarkPullRequestAutolinks({ autolinks })(tree as never); - const found: Array<[string | undefined, string | undefined, unknown]> = []; - const visit = (node: Node) => { - if (node.type === "link") { - found.push([ - node.children?.[0]?.value, - node.url, - node.data?.hProperties?.["dataPullRequestAutolink"], - ]); + }); + const tree = wordsHast(markdown, { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const found: Array<[string, unknown, unknown]> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "a") { + const label = child.children[0]; + found.push([ + label?.type === "text" ? label.value : "", + child.properties.href, + child.properties.dataPullRequestAutolink, + ]); + } + visit(child); } - node.children?.forEach(visit); }; visit(tree); return found; } -describe("remarkPullRequestAutolinks", () => { +describe("pullRequestMarkdownExtensions", () => { it("links the host's references in prose and leaves links and code alone", () => { expect(links("Fixes #12 in **abcdef1**. [#13](https://example.com) `#14`")).toEqual([ ["#12", "https://github.com/team/repo/issues/12", "reference"], @@ -47,22 +46,25 @@ describe("remarkPullRequestAutolinks", () => { ["#13", "https://example.com", undefined], ]); }); -}); - -describe("pullRequestMarkdownPlugins", () => { it("renders GitHub emoji shortcodes in prose and leaves code literal", () => { - const processor = unified() - .use(remarkParse) - .use( - pullRequestMarkdownPlugins({ - provider: "github", - url: "https://github.com/team/repo/pull/8", - }), - ); - const tree = processor.runSync(processor.parse("Ship it :tada: :+1: `:tada:`")) as Node; - const text = (node: Node): string => - (node.type === "inlineCode" ? `\`${node.value}\`` : (node.value ?? "")) + - (node.children ?? []).map(text).join(""); + const extensions = pullRequestMarkdownExtensions({ + provider: "github", + url: "https://github.com/team/repo/pull/8", + }); + const tree = wordsHast("Ship it :tada: :+1: `:tada:`", { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const text = (node: Root | Element | Root["children"][number]): string => { + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "code") { + return `\`${node.children.map(text).join("")}\``; + } + return "children" in node ? node.children.map(text).join("") : ""; + }; expect(text(tree)).toBe("Ship it 🎉 👍 `:tada:`"); }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts index 21f3574838e06..560b6ee03fd37 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts @@ -1,130 +1,63 @@ -import { - changeRequestReferenceAutolinker, - expandGithubEmojiAliases, - resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; -import { - sourceControlClients, - type ReferenceAutolink, -} from "@t3tools/client-runtime/source-control-clients"; -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import type { Nodes } from "hast"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { unified, type PluggableList } from "unified"; -export { - splitPullRequestBody, +import { + splitPullRequestBody as splitBody, type PullRequestBodySegment, } from "@t3tools/client-runtime/pull-request-markdown"; +import { + markdownReferenceDefinitions, + wordsHast, + type MarkdownExtensions, +} from "~/markdown/wordsHast"; -type MarkdownNode = { - type: string; - value?: string; - children?: MarkdownNode[]; - url?: string; - data?: unknown; -}; - -const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]); - -export function remarkPullRequestAutolinks(options: { - readonly autolinks: (text: string) => ReadonlyArray; -}) { - const visit = (node: MarkdownNode): void => { - const children = node.children; - if (children === undefined) return; - for (let index = 0; index < children.length; index += 1) { - const child = children[index]!; - if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue; - if (child.type !== "text" || child.value === undefined) { - visit(child); - continue; - } - const value = child.value; - const links = options.autolinks(value); - if (links.length === 0) continue; - const replacements: MarkdownNode[] = []; - let start = 0; - for (const link of links) { - if (start < link.index) { - replacements.push({ type: "text", value: value.slice(start, link.index) }); - } - replacements.push({ - type: "link", - url: link.url, - data: { hProperties: { dataPullRequestAutolink: link.kind } }, - children: [{ type: "text", value: link.label }], - }); - start = link.index + link.text.length; - } - if (start < value.length) replacements.push({ type: "text", value: value.slice(start) }); - children.splice(index, 1, ...replacements); - index += replacements.length - 1; - } - }; - return (tree: MarkdownNode) => visit(tree); -} +export type { PullRequestBodySegment }; -function remarkChangeRequestMediaUrls(options: { readonly changeRequestUrl: string }) { - const visit = (node: MarkdownNode): void => { - if ((node.type === "image" || node.type === "definition") && node.url !== undefined) { - node.url = resolveChangeRequestMediaUrl(node.url, options.changeRequestUrl); - } - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); +export function splitPullRequestBody(body: string): ReadonlyArray { + return splitBody(body, markdownReferenceDefinitions); } -/** GitHub renders `:alias:` emoji in prose; code keeps them, being `inlineCode`/`code`, not `text`. */ -function remarkGithubEmoji() { - const visit = (node: MarkdownNode): void => { - if (node.type === "text" && node.value !== undefined) - node.value = expandGithubEmojiAliases(node.value); - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); -} - -const NO_PLUGINS: PluggableList = []; -const markdownPlugins = new Map(); +const NO_EXTENSIONS: MarkdownExtensions = {}; +const markdownExtensions = new Map(); /** - * One plugin list per repository, so every comment of a pull request shares one markdown + * One extension object per repository, so every comment of a pull request shares one markdown * renderer and its parse cache instead of parsing again on each render. */ -export function pullRequestMarkdownPlugins( +export function pullRequestMarkdownExtensions( changeRequest: { readonly provider: string; readonly url: string } | null, -): PluggableList { - if (changeRequest === null) return NO_PLUGINS; +): MarkdownExtensions { + if (changeRequest === null) return NO_EXTENSIONS; const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link .repositoryUrl; - if (repositoryUrl === undefined) return NO_PLUGINS; + if (repositoryUrl === undefined) return NO_EXTENSIONS; const key = `${changeRequest.provider}\u0000${repositoryUrl}`; - let plugins = markdownPlugins.get(key); - if (plugins === undefined) { - const autolinks = changeRequestReferenceAutolinker(changeRequest); - plugins = [[remarkChangeRequestMediaUrls, { changeRequestUrl: repositoryUrl }]]; - if (changeRequest.provider === "github") plugins.push(remarkGithubEmoji); - if (autolinks) plugins.push([remarkPullRequestAutolinks, { autolinks }]); - markdownPlugins.set(key, plugins); + let extensions = markdownExtensions.get(key); + if (extensions === undefined) { + extensions = { + changeRequest: { + repositoryUrl, + autolinks: changeRequestReferenceAutolinker(changeRequest), + }, + githubEmoji: changeRequest.provider === "github", + }; + markdownExtensions.set(key, extensions); } - return plugins; + return extensions; } -const commentPreviewProcessor = (plugins: PluggableList) => - unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(plugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(CHAT_MARKDOWN_REHYPE_PLUGINS) - .freeze(); -const commentPreview = commentPreviewProcessor(NO_PLUGINS); -const githubCommentPreview = commentPreviewProcessor([remarkGithubEmoji]); +const PREVIEW_MARKDOWN = { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions: NO_EXTENSIONS, +}; +const GITHUB_PREVIEW_MARKDOWN = { + ...PREVIEW_MARKDOWN, + extensions: { githubEmoji: true }, +}; const PREVIEW_BLOCK_TAGS = new Set([ "blockquote", @@ -164,7 +97,6 @@ function commentPreviewText(node: Nodes): string { } export function pullRequestCommentPreview(body: string, provider: string): string { - const processor = provider === "github" ? githubCommentPreview : commentPreview; - const tree = processor.runSync(processor.parse(body), body); - return commentPreviewText(tree).replace(/\s+/gu, " ").trim(); + const options = provider === "github" ? GITHUB_PREVIEW_MARKDOWN : PREVIEW_MARKDOWN; + return commentPreviewText(wordsHast(body, options)).replace(/\s+/gu, " ").trim(); } diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx index b5eddbcc10df8..f859695e3360d 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx @@ -11,10 +11,6 @@ import { VoiceSettingsPanel } from "./VoiceSettingsPanel"; import { SettingsScopeProvider } from "./SettingsScopeContext"; vi.mock(import("../../state/session"), { spy: true }); -vi.mock("../../env", async (original) => ({ - ...(await original()), - isSecretsFeatureEnabled: true, -})); vi.mock("../../state/environments", async (importOriginal) => ({ ...(await importOriginal()), useEnvironments: () => ({ @@ -24,6 +20,7 @@ vi.mock("../../state/environments", async (importOriginal) => ({ label: "Laptop", connection: { phase: "available" }, serverConfig: { + featureFlags: { secretProviders: true }, secretReferences: true, settings: { secretProviders: { diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 90c93009d4634..0a992f4f93b61 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -1,6 +1,7 @@ import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; import type { PreparedConnection } from "@t3tools/client-runtime/connection"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { configuredSecretSources, secretRequestReference, @@ -31,7 +32,6 @@ import type { HttpClient } from "effect/http"; import { Atom, AsyncResult } from "effect/reactivity"; import { useId, useState } from "react"; import { T, useGT, useMessages, Var } from "gt-react"; -import { isSecretsFeatureEnabled } from "../../env"; import { inEnvironmentSpeechRuntime, runEnvironmentSpeech, @@ -194,7 +194,8 @@ export function CloudVoiceConfiguration({ const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined; const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider]; const sources = - isSecretsFeatureEnabled && environment.serverConfig?.secretReferences + hasFeatureFlag(environment.serverConfig, "secretProviders") && + environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) : []; const reference = diff --git a/apps/web/src/components/settings/SecretSourceInput.tsx b/apps/web/src/components/settings/SecretSourceInput.tsx index 35b7218a63f03..53263c226d2f0 100644 --- a/apps/web/src/components/settings/SecretSourceInput.tsx +++ b/apps/web/src/components/settings/SecretSourceInput.tsx @@ -7,6 +7,7 @@ import { } from "@t3tools/contracts"; import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry"; import { invalidSecretReferenceText } from "@t3tools/client-runtime/secret-request"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { useAtomValue } from "@effect/atom-react"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -14,7 +15,6 @@ import { useGT, useMessages } from "gt-react"; import { AlertTriangleIcon, CheckIcon, KeyRoundIcon, RefreshCwIcon, TypeIcon } from "lucide-react"; import { useState, type ComponentProps, type ComponentType, type ReactNode } from "react"; -import { isSecretsFeatureEnabled } from "../../env"; import { useEnvironmentSettings } from "../../hooks/useSettings"; import { OnePasswordIcon } from "../Icons"; import { serverEnvironment } from "../../state/server"; @@ -42,9 +42,9 @@ export function useSecretSources(environmentId: EnvironmentId): ReadonlyArray settings.secretProviders); const supported = useAtomValue( serverEnvironment.configValueAtom(environmentId), - (config) => config?.secretReferences === true, + (config) => hasFeatureFlag(config, "secretProviders") && config?.secretReferences === true, ); - if (!isSecretsFeatureEnabled || !supported) return NO_SECRET_SOURCES; + if (!supported) return NO_SECRET_SOURCES; return (Object.entries(providers) as Array<[SecretProviderId, SecretProviderConfig]>) .filter(([, config]) => classifySecretProvider(config).kind !== "unsupported") .map(([id, config]) => ({ id, kind: config.kind, label: config.label })); diff --git a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx index 3457bc2467820..338c4ff0fa111 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx @@ -4,12 +4,13 @@ import { page, userEvent } from "vite-plus/test/browser"; import { act, render } from "../../../test/render"; import { SidebarProvider } from "../ui/sidebar"; import { SettingsSidebarNav } from "./SettingsSidebarNav"; -import { SETTINGS_NAV_GROUPS, SETTINGS_SECTION_LABELS } from "./settingsSearch"; +import { settingsNavGroups, SETTINGS_SECTION_LABELS } from "./settingsSearch"; vi.mock("./useAvailableSettingsSearchItems", () => ({ useAvailableSettingsSearchItems: () => [ { id: "theme", title: "Theme", to: "/settings/appearance" }, ], + useHasSecretProvidersEnvironment: () => false, })); it("ignores composing keys in the search", async () => { @@ -76,9 +77,9 @@ it("moves Tab through every settings section", async () => { await using _screen = await renderNav(); await userEvent.click(page.getByRole("combobox", { name: "Search settings" })); - const sections = SETTINGS_NAV_GROUPS.flatMap((group) => group.paths).map( - (to) => SETTINGS_SECTION_LABELS[to], - ); + const sections = settingsNavGroups(false) + .flatMap((group) => group.paths) + .map((to) => SETTINGS_SECTION_LABELS[to]); const tabbed: string[] = []; for (let step = 0; step < sections.length; step += 1) { await userEvent.tab(); @@ -103,7 +104,7 @@ it.each([1280, 390])("names each group by a heading outside it at %ipx wide", as ); } const groups = page.getByRole("group").elements(); - expect(groups).toHaveLength(SETTINGS_NAV_GROUPS.length); + expect(groups).toHaveLength(settingsNavGroups(false).length); for (const group of groups) { const first = group.querySelector("[data-settings-section]")?.textContent; const heading = document.getElementById(group.getAttribute("aria-labelledby") ?? ""); diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 794574d9505b4..10bc07c123dd8 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -53,13 +53,16 @@ import { scrollToSettingsTarget } from "./settingsLayout"; import { searchSettings, revealSettingsSearchTarget, - SETTINGS_NAV_GROUPS, + settingsNavGroups, SETTINGS_NAV_LABELS, SETTINGS_SECTION_LABELS, type SettingsPath, type SettingsSearchItem, } from "./settingsSearch"; -import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems"; +import { + useAvailableSettingsSearchItems, + useHasSecretProvidersEnvironment, +} from "./useAvailableSettingsSearchItems"; import { handleSettingsSectionKeyDown } from "./settingsSectionNavigation"; import { workspaceAreaProps } from "../../lib/workspaceFocus"; @@ -143,6 +146,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { const [compactSearchOpen, setCompactSearchOpen] = useState(false); const [activeResultIndex, setActiveResultIndex] = useState(0); const searchableItems = useAvailableSettingsSearchItems(); + const navGroups = settingsNavGroups(useHasSecretProvidersEnvironment()); const results = searchSettings(query, searchableItems, m); const isSearching = query.trim().length > 0; const hasResults = results.length > 0; @@ -379,7 +383,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { )}
- {SETTINGS_NAV_GROUPS.map((group, index) => ( + {navGroups.map((group, index) => (
({ - ...(await importOriginal()), - isSecretsFeatureEnabled: false, -})); - const ITEMS: ReadonlyArray = [ { id: "word-wrap", @@ -76,9 +71,27 @@ describe("searchSettings", () => { } }); - it("hides the Secrets page from nav and search while the secrets feature is disabled", () => { - expect(SETTINGS_NAV_GROUPS.flatMap((group) => group.paths)).not.toContain("/settings/secrets"); - expect(searchSettings("1password").map((item) => item.to)).not.toContain("/settings/secrets"); + it("shows the Secrets page in nav and search only when an environment enables secret providers", () => { + const availability = { + hasCloudPublicConfig: false, + hasEnvironment: true, + hasProviderSettingsEnvironment: true, + canManageLocalBackend: false, + isWslSettingsRowVisible: false, + hasThreadAutoSettlement: false, + }; + for (const enabled of [false, true]) { + const navPaths = settingsNavGroups(enabled).flatMap((group) => group.paths); + const searchPaths = searchSettings( + "1password", + filterAvailableSettingsSearchItems({ + ...availability, + hasSecretProvidersEnvironment: enabled, + }), + ).map((item) => item.to); + expect(navPaths.includes("/settings/secrets")).toBe(enabled); + expect(searchPaths.includes("/settings/secrets")).toBe(enabled); + } }); it("finds where subagents and side chats open by any of its names", () => { diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 922fccdd56497..5fbe163fbf6a9 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1,5 +1,5 @@ import { HOSTED_APP_CHANNEL } from "~/branding"; -import { isElectron, isSecretsFeatureEnabled } from "~/env"; +import { isElectron } from "~/env"; import { isMacPlatform, isWindowsPlatform, normalizeSearchText } from "~/lib/utils"; import { STATIC_KEYBINDING_COMMANDS, type KeybindingCommand } from "@t3tools/contracts"; import type { EnvironmentId } from "@t3tools/contracts"; @@ -61,7 +61,7 @@ export interface SettingsSearchItem { readonly macOnly?: boolean; readonly windowsOnly?: boolean; readonly releaseChannelOnly?: boolean; - readonly secretsFeatureOnly?: boolean; + readonly secretProvidersOnly?: boolean; readonly cloudOnly?: boolean; readonly environmentOnly?: boolean; readonly providerSettingsOnly?: boolean; @@ -91,6 +91,7 @@ export interface SettingsSearchAvailability { /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; + readonly hasSecretProvidersEnvironment?: boolean; } export const SETTINGS_SECTION_LABELS: Readonly> = { @@ -128,12 +129,14 @@ export const SETTINGS_NAV_LABELS: Readonly> = { "/settings/access": msg("Sharing & access", { $context: "settings navigation item" }), }; -/** Sidebar order. A group with a hidden heading is set apart on screen by space alone. */ -export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ +type SettingsNavGroup = { readonly heading: string; readonly headingHidden?: true; readonly paths: ReadonlyArray; -}> = [ +}; + +/** Sidebar order. A group with a hidden heading is set apart on screen by space alone. */ +const ALL_SETTINGS_NAV_GROUPS: ReadonlyArray = [ { heading: msg("Preferences"), headingHidden: true, @@ -163,11 +166,7 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ }, { heading: msg("Connections"), - paths: [ - "/settings/connections", - "/settings/access", - ...(isSecretsFeatureEnabled ? (["/settings/secrets"] as const) : []), - ], + paths: ["/settings/connections", "/settings/access", "/settings/secrets"], }, { heading: msg("More"), @@ -176,6 +175,18 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ }, ]; +const SETTINGS_NAV_GROUPS_WITHOUT_SECRETS = ALL_SETTINGS_NAV_GROUPS.map((group) => ({ + ...group, + paths: group.paths.filter((path) => path !== "/settings/secrets"), +})); + +/** Sidebar groups; Secrets shows only when some environment's server enables secret providers. */ +export function settingsNavGroups(hasSecretProvidersEnvironment: boolean) { + return hasSecretProvidersEnvironment + ? ALL_SETTINGS_NAV_GROUPS + : SETTINGS_NAV_GROUPS_WITHOUT_SECRETS; +} + export function keybindingSearchAnchorId(command: Command) { return `keybinding-${command}` as const; } @@ -511,6 +522,7 @@ export const SETTINGS_SEARCH_ITEMS = [ targetId: "boring-sidebar", searchTerms: [msg("beta boring sidebar folder rows multiline branch pull request details")], }, + { id: "tool-call-visibility", title: msg("Tool calls in chat"), @@ -1480,7 +1492,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Secret providers"), to: "/settings/secrets", searchTerms: [msg("1password vault credentials api key")], - secretsFeatureOnly: true, + secretProvidersOnly: true, }, { id: "secret-providers-add", @@ -1488,7 +1500,7 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/secrets", targetId: "secret-providers", searchTerms: [msg("new 1password vault op cli account")], - secretsFeatureOnly: true, + secretProvidersOnly: true, }, { id: "archive", @@ -1661,7 +1673,8 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && - (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true), + (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && + (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true), ); } @@ -1674,7 +1687,6 @@ export function settingsForThisPlatform( (item) => (isElectron || item.desktopOnly !== true) && (!item.releaseChannelOnly || isElectron || HOSTED_APP_CHANNEL !== null) && - (!item.secretsFeatureOnly || isSecretsFeatureEnabled) && (!item.macOnly || isMacPlatform(platform)) && (!item.windowsOnly || isWindowsPlatform(platform)), ); diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index e6d947935bd94..beb5e3c85c52c 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -1,4 +1,5 @@ import { useMessages } from "gt-react"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { AuthEnvironmentMaintainScope } from "@t3tools/contracts"; import { usePrimaryCloudLinkState } from "~/cloud/cloudLinkState"; @@ -17,6 +18,14 @@ import { getThreadAutoSettlementSearchAvailability, } from "./settingsSearch"; +/** Any environment whose server enables secret providers; gates the Secrets page, nav and search. */ +export function useHasSecretProvidersEnvironment() { + const { environments } = useEnvironments(); + return environments.some((environment) => + hasFeatureFlag(environment.serverConfig, "secretProviders"), + ); +} + export function useAvailableSettingsSearchItems() { const { environments } = useEnvironments(); // Explicit booleans keep flags out of the filter cache so environment updates do not rebuild the list. @@ -42,6 +51,7 @@ export function useAvailableSettingsSearchItems() { environment.serverConfig !== null && environment.serverConfig.managedPolicy?.limits?.providers?.allowedDrivers === undefined, ) === true; + const hasSecretProvidersEnvironment = useHasSecretProvidersEnvironment(); const hasThreadAutoSettlement = getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0; const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -75,5 +85,6 @@ export function useAvailableSettingsSearchItems() { hasFastWorktreeCheckoutEnvironment, hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, + hasSecretProvidersEnvironment, }); } diff --git a/apps/web/src/components/ui/shared-tooltip.tsx b/apps/web/src/components/ui/shared-tooltip.tsx new file mode 100644 index 0000000000000..0858fa656e6bb --- /dev/null +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -0,0 +1,262 @@ +import { + cloneElement, + createContext, + use, + useEffect, + useId, + useRef, + useState, + type FocusEvent, + type PointerEvent, + type ReactElement, + type ReactNode, +} from "react"; + +import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; + +// Base UI's tooltip timing: open after a rest, reopen at once right after another closed. +const OPEN_DELAY_MS = 600; +const REOPEN_WINDOW_MS = 400; +// Time to travel from the trigger into a hoverable popup. +const CLOSE_GRACE_MS = 100; + +interface SharedTooltipContent { + readonly render: () => ReactNode; + /** Comparable key that changes whenever `render()` output changes while open. */ + readonly contentKey?: unknown; + readonly side?: "top" | "bottom" | "left" | "right"; + readonly variant?: "default" | "glass" | "code"; +} + +interface SharedTooltipState extends SharedTooltipContent { + readonly anchor: HTMLElement; + readonly open: boolean; +} + +interface SharedTooltipApi { + show(anchor: HTMLElement, content: SharedTooltipContent, immediate: boolean): void; + refresh(anchor: HTMLElement, content: SharedTooltipContent): void; + hide(anchor: HTMLElement): void; + /** A press closes it at once, as Base UI's closeOnClick does. */ + dismiss(anchor: HTMLElement): void; + holdOpen(): void; +} + +function setAriaDescribedBy(element: HTMLElement, id: string, present: boolean) { + const tokens = (element.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean); + const next = present + ? tokens.includes(id) + ? tokens + : [...tokens, id] + : tokens.filter((token) => token !== id); + if (next.length > 0) element.setAttribute("aria-describedby", next.join(" ")); + else element.removeAttribute("aria-describedby"); +} + +const SharedTooltipContext = createContext(null); + +/** + * One tooltip for many triggers: a long message would otherwise mount a Base UI tooltip per + * link and file chip, and almost none of them are ever hovered. + */ +export function SharedTooltipProvider({ children }: { children: ReactNode }) { + const popupId = useId(); + const [state, setState] = useState(null); + const timer = useRef | null>(null); + const pending = useRef(null); + const lastClosedAt = useRef(0); + const current = useRef(null); + + const commit = (next: SharedTooltipState | null) => { + current.current = next; + setState(next); + }; + const clearTimer = () => { + if (timer.current !== null) clearTimeout(timer.current); + timer.current = null; + pending.current = null; + }; + const [api] = useState(() => ({ + show(anchor, content, immediate) { + clearTimer(); + const open = current.current?.open === true; + const reopen = performance.now() - lastClosedAt.current < REOPEN_WINDOW_MS; + if (immediate || open || reopen) { + commit({ ...content, anchor, open: true }); + return; + } + pending.current = { ...content, anchor, open: true }; + timer.current = setTimeout(() => { + const next = pending.current; + pending.current = null; + if (next) commit(next); + }, OPEN_DELAY_MS); + }, + refresh(anchor, content) { + if (pending.current?.anchor === anchor) { + pending.current = { ...pending.current, ...content }; + } + const active = current.current; + if (!active || active.anchor !== anchor) return; + if ( + active.contentKey === content.contentKey && + active.side === content.side && + active.variant === content.variant + ) { + return; + } + commit({ ...active, ...content }); + }, + hide(anchor) { + if (current.current && current.current.anchor !== anchor) { + clearTimer(); + return; + } + clearTimer(); + timer.current = setTimeout(() => { + if (current.current?.open) lastClosedAt.current = performance.now(); + if (current.current) commit({ ...current.current, open: false }); + }, CLOSE_GRACE_MS); + }, + dismiss(anchor) { + clearTimer(); + if (current.current?.anchor !== anchor) return; + if (current.current.open) lastClosedAt.current = 0; + commit({ ...current.current, open: false }); + }, + holdOpen() { + clearTimer(); + }, + })); + + const activeAnchor = state?.open ? state.anchor : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links the active trigger DOM element to the shared tooltip popup via aria-describedby + useEffect(() => { + if (!activeAnchor) return; + setAriaDescribedBy(activeAnchor, popupId, true); + return () => setAriaDescribedBy(activeAnchor, popupId, false); + }, [activeAnchor, popupId]); + + return ( + + {children} + {state ? ( + { + if (!open) api.hide(state.anchor); + }} + > + api.holdOpen()} + onMouseLeave={() => api.hide(state.anchor)} + > + {state.render()} + + + ) : null} + + ); +} + +export interface SharedTooltipTriggerProps { + onPointerEnter: (event: PointerEvent) => void; + onPointerLeave: (event: PointerEvent) => void; + onFocus: (event: FocusEvent) => void; + onBlur: (event: FocusEvent) => void; + onPointerDown: (event: PointerEvent) => void; +} + +/** Props that show `content` on the shared tooltip, or null outside a SharedTooltipProvider. */ +export function useSharedTooltip(content: SharedTooltipContent): SharedTooltipTriggerProps | null { + const api = use(SharedTooltipContext); + const scrollTracker = useTooltipScrollTracker(); + const anchorRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes an open shared tooltip when its trigger's label changes + useEffect(() => { + if (api && anchorRef.current) api.refresh(anchorRef.current, content); + }, [api, content]); + if (!api) return null; + return { + // Touch never opens it, as Base UI's mouseOnly trigger; taps also send compatibility mouse events. + onPointerEnter: (event) => { + if (event.pointerType === "touch") return; + const trigger = event.currentTarget; + anchorRef.current = trigger; + api.show(trigger, content, false); + // Scrolling the timeline closes it, as it does a TooltipTrigger's. + scrollTracker?.hover(trigger, api, () => api.dismiss(trigger)); + }, + onPointerLeave: (event) => api.hide(event.currentTarget), + // Keyboard focus shows it at once, as Base UI does. + onFocus: (event) => { + if (event.currentTarget.matches(":focus-visible")) { + anchorRef.current = event.currentTarget; + api.show(event.currentTarget, content, true); + } + }, + onBlur: (event) => api.hide(event.currentTarget), + onPointerDown: (event) => api.dismiss(event.currentTarget), + }; +} + +type Handlers = Partial void>>; + +/** The trigger's own handlers run first, then the shared tooltip's. */ +export function withSharedTooltip( + element: ReactElement, + tooltip: SharedTooltipTriggerProps, + children?: ReactNode, +): ReactElement { + const own = element.props as Handlers; + const merged: Record void> = {}; + for (const key of Object.keys(tooltip) as Array) { + const shared = tooltip[key] as (event: never) => void; + const mine = own[key]; + merged[key] = mine + ? (event) => { + mine(event); + shared(event); + } + : shared; + } + return children === undefined + ? cloneElement(element, merged as Partial) + : cloneElement(element, merged as Partial, children); +} + +/** A tooltip on `render`: the shared one inside a SharedTooltipProvider, Base UI's otherwise. */ +export function SharedTooltipTrigger({ + render, + children, + label, + side = "top", + variant, +}: { + render: ReactElement; + children?: ReactNode; + label: ReactNode; + side?: SharedTooltipContent["side"]; + variant?: SharedTooltipContent["variant"]; +}) { + const tooltip = useSharedTooltip({ + render: () => label, + contentKey: label, + side, + ...(variant ? { variant } : {}), + }); + if (tooltip) return withSharedTooltip(render, tooltip, children); + return ( + + {children} + + {label} + + + ); +} diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index 24d76784e8a5a..bcb62ee2fdaf0 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -3,41 +3,114 @@ import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./shared-tooltip"; import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "./tooltip"; +function TimelineAction({ shared }: { shared: boolean }) { + if (shared) { + return ( + + }> + Timeline action + + + ); + } + return ( + + Timeline action + Description + + ); +} + it.each([ - { focus: "mouse", keptOpen: false }, - { focus: "keyboard", keptOpen: true }, -])("scrolling with a $focus-focused hovered trigger keeps it open: $keptOpen", async (c) => { - const onScroll = vi.fn(); + { shared: false, focus: "mouse", keptOpen: false }, + { shared: false, focus: "keyboard", keptOpen: true }, + { shared: true, focus: "mouse", keptOpen: false }, + { shared: true, focus: "keyboard", keptOpen: true }, +])( + "scrolling with a $focus-focused hovered trigger (shared: $shared) keeps it open: $keptOpen", + async (c) => { + const onScroll = vi.fn(); + await using screen = await render( + + +
+ , + ); + const trigger = screen.getByRole("button", { name: "Timeline action" }); + if (c.focus === "mouse") { + // A press closes the tooltip; hovering again reopens it with mouse focus kept. + await userEvent.click(trigger); + await userEvent.unhover(trigger); + } else { + await userEvent.keyboard("{Tab}"); + } + await userEvent.hover(trigger); + await expect.element(trigger).toHaveFocus(); + await expect.element(page.getByText("Description")).toBeVisible(); + + // One pixel keeps the pointer over the trigger, so only the scroll can close it. + screen.getByTestId("timeline").element().scrollTop = 1; + await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + + if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); + else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); + }, +); + +it("refreshes an open shared tooltip's label and links aria-describedby on focus", async () => { await using screen = await render( - - - Timeline action - Description - -
- , + + }> + Copy + + , ); - const trigger = screen.getByRole("button", { name: "Timeline action" }); - if (c.focus === "mouse") { - // A press closes the tooltip; hovering again reopens it with mouse focus kept. - await userEvent.click(trigger); - await userEvent.unhover(trigger); - } else { - await userEvent.keyboard("{Tab}"); - } - await userEvent.hover(trigger); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.keyboard("{Tab}"); await expect.element(trigger).toHaveFocus(); - await expect.element(page.getByText("Description")).toBeVisible(); + const popup = page.getByText("Copy code"); + await expect.element(popup).toBeVisible(); + const popupId = trigger.element().getAttribute("aria-describedby"); + expect(popupId).toBeTruthy(); + expect(document.getElementById(popupId!)?.textContent).toBe("Copy code"); - screen.getByTestId("timeline").element().scrollTop = 20; - await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copied")).toBeVisible(); + + await userEvent.keyboard("{Tab}"); + await vi.waitFor(() => expect(trigger.element().getAttribute("aria-describedby")).toBeNull()); +}); - if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); - else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); +it("refreshes a pending shared tooltip if its label changes during the open delay", async () => { + await using screen = await render( + + }> + Copy + + , + ); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.hover(trigger); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copy code")).toBeVisible(); + expect(page.getByText("Copied").query()).toBeNull(); }); diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 577aa48da87fa..e47a6b8d13afe 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -21,13 +21,13 @@ type TooltipActionsRef = RefObject; // The compiler freezes context values; update hovered tooltips through calls instead of shared ref writes. function createTooltipHoverTracker() { - let hovered: { trigger: HTMLElement; actionsRef: TooltipActionsRef } | null = null; + let hovered: { trigger: HTMLElement; owner: object; close: () => void } | null = null; return { - hover(trigger: HTMLElement, actionsRef: TooltipActionsRef) { - hovered = { trigger, actionsRef }; + hover(trigger: HTMLElement, owner: object, close: () => void) { + hovered = { trigger, owner, close }; }, - release(actionsRef: TooltipActionsRef) { - if (hovered?.actionsRef === actionsRef) hovered = null; + release(owner: object) { + if (hovered?.owner === owner) hovered = null; }, dismissUnfocused() { const tooltip = hovered; @@ -37,8 +37,7 @@ function createTooltipHoverTracker() { return; } hovered = null; - // Base UI also cancels delayed hover opens through this action. - tooltip.actionsRef.current?.close(); + tooltip.close(); }, }; } @@ -96,7 +95,8 @@ function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) { {...props} onMouseEnter={(event) => { props.onMouseEnter?.(event); - tracker.hover(event.currentTarget, actionsRef); + // Base UI also cancels delayed hover opens through this action. + tracker.hover(event.currentTarget, actionsRef, () => actionsRef.current?.close()); }} /> ); @@ -161,4 +161,14 @@ function TooltipPopup({ ); } -export { TooltipProvider, Tooltip, TooltipTrigger, TooltipPopup, TooltipScrollDismissArea }; +/** The enclosing TooltipScrollDismissArea's tracker, for triggers that bypass TooltipTrigger. */ +const useTooltipScrollTracker = () => use(TooltipScrollContext); + +export { + TooltipProvider, + Tooltip, + TooltipTrigger, + TooltipPopup, + TooltipScrollDismissArea, + useTooltipScrollTracker, +}; diff --git a/apps/web/src/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/env.ts b/apps/web/src/env.ts index a0a28c5d7fd60..be2a563d736bd 100644 --- a/apps/web/src/env.ts +++ b/apps/web/src/env.ts @@ -1,6 +1,2 @@ // Preload installs desktopBridge before web code runs, so module-load detection is reliable. export const isElectron = typeof window !== "undefined" && window.desktopBridge !== undefined; - -export const isSecretsFeatureEnabled = ["1", "true"].includes( - import.meta.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", -); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index fcddeae4d8b14..89c7edca93faa 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -118,9 +118,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.", @@ -2561,10 +2561,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 +2573,7 @@ "a3178769f8308cbc": "Thread fehlgeschlagen", "89b5e8f3887812da": "Gastanfrage", "62e626804919b294": "Eingabe nötig", + "c6196d99000642b4": "Thread öffnen", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -3035,8 +3035,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 +3279,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 +3456,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", @@ -3694,7 +3698,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 +3709,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 +3987,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", @@ -12476,8 +12477,6 @@ "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", "2c4153283b647365": "Claude {account}: {session} des 5-Stunden-Fensters und {weekly} der Woche verbraucht", "0ebc6d14caaaca3b": "Last {one} · {five} · {fifteen} auf {cores} Kernen", "578c5947c810f7b9": "{percent} % ausgelastet", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e13b0869e4c40..f3cea2768559f 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -118,9 +118,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.", @@ -2560,10 +2560,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 +2572,7 @@ "a3178769f8308cbc": "Thread failed", "89b5e8f3887812da": "Guest request", "62e626804919b294": "Input needed", + "c6196d99000642b4": "Open thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "You:", "a1fbf2422c588292": "Agent:", @@ -3034,8 +3034,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 +3278,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 +3455,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", @@ -3693,7 +3697,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 +3708,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 +3985,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", @@ -12485,8 +12486,6 @@ "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", "2c4153283b647365": "Claude {account}: {session} of the 5-hour window and {weekly} of the week used", "0ebc6d14caaaca3b": "load {one} · {five} · {fifteen} on {cores} cores", "578c5947c810f7b9": "{percent}% busy", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 3962cc07a3dd2..af2941c0241e6 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -118,9 +118,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.", @@ -2560,10 +2560,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 +2572,7 @@ "a3178769f8308cbc": "El hilo falló", "89b5e8f3887812da": "Solicitud de invitado", "62e626804919b294": "Se necesita una respuesta", + "c6196d99000642b4": "Abrir hilo", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Tú:", "a1fbf2422c588292": "Agente:", @@ -3034,8 +3034,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 +3278,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 +3455,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", @@ -3693,7 +3697,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 +3708,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 +3983,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", @@ -12471,8 +12472,6 @@ "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", "2c4153283b647365": "Claude {account}: {session} de la ventana de 5 horas y {weekly} de la semana usados", "0ebc6d14caaaca3b": "carga {one} · {five} · {fifteen} en {cores} núcleos", "578c5947c810f7b9": "{percent} % ocupado", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 4f0e493c7496a..3fd389af8f1ed 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -118,9 +118,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}.", @@ -2560,10 +2560,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 +2572,7 @@ "a3178769f8308cbc": "Échec du fil", "89b5e8f3887812da": "Demande d’invité", "62e626804919b294": "Réponse requise", + "c6196d99000642b4": "Ouvrir le fil", "826cb862b4a11fb3": "{label} :", "3e597ec938e7551b": "Vous :", "a1fbf2422c588292": "Agent :", @@ -3034,8 +3034,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 +3278,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 +3455,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", @@ -3693,7 +3697,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 +3708,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 +3984,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", @@ -12476,8 +12477,6 @@ "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", "2c4153283b647365": "Claude {account} : {session} de la fenêtre de 5 heures et {weekly} de la semaine utilisés", "0ebc6d14caaaca3b": "charge {one} · {five} · {fifteen} sur {cores} cœurs", "578c5947c810f7b9": "{percent} % occupé", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index cc5633afb7e47..e3341709ef841 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -118,9 +118,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 がありません。", @@ -2558,10 +2558,9 @@ }, " にインストール" ], + "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", "5bbac0e5afeec779": "現在のスレッド", "33c7e68fca089036": "スレッド、{title}", - "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", - "c6196d99000642b4": "スレッドを開く", "34cc63390ad793cc": "スレッドを選択", "8f12309ead62e38a": "スレッドまたはプロジェクトを検索...", "2f664754d005d9a7": "アクティブなスレッドが見つかりません。", @@ -2571,6 +2570,7 @@ "a3178769f8308cbc": "スレッドが失敗しました", "89b5e8f3887812da": "ゲストのリクエスト", "62e626804919b294": "入力が必要です", + "c6196d99000642b4": "スレッドを開く", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "あなた:", "a1fbf2422c588292": "エージェント:", @@ -3032,8 +3032,8 @@ "6f85f14f35b3f547": "{provider} ({environment} 経由)", "7c59a888a062a8bd": "音声入力を記録する下書きがありません。", "62450481c00d2ef3": "下書きの環境を利用できないため、文字起こしを整形できません。", - "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "0674544195fcdc39": "元の文字起こしを追加しました。", + "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "296496693cdac0db": "t3 コマンドを利用できません。", "efbcef7bc9bbda01": "t3 コマンドの状態を読み込めませんでした。", "1bf6910332426e62": "デスクトップのネットワークアクセスを利用できません。", @@ -3276,6 +3276,7 @@ "4d493d0bda4d403d": "中断されたファイルをもう一度添付するか、削除してください", "c9cad1d84d5f1a32": "中断されたファイルをもう一度添付するか、削除してください", "536a820f2ff726da": "モデルを少なくとも 1 つ選択してください。", + "48d6389202ad6754": "準備ができたら送信", "fbafbe78b5e37966": "スレッドを再開", "bcd7eb979dd38dae": "入力欄を開いて圧縮して送信", "95ee62a0d6968b89": "メッセージを送信", @@ -3450,6 +3451,9 @@ "e778e4f446fdf873": "次のメッセージで新しいセッションが始まります", "0e2f2da4f2d94785": "エージェントはこのスレッドの以前のメッセージを参照できません。", "e1189d2e582b008d": "現在のセッションを維持", + "2bb448d605877a22": "編集または Esc でキャンセル", + "1a1f128d70c62304": "{count, plural, other {画像の準備ができたら送信}}", + "5af3ab719a9725fb": "メッセージを送信中", "461c9f865f2e9b92": "{option} オン", "f2aa17b5c620f2a4": "{option} オフ", "f59314a884aae1ff": "デフォルト", @@ -3688,7 +3692,6 @@ "7c1923203049d602": "コードをコピー", "637817e4ff79c90e": "コードブロックの操作", "ebf3a2b1e314aa5f": "ターミナルで実行", - "fe219642547fa0bf": "ターミナルで実行", "122a8512abc51180": "詳細", "58c38c65c2783c5d": "フルパス", "f37e7d36b51c5b28": "相対パスをコピー", @@ -3700,10 +3703,6 @@ "4967584e8d0fb1c2": "メディアをプレビュー", "67589dd912eacb7c": "統合ブラウザーで開く", "a3c98d4c4b24cecb": "{label} のファイルオプション", - "b4fe8a076e9fd2f8": "ディスプレイ数式", - "085d1407e8c92cce": "インライン数式", - "a2ef393fa7b48ae8": "ディスプレイ数式をスクロール", - "e94685ea5642e088": "インライン数式をスクロール", "3a04583c8500e23d": "図を表示", "16d64f650840fe06": "コードを表示", "6d329f7d3a50c7e7": "表をコピー", @@ -3975,9 +3974,11 @@ "973e99fa86d7f531": "キュー内のメッセージ {position}/{total}、未送信", "0f6087c4f53c7f17": "このメッセージでターンを開始 ({shortcut})", "adab89933af02669": "圧縮をスキップしてこのメッセージを送信 ({shortcut})", + "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", "3de4016452e8d2bd": "現在のターンに送信 ({shortcut})", "259cc9568148e8ad": "このメッセージでターンを開始", "bb7fddb812d5d29e": "圧縮をスキップしてこのメッセージを送信", + "425ab15036aec8a4": "このコマンドをキューの先頭に移動", "a5fe1ee609b29a9f": "現在のターンに送信", "2b7fd345e4f4fd6e": "キュー内のメッセージの編集をキャンセル", "47f1726bf106d2c8": "キュー内のメッセージを編集", @@ -12425,8 +12426,6 @@ "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", - "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", - "425ab15036aec8a4": "このコマンドをキューの先頭に移動", "2c4153283b647365": "Claude {account}: 5時間枠の{session}、週間枠の{weekly}を使用済み", "0ebc6d14caaaca3b": "負荷 {one} · {five} · {fifteen}({cores} コア)", "578c5947c810f7b9": "使用率 {percent}%", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 4cfaa3a1ccc27..265902a04d9c3 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -118,9 +118,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이 없습니다.", @@ -2559,10 +2559,9 @@ }, "에 설치" ], + "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", "5bbac0e5afeec779": "현재 스레드", "33c7e68fca089036": "스레드, {title}", - "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", - "c6196d99000642b4": "스레드 열기", "34cc63390ad793cc": "스레드 선택", "8f12309ead62e38a": "스레드 또는 프로젝트 검색...", "2f664754d005d9a7": "활성 스레드를 찾을 수 없습니다.", @@ -2572,6 +2571,7 @@ "a3178769f8308cbc": "스레드 실패", "89b5e8f3887812da": "게스트 요청", "62e626804919b294": "입력 필요", + "c6196d99000642b4": "스레드 열기", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "나:", "a1fbf2422c588292": "에이전트:", @@ -3033,8 +3033,8 @@ "6f85f14f35b3f547": "{environment}을(를) 통한 {provider}", "7c59a888a062a8bd": "음성 입력을 기록할 초안이 없습니다.", "62450481c00d2ef3": "초안의 환경을 사용할 수 없어 받아쓴 내용을 정리할 수 없습니다.", - "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "0674544195fcdc39": "원본 받아쓰기 내용이 추가되었습니다.", + "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "296496693cdac0db": "t3 명령을 사용할 수 없습니다.", "efbcef7bc9bbda01": "t3 명령 상태를 불러오지 못했습니다.", "1bf6910332426e62": "데스크톱 네트워크 액세스를 사용할 수 없습니다.", @@ -3277,6 +3277,7 @@ "4d493d0bda4d403d": "중단된 파일을 다시 첨부하거나 제거하세요", "c9cad1d84d5f1a32": "중단된 파일을 다시 첨부하거나 제거하세요", "536a820f2ff726da": "모델을 하나 이상 선택하세요.", + "48d6389202ad6754": "준비되면 전송", "fbafbe78b5e37966": "스레드 재개", "bcd7eb979dd38dae": "압축하고 보내려면 입력창을 여세요", "95ee62a0d6968b89": "메시지 보내기", @@ -3450,6 +3451,9 @@ "e778e4f446fdf873": "다음 메시지부터 새 세션이 시작됩니다", "0e2f2da4f2d94785": "에이전트는 이 스레드의 이전 메시지를 볼 수 없습니다.", "e1189d2e582b008d": "현재 세션 유지", + "2bb448d605877a22": "편집하거나 Esc를 눌러 취소", + "1a1f128d70c62304": "{count, plural, other {이미지가 준비되면 전송}}", + "5af3ab719a9725fb": "메시지 전송 중", "461c9f865f2e9b92": "{option} 켜짐", "f2aa17b5c620f2a4": "{option} 꺼짐", "f59314a884aae1ff": "기본값", @@ -3688,7 +3692,6 @@ "7c1923203049d602": "코드 복사", "637817e4ff79c90e": "코드 블록 작업", "ebf3a2b1e314aa5f": "터미널에서 실행", - "fe219642547fa0bf": "터미널에서 실행", "122a8512abc51180": "세부 정보", "58c38c65c2783c5d": "전체 경로", "f37e7d36b51c5b28": "상대 경로 복사", @@ -3700,10 +3703,6 @@ "4967584e8d0fb1c2": "미디어 미리 보기", "67589dd912eacb7c": "통합 브라우저에서 열기", "a3c98d4c4b24cecb": "{label} 파일 옵션", - "b4fe8a076e9fd2f8": "블록 수식", - "085d1407e8c92cce": "인라인 수식", - "a2ef393fa7b48ae8": "블록 수식 스크롤", - "e94685ea5642e088": "인라인 수식 스크롤", "3a04583c8500e23d": "다이어그램 표시", "16d64f650840fe06": "코드 표시", "6d329f7d3a50c7e7": "표 복사", @@ -3973,9 +3972,11 @@ "973e99fa86d7f531": "대기열 메시지 {total}개 중 {position}번째, 보내지 않음", "0f6087c4f53c7f17": "이 메시지로 턴 시작({shortcut})", "adab89933af02669": "압축을 건너뛰고 이 메시지 보내기({shortcut})", + "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", "3de4016452e8d2bd": "현재 턴에 보내기({shortcut})", "259cc9568148e8ad": "이 메시지로 턴 시작", "bb7fddb812d5d29e": "압축을 건너뛰고 이 메시지 보내기", + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동", "a5fe1ee609b29a9f": "현재 턴에 보내기", "2b7fd345e4f4fd6e": "대기열 메시지 편집 취소", "47f1726bf106d2c8": "대기열 메시지 편집", @@ -12420,8 +12421,6 @@ "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", - "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", - "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동", "2c4153283b647365": "Claude {account}: 5시간 창의 {session}, 주간 한도의 {weekly} 사용", "0ebc6d14caaaca3b": "부하 {one} · {five} · {fifteen} ({cores}코어)", "578c5947c810f7b9": "사용률 {percent}%", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 0af69d4bc5ae0..1387b89e7cb6b 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -118,9 +118,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.", @@ -2560,10 +2560,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 +2572,7 @@ "a3178769f8308cbc": "A thread falhou", "89b5e8f3887812da": "Pedido de convidado", "62e626804919b294": "Resposta necessária", + "c6196d99000642b4": "Abrir thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Você:", "a1fbf2422c588292": "Agente:", @@ -3034,8 +3034,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 +3278,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 +3455,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", @@ -3693,7 +3697,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 +3708,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 +3984,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", @@ -12476,8 +12477,6 @@ "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", "2c4153283b647365": "Claude {account}: {session} da janela de 5 horas e {weekly} da semana usados", "0ebc6d14caaaca3b": "carga {one} · {five} · {fifteen} em {cores} núcleos", "578c5947c810f7b9": "{percent}% ocupado", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 2c5e0b4c1fdfc..b036bf2920aff 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -118,9 +118,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}.", @@ -2560,10 +2560,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", "5bbac0e5afeec779": "Текущий тред", "33c7e68fca089036": "Тред, {title}", - "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", - "c6196d99000642b4": "Открыть тред", "34cc63390ad793cc": "Выберите тред", "8f12309ead62e38a": "Поиск тредов или проектов...", "2f664754d005d9a7": "Активные треды не найдены.", @@ -2573,6 +2572,7 @@ "a3178769f8308cbc": "Ошибка в треде", "89b5e8f3887812da": "Запрос гостя", "62e626804919b294": "Нужен ввод", + "c6196d99000642b4": "Открыть тред", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Вы:", "a1fbf2422c588292": "Агент:", @@ -3034,8 +3034,8 @@ "6f85f14f35b3f547": "{provider} через {environment}", "7c59a888a062a8bd": "Нет черновика для записи голосового ввода.", "62450481c00d2ef3": "Окружение черновика недоступно для очистки расшифровки.", - "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "0674544195fcdc39": "Добавлена исходная расшифровка.", + "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "296496693cdac0db": "Команда t3 недоступна.", "efbcef7bc9bbda01": "Не удалось загрузить состояние команды t3.", "1bf6910332426e62": "Сетевой доступ десктопа недоступен.", @@ -3278,6 +3278,7 @@ "4d493d0bda4d403d": "Прикрепите прерванный файл снова или удалите его", "c9cad1d84d5f1a32": "Прикрепите прерванные файлы снова или удалите их", "536a820f2ff726da": "Выберите хотя бы одну модель.", + "48d6389202ad6754": "Отправка по готовности", "fbafbe78b5e37966": "Возобновить тред", "bcd7eb979dd38dae": "Откройте поле ввода, чтобы сжать и отправить", "95ee62a0d6968b89": "Отправить сообщение", @@ -3454,6 +3455,9 @@ "e778e4f446fdf873": "Следующее сообщение начнёт новый сеанс", "0e2f2da4f2d94785": "Агент не увидит предыдущие сообщения этого треда.", "e1189d2e582b008d": "Оставить текущий сеанс", + "2bb448d605877a22": "Отредактируйте или нажмите Esc для отмены", + "1a1f128d70c62304": "{count, plural, one {Отправится, когда изображение будет готово} few {Отправится, когда {count} изображения будут готовы} many {Отправится, когда {count} изображений будут готовы} other {Отправится, когда {count} изображения будут готовы}}", + "5af3ab719a9725fb": "Отправка сообщения", "461c9f865f2e9b92": "{option}: вкл.", "f2aa17b5c620f2a4": "{option}: выкл.", "f59314a884aae1ff": "По умолчанию", @@ -3693,7 +3697,6 @@ "7c1923203049d602": "Копировать код", "637817e4ff79c90e": "Действия с блоком кода", "ebf3a2b1e314aa5f": "Выполнить в терминале", - "fe219642547fa0bf": "Выполнить в терминале", "122a8512abc51180": "Подробности", "58c38c65c2783c5d": "Полный путь", "f37e7d36b51c5b28": "Копировать относительный путь", @@ -3705,10 +3708,6 @@ "4967584e8d0fb1c2": "Предпросмотр медиа", "67589dd912eacb7c": "Открыть во встроенном браузере", "a3c98d4c4b24cecb": "Параметры файла {label}", - "b4fe8a076e9fd2f8": "Формула в отдельной строке", - "085d1407e8c92cce": "Формула в строке", - "a2ef393fa7b48ae8": "Прокрутить формулу", - "e94685ea5642e088": "Прокрутить формулу в строке", "3a04583c8500e23d": "Показать диаграмму", "16d64f650840fe06": "Показать код", "6d329f7d3a50c7e7": "Копировать таблицу", @@ -3985,9 +3984,11 @@ "973e99fa86d7f531": "Сообщение в очереди {position} из {total}, не отправлено", "0f6087c4f53c7f17": "Начать ход с этим сообщением ({shortcut})", "adab89933af02669": "Пропустить сжатие и отправить сообщение ({shortcut})", + "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", "3de4016452e8d2bd": "Отправить в текущий ход ({shortcut})", "259cc9568148e8ad": "Начать ход с этим сообщением", "bb7fddb812d5d29e": "Пропустить сжатие и отправить сообщение", + "425ab15036aec8a4": "Переместить эту команду в начало очереди", "a5fe1ee609b29a9f": "Отправить в текущий ход", "2b7fd345e4f4fd6e": "Отменить редактирование сообщения в очереди", "47f1726bf106d2c8": "Редактировать сообщение в очереди", @@ -12476,8 +12477,6 @@ "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", - "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", - "425ab15036aec8a4": "Переместить эту команду в начало очереди", "2c4153283b647365": "Claude {account}: использовано {session} 5-часового окна и {weekly} недельного лимита", "0ebc6d14caaaca3b": "нагрузка {one} · {five} · {fifteen} на {cores} ядрах", "578c5947c810f7b9": "занято {percent}%", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index a40ecfd0d7cc1..43463869d989e 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -118,9 +118,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}.", @@ -2560,10 +2560,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 +2572,7 @@ "a3178769f8308cbc": "Tråden misslyckades", "89b5e8f3887812da": "Gästbegäran", "62e626804919b294": "Input behövs", + "c6196d99000642b4": "Öppna tråd", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -3034,8 +3034,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 +3278,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 +3455,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", @@ -3693,7 +3697,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 +3708,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 +3984,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", @@ -12483,8 +12484,6 @@ "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", "2c4153283b647365": "Claude {account}: {session} av 5-timmarsfönstret och {weekly} av veckan använt", "0ebc6d14caaaca3b": "last {one} · {five} · {fifteen} på {cores} kärnor", "578c5947c810f7b9": "{percent} % upptagen", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 0fafb061e50c9..3be6b7b299aae 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -118,9 +118,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。", @@ -2564,10 +2564,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", "5bbac0e5afeec779": "当前会话", "33c7e68fca089036": "会话,{title}", - "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", - "c6196d99000642b4": "打开会话", "34cc63390ad793cc": "选择会话", "8f12309ead62e38a": "搜索会话或项目…", "2f664754d005d9a7": "未找到活动会话。", @@ -2577,6 +2576,7 @@ "a3178769f8308cbc": "会话失败", "89b5e8f3887812da": "访客请求", "62e626804919b294": "需要输入", + "c6196d99000642b4": "打开会话", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "你:", "a1fbf2422c588292": "智能体:", @@ -3038,8 +3038,8 @@ "6f85f14f35b3f547": "{provider}(经由 {environment})", "7c59a888a062a8bd": "语音输入没有可录入的草稿。", "62450481c00d2ef3": "草稿所在环境不可用,无法整理转写内容。", - "c64cb58d9cecbcd2": "转写文本整理失败", "0674544195fcdc39": "已添加原始转写文本。", + "c64cb58d9cecbcd2": "转写文本整理失败", "296496693cdac0db": "t3 命令不可用。", "efbcef7bc9bbda01": "无法加载 t3 命令状态。", "1bf6910332426e62": "桌面网络访问不可用。", @@ -3282,6 +3282,7 @@ "4d493d0bda4d403d": "请重新添加中断的文件,或将其移除", "c9cad1d84d5f1a32": "请重新添加中断的文件,或将它们移除", "536a820f2ff726da": "请至少选择一个模型。", + "48d6389202ad6754": "就绪后发送", "fbafbe78b5e37966": "继续会话", "bcd7eb979dd38dae": "打开输入框以压缩并发送", "95ee62a0d6968b89": "发送消息", @@ -3459,6 +3460,9 @@ "e778e4f446fdf873": "你的下一条消息将以全新上下文开始", "0e2f2da4f2d94785": "智能体将看不到这个会话里之前的消息。", "e1189d2e582b008d": "保留当前上下文", + "2bb448d605877a22": "编辑或按 Esc 取消", + "1a1f128d70c62304": "{count, plural, other {图片就绪后发送}}", + "5af3ab719a9725fb": "正在发送消息", "461c9f865f2e9b92": "{option} 开启", "f2aa17b5c620f2a4": "{option} 关闭", "f59314a884aae1ff": "默认", @@ -3698,7 +3702,6 @@ "7c1923203049d602": "复制代码", "637817e4ff79c90e": "代码块操作", "ebf3a2b1e314aa5f": "在终端中运行", - "fe219642547fa0bf": "在终端中运行", "122a8512abc51180": "详情", "58c38c65c2783c5d": "完整路径", "f37e7d36b51c5b28": "复制相对路径", @@ -3710,10 +3713,6 @@ "4967584e8d0fb1c2": "预览媒体", "67589dd912eacb7c": "在内置浏览器中打开", "a3c98d4c4b24cecb": "{label} 的文件选项", - "b4fe8a076e9fd2f8": "独立公式", - "085d1407e8c92cce": "行内公式", - "a2ef393fa7b48ae8": "滚动查看独立公式", - "e94685ea5642e088": "滚动查看行内公式", "3a04583c8500e23d": "显示图表", "16d64f650840fe06": "显示代码", "6d329f7d3a50c7e7": "复制表格", @@ -3990,9 +3989,11 @@ "973e99fa86d7f531": "排队消息 {position}/{total},尚未发送", "0f6087c4f53c7f17": "用此消息开始一个轮次 ({shortcut})", "adab89933af02669": "跳过压缩并发送此消息 ({shortcut})", + "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", "3de4016452e8d2bd": "发送到当前轮次 ({shortcut})", "259cc9568148e8ad": "用这条消息开始新一轮", "bb7fddb812d5d29e": "跳过压缩并发送这条消息", + "425ab15036aec8a4": "将此命令移到队列最前面", "a5fe1ee609b29a9f": "发送到当前这一轮", "2b7fd345e4f4fd6e": "取消编辑排队消息", "47f1726bf106d2c8": "编辑排队消息", @@ -12502,8 +12503,6 @@ "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", "9e91e9a77b664e4e": "无法开始生成审查导览", - "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", - "425ab15036aec8a4": "将此命令移到队列最前面", "2c4153283b647365": "Claude {account}:已用 5 小时窗口的 {session},本周额度的 {weekly}", "0ebc6d14caaaca3b": "负载 {one} · {five} · {fifteen}({cores} 核)", "578c5947c810f7b9": "占用 {percent}%", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index c8e34b901ad98..d1c43862f2020 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1889,10 +1889,6 @@ code { margin: 0.65rem 0; } -.chat-markdown-math-display .katex-display { - margin: 0; -} - :is(.chat-markdown, .composer-tiptap) h1, :is(.chat-markdown, .composer-tiptap) h2, :is(.chat-markdown, .composer-tiptap) h3, @@ -2314,6 +2310,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/selectionActions.browser.test.ts b/apps/web/src/lib/selectionActions.browser.test.ts new file mode 100644 index 0000000000000..de5b70908fbb6 --- /dev/null +++ b/apps/web/src/lib/selectionActions.browser.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { fakeTimers } from "../../test/render"; +import { observeSelectionActions, SELECTION_MULTI_CLICK_INTERVAL_MS } from "./selectionActions"; + +describe("observeSelectionActions", () => { + it.each([ + { immediateMultiClick: false, nextFrame: [], afterInterval: [[{ x: 40, y: 12 }]] }, + { immediateMultiClick: true, nextFrame: [[null]], afterInterval: [[null]] }, + ])( + "double-click with immediateMultiClick=$immediateMultiClick", + ({ immediateMultiClick, nextFrame, afterInterval }) => { + using stack = new DisposableStack(); + const element = stack.adopt(document.body.appendChild(document.createElement("div")), (e) => + e.remove(), + ); + stack.use(fakeTimers()); + const onSelection = vi.fn(); + const actions = observeSelectionActions({ + element, + immediateMultiClick, + onSelection, + onDismiss: () => {}, + }); + stack.defer(() => actions.dispose()); + + element.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, isPrimary: true, button: 0 }), + ); + element.dispatchEvent( + new MouseEvent("mouseup", { + bubbles: true, + button: 0, + detail: 2, + clientX: 40, + clientY: 12, + }), + ); + + vi.advanceTimersByTime(20); + expect(onSelection.mock.calls).toEqual(nextFrame); + vi.advanceTimersByTime(SELECTION_MULTI_CLICK_INTERVAL_MS - 21); + expect(onSelection.mock.calls).toEqual(nextFrame); + vi.advanceTimersByTime(50); + expect(onSelection.mock.calls).toEqual(afterInterval); + }, + ); +}); diff --git a/apps/web/src/lib/selectionActions.ts b/apps/web/src/lib/selectionActions.ts index 9303602097543..2c219000290c3 100644 --- a/apps/web/src/lib/selectionActions.ts +++ b/apps/web/src/lib/selectionActions.ts @@ -47,12 +47,19 @@ export function observeSelectionActions({ element, getActionElement, restoreAfterScroll = false, + immediateMultiClick = false, onSelection, onDismiss, }: { element: HTMLElement; getActionElement?: () => HTMLElement | null; restoreAfterScroll?: boolean; + /** + * Show double- and triple-click selections at once instead of waiting out the multi-click + * interval. Their pointer is withheld so the action anchors below the selection, clear of + * the spot where a following click lands. + */ + immediateMultiClick?: boolean; onSelection: (pointer: SelectionActionPoint | null) => void; onDismiss: (reason: "interaction" | "cancel") => void; }) { @@ -132,8 +139,9 @@ export function observeSelectionActions({ pointerDown = false; if (!gestureActive) return; gestureActive = false; - pointer = { x: event.clientX, y: event.clientY }; - schedule(event.detail >= 2 ? SELECTION_MULTI_CLICK_INTERVAL_MS : 0); + const multiClick = event.detail >= 2; + pointer = multiClick && immediateMultiClick ? null : { x: event.clientX, y: event.clientY }; + schedule(multiClick && !immediateMultiClick ? SELECTION_MULTI_CLICK_INTERVAL_MS : 0); }; const onKeyDown = (event: KeyboardEvent) => { if (isActionTarget(event.target) && event.key !== "Escape") return; 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.secrets.tsx b/apps/web/src/routes/_chat.settings.secrets.tsx index d97e00fda19f7..e0031f4aeaf9a 100644 --- a/apps/web/src/routes/_chat.settings.secrets.tsx +++ b/apps/web/src/routes/_chat.settings.secrets.tsx @@ -1,11 +1,19 @@ -import { createFileRoute, redirect } from "@tanstack/react-router"; +import { createFileRoute, Navigate } from "@tanstack/react-router"; import { SecretsSettingsPanel } from "../components/settings/SecretsSettings"; -import { isSecretsFeatureEnabled } from "../env"; +import { useHasSecretProvidersEnvironment } from "../components/settings/useAvailableSettingsSearchItems"; +import { useEnvironments } from "../state/environments"; export const Route = createFileRoute("/_chat/settings/secrets")({ - beforeLoad: () => { - if (!isSecretsFeatureEnabled) throw redirect({ to: "/settings/general", replace: true }); - }, - component: SecretsSettingsPanel, + component: SecretsSettingsRoute, }); + +function SecretsSettingsRoute() { + const enabled = useHasSecretProvidersEnvironment(); + // Only redirect once every environment reported flags; one may enable them after another loads. + const { isReady, environments } = useEnvironments(); + const allReported = + isReady && environments.every((environment) => environment.serverConfig !== null); + if (!enabled && allReported) return ; + return ; +} diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts index 63f7cca9cbfc6..307b9c5d8284d 100644 --- a/apps/web/src/vite-env.d.ts +++ b/apps/web/src/vite-env.d.ts @@ -15,7 +15,6 @@ interface ImportMetaEnv { readonly VITE_RELAY_OTLP_TRACES_DATASET: string; readonly VITE_RELAY_OTLP_TRACES_TOKEN: string; readonly T3CODE_DESKTOP_UPDATE_REPOSITORY: string; - readonly T3CODE_FEATURE_SECRETS: string; readonly APP_VERSION: string; } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 073fca7943d3e..005e828202bda 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -50,7 +50,6 @@ const configuredDesktopUpdateRepository = process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() || process.env.GITHUB_REPOSITORY?.trim() || ""; -const configuredFeatureSecrets = process.env.T3CODE_FEATURE_SECRETS?.trim() || ""; const configuredHostedAppUrl = (() => { const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim(); if (explicitHostedAppUrl) { @@ -370,7 +369,6 @@ export default defineConfig(({ command }) => { "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify( configuredDesktopUpdateRepository, ), - "import.meta.env.T3CODE_FEATURE_SECRETS": JSON.stringify(configuredFeatureSecrets), "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel), "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion), }, diff --git a/docs/progress.md b/docs/progress.md index 308793a98dcb3..ebd4bc2a18b3d 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -274,3 +274,16 @@ - Numbers: `vp run check:changed upstream/main` (the fork's 119 files): unused patches, format, lint, knip, graphql, typecheck (43 packages), 1602 tests in 57 files and react compiler all pass. `vp run check:changed origin/main` (upstream's 82 files): every step passes except the test step, where 3 cases of the new upstream `browserHistoryStore.browser.test.ts` failed under the 44-file parallel run (two 15 s timeouts, one cascading assertion after them); that file alone passes 10/10, and the other 1756 tests pass. `vp run i18n:check` pass. CI owns the full suite. - Real run: `vp run migrate-dev-db --base-dir .t3/verify` seeded a scratch data dir from a read-only snapshot of the live database (67.8 MB, 5 projects, 31 threads) and applied migrations 103-105 from earlier syncs. The server then booted on that dir on port 16257, completed V2 orchestration recovery and answered HTTP 302; it was stopped by the PIDs this task started and the port was released. No agent turn was sent. The dev runner had no Rust build for the resource monitor, so it started without process telemetry; the scratch home inside the Git repo also warns, as expected. - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Recheck upstream main before the merge if it moved during the sync; no new migrations came with these 26 commits. + +## 2026-11-22: Fork synced with upstream `3b3f8808f4` by a merge + +- What: upstream main `3b3f8808f4`, 32 commits newer than the last sync base `dac6422b89` (231 files, +7455/-3026), was merged into `tomas/sync-upstream-2026-11-22` at fork main `cfbcb25a04` (#29) with a real merge (this commit), as in the last five syncs. Fork main is the first parent and was the branch head, so no `-s ours` merge was needed and the PR needs no force-push. +- Why: upstream main moved 32 commits while #29 was being checked. +- Conflicts: the 10 web catalogs, at their tails. Upstream moved the two "Move this command to the front of the queue" keys from the end into source order, and the fork had appended its keys after them. Resolved per JSON key: base, plus the fork's key changes (64 added, 3 removed), plus upstream's (4 added, 5 removed). No key was changed by both sides, and each catalog parses to exactly that merge with no duplicate keys. The other 14 files changed on both sides merged without conflicts: `Orchestrator.ts`, `ProviderTurnStartService.ts`, `server.ts`, `ws.ts` and its test, the MCP project `handlers.ts`, `orchestrationV2.ts`, `packages/shared/package.json`, `ChatView.tsx`, `ComposerFooterControls.tsx`, `settingsSearch.ts`, `index.css`, `docs/user/thread-sidebar.md` and mobile `use-thread-composer-state.ts`. +- Fork behavior kept: the fork's diff against upstream is 119 files, +6924/-308, before (`dac6422b89..cfbcb25a04`) and after the merge (`3b3f8808f4..HEAD`), with identical per-file added and removed line counts. In 109 of the files the added and removed lines themselves are identical; in each of the 10 web catalogs, only the line that gains a comma before the fork's appended keys differs. +- Checked and left alone: #40622 (a steer that missed its turn keeps its queue place) changes where such a steer queues, not which model it runs on: a queued Auto-stamped run still takes the thread's current pick when it starts (`queuedRunFollowsCurrent`), and the fork's unread-steer requeue still queues behind its source run. #40670 (a dropped Cursor prompt keeps its inline handoff) makes `unsentManualContinuationSource` skip dropped turns, so Resume re-sends a dropped prompt instead of the fork's "Continue where you left off."; only Cursor marks prompts dropped. #40567 (`t3_thread_launch` sets `titleRenamed`) sits beside the fork's `delegatedFrom` stamping. #40633 and #40604 change `t3_thread_wait` only for app-owned delegated tasks, not launched threads. #40594 moves the feature flags into one `T3CODE_FEATURE_FLAGS` list (`secret_providers`, `tanstack_source`, `github_app_client_id=…`) and restructures settings search; the Machine bar, Agent limit and failover search entries are intact, and neither hub sets the removed `T3CODE_FEATURE_SECRETS`, `T3CODE_TANSTACK_SOURCE` or `T3CODE_GITHUB_APP_CLIENT_ID`. #27866 drops `react-markdown` and remark from the web app; no fork file imports them. `OrchestratorV2Shape` did not change, so Auto routing still wraps every dispatch. Upstream did not touch `autoModel.ts`, `AutoFailoverService.ts`, `ClaudeAdapterV2.ts`, `ThreadMessageIntake.ts` or the Grok usage reader. +- Numbers: `vp run check:changed upstream/main` (the fork's 119 files): unused patches, format, lint, knip, graphql, typecheck (43 packages) and react compiler pass; tests 1603/1604 in 57 files. The one failure, the first case of `ChatView.browser.test.tsx`, hit its 15 s timeout under the parallel run while the review agent was also working; that file alone passes 18/18. `vp run check:changed origin/main` (upstream's 231 files): unused patches, format, lint, knip, graphql, typecheck (43 packages) and react compiler (65 files) pass. Its 114-file test step ran past the runner's 900 s timeout on the first run and was killed without output; rerun with `--timeout 2700`, it finished in 835 s with 3253 of 3266 tests passing (12 skipped). The one failure, a drag-scroll case in upstream's `FilePreviewPanel.browser.test.tsx` (a file the fork does not touch), missed its wait under that load; that file alone passes 15/15. `vp run i18n:check` pass. +- Real run: a copy of the live database was taken through a read-only connection (`VACUUM INTO`, 381 MB), and `vp run migrate-dev-db --base-dir .t3/verify --source ` seeded a scratch data dir from it (65.6 MB, 5 projects, 29 threads), applying migrations 103-105 from earlier syncs. The server booted on that dir on port 13990, completed V2 orchestration recovery and answered HTTP 302. The harness stopped its process tree and the port was released. No agent turn was sent. The only warnings were the expected two: no Rust build for the resource monitor, and the scratch home inside the Git repo. +- Review: one read-only review on the first Claude account found no bugs (the second account is at its weekly limit until Nov 25, and the Codex account had no quota for a GPT reviewer). It compared the fork's added and removed lines file by file, parsed the 10 catalogs per key, and confirmed each call above. +- Switching the hubs: these 32 commits add no migrations; hub2's live database is still at 102, so its switch applies 103-105 from earlier syncs. The lockfile changed (#27866 vendors `@pierre/words` as `apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz`), so the new build needs `vp i`. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Upstream main moved 6 commits during the sync (`4ac5e6e791`: #40693, #40676, #40702, #40701, #40699, #40682); they touch one fork file (`ProviderRegistry.test.ts`), merge without conflicts, and go in the next sync. diff --git a/docs/user/keyboard-focus.md b/docs/user/keyboard-focus.md index 6691b525167d7..2a8edd62b2fa1 100644 --- a/docs/user/keyboard-focus.md +++ b/docs/user/keyboard-focus.md @@ -2,7 +2,7 @@ The command palette keeps focus while open. Closing it returns focus to the composer in chat, or to the previous control on other pages. Choosing a workspace focus command moves to that -area instead. Opening Pull Requests moves focus into that page. +area instead. Opening Pull requests moves focus into that page. While the palette or model picker is open, number shortcuts select its entries instead of switching threads. Model shortcuts work in Settings as well as the composer. See [Keybindings](./keybindings.md) to customize these shortcuts. @@ -14,7 +14,7 @@ becomes ready. Opening or switching to a terminal explicitly still focuses it. On web and desktop, press `F6` or `Shift+F6` to move between the Threads sidebar, conversation, message input, and visible panels. Navigation wraps around and restores -the last focused control in each area. Pull Requests has a page content area. In Settings, +the last focused control in each area. Pull requests has a page content area. In Settings, `F6` moves between the section list and the open section. Hidden areas are skipped. Other dialogs and form popups retain focus; a thread context menu closes when an area command moves focus away. diff --git a/docs/user/source-control.md b/docs/user/source-control.md index cb8d252b9ab37..fa193bf0e87a8 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -146,8 +146,10 @@ Merging a stack lands it through GitCafe, and updating a branch restacks the lay ### TanStack Source -TanStack Source is in private beta, so the server shows it only when started with -`T3CODE_TANSTACK_SOURCE=1` in its environment. Install its CLI and sign in: +TanStack Source is in private beta, so the server shows it only when its environment turns the flag +on: `export T3CODE_FEATURE_FLAGS=tanstack_source` in your shell profile, then restart T3 Code. Separate +several flags with commas. A value already set in the server's own environment, such as a service +definition, is used instead of the profile. Install its CLI and sign in: ```sh curl -fsSL https://source.tanstack.com/install | sh diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 443cc7fa22d54..8029c547abe1e 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/thread-titles/run.ts b/evals/thread-titles/run.ts index d53571698b021..5c77f68752485 100644 --- a/evals/thread-titles/run.ts +++ b/evals/thread-titles/run.ts @@ -6,6 +6,7 @@ import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Duration from "effect/Duration"; @@ -153,6 +154,7 @@ await Effect.runPromise( ProcessRunner.layer, SourceControlProviderRegistry.layer.pipe( Layer.provide(SourceControlBuiltInDrivers.layer), + Layer.provide(FeatureFlags.layer), Layer.provide(ServerSettings.layerTest()), Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))), Layer.provide(GitVcsDriver.layer), diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.ts index 81e76b0391aae..f06c751982710 100644 --- a/infra/relay/src/agentActivity/ApnsClient.test.ts +++ b/infra/relay/src/agentActivity/ApnsClient.test.ts @@ -151,7 +151,7 @@ describe("ApnsClient", () => { const environmentId = "é".repeat(191); const threadId = "t".repeat(512); const notification = sanitizeApnsNotificationPayload({ - title: "界".repeat(120), + title: "😀".repeat(120), body: "界".repeat(120), environmentId, threadId, @@ -159,6 +159,8 @@ describe("ApnsClient", () => { }); const request = apns.makePushNotificationRequest({ token: "push-token", notification }); + expect(notification.title).toBe(`${"😀".repeat(58)}...`); + expect( new TextEncoder().encode(JSON.stringify(request.payload)).byteLength, ).toBeLessThanOrEqual(4096); diff --git a/infra/relay/src/agentActivity/agentActivityPayloads.ts b/infra/relay/src/agentActivity/agentActivityPayloads.ts index 4195c81171803..2dd8be5870b9b 100644 --- a/infra/relay/src/agentActivity/agentActivityPayloads.ts +++ b/infra/relay/src/agentActivity/agentActivityPayloads.ts @@ -52,7 +52,12 @@ export function truncateText(value: string, maxLength: number): string { if (trimmed.length <= maxLength) { return trimmed; } - return trimmed.slice(0, maxLength - 3).trimEnd() + "..."; + return ( + trimmed + .slice(0, maxLength - 3) + .replace(/[\uD800-\uDBFF]$/, "") + .trimEnd() + "..." + ); } function sanitizeDeepLink(value: string): string { diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index fee70319c71de..92fad6b57ac9d 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -654,6 +654,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 +684,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/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 66909fad1f054..661dfe1a94cae 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -49,6 +49,17 @@ describe("resolveIssueLinkTarget", () => { expect(target?.ref).toMatchObject({ projectId: "fork", scope: "me/web", key: "3" }); }); + it("uses the current repository identity after a project changes repositories", () => { + const url = "https://github.com/acme/api/issues/7"; + const original = project("p1", "acme/api"); + const replacement = project("p1", "acme/mobile"); + const lender = project("p3", "acme/web"); + expect(resolveIssueLinkTarget({ url, projects: [lender, original] })?.ref.projectId).toBe("p1"); + expect(resolveIssueLinkTarget({ url, projects: [lender, replacement] })?.ref.projectId).toBe( + "p3", + ); + }); + it("prefers the project bound to the link's own port over one on the bare hostname", () => { const enterprise = (id: string, host: string) => ({ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 0b442d18c92b5..db06b1b0a218f 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -3,6 +3,7 @@ import { issueTrackerBindingScopes, type IssueRef, type IssueTrackerConnectionList, + type RepositoryIdentity, } from "@t3tools/contracts"; import { LINEAR_HOST, @@ -15,11 +16,22 @@ import type { EnvironmentProject } from "./state/shell.ts"; type LinkProject = Pick; +const issueBindingsByRepository = new WeakMap< + RepositoryIdentity, + ReturnType +>(); + /** The hosts and scopes a project's git-host tracker is bound to, the way the server resolves them. */ function projectIssueBindings(project: LinkProject) { - return sourceControlClients - .issueBindings(project.repositoryIdentity) + const identity = project.repositoryIdentity; + if (identity == null) return []; + const cached = issueBindingsByRepository.get(identity); + if (cached !== undefined) return cached; + const bindings = sourceControlClients + .issueBindings(identity) .map((binding) => ({ ...binding, scope: binding.scope.toLowerCase() })); + issueBindingsByRepository.set(identity, bindings); + return bindings; } function linkAuthority(url: string): string | null { 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 = ['

    ");
         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/shell.test.ts b/packages/shared/src/shell.test.ts index d9950edc60cfb..08731a41c19ef 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"; @@ -591,7 +592,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 +611,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 +637,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 +648,111 @@ 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(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(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]); + 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 synchronous 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(resolveExecutable("cursor", "win32", env)).toBe(path.join(directory, "cursor.CMD")); + expect(resolveExecutable("late", "win32", env)).toBeUndefined(); + yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); + yield* fs.utimes(directory, 946_684_830, 946_684_830); + expect(resolveExecutable("late", "win32", env)).toBe(path.join(directory, "late.EXE")); + }), + ); }); describe("runsGitWithoutConsole", () => { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 8ccb466775c1f..ffcc1110fe381 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"; @@ -108,7 +109,12 @@ function resolveSpawnExecutableWithNode( for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { const normalizedPathEntry = normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; + const names = + platform === "win32" + ? listPathDirectorySync(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; } @@ -578,7 +584,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 +629,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 syncPathDirectoryListings = new Map< + string, + { readonly modified: number; readonly names: ReadonlySet } +>(); + +// The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. +function listPathDirectorySync( + directory: string, + isAbsolute: (path: string) => boolean, +): ReadonlySet | undefined { + let modified: number; + try { + const stats = NodeFS.statSync(directory); + if (!stats.isDirectory()) return undefined; + modified = stats.mtimeMs; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; + } + const cached = syncPathDirectoryListings.get(directory); + if (cached?.modified === modified) return cached.names; + syncPathDirectoryListings.delete(directory); + // This resolver runs outside Effect, so it has no Clock to read. + // @effect-diagnostics-next-line globalDate:off + const listedAtMs = Date.now(); + let names: ReadonlySet; + try { + names = new Set(NodeFS.readdirSync(directory).map((entry) => entry.toLowerCase())); + } catch { + return undefined; + } + if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { + if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = syncPathDirectoryListings.keys().next().value; + if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); + } + syncPathDirectoryListings.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 +770,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 +780,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); 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 = /(?<=[.!?؟])(?; +export type TrackerIssueLink = Pick; export interface TrackerIssuePage { readonly items: ReadonlyArray; @@ -134,6 +135,11 @@ export interface IssueTrackerApi { /** The issue with its first page of conversation, in one read where the tracker allows. */ readonly getIssue: (input: IssueTarget) => Effect.Effect; + /** Confirms an issue exists and names it for a thread link. */ + readonly getIssueLink?: ( + input: IssueTarget, + ) => Effect.Effect; + /** One page of older comments past a cursor `getIssue` or a previous page handed over. */ readonly getComments: ( input: IssueTarget & { readonly cursor: string }, diff --git a/packages/source-control-core/src/server/driver.ts b/packages/source-control-core/src/server/driver.ts index 7f86d0fff3b9e..fcf737fe2181d 100644 --- a/packages/source-control-core/src/server/driver.ts +++ b/packages/source-control-core/src/server/driver.ts @@ -11,6 +11,7 @@ import type * as FileSystem from "effect/FileSystem"; import type { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; +import type * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import type { SourceControlDefinition } from "../shared/definition.ts"; @@ -80,7 +81,8 @@ export type SourceControlDriverServices = | SourceControlRateLimit.SourceControlRateLimit | HttpClient.HttpClient | FileSystem.FileSystem - | Digest.Digest; + | Digest.Digest + | FeatureFlags.FeatureFlags; export interface SourceControlDriver { readonly kind: SourceControlProviderKind; diff --git a/packages/source-control-definitions/src/registry.ts b/packages/source-control-definitions/src/registry.ts index 46bc9c5b0abd4..90f14961c0d57 100644 --- a/packages/source-control-definitions/src/registry.ts +++ b/packages/source-control-definitions/src/registry.ts @@ -13,42 +13,35 @@ export { canonicalizePullRequestUrl as canonicalizeGitCafePullRequestUrl } from /** * GitHub comes first as the client default for unknown hosts. GitCafe, TanStack Source and Origin * claim URLs first: GitHub and Forgejo accept the same routes on any hostname. TanStack Source is a - * private beta a server may leave out; clients always know it, for a server that has it. + * private beta: every reader knows its URLs, and only a server with its flag on offers the forge. */ -export function makeBuiltInSourceControlDefinitions(options: { readonly tanStackSource: boolean }) { - const tanStackSource = options.tanStackSource ? [TanStackSource.definition] : []; - return makeSourceControlDefinitionRegistry( - [ - GitHub.definition, - CursorOrigin.definition, - GitLab.definition, - GitCafe.definition, - ...tanStackSource, - Forgejo.definition, - Bitbucket.definition, - AzureDevOps.definition, +export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegistry( + [ + GitHub.definition, + CursorOrigin.definition, + GitLab.definition, + GitCafe.definition, + TanStackSource.definition, + Forgejo.definition, + Bitbucket.definition, + AzureDevOps.definition, + ], + { + claimChangeRequestUrlsFirst: [ + GitCafe.definition.kind, + TanStackSource.definition.kind, + CursorOrigin.definition.kind, + AzureDevOps.definition.kind, ], - { - claimChangeRequestUrlsFirst: [ - GitCafe.definition.kind, - ...tanStackSource.map((definition) => definition.kind), - CursorOrigin.definition.kind, - AzureDevOps.definition.kind, - ], - recognizeRemotesIn: [ - GitCafe.definition.kind, - ...tanStackSource.map((definition) => definition.kind), - CursorOrigin.definition.kind, - Forgejo.definition.kind, - GitHub.definition.kind, - GitLab.definition.kind, - AzureDevOps.definition.kind, - Bitbucket.definition.kind, - ], - }, - ); -} - -export const builtInSourceControlDefinitions = makeBuiltInSourceControlDefinitions({ - tanStackSource: true, -}); + recognizeRemotesIn: [ + GitCafe.definition.kind, + TanStackSource.definition.kind, + CursorOrigin.definition.kind, + Forgejo.definition.kind, + GitHub.definition.kind, + GitLab.definition.kind, + AzureDevOps.definition.kind, + Bitbucket.definition.kind, + ], + }, +); diff --git a/packages/source-control-github/scripts/measure-pr-preview.ts b/packages/source-control-github/scripts/measure-pr-preview.ts index 5047dcb281b1e..551245c5600ee 100644 --- a/packages/source-control-github/scripts/measure-pr-preview.ts +++ b/packages/source-control-github/scripts/measure-pr-preview.ts @@ -21,6 +21,7 @@ import * as GitHubAppAccess from "../src/server/GitHubAppAccess.ts"; import * as GitHubPullRequestApi from "../src/server/GitHubPullRequestApi.ts"; import * as GitHubPullRequestProvider from "../src/server/GitHubPullRequestProvider.ts"; import * as GitHubRest from "../src/server/GitHubRest.ts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; const repeatsFlag = process.argv.find((arg) => arg.startsWith("--repeats=")); const repeats = repeatsFlag === undefined ? 1 : Number(repeatsFlag.slice("--repeats=".length)); @@ -119,6 +120,7 @@ const services = GitHubPullRequestApi.layer.pipe( Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(measuredHttp), Layer.provideMerge(sourceControlHost), + Layer.provideMerge(FeatureFlags.layer), ); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts index 1d8652f06495f..f212386f61942 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts @@ -15,6 +15,7 @@ import { DEFAULT_SERVER_SETTINGS, ServerSettingsError } from "@t3tools/contracts import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; @@ -54,6 +55,8 @@ function harness(options: { readonly settingsWritesFail?: boolean; /** Holds a request open until it completes, to interleave other work with it. */ readonly gate?: (sent: Sent) => Effect.Effect; + /** Defaults to a configured app; null runs without one. */ + readonly clientId?: string | null; }) { const requests: Array = []; const http = HttpClient.make((request) => { @@ -114,6 +117,13 @@ function harness(options: { Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(options.settingsWritesFail === true ? failingWrites : host), Layer.provide(NodeCrypto.layer), + Layer.provide( + FeatureFlags.layerTest({ + githubAppClientId: Option.fromNullishOr( + options.clientId === undefined ? "Iv-test-client" : options.clientId, + ), + }), + ), Layer.provide(FileSystem.layerNoop({})), Layer.provide(Layer.succeed(HttpClient.HttpClient, http)), ); @@ -157,7 +167,6 @@ const installedOn = (sent: Sent): Reply => beforeEach(() => { for (const name of ["GH_TOKEN", "GITHUB_TOKEN"]) vi.stubEnv(name, ""); - vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, "Iv-test-client"); }); afterEach(() => { vi.unstubAllEnvs(); @@ -267,8 +276,8 @@ describe("GitHubAppSignIn", () => { }); it.effect("does nothing with the app when the server has no client ID", () => { - vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, ""); const { layer, requests } = harness({ + clientId: null, signIns: { "github.com": session() }, handle: () => ({ body: { login: "octocat" } }), }); diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.ts b/packages/source-control-github/src/server/GitHubAppSignIn.ts index 28bde65ed84a8..843e14ce00687 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.ts @@ -19,16 +19,10 @@ import * as Schema from "effect/Schema"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as GitHubClient from "../shared/definition.ts"; -/** - * The public client ID of the T3 Code for GitHub app, which the device flow needs (no secret). - * Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. - */ -export const CLIENT_ID_VARIABLE = "T3CODE_GITHUB_APP_CLIENT_ID"; - const KIND = SourceControlProviderKind.make("github"); const REQUEST_TIMEOUT = Duration.seconds(15); // Refresh ahead of expiry so a token never lapses between the check and a long request. @@ -107,7 +101,8 @@ const signInError = (host: string, reason: SourceControlSignInFailure, detail: s export const make = Effect.gen(function* () { const sourceControlHost = yield* SourceControlHost.SourceControlHost; const httpClient = yield* HttpClient.HttpClient; - const clientId = (yield* HostProcess.Environment)[CLIENT_ID_VARIABLE]?.trim() ?? ""; + // Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. + const clientId = Option.getOrElse((yield* FeatureFlags.FeatureFlags).githubAppClientId, () => ""); const enabled = clientId !== ""; const scope = yield* Effect.scope; const refreshLock = yield* Semaphore.make(1); diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index 3ddcd024f8b35..c04145758f7b1 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -226,6 +226,31 @@ const decodeBody = Schema.decodeUnknownSync( ); describe("GitHubIssueTracker", () => { + it.effect("reads only the fields needed to link a GitHub issue and rejects missing issues", () => + Effect.gen(function* () { + const requests: unknown[] = []; + const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" }; + const url = "https://github.com/acme/web/issues/42"; + const found = yield* tracker((input) => requests.push(input), { + issue: { number: 42, title: "Fixture issue", url }, + }); + expect(yield* found.getIssueLink(target)).toEqual({ + displayKey: "#42", + title: "Fixture issue", + url, + }); + + const missing = yield* tracker((input) => requests.push(input), { issue: null }); + expect(yield* Effect.flip(missing.getIssueLink(target))).toMatchObject({ + reason: "not-found", + }); + expect(requests).toEqual([ + { owner: "acme", name: "web", number: 42 }, + { owner: "acme", name: "web", number: 42 }, + ]); + }), + ); + it.effect("writes an issue lifecycle without mutating pull requests or foreign comments", () => Effect.gen(function* () { const writes: unknown[] = []; diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.ts b/packages/source-control-github/src/server/GitHubIssueTracker.ts index bf1c20abae4e3..b2cb38ff4d413 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.ts @@ -337,6 +337,16 @@ export const make = Effect.gen(function* () { }; }), + getIssueLink: Effect.fn("GitHubIssueTracker.getIssueLink")(function* (input) { + const { owner, name, number } = yield* issue(input, "getIssue"); + const result = yield* client + .IssueLinkMetadata({ owner, name, number }) + .pipe(graphql(input.host, "getIssue")); + const found = result.repository?.issue; + if (found == null) return yield* notFound("getIssue"); + return { displayKey: `#${found.number}`, title: found.title, url: found.url }; + }), + getComments: (input) => issue(input, "getComments").pipe( Effect.flatMap(({ owner, name, number }) => diff --git a/packages/source-control-github/src/server/GitHubRest.test.ts b/packages/source-control-github/src/server/GitHubRest.test.ts index 460bfbc16d82c..9d82bee19752c 100644 --- a/packages/source-control-github/src/server/GitHubRest.test.ts +++ b/packages/source-control-github/src/server/GitHubRest.test.ts @@ -8,6 +8,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- Keep the native socket path within the temporary directory. import * as NodePath from "node:path"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -360,7 +361,10 @@ describe("GitHubRest", () => { const media = yield* instance.fetchMedia!({ url: mediaUrl, headers: {} }); expect(media?.status).toBe(401); expect(directRequests).toEqual([mediaUrl]); - }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {})); + }).pipe( + Effect.provide(layer.pipe(Layer.provideMerge(FeatureFlags.layerTest()))), + Effect.provideService(HostProcess.Environment, {}), + ); }), ); diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 42dc67a98a123..18c8cee3536a2 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -270,6 +270,16 @@ query IssueComments($owner: String!, $name: String!, $number: Int!, $cursor: Str } } +query IssueLinkMetadata($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { + issue(number: $number) { + number + title + url + } + } +} + query IssueNodeId($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index d99defc174a5c..9d059396d26a0 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -666,6 +666,52 @@ export declare namespace IssueComments { export type Result = typeof IssueComments.result.Type } +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ +export const IssueLinkMetadataRepositoryIssueIssue = Schema.Struct({ + /** Identifies the issue number. */ + number: Shared.Int, + /** Identifies the issue title. */ + title: Schema.String, + /** The HTTP URL for this issue */ + url: Shared.URI +}) +export interface IssueLinkMetadataRepositoryIssueIssue extends Schema.Struct.Type {} + +/** A repository contains the content for a project. */ +export const IssueLinkMetadataRepositoryRepository = Schema.Struct({ + /** Returns a single issue from the current repository by number. */ + issue: Schema.NullOr(IssueLinkMetadataRepositoryIssueIssue) +}) +export interface IssueLinkMetadataRepositoryRepository extends Schema.Struct.Type {} + +/** `query IssueLinkMetadata` */ +export const IssueLinkMetadata = GraphQL.query("IssueLinkMetadata", { + document: { + variables: [ + { name: "owner", body: "String!" }, + { name: "name", body: "String!" }, + { name: "number", body: "Int!" } + ], + selections: [ + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){number title url}}"] } + ], + fragments: [] + }, + variables: { + owner: Schema.String, + name: Schema.String, + number: Shared.Int + }, + result: Schema.Struct({ + /** Lookup a given repository by the owner and repository name. */ + repository: Schema.NullOr(IssueLinkMetadataRepositoryRepository) + }) +}) +export declare namespace IssueLinkMetadata { + export type Variables = typeof IssueLinkMetadata.variables.Type + export type Result = typeof IssueLinkMetadata.result.Type +} + /** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ export const IssueNodeIdRepositoryIssueIssue = Schema.Struct({ /** The Node ID of the Issue object */ @@ -1038,4 +1084,4 @@ export declare namespace IssueCollections { } /** Every operation in issues.graphql. */ -export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections) +export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueLinkMetadata, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 62cbee3b4d8f8..43c68fa25cadb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -359,7 +359,7 @@ overrides: packageExtensionsChecksum: sha256-18pwcgTDbqYFYAzCw8OfBYuC2btyq6aJSLhE/gjTJb4= -pnpmfileChecksum: sha256-h8NLkl2dhhbQKbAHnoo4rQ3tYV96igLQxJ7la6dsbSc= +pnpmfileChecksum: sha256-G0L7+qfid3Wo9BlLIlMyF/+fqBnAnqHKSe0HlWAtlg8= patchedDependencies: '@alchemy.run/test@2.0.0-beta.85': 29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e @@ -1107,6 +1107,9 @@ importers: '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) + '@pierre/words': + specifier: file:deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz + version: file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0) '@t3tools/client-runtime': specifier: workspace:* version: link:../../packages/client-runtime @@ -1158,6 +1161,9 @@ importers: '@tiptap/extension-list': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-paragraph': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) '@tiptap/extension-strike': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) @@ -1224,39 +1230,21 @@ importers: lucide-react: specifier: ^0.564.0 version: 0.564.0(react@19.3.0) - mdast-util-from-markdown: - specifier: ^2.0.3 - version: 2.0.3(supports-color@8.1.1) - micromark-util-combine-extensions: - specifier: ^2.0.1 - version: 2.0.1 pdfjs-dist: specifier: 6.4.299 version: 6.4.299 pele: specifier: 'catalog:' version: 1.8.0 + property-information: + specifier: ^7.2.0 + version: 7.2.0 react: specifier: 'catalog:' version: 19.3.0 react-dom: specifier: 'catalog:' version: 19.3.0(react@19.3.0) - react-markdown: - specifier: ^10.1.0 - version: 10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1) - remark-gfm: - specifier: 'catalog:' - version: 4.0.1(supports-color@8.1.1) - remark-math: - specifier: 6.0.0 - version: 6.0.0(supports-color@8.1.1) - remark-parse: - specifier: 'catalog:' - version: 11.0.0(supports-color@8.1.1) - remark-rehype: - specifier: 'catalog:' - version: 11.1.2 saxes: specifier: 6.0.0 version: 6.0.0 @@ -1269,15 +1257,9 @@ importers: tiff: specifier: 7.1.3 version: 7.1.3 - unified: - specifier: 'catalog:' - version: 11.0.5 use-sync-external-store: specifier: ^1.6.0 version: 1.6.0(react@19.3.0) - vfile: - specifier: ^6.0.3 - version: 6.0.3 zustand: specifier: ^5.0.11 version: 5.0.14(@types/react@19.3.0)(react@19.3.0)(use-sync-external-store@1.6.0(react@19.3.0)) @@ -1306,9 +1288,6 @@ importers: '@types/hast': specifier: ^3.0.4 version: 3.0.5 - '@types/mdast': - specifier: ^4.0.4 - version: 4.0.4 '@types/react': specifier: 'catalog:' version: 19.3.0 @@ -1336,9 +1315,6 @@ importers: gt: specifier: 2.27.0 version: 2.27.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) - micromark-util-types: - specifier: 'catalog:' - version: 2.0.2 oxc-transform-react: specifier: ~0.152.0 version: 0.152.0 @@ -1574,21 +1550,12 @@ importers: jszip: specifier: 3.10.1 version: 3.10.1 - remark-gfm: - specifier: 'catalog:' - version: 4.0.1(supports-color@8.1.1) - remark-parse: - specifier: 'catalog:' - version: 11.0.0(supports-color@8.1.1) three: specifier: 0.180.0 version: 0.180.0 unbash: specifier: ^5.0.0 version: 5.0.0 - unified: - specifier: 'catalog:' - version: 11.0.5 devDependencies: '@effect/vitest': specifier: 4.1.5 @@ -1599,6 +1566,15 @@ importers: '@types/three': specifier: 0.180.0 version: 0.180.0 + remark-gfm: + specifier: 'catalog:' + version: 4.0.1(supports-color@8.1.1) + remark-parse: + specifier: 'catalog:' + version: 11.0.0(supports-color@8.1.1) + unified: + specifier: 'catalog:' + version: 11.0.5 vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -2156,6 +2132,9 @@ importers: gt-i18n: specifier: 1.0.40 version: 1.0.40 + hast-util-sanitize: + specifier: ^5.0.2 + version: 5.0.2 mdast-util-directive: specifier: 'catalog:' version: 3.1.0(supports-color@8.1.1) @@ -2208,12 +2187,18 @@ importers: '@effect/vitest': specifier: 4.1.5 version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@types/hast': + specifier: ^3.0.5 + version: 3.0.5 '@types/mdast': specifier: ^4.0.4 version: 4.0.4 '@types/node': specifier: 24.12.4 version: 24.12.4 + hast-util-to-html: + specifier: ^9.0.5 + version: 9.0.5 micromark-util-types: specifier: 'catalog:' version: 2.0.2 @@ -6484,6 +6469,18 @@ packages: react: ^18.3.1 || ^19.0.0 react-dom: ^18.3.1 || ^19.0.0 + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz': + resolution: {integrity: sha512-EuIvU8imMY3c/deOHm9/gEh9VJga8R7jjWiIKfjKHbDXjgMo/O3NDN15H0dLc/vo+YTf/QpY0xinfnv7xpf7Rw==, tarball: file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz} + version: 0.2.2-t3.4 + peerDependencies: + '@pierre/highlights': '>=0.5.1' + react: ^18.3.1 || ^19.0.0 + peerDependenciesMeta: + '@pierre/highlights': + optional: true + react: + optional: true + '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} @@ -11626,12 +11623,6 @@ packages: react-is@19.2.7: resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==} - react-markdown@10.1.0: - resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==} - peerDependencies: - '@types/react': '>=18' - react: '>=18' - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz: resolution: {integrity: sha512-TdP2nTxn8W4jPJ5EU+9Ctgf6aOncENP/kMa9aEZpJDmWNLXkxPpcugHMWyZJt2o5WDYE4SPi0V6zV6mOl3+8cA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz} version: 1.2.0-t3.18 @@ -16553,6 +16544,11 @@ snapshots: - '@shikijs/themes' - shiki + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0)': + optionalDependencies: + '@pierre/highlights': 0.5.1 + react: 19.3.0 + '@pinojs/redact@0.4.0': {} '@polka/url@1.0.0-next.29': {} @@ -22528,24 +22524,6 @@ snapshots: react-is@19.2.7: {} - react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1): - dependencies: - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - '@types/react': 19.3.0 - devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.6(supports-color@8.1.1) - html-url-attributes: 3.0.1 - mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1) - react: 19.3.0 - remark-parse: 11.0.0(supports-color@8.1.1) - remark-rehype: 11.1.2 - unified: 11.0.5 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - transitivePeerDependencies: - - supports-color - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz(katex@0.16.47)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0): dependencies: react: 19.3.0 diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index 135ff4ed201f7..d5881661f4cdc 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -433,6 +433,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { file === ".pnpmfile.cjs" || file.startsWith("patches/") || file.startsWith("apps/mobile/deps/") || + file.startsWith("apps/web/deps/") || path.basename(file) === "package.json", ); @@ -479,7 +480,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest); } } - for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) { + for (const extra of ["apps/mobile/deps", "apps/web/deps", "patches", ".pnpmfile.cjs"]) { if (yield* fs.exists(inRoot(extra))) yield* copy(extra); } const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp); diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 3c58be4cbabbf..e7acbf1e76ff1 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -68,11 +68,12 @@ function copyWorkspaceManifestFixture(targetRoot: string): void { NodeFS.cpSync(sourcePath, destinationPath); } - const mobileDependencies = NodePath.resolve(repoRoot, "apps/mobile/deps"); - if (NodeFS.existsSync(mobileDependencies)) { - NodeFS.cpSync(mobileDependencies, NodePath.resolve(targetRoot, "apps/mobile/deps"), { - recursive: true, - }); + // Fork tarballs that file: dependencies install from. + for (const forks of ["apps/mobile/deps", "apps/web/deps"]) { + const source = NodePath.resolve(repoRoot, forks); + if (NodeFS.existsSync(source)) { + NodeFS.cpSync(source, NodePath.resolve(targetRoot, forks), { recursive: true }); + } } const patchesDirectory = NodePath.resolve(repoRoot, "patches");