diff --git a/.agents/skills/launch-video/SKILL.md b/.agents/skills/launch-video/SKILL.md index 37d67577b9a26..ec1e8a84daa60 100644 --- a/.agents/skills/launch-video/SKILL.md +++ b/.agents/skills/launch-video/SKILL.md @@ -37,10 +37,25 @@ There are two ways to build one: - Agent turns: pass `claude: [turns]` to `prepareHome` and the real Claude provider runs `scripts/fake-claude.mjs` as its CLI, so the video shows Claude's logo, models, thinking and tool rows. Each turn is `{ match, steps }`: `think`, `text`, `bash` (+ `output`, `ms`), - `wait`, and `tool` (+ `input`), which calls that T3 MCP tool for real, e.g. - `delegate_task`. Match generated titles with a `{ match: "title", repeat: true }` turn. - `` is filled from the JSON file at `FAKE_CLAUDE_VARS`, for ids that change - every run. `fake-claude.log` in the home records the protocol, for debugging. + `wait`, `edit` (+ `old`, `new`) and `write` (+ `content`), which change the file for real + so diffs and checkpoints show them, and `tool` (+ `input`), which calls that T3 MCP tool + for real, e.g. `delegate_task`; with `server` and `output` it plays another MCP server's + tool instead. `` is filled from the JSON file at `FAKE_CLAUDE_VARS`, for ids + that change every run. `bash` with `run: true` executes the command in the session's cwd + (to push a branch or open a pull request with a forge CLI); `as: "name"` keeps its output, + or the `pick` regex match in it, as `` for the turn's later steps. A workflow + `agent` step with `returns` finishes on `submit: { ... }`, which hands it that value + through `t3_submit_output`. `fake-claude.log` in the home records the protocol, for debugging. + - Titles, commit messages and branch names come from `claude -p --json-schema`: answer them + with `{ match, json }` turns, where `match` is tested against the schema plus the prompt + (`'"title"'`, `'"subject"[\\s\\S]*products\\.ts'`). Unanswered ones fail in the app. + - An MCP server that needs a sign-in: pass `claude: { turns, servers: [{ name, authUrl }] }`. + The fake answers Claude's `mcp_status`, `mcp_authenticate` and `mcp_oauth_callback_url`, + and remembers the sign-in across processes like the real CLI. + - `createProject(env, title, files, { repos: ["api", "web"] })` makes a plain folder of + several repositories. Staged repos commit as a fictional author. Keep staging homes + outside this checkout (e.g. `/home`): a project folder inside it shows this + checkout's branch. - Data a real flow can't produce cheaply goes into the app's own stores, never into pixels. `insertPeerLinks` writes link rows into a stopped server; `serveDescriptors` makes fake machines answer the reachability probe. The client's saved environments and routes live @@ -82,6 +97,11 @@ harness's task stop; it ends its servers' process groups. only on tailnet names. `serve.mjs` links to this machine's tailnet DNS name. - **Leaks.** Grep the beats for the real hostname, username and tailnet name before rendering. `snapshot.mjs` drops hidden inputs' values (they hold local paths). +- **Timeline rows** (`[data-timeline-row-id]`) are placed by a transform; `rise`/`pop` on one + replaces it and the row vanishes. Animate an element inside the row. +- **The app's own animations** (a running tool's shine) are frozen into the beat and seeked + with the story, which can leave text invisible. Cancel them in `setup()`: + `iframe.contentDocument.getAnimations().forEach((a) => a.cancel())`. - **Timing.** A replayed turn streams in real time (each frame delay caps at 2 s). Make a recording long enough for the drive to catch the state you need, and freeze beats on a timer when the UI summarises (a running command shows only "Running pnpm"). diff --git a/.agents/skills/launch-video/assets/kit.js b/.agents/skills/launch-video/assets/kit.js index 0f682543415a5..3be85be01aac7 100644 --- a/.agents/skills/launch-video/assets/kit.js +++ b/.agents/skills/launch-video/assets/kit.js @@ -160,7 +160,9 @@ window.Kit = (() => { const visible = (target, from, to = Infinity, fade = 0) => { const shown = from + fade; const open = !Number.isFinite(to); - const end = open ? shown + 1 : to; + // A closed window stays shown through `to`: when the next beat starts exactly on a frame, + // its first keyframe is still 0 there, and both hiding would flash black. + const end = open ? shown + 1 : to + 0.002; const keys = [ { offset: 0, opacity: 0 }, { offset: from / end, opacity: 0 }, @@ -169,7 +171,7 @@ window.Kit = (() => { ...(open ? [{ offset: 1, opacity: 1 }] : [ - { offset: Math.max(shown, to - 0.001) / end, opacity: 1 }, + { offset: Math.max(shown, to) / end, opacity: 1 }, { offset: 1, opacity: 0 }, ]), ]; diff --git a/.agents/skills/launch-video/scripts/fake-claude.mjs b/.agents/skills/launch-video/scripts/fake-claude.mjs index 4d1a83dacb8d6..02312bac813ba 100755 --- a/.agents/skills/launch-video/scripts/fake-claude.mjs +++ b/.agents/skills/launch-video/scripts/fake-claude.mjs @@ -2,8 +2,10 @@ // A stand-in `claude` CLI for staged launch videos: T3's real Claude provider runs it, and it // plays the scripted turns in FAKE_CLAUDE_SCRIPT over the Agent SDK's stream-json protocol. // Script format: see the launch-video SKILL.md. FAKE_CLAUDE_LOG records every line. +import * as NodeChildProcess from "node:child_process"; import * as NodeCrypto from "node:crypto"; import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; import * as NodeReadline from "node:readline"; const VERSION = "2.1.329"; @@ -28,10 +30,22 @@ const readJson = (file, fallback) => { return fallback; } }; -const script = readJson(process.env.FAKE_CLAUDE_SCRIPT ?? "", []); +// An array of turns, or { turns, servers } where servers are MCP servers that need a sign-in: +// [{ name, authUrl }]. Sign-in follows the SDK's mcp_authenticate / mcp_oauth_callback_url. +const loaded = readJson(process.env.FAKE_CLAUDE_SCRIPT ?? "", []); +const script = Array.isArray(loaded) ? loaded : (loaded.turns ?? []); +// Sign-ins outlive the process, like the real CLI's stored credentials. +const signedInFile = `${process.env.FAKE_CLAUDE_SCRIPT}.signed-in.json`; +const signedIn = new Set(readJson(signedInFile, [])); +const signInServers = new Map( + (Array.isArray(loaded) ? [] : (loaded.servers ?? [])).map((server) => [ + server.name, + { ...server, status: signedIn.has(server.name) ? "connected" : "needs-auth" }, + ]), +); const played = new Set(); -const fill = (value) => { - const vars = readJson(process.env.FAKE_CLAUDE_VARS ?? "", {}); +const fill = (value, local = {}) => { + const vars = { ...readJson(process.env.FAKE_CLAUDE_VARS ?? "", {}), ...local }; const walk = (v) => typeof v === "string" ? v.replace(//g, (m, name) => vars[name] ?? m) @@ -47,6 +61,33 @@ const argValue = (name) => { const i = process.argv.indexOf(name); return i === -1 ? undefined : process.argv[i + 1]; }; + +// `-p --json-schema` is T3's text generation (titles, commit messages, branch names). It answers +// with the first `{ match, json }` turn whose regex matches the schema plus the prompt. +if (process.argv.includes("-p")) { + const schema = argValue("--json-schema") ?? ""; + let prompt = ""; + for await (const chunk of process.stdin) prompt += chunk; + log("print", { schema, prompt: prompt.slice(0, 2000) }); + const turn = script.find( + (t) => t.json && new RegExp(t.match ?? "", "i").test(`${schema}\n${prompt}`), + ); + if (!turn) { + console.error(`fake-claude: no json turn matches ${schema}`); + process.exit(1); + } + console.log( + JSON.stringify({ + type: "result", + subtype: "success", + is_error: false, + result: "", + structured_output: fill(turn.json), + session_id: NodeCrypto.randomUUID(), + }), + ); + process.exit(0); +} const sessionId = argValue("--session-id") ?? argValue("--resume") ?? NodeCrypto.randomUUID(); let model = argValue("--model") ?? "claude-opus-5-5"; const cwd = process.cwd(); @@ -82,12 +123,12 @@ const assistant = (content, id = `msg_${uuid().replaceAll("-", "").slice(0, 24)} session_id: sessionId, uuid: uuid(), }); -const toolResult = (toolUseId, content, extra = {}) => +const toolResult = (toolUseId, content, extra = {}, isError = false) => send({ type: "user", message: { role: "user", - content: [{ tool_use_id: toolUseId, type: "tool_result", content, is_error: false }], + content: [{ tool_use_id: toolUseId, type: "tool_result", content, is_error: isError }], }, parent_tool_use_id: null, session_id: sessionId, @@ -164,6 +205,11 @@ const streamText = async (text, type = "text") => { }); }; +const serverStatuses = () => [ + ...Object.keys(mcpServers).map((name) => ({ name, status: "connected", scope: "dynamic" })), + ...[...signInServers.values()].map(({ name, status }) => ({ name, status, scope: "user" })), +]; + // One MCP tools/call over streamable HTTP against the server T3 registered. async function callTool(name, args) { const [serverName, server] = Object.entries(mcpServers).find(([, s]) => s.url) ?? []; @@ -205,9 +251,11 @@ async function callTool(name, args) { async function playTurn(prompt) { let index = script.findIndex( - (turn, i) => !played.has(i) && turn.match && new RegExp(turn.match, "i").test(prompt), + (turn, i) => + !played.has(i) && !turn.json && turn.match && new RegExp(turn.match, "i").test(prompt), ); - if (index === -1) index = script.findIndex((turn, i) => !played.has(i) && !turn.match); + if (index === -1) + index = script.findIndex((turn, i) => !played.has(i) && !turn.json && !turn.match); const turn = index === -1 ? { steps: [{ text: "Done." }] } : script[index]; if (index !== -1 && !turn.repeat) played.add(index); send({ @@ -217,7 +265,7 @@ async function playTurn(prompt) { claude_code_version: VERSION, cwd, tools: ["Bash", "Read", "Edit"], - mcp_servers: Object.keys(mcpServers).map((name) => ({ name, status: "connected" })), + mcp_servers: serverStatuses().map(({ name, status }) => ({ name, status })), model, permissionMode: "bypassPermissions", slash_commands: [], @@ -229,44 +277,121 @@ async function playTurn(prompt) { session_id: sessionId, }); let last = ""; - for (const step of fill(turn.steps)) { - if (step.wait) await sleep(step.wait); - if (step.think) await streamText(step.think, "thinking"); - if (step.text) { - await streamText(step.text); - last = step.text; - } - if (step.bash) { - const id = `toolu_${uuid().replaceAll("-", "").slice(0, 24)}`; - assistant([ - { + // `as` keeps a step's real output for later steps of the turn, as . + const local = {}; + // The tool call awaiting its result, so a failing step can still answer it. + let pending; + const toolUse = (block) => { + pending = block.id; + assistant([block]); + }; + const answer = (...args) => { + toolResult(...args); + pending = undefined; + }; + try { + for (const raw of turn.steps) { + const filled = fill(raw, local); + // `submit` hands a workflow agent step its typed result through T3's own MCP. + const step = filled.submit + ? { ...filled, tool: "t3_submit_output", input: { json: JSON.stringify(filled.submit) } } + : filled; + if (step.wait) await sleep(step.wait); + if (step.think) await streamText(step.think, "thinking"); + if (step.text) { + await streamText(step.text); + last = step.text; + } + if (step.bash) { + const id = `toolu_${uuid().replaceAll("-", "").slice(0, 24)}`; + toolUse({ type: "tool_use", id, name: "Bash", input: { command: step.bash, description: step.description ?? step.bash }, - }, - ]); - await sleep(step.ms ?? 1200); - toolResult(id, step.output ?? "", { - tool_use_result: { - stdout: step.output ?? "", - stderr: "", - interrupted: false, - isImage: false, - }, - }); - } - if (step.tool) { - const id = `toolu_${uuid().replaceAll("-", "").slice(0, 24)}`; - const serverName = Object.keys(mcpServers)[0] ?? "t3-code"; - assistant([ - { type: "tool_use", id, name: `mcp__${serverName}__${step.tool}`, input: step.input ?? {} }, - ]); - const { text } = await callTool(step.tool, step.input ?? {}).catch((error) => ({ - text: String(error), - })); - toolResult(id, [{ type: "text", text }]); + }); + // `run` executes the command for real in the session's cwd, e.g. to push and open a PR. + let output = step.output ?? ""; + if (step.run) { + const started = Date.now(); + output = NodeChildProcess.execSync(step.bash, { + cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }).trim(); + await sleep(Math.max(0, (step.ms ?? 1200) - (Date.now() - started))); + } else await sleep(step.ms ?? 1200); + if (step.as) + local[step.as] = step.pick ? (new RegExp(step.pick).exec(output)?.[0] ?? output) : output; + answer(id, output, { + tool_use_result: { + stdout: output, + stderr: "", + interrupted: false, + isImage: false, + }, + }); + } + if (step.tool) { + const id = `toolu_${uuid().replaceAll("-", "").slice(0, 24)}`; + // `server` names a scripted server whose answer is `output`; otherwise T3's own MCP runs it. + const serverName = step.server ?? Object.keys(mcpServers)[0] ?? "t3-code"; + toolUse({ + type: "tool_use", + id, + name: `mcp__${serverName}__${step.tool}`, + input: step.input ?? {}, + }); + if (step.server) await sleep(step.ms ?? 900); + const { text, isError = false } = step.server + ? { text: step.output ?? "" } + : await callTool(step.tool, step.input ?? {}).catch((error) => ({ + text: String(error), + isError: true, + })); + answer(id, [{ type: "text", text }], {}, isError); + } + // Real edits, so checkpoints and diffs show them. Paths are relative to the session's cwd. + if (step.edit || step.write) { + const id = `toolu_${uuid().replaceAll("-", "").slice(0, 24)}`; + const file = NodePath.resolve(cwd, step.edit ?? step.write); + const input = step.edit + ? { file_path: file, old_string: step.old, new_string: step.new } + : { file_path: file, content: step.content }; + toolUse({ type: "tool_use", id, name: step.edit ? "Edit" : "Write", input }); + await sleep(step.ms ?? 700); + if (step.edit) { + const before = NodeFS.readFileSync(file, "utf8"); + if (!before.includes(step.old)) throw new Error(`${step.edit}: old text not found`); + NodeFS.writeFileSync(file, before.replace(step.old, step.new)); + } else { + NodeFS.mkdirSync(NodePath.dirname(file), { recursive: true }); + NodeFS.writeFileSync(file, step.content); + } + answer(id, `The file ${file} has been updated successfully.`); + } } + } catch (error) { + // A scripted step that fails (an edit whose text is gone, a command that exits non-zero) + // still ends the turn, as a failed one, so the app does not wait forever. + log("step failed", String(error)); + if (pending) answer(pending, String(error.message ?? error), {}, true); + send({ + type: "result", + subtype: "error_during_execution", + is_error: true, + duration_ms: 4000, + duration_api_ms: 3500, + num_turns: 1, + result: String(error.message ?? error), + session_id: sessionId, + total_cost_usd: 0, + usage, + modelUsage: {}, + permission_denials: [], + uuid: uuid(), + }); + return; } send({ type: "result", @@ -304,6 +429,29 @@ const controlResponse = (request) => { return {}; case "get_usage": return { rate_limits_available: false, rate_limits: [] }; + case "mcp_status": + return { mcpServers: serverStatuses() }; + case "mcp_authenticate": { + const server = signInServers.get(request.serverName); + if (!server) throw new Error(`no MCP server ${request.serverName}`); + if (server.status === "connected") return { requiresUserAction: false }; + server.state = uuid(); + const url = new URL(server.authUrl); + url.searchParams.set("state", server.state); + return { authUrl: url.toString(), requiresUserAction: true }; + } + case "mcp_oauth_callback_url": { + const server = signInServers.get(request.serverName); + const state = new URL(request.callbackUrl).searchParams.get("state"); + if (!server || !server.state || state !== server.state) + throw new Error("callback is not from this sign-in"); + server.status = "connected"; + signedIn.add(server.name); + NodeFS.writeFileSync(signedInFile, JSON.stringify([...signedIn])); + return {}; + } + case "mcp_reconnect": + return {}; default: return {}; } @@ -321,14 +469,17 @@ input.on("line", (line) => { } log("in", message); if (message.type === "control_request") { - send({ - type: "control_response", - response: { + let response; + try { + response = { subtype: "success", request_id: message.request_id, response: controlResponse(message.request ?? {}), - }, - }); + }; + } catch (error) { + response = { subtype: "error", request_id: message.request_id, error: String(error) }; + } + send({ type: "control_response", response }); return; } if (message.type === "user") { diff --git a/.agents/skills/launch-video/scripts/snapshot.mjs b/.agents/skills/launch-video/scripts/snapshot.mjs index 8bef33d3622d5..3f055927ebf7c 100644 --- a/.agents/skills/launch-video/scripts/snapshot.mjs +++ b/.agents/skills/launch-video/scripts/snapshot.mjs @@ -82,6 +82,49 @@ async function freeze(known) { }); for (const el of clone.querySelectorAll("script, noscript, style, link, base")) el.remove(); + // Open shadow roots (the diff viewer draws inside one) become declarative shadow DOM. + const sheetText = (root) => + [...root.adoptedStyleSheets] + .map((sheet) => { + try { + return [...sheet.cssRules].map((r) => r.cssText).join("\n"); + } catch { + return ""; + } + }) + .join("\n"); + const rootsIn = (root) => + [...root.querySelectorAll("*")] + .filter((el) => el.shadowRoot) + .flatMap((el) => [el.shadowRoot, ...rootsIn(el.shadowRoot)]); + const shadowHtml = (root) => { + const nested = rootsIn(root); + // Adopted sheets do not serialize. Each root gets them as its last `; } diff --git a/apps/mobile/src/features/threads/SecretRequestCard.tsx b/apps/mobile/src/features/threads/SecretRequestCard.tsx index e52fae8ce659f..24b0a1aa81d67 100644 --- a/apps/mobile/src/features/threads/SecretRequestCard.tsx +++ b/apps/mobile/src/features/threads/SecretRequestCard.tsx @@ -16,10 +16,11 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { - EnvironmentId, - OrchestrationV2ProjectedTurnItem, - SecretProviderId, +import { + AuthProvidersManageScope, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { useGT, useMessages } from "gt-react-native"; @@ -31,6 +32,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/ import { SecretTextInput } from "../../components/ui/SecretTextInput"; import type { SecretTextInputHandle } from "../../components/ui/SecretTextInput.types"; import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { Button } from "../../components/ui/Button"; @@ -91,10 +93,13 @@ function PendingSecretRequestForm(props: { const inputs = secretRequestInputs(item, m); const multiple = item.fields !== undefined; const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); + // The server accepts a reference answer only with this scope; without it the card is typed. + const canUseReferences = useEnvironmentScope(props.environmentId, AuthProvidersManageScope); // A reference answers one value, so a card with fields is always typed. - const sources = multiple - ? NO_SOURCES - : secretRequestSources(config, config?.settings.secretProviders ?? {}, m); + const sources = + multiple || !canUseReferences + ? NO_SOURCES + : secretRequestSources(config, config?.settings.secretProviders ?? {}, m); const [sourceId, setSourceId] = useState(null); const source = sources.find((candidate) => candidate.id === sourceId) ?? null; const [values, setValues] = useState>>({}); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index d3b9c7cf76dc6..63fbe2ef5d3bf 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -66,9 +66,6 @@ import { } from "@t3tools/client-runtime/user-message"; import type { FyiCarrierRun } from "@t3tools/client-runtime/fork/fyi-marker"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; -import { turnChanges } from "@t3tools/client-runtime/state/thread-repositories"; -import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { AuthFilesystemReadScope, @@ -88,7 +85,12 @@ import { } from "@t3tools/contracts"; import type { ToolCallVisibility } from "@t3tools/contracts/settings"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; -import { hasThreadLinks, hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks"; +import { + hasThreadLinks, + hostedThreadLink, + parseThreadLinkHref, + threadLinkRefs, +} from "@t3tools/shared/threadLinks"; import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks"; import { parseComposerContextHref, @@ -212,8 +214,6 @@ import { type MediaVideoPreviewSource, } from "../../lib/videoPreviewSource"; import { CopyTextButton } from "./CopyTextButton"; -import { getReviewSectionIdForCheckpoint } from "../review/reviewModel"; -import { setReviewSelectedSectionId } from "../review/reviewState"; import { Menu } from "../../components/ui/Menu"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; import { useBarInset, useContentTopInset } from "../../components/ui/useBarInset"; @@ -345,6 +345,11 @@ import { } from "./threadFeedEndFollow"; import { useMessageTimeFormatter } from "./useMessageTimeFormatter"; +const linkedThreadEnvironmentIds = (markdown: string, environmentId: EnvironmentId) => + hasThreadLinks(markdown) + ? threadLinkRefs(markdown, environmentId).map((ref) => ref.environmentId) + : []; + const WIDE_MARKDOWN_BLOCK_OPTIONS = { // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width. includeBlockquotes: Platform.OS === "ios", @@ -1319,7 +1324,10 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { const liveMarkdown = useLiveThreadLinkLabels( props.markdown, props.environmentId, - useLinkedEnvironments(hasThreadLinks(props.markdown) ? props.environmentId : null), + useLinkedEnvironments( + hasThreadLinks(props.markdown) ? props.environmentId : null, + linkedThreadEnvironmentIds(props.markdown, props.environmentId), + ), ); const [quoteSelection, setQuoteSelection] = useState<{ markdown: string; @@ -1988,7 +1996,6 @@ function renderFeedEntry( readonly onToggleWorkRow: (rowId: string, anchorKey?: string, groupId?: string) => void; readonly onToggleUserMessage: (rowId: string, anchorKey: string) => void; readonly onToggleTurnFold: (runId: RunId) => void; - readonly onOpenTurnDiff: (checkpoint: ThreadCheckpointSummary) => void; readonly onPressPreview: (source: FilePreviewSource) => void; readonly onPlaybackStart: () => void; readonly markdownLinkHandlers: MarkdownLinkHandlers; @@ -2083,12 +2090,6 @@ function renderFeedEntry( onOpenDetails={props.onOpenSetupDetails} /> ) : null} - {entry.checkpointSummary ? ( - - ) : null} ); } @@ -2100,6 +2101,7 @@ function renderFeedEntry( iconSubtleColor={iconSubtleColor} label={entry.label} providerStartingLabel={entry.providerStartingLabel} + providerStartingDriver={entry.providerStartingDriver} /> ); } @@ -2179,14 +2181,6 @@ function renderFeedEntry( hasFailure={entry.hasFailure} shimmer={entry.shimmer} thought={entry.thought} - trailing={ - entry.checkpointSummary ? ( - - ) : null - } onToggle={() => props.onToggleWorkGroup(entry.groupId, entry.id)} /> ); @@ -2704,12 +2698,6 @@ function renderFeedEntry( onPressPreview={props.onPressPreview} onPlaybackStart={props.onPlaybackStart} /> - {showAssistantMeta && message.checkpointSummary ? ( - - ) : null} {showAssistantMeta ? ( void; -}) { - const gt = useGT(); - const { repositories, rootFiles, totals } = turnChanges(props.checkpoint); - const { additions, deletions } = totals; - const folderCount = repositories.length + (rootFiles.length > 0 ? 1 : 0); - const repositoriesLabel = - repositories.length === 0 - ? null - : folderCount === 1 - ? repositories[0]!.name - : gt("{count} repos", { count: folderCount }); - const changedIn = - repositories.length === 0 - ? null - : [ - ...(rootFiles.length > 0 ? [gt("this folder")] : []), - ...repositories.map((repository) => repository.name), - ].join(", "); - return ( - props.onOpenTurnDiff(props.checkpoint)} - className="min-h-11 shrink-0 flex-row items-center gap-2 px-2 active:bg-subtle" - > - {repositoriesLabel ? ( - - {repositoriesLabel} - - ) : null} - - +{formatDiffCount(additions)} - - - −{formatDiffCount(deletions)} - - - - ); -} - type UserMessageContentProps = { readonly text: string; readonly environmentId: EnvironmentId; @@ -2835,7 +2769,10 @@ function UserMessageContent(props: UserMessageContentProps) { const liveText = useLiveThreadLinkLabels( props.text, props.environmentId, - useLinkedEnvironments(hasThreadLinks(props.text) ? props.environmentId : null), + useLinkedEnvironments( + hasThreadLinks(props.text) ? props.environmentId : null, + linkedThreadEnvironmentIds(props.text, props.environmentId), + ), ); const threadIcons = useThreadChipIcons(props.environmentId, liveText, props.context?.records); const text = replaceComposerContextReferences(liveText, (ref) => { @@ -3178,19 +3115,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const [retainedMediaRowId, setRetainedMediaRowId] = useState(null); const focused = useIsFocused(); if (!focused && retainedMediaRowId !== null) setRetainedMediaRowId(null); - const onOpenTurnDiff = useCallback( - (checkpoint: ThreadCheckpointSummary) => { - setReviewSelectedSectionId( - scopedThreadKey(props.environmentId, props.threadId), - getReviewSectionIdForCheckpoint(checkpoint), - ); - navigation.navigate("ThreadReview", { - environmentId: props.environmentId, - threadId: props.threadId, - }); - }, - [navigation, props.environmentId, props.threadId], - ); const { themeAppearance } = useAppearancePreferences(); const copyFeedbackTimeoutRef = useRef | null>(null); const headerMaterialVisibleRef = useRef(false); @@ -4209,7 +4133,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { if (entry.type === "html-render") { return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth)); } - if (workRowSizing.fixedRowHeight === undefined || entry.checkpointSummary) { + if (workRowSizing.fixedRowHeight === undefined) { return undefined; } switch (entry.type) { @@ -4320,7 +4244,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onToggleWorkRow, onToggleUserMessage, onToggleTurnFold, - onOpenTurnDiff, onPressPreview, onPlaybackStart: onInlinePlaybackStart, markdownLinkHandlers, diff --git a/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts b/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts new file mode 100644 index 0000000000000..1538540949880 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts @@ -0,0 +1,9 @@ +import { expect, it } from "vite-plus/test"; + +import { compactMenuBranchLabel } from "./ThreadGitControls.logic"; + +it("keeps emoji whole at both cuts of a long branch name", () => { + expect(compactMenuBranchLabel("feature/abc😀-long-branch-name-😀-for-menus")).toBe( + "feature/abc…-for-menus", + ); +}); diff --git a/apps/mobile/src/features/threads/ThreadGitControls.logic.ts b/apps/mobile/src/features/threads/ThreadGitControls.logic.ts new file mode 100644 index 0000000000000..a3441835b5951 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.logic.ts @@ -0,0 +1,17 @@ +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; + +function truncateMiddle(value: string, maxLength: number): string { + if (value.length <= maxLength) { + return value; + } + + const headLength = Math.ceil((maxLength - 1) / 2); + const tailStart = value.length - Math.floor((maxLength - 1) / 2); + const headEnd = splitsSurrogatePair(value, headLength) ? headLength - 1 : headLength; + const tailFrom = splitsSurrogatePair(value, tailStart) ? tailStart + 1 : tailStart; + return `${value.slice(0, headEnd)}…${value.slice(tailFrom)}`; +} + +export function compactMenuBranchLabel(branch: string): string { + return truncateMiddle(branch, 24); +} diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 5e67fb0181ad5..9e7ab388ccee4 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -30,20 +30,7 @@ import { type TerminalMenuSession, } from "../terminal/terminalMenu"; import { projectScriptMenuLabel } from "@t3tools/shared/projectScriptsCopy"; - -function truncateMiddle(value: string, maxLength: number): string { - if (value.length <= maxLength) { - return value; - } - - const headLength = Math.ceil((maxLength - 1) / 2); - const tailLength = Math.floor((maxLength - 1) / 2); - return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`; -} - -function compactMenuBranchLabel(branch: string): string { - return truncateMiddle(branch, 24); -} +import { compactMenuBranchLabel } from "./ThreadGitControls.logic"; function compactMenuStatus(gitStatus: VcsStatusResult | null, resolve: MessageResolver): string { if (!gitStatus) { @@ -237,8 +224,6 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) { environmentId: String(environmentId), threadId: String(threadId), confirmAction: confirmableAction, - branchName, - includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"), }); return; } diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx index 4f5b799f82879..41aed6dfd3d9f 100644 --- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx +++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx @@ -39,6 +39,7 @@ import { useQuietThreadShell } from "../../state/entities"; import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; import { assetImageSource } from "../../lib/assetImageSource"; +import { appAtomRegistry } from "../../state/atom-registry"; import { beginQueuedRunEdit, useQueuedRunEdit } from "../../state/queued-run-edit"; import { environmentThreadDetails, threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -181,6 +182,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) { runId, messageId: entry.messageId, originalText: entry.text, + modelSelection: entry.message?.followsThreadSelection + ? (appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(target))?.projection + .thread.modelSelection ?? entry.run.modelSelection) + : entry.run.modelSelection, + followsThreadSelection: entry.message?.followsThreadSelection === true, existingAttachments: entry.attachments, ...(entry.context ? { context: entry.context } : {}), }, diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index 51fe125bf087e..fc14b7f172997 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -1502,10 +1502,11 @@ export function ExistingThreadSettingsRouteScreen({ const structure = useQuietThreadStructure(selectedThreadDetailRef); const reportedModelSelection = useThreadReportedModelSelection(selectedThreadDetailRef); const threadKey = scopedThreadKey(route.params.environmentId, route.params.threadId); - const draftSettings = useComposerDraftSettings(threadKey); const queuedRunEdit = useQueuedRunEdit(threadKey); // A queued edit can end while the sheet is open; the prompt then belongs to the thread's draft. const draftKey = activeComposerDraftKey(threadKey, route.params.draftKey, queuedRunEdit); + const draftSettings = useComposerDraftSettings(draftKey); + const threadDraftSettings = useComposerDraftSettings(threadKey); const prompt = useComposerDraft(draftKey).text; if (!selectedThread) { @@ -1567,7 +1568,7 @@ export function ExistingThreadSettingsRouteScreen({ rememberModelOptions(modelSelection.instanceId, modelSelection.model, options ?? []); updateModelSelection({ ...modelSelection, options }); }} - runtimeMode={draftSettings.runtimeMode ?? selectedThread.runtimeMode} + runtimeMode={threadDraftSettings.runtimeMode ?? selectedThread.runtimeMode} onUpdateRuntimeMode={(runtimeMode) => updateComposerDraftSettings(threadKey, { runtimeMode })} onClose={() => navigation.goBack()} /> diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx new file mode 100644 index 0000000000000..90b9580fd48bc --- /dev/null +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx @@ -0,0 +1,124 @@ +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +type ActionProps = { label: string; disabled?: boolean; onPress: () => void }; +type IntroProps = { title: string; description: string }; +const state = vi.hoisted(() => ({ + refName: null as string | null, + intro: null as IntroProps | null, + actions: [] as ActionProps[], + ran: [] as object[], +})); + +vi.mock("react-native", () => ({ + View: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("@react-navigation/native", () => ({ + useNavigation: () => ({ goBack: () => {} }), +})); +vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); +vi.mock("../../../components/ui/FitSheet", () => ({ + FitSheet: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../../components/ui/SheetIntro", () => ({ + SheetIntro: (props: IntroProps) => { + state.intro = props; + return null; + }, +})); +vi.mock("../../../state/query", () => ({ + useEnvironmentQuery: () => ({ + data: state.refName === null ? undefined : { refName: state.refName }, + }), +})); +vi.mock("../../../state/use-thread-selection", () => ({ + useThreadSelection: () => ({ + selectedThread: { environmentId: "environment" }, + selectedThreadProject: null, + }), +})); +vi.mock("../../../state/use-selected-thread-worktree", () => ({ + useSelectedThreadWorktree: () => ({ selectedThreadCwd: "/repo" }), +})); +vi.mock("../../../state/use-selected-thread-git-state", () => ({ + useSelectedThreadGitState: () => ({ selectedThreadBranches: [] }), +})); +vi.mock("../../../state/use-selected-thread-git-actions", () => ({ + useSelectedThreadGitActions: () => ({ + canWriteSourceControl: true, + canCreateFeatureBranch: true, + onRunSelectedThreadGitAction: (input: object) => { + state.ran.push(input); + return Promise.resolve(null); + }, + }), +})); +vi.mock("../../../state/vcs", () => ({ vcsEnvironment: { status: () => null } })); +vi.mock("../thread-inspector-navigation", () => ({ useReturnToThread: () => () => {} })); +vi.mock("./gitSheetComponents", () => ({ + SheetActionButton: (props: ActionProps) => { + state.actions.push(props); + return null; + }, +})); + +import { GitConfirmSheet } from "./GitConfirmSheet"; + +function setup(refName: string | null, params: Record) { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + state.refName = refName; + state.intro = null; + state.actions = []; + state.ran = []; + const root = createRoot(document.createElement("div")); + act(() => { + root.render( + , + ); + }); + // Each render registers Continue first, then the feature branch button. + const [continueButton, featureBranchButton] = state.actions.slice(-2); + return { + continueButton: continueButton!, + featureBranchButton: featureBranchButton!, + [Symbol.dispose]() { + act(() => root.unmount()); + }, + }; +} + +it("describes the action it runs on the branch that is checked out", async () => { + using screen = setup("main", { + confirmAction: "commit_push", + branchName: "docs", + includesCommit: "false", + commitMessage: "from the route", + filePaths: "a.ts,b.ts", + }); + expect(state.intro).toMatchObject({ + title: "Commit & push to default branch?", + description: expect.stringContaining('commit and push changes on "main"'), + }); + expect(screen.continueButton.label).toBe("Commit & push to main"); + await act(async () => screen.continueButton.onPress()); + await act(async () => screen.featureBranchButton.onPress()); + expect(state.ran).toEqual([ + { action: "commit_push" }, + { action: "commit_push", featureBranch: true }, + ]); +}); + +it.each([ + ["an action it does not confirm", "main", "commit"], + ["no checked out branch", null, "push"], +])("runs nothing for %s", async (_case, refName, confirmAction) => { + using screen = setup(refName, { confirmAction }); + expect(screen.continueButton.disabled).toBe(true); + expect(screen.featureBranchButton.disabled).toBe(true); + await act(async () => screen.continueButton.onPress()); + await act(async () => screen.featureBranchButton.onPress()); + expect(state.ran).toEqual([]); +}); diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index 1da0ec450a572..32a6fcbe22c2a 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -1,4 +1,7 @@ -import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime/state/vcs"; +import { + resolveDefaultBranchActionDialogCopy, + type DefaultBranchConfirmableAction, +} from "@t3tools/client-runtime/state/vcs"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; @@ -13,6 +16,7 @@ import { FitSheet } from "../../../components/ui/FitSheet"; import { SheetIntro } from "../../../components/ui/SheetIntro"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; +import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useEnvironmentQuery } from "../../../state/query"; import { @@ -28,13 +32,16 @@ type GitConfirmSheetProps = StaticScreenProps< readonly environmentId: string; readonly threadId: string; readonly confirmAction?: string; - readonly branchName?: string; - readonly includesCommit?: string; - readonly commitMessage?: string; - readonly filePaths?: string; } & GitRepositoryRouteParams >; +const CONFIRMABLE_ACTIONS: ReadonlyArray = [ + "push", + "create_pr", + "commit_push", + "commit_push_pr", +]; + export function GitConfirmSheet(props: GitConfirmSheetProps) { const gt = useGT(); const messages = useMessages(); @@ -45,37 +52,35 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const gitActions = useSelectedThreadGitActions(repository); const { canWriteSourceControl, canCreateFeatureBranch } = gitActions; const { selectedThread, selectedThreadProject } = useThreadSelection(); - // The overview that opened this sheet already holds the repository's status subscription. - const repositoryStatus = useEnvironmentQuery( - repository !== undefined && selectedThread !== null + const threadWorktree = useSelectedThreadWorktree(); + const selectedThreadCwd = repository?.cwd ?? threadWorktree.selectedThreadCwd; + // The Git controls that opened this sheet already hold the checkout's status subscription. + const gitStatus = useEnvironmentQuery( + selectedThread !== null && selectedThreadCwd !== null ? vcsEnvironment.status({ environmentId: selectedThread.environmentId, - input: { cwd: repository.cwd }, + input: { cwd: selectedThreadCwd }, }) : null, ); const terminology = sourceControlClients.get( repository === undefined ? selectedThreadProject?.repositoryIdentity?.provider - : repositoryStatus.data?.sourceControlProvider?.kind, + : gitStatus.data?.sourceControlProvider?.kind, ).changeRequest; const params = props.route.params; - const confirmAction = params.confirmAction as - | "push" - | "create_pr" - | "commit_push" - | "commit_push_pr" - | undefined; - const branchName = params.branchName ?? ""; - const includesCommit = params.includesCommit === "true"; + // The route only names the action; what the sheet says about it comes from the checkout. + const confirmAction = CONFIRMABLE_ACTIONS.find((action) => action === params.confirmAction); + const branchName = gitStatus.data?.refName ?? null; + const includesCommit = confirmAction === "commit_push" || confirmAction === "commit_push_pr"; const environmentId = params.environmentId ?? ""; const threadId = params.threadId ?? ""; const copy = useMemo( () => - confirmAction + confirmAction && branchName ? resolveDefaultBranchActionDialogCopy( { action: confirmAction, @@ -90,26 +95,17 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { ); const continuePendingAction = async () => { - if (!canWriteSourceControl || !confirmAction) return; + if (!canWriteSourceControl || !confirmAction || !copy) return; returnToThread({ environmentId, threadId }); - await gitActions.onRunSelectedThreadGitAction({ - action: confirmAction, - ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), - ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), - }); + await gitActions.onRunSelectedThreadGitAction({ action: confirmAction }); }; const movePendingActionToFeatureBranch = useCallback(async () => { - if (!canCreateFeatureBranch || !confirmAction) return; + if (!canCreateFeatureBranch || !confirmAction || !copy) return; returnToThread({ environmentId, threadId }); if (includesCommit) { - await gitActions.onRunSelectedThreadGitAction({ - action: confirmAction, - featureBranch: true, - ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), - ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), - }); + await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, featureBranch: true }); return; } @@ -129,10 +125,10 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { }, [ canCreateFeatureBranch, confirmAction, + copy, gitActions, gitState.selectedThreadBranches, includesCommit, - params, returnToThread, environmentId, threadId, @@ -153,13 +149,13 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { void continuePendingAction()} /> void movePendingActionToFeatureBranch()} /> diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index 0ab21904489e1..4c7225f5cbb4d 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -247,10 +247,6 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) { threadId: String(threadId), ...repositoryParams, confirmAction: confirmableAction, - branchName, - includesCommit: String( - input.action === "commit_push" || input.action === "commit_push_pr", - ), }), ); return; diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 7a18e1429934e..120270cb14072 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -1074,7 +1074,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { }, m, ), - { id: "mark-unread", title: gt("Mark unread"), image: "envelope.badge" }, + ...(thread.latestRun?.completedAt != null && threadCanArchive(thread.runtime) + ? [{ id: "mark-unread", title: gt("Mark unread"), image: "envelope.badge" }] + : []), ...(canTurnIntoProject ? [ { @@ -1091,6 +1093,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { gt, m, props.titleRegenerationSupported, + thread.latestRun, thread.runtime, isRegeneratingTitle, ], diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index f0bc00e11385e..e9178663e6e9a 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -1,3 +1,4 @@ +import { ProviderIcon } from "../../components/ProviderIcon"; import { Button } from "../../components/ui/Button"; import { ThreadSubagentGroup } from "./thread-subagent-group"; import { ProposedPlanCard } from "./ProposedPlanCard"; @@ -214,6 +215,7 @@ function ShimmerWorkContent(props: { readonly environmentId?: EnvironmentId; readonly highlighted: boolean; readonly icon: WorkContentIcon; + readonly iconNode?: ReactNode; readonly iconSubtleColor: ColorValue; readonly label: string; readonly onTextLayout?: ComponentProps["onTextLayout"]; @@ -225,7 +227,9 @@ function ShimmerWorkContent(props: { {props.showIcon ? ( - {props.toolIcon && props.environmentId ? ( + {props.iconNode !== undefined ? ( + props.iconNode + ) : props.toolIcon && props.environmentId ? ( { progress.setValue(0); @@ -315,6 +320,7 @@ export function ShimmeringWorkContent(props: { environmentId={props.environmentId} highlighted={false} icon={props.icon} + iconNode={props.iconNode} iconSubtleColor={props.iconSubtleColor} label={props.label} showIcon={props.showIcon} @@ -366,6 +372,7 @@ export function ShimmeringWorkContent(props: { environmentId={props.environmentId} highlighted icon={props.icon} + iconNode={props.iconNode} iconSubtleColor={props.iconSubtleColor} label={props.label} showIcon={props.showIcon} @@ -1413,7 +1420,6 @@ export function ThreadWorkGroupToggle(props: { readonly hasFailure: boolean; readonly shimmer: boolean; readonly thought?: string | undefined; - readonly trailing?: ReactNode; readonly onToggle: () => void; }) { const gt = useGT(); @@ -1503,7 +1509,6 @@ export function ThreadWorkGroupToggle(props: { /> - {props.trailing} ); @@ -1515,9 +1520,12 @@ export function ThreadThinkingRow(props: { readonly label?: string; /** Replaces "Thinking" while the provider has not started a turn. */ readonly providerStartingLabel?: string | undefined; + /** The starting provider, whose logo replaces the thinking icon. */ + readonly providerStartingDriver?: string | undefined; }) { const gt = useGT(); const label = props.providerStartingLabel ?? props.label ?? gt("Thinking"); + const driver = props.providerStartingDriver; return ( + + + ) + } iconSubtleColor={props.iconSubtleColor} label={label} showIcon diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts index 171d73a148597..e0771be61c5eb 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts @@ -64,10 +64,15 @@ describe("resolveSubagentRowPresentation", () => { it("falls back to a trimmed prompt when the agent has no title", () => { const long = resolveSubagentRowPresentation({ ...base, prompt: "x".repeat(200) }); + const emoji = resolveSubagentRowPresentation({ + ...base, + prompt: `${"x".repeat(76)}😀 and more`, + }); const titled = resolveSubagentRowPresentation({ ...base, title: "Subagent: /root/my_worker" }); expect(long.title).toHaveLength(80); expect(long.title.endsWith("...")).toBe(true); + expect(emoji.title).toBe(`${"x".repeat(76)}...`); expect(titled.title).toBe("My Worker"); }); diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.ts index 270cc1f3d7fbe..a5af5b0e6c5ed 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.ts @@ -7,6 +7,7 @@ import { } from "@t3tools/client-runtime/state/subagent-display"; import { isActiveSubagentStatus, + promptTitle, type RuntimeSubagent, type SubagentWorkflowGroup, } from "@t3tools/client-runtime/state/subagentRuntime"; @@ -22,8 +23,6 @@ import { msg } from "gt-react-native"; import { m, type MessageResolver } from "../../i18n/messages"; -const PROMPT_TITLE_LIMIT = 80; - export type SubagentRowTone = "working" | "completed" | "failed" | "stopped"; export interface SubagentRowPresentation { @@ -82,9 +81,7 @@ function rowTitle( if (title) return formatSubagentDisplayTitle(title); const prompt = subagent.prompt.trim(); if (prompt.length === 0) return resolve(msg("Subagent")); - return prompt.length > PROMPT_TITLE_LIMIT - ? `${prompt.slice(0, PROMPT_TITLE_LIMIT - 3)}...` - : prompt; + return promptTitle(prompt); } function rowTone(status: OrchestrationV2Subagent["status"]): SubagentRowTone { diff --git a/apps/mobile/src/i18n/native-locale.test.ts b/apps/mobile/src/i18n/native-locale.test.ts new file mode 100644 index 0000000000000..781eae9e898fb --- /dev/null +++ b/apps/mobile/src/i18n/native-locale.test.ts @@ -0,0 +1,55 @@ +import * as NodeChildProcess from "node:child_process"; +import * as NodeURL from "node:url"; +import { expect, it } from "vite-plus/test"; + +it("uses the new Android locale before native storage finishes writing it", () => { + // Load the real GT store in a subprocess because mobile's Vite config replaces GT. + const output = NodeChildProcess.execFileSync( + process.execPath, + [ + "--input-type=module", + "-e", + ` + import { createRequire, registerHooks } from "node:module"; + import { pathToFileURL } from "node:url"; + + const require = createRequire(process.cwd() + "/package.json"); + const gtEntry = pathToFileURL(require.resolve("gt-react-native")); + const androidBridge = "data:text/javascript," + encodeURIComponent(\` + const preferences = new Map(); + export const pending = []; + export const Platform = { OS: "android" }; + export const TurboModuleRegistry = { + getEnforcing: () => ({ + getNativeLocales: () => ["en-US"], + nativeStoreGet: (key) => preferences.get(key) ?? null, + nativeStoreSet: (key, value) => { + pending.push(() => preferences.set(key, value)); + }, + }), + }; + \`); + const hooks = registerHooks({ + resolve(specifier, context, nextResolve) { + return specifier === "react-native" + ? { url: androidBridge, shortCircuit: true } + : nextResolve(specifier, context); + }, + }); + const { initializeGT } = await import(new URL("./setup/initializeGT.js", gtEntry)); + const { NativeConditionStore } = await import( + new URL("./condition-store/NativeConditionStore.js", gtEntry) + ); + const { pending } = await import(androidBridge); + hooks.deregister(); + + initializeGT({ defaultLocale: "en", locales: ["en", "zh"] }); + new NativeConditionStore({ locale: "en" }); + for (const apply of pending.splice(0)) apply(); + console.log(new NativeConditionStore({ locale: "zh" }).getLocale()); + `, + ], + { cwd: NodeURL.fileURLToPath(new URL("../../", import.meta.url)), encoding: "utf8" }, + ); + expect(output.trim()).toBe("zh"); +}); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 10ed053228b10..330b89fafe2b6 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Fertig", "d4d89c139de812a8": "Fehlgeschlagen", "c1e03a860c856245": "Gestoppt", - "f1d27d127ab27ac6": "Wird gestartet", + "7e5abc299ead1d09": "{provider}-Plugins werden geladen", + "21872f69ccbc711d": "{provider}-MCP-Server werden gestartet", + "fedaa29ff8815a77": "{provider}-Hooks werden geladen", + "57025ae4de5beb57": "{provider}-Regeln und -Skills werden geladen", + "4729a188600f1501": "Verbindung zu {provider} wird hergestellt", "8c8977097681630f": "{provider} wird gestartet", + "f1d27d127ab27ac6": "Wird gestartet", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Wartet", "54002bf654ddbab1": "Abgeschlossen", @@ -1507,7 +1512,7 @@ "88b831780dfddb26": "Dieser Entwurf hat zu viel Kontext zum Senden. Entferne einige Kontextelemente und versuch es erneut.", "0df5fa81eb1674de": "Diese Kontextauswahl ist zu groß zum Kopieren. Wähle weniger Elemente aus.", "d80f9b03a38cc473": "Entferne einige Kontextelemente aus dem Entwurf, bevor du weitere einfügst.", - "62cb87ddfea69267": "Anhangslimit erreicht", + "62cb87ddfea69267": "Anhanglimit erreicht", "17daf9945d4378c7": "Erneut mit der Quellumgebung verbinden", "02c1fea7edd167cc": "Anhang-URL nicht verfügbar", "433237d7492c5401": "Die Zwischenablage ist leer.", @@ -1521,8 +1526,8 @@ "cb7049baa8fdacc4": "Videoanhänge sind hier nicht verfügbar.", "6c5e9cc01a8fd18f": "Nicht unterstützter Dateityp für ''{name}''.", "a8c3d59b323e4d6b": "''{name}'' konnte nicht gelesen werden.", - "1dc797c5c01c5d70": "''{name}'' überschreitet das Anhangslimit von 10 MB.", - "e4991173a9124f38": "Ein eingefügtes Bild überschreitet das Anhangslimit von 10 MB.", + "1dc797c5c01c5d70": "''{name}'' überschreitet das Anhanglimit von 10 MB.", + "e4991173a9124f38": "Ein eingefügtes Bild überschreitet das Anhanglimit von 10 MB.", "218c111b4aa6e029": "Ein eingefügtes Bild konnte nicht gelesen werden.", "ce88bed3d928cf6b": "Dieser Anhang ist nicht mehr verfügbar. Hänge die Datei erneut an.", "232298a82d027b3d": "Details", @@ -1884,7 +1889,7 @@ "6bf09d4b7e4ba53b": "T3 Code auf {environment} aktualisieren", "663465f828e70345": "Keine Verbindung zu {environment}", "d14ca43d8ae95c78": "{host} nicht erreichbar", - "b42f0ff267623384": "Auf {environment} läuft eine T3 Code-Version, die ihre localhost-Seiten nicht auf diesem Gerät öffnen kann. Aktualisiere sie dort und versuche es dann erneut.", + "b42f0ff267623384": "Auf {environment} läuft eine T3-Code-Version, die ihre localhost-Seiten nicht auf diesem Gerät öffnen kann. Aktualisiere sie dort und versuche es dann erneut.", "69e9c247d0266e9f": "Seiten auf dem localhost von {environment} laden über dessen Verbindung. Versuche es erneut, sobald die Verbindung wieder steht.", "301045c720839f4d": "Auf {environment} lauscht nichts auf Port {port}. Starte dort den Server und versuche es dann erneut.", "0b16434dff468d30": "Der Upload wurde abgelehnt.", @@ -3090,7 +3095,7 @@ "7b4c64fffd3019e3": "{term, select, mr {Merge Request schließen} cr {Änderungsanfrage schließen} other {Pull Request schließen}}", "c946b24a4da6aa7a": "{term, select, mr {Merge Request wieder öffnen} cr {Änderungsanfrage wieder öffnen} other {Pull Request wieder öffnen}}", "37948395ebd6d50d": "Branch aktualisieren", - "4812cf02a34c9a05": "{term, select, mr {Revert-Merge Request erstellen} cr {Revert-Änderungsanfrage erstellen} other {Revert-Pull Request erstellen}}", + "4812cf02a34c9a05": "{term, select, mr {Revert-Merge-Request erstellen} cr {Revert-Änderungsanfrage erstellen} other {Revert-Pull-Request erstellen}}", "e91d7bcfc952ecdc": "Branch löschen", "80cde74d5241204f": "{term, select, mr {Dieser Merge Request wurde gemergt.} cr {Diese Änderungsanfrage wurde gemergt.} other {Dieser Pull Request wurde gemergt.}}", "c62311139918f880": "{term, select, mr {Öffne diesen Merge Request vor dem Mergen wieder.} cr {Öffne diese Änderungsanfrage vor dem Mergen wieder.} other {Öffne diesen Pull Request vor dem Mergen wieder.}}", @@ -4646,10 +4651,6 @@ "ccde552cdff4a9e5": "Doppeltippen, um den Prompt anzuzeigen.", "630df4f8b78ab8d3": "Arbeitet seit {duration}", "01deb1ae9f51d3e0": "Arbeit konnte nicht geladen werden. Tippe, um es erneut zu versuchen.", - "868ed4fea1a3273c": "{count} Repos", - "c887abfd190d8b40": "diesem Ordner", - "275b5fe6040f2c1c": "{files, plural, one {{files} geänderte Datei prüfen, {additions} Hinzufügungen, {deletions} Löschungen} other {{files} geänderte Dateien prüfen, {additions} Hinzufügungen, {deletions} Löschungen}}", - "c4a35456c7bdc3a1": "{files, plural, one {{files} geänderte Datei in {folders} prüfen, {additions} Hinzufügungen, {deletions} Löschungen} other {{files} geänderte Dateien in {folders} prüfen, {additions} Hinzufügungen, {deletions} Löschungen}}", "7a13ae3b70a050fb": "{label} (nicht verfügbar)", "8f033834a0194c33": "Kontext nicht verfügbar", "4031ea1541b3ec2b": "Kontext öffnen", @@ -4851,7 +4852,7 @@ "6b2294cfd43aee15": "{name} (Gast)", "93ac0c76ae6a2a3b": "Die geteilten Inhalte sind nicht mehr im Posteingang.", "72e35523181b36eb": "Die Anhangsunterstützung des Servers wird noch geladen.", - "100ddd593ab0b485": "{count, plural, one {{count} geteilte Datei wurde übersprungen, weil dieser Entwurf das Anhangslimit erreicht hat.} other {{count} geteilte Dateien wurden übersprungen, weil dieser Entwurf das Anhangslimit erreicht hat.}}", + "100ddd593ab0b485": "{count, plural, one {{count} geteilte Datei wurde übersprungen, weil dieser Entwurf das Anhanglimit erreicht hat.} other {{count} geteilte Dateien wurden übersprungen, weil dieser Entwurf das Anhanglimit erreicht hat.}}", "a9d0457b171de12d": "Aktueller Worktree", "731c754897f77b89": "{term, select, mr {Aus MR #{number}} cr {Aus Änderungsanfrage #{number}} other {Aus PR #{number}}}", "3a05fec4b1d0f0a0": "Branch wählen", @@ -5001,10 +5002,10 @@ "2a6969164260cdee": "Pull Requests sind für dieses Projekt nicht verfügbar.", "a0ce478324829283": "{term, select, mr {Dieser Merge Request konnte nicht verknüpft werden} cr {Diese Änderungsanfrage konnte nicht verknüpft werden} other {Dieser Pull Request konnte nicht verknüpft werden}}", "962d13f9565f189b": "{term, select, mr {Die Verknüpfung dieses Merge Requests konnte nicht aufgehoben werden} cr {Die Verknüpfung dieser Änderungsanfrage konnte nicht aufgehoben werden} other {Die Verknüpfung dieses Pull Requests konnte nicht aufgehoben werden}}", - "0f9053e44ef763ec": "{term, select, mr {Füge eine Merge Request-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.} cr {Füge eine Änderungsanfrage-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.} other {Füge eine Pull Request-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.}}", - "e8c0bb0c1d4f43fe": "{term, select, mr {Merge Request-URL oder #42} cr {Änderungsanfrage-URL oder #42} other {Pull Request-URL oder #42}}", + "0f9053e44ef763ec": "{term, select, mr {Füge eine Merge-Request-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.} cr {Füge eine Änderungsanfrage-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.} other {Füge eine Pull-Request-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.}}", + "e8c0bb0c1d4f43fe": "{term, select, mr {Merge-Request-URL oder #42} cr {Änderungsanfrage-URL oder #42} other {Pull-Request-URL oder #42}}", "1ed642782ae61c57": "Verknüpfen", - "be61723be45aacfd": "{term, select, mr {Verwende eine Merge Request-URL, 123 oder #123.} cr {Verwende eine Änderungsanfrage-URL, 123 oder #123.} other {Verwende eine Pull Request-URL, 123 oder #123.}}", + "be61723be45aacfd": "{term, select, mr {Verwende eine Merge-Request-URL, 123 oder #123.} cr {Verwende eine Änderungsanfrage-URL, 123 oder #123.} other {Verwende eine Pull-Request-URL, 123 oder #123.}}", "ed09d936d8ba9792": "Beobachtung beenden", "af6adbd67cef13b1": "Auf Änderungen beobachten", "13eb3e529a3e9bff": "Aus dem Thread entfernen", @@ -5613,5 +5614,6 @@ "856812e7e1fc445e": "Tool-Aufrufe im Chat", "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", "99d51127f573296b": "Weiteres Konto", - "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer." + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "892f08d21b8e48a9": "{layers} per {kind, select, squash {Squash} merge {Merge} rebase {Rebase} fastForward {Fast-Forward} other {{method}}} in {base} mergen, sobald die Anforderungen erfüllt sind. Das kann sofort passieren." } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 312e7e4c60bbd..c930bce1b6b88 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Done", "d4d89c139de812a8": "Failed", "c1e03a860c856245": "Stopped", - "f1d27d127ab27ac6": "Starting", + "7e5abc299ead1d09": "Loading {provider} plugins", + "21872f69ccbc711d": "Starting {provider} MCP servers", + "fedaa29ff8815a77": "Loading {provider} hooks", + "57025ae4de5beb57": "Loading {provider} rules and skills", + "4729a188600f1501": "Connecting to {provider}", "8c8977097681630f": "Starting {provider}", + "f1d27d127ab27ac6": "Starting", "86d60d42f6cb4a40": "Idle", "0e8eab930d79d8b4": "Waiting", "54002bf654ddbab1": "Completed", @@ -4648,10 +4653,6 @@ "ccde552cdff4a9e5": "Double tap to show the prompt.", "630df4f8b78ab8d3": "Working for {duration}", "01deb1ae9f51d3e0": "Couldn't load work. Tap to retry.", - "868ed4fea1a3273c": "{count} repos", - "c887abfd190d8b40": "this folder", - "275b5fe6040f2c1c": "{files, plural, one {Review {files} file changed, {additions} additions, {deletions} deletions} other {Review {files} files changed, {additions} additions, {deletions} deletions}}", - "c4a35456c7bdc3a1": "{files, plural, one {Review {files} file changed in {folders}, {additions} additions, {deletions} deletions} other {Review {files} files changed in {folders}, {additions} additions, {deletions} deletions}}", "7a13ae3b70a050fb": "{label} (unavailable)", "8f033834a0194c33": "Context unavailable", "4031ea1541b3ec2b": "Open context", @@ -5615,5 +5616,6 @@ "856812e7e1fc445e": "Tool calls in chat", "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", "99d51127f573296b": "Another account", - "8ec2c57414669b79": "Connect a second {tracker} workspace or user." + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "892f08d21b8e48a9": "Merge {layers} into {base} using {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} once their requirements are met. This may happen immediately." } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 9124637171066..a809ff2b5ecb4 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminado", "d4d89c139de812a8": "Falló", "c1e03a860c856245": "Detenido", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Cargando plugins de {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP de {provider}", + "fedaa29ff8815a77": "Cargando hooks de {provider}", + "57025ae4de5beb57": "Cargando reglas y skills de {provider}", + "4729a188600f1501": "Conectando con {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Inactivo", "0e8eab930d79d8b4": "Esperando", "54002bf654ddbab1": "Completado", @@ -4639,10 +4644,6 @@ "ccde552cdff4a9e5": "Toca dos veces para mostrar el prompt.", "630df4f8b78ab8d3": "Trabajando durante {duration}", "01deb1ae9f51d3e0": "No se pudo cargar el trabajo. Toca para reintentar.", - "868ed4fea1a3273c": "{count} repos", - "c887abfd190d8b40": "esta carpeta", - "275b5fe6040f2c1c": "{files, plural, one {Revisar {files} archivo modificado, {additions} adiciones, {deletions} eliminaciones} other {Revisar {files} archivos modificados, {additions} adiciones, {deletions} eliminaciones}}", - "c4a35456c7bdc3a1": "{files, plural, one {Revisar {files} archivo modificado en {folders}, {additions} adiciones, {deletions} eliminaciones} other {Revisar {files} archivos modificados en {folders}, {additions} adiciones, {deletions} eliminaciones}}", "7a13ae3b70a050fb": "{label} (no disponible)", "8f033834a0194c33": "Contexto no disponible", "4031ea1541b3ec2b": "Abrir contexto", @@ -5607,5 +5608,6 @@ "856812e7e1fc445e": "Llamadas a herramientas en el chat", "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", "99d51127f573296b": "Otra cuenta", - "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}." + "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", + "892f08d21b8e48a9": "Fusionar {layers} en {base} con {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} cuando se cumplan sus requisitos. Puede ocurrir de inmediato." } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index ad9d49d83c52c..7cf4c8c8a1a07 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminé", "d4d89c139de812a8": "Échec", "c1e03a860c856245": "Arrêté", - "f1d27d127ab27ac6": "Démarrage", + "7e5abc299ead1d09": "Chargement des plugins de {provider}", + "21872f69ccbc711d": "Démarrage des serveurs MCP de {provider}", + "fedaa29ff8815a77": "Chargement des hooks de {provider}", + "57025ae4de5beb57": "Chargement des règles et des skills de {provider}", + "4729a188600f1501": "Connexion à {provider}", "8c8977097681630f": "Démarrage de {provider}", + "f1d27d127ab27ac6": "Démarrage", "86d60d42f6cb4a40": "Inactif", "0e8eab930d79d8b4": "En attente", "54002bf654ddbab1": "Terminé", @@ -4640,10 +4645,6 @@ "ccde552cdff4a9e5": "Touchez deux fois pour afficher le prompt.", "630df4f8b78ab8d3": "Au travail depuis {duration}", "01deb1ae9f51d3e0": "Impossible de charger le travail. Touchez pour réessayer.", - "868ed4fea1a3273c": "{count} dépôts", - "c887abfd190d8b40": "ce dossier", - "275b5fe6040f2c1c": "{files, plural, one {Relire {files} fichier modifié, {additions} ajouts, {deletions} suppressions} other {Relire {files} fichiers modifiés, {additions} ajouts, {deletions} suppressions}}", - "c4a35456c7bdc3a1": "{files, plural, one {Relire {files} fichier modifié dans {folders}, {additions} ajouts, {deletions} suppressions} other {Relire {files} fichiers modifiés dans {folders}, {additions} ajouts, {deletions} suppressions}}", "7a13ae3b70a050fb": "{label} (indisponible)", "8f033834a0194c33": "Contexte indisponible", "4031ea1541b3ec2b": "Ouvrir le contexte", @@ -5607,5 +5608,6 @@ "856812e7e1fc445e": "Appels d’outils dans la discussion", "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", "99d51127f573296b": "Autre compte", - "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}." + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "892f08d21b8e48a9": "Fusionner {layers} dans {base} avec {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} dès que leurs conditions sont remplies. Cela peut se produire immédiatement." } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index b80aeaddbb35a..6cd8a3892e03b 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完了", "d4d89c139de812a8": "失敗", "c1e03a860c856245": "停止", - "f1d27d127ab27ac6": "起動中", + "7e5abc299ead1d09": "{provider} のプラグインを読み込み中", + "21872f69ccbc711d": "{provider} の MCP サーバーを起動中", + "fedaa29ff8815a77": "{provider} のフックを読み込み中", + "57025ae4de5beb57": "{provider} のルールとスキルを読み込み中", + "4729a188600f1501": "{provider} に接続中", "8c8977097681630f": "{provider} を起動中", + "f1d27d127ab27ac6": "起動中", "86d60d42f6cb4a40": "アイドル", "0e8eab930d79d8b4": "待機中", "54002bf654ddbab1": "完了", @@ -4620,10 +4625,6 @@ "ccde552cdff4a9e5": "ダブルタップでプロンプトを表示します。", "630df4f8b78ab8d3": "{duration} 作業中", "01deb1ae9f51d3e0": "作業を読み込めませんでした。タップして再試行してください。", - "868ed4fea1a3273c": "{count} 件のリポジトリ", - "c887abfd190d8b40": "このフォルダー", - "275b5fe6040f2c1c": "{files, plural, other {{files} 個の変更ファイルをレビュー、{additions} 行追加、{deletions} 行削除}}", - "c4a35456c7bdc3a1": "{files, plural, other {{folders} の {files} 個の変更ファイルをレビュー、{additions} 行追加、{deletions} 行削除}}", "7a13ae3b70a050fb": "{label} (利用不可)", "8f033834a0194c33": "コンテキストを利用できません", "4031ea1541b3ec2b": "コンテキストを開く", @@ -5587,5 +5588,6 @@ "856812e7e1fc445e": "チャット内のツール呼び出し", "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", "99d51127f573296b": "別のアカウント", - "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。" + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "892f08d21b8e48a9": "要件が満たされたら、{layers} を{kind, select, squash {スカッシュ} merge {マージ} rebase {リベース} fastForward {早送り} other {{method}}}で {base} にマージします。すぐにマージされる場合があります。" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b35b6391337f1..3c6d213c2ae32 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "완료", "d4d89c139de812a8": "실패", "c1e03a860c856245": "중지됨", - "f1d27d127ab27ac6": "시작 중", + "7e5abc299ead1d09": "{provider} 플러그인 불러오는 중", + "21872f69ccbc711d": "{provider} MCP 서버 시작 중", + "fedaa29ff8815a77": "{provider} 훅 불러오는 중", + "57025ae4de5beb57": "{provider} 규칙 및 스킬 불러오는 중", + "4729a188600f1501": "{provider}에 연결 중", "8c8977097681630f": "{provider} 시작 중", + "f1d27d127ab27ac6": "시작 중", "86d60d42f6cb4a40": "유휴", "0e8eab930d79d8b4": "대기 중", "54002bf654ddbab1": "완료됨", @@ -4625,10 +4630,6 @@ "ccde552cdff4a9e5": "두 번 탭하여 프롬프트를 표시합니다.", "630df4f8b78ab8d3": "{duration} 동안 작업 중", "01deb1ae9f51d3e0": "작업을 불러올 수 없습니다. 탭하여 다시 시도하세요.", - "868ed4fea1a3273c": "저장소 {count}개", - "c887abfd190d8b40": "이 폴더", - "275b5fe6040f2c1c": "{files, plural, other {변경된 파일 {files}개 검토, 추가 {additions}줄, 삭제 {deletions}줄}}", - "c4a35456c7bdc3a1": "{files, plural, other {{folders}에서 변경된 파일 {files}개 검토, 추가 {additions}줄, 삭제 {deletions}줄}}", "7a13ae3b70a050fb": "{label}(사용할 수 없음)", "8f033834a0194c33": "컨텍스트를 사용할 수 없음", "4031ea1541b3ec2b": "컨텍스트 열기", @@ -5593,5 +5594,6 @@ "856812e7e1fc445e": "채팅의 도구 호출", "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", "99d51127f573296b": "다른 계정", - "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다." + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "892f08d21b8e48a9": "요구 사항이 충족되면 {layers}을(를) {kind, select, squash {스쿼시} merge {병합} rebase {리베이스} fastForward {빨리 감기} other {{method}}} 방식으로 {base}에 병합합니다. 바로 병합될 수도 있습니다." } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 037e9559e0aa3..3cf35e98426da 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Concluído", "d4d89c139de812a8": "Falhou", "c1e03a860c856245": "Parado", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Carregando plugins do {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP do {provider}", + "fedaa29ff8815a77": "Carregando hooks do {provider}", + "57025ae4de5beb57": "Carregando regras e skills do {provider}", + "4729a188600f1501": "Conectando ao {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Ocioso", "0e8eab930d79d8b4": "Aguardando", "54002bf654ddbab1": "Concluído", @@ -4640,10 +4645,6 @@ "ccde552cdff4a9e5": "Toque duas vezes para mostrar o prompt.", "630df4f8b78ab8d3": "Trabalhando há {duration}", "01deb1ae9f51d3e0": "Não foi possível carregar o trabalho. Toque para tentar novamente.", - "868ed4fea1a3273c": "{count} repos", - "c887abfd190d8b40": "esta pasta", - "275b5fe6040f2c1c": "{files, plural, one {Revisar {files} arquivo alterado, {additions} adições, {deletions} exclusões} other {Revisar {files} arquivos alterados, {additions} adições, {deletions} exclusões}}", - "c4a35456c7bdc3a1": "{files, plural, one {Revisar {files} arquivo alterado em {folders}, {additions} adições, {deletions} exclusões} other {Revisar {files} arquivos alterados em {folders}, {additions} adições, {deletions} exclusões}}", "7a13ae3b70a050fb": "{label} (indisponível)", "8f033834a0194c33": "Contexto indisponível", "4031ea1541b3ec2b": "Abrir contexto", @@ -5607,5 +5608,6 @@ "856812e7e1fc445e": "Chamadas de ferramentas no chat", "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", "99d51127f573296b": "Outra conta", - "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}." + "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", + "892f08d21b8e48a9": "Mesclar {layers} em {base} usando {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} quando os requisitos forem atendidos. Isso pode acontecer imediatamente." } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index a36a2f6e8716b..c0ac6fa81319c 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Готово", "d4d89c139de812a8": "Ошибка", "c1e03a860c856245": "Остановлено", - "f1d27d127ab27ac6": "Запуск", + "7e5abc299ead1d09": "Загрузка плагинов {provider}", + "21872f69ccbc711d": "Запуск MCP-серверов {provider}", + "fedaa29ff8815a77": "Загрузка хуков {provider}", + "57025ae4de5beb57": "Загрузка правил и навыков {provider}", + "4729a188600f1501": "Подключение к {provider}", "8c8977097681630f": "Запуск {provider}", + "f1d27d127ab27ac6": "Запуск", "86d60d42f6cb4a40": "Простаивает", "0e8eab930d79d8b4": "Ожидание", "54002bf654ddbab1": "Завершено", @@ -4718,10 +4723,6 @@ "ccde552cdff4a9e5": "Дважды нажмите, чтобы показать промпт.", "630df4f8b78ab8d3": "Работает {duration}", "01deb1ae9f51d3e0": "Не удалось загрузить работу. Нажмите, чтобы повторить.", - "868ed4fea1a3273c": "Репозиториев: {count}", - "c887abfd190d8b40": "эта папка", - "275b5fe6040f2c1c": "{files, plural, one {Ревью: изменён {files} файл, добавлений: {additions}, удалений: {deletions}} few {Ревью: изменено {files} файла, добавлений: {additions}, удалений: {deletions}} many {Ревью: изменено {files} файлов, добавлений: {additions}, удалений: {deletions}} other {Ревью: изменено {files} файла, добавлений: {additions}, удалений: {deletions}}}", - "c4a35456c7bdc3a1": "{files, plural, one {Ревью: изменён {files} файл в: {folders}, добавлений: {additions}, удалений: {deletions}} few {Ревью: изменено {files} файла в: {folders}, добавлений: {additions}, удалений: {deletions}} many {Ревью: изменено {files} файлов в: {folders}, добавлений: {additions}, удалений: {deletions}} other {Ревью: изменено {files} файла в: {folders}, добавлений: {additions}, удалений: {deletions}}}", "7a13ae3b70a050fb": "{label} (недоступно)", "8f033834a0194c33": "Контекст недоступен", "4031ea1541b3ec2b": "Открыть контекст", @@ -5687,5 +5688,6 @@ "856812e7e1fc445e": "Вызовы инструментов в чате", "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", "99d51127f573296b": "Другой аккаунт", - "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}." + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "892f08d21b8e48a9": "Слить {layers} в {base} методом {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}}, когда будут выполнены требования. Это может произойти сразу." } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 6c1040e3eb0b0..954d421c5a515 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Klar", "d4d89c139de812a8": "Misslyckades", "c1e03a860c856245": "Stoppad", - "f1d27d127ab27ac6": "Startar", + "7e5abc299ead1d09": "Läser in plugins för {provider}", + "21872f69ccbc711d": "Startar MCP-servrar för {provider}", + "fedaa29ff8815a77": "Läser in hooks för {provider}", + "57025ae4de5beb57": "Läser in regler och färdigheter för {provider}", + "4729a188600f1501": "Ansluter till {provider}", "8c8977097681630f": "Startar {provider}", + "f1d27d127ab27ac6": "Startar", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Väntar", "54002bf654ddbab1": "Slutförd", @@ -4646,10 +4651,6 @@ "ccde552cdff4a9e5": "Dubbeltryck för att visa prompten.", "630df4f8b78ab8d3": "Har arbetat i {duration}", "01deb1ae9f51d3e0": "Kunde inte läsa in arbetet. Tryck för att försöka igen.", - "868ed4fea1a3273c": "{count} repon", - "c887abfd190d8b40": "den här mappen", - "275b5fe6040f2c1c": "{files, plural, one {Granska {files} ändrad fil, {additions} tillägg, {deletions} borttagningar} other {Granska {files} ändrade filer, {additions} tillägg, {deletions} borttagningar}}", - "c4a35456c7bdc3a1": "{files, plural, one {Granska {files} ändrad fil i {folders}, {additions} tillägg, {deletions} borttagningar} other {Granska {files} ändrade filer i {folders}, {additions} tillägg, {deletions} borttagningar}}", "7a13ae3b70a050fb": "{label} (inte tillgänglig)", "8f033834a0194c33": "Kontexten är inte tillgänglig", "4031ea1541b3ec2b": "Öppna kontext", @@ -5613,5 +5614,6 @@ "856812e7e1fc445e": "Verktygsanrop i chatten", "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", "99d51127f573296b": "Ett konto till", - "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare." + "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", + "892f08d21b8e48a9": "Merga {layers} in i {base} med {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} när kraven är uppfyllda. Det kan ske direkt." } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 7f0cdbac92e7d..cd07ca7dad6c0 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完成", "d4d89c139de812a8": "失败", "c1e03a860c856245": "已停止", - "f1d27d127ab27ac6": "正在启动", + "7e5abc299ead1d09": "正在加载 {provider} 插件", + "21872f69ccbc711d": "正在启动 {provider} MCP 服务器", + "fedaa29ff8815a77": "正在加载 {provider} 钩子", + "57025ae4de5beb57": "正在加载 {provider} 规则和技能", + "4729a188600f1501": "正在连接 {provider}", "8c8977097681630f": "正在启动 {provider}", + "f1d27d127ab27ac6": "正在启动", "86d60d42f6cb4a40": "闲置", "0e8eab930d79d8b4": "等待中", "54002bf654ddbab1": "已完成", @@ -4629,10 +4634,6 @@ "ccde552cdff4a9e5": "轻点两下以显示提示词。", "630df4f8b78ab8d3": "已工作 {duration}", "01deb1ae9f51d3e0": "无法加载工作内容。轻点以重试。", - "868ed4fea1a3273c": "{count} 个仓库", - "c887abfd190d8b40": "此文件夹", - "275b5fe6040f2c1c": "{files, plural, other {审查 {files} 个已更改的文件,新增 {additions} 行,删除 {deletions} 行}}", - "c4a35456c7bdc3a1": "{files, plural, other {审查 {folders} 中 {files} 个已更改的文件,新增 {additions} 行,删除 {deletions} 行}}", "7a13ae3b70a050fb": "{label}(不可用)", "8f033834a0194c33": "上下文不可用", "4031ea1541b3ec2b": "打开上下文", @@ -5597,5 +5598,6 @@ "856812e7e1fc445e": "聊天中的工具调用", "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", "99d51127f573296b": "其他账号", - "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。" + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "892f08d21b8e48a9": "满足要求时使用{kind, select, squash {压缩合并} merge {合并} rebase {变基} fastForward {快进} other {{method}}}方式将 {layers} 合并到 {base}。这可能会立即发生。" } diff --git a/apps/mobile/src/lib/appLinking.test.ts b/apps/mobile/src/lib/appLinking.test.ts index 75db18a2337b8..09db1de62056a 100644 --- a/apps/mobile/src/lib/appLinking.test.ts +++ b/apps/mobile/src/lib/appLinking.test.ts @@ -91,6 +91,16 @@ describe("draft deep links", () => { }); }); + it.each(["/new/draft", "/new/draft/branch"])("drops the checkout a %s link names", (path) => { + const project = { environmentId: "env-1", projectId: "project-1" }; + const linked = { ...project, branch: "other", worktreePath: "/elsewhere" }; + const name = path === "/new/draft" ? "Thread" : "NewTaskBranch"; + expect(restoreDraftLinkState({ routes: [{ name, params: linked }] }, path)?.routes[0]).toEqual({ + name: "Thread", + params: { draft: project }, + }); + }); + it("leaves live-thread and project-selection links unchanged", () => { const state = { routes: [{ name: "Thread", params: { threadId: "thread-1" } }] }; expect(restoreDraftLinkState(state, "/threads/env-1/thread-1")).toBe(state); diff --git a/apps/mobile/src/lib/appLinking.ts b/apps/mobile/src/lib/appLinking.ts index 570c86b36abf4..fc448b4d02ac4 100644 --- a/apps/mobile/src/lib/appLinking.ts +++ b/apps/mobile/src/lib/appLinking.ts @@ -35,7 +35,14 @@ export function restoreDraftLinkState( if (!state || !pathname || !/^new\/draft(?:\/|$)/.test(pathname)) return state; const target = state.routes.at(-1); if (!target) return state; - const draft = target.params ?? {}; + // The draft screen checks out its branch on mount; the checkout comes from the draft, not the link. + const { + branch: _branch, + worktreePath: _worktreePath, + ...draft + } = (target.params ?? {}) as { + readonly [param: string]: unknown; + }; const routes = state.routes.slice(0, -1); routes.push({ name: "Thread", params: { draft } }); if (pathname !== "new/draft") routes.push(target); diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index b44b96fca49b8..c11d00bc9aae0 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -498,13 +498,44 @@ function markdownWithWindowsPathDestinations(markdown: string): string { return applyMarkdownEdits(markdown, edits); } +const isImage = (node: MarkdownNode) => node.type === "image" || node.type === "imageReference"; +const isSpace = (node: MarkdownNode) => + node.type === "break" || (node.type === "text" && node.value.trim() === ""); + +// Native Markdown sizes an image as a block only when it is its paragraph's only child. +function markdownWithImageParagraphs(markdown: string): string { + // Skips the extra parse unless a line ending sits between two images. + if (!/[\])][ \t]*\\?(?:\r\n?|\n)[ \t]*!\[/.test(markdown)) return markdown; + const edits: MarkdownEdit[] = []; + for (const block of parser.parse(markdown).children) { + if ( + block.type !== "paragraph" || + !block.children.every((child) => isImage(child) || isSpace(child)) + ) + continue; + const images = block.children.filter(isImage); + for (const [index, image] of images.slice(1).entries()) { + const start = images[index]!.position?.end.offset; + const end = image.position?.start.offset; + if (start === undefined || end === undefined) continue; + const ending = /\r\n?|\n/.exec(markdown.slice(start, end)); + if (ending) edits.push({ start, end, content: ending[0].repeat(2) }); + } + } + return applyMarkdownEdits(markdown, edits); +} + // HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first. -export function markdownForNativeParsing(markdown: string): string { +function normalizedMarkdown(markdown: string): string { return markdownWithWindowsPathDestinations(markdownWithHtml(markdown)); } +export function markdownForNativeParsing(markdown: string): string { + return markdownWithImageParagraphs(normalizedMarkdown(markdown)); +} + export function parseMarkdownDocument(markdown: string): Root { - return parser.parse(markdownForNativeParsing(markdown)); + return parser.parse(normalizedMarkdown(markdown)); } export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string { diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts index 64c5d02df3532..6cce7f84b475c 100644 --- a/apps/mobile/src/lib/markdownHtml.test.ts +++ b/apps/mobile/src/lib/markdownHtml.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { + markdownForNativeParsing, markdownForNativeRendering, markdownHtmlContent, markdownWithHtml, @@ -303,6 +304,30 @@ describe("file embeds in native thread and file Markdown", () => { } }); + it("gives each image on its own line its own native paragraph", async () => { + const images = + "![before](./before.png)\n![after light](./after-light.png) \\\n![after dark][dark]"; + const source = `Shots:\n\n${images}\n\n![a](./a.svg) ![b](./b.svg)\n![c](./c.svg)\n\nNext\n\n[dark]: ./after-dark.png`; + const paragraphs = ( + await parseMarkdown(markdownForNativeRendering(source, ENRICHED_INLINE_FILE_LINK_REGEX)) + ).children?.map((block) => block.children?.map((child) => child.type).join(" ")); + expect(paragraphs).toEqual([ + "Text", + "Image", + "Image", + "Image", + "Image Text Image", + "Image", + "Text", + ]); + expect(markdownForNativeParsing("![a](./a.png)\r\n![b](./b.png)")).toBe( + "![a](./a.png)\r\n\r\n![b](./b.png)", + ); + expect(markdownForNativeParsing("![a](./a.png)\r![b](./b.png)")).toBe( + "![a](./a.png)\r\r![b](./b.png)", + ); + }); + it("retains standalone audio players and image/video embeds in threads", () => { const source = "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)"; diff --git a/apps/mobile/src/lib/markdownLinks.test.ts b/apps/mobile/src/lib/markdownLinks.test.ts index 101a064b8e61f..142d084c56dae 100644 --- a/apps/mobile/src/lib/markdownLinks.test.ts +++ b/apps/mobile/src/lib/markdownLinks.test.ts @@ -70,6 +70,13 @@ describe("resolveMarkdownLinkPresentation", () => { }); }); + it("shows CommonJS sources with the JavaScript icon", () => { + expect(resolveMarkdownLinkPresentation("scripts/build.cjs")).toMatchObject({ + kind: "file", + icon: "javascript", + }); + }); + // regression: #8098 open agent file links in the file viewer it("recognizes spaced relative paths", () => { expect(resolveMarkdownLinkPresentation("docs/My%20Folder/checklist.xml")).toMatchObject({ diff --git a/apps/mobile/src/lib/markdownLinks.ts b/apps/mobile/src/lib/markdownLinks.ts index 55030cf03b859..77e5135484220 100644 --- a/apps/mobile/src/lib/markdownLinks.ts +++ b/apps/mobile/src/lib/markdownLinks.ts @@ -150,6 +150,7 @@ const FILE_ICON_BY_EXTENSION: Readonly> = { bz2: "zip", c: "c", cc: "cpp", + cjs: "javascript", cpp: "cpp", cxx: "cpp", css: "css", diff --git a/apps/mobile/src/lib/openExternalUrl.test.ts b/apps/mobile/src/lib/openExternalUrl.test.ts index 1dd1ff7db002b..f14037d99205f 100644 --- a/apps/mobile/src/lib/openExternalUrl.test.ts +++ b/apps/mobile/src/lib/openExternalUrl.test.ts @@ -1,7 +1,7 @@ import { Linking } from "react-native"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { tryOpenExternalUrl } from "./openExternalUrl"; +import { tryOpenExternalUrl, tryOpenWebLink } from "./openExternalUrl"; vi.mock("react-native", () => ({ Linking: { openURL: vi.fn() }, @@ -34,3 +34,16 @@ describe("tryOpenExternalUrl", () => { expect(diagnostics).not.toContain("43123"); }); }); + +describe("tryOpenWebLink", () => { + it("opens web, mail and phone links only", async () => { + openURL.mockResolvedValue(undefined); + for (const url of ["https://example.com/a", "HTTP://example.com", "mailto:a@example.com"]) { + await expect(tryOpenWebLink(url, "pull-request")).resolves.toBe(true); + } + for (const url of ["otherapp://open", "intent://x#Intent;end", "/owner/repo", ""]) { + await expect(tryOpenWebLink(url, "pull-request")).resolves.toBe(false); + } + expect(openURL).toHaveBeenCalledTimes(3); + }); +}); diff --git a/apps/mobile/src/lib/openExternalUrl.ts b/apps/mobile/src/lib/openExternalUrl.ts index 962769b184e33..d57442ac78045 100644 --- a/apps/mobile/src/lib/openExternalUrl.ts +++ b/apps/mobile/src/lib/openExternalUrl.ts @@ -61,3 +61,14 @@ export async function tryOpenExternalUrl( return false; } } + +/** + * For a link in rendered text, such as a pull request body: opens web, mail and phone links + * only. + */ +export async function tryOpenWebLink( + url: string, + target: ExternalUrlTarget = "external-link", +): Promise { + return /^(?:https?|mailto|tel):/i.test(url) && (await tryOpenExternalUrl(url, target)); +} diff --git a/apps/mobile/src/lib/projectThreadStartTurn.test.ts b/apps/mobile/src/lib/projectThreadStartTurn.test.ts index a4b21fec19448..d01a79e32ac47 100644 --- a/apps/mobile/src/lib/projectThreadStartTurn.test.ts +++ b/apps/mobile/src/lib/projectThreadStartTurn.test.ts @@ -5,6 +5,7 @@ import { serializeComposerMessageForServer } from "./composerContext"; import { buildProjectThreadStartTurnInput, + deriveThreadTitleFromPrompt, type ProjectThreadStartTurnSpec, } from "./projectThreadStartTurn"; @@ -98,4 +99,10 @@ describe("project thread title", () => { repositories: [{ path: "/workspace/api" }], }); }); + + it("shortens a long prompt without splitting an emoji", () => { + expect(deriveThreadTitleFromPrompt(`${"a".repeat(68)}😀 and the rest of the prompt`)).toBe( + `${"a".repeat(68)}...`, + ); + }); }); diff --git a/apps/mobile/src/lib/projectThreadStartTurn.ts b/apps/mobile/src/lib/projectThreadStartTurn.ts index c7e89d8c6e600..e4b550f6b5cd4 100644 --- a/apps/mobile/src/lib/projectThreadStartTurn.ts +++ b/apps/mobile/src/lib/projectThreadStartTurn.ts @@ -13,6 +13,7 @@ import { deriveThreadTitleSeed, threadTitleTextFromPrompt, } from "@t3tools/client-runtime/operations"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { msg } from "gt-react-native"; import { m } from "../i18n/messages"; @@ -95,5 +96,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe export function deriveThreadTitleFromPrompt(value: string): string { const title = threadTitleTextFromPrompt(value, m) || m(msg("New thread")); - return title.length <= 72 ? title : `${title.slice(0, 69).trimEnd()}...`; + if (title.length <= 72) return title; + const end = splitsSurrogatePair(title, 69) ? 68 : 69; + return `${title.slice(0, end).trimEnd()}...`; } diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 8d66dfaf5c520..49597ca0fdd7c 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -1,8 +1,5 @@ import { MessageId, - CheckpointId, - CheckpointRef, - CheckpointScopeId, RuntimeRequestId, NodeId, ProviderInstanceId, @@ -17,9 +14,7 @@ import { type OrchestrationV2ProjectedTurnItem, type OrchestrationV2TurnItem, } from "@t3tools/contracts"; -import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; import { summarizeToolGroup } from "@t3tools/client-runtime/work-log/presentation"; -import { getReviewSectionIdForCheckpoint } from "../features/review/reviewModel"; import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; @@ -568,144 +563,6 @@ describe("buildThreadFeed", () => { }, ); - it.each([false, true])( - "carries a late checkpoint to only the final answer without changing cached messages (cache: %s)", - (cached) => { - const cache = cached ? createThreadFeedCache() : undefined; - const earlier = { - ...assistantMessage(), - id: TurnItemId.make("earlier-item"), - messageId: MessageId.make("earlier-message"), - text: "Working on the files", - }; - const final = assistantMessage("2026-06-20T00:00:04.000Z"); - const rows = [projected(earlier, 0), projected(final, 1)]; - const before = buildThreadFeed(rows, { cache }); - const [summary] = deriveThreadCheckpointSummaries({ - messages: [earlier, final].map((message) => ({ - ...message, - id: message.messageId, - role: "assistant", - createdBy: "agent", - creationSource: "provider", - attachments: [], - createdAt: message.startedAt, - })), - checkpoints: [ - { - id: CheckpointId.make("checkpoint-final"), - threadId, - scopeId: CheckpointScopeId.make("scope"), - runId, - nodeId: NodeId.make("node"), - parentCheckpointId: null, - ordinalWithinScope: 1, - appRunOrdinal: 2, - ref: CheckpointRef.make("checkpoint-ref"), - status: "ready", - capturedAt: final.updatedAt, - files: [ - { path: "src/one.ts", kind: "modified", additions: 10, deletions: 2 }, - { path: "src/two.ts", kind: "added", additions: 5, deletions: 0 }, - ], - }, - ], - }); - expect(summary).toBeDefined(); - if (!summary) return; - const after = buildThreadFeed(rows, { checkpointSummaries: [summary], cache }); - expect(after[0]).toBe(before[0]); - expect(after[1]).toMatchObject({ - type: "message", - message: { id: final.messageId, checkpointSummary: summary }, - }); - expect(before[1]).not.toHaveProperty("message.checkpointSummary"); - expect(getReviewSectionIdForCheckpoint(summary)).toBe("turn:2"); - // A plain folder's own checkpoint is missing every turn; its repositories still changed. - const inRepository = { - ...summary, - status: "missing" as const, - files: [], - repositories: [ - { - scopeId: CheckpointScopeId.make("scope-api"), - name: "api", - repositoryPath: "/work/api", - cwd: "/work/api", - files: summary.files, - baselineMissing: false, - }, - ], - }; - expect(buildThreadFeed(rows, { checkpointSummaries: [inRepository] })[1]).toMatchObject({ - message: { checkpointSummary: inRepository }, - }); - const fallback = deriveThreadFeedPresentation( - [after.at(-1)!], - null, - new Set(), - new Set(), - null, - false, - cache, - ); - expect(fallback.at(-1)).toMatchObject({ message: { checkpointSummary: summary } }); - const workRows = [ - projected(userMessage(), 0), - projected(command(), 1), - projected({ ...command(), id: TurnItemId.make("second-command") }, 2), - projected(final, 3), - ]; - const workBefore = buildThreadFeed(workRows, { cache }); - deriveThreadFeedPresentation(workBefore, null, new Set(), new Set(), null, false, cache); - const workAfter = buildThreadFeed(workRows, { checkpointSummaries: [summary], cache }); - for (const expanded of [new Set(), new Set([runId])]) { - const presented = deriveThreadFeedPresentation( - workAfter, - null, - expanded, - new Set(), - null, - false, - cache, - ); - expect(presented.find((entry) => entry.type === "run-fold")).toMatchObject({ - checkpointSummary: summary, - }); - expect(presented.at(-1)).not.toHaveProperty("message.checkpointSummary"); - } - const active = deriveThreadFeedPresentation( - workAfter, - { - runId, - status: "running", - startedAt: "2026-06-20T00:00:00.000Z", - completedAt: null, - }, - new Set(), - new Set(), - null, - false, - cache, - ); - expect(active.find((entry) => entry.type === "work-toggle")).toMatchObject({ - checkpointSummary: summary, - }); - expect(active.at(-1)).not.toHaveProperty("message.checkpointSummary"); - expect(workBefore.at(-1)).not.toHaveProperty("message.checkpointSummary"); - - for (const checkpoint of [ - { ...summary, files: [] }, - ...(["missing", "error", "stale"] as const).map((status) => ({ ...summary, status })), - { ...summary, runId: RunId.make("another-run") }, - { ...summary, assistantMessageId: MessageId.make("unloaded-message") }, - ]) { - expect(buildThreadFeed(rows, { checkpointSummaries: [checkpoint], cache })).toEqual(before); - } - expect(buildThreadFeed(rows, { cache })).toEqual(before); - }, - ); - it("omits cached tool output and patch bodies from expanded and copied activity", () => { const rawOutput = "RAW_TOOL_OUTPUT"; const items: OrchestrationV2TurnItem[] = [ diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index c2ff4a4909d58..90158a0fd437e 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -4,8 +4,6 @@ import type { } from "@t3tools/client-runtime/state/thread-requests"; import { linkRequestTargetName } from "@t3tools/client-runtime/link-request"; import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; -import { turnHasChanges } from "@t3tools/client-runtime/state/thread-repositories"; import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { isLiveSubagentTurnItem, @@ -157,7 +155,6 @@ export interface ThreadFeedMessage { readonly createdAt: string; readonly updatedAt: string; readonly projectedItem?: OrchestrationV2ProjectedTurnItem; - readonly checkpointSummary?: ThreadCheckpointSummary; } export interface LocalThreadMessage { @@ -213,7 +210,6 @@ type RawThreadFeedEntry = export type ThreadFeedEntry = ThreadFeedEntryContent & { readonly continuesWorkLog?: boolean; - readonly checkpointSummary?: ThreadCheckpointSummary; }; type ThreadFeedEntryContent = @@ -270,6 +266,8 @@ type ThreadFeedEntryContent = readonly label?: string; /** Shown instead of "Thinking" while the provider has not started a turn. */ readonly providerStartingLabel?: string; + /** The starting provider's driver, whose logo replaces the thinking icon. */ + readonly providerStartingDriver?: string; }; export interface ThreadFeedLatestRun { @@ -280,6 +278,7 @@ export interface ThreadFeedLatestRun { readonly turnEnded?: boolean; readonly providerStartingLabel?: string; readonly providerStartingLabelMsg?: string; + readonly providerStarting?: { readonly driver: string }; } /** Long Android headers can ANR despite one-line display; cap labels only, preserving expanded and copied text. */ @@ -1499,7 +1498,8 @@ function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLate left.completedAt === right.completedAt && left.turnEnded === right.turnEnded && left.providerStartingLabel === right.providerStartingLabel && - left.providerStartingLabelMsg === right.providerStartingLabelMsg) + left.providerStartingLabelMsg === right.providerStartingLabelMsg && + left.providerStarting?.driver === right.providerStarting?.driver) ); } @@ -1991,42 +1991,10 @@ export function deriveThreadFeedPresentation( latestRun?.providerStartingLabelMsg === undefined ? latestRun?.providerStartingLabel : resolve(latestRun.providerStartingLabelMsg), + latestRun?.providerStarting?.driver, ), ); } - const checkpointByRunId = new Map(); - for (const entry of sourceFeed) { - if (entry.type === "message" && entry.message.checkpointSummary) { - checkpointByRunId.set(entry.message.checkpointSummary.runId, entry.message.checkpointSummary); - } - } - const workRowByRunId = new Map(); - for (let index = tailStart; index < result.length; index += 1) { - const row = result[index]!; - if ( - (row.type === "run-fold" || row.type === "work-toggle") && - row.runId !== null && - checkpointByRunId.has(row.runId) && - (row.type === "run-fold" || !workRowByRunId.has(row.runId)) - ) { - workRowByRunId.set(row.runId, index); - } - } - for (const [runId, index] of workRowByRunId) { - result[index] = { ...result[index]!, checkpointSummary: checkpointByRunId.get(runId)! }; - } - for (let index = tailStart; index < result.length; index += 1) { - const row = result[index]!; - if ( - row.type !== "message" || - !row.message.checkpointSummary || - !workRowByRunId.has(row.message.checkpointSummary.runId) - ) - continue; - const message = { ...row.message }; - delete message.checkpointSummary; - result[index] = { ...row, message }; - } // Reused rows are final: the user message after them never continues a work log. for (let index = tailStart; index < result.length; index += 1) { const row = result[index]!; @@ -2137,12 +2105,14 @@ function thinkingRow( runId: RunId | null, label: string | null, providerStartingLabel: string | undefined, + providerStartingDriver: string | undefined, ) { if ( cachedThinkingRow?.createdAt !== createdAt || cachedThinkingRow.runId !== runId || (cachedThinkingRow.label ?? null) !== label || - cachedThinkingRow.providerStartingLabel !== providerStartingLabel + cachedThinkingRow.providerStartingLabel !== providerStartingLabel || + cachedThinkingRow.providerStartingDriver !== providerStartingDriver ) { cachedThinkingRow = { type: "thinking", @@ -2151,6 +2121,9 @@ function thinkingRow( runId, ...(label === null ? {} : { label }), ...(providerStartingLabel === undefined ? {} : { providerStartingLabel }), + ...(providerStartingLabel === undefined || providerStartingDriver === undefined + ? {} + : { providerStartingDriver }), }; } return cachedThinkingRow; @@ -2468,7 +2441,6 @@ interface ThreadFeedBuild { readonly locale: string | undefined; readonly attempts: ReadonlyArray | undefined; readonly nodes: ReadonlyArray | undefined; - readonly checkpointSummaries: ReadonlyArray | undefined; readonly foldedAnswerRunIdByMessageId: ReadonlyMap; readonly delegatedChildrenByRun: ReadonlyMap>; readonly feed: ReadonlyArray; @@ -2495,31 +2467,6 @@ function setsEqual(left: ReadonlySet, right: ReadonlySet): boolean { return true; } -// Summaries are re-derived whenever messages change, including streamed text, -// so a new array often holds the same checkpoints. -function checkpointSummariesEqual( - left: ReadonlyArray | undefined, - right: ReadonlyArray | undefined, -): boolean { - if (left === right) return true; - if (left === undefined || right === undefined || left.length !== right.length) return false; - return left.every((summary, index) => { - const other = right[index]!; - return ( - summary.checkpointId === other.checkpointId && - summary.scopeId === other.scopeId && - summary.runId === other.runId && - summary.checkpointTurnCount === other.checkpointTurnCount && - summary.checkpointRef === other.checkpointRef && - summary.completedAt === other.completedAt && - summary.status === other.status && - summary.files === other.files && - summary.repositories === other.repositories && - summary.assistantMessageId === other.assistantMessageId - ); - }); -} - function mapsEqual(left: ReadonlyMap, right: ReadonlyMap): boolean { if (left.size !== right.size) return false; for (const [key, value] of left) { @@ -2554,7 +2501,6 @@ export function buildThreadFeed( readonly anchoredMessages?: ReadonlyArray; readonly attempts?: ReadonlyArray; readonly nodes?: ReadonlyArray; - readonly checkpointSummaries?: ReadonlyArray; readonly cache?: ThreadFeedCache; readonly resolve?: MessageResolver; /** Keys the caches; text comes from `resolve`. */ @@ -2608,7 +2554,6 @@ export function buildThreadFeed( previous.locale === locale && previous.attempts === options?.attempts && previous.nodes === options?.nodes && - checkpointSummariesEqual(previous.checkpointSummaries, options?.checkpointSummaries) && mapsEqual(previous.foldedAnswerRunIdByMessageId, foldedAnswerRunIdByMessageId) && setMapsEqual(previous.delegatedChildrenByRun, delegatedChildrenByRun) ) { @@ -2804,23 +2749,8 @@ export function buildThreadFeed( if (insertionIndex === -1) entries.push(entry); else entries.splice(insertionIndex, 0, entry); } - const checkpointByMessageId = new Map( - (options?.checkpointSummaries ?? []) - // A plain folder holding repositories never has a ready checkpoint of its own. - .filter( - (checkpoint) => - (checkpoint.status === "ready" || checkpoint.repositories !== undefined) && - turnHasChanges(checkpoint), - ) - .map((checkpoint) => [checkpoint.assistantMessageId, checkpoint]), - ); const grouped = groupAdjacentActivities( - entries.map((entry) => { - if (entry.type !== "message" || entry.message.role !== "assistant") return entry; - const checkpointSummary = checkpointByMessageId.get(entry.message.id); - if (!checkpointSummary || checkpointSummary.runId !== entry.message.runId) return entry; - return { ...entry, message: { ...entry.message, checkpointSummary } }; - }), + entries, delegatedChildrenByRun, // Anchored messages shift entries away from their rows; such a build is not reused. anchoredMessages.length > 0 @@ -2841,7 +2771,6 @@ export function buildThreadFeed( locale, attempts: options?.attempts, nodes: options?.nodes, - checkpointSummaries: options?.checkpointSummaries, foldedAnswerRunIdByMessageId, delegatedChildrenByRun, feed, diff --git a/apps/mobile/src/native/useOpenPullRequest.ts b/apps/mobile/src/native/useOpenPullRequest.ts index b492ece6fbef5..aac80fb3004a4 100644 --- a/apps/mobile/src/native/useOpenPullRequest.ts +++ b/apps/mobile/src/native/useOpenPullRequest.ts @@ -7,7 +7,7 @@ import { import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useProjects, useThreadShell } from "../state/entities"; -import { tryOpenExternalUrl } from "../lib/openExternalUrl"; +import { tryOpenWebLink } from "../lib/openExternalUrl"; import { appAtomRegistry } from "../state/atom-registry"; import { environmentServerConfigsAtom } from "../state/server"; import { issueTrackerEnvironment } from "../state/issueTrackers"; @@ -59,7 +59,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean trackers: connections?._tag === "Success" ? connections.value : undefined, }) : null; - if (!issue || !environmentId) return tryOpenExternalUrl(url, "pull-request"); + if (!issue || !environmentId) return tryOpenWebLink(url, "pull-request"); const candidate = pullRequestCandidateForIssueLink(url, issue.ref); if (candidate) { const preview = await readPreview({ environmentId, input: candidate.target }); @@ -76,7 +76,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean return true; } // A dropped connection says nothing about what the link names; the browser knows. - if (isAtomCommandInterrupted(preview)) return tryOpenExternalUrl(url, "pull-request"); + if (isAtomCommandInterrupted(preview)) return tryOpenWebLink(url, "pull-request"); } const issueParams = { environmentId, diff --git a/apps/mobile/src/state/linkedThread.ts b/apps/mobile/src/state/linkedThread.ts index ff4c75b9ac1ac..8a0adc790940e 100644 --- a/apps/mobile/src/state/linkedThread.ts +++ b/apps/mobile/src/state/linkedThread.ts @@ -27,16 +27,14 @@ export function useLinkedThreadReach( const own = presentationById.get(id); return own && { connected: own.connection.phase === "connected" }; }; - const links = useLinkedEnvironments( - subagents.some( - (subagent) => - subagent.childThreadId === null && - subagent.remoteChild !== undefined && - ownConnection(subagent.remoteChild.environmentId)?.connected !== true, - ) - ? environmentId - : null, + const remote = subagents.flatMap((subagent) => + subagent.childThreadId === null && + subagent.remoteChild !== undefined && + ownConnection(subagent.remoteChild.environmentId)?.connected !== true + ? [subagent.remoteChild.environmentId] + : [], ); + const links = useLinkedEnvironments(remote.length > 0 ? environmentId : null, remote); return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) }; } diff --git a/apps/mobile/src/state/peerLinks.ts b/apps/mobile/src/state/peerLinks.ts index 40a13f2150234..ae403a4e72068 100644 --- a/apps/mobile/src/state/peerLinks.ts +++ b/apps/mobile/src/state/peerLinks.ts @@ -1,4 +1,4 @@ -import { useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { linkableMachines, linkedEnvironmentNames, @@ -6,7 +6,7 @@ import { } from "@t3tools/client-runtime/link-request"; import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks"; import type { EnvironmentId } from "@t3tools/contracts"; -import { useEffect, useEffectEvent, useMemo } from "react"; +import { useContext, useEffect, useEffectEvent, useMemo } from "react"; import { connectionAtomRuntime } from "../connection/runtime"; import { useEnvironments } from "./environments"; @@ -19,19 +19,36 @@ export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtom /** * The machines `environmentId` links to, by name, while it offers links, and none otherwise. * Its agents can read threads there, and so can a client allowed to read threads on it. + * A `wanted` machine this app is not connected to and the names lack makes them reread. */ export function useLinkedEnvironments( environmentId: EnvironmentId | null, + wanted: ReadonlyArray = [], ): ReadonlyMap { const { environments } = useEnvironments(); const offered = offersLinkedEnvironments( environments.find((environment) => environment.environmentId === environmentId)?.serverConfig, ); + const queried = offered ? environmentId : null; const links = useEnvironmentQuery( - offered && environmentId !== null - ? peerLinkEnvironment.names({ environmentId, input: {} }) - : null, + queried === null ? null : peerLinkEnvironment.names({ environmentId: queried, input: {} }), ); + const connected = new Set( + environments + .filter((environment) => environment.connection.phase === "connected") + .map((environment) => environment.environmentId), + ); + const missing = [...new Set(wanted)].filter((id) => id !== environmentId && !connected.has(id)); + const refreshKey = + queried === null || missing.length === 0 ? "" : [queried, ...[...missing].sort()].join(" "); + const registry = useContext(RegistryContext); + const refreshLacking = useEffectEvent(() => { + if (queried !== null) peerLinkEnvironment.refreshNamesLacking(registry, queried, missing); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links made outside this app are not pushed, so meeting an unknown machine asks the server again + useEffect(() => { + if (refreshKey !== "") refreshLacking(); + }, [refreshKey]); return useMemo( () => linkedEnvironmentNames({ links: offered ? (links.data?.links ?? []) : [], environments }), [environments, links.data, offered], diff --git a/apps/mobile/src/state/queued-run-edit.test.ts b/apps/mobile/src/state/queued-run-edit.test.ts index 8a6176c1140c0..b2c06709518be 100644 --- a/apps/mobile/src/state/queued-run-edit.test.ts +++ b/apps/mobile/src/state/queued-run-edit.test.ts @@ -8,14 +8,20 @@ import { ChatAttachmentId, ComposerContextId, MessageId, + EnvironmentId, + ThreadId, + ProviderInstanceId, RunId, type ChatAttachment, type OrchestrationMessageContext, } from "@t3tools/contracts"; +import { selectThreadModel } from "./thread-model-selection"; +import { scopedThreadKey } from "../lib/scopedEntities"; import { appAtomRegistry } from "./atom-registry"; import { activeComposerDraftKey, + startQueuedRunEditSave, beginQueuedRunEdit, getQueuedRunEdit, queuedEditDraftKey, @@ -31,6 +37,13 @@ import { waitForComposerDraftsLoaded, } from "./use-composer-drafts"; +vi.mock("../components/ui/Dialog", () => ({ alert: vi.fn() })); +vi.mock("./session", () => ({ readEnvironmentScope: () => false })); +vi.mock("./threads", () => ({ + environmentThreadShells: { threadShellAtom: () => Atom.make(null) }, + threadEnvironment: { setModelSelection: {} }, +})); + vi.mock("expo-file-system", () => ({ Directory: class { create() {} @@ -266,3 +279,27 @@ describe("activeComposerDraftKey", () => { expect(activeComposerDraftKey(threadKey, editKey, null)).toBe(threadKey); }); }); + +it("blocks model and option picks while a queued edit save is in flight", () => { + const ref = { + environmentId: EnvironmentId.make("env-model-save"), + threadId: ThreadId.make("thread"), + }; + const threadKey = scopedThreadKey(ref.environmentId, ref.threadId); + const originalSelection = { instanceId: ProviderInstanceId.make("codex"), model: "original" }; + const edited = { ...edit([]), modelSelection: originalSelection }; + const draftKey = queuedEditDraftKey(threadKey, edited.runId); + const runs = Atom.make([{ id: edited.runId, status: "queued" }]); + beginQueuedRunEdit(threadKey, edited, runs); + const finishSave = startQueuedRunEditSave(threadKey)!; + const changed = { + ...originalSelection, + model: "changed", + options: [{ id: "effort", value: "high" }], + }; + selectThreadModel({ ...ref, draftKey }, changed); + expect(getComposerDraftSnapshot(draftKey).modelSelection).toEqual(originalSelection); + finishSave(false); + selectThreadModel({ ...ref, draftKey }, changed); + expect(getComposerDraftSnapshot(draftKey).modelSelection).toEqual(changed); +}); diff --git a/apps/mobile/src/state/queued-run-edit.ts b/apps/mobile/src/state/queued-run-edit.ts index 3c046f847f29f..2ab7a6729165b 100644 --- a/apps/mobile/src/state/queued-run-edit.ts +++ b/apps/mobile/src/state/queued-run-edit.ts @@ -1,10 +1,12 @@ import type { ChatAttachment, MessageId, + ModelSelection, OrchestrationMessageContext, RunId, UploadChatAttachment, } from "@t3tools/contracts"; +import * as Equal from "effect/Equal"; import { useAtomValue } from "@effect/atom-react"; import { msg } from "gt-react-native"; import { stripAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; @@ -26,9 +28,12 @@ import { mergeComposerDraftContent, setComposerDraftContext, setComposerDraftText, + updateComposerDraftSettings, } from "./use-composer-drafts"; export interface QueuedRunEdit { + readonly modelSelection?: ModelSelection; + readonly followsThreadSelection?: boolean; readonly runId: RunId; readonly messageId: MessageId; readonly originalText: string; @@ -47,6 +52,9 @@ export { queuedEditDraftKey } from "./queued-edit-draft-key"; export const getQueuedRunEdit = queuedRunEdits.get; +export const isQueuedRunEditSaving = (threadKey: string): boolean => + appAtomRegistry.get(queuedRunEdits.savingAtom)[threadKey] === true; + /** * The draft a sheet opened for `requestedKey` should edit now: a queued edit's * draft only while that edit is still open, else the thread's own draft. @@ -77,8 +85,12 @@ function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void { const editDraft = getComposerDraftSnapshot(editDraftKey); const threadDraft = getComposerDraftSnapshot(threadKey); const editRestorable = editDraft.text.trim().length > 0 || editDraft.attachments.length > 0; + const modelChanged = + editDraft.modelSelection !== undefined && + !Equal.equals(editDraft.modelSelection, edit.modelSelection); const recovery = resolveQueuedEditExit({ editChanged: + modelChanged || editDraft.text !== edit.originalText || editDraft.attachments.length > 0 || edit.removedExistingAttachment === true, @@ -89,6 +101,8 @@ function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void { threadDraft.attachments.length === 0, }); if (recovery === "kept") { + if (modelChanged) + updateComposerDraftSettings(threadKey, { modelSelection: editDraft.modelSelection }); // The merge publishes the draft before writing it, so a failed write only delays persistence to the next one. mergeComposerDraftContent(threadKey, { text: editDraft.text, @@ -124,6 +138,8 @@ export function beginQueuedRunEdit( const originalText = stripAttachmentOnlyBootstrapPrompt(edit.originalText); clearComposerDraft(draftKey); setComposerDraftText(draftKey, originalText); + if (edit.modelSelection && !edit.followsThreadSelection) + updateComposerDraftSettings(draftKey, { modelSelection: edit.modelSelection }); setComposerDraftContext(draftKey, edit.context); queuedRunEdits.begin( threadKey, diff --git a/apps/mobile/src/state/thread-model-selection.ts b/apps/mobile/src/state/thread-model-selection.ts index fd6bca2dd6a4c..aa0ed03e07a2f 100644 --- a/apps/mobile/src/state/thread-model-selection.ts +++ b/apps/mobile/src/state/thread-model-selection.ts @@ -12,6 +12,7 @@ import * as Dialog from "../components/ui/Dialog"; import { msg } from "gt-react-native"; import { m } from "../i18n/messages"; import { appAtomRegistry } from "./atom-registry"; +import { activeComposerDraftKey, getQueuedRunEdit, isQueuedRunEditSaving } from "./queued-run-edit"; import { readEnvironmentScope } from "./session"; import { environmentThreadShells, threadEnvironment } from "./threads"; import { @@ -21,13 +22,24 @@ import { /** Sets an existing thread's pick on the thread, so any next turn runs on it. */ export function selectThreadModel( - ref: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, + ref: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly draftKey?: string; + }, value: ModelSelection, ): void { const threadKey = scopedThreadKey(ref.environmentId, ref.threadId); // Its own object, so an older reply for an equal pick cannot release this one. const modelSelection = { ...value }; - updateComposerDraftSettings(threadKey, { modelSelection }); + const draftKey = activeComposerDraftKey( + threadKey, + ref.draftKey ?? threadKey, + getQueuedRunEdit(threadKey), + ); + if (draftKey !== threadKey && isQueuedRunEditSaving(threadKey)) return; + updateComposerDraftSettings(draftKey, { modelSelection }); + if (draftKey !== threadKey) return; const thread = appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref)); // Another instance replaces the live session, which may hold an open question; that pick // still waits for a sent message. diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 9f7765684252d..4f2a4364169d8 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -7,7 +7,6 @@ import { readEnvironmentScope } from "./session"; import { useAtomValue } from "@effect/atom-react"; import { compactBeforeSendTokens } from "@t3tools/client-runtime/state/context-window"; import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { @@ -155,7 +154,6 @@ function setKeepFullHistory(threadKey: string, keep: boolean) { appAtomRegistry.set(fullHistoryThreadKeysAtom, keep ? { ...rest, [threadKey]: true } : rest); } -const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make>([]); const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0); export function appendReviewCommentToDraft(input: { @@ -295,11 +293,6 @@ export function useThreadComposerState(input: { messages: selectedThreadMessages, }); }, [acknowledgedMessages, selectedThreadKey, selectedThreadSequence, selectedThreadMessages]); - const checkpointSummaries = useAtomValue( - selectedThreadDetailRef === null - ? EMPTY_CHECKPOINT_SUMMARIES_ATOM - : environmentThreadDetails.checkpointSummariesAtom(selectedThreadDetailRef), - ); // A thread whose creation has not delivered its turn yet: the prompt only // exists in the outbox, so it is appended to whatever the server has. The // detail is usually present but empty during a worktree checkout, so this @@ -316,7 +309,6 @@ export function useThreadComposerState(input: { anchoredMessages: pendingCreation, attempts: selectedThreadAttempts, nodes: selectedThreadNodes, - checkpointSummaries, cache: feedCache, resolve, locale, @@ -355,7 +347,8 @@ export function useThreadComposerState(input: { : queuedRunEdit === null ? selectedThreadKey : queuedEditDraftKey(selectedThreadKey, queuedRunEdit.runId); - const selectedDraft = useComposerDraftSettings(selectedThreadKey); + const selectedDraft = useComposerDraftSettings(composerDraftKey); + const threadDraftSettings = useComposerDraftSettings(selectedThreadKey); const selectedThreadQueueCount = selectedThreadQueuedMessages.length; const selectedThread = selectedThreadShell; const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; @@ -367,7 +360,7 @@ export function useThreadComposerState(input: { : modelSelection, serverConfig?.providers ?? [], ); - const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null; + const runtimeMode = threadDraftSettings.runtimeMode ?? selectedThread?.runtimeMode ?? null; // Plan mode is not offered to users; every send runs in build mode. const interactionMode = selectedThread ? DEFAULT_PROVIDER_INTERACTION_MODE : null; const canSwitchThreadProvider = threadAllowsProviderSwitch({ @@ -596,6 +589,9 @@ export function useThreadComposerState(input: { threadId: thread.id, runId: edit.runId, text: restoreAttachmentOnlyBootstrapPrompt(text, payload.attachments.length > 0), + ...(!edit.followsThreadSelection || draft.modelSelection + ? { modelSelection: draft.modelSelection ?? thread.modelSelection } + : {}), edit: { messageId: edit.messageId, attachments: payload.attachments, diff --git a/apps/mobile/src/widgets/AgentActivity.test.ts b/apps/mobile/src/widgets/AgentActivity.test.ts new file mode 100644 index 0000000000000..9ad17d330f5ac --- /dev/null +++ b/apps/mobile/src/widgets/AgentActivity.test.ts @@ -0,0 +1,83 @@ +import type { LiveActivityLayout } from "expo-widgets"; +import { describe, expect, it, vi } from "vite-plus/test"; + +vi.mock("@expo/ui/swift-ui", () => ({ + HStack: "HStack", + Image: "Image", + Spacer: "Spacer", + Text: "Text", + VStack: "VStack", + ZStack: "ZStack", +})); + +vi.mock("@expo/ui/swift-ui/modifiers", () => { + const modifier = (value: unknown) => value; + return { + accessibilityElement: modifier, + accessibilityLabel: modifier, + activityBackgroundTint: modifier, + font: modifier, + foregroundStyle: modifier, + frame: modifier, + layoutPriority: modifier, + lineLimit: modifier, + minimumScaleFactor: modifier, + padding: modifier, + resizable: modifier, + widgetURL: modifier, + }; +}); + +// Hand back the layout function so the test can render it with a chosen environment. +vi.mock("expo-widgets", () => ({ + createLiveActivity: (_name: string, layout: unknown) => layout, +})); + +import AgentActivity, { + type AgentActivityProps, + type AgentActivityRowProps, +} from "./AgentActivity"; + +const render = AgentActivity as unknown as ( + props: AgentActivityProps, + environment: unknown, +) => LiveActivityLayout; + +function row(overrides: Partial): AgentActivityRowProps { + return { + environmentId: "env-1", + threadId: "thread-1", + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "Model", + phase: "running", + status: "Working", + updatedAt: "2026-01-01T00:00:00.000Z", + deepLink: "/threads/env-1/thread-1", + ...overrides, + }; +} + +describe("AgentActivity", () => { + it("drops the agent count from the expanded Dynamic Island once the activity is stale", () => { + const layout = render( + { + title: "Agents", + subtitle: "", + activeCount: 2, + updatedAt: "2026-01-01T00:00:00.000Z", + activities: [row({}), row({ threadId: "thread-2", phase: "starting" })], + }, + { + colorScheme: "dark", + isLuminanceReduced: false, + isLiquidGlassAvailable: false, + isStale: true, + widgetRenderingMode: "fullColor", + }, + ); + const expandedLeading = JSON.stringify(layout.expandedLeading); + expect(expandedLeading).not.toContain('"children":"2"'); + expect(expandedLeading).toContain('"children":"Out of date"'); + }); +}); diff --git a/apps/mobile/src/widgets/AgentActivity.tsx b/apps/mobile/src/widgets/AgentActivity.tsx index 0c1017272f895..2def7e7e75f20 100644 --- a/apps/mobile/src/widgets/AgentActivity.tsx +++ b/apps/mobile/src/widgets/AgentActivity.tsx @@ -389,7 +389,7 @@ function AgentActivity( {renderLogo(15, tint)} - {allDone ? doneLabel : `${props.activeCount}`} + {allDone || environment.isStale ? activeLabel : `${props.activeCount}`} ), diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 436cea63f4f28..584ac4ae67968 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -8,6 +8,7 @@ const reactTests = [ "src/features/threads/ThreadGuestShareSheet.test.tsx", "src/features/threads/useSubmitAfterNativeImages.test.tsx", "src/features/threads/git/GitBranchesSheet.test.tsx", + "src/features/threads/git/GitConfirmSheet.test.tsx", "src/features/threads/new-task-flow-provider.test.tsx", "src/features/threads/NewTaskRouteScreen.test.tsx", "src/features/layout/workspace/workspace-tabs-state.test.ts", diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index c81b01b0fe604..d92b5e6a4aab8 100644 --- a/apps/server/scripts/migrate-dev-db.test.ts +++ b/apps/server/scripts/migrate-dev-db.test.ts @@ -7,7 +7,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import { runMigrations } from "../src/persistence/Migrations.ts"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; -import { runMigrateDevDb } from "./migrate-dev-db.ts"; +import { dropResumableFamilies, runMigrateDevDb } from "./migrate-dev-db.ts"; const withDatabase = ( databasePath: string, @@ -102,6 +102,8 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio ["subagent-parent", "project-kept", "completed", "{}", "2026-08-05"], ["subagent-child", "project-kept", "completed", subagentPayload, "2026-08-05"], ["deleted-project-thread", "project-deleted", "completed", "{}", "2026-08-05"], + // Finished, but startup recovery would deliver its unread steer and start a turn. + ["steer-thread", "project-kept", "completed", "{}", "2026-08-09"], ] as const; for (const [threadId, projectId, runStatus, payload, updatedAt] of threads) { yield* sql`INSERT INTO orchestration_v2_projection_threads @@ -114,6 +116,10 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio (event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version) VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}', 2)`; } + yield* sql`INSERT INTO orchestration_v2_projection_turn_items + (turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json) + VALUES ('steer-item', 'steer-thread', 'run-steer-thread', 2, 'user_message', 'pending', + '2026-08-09', '{"inputIntent":"steer"}')`; // A V1 thread the server already imported must not trip the legacy guard. yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, created_at, updated_at) @@ -244,6 +250,78 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { }), ); + it.effect("drops resumable families from a seed in place, the pending steer included", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-resumable-" }); + const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-home-" }); + const database = yield* createFixtureSource(dir); + + assert.equal(yield* dropResumableFamilies(database, { sharedHome }), 4); + const { threads, sessions } = yield* withDatabase( + database, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return { + threads: yield* sql<{ thread_id: string }>` + SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`, + sessions: yield* sql<{ provider_session_id: string }>` + SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`, + }; + }), + ); + assert.deepStrictEqual( + threads.map((row) => row.thread_id), + [ + "archived-thread", + "deleted-project-thread", + "fork-thread", + "settled-thread", + "stopped-thread", + ], + ); + assert.deepStrictEqual( + sessions.map((row) => row.provider_session_id), + ["session-shared"], + "a session the kept stopped-thread still binds stays with it", + ); + assert.equal(yield* dropResumableFamilies(database, { sharedHome }), 0); + }), + ); + + it.effect("refuses to drop from the shared database through a symlink or a hard link", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" }); + const elsewhere = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-link-" }); + const fixture = yield* createFixtureSource(sharedHome); + const live = path.join(sharedHome, "userdata", "statev2.sqlite"); + yield* fs.makeDirectory(path.dirname(live), { recursive: true }); + yield* fs.rename(fixture, live); + const symlink = path.join(elsewhere, "statev2.sqlite"); + yield* fs.symlink(live, symlink); + // A hard link has its own path; only the file's identity gives it away. + const hardLink = path.join(elsewhere, "copy.sqlite"); + yield* fs.link(live, hardLink); + + for (const link of [symlink, hardLink]) { + const refused = yield* Effect.flip(dropResumableFamilies(link, { sharedHome })); + assert.equal(refused._tag, "MigrateDevDbSharedHomeError", link); + } + const threads = yield* withDatabase( + live, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const [row] = yield* sql<{ n: number }>` + SELECT COUNT(*) AS n FROM orchestration_v2_projection_threads`; + return Number(row?.n ?? 0); + }), + ); + assert.equal(threads, 10, "the shared database is untouched"); + }), + ); + it.effect("never copies an archived thread, and new events append after the source's", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/scripts/migrate-dev-db.ts b/apps/server/scripts/migrate-dev-db.ts index b44e7c52ea14f..858806c1de706 100644 --- a/apps/server/scripts/migrate-dev-db.ts +++ b/apps/server/scripts/migrate-dev-db.ts @@ -18,6 +18,7 @@ import { Command, Flag } from "effect/cli"; import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts"; import { rebuildMessageSearch } from "../src/orchestration-v2/messageSearchIndex.ts"; import { runMigrations } from "../src/persistence/Migrations.ts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; export class MigrateDevDbNotInWorktreeError extends Schema.TaggedError()( @@ -195,12 +196,19 @@ const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: } }); -const RECOVERY_KINDS: ReadonlyArray = [ - "queued-runs", - "runtime", - "subagent-results", - "delegated-completions", -]; +// Every kind startup recovery resumes, so a copied family never starts work by itself. The record +// fails typecheck when a kind is added and not listed here. +const RECOVERY_KIND_SET = { + "queued-runs": true, + runtime: true, + "restart-continuations": true, + "subagent-results": true, + "delegated-completions": true, + "unread-steers": true, +} satisfies Record; +const RECOVERY_KINDS = Object.keys( + RECOVERY_KIND_SET, +) as ReadonlyArray; const CLEARED_TABLES: ReadonlyArray = [ "scheduled_tasks", @@ -322,19 +330,17 @@ const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath: yield* sql`DETACH DATABASE src`; }); -const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) { +/** + * Threads a server started on this database would resume by itself: every startup recovery kind, + * plus latest-run failures and recovery choices, which usage-limit recovery can resume. + */ +export const resumableThreadIds = Effect.fn("resumableDevDbThreadIds")(function* () { const sql = yield* SqlClient.SqlClient; - - // Usage-limit recovery also depends on settings; exclude latest-run failures and recovery choices. const projections = yield* ProjectionStore.ProjectionStoreV2; - const recoveryThreadIds = yield* Effect.forEach(RECOVERY_KINDS, (kind) => + const recovery = yield* Effect.forEach(RECOVERY_KINDS, (kind) => projections.getRecoveryThreadIds(kind), ); - yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`; - for (const threadId of new Set(recoveryThreadIds.flat())) { - yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`; - } - yield* sql`INSERT OR IGNORE INTO live_threads (thread_id) + const failedOrRecovering = yield* sql<{ thread_id: string }>` SELECT r.thread_id FROM orchestration_v2_projection_runs r WHERE r.status = 'failed' AND r.ordinal = ( SELECT MAX(latest.ordinal) FROM orchestration_v2_projection_runs latest @@ -342,6 +348,121 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra UNION SELECT thread_id FROM orchestration_v2_projection_threads WHERE json_extract(payload_json, '$.limitRecovery') IS NOT NULL`; + return [ + ...new Set([...recovery.flat(), ...failedOrRecovering.map((row) => row.thread_id)]), + ]; +}); + +export class MigrateDevDbResumableWorkError extends Schema.TaggedError()( + "MigrateDevDbResumableWorkError", + { databasePath: Schema.String, threads: Schema.Number }, +) { + override get message() { + return `${this.databasePath} still holds ${this.threads} threads a server would resume.`; + } +} + +/** + * Drops, in place, every thread family a server started on `databasePath` would resume, and fails + * if any remain. A database seeded by an older checkout can miss a recovery kind added since. + */ +export const dropResumableFamilies = Effect.fn("dropResumableDevDbFamilies")(function* ( + databasePath: string, + options: RunMigrateDevDbOptions = {}, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const platform = yield* HostProcess.Platform; + // A symlink, `..` or another letter case can name the live database; compare where they lead. + const resolve = (file: string) => + fs.realPath(file).pipe( + Effect.catch(() => + fs + .realPath(path.dirname(file)) + .pipe(Effect.map((dir) => path.join(dir, path.basename(file)))), + ), + Effect.orElseSucceed(() => path.resolve(file)), + ); + const comparable = (resolved: string) => + platform === "linux" ? resolved : resolved.toLowerCase(); + // A hard link has its own path, so the file itself is compared too. + const identity = (file: string) => + fs.stat(file).pipe( + Effect.map((info) => Option.map(info.ino, (ino) => `${info.dev}:${ino}`)), + Effect.orElseSucceed(() => Option.none()), + ); + const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3")); + const liveDatabase = path.join(sharedHome, "userdata", "statev2.sqlite"); + const [target, live] = yield* Effect.all([resolve(databasePath), resolve(liveDatabase)]); + const targetIdentity = yield* identity(target); + const liveIdentities = yield* Effect.forEach( + [liveDatabase, `${liveDatabase}-wal`, `${liveDatabase}-shm`], + identity, + ); + if ( + comparable(target) === comparable(live) || + (Option.isSome(targetIdentity) && + liveIdentities.some( + (candidate) => Option.isSome(candidate) && candidate.value === targetIdentity.value, + )) + ) { + return yield* new MigrateDevDbSharedHomeError(); + } + // Beside the real file, where a running server keeps its runtime state. + yield* ensureNotInUse(target); + return yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const resumable = yield* resumableThreadIds(); + if (resumable.length > 0) { + yield* sql`CREATE TEMP TABLE resumable_families (thread_id TEXT PRIMARY KEY)`; + yield* sql`INSERT OR IGNORE INTO resumable_families + SELECT family.thread_id FROM orchestration_v2_projection_threads family + WHERE COALESCE(json_extract(family.payload_json, '$.lineage.rootThreadId'), family.thread_id) IN ( + SELECT COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id) + FROM orchestration_v2_projection_threads WHERE thread_id IN ${sql.in(resumable)})`; + yield* sql.withTransaction( + Effect.gen(function* () { + for (const { name } of yield* sql<{ name: string }>` + SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c + WHERE m.type = 'table' AND c.name = 'thread_id' + AND m.name <> ${PROVIDER_SESSIONS_TABLE}`) { + yield* sql`DELETE FROM ${sql(name)} + WHERE thread_id IN (SELECT thread_id FROM resumable_families)`; + } + // A session a kept thread still binds stays, as pruning keeps it. + yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)} + WHERE thread_id IN (SELECT thread_id FROM resumable_families) + AND provider_session_id NOT IN ( + SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings + WHERE thread_id NOT IN (SELECT thread_id FROM resumable_families) + )`; + yield* sql`DELETE FROM orchestration_v2_projection_context_transfers + WHERE source_thread_id IN (SELECT thread_id FROM resumable_families) + OR target_thread_id IN (SELECT thread_id FROM resumable_families)`; + yield* sql`DELETE FROM orchestration_events WHERE aggregate_kind = 'thread' + AND stream_id IN (SELECT thread_id FROM resumable_families)`; + }), + ); + } + const left = yield* resumableThreadIds(); + if (left.length > 0) { + return yield* new MigrateDevDbResumableWorkError({ databasePath, threads: left.length }); + } + return resumable.length; + }).pipe( + Effect.provide( + ProjectionStore.layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename: target }))), + ), + ); +}); + +const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) { + const sql = yield* SqlClient.SqlClient; + + yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`; + for (const threadId of yield* resumableThreadIds()) { + yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`; + } // Clone or drop whole thread families to preserve fork and subagent lineage reads. yield* sql`CREATE TEMP TABLE thread_families AS @@ -641,9 +762,20 @@ export const migrateDevDbCommand = Command.make( Flag.optional, Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."), ), + dropResumable: Flag.String("drop-resumable").pipe( + Flag.optional, + Flag.withDescription( + "Only drop, in place, the thread families a server started on this database would resume, and fail if any remain. Copies only; never the live database.", + ), + ), }, - ({ projects, threadsPerProject, baseDir, source }) => + ({ projects, threadsPerProject, baseDir, source, dropResumable }) => Effect.gen(function* () { + if (Option.isSome(dropResumable)) { + const dropped = yield* dropResumableFamilies(dropResumable.value); + yield* Console.log(`Dropped ${dropped} resumable threads.`); + return; + } const result = yield* runMigrateDevDb({ projects, threadsPerProject, diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index a5c65894b26df..8734aa70cc20d 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -757,7 +757,7 @@ describe("AssetAccess", () => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "t3-link-" })); - yield* fs.writeFileString(path.join(root, "payload.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); yield* fs.writeFileString(path.join(root, "real.pdf"), "%PDF-1.4"); const link = path.join(root, "report.pdf"); const issue = issueAssetUrl({ @@ -774,7 +774,7 @@ describe("AssetAccess", () => { return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); }; - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); yield* fs.remove(link); @@ -785,7 +785,7 @@ describe("AssetAccess", () => { }); yield* fs.remove(link); - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect(yield* resolveIssued(issued.relativeUrl)).toBeNull(); }).pipe(Effect.provide(layerTest)), ); @@ -1314,8 +1314,16 @@ describe("AssetAccess", () => { const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-asset-revision-" }); const pages = path.join(root, "pages"); yield* fileSystem.makeDirectory(pages); + // Coarse kernel clocks can stamp two quick same-size writes alike, so each edit gets its own mtime. + let editedAt = 1_000; const write = (name: string, text: string) => - fileSystem.writeFileString(path.join(pages, name), text); + fileSystem + .writeFileString(path.join(pages, name), text) + .pipe( + Effect.andThen( + Effect.promise(() => NodeFSP.utimes(path.join(pages, name), ++editedAt, editedAt)), + ), + ); yield* write("a.html", ''); yield* write("a.css", "body { color: red; }"); yield* write("b.html", "

b

"); @@ -1815,6 +1823,51 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.skipIf(!symlinksSupported)("refuses a favicon link whose target is not an image", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-" }), + ); + const pictures = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-pictures-" }), + ); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "real.svg"), ""); + const resolveIssued = (relativeUrl: string) => { + const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); + }; + for (const link of [path.join(root, "favicon.svg"), path.join(pictures, "custom.svg")]) { + const issue = issueAssetUrl({ + resource: { _tag: "project-favicon", cwd: root }, + ...(link.startsWith(pictures) ? { projectFaviconPath: link } : {}), + }); + + yield* fs.symlink(path.join(root, "page.xhtml"), link); + expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "real.svg"), link); + const issued = yield* issue; + expect(yield* resolveIssued(issued.relativeUrl)).toEqual({ + kind: "file", + path: path.join(root, "real.svg"), + }); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); + // An outside icon's URL names its target, so repointing the link cannot change it. + expect(yield* resolveIssued(issued.relativeUrl)).toEqual( + link.startsWith(pictures) ? { kind: "file", path: path.join(root, "real.svg") } : null, + ); + yield* fs.remove(link); + } + }).pipe(Effect.provide(layerTest)), + ); + it.effect("ignores a client favicon path hint", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 4054eb91f1e4e..6807bf1820684 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -288,6 +288,8 @@ const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(functio const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* ( filePath: string, ) { + // Checked again here: a link can be repointed after its URL was issued. + if (!isProjectFaviconPath(filePath)) return null; if (!filePath.toLowerCase().endsWith(".icns")) { return { kind: "file", path: filePath } satisfies ResolvedAsset; } @@ -825,6 +827,10 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i resource: input.resource, }); } + // A favicon link must resolve to an image file. + if (canonicalFaviconPath && !isProjectFaviconPath(canonicalFaviconPath)) { + return yield* new AssetPreviewTypeValidationError({ resource: input.resource }); + } claims = isExternalOverride && canonicalFaviconPath ? { diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index c800c166b9e03..f8f6cc1f118ab 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -20,6 +20,7 @@ import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import * as PairingGrantStore from "./PairingGrantStore.ts"; import * as ServerSecretStore from "./ServerSecretStore.ts"; import * as SessionStore from "./SessionStore.ts"; @@ -957,6 +958,49 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( ), ); + it.effect("issues no session to an exchange that revoking all others overtook", () => + Effect.gen(function* () { + const pairingLinks = yield* PairingGrantStore.PairingGrantStore; + let afterSpend: Effect.Effect = Effect.void; + const serverAuth = yield* EnvironmentAuth.make.pipe( + Effect.provideService(PairingGrantStore.PairingGrantStore, { + ...pairingLinks, + consume: (credential, input) => + pairingLinks.consume(credential, input).pipe(Effect.tap(() => afterSpend)), + }), + Effect.provide( + Layer.merge( + ManagedPolicy.layerTest(), + ServerSecretStore.layer.pipe(Layer.provideMerge(layerServerConfig())), + ), + ), + ); + const owner = yield* serverAuth.issueSession(); + const succeeded = { onFailure: () => false, onSuccess: () => true }; + const exchanges = [ + (credential: string) => + serverAuth + .createBrowserSession(credential, requestMetadata) + .pipe(Effect.match(succeeded)), + (credential: string) => + serverAuth + .exchangeBootstrapCredentialForAccessToken(credential, undefined, requestMetadata) + .pipe(Effect.match(succeeded)), + ]; + for (const exchange of exchanges) { + const pairing = yield* serverAuth.issuePairingCredential(); + afterSpend = serverAuth.revokeOtherClientSessions(owner.sessionId).pipe(Effect.orDie); + const exchanged = yield* exchange(pairing.credential); + afterSpend = Effect.void; + + expect(exchanged).toBe(false); + expect((yield* serverAuth.listSessions()).map((session) => session.sessionId)).toEqual([ + owner.sessionId, + ]); + } + }).pipe(Effect.provide(layerEnvironmentAuth())), + ); + it.effect("accepts cookie sessions on socket upgrades only from the app's own origins", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index eb20e64e77907..a82b3241fda49 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -36,6 +36,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; @@ -647,18 +648,25 @@ export class EnvironmentAuth extends Context.Service< readonly revokeMcpClientToken: ( token: string, ) => Effect.Effect; + /** How many times "revoke all others" has run since this server started. */ + readonly otherSessionRevocationCount: Effect.Effect; readonly issueMcpClientSession: (input: { readonly label: string; readonly access: AuthMcpClientAccess; readonly peerLink: boolean; readonly client: AuthClientMetadata; + /** + * `otherSessionRevocationCount` read before the sign-in was approved. The session is + * refused when "revoke all others" has run since. + */ + readonly approvedAtRevocationCount?: number; }) => Effect.Effect< { readonly sessionId: AuthSessionId; readonly token: string; readonly expiresAt: DateTime.DateTime; }, - ServerAuthInternalError + ServerAuthInvalidCredentialError | ServerAuthInternalError >; /** * Spends a code covering all granted scopes and returns the level it approves. A level-bound @@ -955,6 +963,28 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.getSessionState"), ); + // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints + // at once would open two requests with one code, and a revoke landing between an exchange + // spending its credential and trusting the key would be undone by that exchange. + const connectTrustLock = yield* Semaphore.make(1); + + // Counts "revoke all others" runs. An exchange or sign-in approval that began before a run + // issues its session here, under the lock the run holds, so it cannot leave a session behind. + const otherSessionRevocations = yield* Ref.make(0); + const issueUnlessOthersRevokedSince = (since: number, issue: Effect.Effect) => + Ref.get(otherSessionRevocations).pipe( + Effect.flatMap((count): Effect.Effect => + count === since + ? issue + : Effect.fail( + new ServerAuthInvalidCredentialError({ + diagnostic: "All other sessions were revoked before this one was issued.", + }), + ), + ), + connectTrustLock.withPermits(1), + ); + const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = Effect.fn( "EnvironmentAuth.createBrowserSession", )(function* (credential, requestMetadata, previousSessionToken) { @@ -982,6 +1012,7 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.createBrowserSession"), ); } + const revocationsAtStart = yield* Ref.get(otherSessionRevocations); const previousSession = previousSessionToken === undefined ? undefined @@ -992,20 +1023,23 @@ export const make = Effect.gen(function* () { const grant = yield* bootstrapCredentials .consume(credential) .pipe(Effect.mapError(toBootstrapExchangeError)); - const session = yield* sessions - .issue({ - method: "browser-session-cookie", - subject: grant.subject, - scopes: grant.scopes, - ...(previousSession?.method === "browser-session-cookie" - ? { replaceSessionId: previousSession.sessionId } - : {}), - client: { - ...requestMetadata, - ...(grant.label ? { label: grant.label } : {}), - }, - }) - .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))); + const session = yield* issueUnlessOthersRevokedSince( + revocationsAtStart, + sessions + .issue({ + method: "browser-session-cookie", + subject: grant.subject, + scopes: grant.scopes, + ...(previousSession?.method === "browser-session-cookie" + ? { replaceSessionId: previousSession.sessionId } + : {}), + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))), + ); return { response: { authenticated: true, @@ -1077,11 +1111,6 @@ export const make = Effect.gen(function* () { ); }; - // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints - // at once would open two requests with one code, and a revoke landing between an exchange - // spending its credential and trusting the key would be undone by that exchange. - const connectTrustLock = yield* Semaphore.make(1); - const toAccessTokenResult = (session: SessionStore.IssuedSession) => DateTime.now.pipe( Effect.map( @@ -1121,63 +1150,71 @@ export const make = Effect.gen(function* () { const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] = (credential, requestedScopes, requestMetadata, input) => { - return resolveBootstrapGrant(credential, { - ...input, - requestMetadata, - ...(requestedScopes !== undefined ? { requestedScopes } : {}), - }).pipe( - // Every T3 Connect key that gets in is remembered, so turning approval on later - // keeps the devices already in use and lists them for review. - Effect.tap((grant) => - grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint - ? bootstrapCredentials - .trustConnectDevice(input.proofKeyThumbprint, requestMetadata) - .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))) - : Effect.void, - ), - Effect.flatMap((grant) => - Effect.gen(function* () { - const grantedScopes = - requestedScopes === undefined - ? grant.scopes - : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope)); - if (grantedScopes.length === 0) { - return yield* new ServerAuthScopeNotGrantedError({}); - } - // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep - // their own lifetimes, so unlinking Connect or rotating a credential still cuts off. - const renewable = - input?.proofKeyThumbprint !== undefined && - grant.method === "one-time-token" && - grant.subject === PAIRING_LINK_SUBJECT; - return yield* sessions - .issue({ - method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", - subject: grant.subject, - scopes: grantedScopes, - ...(input?.proofKeyThumbprint - ? { - proofKeyThumbprint: input.proofKeyThumbprint, - ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), - } - : {}), - ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), - replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", - client: { - ...requestMetadata, - ...(grant.label ? { label: grant.label } : {}), - }, - }) - .pipe( - Effect.mapError( - (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }), - ), - ); - }), - ), - Effect.flatMap(toAccessTokenResult), - (exchange) => - input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange, + const exchangeSince = (revocationsAtStart: number) => + resolveBootstrapGrant(credential, { + ...input, + requestMetadata, + ...(requestedScopes !== undefined ? { requestedScopes } : {}), + }).pipe( + // Every T3 Connect key that gets in is remembered, so turning approval on later + // keeps the devices already in use and lists them for review. + Effect.tap((grant) => + grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint + ? bootstrapCredentials + .trustConnectDevice(input.proofKeyThumbprint, requestMetadata) + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))) + : Effect.void, + ), + Effect.flatMap((grant) => + Effect.gen(function* () { + const grantedScopes = + requestedScopes === undefined + ? grant.scopes + : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope)); + if (grantedScopes.length === 0) { + return yield* new ServerAuthScopeNotGrantedError({}); + } + // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep + // their own lifetimes, so unlinking Connect or rotating a credential still cuts off. + const renewable = + input?.proofKeyThumbprint !== undefined && + grant.method === "one-time-token" && + grant.subject === PAIRING_LINK_SUBJECT; + const issue = sessions + .issue({ + method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", + subject: grant.subject, + scopes: grantedScopes, + ...(input?.proofKeyThumbprint + ? { + proofKeyThumbprint: input.proofKeyThumbprint, + ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), + } + : {}), + ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), + replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe( + Effect.mapError( + (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }), + ), + ); + // A proof-key exchange holds the lock from before it spends its credential. + return yield* input?.proofKeyThumbprint + ? issue + : issueUnlessOthersRevokedSince(revocationsAtStart, issue); + }), + ), + Effect.flatMap(toAccessTokenResult), + (exchange) => + input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange, + ); + return Ref.get(otherSessionRevocations).pipe( + Effect.flatMap(exchangeSince), Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"), ); }; @@ -1501,7 +1538,12 @@ export const make = Effect.gen(function* () { .revokeConnectDevicesExcept(Option.getOrNull(currentProofKey)) .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))); return yield* revokeOtherSessionsExcept(currentSessionId); - }).pipe(connectTrustLock.withPermits(1)); + }).pipe( + // Counted last, after unspent links and session rows are gone, so whatever reads the + // new count can no longer use either. + Effect.ensuring(Ref.update(otherSessionRevocations, (count) => count + 1)), + connectTrustLock.withPermits(1), + ); }); const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) => @@ -1682,8 +1724,8 @@ export const make = Effect.gen(function* () { return yield* revokeSession(session.value.sessionId); }); - const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => - sessions + const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => { + const issue = sessions .issue({ subject: MCP_CLIENT_SUBJECT, method: "bearer-access-token", @@ -1700,8 +1742,13 @@ export const make = Effect.gen(function* () { expiresAt: issued.expiresAt, })), Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })), - Effect.withSpan("EnvironmentAuth.issueMcpClientSession"), ); + return ( + input.approvedAtRevocationCount === undefined + ? issue + : issueUnlessOthersRevokedSince(input.approvedAtRevocationCount, issue) + ).pipe(Effect.withSpan("EnvironmentAuth.issueMcpClientSession")); + }; const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = ( code, @@ -1765,6 +1812,7 @@ export const make = Effect.gen(function* () { issueStartupPairingUrl, authenticateMcpClient, revokeMcpClientToken, + otherSessionRevocationCount: Ref.get(otherSessionRevocations), issueMcpClientSession, consumeMcpApprovalCode, }); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index f66d0b1c6e81c..ea321bcf0241c 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -27,6 +27,7 @@ import * as CloudLink from "../cloud/CloudLink.ts"; import * as ServerConfig from "../config.ts"; import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as Sqlite from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; @@ -75,6 +76,7 @@ const makeLayerRoutes = ( ), ), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ).pipe( Layer.provideMerge(layerEnvironmentAuth), @@ -216,6 +218,26 @@ it.effect("derives discovery metadata from the origin the client reached", () => ), ); +it.effect("answers 413 to a body over the API limit", () => + withRoutes((handler) => + Effect.gen(function* () { + const body = "x".repeat(ServerHttp.API_MAX_BODY_BYTES + 1); + for (const [path, contentType] of [ + ["/api/auth/browser-session", "application/json"], + ["/oauth/token", "application/x-www-form-urlencoded"], + ["/oauth/mcp/register", "application/json"], + ]) { + const init = { method: "POST", headers: { "content-type": contentType! } }; + expect((yield* handler(at(path!, { ...init, body }))).status, path).toBe(413); + // A chunked body declares no length, so the reader itself has to stop. + const chunked = new Blob([body]).stream(); + const streamed = at(path!, { ...init, body: chunked, duplex: "half" } as RequestInit); + expect((yield* handler(streamed)).status, `${path} chunked`).toBe(413); + } + }), + ), +); + it.effect("registers loopback and https clients and never redirects for an unverified client", () => withRoutes((handler) => Effect.gen(function* () { @@ -516,6 +538,44 @@ it.live("signs in Gemini, which registers six user-bound redirect URIs for one c ), ); +it.live("issues no session for a sign-in approved before all other sessions were revoked", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const clientId = yield* registeredClientId(handler); + const params = authorizeParams(clientId); + const approved = yield* decide(handler, params, { + _tag: "pairing-code", + access: "approval-required", + code: (yield* auth.issuePairingCredential()).credential, + }); + const code = new URL(approved.redirectTo!).searchParams.get("code")!; + const owner = yield* auth.issueSession(); + yield* auth.revokeOtherClientSessions(owner.sessionId); + + const response = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code, + redirect_uri: params.redirect_uri, + client_id: clientId, + code_verifier: verifier, + }), + ), + ); + expect(response.status).toBe(400); + expect(yield* json(response)).toEqual({ + error: "invalid_grant", + error_description: "The authorization code is invalid or expired.", + }); + expect((yield* auth.listSessions()).map((session) => session.sessionId)).toEqual([ + owner.sessionId, + ]); + }), + ), +); + it.live("rejects a wrong PKCE verifier and spends the code", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index e63c600ae1b2d..7c6cdc677cc3c 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -197,6 +197,7 @@ interface PendingCode { readonly codeChallenge: string; readonly resource: string; readonly access: AuthMcpClientAccess; + readonly approvedAtRevocationCount: number; readonly expiresAtMs: number; } @@ -445,6 +446,7 @@ const make = Effect.gen(function* () { const mintCode = Effect.fn("McpOAuth.mintCode")(function* ( authorization: AuthorizationRequest, access: AuthMcpClientAccess, + approvedAtRevocationCount: number, ) { const now = yield* Clock.currentTimeMillis; const code = Buffer.from(yield* random.randomBytes(32)).toString("base64url"); @@ -458,6 +460,7 @@ const make = Effect.gen(function* () { codeChallenge: authorization.codeChallenge, resource: authorization.resource, access, + approvedAtRevocationCount, expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS, }); return next; @@ -467,6 +470,9 @@ const make = Effect.gen(function* () { const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) { const { decision } = input; + // Read before the approver is checked: "revoke all others" then ends this sign-in whether + // it lands before the check or after the code is handed out. + const approvedAtRevocationCount = yield* environmentAuth.otherSessionRevocationCount; let access = decision.access; if (decision._tag === "pairing-code") { // An approval code is for one app's sign-in, never for linking another environment. @@ -502,7 +508,7 @@ const make = Effect.gen(function* () { }); } } - const code = yield* mintCode(input.authorization, access); + const code = yield* mintCode(input.authorization, access, approvedAtRevocationCount); yield* Effect.logInfo("Approved an MCP client sign-in.", { client: input.authorization.client.name, access, @@ -567,14 +573,17 @@ const make = Effect.gen(function* () { access: pending.access, peerLink: pending.peerLink, client: deriveAuthClientMetadata({ request }), + approvedAtRevocationCount: pending.approvedAtRevocationCount, }) .pipe( Effect.catch((cause) => - Effect.logError("Could not issue an MCP client session.", { cause }).pipe( - Effect.andThen( - Effect.fail(fail("invalid_grant", "The session could not be issued.")), - ), - ), + cause._tag === "ServerAuthInvalidCredentialError" + ? Effect.fail(fail("invalid_grant", "The authorization code is invalid or expired.")) + : Effect.logError("Could not issue an MCP client session.", { cause }).pipe( + Effect.andThen( + Effect.fail(fail("invalid_grant", "The session could not be issued.")), + ), + ), ), ); return { diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 750ff136ac07d..1aa2a5b182ffa 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -355,6 +355,76 @@ it.effect("pairs a client with a linked environment only for one that may hand o }).pipe(Effect.scoped), ); +it.effect("hands out a link code or a guest link only within what the session itself holds", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.peerLinksPairLink | typeof WS_METHODS.guestShareCreate + > => tag !== WS_METHODS.peerLinksPairLink && tag !== WS_METHODS.guestShareCreate, + ), + ); + let handled = 0; + const environmentId = EnvironmentId.make("environment-box"); + const threadId = ThreadId.make("thread-1"); + const handlers = Layer.mergeAll( + group.toLayerHandler(WS_METHODS.peerLinksPairLink, () => + Effect.sync(() => { + handled++; + return { + type: "unsupported" as const, + reason: "link_access" as const, + environmentId, + label: "Box", + urls: [], + }; + }), + ), + group.toLayerHandler(WS_METHODS.guestShareCreate, () => + Effect.sync(() => handled++).pipe(Effect.andThen(Effect.die("no share in this test"))), + ), + ); + const clientWith = (scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handlers, RpcAuthorization.layer(scopes))), + ); + + // Managing access alone is not running agents or reading threads. + const manager = yield* clientWith([AuthAccessWriteScope]); + expect( + yield* manager[WS_METHODS.peerLinksPairLink]({ environmentId, access: "read-only" }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + expect( + yield* manager[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + + const supervisor = yield* clientWith([ + AuthAccessWriteScope, + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + ]); + expect( + yield* supervisor[WS_METHODS.peerLinksPairLink]({ + environmentId, + access: "full-access", + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthSettingsWriteScope }); + expect(handled).toBe(0); + + expect( + (yield* supervisor[WS_METHODS.peerLinksPairLink]({ environmentId, access: "auto" })).type, + ).toBe("unsupported"); + expect(handled).toBe(1); + yield* supervisor[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.exit); + expect(handled).toBe(2); + }).pipe(Effect.scoped), +); + it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)( "enforces read permission on stream %s", (method) => @@ -587,6 +657,67 @@ describe("settings mutation authorization", () => { ); }); +it.effect("answering a secret request with a reference needs provider management", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.secretsAnswerRequest + > => tag !== WS_METHODS.secretsAnswerRequest, + ), + ); + const handled: string[] = []; + const handler = group.toLayerHandler(WS_METHODS.secretsAnswerRequest, ({ answer }) => + Effect.sync(() => { + handled.push(answer.type); + }), + ); + const clientWith = (...scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handler, RpcAuthorization.layer(scopes))), + ); + const request = { threadId: ThreadId.make("thread"), turnItemId: TurnItemId.make("item") }; + const reference = { + type: "reference" as const, + reference: { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }, + }; + + const operate = yield* clientWith(AuthOrchestrationOperateScope); + expect( + yield* operate[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthProvidersManageScope }); + expect(handled).toEqual([]); + // Typed values stay with the scope that runs the thread, whatever the fields are called. + yield* operate[WS_METHODS.secretsAnswerRequest]({ + ...request, + answer: { type: "save", secret: "typed-value" }, + }); + yield* operate[WS_METHODS.secretsAnswerRequest]({ + ...request, + answer: { type: "save", values: { provider: "personal", reference: "typed-value" } }, + }); + expect(handled).toEqual(["save", "save"]); + + const manage = yield* clientWith(AuthOrchestrationOperateScope, AuthProvidersManageScope); + yield* manage[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }); + expect(handled).toEqual(["save", "save", "reference"]); + const manageOnly = yield* clientWith(AuthProvidersManageScope); + expect( + yield* manageOnly[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope }); + }), +); + it.effect("requires task permission before attaching a prepared worktree to a thread", () => Effect.gen(function* () { const group = WsRpcGroup.omit( diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 329b371aad67b..7f9f42231b854 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -11,6 +11,7 @@ import { requiredScopesForServerSettingsPatch, requiredScopesForProjectMutation, ProjectMutation, + SecretRequestAnswerInput, AuthSettingsWriteScope, AuthProvidersManageScope, AuthEnvironmentMaintainScope, @@ -289,6 +290,7 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => { const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation); const decodeAssetCreateUrlInput = Schema.decodeUnknownSync(AssetCreateUrlInput); +const decodeSecretRequestAnswer = Schema.decodeUnknownSync(SecretRequestAnswerInput); /** * A queued edit that omits `attachments` keeps the queued ones, which a payload cannot show; @@ -344,6 +346,14 @@ const requiredScopesForRpcCall = ( ) { return [AuthSettingsWriteScope, AuthProvidersManageScope]; } + // A reference answer has the server read a secret the caller names, as a saved reference does. + // Typed values can use any field names, so the answer's type decides, not its shape. + if ( + method === WS_METHODS.secretsAnswerRequest && + decodeSecretRequestAnswer(payload).answer.type === "reference" + ) { + return [AuthOrchestrationOperateScope, AuthProvidersManageScope]; + } if (method === WS_METHODS.projectsMutate) { return requiredScopesForProjectMutation(decodeProjectMutation(payload)); } diff --git a/apps/server/src/background/KeepAwake.test.ts b/apps/server/src/background/KeepAwake.test.ts index 8984102729cec..628590930e470 100644 --- a/apps/server/src/background/KeepAwake.test.ts +++ b/apps/server/src/background/KeepAwake.test.ts @@ -34,3 +34,12 @@ describe("KeepAwake.holdWhileWanted", () => { }), ); }); + +describe("KeepAwake.inhibitorCommand", () => { + it("runs PowerShell by its System32 path on Windows", () => { + expect( + KeepAwake.inhibitorCommand("win32", 1, false, { SYSTEMROOT: String.raw`D:\Windows` }) + ?.command, + ).toBe(String.raw`D:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`); + }); +}); diff --git a/apps/server/src/background/KeepAwake.ts b/apps/server/src/background/KeepAwake.ts index f9d2cf3da7532..72e5c1fbf031b 100644 --- a/apps/server/src/background/KeepAwake.ts +++ b/apps/server/src/background/KeepAwake.ts @@ -14,6 +14,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; import { forkParked } from "../serverActivation.ts"; import * as Settings from "../serverSettings.ts"; @@ -27,10 +28,11 @@ const WINDOWS_HOLD_SCRIPT = `$t = Add-Type -Name Power -Namespace T3 -PassThru - * Each command writes a line to stdout once it holds its inhibitor, holds it until it exits, and * exits on its own if the server dies. */ -function inhibitorCommand( +export function inhibitorCommand( platform: NodeJS.Platform, serverPid: number, isWsl: boolean, + env: NodeJS.ProcessEnv, ): | { readonly command: string; @@ -77,7 +79,7 @@ function inhibitorCommand( }; case "win32": return { - command: "powershell.exe", + command: windowsPowerShellPath(env), args: [ "-NoProfile", "-NonInteractive", @@ -145,7 +147,7 @@ export const layer = Layer.effectDiscard( Effect.map((release) => release.toLowerCase().includes("microsoft")), Effect.orElseSucceed(() => false), )); - const command = inhibitorCommand(platform, process.pid, isWsl); + const command = inhibitorCommand(platform, process.pid, isWsl, yield* HostProcess.Environment); if (command === undefined) return; const settings = yield* Settings.ServerSettingsService; const events = yield* OrchestrationEventStore.OrchestrationEventStore; diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index 7b980e01b5fa7..4bbc5801d2c83 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -53,6 +53,10 @@ if ( const launcherOptions = launcher?.parseServiceLauncherArgs(process.argv.slice(3)); if (launcher !== undefined && launcherOptions !== undefined) { await launcher.runServiceLauncherCli(launcherOptions); + } else if (process.argv[2] === "__process-launcher") { + // Single executables host the launcher here; other builds start process-launcher.mjs directly. + const { runProcessLauncher } = await import("./process/processLauncherWorker.ts"); + runProcessLauncher(); } else { const { runCliCommand } = await loadCliMain(); await runCliCommand(); diff --git a/apps/server/src/cli/automaticPort.test.ts b/apps/server/src/cli/automaticPort.test.ts index 1f7805569744f..b39c94720cbc8 100644 --- a/apps/server/src/cli/automaticPort.test.ts +++ b/apps/server/src/cli/automaticPort.test.ts @@ -34,6 +34,7 @@ interface Scenario { readonly tcpv6ExitCode?: number; readonly wslpathMissing?: boolean; readonly reservedPorts?: ReadonlyArray; + readonly host?: string; } const select = (scenario: Scenario) => { @@ -92,7 +93,7 @@ const select = (scenario: Scenario) => { ); return Effect.gen(function* () { const selectAutomaticPort = yield* AutomaticPort.make; - const port = yield* selectAutomaticPort(3773); + const port = yield* selectAutomaticPort(3773, scenario.host); return { port, commands }; }).pipe(Effect.provide(layer)); }; @@ -149,12 +150,13 @@ describe("automatic port selection", () => { }), ); - it.effect("never queries Windows outside WSL", () => + it.effect("never queries Windows outside WSL or for a specific bind address", () => Effect.gen(function* () { for (const scenario of [ { kernelRelease: "6.8.0-45-generic\n" }, // macOS and Windows have no kernel release file. {}, + { kernelRelease: WSL_KERNEL, windowsPorts: [3773], host: "100.64.0.7" }, ] satisfies ReadonlyArray) { const result = yield* select(scenario); expect(result.port).toBe(3773); diff --git a/apps/server/src/cli/automaticPort.ts b/apps/server/src/cli/automaticPort.ts index 354de65d2519b..70e8bad6c8b05 100644 --- a/apps/server/src/cli/automaticPort.ts +++ b/apps/server/src/cli/automaticPort.ts @@ -1,3 +1,4 @@ +import { listensOnLoopback } from "@t3tools/shared/hostClassification"; import * as NetService from "@t3tools/shared/Net"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -44,14 +45,17 @@ export const make = Effect.gen(function* () { return new Set(listeners.map((listener) => listener.port)); }).pipe(Effect.orElseSucceed(() => null)); - return Effect.fn("automaticPort.select")(function* (preferred: number) { - if (!(yield* isWsl)) return yield* net.findAvailablePort(preferred); + return Effect.fn("automaticPort.select")(function* (preferred: number, host: string | undefined) { + // Windows localhost forwarding reaches only WSL listeners on loopback or a wildcard address. + if (!listensOnLoopback(host) || !(yield* isWsl)) { + return yield* net.findAvailablePort(preferred, host); + } const windows = yield* readWindowsHostListeners; if (windows === null) { yield* Effect.logWarning( "Could not list Windows TCP listeners from WSL; Windows may be unable to reach the selected port. Pass --port to choose one.", ); - return yield* net.findAvailablePort(preferred); + return yield* net.findAvailablePort(preferred, host); } if (!windows.has(preferred) && (yield* net.isPortAvailableOnLoopback(preferred))) { return preferred; diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 9d1ffb5c1298a..bbd13c1132953 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -872,15 +872,16 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { const baseDir = yield* FileSystem.FileSystem.pipe( Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-auto-port-" })), ); - const selected: number[] = []; - const selectAutomaticPort = (preferred: number) => + const selected: Array = []; + const selectAutomaticPort = (preferred: number, host: string | undefined) => Effect.sync(() => { - selected.push(preferred); + selected.push([preferred, host]); return 50_123; }); const resolvePort = (flags: { readonly mode?: Option.Option<"web" | "desktop">; readonly port: Option.Option; + readonly host?: Option.Option; }) => resolveServerConfig({ ...minimalWebFlags(baseDir), ...flags }, Option.none(), { selectAutomaticPort, @@ -895,12 +896,18 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { ); expect(yield* resolvePort({ port: Option.none() })).toBe(50_123); - expect(selected).toEqual([3773]); + expect(yield* resolvePort({ port: Option.none(), host: Option.some("100.64.0.7") })).toBe( + 50_123, + ); + expect(selected).toEqual([ + [3773, undefined], + [3773, "100.64.0.7"], + ]); expect(yield* resolvePort({ port: Option.some(8788) })).toBe(8788); expect( yield* resolvePort({ mode: Option.some("desktop" as const), port: Option.none() }), ).toBe(3773); - expect(selected).toEqual([3773]); + expect(selected).toHaveLength(2); }), ); diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index a62682772bcce..87ff2588c5e34 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -271,6 +271,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct readonly rejectRunningServer?: boolean; readonly selectAutomaticPort?: ( preferred: number, + host: string | undefined, ) => Effect.Effect; }, ) { @@ -310,22 +311,6 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct () => "web", ); - const port = yield* Option.match( - resolveOptionPrecedence( - normalizedFlags.port, - Option.fromUndefinedOr(env.port), - Option.fromUndefinedOr(bootstrap?.port), - ), - { - onSome: (value) => Effect.succeed(value), - onNone: () => { - if (mode === "desktop") { - return Effect.succeed(ServerConfig.DEFAULT_PORT); - } - return selectAutomaticPort(ServerConfig.DEFAULT_PORT); - }, - }, - ); const devUrl = Option.getOrElse( resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)), () => undefined, @@ -451,6 +436,22 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct const host = Option.getOrElse(explicitHost, () => privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined, ); + const port = yield* Option.match( + resolveOptionPrecedence( + normalizedFlags.port, + Option.fromUndefinedOr(env.port), + Option.fromUndefinedOr(bootstrap?.port), + ), + { + onSome: (value) => Effect.succeed(value), + onNone: () => { + if (mode === "desktop") { + return Effect.succeed(ServerConfig.DEFAULT_PORT); + } + return selectAutomaticPort(ServerConfig.DEFAULT_PORT, host); + }, + }, + ); const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel); const otel = yield* OtelEnvironment.load; diff --git a/apps/server/src/cli/environment.test.ts b/apps/server/src/cli/environment.test.ts index 739125e0dd507..2fcdc88589e6e 100644 --- a/apps/server/src/cli/environment.test.ts +++ b/apps/server/src/cli/environment.test.ts @@ -5,6 +5,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { NodeHttpServer } from "@effect/platform-node"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -63,6 +64,23 @@ it.effect("links a file of environments, reports each line, and fails when one d const link = (from: string) => runCli(["environment", "link", "--from", from, "--access", "auto", "--base-dir", baseDir]); + const conflict = yield* runCli([ + "environment", + "link", + "--from", + file, + "--url", + "http://ignored.invalid", + "--access", + "auto", + "--base-dir", + baseDir, + ]).pipe(Effect.flip); + expect(conflict).toMatchObject({ + _tag: "EnvironmentLinkUsageError", + detail: "--from takes its addresses and pairing codes from the file.", + }); + const failed = yield* link(file).pipe(Effect.flip); expect(failed).toMatchObject({ _tag: "EnvironmentLinkBatchError", failed: 1, total: 3 }); const report = (yield* reports).at(-1) ?? ""; @@ -84,7 +102,7 @@ it.effect("links a file of environments, reports each line, and fails when one d retry, `${one.url} ${firstCode}\n${two.url} ${yield* codeFor(two)}\n${three.url} never-valid\n`, ); - yield* link(retry); + yield* link("~/retry.txt").pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)); const retried = (yield* reports).at(-1) ?? ""; expect(retried).toContain( `${one.url}: already linked as VM 1 (environment-vm-1), left as it is`, diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts index 9243d0340eabf..a4b47ebbe8c55 100644 --- a/apps/server/src/cli/environment.ts +++ b/apps/server/src/cli/environment.ts @@ -29,6 +29,7 @@ import * as PeerLinks from "../peer/PeerLinks.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { expandHomePath } from "../os-jank.ts"; import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -201,7 +202,7 @@ const readLinkBatch = Effect.fn("environment.readLinkBatch")(function* (from: st ); } const fs = yield* FileSystem.FileSystem; - return yield* fs.readFileString(from); + return yield* fs.readFileString(yield* expandHomePath(from)); }); const environmentLinkCommand = Command.make("link", { @@ -239,7 +240,11 @@ const environmentLinkCommand = Command.make("link", { Command.withHandler((flags) => Effect.gen(function* () { if (Option.isSome(flags.from)) { - if (Option.isSome(flags.url) || Option.isSome(flags.pairingCode)) { + if ( + Option.isSome(flags.url) || + Option.isSome(flags.pairingCode) || + flags.alternateUrl.length > 0 + ) { return yield* new EnvironmentLinkUsageError({ detail: "--from takes its addresses and pairing codes from the file.", }); diff --git a/apps/server/src/cli/install.test.ts b/apps/server/src/cli/install.test.ts index f7aaeca3120cc..f7d8b1df86d76 100644 --- a/apps/server/src/cli/install.test.ts +++ b/apps/server/src/cli/install.test.ts @@ -212,17 +212,32 @@ it.layer(NodeServices.layer)("t3 install", (it) => { const globalBin = path.join(root, "global-bin"); yield* fs.makeDirectory(globalBin); yield* fs.writeFileString(path.join(globalBin, "t3"), ""); + yield* fs.chmod(path.join(globalBin, "t3"), 0o755); yield* offer(false, { env: { PATH: globalBin } }); assert.equal(asked, 0); assert.isFalse(yield* fs.exists(link)); - // A runner's own .bin on PATH is not an installed t3. + // A directory or non-executable file named `t3` on PATH is not an installed t3. + const dirBin = path.join(root, "dir-bin"); + yield* fs.makeDirectory(path.join(dirBin, "t3"), { recursive: true }); + const nonExecBin = path.join(root, "non-exec-bin"); + yield* fs.makeDirectory(nonExecBin); + yield* fs.writeFileString(path.join(nonExecBin, "t3"), ""); + assert.isFalse(yield* offer(undefined, { env: { PATH: dirBin } })); + assert.equal(asked, 1); + assert.isFalse(yield* offer(undefined, { env: { PATH: nonExecBin } })); + assert.equal(asked, 2); + asked = 0; + + // A runner's own .bin on PATH, even found through a bare launcher record, is not an installed t3. const npxBin = path.join(npmPackage, "../.bin"); const pnpmBin = path.join(root, ".cache/pnpm/dlx/abc/node_modules/.bin"); for (const bin of [npxBin, pnpmBin]) { yield* fs.makeDirectory(bin, { recursive: true }); yield* fs.writeFileString(path.join(bin, "t3"), ""); + yield* fs.chmod(path.join(bin, "t3"), 0o755); } + yield* fs.writeFileString(path.join(runtimeDir, "launchers"), "t3\n"); assert.isFalse(yield* offer(undefined, { env: { PATH: `${npxBin}:${pnpmBin}` } })); assert.equal(asked, 1); assert.isFalse(yield* fs.exists(path.join(runtimeDir, "install-prompt-declined"))); diff --git a/apps/server/src/cli/install.ts b/apps/server/src/cli/install.ts index 4e6420842dc9d..b789930b2cfbb 100644 --- a/apps/server/src/cli/install.ts +++ b/apps/server/src/cli/install.ts @@ -322,7 +322,7 @@ export const offerCliInstall = Effect.fn("cli.install.offer")(function* "")); const candidates = [ - ...launchers.split(/\r?\n/).filter(Boolean), + ...launchers.split(/\r?\n/).filter((launcher) => path.isAbsolute(launcher)), path.join(path.dirname(runtimeDir), "bin", windows ? "t3.cmd" : "t3"), ...(environment.PATH ?? environment.Path ?? "") .split(windows ? ";" : ":") @@ -332,7 +332,7 @@ export const offerCliInstall = Effect.fn("cli.install.offer")(function* names.map((name) => path.join(directory, name))), ]; for (const candidate of candidates) { - if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) return true; + if (yield* resolveCommandPath(candidate, { env: environment })) return true; } const declinedFile = path.join(runtimeDir, "install-prompt-declined"); diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts index 8310649aa77cb..928e97dc69246 100644 --- a/apps/server/src/cli/invocation.test.ts +++ b/apps/server/src/cli/invocation.test.ts @@ -8,6 +8,7 @@ import * as Path from "effect/Path"; import packageJson from "../../package.json" with { type: "json" }; import { posixLauncherScript } from "../cloud/pinnedRuntime.ts"; import { + hostShellWord, resolveHostCliCommand, resolveRootCliCommand, resolveServerInstallation, @@ -187,6 +188,40 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => { ); }), ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "names the absolute path of a t3 found through a relative PATH entry", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bin = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(bin, "t3"), "#!/bin/sh\n", { mode: 0o755 }); + const hostCommand = (searchPath: string) => + resolveHostCliCommand("doctor").pipe( + Effect.provideService(HostProcess.ExecutablePath, "/usr/bin/node"), + Effect.provideService(HostProcess.Arguments, [ + "/usr/bin/node", + "/opt/t3/lib/node_modules/t3/dist/bin.mjs", + ]), + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + ); + + // A relative entry was searched from this process's directory, unlike the user's shell. + expect(yield* hostCommand(path.relative(process.cwd(), bin))).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + // An empty entry makes the shell search its own directory first, wherever that is. + expect(yield* hostCommand(`:${bin}`)).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + expect(yield* hostCommand(bin)).toEqual({ command: "t3 doctor", launcher: false }); + }), + ); }); it.layer(NodeServices.layer)("manual server installation ownership", (it) => { diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts index 4804d44f0e324..69a3a5815bbd6 100644 --- a/apps/server/src/cli/invocation.ts +++ b/apps/server/src/cli/invocation.ts @@ -205,7 +205,16 @@ export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand ) : null; if (own === null || own === (yield* real(onPath))) { - return { command: withArgs(command), launcher: false }; + const path = yield* Path.Path; + const searchPath = (yield* HostProcess.Environment).PATH ?? ""; + // With an empty or relative PATH entry, plain `t3` depends on the directory it runs from. + const cwdDependent = + platform !== "win32" && + searchPath.length > 0 && + searchPath.split(":").some((entry) => !path.isAbsolute(entry)); + if (!cwdDependent) return { command: withArgs(command), launcher: false }; + const quoted = hostShellWord(platform, path.resolve(onPath)); + return { command: withArgs(`${quoted} ${subcommand}`), launcher: false }; } } const launcher = yield* resolveInstallLauncher; diff --git a/apps/server/src/cli/policy.test.ts b/apps/server/src/cli/policy.test.ts index 7066cceebcd0f..04e29808078c1 100644 --- a/apps/server/src/cli/policy.test.ts +++ b/apps/server/src/cli/policy.test.ts @@ -1,12 +1,17 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { Command } from "effect/cli"; +import * as TestConsole from "effect/testing/TestConsole"; +import { cli } from "../binCli.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { makePersistedServerRuntimeState, @@ -16,7 +21,7 @@ import { describeRunningServer } from "./policy.ts"; const encodeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState)); -it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => { it.effect("tells whether the running server loaded the installed policy", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -53,5 +58,52 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => assert.include(yield* running(null, null), "runs without a policy, as installed"); assert.include(yield* running(undefined), "does not report which policy it loaded"); }), - ), -); + ); + + it.effect("templates reads a ~/ --policy file from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-templates-" }); + yield* fs.writeFileString( + path.join(home, "policy.json"), + JSON.stringify({ schemaVersion: 1, organization: "Tilde Corp" }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "policy", + "templates", + home, + "--policy=~/policy.json", + ]).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provide(NetService.layer), + ); + + assert.include( + yield* fs.readFileString(path.join(home, "macos", "t3code.mobileconfig")), + "Tilde Corp", + ); + }), + ); + + it.effect("check reads a ~/ policy file from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-check-" }); + const file = path.join(home, "policy.json"); + yield* fs.writeFileString( + file, + JSON.stringify({ schemaVersion: 1, organization: "Tilde Corp" }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })(["policy", "check", "~/policy.json"]).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provide(NetService.layer), + ); + + assert.include((yield* TestConsole.logLines).join("\n"), `Managed by Tilde Corp (${file}`); + }).pipe(Effect.provide(Layer.fresh(TestConsole.layer))), + ); +}); diff --git a/apps/server/src/cli/policy.ts b/apps/server/src/cli/policy.ts index dafc5352166f0..e8badd9123615 100644 --- a/apps/server/src/cli/policy.ts +++ b/apps/server/src/cli/policy.ts @@ -13,6 +13,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { listManageableSettings } from "../policy/managedSettings.ts"; import { macosProfile, windowsAdml, windowsAdmx } from "../policy/policyTemplates.ts"; +import { expandHomePath } from "../os-jank.ts"; import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -95,14 +96,15 @@ const checkCommand = Command.make("check", { Command.withDescription("Validate a policy file before deploying it."), Command.withHandler( Effect.fn("cli.policy.check")(function* ({ file }) { + const policyFile = yield* expandHomePath(file); // Startup treats a missing file as no policy; a draft that is not there checks nothing. - if (!(yield* (yield* FileSystem.FileSystem).exists(file))) { + if (!(yield* (yield* FileSystem.FileSystem).exists(policyFile))) { return yield* new CliError.UserError({ cause: file, userMessage: `No policy file at ${file}.`, }); } - const policy = yield* ManagedPolicy.load(file); + const policy = yield* ManagedPolicy.load(policyFile); yield* Console.log(describePolicy(policy, yield* ManagedPolicy.loadedPolicy(policy))); }), ), @@ -132,13 +134,14 @@ const templatesCommand = Command.make("templates", { const path = yield* Path.Path; let document = SAMPLE_POLICY; if (Option.isSome(policy)) { - if (!(yield* fs.exists(policy.value))) { + const file = yield* expandHomePath(policy.value); + if (!(yield* fs.exists(file))) { return yield* new CliError.UserError({ cause: policy.value, userMessage: `No policy file at ${policy.value}.`, }); } - const loaded = (yield* ManagedPolicy.load(policy.value)).document; + const loaded = (yield* ManagedPolicy.load(file)).document; if (loaded !== undefined) document = loaded; } const random = yield* SecureRandom.SecureRandom; diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 21c3e1caa1943..6dfd723e7084a 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2AppThread, type ProjectId, } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -139,6 +140,7 @@ it.effect( // Repositories inside the folder are found; `--track` adds one from outside it. const shared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-shared-")); + const homeShared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-home-")); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "api", ".git"), { recursive: true }); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "notes")); yield* runCli([ @@ -147,12 +149,15 @@ it.effect( workspaceRoot, "--track", `${shared}${NodePath.sep}`, + "--track", + `~/${NodePath.basename(homeShared)}`, "--base-dir", baseDir, - ]); + ]).pipe(Effect.provideService(HostProcess.HomeDirectory, NodeOS.tmpdir())); assert.deepEqual((yield* readProjects(baseDir)).projects[0]?.trackedFolders, [ { path: NodePath.join(workspaceRoot, "api"), name: "api", discovered: true }, { path: shared, name: NodePath.basename(shared) }, + { path: homeShared, name: NodePath.basename(homeShared) }, ]); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index d2e84e0d4f4f5..1fa7cc0f3f264 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -7,6 +7,8 @@ import { type ProjectSnapshot, ProjectId, } from "@t3tools/contracts"; +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -395,9 +397,10 @@ const projectAddCommand = Command.make("add", { (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot, ); const path = yield* Path.Path; + const home = yield* HostProcess.HomeDirectory; const named = flags.track .map((folder) => { - const resolved = path.resolve(folder); + const resolved = path.resolve(expandHomePath(folder, home)); return { path: resolved, name: (path.basename(resolved) || resolved).slice(0, 128).trim(), diff --git a/apps/server/src/cli/server.ts b/apps/server/src/cli/server.ts index 303402d46c2b4..73383888c7dfd 100644 --- a/apps/server/src/cli/server.ts +++ b/apps/server/src/cli/server.ts @@ -8,7 +8,7 @@ import * as CliError from "effect/cli/CliError"; import { awaitServiceLauncherStop } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; -import { awaitLauncherLoss } from "../launcherWatch.ts"; +import { stopOnLauncherLoss } from "../launcherWatch.ts"; import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as AutomaticPort from "./automaticPort.ts"; @@ -41,13 +41,7 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* ( ), ); if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run; - return yield* Effect.raceFirst( - run, - awaitLauncherLoss().pipe( - // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit). - Effect.andThen(Effect.interrupt), - ), - ); + return yield* stopOnLauncherLoss(run); }); export const runDefaultServerCommand = Effect.fn("server.runDefaultServerCommand")(function* ( diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts index ada548ba2bf39..70907ab446a09 100644 --- a/apps/server/src/cli/service.test.ts +++ b/apps/server/src/cli/service.test.ts @@ -288,6 +288,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands const { service, uninstalls } = makeTestService({ ...status, installedBaseDir: input.otherHome ? "/home/me/.t3" : baseDir, + ...(input.otherHome ? { otherBaseDir: "/home/me/.t3" } : {}), }); vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index fc2aa8d0889aa..4c55d1fa329da 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -325,19 +325,14 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags). flags, Effect.gen(function* () { const service = yield* BootService.BootService; - const path = yield* Path.Path; - const { baseDir } = yield* ServerConfig.ServerConfig; // An unreadable unit stays removable; only a unit known to serve another home is kept. - const installedBaseDir = yield* service.status.pipe( - Effect.map((status) => status.installedBaseDir), + const otherBaseDir = yield* service.status.pipe( + Effect.map((status) => status.otherBaseDir), Effect.orElseSucceed(() => undefined), ); - if ( - installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(baseDir) - ) { + if (otherBaseDir !== undefined) { yield* Console.log( - `The T3 Code service serves ${installedBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(installedBaseDir)}\` to remove it.`, + `The T3 Code service serves ${otherBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(otherBaseDir)}\` to remove it.`, ); return; } diff --git a/apps/server/src/cli/theme.test.ts b/apps/server/src/cli/theme.test.ts index b81cf6926c57e..d2e72dd7e1cc8 100644 --- a/apps/server/src/cli/theme.test.ts +++ b/apps/server/src/cli/theme.test.ts @@ -30,6 +30,17 @@ const runCli = (args: ReadonlyArray) => ), ); +const runCliIn = (cwd: string, args: ReadonlyArray) => + Effect.acquireUseRelease( + Effect.sync(() => { + const previous = process.cwd(); + process.chdir(cwd); + return previous; + }), + () => runCli(args), + (previous) => Effect.sync(() => process.chdir(previous)), + ); + const makeBaseDir = () => NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-theme-cli-")); const settingsPathFor = (baseDir: string) => NodePath.join(baseDir, "userdata", "settings.json"); @@ -136,6 +147,77 @@ describe("t3 theme", () => { }), ); + it.effect("publishes the file named with a leading space, not its trimmed sibling", () => + Effect.gen(function* () { + const baseDir = makeBaseDir(); + NodeFS.mkdirSync(NodePath.join(baseDir, " palettes")); + NodeFS.mkdirSync(NodePath.join(baseDir, "palettes")); + NodeFS.writeFileSync( + NodePath.join(baseDir, " palettes", "nightfall.json"), + NIGHTFALL_THEME_JSON, + ); + NodeFS.writeFileSync(NodePath.join(baseDir, "palettes", "nightfall.json"), JUNK_THEME_JSON); + + yield* runCliIn(baseDir, ["theme", "set", " palettes/nightfall.json", "--base-dir", "."]); + + const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json"); + assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON); + assert.equal(readSettings(baseDir).defaultTheme, "nightfall"); + }), + ); + + // Win32 resolves both names to one file. + it.effect.skipIf(windowsHost)("publishes a file whose name ends in a space", () => + Effect.gen(function* () { + const baseDir = makeBaseDir(); + NodeFS.writeFileSync(NodePath.join(baseDir, "nightfall.json "), NIGHTFALL_THEME_JSON); + NodeFS.writeFileSync(NodePath.join(baseDir, "nightfall.json"), JUNK_THEME_JSON); + + yield* runCliIn(baseDir, [ + "theme", + "set", + "nightfall.json ", + "--id", + "nightfall", + "--base-dir", + ".", + ]); + + const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json"); + assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON); + }), + ); + + // Simulates Win32 on other hosts; on Windows itself the two fixtures would be one file. + it.effect.skipIf(windowsHost)("drops trailing spaces from the path on Windows", () => + Effect.gen(function* () { + const baseDir = makeBaseDir(); + const themeFile = NodePath.join(baseDir, "nightfall.json"); + NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON); + NodeFS.writeFileSync(`${themeFile} `, JUNK_THEME_JSON); + + yield* runCli(["theme", "set", `${themeFile} `, "--base-dir", baseDir]).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + ); + + const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json"); + assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON); + }), + ); + + it.effect("still trims a path that only names a file once trimmed", () => + Effect.gen(function* () { + const baseDir = makeBaseDir(); + const themeFile = NodePath.join(baseDir, "palettes", "nightfall.json"); + NodeFS.mkdirSync(NodePath.dirname(themeFile)); + NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON); + NodeFS.mkdirSync(NodePath.join(baseDir, " palettes", "nightfall.json"), { recursive: true }); + + yield* runCliIn(baseDir, ["theme", "set", " palettes/nightfall.json", "--base-dir", "."]); + assert.equal(readSettings(baseDir).defaultTheme, "nightfall"); + }), + ); + it.effect("refuses to publish over a directory with the theme's file name", () => Effect.gen(function* () { const baseDir = makeBaseDir(); diff --git a/apps/server/src/cli/theme.ts b/apps/server/src/cli/theme.ts index 26048240d5248..ba9e89c17a2b5 100644 --- a/apps/server/src/cli/theme.ts +++ b/apps/server/src/cli/theme.ts @@ -22,6 +22,7 @@ import * as Schema from "effect/Schema"; import { Argument, Command, Flag } from "effect/cli"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ServerConfig from "../config.ts"; import { MAX_THEME_FILE_BYTES, @@ -455,7 +456,7 @@ const themeSetCommand = Command.make("set", { Command.withHandler((flags) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const target = yield* expandHomePath(flags.theme.trim()); + let target = yield* expandHomePath(flags.theme.trim()); if (target.length === 0) { return yield* new ThemeTargetMissingError(); } @@ -467,6 +468,17 @@ const themeSetCommand = Command.make("set", { target.includes("/") || target.includes("\\") || target.startsWith("~"); + if (looksLikePath) { + // Spaces stay part of the path when the argument names a file as typed. Win32 drops + // trailing spaces from ordinary paths, so only leading ones can name another file there. + const expanded = yield* expandHomePath(flags.theme); + const asTyped = + (yield* HostProcess.Platform) === "win32" && !expanded.startsWith("\\\\?\\") + ? expanded.replace(/ +$/, "") + : expanded; + const info = yield* fs.stat(asTyped).pipe(Effect.option); + if (Option.isSome(info) && info.value.type === "File") target = asTyped; + } const targetIsFile = looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false))); let themeId: string; diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index bb0906a9c6919..eafda7f3e9b69 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -27,6 +27,7 @@ import { latestRunError, launchModelSelection, readLatestMessages, + readOutputSchema, resolveProject, threadCommand, type ThreadTools, @@ -524,17 +525,44 @@ it.effect("start rejects a repeated --option before reaching the server", () => ), ); -/** Serves t3_thread_read pages the way the server does: positions count every item. */ +it.effect("--output-schema reads a ~/ path from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-schema-" }); + yield* fs.writeFileString(path.join(home, "schema.json"), '{"type":"object"}'); + + const output = yield* readOutputSchema(Option.some("~/schema.json")).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + ); + + assert.deepStrictEqual(output, { outputSchema: { type: "object" } }); + }).pipe(Effect.provide(NodeServices.layer)), +); + +/** Serves t3_thread_read pages the way the server does: positions count every item, and a cursorless read is the newest page. */ const timelineTools = (types: ReadonlyArray) => { const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type })); const served: Array = []; const call = ((_tool: string, input: unknown) => { const args = input as { readonly afterPosition?: number; readonly limit: number }; + const isMessage = (item: (typeof items)[number]) => + ["user_message", "assistant_message", "proposed_plan"].includes(item.type); + if (args.afterPosition === undefined) { + const page = items.filter(isMessage).slice(-args.limit); + served.push(page.length); + return Effect.succeed({ + thread: { itemCount: items.length }, + items: page, + nextPosition: null, + hasMore: false, + }); + } // Scanning one match past the page keeps reads of huge fixtures linear. const matching: typeof items = []; - for (let position = (args.afterPosition ?? -1) + 1; position < items.length; position++) { + for (let position = args.afterPosition + 1; position < items.length; position++) { const item = items[position]!; - if (["user_message", "assistant_message", "proposed_plan"].includes(item.type)) { + if (isMessage(item)) { matching.push(item); if (matching.length > args.limit) break; } diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 3ba496d1a522b..079d16b903f73 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -426,7 +426,7 @@ const readTimeline = Effect.fn("cli.thread.readTimeline")(function* ( view: "messages" | "activity", ) { const items: Array = []; - let afterPosition: number | undefined; + let afterPosition: number | null = -1; let page: OrchestratorMcpThreadReadResult; do { page = yield* tools.call( @@ -437,13 +437,13 @@ const readTimeline = Effect.fn("cli.thread.readTimeline")(function* ( limit: READ_PAGE_LIMIT, maxCharsPerItem: READ_ITEM_MAX_CHARS, runLimit: 1, - ...(afterPosition === undefined ? {} : { afterPosition }), + afterPosition, }, OrchestratorMcpThreadReadResult, ); items.push(...page.items); - afterPosition = page.nextPosition ?? undefined; - } while (page.hasMore && afterPosition !== undefined); + afterPosition = page.nextPosition; + } while (page.hasMore && afterPosition !== null); return { thread: page.thread, items }; }); @@ -483,7 +483,7 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun limit: READ_PAGE_LIMIT, maxCharsPerItem: READ_ITEM_MAX_CHARS, runLimit: 1, - ...(afterPosition < 0 ? {} : { afterPosition }), + afterPosition, }, OrchestratorMcpThreadReadResult, ); @@ -847,14 +847,16 @@ const outputSchemaFlag = Flag.String("output-schema").pipe( const decodeOutputSchema = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)), ); -const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* ( +export const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* ( path: Option.Option, ) { if (Option.isNone(path)) return {}; const fileSystem = yield* FileSystem.FileSystem; const usage = () => new ThreadUsageError({ detail: `${path.value} does not hold a JSON Schema object.` }); - const text = yield* fileSystem.readFileString(path.value).pipe(Effect.mapError(usage)); + const text = yield* fileSystem + .readFileString(yield* expandHomePath(path.value)) + .pipe(Effect.mapError(usage)); return { outputSchema: yield* decodeOutputSchema(text).pipe(Effect.mapError(usage)) }; }); const messageArgument = Argument.String("message").pipe( @@ -935,7 +937,7 @@ const threadStartCommand = Command.make("start", { ), option: Flag.String("option").pipe( Flag.withDescription( - "Model option as id=value, such as effort=high. Repeat for more. Needs --provider and --model.", + "Model option as id=value (Codex: reasoningEffort=high; Claude: effort=high). Ids depend on the model. Repeat for more. Needs --provider and --model.", ), Flag.atLeast(0), ), diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts index 25f7baeb3211e..41f4241fade68 100644 --- a/apps/server/src/cli/triage.test.ts +++ b/apps/server/src/cli/triage.test.ts @@ -190,3 +190,51 @@ it.live("a failed agent launch points at the prompt it could not run", () => ), ), ); + +it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "starts an agent found through a relative PATH entry from the session directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" }); + // Relative to this process, as an entry like "." is to the server that checked it. + const relativeBinDir = NodePath.relative(process.cwd(), binDir); + // Nested deeper than the entry climbs, so from the session directory it leads nowhere. + const climbs = relativeBinDir.split(NodePath.sep).filter((part) => part === "..").length; + const baseDir = NodePath.join( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" }), + ...Array.from({ length: climbs }, () => "nested"), + ); + NodeFS.mkdirSync(baseDir, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 }); + yield* Effect.acquireRelease( + Effect.sync(() => { + vi.stubEnv("PATH", relativeBinDir); + vi.stubEnv("CODEX_HOME", NodePath.join(baseDir, "codex-home")); + }), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const previousExitCode = process.exitCode; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + process.exitCode = previousExitCode; + }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "triage", + "--agent", + "codex", + "--base-dir", + baseDir, + ]); + + // The fake agent ran and exited 1, rather than failing to start. + assert.equal(process.exitCode, 1); + assert.include((yield* TestConsole.logLines).join("\n"), "Codex exited with code 1."); + }).pipe( + Effect.provide( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer), + ), + ), +); diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index cb0f94b254589..df73347cd9fe4 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -4,7 +4,8 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeReadlinePromises from "node:readline/promises"; -import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isCommandAvailable, resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; @@ -220,7 +221,14 @@ export const triageCommand = Command.make("triage", { const model = Option.getOrUndefined(flags.model); const launchPrompt = buildTriageLaunchPrompt(promptFilePath); - const spawnSpec = yield* resolveSpawnCommand(selected.command, [ + // The agent starts in the session directory, so a PATH match relative to this one would + // be searched from there. Windows keeps the bare name for its .cmd shim handling. + const onPath = + (yield* HostProcess.Platform) === "win32" + ? null + : yield* resolveCommandPath(selected.command); + const command = onPath === null ? selected.command : NodePath.resolve(onPath); + const spawnSpec = yield* resolveSpawnCommand(command, [ ...(model === undefined ? [] : ["--model", model]), ...(selected.promptArgs ?? []), launchPrompt, diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index c22760da53453..19093032fc3d3 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -89,23 +89,38 @@ it.live("reports failure when the Windows cleanup shell cannot start", () => ); it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => { - it.effect("names another home's service it leaves installed", () => + it.effect.each([ + { + label: "names another home's service it leaves installed", + otherFromRead: 1, + removed: [], + output: "--base-dir '/home/me/.t3'", + }, + { + label: "leaves a service that serves another home by the time it is removed", + otherFromRead: 2, + removed: [], + output: "Left the background service: it now serves another T3 home.", + }, + ])("$label", (input) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-cli-test-" }); const uninstalls: Array = []; + let reads = 0; vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( BootService.BootService, BootService.BootService.of({ - status: Effect.succeed({ + status: Effect.sync(() => ({ supported: true, installed: true, current: true, installedBaseDir: "/home/me/.t3", + ...(++reads >= input.otherFromRead ? { otherBaseDir: "/home/me/.t3" } : {}), unitPath: "/home/me/.config/systemd/user/t3code.service", logPath: "/home/me/.t3/userdata/logs/boot-service.log", - }), + })), withStopped: (operation) => operation, restart: Effect.die("unexpected restart"), install: () => Effect.die("unexpected install"), @@ -133,8 +148,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall com ), ), ); - assert.deepStrictEqual(uninstalls, []); - assert.include(output, "--base-dir '/home/me/.t3'"); + assert.deepStrictEqual(uninstalls, input.removed); + assert.include(output, input.output); }), ); }); @@ -200,9 +215,21 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { // recorded launchers: through a symlinked home, and dangling after a prune. const throughAlias = path.join(root, "bin/t3-alias"); const pruned = path.join(root, "bin/t3-pruned"); + const scriptThroughAlias = path.join(scriptDir, "t3-alias"); + const prunedScript = path.join(scriptDir, "t3-pruned"); yield* fs.symlink(root, path.join(root, "alias")); yield* fs.symlink(path.join(root, "alias/runtime/versions/1.0.0/t3"), throughAlias); yield* fs.symlink(path.join(versionsDir, "0.9.0/t3"), pruned); + yield* fs.writeFileString( + scriptThroughAlias, + posixLauncherScript(path.join(root, "alias/runtime/versions/1.0.0/t3")), + { mode: 0o755 }, + ); + yield* fs.writeFileString( + prunedScript, + posixLauncherScript(path.join(versionsDir, "0.9.0/t3")), + { mode: 0o755 }, + ); // Another program inside a version is not a launcher. const sibling = path.join(root, "bin/t3-sibling"); yield* fs.symlink(path.join(versionsDir, "1.0.0/node"), sibling); @@ -216,6 +243,8 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { pruned, sibling, script, + scriptThroughAlias, + prunedScript, editedScript, path.join(root, "missing"), ].join("\n") + "\n", @@ -226,6 +255,8 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { throughAlias, pruned, script, + scriptThroughAlias, + prunedScript, ]); } diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index a0d47c7384910..07978299b4642 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -23,6 +23,7 @@ import { import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; import { awaitDetachedSpawn } from "../process/windowsVerbatimSpawn.ts"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { findWindowsShim } from "./update.ts"; export class CliUninstallError extends Schema.TaggedError()( @@ -75,7 +76,8 @@ const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* ( const realVersionsDir = yield* fs .realPath(versionsDir) .pipe(Effect.orElseSucceed(() => versionsDir)); - // The link's own text keeps a pruned (dangling) target; the real path sees through a + const scriptTarget = platform === "win32" ? undefined : yield* readPosixLauncherTarget(launcher); + // The link or script text keeps a pruned (dangling) target; the real path sees through a // symlinked T3 home. const targets = platform === "win32" @@ -91,7 +93,10 @@ const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* ( Effect.orElseSucceed(() => undefined), ), yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined)), - yield* readPosixLauncherTarget(launcher), + scriptTarget, + scriptTarget !== undefined + ? yield* fs.realPath(scriptTarget).pipe(Effect.orElseSucceed(() => undefined)) + : undefined, ]; return targets.some( (target) => @@ -151,9 +156,7 @@ const planUninstall = Effect.fn("cli.uninstall.plan")(function* (input: { const status = yield* service.status; const installedBaseDir = status.supported && status.installed ? status.installedBaseDir : undefined; - const servesThisHome = - installedBaseDir !== undefined && - path.resolve(installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = installedBaseDir !== undefined && status.otherBaseDir === undefined; const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir); const runtimeDir = path.dirname(versionsDir); const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined; @@ -254,12 +257,14 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { } } - if (plan.service) { + // The prompt can wait a long time; keep a service or launcher that changed hands meanwhile. + if (plan.service && (yield* service.status).otherBaseDir !== undefined) { + yield* Console.log("Left the background service: it now serves another T3 home."); + } else if (plan.service) { yield* service.uninstall; yield* Console.log("Removed the background service."); } for (const launcher of plan.launchers) { - // The prompt can wait a long time; never delete a file that replaced the launcher meanwhile. if (!(yield* ownsLauncher(launcher, plan.versionsDir))) { yield* Console.log(`Left ${launcher}: it no longer runs this t3.`); continue; @@ -277,7 +282,10 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { // Windows refuses to unlink this running executable; a detached shell removes it after exit. if (platform === "win32") { const runtimeDir = plan.runtimeDir; - const comspec = environment["ComSpec"] ?? environment["COMSPEC"] ?? "cmd.exe"; + const comspec = + environment["ComSpec"] ?? + environment["COMSPEC"] ?? + windowsSystem32Path(environment, "cmd.exe"); const notScheduled = () => new CliUninstallError({ reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`, diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 07f3458fb3b66..dc798afdaa4da 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -423,9 +423,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: { const status = yield* service.status; // Service names are per user, so another home's unit belongs to a different install. - const servesThisHome = - status.installedBaseDir !== undefined && - path.resolve(status.installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = status.installedBaseDir !== undefined && status.otherBaseDir === undefined; const serviceInstalled = status.supported && status.installed && servesThisHome; const foreground = yield* findForegroundServer({ serverRuntimeStatePath: input.serverRuntimeStatePath, diff --git a/apps/server/src/cli/workflow.test.ts b/apps/server/src/cli/workflow.test.ts index 0c99ca8ee8d21..82b4705e45fa6 100644 --- a/apps/server/src/cli/workflow.test.ts +++ b/apps/server/src/cli/workflow.test.ts @@ -166,21 +166,25 @@ it.effect("reports what the server refused instead of calling it unreachable", ( }), ); -it.effect("signal refuses both addresses at once before reaching the server", () => +it.effect("signal sends only one complete address to the server", () => Effect.gen(function* () { - const { error, calls } = yield* runCli([ - "signal", - "{}", - "--run", - "run-1", - "--wait", - "approve", - "--workflow", - "review", - "--channel", - "pr-1", - ]); - assert.strictEqual(error?._tag, "ThreadUsageError"); - assert.lengthOf(calls, 0); + const byRun = ["--run", "run-1", "--wait", "approve"]; + const byChannel = ["--workflow", "review", "--channel", "pr-1"]; + for (const [address, sent] of [ + [byRun, true], + [byChannel, true], + [[...byRun, ...byChannel], false], + [[], false], + [["--run", "run-1"], false], + [["--wait", "approve"], false], + [["--workflow", "review"], false], + [["--channel", "pr-1"], false], + ] as const) { + const { error, calls } = yield* runCli(["signal", "{}", ...address], () => + Effect.succeed({ structuredContent: { delivery: "delivered" } }), + ); + assert.strictEqual(error?._tag, sent ? undefined : "ThreadUsageError"); + assert.lengthOf(calls, sent ? 1 : 0); + } }), ); diff --git a/apps/server/src/cli/workflow.ts b/apps/server/src/cli/workflow.ts index 95a499043c6c6..c02ee63551f88 100644 --- a/apps/server/src/cli/workflow.ts +++ b/apps/server/src/cli/workflow.ts @@ -244,6 +244,13 @@ const signalCommand = Command.make("signal", { "Address a signal with --run and --wait, or with --workflow and --channel, not both.", }); } + const completeRun = Option.isSome(flags.run) && Option.isSome(flags.wait); + const completeChannel = Option.isSome(flags.workflow) && Option.isSome(flags.channel); + if (!completeRun && !completeChannel) { + return yield* new ThreadUsageError({ + detail: "Address a signal with --run and --wait, or with --workflow and --channel.", + }); + } yield* withThreadTools( { ...flags, json: false }, Effect.fn("cli.workflow.signal")(function* (tools) { diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index ad926f2b5154d..535e2cfed313f 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -22,6 +22,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { serviceLauncherLockPath } from "../serviceLauncher.ts"; import * as BootService from "./bootService.ts"; import { pinnedRuntimePaths } from "./pinnedRuntime.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { decodeServiceUnit, disabledServiceTask, @@ -52,6 +53,8 @@ vi.mock("node:fs", async (importOriginal) => { }; }); +const SCHTASKS = "D:\\WinNT\\System32\\schtasks.exe"; + const windowsTaskOptions = { userId: "PC\\theo", homeDir: "C:\\Users\\theo", @@ -250,13 +253,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( command === "systemctl --user disable --now t3code.service" || command === "systemctl --user restart --no-block t3code.service" || command.startsWith("launchctl bootout --wait ") || - (input.command === "schtasks" && input.args[0] === "/End") + (input.command === SCHTASKS && input.args[0] === "/End") ) { markersAtStop.push(yield* fs.exists(marker)); } if ( command === "systemctl --user daemon-reload" || - (input.command === "schtasks" && input.args[0] === "/Create") + (input.command === SCHTASKS && input.args[0] === "/Create") ) { markersAtPreparation.push(yield* fs.exists(marker)); } @@ -275,8 +278,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( } if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true; const taskMissing = - input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined; - if (input.command === "schtasks" && !failed) { + input.command === SCHTASKS && input.args[0] !== "/Create" && control.task === undefined; + if (input.command === SCHTASKS && !failed) { if (input.args[0] === "/Create") { const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? "")); control.task = { xml, enabled: !serviceTaskIsDisabled(xml) }; @@ -317,7 +320,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( }) : input.args[0] === "--version" ? `t3 v${/versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n` - : input.command === "schtasks" && input.args.includes("/XML") + : input.command === SCHTASKS && input.args.includes("/XML") ? control.task?.enabled === false ? disabledServiceTask(control.task.xml) : (control.task?.xml ?? "") @@ -396,6 +399,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( USERPROFILE: home, LOCALAPPDATA: path.join(home, "AppData", "Local"), USERDOMAIN: "PC", + windir: "D:\\WinNT", USERNAME: "theo", ...(environmentPath === undefined || environmentPath === "" ? {} @@ -1307,6 +1311,28 @@ process.disconnect(); }), ); + it.effect("treats a symlinked T3 home path as the same home", () => + Effect.gen(function* () { + const { service, fs, baseDir, commands, makeService } = yield* makeHarness(); + yield* service.install(); + const path = yield* Path.Path; + const linkDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-symlink-home-" }); + const aliasDir = path.join(linkDir, "a$$b"); + yield* fs.symlink(baseDir, aliasDir); + + const alias = yield* makeService(undefined, "1.2.3", aliasDir); + expect(yield* alias.status).toMatchObject({ current: true }); + expect((yield* alias.status).otherBaseDir).toBeUndefined(); + expect(yield* alias.restart).toBe("restarted"); + commands.length = 0; + yield* alias.withStopped(Effect.void); + expect(commands).toContain("systemctl --user stop t3code.service"); + expect((yield* alias.install()).baseDir).toBe(aliasDir); + expect(yield* service.status).toMatchObject({ current: true }); + expect((yield* service.status).otherBaseDir).toBeUndefined(); + }), + ); + it.effect("hands the whole install to systemd without changing the running service", () => Effect.gen(function* () { const { fs, commands, invocations, control, makeService } = yield* makeHarness(); @@ -1406,6 +1432,7 @@ process.disconnect(); const outcome = yield* inside.restart; expect(commands).toEqual([ "systemctl --user daemon-reload", + `/bin/sh -c ${RESTORE_OOMD_WATCH_SCRIPT}`, "systemctl --user enable t3code.service", "systemctl --user reset-failed t3code.service", "systemctl --user restart --no-block t3code.service", @@ -1557,9 +1584,9 @@ process.disconnect(); protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: "1.2.3", }); - expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual([ - `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, - "schtasks /Run /TN t3code-PC-theo", + expect(commands.filter((command) => command.startsWith(`${SCHTASKS} `))).toEqual([ + `${SCHTASKS} /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]); // No launcher holds the lock here. expect(yield* service.status).toMatchObject({ @@ -1569,7 +1596,7 @@ process.disconnect(); }); // A task that Task Scheduler refuses to delete stays installed, so a retry finds it. - control.failCommand = "schtasks /Delete /TN t3code-PC-theo /F"; + control.failCommand = `${SCHTASKS} /Delete /TN t3code-PC-theo /F`; expect((yield* service.uninstall.pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); expect((yield* service.status).installed).toBe(true); control.failCommand = undefined; @@ -1577,9 +1604,9 @@ process.disconnect(); commands.length = 0; expect(yield* service.uninstall).toBe(true); expect(commands).toEqual([ - "schtasks /Change /TN t3code-PC-theo /DISABLE", - "schtasks /End /TN t3code-PC-theo", - "schtasks /Delete /TN t3code-PC-theo /F", + `${SCHTASKS} /Change /TN t3code-PC-theo /DISABLE`, + `${SCHTASKS} /End /TN t3code-PC-theo`, + `${SCHTASKS} /Delete /TN t3code-PC-theo /F`, ]); expect(control.task).toBeUndefined(); expect((yield* service.status).installed).toBe(false); @@ -1619,11 +1646,11 @@ process.disconnect(); commands.length = 0; yield* service.withStopped(Effect.sync(() => commands.push("repair"))); expect(commands.filter((command) => !command.includes("/Query"))).toEqual([ - "schtasks /Change /TN t3code-PC-theo /DISABLE", - "schtasks /End /TN t3code-PC-theo", + `${SCHTASKS} /Change /TN t3code-PC-theo /DISABLE`, + `${SCHTASKS} /End /TN t3code-PC-theo`, "repair", - "schtasks /Change /TN t3code-PC-theo /ENABLE", - "schtasks /Run /TN t3code-PC-theo", + `${SCHTASKS} /Change /TN t3code-PC-theo /ENABLE`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]); }), ); @@ -1644,14 +1671,14 @@ process.disconnect(); const inside = yield* makeService(undefined, "1.2.4", undefined, true); const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`; const handoff = [ - `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, - "schtasks /End /TN t3code-PC-theo", - "schtasks /Run /TN t3code-PC-theo", + `${SCHTASKS} /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + `${SCHTASKS} /End /TN t3code-PC-theo`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]; commands.length = 0; expect(yield* inside.install()).toMatchObject({ handedOff: true, logPath: plan.logPath }); - expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual(handoff); + expect(commands.filter((command) => command.startsWith(`${SCHTASKS} `))).toEqual(handoff); expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.4"); expect( yield* fs.readFileString(`${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`), diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 4f81ec8641931..11a1978b01830 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -19,6 +19,7 @@ import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as ProcessRunner from "../processRunner.ts"; import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { serviceLauncherIsRunning, serviceLauncherLockPath, @@ -329,12 +330,21 @@ function systemdManager(input: { command: "systemctl", args: ["--user", "reset-failed", BOOT_SERVICE_UNIT_FILE], }; - const prepareActivation = [ + const reload = [ { step: "reloading systemd user units", command: "systemctl", args: ["--user", "daemon-reload"], }, + { + step: "restoring systemd-oomd's watch on the user manager", + optional: true, + command: "/bin/sh", + args: ["-c", RESTORE_OOMD_WATCH_SCRIPT], + }, + ]; + const prepareActivation = [ + ...reload, { step: "enabling the service", command: "systemctl", @@ -388,13 +398,7 @@ function systemdManager(input: { timeout: STOP_STEP_TIMEOUT, }, ], - finalize: [ - { - step: "reloading systemd user units", - command: "systemctl", - args: ["--user", "daemon-reload"], - }, - ], + finalize: reload, }; } @@ -478,6 +482,8 @@ interface WindowsTaskSteps { readonly remove: Effect.Effect; } +const schtasksPath = (systemRoot: string) => `${systemRoot}\\System32\\schtasks.exe`; + function schtasksManager(input: { readonly path: Path.Path; readonly homeDir: string; @@ -485,13 +491,14 @@ function schtasksManager(input: { readonly steps: WindowsTaskSteps; }): BootServiceManager { const unitPath = scheduledTaskPath(input.path, input.session.localAppData); + const schtasks = schtasksPath(input.session.systemRoot); const task = ["/TN", input.session.taskName]; const register = { step: "registering the scheduled task", - command: "schtasks", + command: schtasks, args: ["/Create", "/XML", unitPath, ...task, "/F"], }; - const run = { step: "starting the service", command: "schtasks", args: ["/Run", ...task] }; + const run = { step: "starting the service", command: schtasks, args: ["/Run", ...task] }; const stop: ReadonlyArray = [ { step: "disabling the scheduled task", run: input.steps.disable }, { @@ -515,7 +522,7 @@ function schtasksManager(input: { restart: [ { step: "enabling the scheduled task", - command: "schtasks", + command: schtasks, args: ["/Change", ...task, "/ENABLE"], }, { ...run, step: "restarting the service after a failed update" }, @@ -527,7 +534,7 @@ function schtasksManager(input: { restart: [ { step: "ending the scheduled task", - command: "schtasks", + command: schtasks, args: ["/End", ...task], optional: true, }, @@ -891,7 +898,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { yield* windowsVariable("USERDOMAIN"), yield* windowsVariable("USERNAME"), ), - systemRoot: (yield* windowsVariable("SystemRoot")) || "C:\\Windows", + systemRoot: + (yield* windowsVariable("SystemRoot")) || (yield* windowsVariable("windir")) || "C:\\Windows", }; // The unit is per user, so the launcher to stop is the one serving the installed unit's home. const launcherLockPath = (unit: Option.Option) => @@ -899,6 +907,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { Option.getOrUndefined(Option.flatMapNullishOr(unit, bootServiceBaseDirOf)) ?? input.baseDir, ); const windowsTask = ["/TN", windowsSession.taskName]; + const schtasks = schtasksPath(windowsSession.systemRoot); /** Runs a command that changes the task; a task that is not registered has nothing to change. */ const changeWindowsTask = Effect.fn("cloud.boot_service.change_windows_task")(function* ( step: string, @@ -907,12 +916,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ) { const toError = (cause: unknown) => new BootServiceCommandError({ step, cause }); const changed = yield* runner - .run({ command: "schtasks", args: [verb, ...windowsTask, flag] }) + .run({ command: schtasks, args: [verb, ...windowsTask, flag] }) .pipe(Effect.mapError(toError)); if (changed.code === 0) return; const queried = yield* runner .run({ - command: "schtasks", + command: schtasks, args: ["/Query", ...windowsTask, "/HRESULT"], timeout: Duration.seconds(5), }) @@ -947,14 +956,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { unit: string, ) { const register = (xmlPath: string) => - runStep("registering the scheduled task", "schtasks", [ + runStep("registering the scheduled task", schtasks, [ "/Create", "/XML", xmlPath, ...windowsTask, "/F", ]); - const registered = yield* probe("schtasks", ["/Query", ...windowsTask, "/XML"]); + const registered = yield* probe(schtasks, ["/Query", ...windowsTask, "/XML"]); if ( Option.isSome(registered) && registered.value.code === 0 && @@ -977,7 +986,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // Task Scheduler then reports the task stopped at once, so the lock says when it really is. const stopWindowsLauncher = Effect.gen(function* () { const unit = yield* readUnit().pipe(Effect.option); - yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore); + yield* runner.run({ command: schtasks, args: ["/End", ...windowsTask] }).pipe(Effect.ignore); yield* Effect.tryPromise({ try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal), catch: (cause) => @@ -1020,12 +1029,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir); const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE); const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE); + const canonicalPath = (dir: string) => + fs.realPath(dir).pipe(Effect.orElseSucceed(() => path.resolve(dir))); + const isThisHome = (dir: string) => + Effect.zipWith(canonicalPath(dir), canonicalPath(input.baseDir), (a, b) => a === b); const otherBaseDirOf = (unit: string) => { const installedBaseDir = bootServiceBaseDirOf(unit); - return installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ? installedBaseDir - : undefined; + return installedBaseDir === undefined + ? Effect.undefined + : Effect.map(isThisHome(installedBaseDir), (same) => (same ? undefined : installedBaseDir)); }; const writeDurably = (filePath: string, contents: string | Uint8Array) => Effect.scoped( @@ -1208,7 +1220,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ) { const [task, running] = yield* Effect.all( [ - probe("schtasks", ["/Query", "/TN", windowsSession.taskName, "/XML"]), + probe(schtasks, ["/Query", "/TN", windowsSession.taskName, "/XML"]), Effect.promise(() => serviceLauncherIsRunning(launcherLockPath(unit))), ], { concurrency: "unbounded" }, @@ -1257,7 +1269,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const refuseOtherBaseDir = Effect.gen(function* () { const existingUnit = yield* readUnit().pipe(Effect.option); const installedBaseDir = Option.isSome(existingUnit) - ? otherBaseDirOf(existingUnit.value) + ? yield* otherBaseDirOf(existingUnit.value) : undefined; if (installedBaseDir !== undefined) { return yield* new BootServiceOtherBaseDirError({ @@ -1487,10 +1499,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return "skipped" as const; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return "skipped" as const; } // Writes no state, and the launcher lets an update transition in flight @@ -1520,10 +1529,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return yield* operation; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return yield* operation; } // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid. @@ -1603,7 +1609,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? serviceStateActiveVersion(stateText.value) : undefined; const installedBaseDir = bootServiceBaseDirOf(unit); - const otherBaseDir = otherBaseDirOf(unit); + const otherBaseDir = yield* otherBaseDirOf(unit); + // Another spelling of this home is current; repairing it would flip the unit between spellings. + const thisHomeUnit = + installedBaseDir !== undefined && otherBaseDir === undefined + ? unit.replaceAll(installedBaseDir, () => input.baseDir) + : unit; const normalizeUnit = (contents: string) => manager.kind === "launchd" ? contents.replace(/(PATH<\/key>\n\s*)[^<]*(<\/string>)/, "$1$2") @@ -1625,7 +1636,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { current: problems.length === 0 && !(manager.kind === "systemd" && systemdUnsafeValue(planForUnit(unit))) && - normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) && + normalizeUnit(thisHomeUnit) === normalizeUnit(manager.render(planForUnit(unit))) && runtimeEntryExists && Option.isSome(runtimeSentinel) && runtimeSentinel.value.trim() === input.cliVersion && diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 5115a27e63012..852be24a22200 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -31,6 +31,7 @@ import * as AuthHttp from "../auth/http.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts"; import * as CliTokenManager from "./CliTokenManager.ts"; @@ -78,6 +79,7 @@ const layerConfig = Layer.effect( const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe( Layer.provide([AuthHttp.layer, ConnectHttp.layer]), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), Layer.provide(CloudLink.layer), Layer.provide(ServerSettings.ServerSettingsService.layerTest()), Layer.provide(EnvironmentKeys.layer), @@ -303,4 +305,14 @@ describe("link proof over a non-loopback transport", () => { expect(response.status).toBe(401); }), ); + + it.effect("answers 413 to a relay proof body over the API limit", () => + Effect.gen(function* () { + const { post } = yield* linkProofClient; + const payload = { proof: "x".repeat(ServerHttp.API_MAX_BODY_BYTES) }; + for (const path of ["/api/t3-connect/health", "/api/t3-connect/mint-credential"]) { + expect((yield* post(path, payload)).status, path).toBe(413); + } + }), + ); }); diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 28a7d720c525f..d5f15cd1b4591 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -18,6 +18,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; import { + findPosixLauncher, isVersionExecutable, ensurePinnedRuntimeInstalled, isUnpublishedRelease, @@ -25,7 +26,9 @@ import { pinnedRuntimePaths, PinnedRuntimeInstallError, type PinnedRuntimeProgress, + posixLauncherScript, prunePinnedRuntimes, + resolveLauncherPath, } from "./pinnedRuntime.ts"; import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts"; @@ -987,3 +990,67 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => { }), ); }); + +// NTFS reports no exec bits, and these lookups pass over files without them. +const posixHost = HostProcess.Platform.defaultValue() !== "win32"; + +it.layer(NodeServices.layer)("launcher lookup on PATH", (it) => { + it.effect.skipIf(!posixHost)( + "resolves an empty entry of a nonempty PATH against the working directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const launcher = path.join(root, "t3"); + yield* fs.writeFileString(launcher, "", { mode: 0o755 }); + const missing = path.join(root, "missing"); + const lookup = (platform: NodeJS.Platform, searchPath: string) => + resolveLauncherPath.pipe( + Effect.provideService(HostProcess.InvokedAs, "t3"), + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + Effect.provideService(HostProcess.WorkingDirectory, root), + ); + + assert.equal(yield* lookup("linux", `:${missing}`), launcher); + assert.equal(yield* lookup("linux", `${missing}:`), launcher); + assert.equal(yield* lookup("linux", `${missing}::${missing}`), launcher); + // An empty PATH searches nothing, and Windows has no such rule. + assert.isUndefined(yield* lookup("linux", "")); + assert.isUndefined(yield* lookup("win32", `;${missing}`)); + }), + ); + + it.effect.skipIf(!posixHost)("finds a launcher script through an empty PATH entry", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const versionsDir = path.join(root, ".t3", "runtime", "versions"); + const executable = path.join(versionsDir, "1.0.0", "t3"); + yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); + yield* fs.writeFileString(executable, "", { mode: 0o755 }); + const bin = path.join(root, "bin"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString(path.join(bin, "t3"), posixLauncherScript(executable), { + mode: 0o755, + }); + const script = yield* fs.realPath(path.join(bin, "t3")); + const missing = path.join(root, "missing"); + const lookup = (searchPath: string) => + findPosixLauncher({ launchedAs: executable, versionsDir }).pipe( + Effect.provideService(HostProcess.Environment, { + PATH: searchPath, + T3CODE_INSTALL_BIN_DIR: missing, + }), + Effect.provideService(HostProcess.WorkingDirectory, bin), + ); + + assert.equal(yield* lookup(`:${missing}`), script); + assert.equal(yield* lookup(`${missing}:`), script); + // An empty PATH searches nothing, not even the working directory. + assert.isUndefined(yield* lookup("")); + }), + ); +}); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 13c8f251c93b6..06e320bc314ad 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -25,6 +25,7 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts"; const PINNED_RUNTIME_DIR = "runtime"; @@ -537,9 +538,11 @@ export const resolveLauncherPath = Effect.gen(function* () { return path.resolve(cwd, invokedAs); } const delimiter = platform === "win32" ? ";" : ":"; - for (const directory of (environment["PATH"] ?? "").split(delimiter)) { - if (directory.length === 0) continue; - const candidate = path.resolve(cwd, directory, invokedAs); + const searchPath = environment["PATH"] ?? ""; + for (const directory of searchPath.split(delimiter)) { + // POSIX shells search the working directory for an empty entry of a nonempty PATH. + if (directory.length === 0 && (platform === "win32" || searchPath.length === 0)) continue; + const candidate = path.resolve(cwd, directory || ".", invokedAs); const info = yield* fs.stat(candidate).pipe(Effect.option); // Like the shell, pass over directories and non-executable files named the same. if ( @@ -645,12 +648,13 @@ export const findPosixLauncher = Effect.fn("cloud.pinned_runtime.find_posix_laun .readFileString(path.join(path.dirname(input.versionsDir), "launchers")) .pipe(Effect.orElseSucceed(() => "")); const cwd = yield* HostProcess.WorkingDirectory; + const searchPath = environment["PATH"] ?? ""; const candidates = [ - // PATH first, resolved like the shell does: it decides which t3 the user runs. - ...(environment["PATH"] ?? "") - .split(":") - .filter((directory) => directory.length > 0) - .map((directory) => path.resolve(cwd, directory, "t3")), + // PATH first, resolved like the shell does: it decides which t3 the user runs. An empty + // entry of a nonempty PATH is the working directory; an empty PATH searches nothing. + ...(searchPath.length === 0 ? [] : searchPath.split(":")).map((directory) => + path.resolve(cwd, directory || ".", "t3"), + ), path.join( environment["T3CODE_INSTALL_BIN_DIR"] || path.join(yield* HostProcess.HomeDirectory, ".local", "bin"), @@ -789,7 +793,7 @@ const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables") .run({ ...(platform === "win32" ? { - command: "powershell.exe", + command: windowsPowerShellPath(yield* HostProcess.Environment), args: [ "-NoProfile", "-NonInteractive", diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 338ff32a3c16e..8c52725dd8a3c 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -6,6 +6,7 @@ import * as PlatformError from "effect/PlatformError"; import { assert, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import { @@ -83,11 +84,42 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])( }; const host = new FakeLauncherProcess({ protocol, childVersion: "1.1.0", update: pending }); host.env["HOME"] = root; - const client = yield* makeClient(host, "1.1.0"); + // The launcher reloads the user manager after commit, so oomd's watch must already be mirrored. + const bin = path.join(root, "bin"); + const calls = path.join(root, "systemctl-calls"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString( + path.join(bin, "systemctl"), + [ + "#!/bin/sh", + `echo "$*" >>'${calls}'`, + 'case "$*" in', + " *ControlGroup*) echo /user.slice/user-1000.slice/user@1000.service ;;", + " *ManagedOOMMemoryPressureLimit*) echo 0 ;;", + " *ManagedOOMMemoryPressure\\ *) echo kill ;;", + "esac", + "", + ].join("\n"), + ); + yield* fs.chmod(path.join(bin, "systemctl"), 0o755); + host.env["PATH"] = `${bin}:/usr/bin:/bin`; + const sentPrepared = yield* Deferred.make(); + const send = host.send; + host.send = (message, callback) => { + Deferred.doneUnsafe(sentPrepared, Effect.void); + return send(message, callback); + }; + const client = yield* makeClient(host, "1.1.0").pipe( + Effect.provideService(HostProcess.Platform, "linux"), + ); const prepared = yield* Effect.forkChild(client.prepareTrial({ baseDir }), { startImmediately: true, }); - yield* Effect.yieldNow; + yield* Deferred.await(sentPrepared); + // Nothing runs systemctl after "prepared", so the log is what ran before it. + expect(yield* fs.readFileString(calls)).toContain( + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill", + ); expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]); assert.equal(yield* fs.readLink(installed), exe("1.0.0")); @@ -325,4 +357,71 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { assert.equal(yield* fs.readLink(onPath), foreign); }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); + + it.effect.each([ + { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true }, + { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true }, + { name: "whole", searchPath: () => "", moved: false }, + ])("treats a $name empty PATH entry like the shell does", ({ searchPath, moved }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const inCwd = path.join(cwd, "t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + yield* fs.makeDirectory(cwd); + yield* fs.symlink(exe("1.0.0"), inCwd); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: searchPath(path.join(root, "missing")), + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + // A nonempty PATH searches the working directory there; an empty PATH searches nothing. + if (moved) { + assert.equal(yield* fs.readFileString(inCwd), posixLauncherScript(exe("2.0.0"))); + } else { + assert.equal(yield* fs.readLink(inCwd), exe("1.0.0")); + } + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); + + it.effect("passes over a working-directory t3 the shell cannot run", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const onPath = path.join(root, "bin/t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + // A directory named t3 in the working directory, which the shell skips. + yield* fs.makeDirectory(path.join(cwd, "t3"), { recursive: true }); + yield* fs.makeDirectory(path.dirname(onPath), { recursive: true }); + yield* fs.symlink(exe("1.0.0"), onPath); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: `:${path.dirname(onPath)}`, + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0"))); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); }); diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index e8f8941f3f9e8..50b596b0e30d5 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -8,6 +8,8 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import packageJson from "../../package.json" with { type: "json" }; import { @@ -24,6 +26,7 @@ import { type ServiceLauncherParentMessage, type SupportedLauncherProtocol, } from "./serviceProtocol.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; export class ServiceLauncherClientError extends Schema.TaggedError()( "ServiceLauncherClientError", @@ -163,9 +166,21 @@ export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined); const candidates = new Set(); if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3")); - for (const directory of (environment["PATH"] ?? "").split(":")) { - if (directory.length === 0) continue; - const candidate = path.join(directory, "t3"); + const searchPath = environment["PATH"] ?? ""; + const cwd = yield* HostProcess.WorkingDirectory; + for (const directory of searchPath.split(":")) { + // Like the shell, an empty entry of a nonempty PATH is the working directory. + if (directory.length === 0 && searchPath.length === 0) continue; + const candidate = path.join(directory || cwd, "t3"); + if (directory.length === 0) { + // The shell passes over a working-directory entry it cannot run and keeps searching. + const info = yield* fs.stat(candidate).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "File" || (info.value.mode & 0o111) === 0) { + continue; + } + candidates.add(candidate); + break; + } if ( yield* fs.exists(candidate).pipe( Effect.catch((cause) => @@ -252,6 +267,22 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o const path = yield* Path.Path; const environment = yield* HostProcess.Environment; const platform = yield* HostProcess.Platform; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // The launcher that commits a remote update is the old one; its reload after commit + // keeps oomd's watch only if the policy is mirrored before it. + const keepOomdWatch = + platform === "linux" + ? spawner + .exitCode( + ChildProcess.make("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + env: environment, + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + }), + ) + .pipe(Effect.timeout("30 seconds"), Effect.ignore) + : Effect.void; const exchange = ( message: ServiceLauncherChildMessage, @@ -331,28 +362,31 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o : context.update; const prepareTrial = (input: { readonly baseDir: string }) => pending !== undefined - ? exchange( - { type: "prepared", updateId: pending.id }, - (reply) => reply.type === "committed" && reply.updateId === pending.id, - ).pipe( - Effect.flatMap((reply) => - reply.type !== "committed" - ? Effect.die("service launcher returned an impossible prepared response") - : repointLaunchers({ - baseDir: input.baseDir, - targetVersion: pending.targetVersion, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fs), - Effect.provideService(Path.Path, path), - Effect.provideService(HostProcess.Environment, environment), - Effect.provideService(HostProcess.Platform, platform), - Effect.as({ - id: pending.id, - fromVersion: pending.fromVersion, + ? Effect.andThen( + keepOomdWatch, + exchange( + { type: "prepared", updateId: pending.id }, + (reply) => reply.type === "committed" && reply.updateId === pending.id, + ).pipe( + Effect.flatMap((reply) => + reply.type !== "committed" + ? Effect.die("service launcher returned an impossible prepared response") + : repointLaunchers({ + baseDir: input.baseDir, targetVersion: pending.targetVersion, - status: "committed" as const, - }), - ), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HostProcess.Platform, platform), + Effect.as({ + id: pending.id, + fromVersion: pending.fromVersion, + targetVersion: pending.targetVersion, + status: "committed" as const, + }), + ), + ), ), ) : Effect.succeed(outcome); diff --git a/apps/server/src/cloud/serviceProtection.ts b/apps/server/src/cloud/serviceProtection.ts index 48790bcf6cc05..a8952ce299fd9 100644 --- a/apps/server/src/cloud/serviceProtection.ts +++ b/apps/server/src/cloud/serviceProtection.ts @@ -8,6 +8,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProcessRunner from "../processRunner.ts"; import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; const PROTECT_DROP_IN = "90-t3code-protect.conf"; const SYSTEM_UNIT_DIR = "/etc/systemd/system"; @@ -210,10 +211,12 @@ export const detectRemoteAccessUnits = run("list remote-access services", "syste Effect.withSpan("ServiceProtection.detectRemoteAccessUnits"), ); -const reloadUserManager = run("reload systemd user units", "systemctl", [ - "--user", - "daemon-reload", -]); +const reloadUserManager = Effect.andThen( + run("reload systemd user units", "systemctl", ["--user", "daemon-reload"]), + run("restore systemd-oomd's watch", "/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT]).pipe( + Effect.ignore, + ), +); const writeDropIns = Effect.fn("ServiceProtection.writeDropIns")(function* ( dropIns: ReadonlyArray, diff --git a/apps/server/src/cloud/userManagerOom.test.ts b/apps/server/src/cloud/userManagerOom.test.ts new file mode 100644 index 0000000000000..67c0e51e11639 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.test.ts @@ -0,0 +1,72 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { expect, it } from "vite-plus/test"; + +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; + +const userService = "/user.slice/user-1001.slice/user@1001.service"; + +it.each([ + [ + "mirrors the system manager's kill policy onto the user manager's root slice", + { cgroup: userService, mode: "kill", limit: "4252017622", duration: "" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=99.00%", + ], + [ + "keeps a custom duration and an unset limit", + { cgroup: userService, mode: "kill", limit: "0", duration: "20s" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=0.00% ManagedOOMMemoryPressureDurationSec=20s", + ], + [ + "leaves the slice alone when oomd is not told to kill", + { cgroup: userService, mode: "auto", limit: "0", duration: "infinity" }, + undefined, + ], + [ + "leaves the slice alone outside a user@ service", + { cgroup: "/system.slice/foo.service", mode: "kill", limit: "0", duration: "infinity" }, + undefined, + ], +])("%s", (_name, system, expected) => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-oomd-")); + try { + const calls = NodePath.join(root, "calls"); + NodeFS.writeFileSync( + NodePath.join(root, "systemctl"), + [ + "#!/bin/sh", + 'echo "$*" >>"$CALLS"', + 'case "$*" in', + ' *ControlGroup*) echo "$CGROUP" ;;', + ' *ManagedOOMMemoryPressureLimit*) echo "$LIMIT" ;;', + ' *ManagedOOMMemoryPressureDurationUSec*) echo "$DURATION" ;;', + ' *ManagedOOMMemoryPressure\\ *) echo "$MODE" ;;', + "esac", + "", + ].join("\n"), + { mode: 0o755 }, + ); + const result = NodeChildProcess.spawnSync("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + encoding: "utf8", + env: { + PATH: `${root}:/usr/bin:/bin`, + CALLS: calls, + CGROUP: system.cgroup, + MODE: system.mode, + LIMIT: system.limit, + DURATION: system.duration, + }, + }); + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + const setProperty = NodeFS.readFileSync(calls, "utf8") + .split("\n") + .find((call) => call.includes("set-property")); + expect(setProperty).toBe(expected); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/server/src/cloud/userManagerOom.ts b/apps/server/src/cloud/userManagerOom.ts new file mode 100644 index 0000000000000..6f23427b83999 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.ts @@ -0,0 +1,22 @@ +/** + * Run after `systemctl --user daemon-reload`. The user manager's -.slice shares the cgroup of + * user@.service and reports it to systemd-oomd as `auto` on reload, which drops the system + * manager's `kill` watch (systemd/systemd#43174). Mirroring that policy onto -.slice restores the + * watch and keeps it through later reloads. Best effort: exits 0 when there is nothing to mirror. + */ +export const RESTORE_OOMD_WATCH_SCRIPT = [ + "unit=$(systemctl --user show --property=ControlGroup --value -- -.slice) || exit 0", + "unit=${unit##*/}", + "case $unit in user@*.service) ;; *) exit 0 ;; esac", + 'show() { systemctl show --property="$1" --value "$unit"; }', + '[ "$(show ManagedOOMMemoryPressure)" = kill ] || exit 0', + "limit=$(show ManagedOOMMemoryPressureLimit)", + "case $limit in '' | *[!0-9]*) exit 0 ;; esac", + // The limit is a fraction of 2^32; set-property takes a percentage. + "p=$(( (limit * 10000 + 2147483648) / 4294967296 ))", + 'set -- ManagedOOMMemoryPressure=kill "ManagedOOMMemoryPressureLimit=$((p / 100)).$(printf %02d $((p % 100)))%"', + "duration=$(show ManagedOOMMemoryPressureDurationUSec)", + 'case $duration in "" | infinity) ;; *) set -- "$@" "ManagedOOMMemoryPressureDurationSec=$duration" ;; esac', + 'exec systemctl --user set-property --runtime -- -.slice "$@"', + "", +].join("\n"); diff --git a/apps/server/src/device/DeviceHost.ts b/apps/server/src/device/DeviceHost.ts index 898b028c4329c..aaf858cecbcad 100644 --- a/apps/server/src/device/DeviceHost.ts +++ b/apps/server/src/device/DeviceHost.ts @@ -67,6 +67,8 @@ export class AgentDeviceStartError extends Schema.TaggedError export const makeDeviceHubOperations = (options: { readonly hostId: DeviceHostId; readonly origin: string; + readonly token?: string | undefined; readonly http: HttpClient.HttpClient; readonly run: DeviceHostReady["run"]; /** Android gates listing AVDs, which the hub does not report until they boot. */ readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect; }): DeviceOperations => { const { hostId, origin, run } = options; - const httpClient = options.http.pipe(HttpClient.withScope); + const { token } = options; + const httpClient = ( + token === undefined + ? options.http + : options.http.pipe(HttpClient.mapRequest(HttpClientRequest.bearerToken(token))) + ).pipe(HttpClient.withScope); const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* ( request: HttpClientRequest.HttpClientRequest, @@ -290,11 +299,26 @@ export const makeDeviceHubOperations = (options: { ? attachIosStream(device.id, "open").pipe(Effect.asVoid) : Effect.void; + // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an + // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer + // lists its serial in any state. + const emulatorExited = (serial: string) => + /^emulator-\d+$/.test(serial) + ? run("adb", ["devices"], { timeoutMs: Duration.toMillis(ADB_DEVICES_TIMEOUT) }).pipe( + Effect.map( + ({ code, stdout }) => + code === 0 && + !stdout.split(/\r?\n/).some((line) => line.trim().split(/\s+/)[0] === serial), + ), + Effect.orElseSucceed(() => false), + ) + : Effect.succeed(false); + const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")( function* (device) { - const postShutdown = (path: string, body: Record) => + const postShutdown = (path: string, body: Record, timeout?: Duration.Input) => postJson(path, body, "shutdown").pipe( - Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")), + Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown", timeout)), Effect.flatMap((result) => result.ok ? Effect.void @@ -323,7 +347,23 @@ export const makeDeviceHubOperations = (options: { ), ), ) - : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id }); + : postShutdown( + "/api/devices/shutdown", + { platform: device.platform, id: device.id }, + ANDROID_SHUTDOWN_TIMEOUT, + ).pipe( + Effect.catch((cause) => + emulatorExited(device.id).pipe( + Effect.flatMap((exited) => + exited + ? Effect.logInfo("Android emulator has exited", { + deviceId: device.id, + }) + : Effect.fail(cause), + ), + ), + ), + ); }, ); diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.ts index d7fee1a2271df..ef4ebd0372034 100644 --- a/apps/server/src/device/DeviceHubProxy.test.ts +++ b/apps/server/src/device/DeviceHubProxy.test.ts @@ -44,7 +44,14 @@ const fixture = ( if (fail) return yield* Effect.die(new Error("upstream failed")); return HttpClientResponse.fromWeb( request, - new Response(stream ?? "frame", { headers: { "set-cookie": "upstream=1" } }), + new Response(stream ?? "frame", { + headers: { + "set-cookie": "upstream=1", + "clear-site-data": '"*"', + "content-type": "text/html", + "content-security-policy": "script-src *", + }, + }), ); }), ); @@ -69,7 +76,7 @@ const fixture = ( Effect.succeed({ hostId: hostId ?? LOCAL_DEVICE_HOST_ID, nodePath: "node", - hub: { origin: "http://hub.test" }, + hub: { origin: "http://hub.test", token: "hub-token" }, devices: { list: unexpectedOperation, boot: () => unexpectedOperation, @@ -122,6 +129,11 @@ describe("device hub proxy", () => { ); expect(response.status).toBe(200); expect(await response.text()).toBe("frame"); + expect(response.headers.get("set-cookie")).toBeNull(); + expect(response.headers.get("clear-site-data")).toBeNull(); + // Opened as a page, a hub response gets an opaque origin and no script. + expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; sandbox"); + expect(response.headers.get("x-content-type-options")).toBe("nosniff"); expect(requests).toEqual(["http://hub.test/api/devices"]); expect(finalized()).toBe(1); }); @@ -214,6 +226,7 @@ describe("device hub proxy", () => { await response.text(); expect(headers).toHaveLength(1); expect(headers[0]?.origin).toBe("http://hub.test"); + expect(headers[0]?.authorization).toBe("Bearer hub-token"); expect(headers[0]).not.toHaveProperty("x-forwarded-proto"); }); diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.ts index 9778cf084b017..90c5743a26050 100644 --- a/apps/server/src/device/DeviceHubProxy.ts +++ b/apps/server/src/device/DeviceHubProxy.ts @@ -164,11 +164,13 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( const headers: Record = {}; for (const [name, value] of Object.entries(response.headers)) { // A cookie from an upstream such as an Expo Simulators session's preview host would land on T3's origin. + // Clear-Site-Data likewise applies to the origin that serves it. if ( name === "content-encoding" || name === "transfer-encoding" || name === "connection" || - name === "set-cookie" + name === "set-cookie" || + name === "clear-site-data" ) { continue; } @@ -176,6 +178,9 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( } // Long-lived MJPEG and AVCC responses must not be buffered by compression. headers["cache-control"] = "no-store, no-transform"; + // Hub responses are data and streams; none renders as a page on this origin. + headers["x-content-type-options"] = "nosniff"; + headers["content-security-policy"] = "default-src 'none'; sandbox"; const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace") ? repeatStillFrame(response.stream) : response.stream; @@ -245,18 +250,21 @@ const handler = Effect.gen(function* () { return HttpServerResponse.text("Not Found", { status: 404 }); } const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`; + const upstreamHeaders = + routed?.headers ?? + (ready.hub.token === undefined ? undefined : { authorization: `Bearer ${ready.hub.token}` }); if (upgrade) { return yield* Effect.raceFirst( proxyWebSocket( request, upstreamUrl.replace(/^http/, "ws"), routed?.protocols, - routed?.headers, + upstreamHeaders, ), invalidated.pipe(Effect.as(HttpServerResponse.empty())), ); } - return yield* proxyHttp(request, upstreamUrl, invalidated, routed?.headers); + return yield* proxyHttp(request, upstreamUrl, invalidated, upstreamHeaders); }); export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler); diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 00e942f1e6df5..972a9a2b150b2 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -18,6 +18,7 @@ import { SshCommandError } from "@t3tools/ssh/errors"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; @@ -192,7 +193,14 @@ const fixture = Effect.fn("fixture")(function* ( const listing = { hangs: false, requested: yield* Deferred.make() }; let booted = false; let shutDown = false; - const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false }; + const connection = { + online: true, + kind: "local" as "local" | "ssh", + failShutdown: false, + shutdownDelay: undefined as Duration.Input | undefined, + adbDevices: undefined as { code: number; stdout: string; stderr: string } | undefined, + }; + const shutdownRequested = yield* Deferred.make(); const http = HttpClient.make((request) => Effect.gen(function* () { requests.push(request.url); @@ -230,6 +238,8 @@ const fixture = Effect.fn("fixture")(function* ( return HttpClientResponse.fromWeb(request, new Response(yield* Ref.get(screenshotBody))); } if (request.url.endsWith("/shutdown")) { + yield* Deferred.succeed(shutdownRequested, undefined); + if (connection.shutdownDelay !== undefined) yield* Effect.sleep(connection.shutdownDelay); if (connection.failShutdown) return HttpClientResponse.fromWeb(request, Response.json({ ok: false })); shutDown = true; @@ -283,10 +293,19 @@ const fixture = Effect.fn("fixture")(function* ( ); }), ); - const run = (command: string) => + const run = (command: string, args: ReadonlyArray) => command === "emulator" ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }) - : Ref.get(encoderResult); + : command === "adb" && args.join(" ") === "devices" + ? Effect.sync( + () => + connection.adbDevices ?? { + code: 0, + stdout: `List of devices attached\n${booted ? "emulator-5554\tdevice\n" : ""}`, + stderr: "", + }, + ) + : Ref.get(encoderResult); const ready: DeviceHost.DeviceHostReady = { nodePath: process.execPath, hub: { origin: "http://device.test" }, @@ -426,6 +445,7 @@ const fixture = Effect.fn("fixture")(function* ( iosAvailable, listing, endDevice, + shutdownRequested, }; }); @@ -1574,6 +1594,66 @@ it.effect.each([ }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))), ); +describe("Android close with shutdown", () => { + const openEmulator = Effect.fn("openEmulator")(function* () { + const harness = yield* fixture(); + yield* harness.service.configure({ enabled: true }); + const threadId = ThreadId.make("android-close"); + const session = yield* harness.service.open({ + threadId, + deviceId: "Pixel_API_35", + platform: "android", + }); + expect(session.deviceId).toBe("emulator-5554"); + return { ...harness, threadId }; + }); + + it.effect("closes the session on a retry once the emulator has exited", () => + Effect.gen(function* () { + const { service, connection, endDevice, threadId } = yield* openEmulator(); + // The hub's `adb emu kill` fails once the serial is gone, so every attempt is rejected. + connection.failShutdown = true; + const first = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(first)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + + endDevice(); + yield* service.close({ threadId, shutdown: true }); + expect((yield* service.state).sessions).toEqual([]); + }), + ); + + it.effect.each([ + { + adb: "lists it offline", + result: { code: 0, stdout: "List of devices attached\nemulator-5554\toffline\n", stderr: "" }, + }, + { adb: "fails", result: { code: 1, stdout: "", stderr: "adb: no server" } }, + ])("keeps the session after a rejected shutdown when adb $adb", ({ result }) => + Effect.gen(function* () { + const { service, connection, threadId } = yield* openEmulator(); + connection.failShutdown = true; + connection.adbDevices = result; + const exit = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(exit)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + }), + ); + + it.effect("waits for an emulator the hub takes longer than 15 seconds to see exit", () => + Effect.gen(function* () { + const { service, connection, shutdownRequested, threadId } = yield* openEmulator(); + // The hub allows the emulator 30 seconds to leave adb after the kill. + connection.shutdownDelay = Duration.seconds(25); + const closing = yield* Effect.forkChild(service.close({ threadId, shutdown: true })); + yield* Deferred.await(shutdownRequested); + yield* TestClock.adjust(Duration.seconds(25)); + expect(Exit.isSuccess(yield* Fiber.await(closing))).toBe(true); + expect((yield* service.state).sessions).toEqual([]); + }), + ); +}); + it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])( "retains hub inventory on %s when AVD enumeration fails and recovers on retry", (hostId) => diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.ts index c1bbcbc347ea0..320aa8daf545c 100644 --- a/apps/server/src/device/LocalDeviceHost.test.ts +++ b/apps/server/src/device/LocalDeviceHost.test.ts @@ -55,6 +55,7 @@ const agentFixture = Effect.fn("agentFixture")(function* ( cameraHelp: "", cameraProbes: 0, spawnedEnvironments: [] as Array, + spawnedArgs: [] as Array>, }; const daemonStopRequested = yield* Deferred.make>(); const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata")); @@ -93,22 +94,25 @@ const agentFixture = Effect.fn("agentFixture")(function* ( ) : Effect.addFinalizer(() => hub.cleanup).pipe( Effect.tap(() => - Effect.sync(() => - hub.spawnedEnvironments.push( + Effect.sync(() => { + if (command._tag === "StandardCommand") hub.spawnedArgs.push(command.args); + return hub.spawnedEnvironments.push( ( command as unknown as { readonly options: { readonly env?: NodeJS.ProcessEnv }; } ).options.env, - ), - ), + ); + }), ), Effect.as( ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(123), stdout: Stream.empty, stderr: Stream.empty, - all: Stream.empty, + all: Stream.encodeText( + Stream.make(" Local: http://localhost:1/?token=hub-token\n"), + ), exitCode: Effect.never, isRunning: Effect.sync(() => hub.running), kill: () => Effect.void, @@ -190,6 +194,82 @@ describe("AgentDevice startup", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + // regression: #41190 a daemon left by the previous pin keeps answering /health + it.effect("hands a daemon recorded at another agent-device version to the pinned client", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const previous = { httpPort: 12345, token: "previous-token", version: "0.21.36" }; + const { host, runs } = yield* agentFixture( + (stateDir) => + fs + .writeFileString( + `${stateDir}/daemon.json`, + JSON.stringify({ + httpPort: 23456, + token: "next-token", + version: AGENT_DEVICE_VERSION, + }), + ) + .pipe(Effect.orDie, Effect.as(processOutput(0))), + processOutput(0), + previous, + ); + const ready = yield* host.ensureAgentReady(() => Effect.void); + expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1); + expect(ready.agentDevice).toMatchObject({ + baseUrl: "http://127.0.0.1:23456", + token: "next-token", + }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps a busy daemon from another version that the pinned client leaves running", () => + Effect.gen(function* () { + const previous = { httpPort: 12345, token: "previous-token", version: "0.21.36" }; + const { host, runs } = yield* agentFixture( + () => Effect.succeed(processOutput(1)), + processOutput(0), + previous, + ); + const ready = yield* host.ensureAgentReady(() => Effect.void); + expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1); + expect(ready.agentDevice).toMatchObject({ + baseUrl: "http://127.0.0.1:12345", + token: "previous-token", + }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reports a stopped daemon a failed replacement left registered", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + let health: Ref.Ref | undefined; + const previous = { + httpPort: 12345, + token: "previous-token", + pid: process.pid, + version: "0.21.36", + }; + const { host, stateDir, runs, daemonHealthy } = yield* agentFixture( + () => (health ? Ref.set(health, false) : Effect.void).pipe(Effect.as(processOutput(1))), + processOutput(0), + previous, + ); + health = daemonHealthy; + const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip); + expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1); + expect(error).toMatchObject({ + _tag: "AgentDeviceStartError", + reason: "command_failed", + exitCode: 1, + }); + expect(yield* fs.readFileString(path.join(stateDir, "daemon.json"))).toContain( + previous.token, + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("uses the SDK a later shell environment selects", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -384,6 +464,18 @@ describe("AgentDevice startup", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + it.effect("starts the hub requiring a session token and keeps the one it prints", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const { host, hub, baseDir } = yield* agentFixture(() => Effect.succeed(processOutput(0))); + expect(hub.spawnedArgs[0]).toContain("--require-token"); + expect(hub.spawnedEnvironments[0]?.EXPO_DEVICE_HUB_STATE_DIR).toBe( + path.join(baseDir, "userdata", "device", "hub"), + ); + expect((yield* host.current)?.hub.token).toBe("hub-token"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("keeps releasing agent sessions while a dead hub fails to restart and after", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index d7443d1a4b88b..7fd2816e3c17c 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -17,6 +17,7 @@ import { import * as NetService from "@t3tools/shared/Net"; import { isCommandAvailable } from "@t3tools/shared/shell"; import * as Clock from "effect/Clock"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -53,6 +54,7 @@ import { } from "./DeviceToolchain.ts"; const HUB_READY_TIMEOUT_MS = 30_000; +const HUB_TOKEN_PATTERN = /\btoken=([\w.~-]+)/; const DAEMON_READY_TIMEOUT_MS = 30_000; const DAEMON_POLL_MS = 100; const HUB_RESTART_STABLE_UPTIME_MS = 60_000; @@ -93,6 +95,7 @@ interface HubProcess { readonly child: ChildProcessSpawner.ChildProcessHandle; readonly scope: Scope.Closeable; readonly origin: string; + readonly token: string; readonly startedAtMillis: number; readonly emulatorExtraArgs: string | undefined; readonly emulatorStamp: string | undefined; @@ -430,6 +433,9 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { yield* fs .makeDirectory(agentDeviceStateDir(path, config.stateDir), { recursive: true }) .pipe(Effect.ignore); + // The hub records its token in this folder, kept with the rest of the server's state. + const hubStateDir = path.join(config.stateDir, "device", "hub"); + yield* fs.makeDirectory(hubStateDir, { recursive: true, mode: 0o700 }).pipe(Effect.ignore); const port = yield* net.reserveLoopbackPort("127.0.0.1").pipe( Effect.mapError( (cause) => @@ -454,6 +460,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { String(port), "--host", "127.0.0.1", + // Only the server, which reads the token the hub prints, talks to the hub. + "--require-token", "--hide-sidebar", "--hide-boot-device", ...hubPlatformArguments(hostPlatform), @@ -464,7 +472,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { shell: false, stdout: "pipe", stderr: "pipe", - env, + env: { ...env, EXPO_DEVICE_HUB_STATE_DIR: hubStateDir }, }, ), ) @@ -480,16 +488,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { ), ); const startedAtMillis = yield* Clock.currentTimeMillis; - const hub: HubProcess = { - child, - scope, - origin, - startedAtMillis, - nodePath, - emulatorExtraArgs: env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS, - emulatorStamp: stamp, - }; - yield* Effect.forkIn(observeHubOutput(hub), scope); + const announcedToken = yield* Deferred.make(); + yield* Effect.forkIn(observeHubOutput(child, announcedToken), scope); yield* waitForHttpReady({ baseUrl: origin, path: "/readyz", @@ -501,21 +501,56 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { cause: info.cause, }), }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)); + const token = yield* Deferred.await(announcedToken).pipe( + Effect.timeoutOrElse({ + duration: Duration.millis(HUB_READY_TIMEOUT_MS), + orElse: () => + Effect.fail( + new DeviceHost.DeviceHostError({ + hostId, + step: "reading the device hub's session token", + cause: new Error("The device hub did not print a session token."), + }), + ), + }), + ); + const hub: HubProcess = { + child, + scope, + origin, + token, + startedAtMillis, + nodePath, + emulatorExtraArgs: env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS, + emulatorStamp: stamp, + }; yield* recordHub(hub, hubTool); yield* Effect.logInfo("Device hub started", { pid: Number(child.pid), port }); return hub; }).pipe(Effect.onError(() => Scope.close(scope, Exit.void).pipe(Effect.ignore))); }); - const observeHubOutput = (hub: HubProcess) => - hub.child.all.pipe( + // The hub generates its session token and prints it in its startup link; keep it out of logs. + const observeHubOutput = ( + child: ChildProcessSpawner.ChildProcessHandle, + announcedToken: Deferred.Deferred, + ) => + child.all.pipe( Stream.decodeText(), Stream.splitLines, Stream.map((line) => line.trim()), Stream.filter((line) => line.length > 0), - Stream.runForEach((line) => - Effect.logDebug("Device hub output", { pid: Number(hub.child.pid), output: line }), - ), + Stream.runForEach((line) => { + const token = HUB_TOKEN_PATTERN.exec(line)?.[1]; + return (token === undefined ? Effect.void : Deferred.succeed(announcedToken, token)).pipe( + Effect.andThen( + Effect.logDebug("Device hub output", { + pid: Number(child.pid), + output: line.replace(HUB_TOKEN_PATTERN, "token="), + }), + ), + ); + }), Effect.ignoreCause, ); @@ -590,19 +625,25 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { token: file.token, entryPath: agentTool.entryPath, }); - if (existing._tag === "Some") { - const alive = yield* HttpClient.withScope(httpClient) - .get(`http://127.0.0.1:${existing.value.httpPort}/health`) + const daemonAnswersHealth = (httpPort: number) => + HttpClient.withScope(httpClient) + .get(`http://127.0.0.1:${httpPort}/health`) .pipe( - Effect.timeout(Duration.seconds(2)), Effect.flatMap((response) => response.arrayBuffer.pipe(Effect.as(response.status === 200)), ), + Effect.timeout(Duration.seconds(2)), Effect.scoped, Effect.orElseSucceed(() => false), ); - if (alive) return toEndpoint(existing.value); - yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore); + if (existing._tag === "Some") { + const alive = yield* daemonAnswersHealth(existing.value.httpPort); + const samePin = + existing.value.version === undefined || existing.value.version === AGENT_DEVICE_VERSION; + if (alive && samePin) return toEndpoint(existing.value); + // A live daemon from another pin may speak another RPC protocol. Keep its registration so + // the pinned CLI retires it, which that CLI does only while the daemon holds no work. + if (!alive) yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore); } // No `daemon start` exists; `devices` is the cheapest command that starts and awaits it. const runResult = yield* runner @@ -614,9 +655,16 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { timeoutBehavior: "timedOutResult", }) .pipe(Effect.result); - // Discovery may fail after startup; accept a published endpoint or preserve the CLI failure. + // A failed run can stop the previous daemon and leave its file. Keep that registration + // only while it still answers; a successful run has published the endpoint it reached. const started = yield* readDaemonFile().pipe(Effect.option); - if (started._tag === "Some") return toEndpoint(started.value); + if (started._tag === "Some") { + const runSucceeded = + runResult._tag === "Success" && !runResult.success.timedOut && runResult.success.code === 0; + if (runSucceeded || (yield* daemonAnswersHealth(started.value.httpPort))) { + return toEndpoint(started.value); + } + } if (runResult._tag === "Failure") { return yield* new DeviceHost.DeviceHostError({ hostId, @@ -892,10 +940,14 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { ); const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({ - hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint, + hub: { + origin: running.hub.origin, + token: running.hub.token, + } satisfies DeviceHost.DeviceHubEndpoint, devices: makeDeviceHubOperations({ hostId, origin: running.hub.origin, + token: running.hub.token, http: httpClient, run, platformAvailable: (platform) => diff --git a/apps/server/src/device/SshDeviceHost.test.ts b/apps/server/src/device/SshDeviceHost.test.ts index cab2784a6b243..54b7d03c480f3 100644 --- a/apps/server/src/device/SshDeviceHost.test.ts +++ b/apps/server/src/device/SshDeviceHost.test.ts @@ -78,6 +78,7 @@ it.effect("preserves installed status after probes and cleans failed agent activ nodePath: "/node", platforms: [{ platform: "ios", available: true }], hubPort: 1234, + hubToken: "hub-token", helpers: { serveSimAxSettings: null, serveSimCli: null }, ...(mode === "agent-start" ? { daemonPort: 1235, token: "fixture", entryPath: "/agent.mjs" } @@ -222,6 +223,7 @@ it.effect("releases the forward of a bootstrap interrupted before its hub answer nodePath: "/node", platforms: [{ platform: "ios", available: true }], hubPort: 1234, + hubToken: "hub-token", helpers: { serveSimAxSettings: null, serveSimCli: null }, }); return ChildProcessSpawner.makeHandle({ @@ -324,6 +326,7 @@ it.effect("lists Android devices without probing the host again once it reports { platform: "android", available: androidInstalled }, ], hubPort: 1234, + hubToken: "hub-token", helpers: { serveSimAxSettings: null, serveSimCli: null }, }); } @@ -422,6 +425,7 @@ it.effect( nodePath: "/node", platforms: [{ platform: "ios", available: true }], hubPort: 1234, + hubToken: "hub-token", helpers: { serveSimAxSettings: null, serveSimCli: null }, }); return ChildProcessSpawner.makeHandle({ diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.ts index d6946b419429a..c85607a17d616 100644 --- a/apps/server/src/device/SshDeviceHost.ts +++ b/apps/server/src/device/SshDeviceHost.ts @@ -76,6 +76,7 @@ const Probe = Schema.Struct({ const Started = Schema.Struct({ ...Probe.fields, hubPort: Schema.Int, + hubToken: Schema.String, daemonPort: Schema.optionalKey(Schema.Int), token: Schema.optionalKey(Schema.String), entryPath: Schema.optionalKey(Schema.String), @@ -438,10 +439,12 @@ export const make = Effect.fn("SshDeviceHost.make")(function* ( const hubOrigin = `http://127.0.0.1:${hubPort}`; const next = { nodePath: remote.nodePath, - hub: { origin: hubOrigin }, + // The forward and the remote hub both require the hub's token. + hub: { origin: hubOrigin, token: remote.hubToken }, devices: makeDeviceHubOperations({ hostId: config.id, origin: hubOrigin, + token: remote.hubToken, http, run, // Keep probing negative reports so tooling installed after connecting is still found. diff --git a/apps/server/src/device/deviceToolMaintenance.ts b/apps/server/src/device/deviceToolMaintenance.ts index 2832071d099d0..7ff3a961eee9d 100644 --- a/apps/server/src/device/deviceToolMaintenance.ts +++ b/apps/server/src/device/deviceToolMaintenance.ts @@ -65,7 +65,7 @@ function pruneTools(root, specs, flat) { return withToolMaintenance(root, () => { // Keep installs used by any running helper, including older T3 releases. const scan = process.platform === 'win32' - ? require('node:child_process').spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine'], { encoding: 'utf8', timeout: 10000 }) + ? require('node:child_process').spawnSync((process.env.SystemRoot || process.env.windir || 'C:\\Windows') + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine'], { encoding: 'utf8', timeout: 10000 }) : require('node:child_process').spawnSync('ps', ['-ax', '-o', 'command='], { encoding: 'utf8', timeout: 10000 }); if (scan.status !== 0 || !scan.stdout) return; for (const [name, required] of specs) { diff --git a/apps/server/src/device/sshDeviceScript.test.ts b/apps/server/src/device/sshDeviceScript.test.ts index 8fd592c20c546..9cfa6f27e01ed 100644 --- a/apps/server/src/device/sshDeviceScript.test.ts +++ b/apps/server/src/device/sshDeviceScript.test.ts @@ -7,6 +7,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; +import { DEVICE_HUB_VERSION } from "./DeviceToolchain.ts"; import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts"; const exec = NodeUtil.promisify(NodeChildProcess.execFile); @@ -239,3 +240,59 @@ it.effect("keeps a daemon record its missing agent CLI cannot stop", () => }); }), ); + +it.effect("starts the hub requiring a session token and reports the one it printed", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + yield* Effect.promise(async () => { + const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-ssh-hub-")); + const run = (mode: "start" | "stop") => + NodeChildProcess.spawnSync(process.execPath, [], { + input: remoteDeviceScript("owner", mode), + env: { + HOME: home, + PATH: `${NodePath.join(home, "bin")}:/usr/bin:/bin`, + ANDROID_HOME: NodePath.join(home, "sdk"), + }, + encoding: "utf8", + }); + try { + const state = NodePath.join(home, ".t3/device/hosts/owner"); + const install = NodePath.join( + home, + ".t3/device/tools", + `expo-device-hub@${DEVICE_HUB_VERSION}`, + ); + const entry = NodePath.join(install, "node_modules/expo-device-hub/dist/server/cli.mjs"); + await completeSdk(NodePath.join(home, "sdk")); + await NodeFSP.mkdir(NodePath.dirname(entry), { recursive: true }); + await NodeFSP.writeFile(NodePath.join(install, ".install-complete"), DEVICE_HUB_VERSION); + // Stands in for the hub: it serves /readyz and prints its startup link. + await NodeFSP.writeFile( + entry, + `import * as http from "node:http"; +const args = process.argv.slice(2); +const token = args.includes("--require-token") ? "printed-token" : undefined; +http.createServer((_request, response) => response.end("ok")).listen(Number(args[args.indexOf("--port") + 1]), "127.0.0.1", () => { + console.log(" Local: http://localhost/" + (token ? "?token=" + token : "")); + console.log("state-dir=" + process.env.EXPO_DEVICE_HUB_STATE_DIR); +});`, + ); + + const started = run("start"); + expect(started.stderr).toBe(""); + expect(JSON.parse(started.stdout).hubToken).toBe("printed-token"); + expect( + JSON.parse(await NodeFSP.readFile(NodePath.join(state, "hub.json"), "utf8")).token, + ).toBe("printed-token"); + expect((await NodeFSP.stat(NodePath.join(state, "hub.log"))).mode & 0o077).toBe(0); + expect(await NodeFSP.readFile(NodePath.join(state, "hub.log"), "utf8")).toContain( + `state-dir=${state}\n`, + ); + } finally { + run("stop"); + await NodeFSP.rm(home, { recursive: true, force: true }); + } + }); + }), +); diff --git a/apps/server/src/device/sshDeviceScript.ts b/apps/server/src/device/sshDeviceScript.ts index 7a32640766a8f..cc3c147fa9b70 100644 --- a/apps/server/src/device/sshDeviceScript.ts +++ b/apps/server/src/device/sshDeviceScript.ts @@ -207,13 +207,20 @@ async function install(name, version, entry) { }) : []; const emulatorExtraArgs = [cameraArgs.join(' '), process.env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS].filter(Boolean).join(' '); let hub = read(hubFile); - if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || hub.emulatorExtraArgs !== emulatorExtraArgs || !await healthy(hub.port, '/readyz')) { + // A hub recorded without a token predates --require-token and is replaced. + if (!hub || hub.owner !== owner || !hub.token || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || hub.emulatorExtraArgs !== emulatorExtraArgs || !await healthy(hub.port, '/readyz')) { stopHub(hub); for (let attempt = 0; attempt < 5; attempt++) { const hubPort = await port(); - const log = fs.openSync(path.join(state, 'hub.log'), 'a'); - const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device', ...(hubPlatform ? ['--platform', hubPlatform] : [])], { - cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: emulatorExtraArgs, FORCE_COLOR: '0', NO_COLOR: '1' }, + // The hub prints the session token it generates, so its log is private and read from here on. + // It also records the token in its state folder, kept in this host's private folder. + const logFile = path.join(state, 'hub.log'); + const log = fs.openSync(logFile, 'a', 0o600); + fs.fchmodSync(log, 0o600); + const logStart = fs.fstatSync(log).size; + const announcedToken = () => /\btoken=([\w.~-]+)/.exec(fs.readFileSync(logFile, 'utf8').slice(logStart))?.[1]; + const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--require-token', '--hide-sidebar', '--hide-boot-device', ...(hubPlatform ? ['--platform', hubPlatform] : [])], { + cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, EXPO_DEVICE_HUB_STATE_DIR: state, EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: emulatorExtraArgs, FORCE_COLOR: '0', NO_COLOR: '1' }, }); try { await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); } finally { fs.closeSync(log); } @@ -223,7 +230,7 @@ async function install(name, version, entry) { const deadline = Date.now() + 30000; let listening = false; while (child.exitCode === null && child.signalCode === null) { - if (await healthy(hub.port, '/readyz')) { listening = true; break; } + if (await healthy(hub.port, '/readyz') && (hub.token = announcedToken())) { write(hubFile, hub); listening = true; break; } if (Date.now() > deadline) { stopHub(hub); throw Error('Device hub did not become ready. See ' + path.join(state, 'hub.log')); } await sleep(200); } @@ -258,7 +265,7 @@ async function install(name, version, entry) { const vendor = path.resolve(path.dirname(hubEntry), '../../vendor/serve-sim/dist'); const optional = file => fs.existsSync(file) ? file : null; await pruneTools(path.join(root, 'tools'), [['expo-device-hub', hubVersion], ...(mode === 'agent-start' ? [['agent-device', agentVersion]] : [])], true).catch(() => {}); - console.log(JSON.stringify({ nodePath: process.execPath, platforms, tools: versions(), hubPort: hub.port, ...agentResult, + console.log(JSON.stringify({ nodePath: process.execPath, platforms, tools: versions(), hubPort: hub.port, hubToken: hub.token, ...agentResult, helpers: { serveSimAxSettings: optional(path.join(vendor, 'simax/serve-sim-ax-settings')), serveSimCli: optional(path.join(vendor, 'serve-sim.js')) } })); } finally { releaseHost(); } })().catch(error => { console.error(error.message); process.exitCode = 1; }); diff --git a/apps/server/src/environmentTheme.test.ts b/apps/server/src/environmentTheme.test.ts index 24c20e802bf87..abced88b2e176 100644 --- a/apps/server/src/environmentTheme.test.ts +++ b/apps/server/src/environmentTheme.test.ts @@ -7,6 +7,7 @@ import { import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -57,8 +58,11 @@ const withEnvironmentThemes = ( | Path.Path | Scope.Scope >, - /** Receives each theme and appearance the service makes the environment default. */ - selected: Array<{ readonly theme?: string; readonly appearance?: string }> = [], + options: { + /** Receives each theme and appearance the service makes the environment default. */ + selected?: Array<{ readonly theme?: string; readonly appearance?: string }>; + wrapFileSystem?: (fs: FileSystem.FileSystem) => FileSystem.FileSystem; + } = {}, ) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -85,7 +89,7 @@ const withEnvironmentThemes = ( }), ) : Effect.sync(() => { - selected.push({ + options.selected?.push({ ...(patch.defaultTheme === undefined ? {} : { theme: patch.defaultTheme }), ...(patch.defaultAppearance === undefined ? {} @@ -95,6 +99,7 @@ const withEnvironmentThemes = ( }), }), ), + Layer.provide(Layer.succeed(FileSystem.FileSystem, options.wrapFileSystem?.(fs) ?? fs)), ), ), ); @@ -290,6 +295,208 @@ describe("environment theme", () => { ), ); + it.live.skipIf(!symlinksSupported)( + "publishes later edits after a linked theme directory's grandparent is restored", + () => + withEnvironmentThemes( + { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) }, + Effect.gen(function* () { + const service = yield* EnvironmentTheme.EnvironmentThemeService; + const { environmentThemesDir } = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" }); + const active = path.join(fixture, "active"); + const restored = path.join(fixture, "restored"); + const target = path.join(active, "shared", "themes"); + const restoredTarget = path.join(restored, "shared", "themes"); + for (const directory of [target, restoredTarget]) { + yield* fs.makeDirectory(directory, { recursive: true }); + yield* fs.writeFileString( + path.join(directory, "shared-light.json"), + encodeThemeFile(SHARED_THEME), + ); + } + + const snapshots = yield* service.streamChanges.pipe( + Stream.map((themes) => themes.map((theme) => theme.name)), + Stream.toQueue({ capacity: "unbounded" }), + ); + assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]); + yield* fs.rename(environmentThemesDir, path.join(fixture, "original")); + yield* fs.symlink(target, environmentThemesDir); + assert.deepEqual( + yield* Stream.fromQueue(snapshots).pipe( + Stream.filter((names) => names.length > 0), + Stream.runHead, + Effect.map((names) => names.valueOrUndefined), + ), + ["Shared Light"], + ); + + yield* fs.rename(active, path.join(fixture, "active-previous")); + assert.deepEqual(yield* Queue.take(snapshots), []); + yield* fs.rename(restored, active); + assert.deepEqual(yield* Queue.take(snapshots), ["Shared Light"]); + + yield* fs.writeFileString( + path.join(fixture, "active-previous", "shared", "themes", "nightfall.json"), + encodeThemeFile(NIGHTFALL_THEME), + ); + yield* fs.writeFileString( + path.join(target, "shared-light.json"), + encodeThemeFile({ ...SHARED_THEME, name: "Edited Shared Light" }), + ); + assert.deepEqual(yield* Queue.take(snapshots), ["Edited Shared Light"]); + }), + ), + ); + + it.live.skipIf(!symlinksSupported)( + "publishes themes when a linked theme tree vanishes after listing and returns between probes", + () => + Effect.gen(function* () { + const resumeProbes = yield* Deferred.make(); + let linkedEntry: string | undefined; + let moveAfterListing: Effect.Effect | undefined; + let holdProbes = false; + yield* withEnvironmentThemes( + { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) }, + Effect.gen(function* () { + const service = yield* EnvironmentTheme.EnvironmentThemeService; + const { environmentThemesDir } = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" }); + const active = path.join(fixture, "active"); + const previous = path.join(fixture, "previous"); + const target = path.join(active, "shared", "themes"); + yield* fs.makeDirectory(target, { recursive: true }); + yield* fs.writeFileString( + path.join(target, "shared-light.json"), + encodeThemeFile(SHARED_THEME), + ); + + const snapshots = yield* service.streamChanges.pipe( + Stream.map((themes) => themes.map((theme) => theme.name)), + Stream.toQueue({ capacity: "unbounded" }), + ); + assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]); + linkedEntry = environmentThemesDir; + yield* fs.rename(environmentThemesDir, path.join(fixture, "original")); + yield* fs.symlink(target, environmentThemesDir); + assert.deepEqual( + (yield* Stream.fromQueue(snapshots).pipe( + Stream.filter((names) => names.length > 0), + Stream.runHead, + )).valueOrUndefined, + ["Shared Light"], + ); + + // The next listing succeeds, then the tree moves before its files are opened. + moveAfterListing = Effect.orDie(fs.rename(active, previous)); + holdProbes = true; + yield* fs.writeFileString( + path.join(target, "nightfall.json"), + encodeThemeFile(NIGHTFALL_THEME), + ); + assert.deepEqual(yield* Queue.take(snapshots), []); + yield* fs.rename(previous, active); + yield* Deferred.succeed(resumeProbes, undefined); + assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]); + }), + { + wrapFileSystem: (fs) => + FileSystem.FileSystem.of({ + ...fs, + readDirectory: (directory, options) => + fs.readDirectory(directory, options).pipe( + Effect.tap(() => { + const move = directory === linkedEntry ? moveAfterListing : undefined; + if (move === undefined) return Effect.void; + moveAfterListing = undefined; + return move; + }), + ), + stat: (entry) => + Effect.suspend(() => + entry === linkedEntry && holdProbes + ? Deferred.await(resumeProbes).pipe(Effect.andThen(fs.stat(entry))) + : fs.stat(entry), + ), + }), + }, + ); + }), + ); + + it.live.skipIf(!symlinksSupported)( + "publishes themes when a linked theme directory's original grandparent is restored between probes", + () => + Effect.gen(function* () { + const resumeProbes = yield* Deferred.make(); + let linkedEntry: string | undefined; + let holdProbes = false; + yield* withEnvironmentThemes( + { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) }, + Effect.gen(function* () { + const service = yield* EnvironmentTheme.EnvironmentThemeService; + const { environmentThemesDir } = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" }); + const active = path.join(fixture, "active"); + const previous = path.join(fixture, "previous"); + const target = path.join(active, "shared", "themes"); + yield* fs.makeDirectory(target, { recursive: true }); + yield* fs.writeFileString( + path.join(target, "shared-light.json"), + encodeThemeFile(SHARED_THEME), + ); + + const snapshots = yield* service.streamChanges.pipe( + Stream.map((themes) => themes.map((theme) => theme.name)), + Stream.toQueue({ capacity: "unbounded" }), + ); + assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]); + linkedEntry = environmentThemesDir; + yield* fs.rename(environmentThemesDir, path.join(fixture, "original")); + yield* fs.symlink(target, environmentThemesDir); + assert.deepEqual( + (yield* Stream.fromQueue(snapshots).pipe( + Stream.filter((names) => names.length > 0), + Stream.runHead, + )).valueOrUndefined, + ["Shared Light"], + ); + + holdProbes = true; + yield* fs.rename(active, previous); + yield* fs.writeFileString( + path.join(previous, "shared", "themes", "nightfall.json"), + encodeThemeFile(NIGHTFALL_THEME), + ); + assert.deepEqual(yield* Queue.take(snapshots), []); + yield* fs.rename(previous, active); + yield* Deferred.succeed(resumeProbes, undefined); + assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]); + }), + { + wrapFileSystem: (fs) => + FileSystem.FileSystem.of({ + ...fs, + stat: (entry) => + Effect.suspend(() => + entry === linkedEntry && holdProbes + ? Deferred.await(resumeProbes).pipe(Effect.andThen(fs.stat(entry))) + : fs.stat(entry), + ), + }), + }, + ); + }), + ); + it.effect("skips invalid files while keeping valid ones", () => withEnvironmentThemes( { @@ -431,7 +638,7 @@ describe("environment theme", () => { { appearance: "light" }, ]); }), - selected, + { selected }, ); }); @@ -445,7 +652,7 @@ describe("environment theme", () => { yield* themes.apply({ themeId: "t3-code" }); assert.deepEqual(selected, [{ theme: "agent-look" }, { theme: "" }]); }), - selected, + { selected }, ); }); diff --git a/apps/server/src/environmentTheme.ts b/apps/server/src/environmentTheme.ts index a27adccd1f630..4be3c6aa9f31a 100644 --- a/apps/server/src/environmentTheme.ts +++ b/apps/server/src/environmentTheme.ts @@ -153,7 +153,11 @@ const pathIsTaken = (filePath: string): boolean => { /** Validates and reads one handle; rejects symlinked files, allows symlinked directories. * Uses non-blocking opens against FIFOs; Windows lacks these flags and checks symlinks with lstat. */ -export const readThemeFileGuarded = (filePath: string, maxBytes: number): string | null => { +export const readThemeFileGuarded = ( + filePath: string, + maxBytes: number, + onMissing?: () => void, +): string | null => { let fd: number; try { if (NodeFS.constants.O_NOFOLLOW === undefined && NodeFS.lstatSync(filePath).isSymbolicLink()) { @@ -165,7 +169,8 @@ export const readThemeFileGuarded = (filePath: string, maxBytes: number): string (NodeFS.constants.O_NOFOLLOW ?? 0) | (NodeFS.constants.O_NONBLOCK ?? 0), ); - } catch { + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") onMissing?.(); return null; } try { @@ -216,11 +221,19 @@ export function findThemeBackground( return null; } -export const readPublishedThemes = Effect.fn(function* (themesDir: string) { +export const readPublishedThemes = Effect.fn(function* ( + themesDir: string, + /** Runs when the directory or a file it listed is gone, as when an ancestor moves mid-read. */ + onPathMissing: Effect.Effect = Effect.void, +) { const fs = yield* FileSystem.FileSystem; - const entries = yield* fs - .readDirectory(themesDir) - .pipe(Effect.orElseSucceed((): Array => [])); + const entries = yield* Effect.catch(fs.readDirectory(themesDir), (error) => + Effect.as(error.reason._tag === "NotFound" ? onPathMissing : Effect.void, []), + ); + let listedFileMissing = false; + const markListedFileMissing = () => { + listedFileMissing = true; + }; const themes: Array = []; const entryNames = new Set(entries); @@ -243,7 +256,7 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) { } const filePath = `${themesDir}/${entry}`; - const raw = readThemeFileGuarded(filePath, MAX_THEME_FILE_BYTES); + const raw = readThemeFileGuarded(filePath, MAX_THEME_FILE_BYTES, markListedFileMissing); if (raw === null) { yield* Effect.logWarning("ignoring unusable environment theme file", { path: filePath, @@ -279,6 +292,7 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) { const background = findThemeBackground(themesDir, id, entryNames); themes.push({ id, ...file, ...(background ? { background: background.revision } : {}) }); } + if (listedFileMissing) yield* onPathMissing; return themes; }); @@ -289,6 +303,7 @@ const make = Effect.gen(function* () { // Sequence numbers let subscribers drop queued events older than their initial snapshot. const changes = yield* PubSub.sliding(1); const published = yield* Ref.make({ seq: 0, themes: [] }); + const pathMissing = yield* Ref.make(false); // Serialize read/compare/publish so slow older reads cannot publish with newer sequence numbers. const refreshSemaphore = yield* Semaphore.make(1); const watcherScope = yield* Scope.make("sequential"); @@ -296,9 +311,10 @@ const make = Effect.gen(function* () { const refresh = refreshSemaphore.withPermits(1)( Effect.gen(function* () { - const themes = yield* readPublishedThemes(environmentThemesDir).pipe( - Effect.provideService(FileSystem.FileSystem, fs), - ); + const themes = yield* readPublishedThemes( + environmentThemesDir, + Ref.set(pathMissing, true), + ).pipe(Effect.provideService(FileSystem.FileSystem, fs)); // Compare the whole value so new fields cannot silently miss republishes. const [changed, next] = yield* Ref.modify( published, @@ -338,6 +354,7 @@ const make = Effect.gen(function* () { const watchEvents = watchDirectoryPath( environmentThemesDir, watchDirectory(environmentThemesDir), + Ref.getAndSet(pathMissing, false), ).pipe( // A save emits several events, and fs.watch can fire before content is flushed. Stream.debounce(Duration.millis(100)), diff --git a/apps/server/src/feedback/FeedbackService.test.ts b/apps/server/src/feedback/FeedbackService.test.ts index cdc7a7984e6f7..be632b62c5fc2 100644 --- a/apps/server/src/feedback/FeedbackService.test.ts +++ b/apps/server/src/feedback/FeedbackService.test.ts @@ -314,6 +314,7 @@ const harness = Effect.gen(function* () { { instanceId, driver: "codex", + auth: { status: "authenticated" }, models: [{ slug: "gpt-5.5", isCustom: false }], } as unknown as ServerProvider, ]), diff --git a/apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts b/apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts index aca3ec1a92f87..dfcdb88cee947 100644 --- a/apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts +++ b/apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts @@ -175,7 +175,8 @@ const runCreated = ( activeAttemptId: threadId === sourceId ? attemptId : null, status, requestedAt: now, - startedAt: now, + // A cancelled run here is a queued turn that never started. + startedAt: status === "cancelled" ? null : now, completedAt: status === "completed" ? now : null, checkpointId: null, contextHandoffId: null, diff --git a/apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts b/apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts index c802c01940407..e9e73c6101643 100644 --- a/apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts +++ b/apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts @@ -45,6 +45,7 @@ import * as ThreadCommandExecutor from "../../orchestration-v2/ThreadCommandExec import * as SqlitePersistence from "../../persistence/Sqlite.ts"; import * as PortScanner from "../../preview/PortScanner.ts"; import * as ProjectService from "../../project/ProjectService.ts"; +import * as ProjectSetupScriptRunner from "../../project/ProjectSetupScriptRunner.ts"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; import * as ModelManifest from "../../provider/ModelManifest.ts"; import * as ProviderInstanceRegistry from "../../provider/ProviderInstanceRegistry.ts"; @@ -55,8 +56,12 @@ import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../../vcs/VcsProcess.ts"; import * as FyiDelivery from "./FyiDelivery.ts"; -const layerPlatformTest = Layer.merge( - Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), +const layerPlatformTest = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ + runForThread: () => Effect.succeed({ status: "no-script" }), + }), Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ resolveLink: () => Effect.die("unused title link"), }), diff --git a/apps/server/src/fork/shownHistory/ShownHistory.test.ts b/apps/server/src/fork/shownHistory/ShownHistory.test.ts index 4686c5ab2a43b..28e6f9b2e75e4 100644 --- a/apps/server/src/fork/shownHistory/ShownHistory.test.ts +++ b/apps/server/src/fork/shownHistory/ShownHistory.test.ts @@ -92,6 +92,7 @@ const LARGE = ThreadId.make("thread:shown:large"); const REWRITES = ThreadId.make("thread:shown:rewrites"); const HUGE = ThreadId.make("thread:shown:huge"); const SPLIT = ThreadId.make("thread:shown:split"); +const CANCELLED = ThreadId.make("thread:shown:cancelled"); const runIdOf = (threadId: ThreadId, run: number) => RunId.make(`run:${threadId}:${run}`); const nodeIdOf = (threadId: ThreadId, run: number) => NodeId.make(`node:${threadId}:${run}`); @@ -145,7 +146,8 @@ function threadCreated( function runEvent( threadId: ThreadId, run: number, - status: "completed" | "failed" | "rolled_back" = "completed", + status: "completed" | "failed" | "rolled_back" | "cancelled" = "completed", + started = true, ): OrchestrationV2DomainEvent { const runId = runIdOf(threadId, run); return { @@ -168,7 +170,7 @@ function runEvent( activeAttemptId: null, status, requestedAt: at, - startedAt: at, + startedAt: started ? at : null, completedAt: at, checkpointId: null, contextHandoffId: null, @@ -664,6 +666,23 @@ const CHILDREN = [ ["a child whose shown rows end on a batch boundary", CHILD_EDGE, 16, 8, PARENT], ] as const; +const queuedMessage = (threadId: ThreadId, run: number, text: string): OrchestrationV2TurnItem => ({ + ...base(threadId, run, 1), + ...TYPED, + type: "user_message", + messageId: messageIdOf(threadId, run, 1), + inputIntent: "queued_turn", + text, + attachments: [], +}); +/** Run 2 started and a restart then cancelled it; run 3 was cancelled before it started. */ +const cancelledThread = () => [ + userMessage(CANCELLED, 1, 1, "Fix the build."), + send(CANCELLED, 1, 2, "On it."), + queuedMessage(CANCELLED, 2, "Also check the logs."), + queuedMessage(CANCELLED, 3, "Never mind this."), +]; + const runsOf = (items: ReadonlyArray) => [ ...new Set(items.map((item) => Number(String(item.runId).split(":").at(-1)))), ]; @@ -694,6 +713,7 @@ const seed = Effect.gen(function* () { [REWRITES, rewritesThread(), threadCreated(REWRITES)], [HUGE, hugeThread(), threadCreated(HUGE)], [SPLIT, splitThread(), threadCreated(SPLIT)], + [CANCELLED, cancelledThread(), threadCreated(CANCELLED)], ]; for (const [threadId, items, created] of threads) { yield* projections.apply(created); @@ -702,6 +722,8 @@ const seed = Effect.gen(function* () { } yield* projections.apply(runEvent(PARENT, ROLLED_BACK_RUN, "rolled_back")); yield* projections.apply(runEvent(GUARD, 3, "failed")); + yield* projections.apply(runEvent(CANCELLED, 2, "cancelled")); + yield* projections.apply(runEvent(CANCELLED, 3, "cancelled", false)); for (const run of range(1, 3)) yield* projections.apply(runEvent(QUIET, run, "failed")); yield* projections.apply({ id: EventId.make("event:shown:question"), @@ -1226,6 +1248,22 @@ it.layer(TestLayer)("shown-only history", (it) => { assert.isTrue(page.items.some((row) => !isShownItem(row.item))); }), ); + it.effect("shows a queued message whose cancelled run had started, as Normal does", () => + Effect.gen(function* () { + const normal = visibleIds( + boundedSnapshotProjection( + yield* firstSnapshot({ threadId: CANCELLED, acceptBoundedSnapshot: true }), + ), + ); + const shown = visibleIds(boundedSnapshotProjection(yield* shownSnapshot(CANCELLED))); + const delivered = String(itemIdOf(CANCELLED, 2, 1)); + const held = String(itemIdOf(CANCELLED, 3, 1)); + assert.include(normal, delivered); + assert.notInclude(normal, held); + assert.include(shown, delivered); + assert.notInclude(shown, held); + }), + ); }); function runOrdinalOf(item: Pick): number { diff --git a/apps/server/src/fork/shownHistory/ShownHistory.ts b/apps/server/src/fork/shownHistory/ShownHistory.ts index 77d0868ad4d90..ccd207018982d 100644 --- a/apps/server/src/fork/shownHistory/ShownHistory.ts +++ b/apps/server/src/fork/shownHistory/ShownHistory.ts @@ -201,7 +201,8 @@ const segmentVisible = (sql: SqlClient.SqlClient, segment: ShownSegment) => ? sql`(run.status IS NULL OR run.status <> 'rolled_back') AND NOT (item.type = 'user_message' AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn' - AND run.status IS 'cancelled')` + AND run.status IS 'cancelled' + AND json_extract(run.payload_json, '$.startedAt') IS NULL)` : sql`(run.ordinal <= ${segment.inherited.runOrdinal} OR (item.run_id IS NULL AND ${segment.inherited.runlessRows ? 1 : 0} = 1))`; diff --git a/apps/server/src/fork/steerRestartCheckpoint/steerRestartCheckpoint.integration.test.ts b/apps/server/src/fork/steerRestartCheckpoint/steerRestartCheckpoint.integration.test.ts new file mode 100644 index 0000000000000..9fbcaabbfd218 --- /dev/null +++ b/apps/server/src/fork/steerRestartCheckpoint/steerRestartCheckpoint.integration.test.ts @@ -0,0 +1,346 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + ThreadId, +} from "@t3tools/contracts"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { CodexProviderCapabilitiesV2 } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EffectWorker from "../../orchestration-v2/EffectWorker.ts"; +import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; +import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as ThreadCommandExecutor from "../../orchestration-v2/ThreadCommandExecutor.ts"; + +const driver = ProviderDriverKind.make("codex"); +const instanceId = ProviderInstanceId.make("codex"); +const runSelection = { + instanceId, + model: "test-model", + options: [{ id: "effort", value: "xhigh" }], +}; +const composerSelection = { + ...runSelection, + options: [...runSelection.options, { id: "fastMode", value: false }], +}; + +// A provider that steers by interrupt-restart; the steer waits in planSelectionTransition. +const steerRestartHarness = Effect.fn("steerRestartHarness")(function* ( + name: string, + beforeSelectionTransition: Effect.Effect, +) { + const cwd = yield* checkpointWorkspace(name); + const events = yield* Queue.unbounded(); + const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = []; + const capabilities = { + ...CodexProviderCapabilitiesV2, + turns: { + ...CodexProviderCapabilitiesV2.turns, + supportsActiveSteering: false, + supportsSteeringByInterruptRestart: true, + }, + }; + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(capabilities), + planSelectionTransition: () => + beforeSelectionTransition.pipe(Effect.as({ type: "apply_on_next_turn" as const })), + openSession: (input) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const turnUpdated = ( + turn: ProviderAdapter.ProviderAdapterV2TurnInput, + status: "running" | "interrupted", + ) => + Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: { driver, nativeId: `native:${turn.attemptId}`, strength: "strong" }, + ordinal: turn.providerTurnOrdinal, + status, + startedAt: now, + completedAt: status === "running" ? null : now, + }, + }); + const startTurn = (turn: ProviderAdapter.ProviderAdapterV2TurnInput) => + Effect.gen(function* () { + started.push(turn); + yield* turnUpdated(turn, "running"); + }); + return { + instanceId, + driver, + providerSessionId: input.providerSessionId, + providerSession: { + id: input.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: runSelection.model, + capabilities, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: input.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn, + compactThread: startTurn, + steerTurn: () => Effect.die("unused"), + interruptTurn: ({ providerTurnId }) => + Effect.forEach( + started.filter( + (turn) => ProviderTurnId.make(`provider-turn:${turn.attemptId}`) === providerTurnId, + ), + (turn) => + turnUpdated(turn, "interrupted").pipe( + Effect.andThen( + Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThread.id, + providerTurnId, + runOrdinal: turn.runOrdinal, + status: "interrupted", + failure: null, + threadDisposition: "reusable", + }), + ), + ), + { discard: true }, + ), + respondToRuntimeRequest: () => Effect.void, + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + const layer = ProviderReplayHarness.layerWithRegistry( + { name }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { runEffectWorker: false }, + ); + const startFirstTurn = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make(`thread:${name}`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make(`project:${name}`), + title: "Steer restart at turn end", + modelSelection: runSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const running = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("first"), + threadId, + messageId: MessageId.make("message:first"), + text: "first", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(running); + yield* (yield* ThreadCommandExecutor.ThreadCommandExecutor).withLock(threadId, Effect.void); + return threadId; + }); + return { cwd, events, started, layer, startFirstTurn }; +}); + +it.effect.each(["completed", "interrupted", "stopped before it starts"] as const)( + "checkpoints a run whose turn ended while a steer restarted it (restart %s)", + (restartEnd) => + Effect.gen(function* () { + const steerReadRunning = yield* Deferred.make(); + const letSteerCommit = yield* Deferred.make(); + const { cwd, events, started, layer, startFirstTurn } = yield* steerRestartHarness( + `steer-restart-after-turn-end-${restartEnd}`, + Deferred.succeed(steerReadRunning, undefined).pipe( + Effect.andThen(Deferred.await(letSteerCommit)), + ), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const runId = started[0]!.runId; + const endTurn = ( + turn: ProviderAdapter.ProviderAdapterV2TurnInput, + status: "completed" | "interrupted", + ) => + Effect.gen(function* () { + const providerTurn = (yield* orchestrator.getThreadProjection( + threadId, + )).providerTurns.find((candidate) => candidate.runAttemptId === turn.attemptId)!; + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === runId && + event.payload.status === status, + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...providerTurn, status, completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: providerTurn.providerThreadId, + providerTurnId: providerTurn.id, + runOrdinal: turn.runOrdinal, + status, + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + }); + const writeWorkspaceFile = (name: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.writeFileString(`${cwd}/${name}`, `${name}\n`); + }).pipe(Effect.provide(NodeServices.layer), Effect.orDie); + // The first turn's capture finds the run restarting and retries with backoff. + const drainWithRetries = Effect.forEach( + [1, 2, 3, 4, 5], + () => TestClock.adjust("1 second").pipe(Effect.andThen(worker.drain())), + { discard: true }, + ); + const checkpointFiles = Effect.gen(function* () { + const projection = yield* orchestrator.getThreadProjection(threadId); + const run = projection.runs.find((candidate) => candidate.id === runId); + const checkpoint = projection.checkpoints.find( + (candidate) => candidate.id === run?.checkpointId, + ); + assert.equal(checkpoint?.status, "ready"); + return { status: run?.status, files: checkpoint?.files.map((file) => file.path) }; + }); + + // The steer reads the run as running, then the turn ends before it commits its restart. + const steer = yield* orchestrator + .dispatch({ + type: "message.dispatch", + commandId: CommandId.make("steer-at-turn-end"), + threadId, + messageId: MessageId.make("message:steer-at-turn-end"), + text: "also check the logs", + attachments: [], + modelSelection: composerSelection, + dispatchMode: { type: "steer_active", targetRunId: runId }, + createdBy: "agent", + creationSource: "mcp", + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(steerReadRunning); + yield* writeWorkspaceFile("first-attempt.txt"); + yield* endTurn(started[0]!, "completed"); + yield* Deferred.succeed(letSteerCommit, undefined); + yield* Fiber.join(steer); + + if (restartEnd === "stopped before it starts") { + yield* worker.runOnce(); + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("stop-before-restart-starts"), + threadId, + }); + yield* drainWithRetries; + assert.equal(started.length, 1); + const { status, files } = yield* checkpointFiles; + assert.equal(status, "interrupted"); + assert.include(files ?? [], "first-attempt.txt"); + return; + } + + const restartRunning = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "provider-turn.updated" && + event.payload.status === "running" && + event.payload.runAttemptId !== started[0]!.attemptId, + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* drainWithRetries; + yield* Fiber.join(restartRunning); + yield* (yield* ThreadCommandExecutor.ThreadCommandExecutor).withLock(threadId, Effect.void); + assert.equal(started.length, 2); + assert.equal(started[1]!.runId, runId); + + yield* writeWorkspaceFile("restarted-attempt.txt"); + yield* endTurn(started[1]!, restartEnd); + yield* worker.drain(); + const { status, files } = yield* checkpointFiles; + assert.equal(status, restartEnd); + assert.includeMembers(files ?? [], ["first-attempt.txt", "restarted-attempt.txt"]); + }).pipe(Effect.provide(layer)); + }), +); diff --git a/apps/server/src/fork/subThreads/SubThreads.ts b/apps/server/src/fork/subThreads/SubThreads.ts index 593c8030e06e8..2ca38551f4849 100644 --- a/apps/server/src/fork/subThreads/SubThreads.ts +++ b/apps/server/src/fork/subThreads/SubThreads.ts @@ -256,7 +256,12 @@ export const layerFromServices = Layer.effect( ${userTypedSql(sql)} AND (run.status IS NULL OR run.status <> 'rolled_back') AND NOT ( - COALESCE(run.status IN ('queued', 'cancelled'), 0) + COALESCE( + run.status = 'queued' OR ( + run.status = 'cancelled' AND json_extract(run.payload_json, '$.startedAt') IS NULL + ), + 0 + ) AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn' ) `; diff --git a/apps/server/src/fork/userMessageTools/SendToUser.test.ts b/apps/server/src/fork/userMessageTools/SendToUser.test.ts index 8add053fdf87e..f7afb57b7c349 100644 --- a/apps/server/src/fork/userMessageTools/SendToUser.test.ts +++ b/apps/server/src/fork/userMessageTools/SendToUser.test.ts @@ -9,7 +9,8 @@ import { TurnItemId, } from "@t3tools/contracts"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; -import { shortId } from "@t3tools/shared/displayModes"; +import { displayEventFromTurnItem, shortId } from "@t3tools/shared/displayModes"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -456,3 +457,41 @@ describe("replace_send_to_user", () => { }).pipe(Effect.provide(layer)), ); }); + +// A provider that drops MCP outputs gets each send's result back from the capture by its input. +describe("Chat sends through the MCP result capture", () => { + const captureLayer = layer.pipe(Layer.provideMerge(McpProviderSessions.layer)); + const reply = { + text: "Fixed the build.", + reply_to: shortId("u1"), + user_message: "Fix the build.", + }; + const recoveredEvent = Effect.gen(function* () { + const sessions = yield* McpProviderSessions.McpProviderSessions; + const output = yield* sessions.takeToolResult(chatThread, "send_to_user", reply); + return displayEventFromTurnItem({ + ...base("recovered"), + type: "dynamic_tool", + toolName: "mcp__t3-code__send_to_user", + input: reply, + output, + } as never)?.type; + }); + + it.effect("keeps a reply shown when an identical later send was refused", () => + Effect.gen(function* () { + history = [typed("u1", "Fix the build.")]; + expect((yield* answerU1(reply.text)).isError).not.toBe(true); + expect((yield* answerU1(reply.text)).isError).toBe(true); + expect(yield* recoveredEvent).toBe("sent"); + }).pipe(Effect.provide(Layer.fresh(captureLayer))), + ); + + it.effect("shows a lone reply", () => + Effect.gen(function* () { + history = [typed("u1", "Fix the build.")]; + expect((yield* answerU1(reply.text)).isError).not.toBe(true); + expect(yield* recoveredEvent).toBe("sent"); + }).pipe(Effect.provide(Layer.fresh(captureLayer))), + ); +}); diff --git a/apps/server/src/fork/userMessageTools/SendToUser.ts b/apps/server/src/fork/userMessageTools/SendToUser.ts index 185d2f1f019a5..f45aa34c72cea 100644 --- a/apps/server/src/fork/userMessageTools/SendToUser.ts +++ b/apps/server/src/fork/userMessageTools/SendToUser.ts @@ -191,6 +191,13 @@ const ReplaceSendToUserTool = Tool.make(REPLACE_SEND_TO_USER_TOOL_NAME, { export const SendToUserToolkit = Toolkit.make(SendToUserTool, ReplaceSendToUserTool); +// A Chat-mode success keeps no field the MCP result capture reads. Its empty record stops an +// identical refused call's error from passing for it when a provider drops both outputs. +export const capturedSuccessFallback = (toolName: string): Record | undefined => + toolName === SEND_TO_USER_TOOL_NAME || toolName === REPLACE_SEND_TO_USER_TOOL_NAME + ? {} + : undefined; + /** The items stored before the calling tool use, when the provider names it; else all of them. */ function itemsBefore(shown: ReadonlyArray, ownItem: string | undefined) { const ownAt = diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 6b32a9ab5bf9e..d26e3752a3348 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -32,6 +32,7 @@ import type { GitPreparePullRequestThreadInput, ModelSelection, ServerSettings as ServerSettingsValue, + ServerProvider, } from "@t3tools/contracts"; import { @@ -651,6 +652,7 @@ function makeManager(input?: { pullRequests?: Partial; sourceControlProvider?: SourceControlProvider["Service"]; textGeneration?: Partial; + providers?: ReadonlyArray; serverSettings?: Parameters[0]; setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]; settingsChanges?: PubSub.PubSub; @@ -784,7 +786,7 @@ function makeManager(input?: { Layer.succeed(TextGeneration.TextGeneration, textGeneration), Layer.mock(PullRequestService.PullRequestService)(input?.pullRequests ?? {}), Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([]), + getProviders: Effect.succeed(input?.providers ?? []), }), Layer.succeed( ProjectSetupScriptRunner.ProjectSetupScriptRunner, @@ -4933,6 +4935,273 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + const claudeWorkProvider: ServerProvider = { + instanceId: ProviderInstanceId.make("claude_work"), + driver: ProviderDriverKind.make("claudeAgent"), + displayName: "Work account", + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-09-27T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + }; + + const seedPrThread = Effect.fnUntraced(function* (input: { + readonly threadId: ThreadId; + readonly worktreePath: string; + readonly forkedFrom?: { readonly threadId: ThreadId; readonly runId: RunId }; + readonly runs: ReadonlyArray<{ + readonly modelSelection: ModelSelection; + readonly text: string; + readonly status?: "rolled_back"; + }>; + }) { + const store = yield* ProjectionStore.ProjectionStoreV2; + const { threadId } = input; + const createdAt = DateTime.makeUnsafe("2026-09-27T00:00:00.000Z"); + const modelSelection = input.runs[0]!.modelSelection; + yield* store.apply({ + id: EventId.make(`event:${threadId}:thread`), + type: "thread.created", + threadId, + providerInstanceId: modelSelection.instanceId, + occurredAt: createdAt, + payload: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project:pr-thread-model"), + title: "PR thread model", + providerInstanceId: modelSelection.instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: input.worktreePath, + activeProviderThreadId: null, + lineage: input.forkedFrom + ? { + parentThreadId: input.forkedFrom.threadId, + relationshipToParent: "fork", + rootThreadId: input.forkedFrom.threadId, + } + : { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: input.forkedFrom ? { type: "run", ...input.forkedFrom } : null, + createdAt, + updatedAt: createdAt, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }); + for (const [index, spec] of input.runs.entries()) { + const ordinal = index + 1; + const runId = RunId.make(`run:${threadId}:${ordinal}`); + const messageId = MessageId.make(`message:${threadId}:${ordinal}`); + yield* store.apply({ + id: EventId.make(`event:${threadId}:run:${ordinal}`), + type: "run.updated", + threadId, + runId, + occurredAt: createdAt, + payload: { + id: runId, + threadId, + ordinal, + providerInstanceId: spec.modelSelection.instanceId, + modelSelection: spec.modelSelection, + providerThreadId: null, + userMessageId: messageId, + rootNodeId: null, + activeAttemptId: null, + status: spec.status ?? "completed", + requestedAt: createdAt, + startedAt: createdAt, + completedAt: createdAt, + checkpointId: null, + contextHandoffId: null, + }, + }); + yield* store.apply({ + id: EventId.make(`event:${threadId}:item:${ordinal}`), + type: "turn-item.updated", + threadId, + runId, + occurredAt: createdAt, + payload: { + id: TurnItemId.make(`item:${threadId}:${ordinal}`), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: null, + startedAt: createdAt, + completedAt: createdAt, + updatedAt: createdAt, + type: "user_message", + messageId, + createdBy: "user", + creationSource: "web", + inputIntent: "turn_start", + text: spec.text, + attachments: [], + }, + }); + } + }); + + const createPrPrompt = Effect.fnUntraced(function* ( + seed: ( + worktreePath: string, + ) => Effect.Effect< + void, + ProjectionStore.ProjectionStoreV2Error, + ProjectionStore.ProjectionStoreV2 + >, + threadId: ThreadId, + ) { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/thread-model"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "thread-model.txt"), "model\n"); + yield* runGit(repoDir, ["add", "thread-model.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Thread model"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + let generatedPrompt = ""; + const writer = fromRunner("test", (request) => { + generatedPrompt = request.prompt; + return decodeJsonReply(request, "test", '{"title":"Thread model","body":"Body"}'); + }); + const { manager } = yield* makeManager({ + serverSettings: { + textGenerationModelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-6.1-terra", + }, + }, + textGeneration: { generatePrContent: writer.generatePrContent }, + providers: [claudeWorkProvider], + seed: seed(repoDir), + }); + yield* manager.runStackedAction({ + actionId: "test-action-id", + cwd: repoDir, + action: "create_pr", + threadId, + }); + return generatedPrompt; + }); + + it.effect("create_pr tells the writer which model and harness made the change", () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread:pr-thread-model"); + const instanceId = claudeWorkProvider.instanceId; + const prompt = yield* createPrPrompt( + (worktreePath) => + seedPrThread({ + threadId, + worktreePath, + runs: [ + { + modelSelection: { instanceId, model: "claude-opus-5-5" }, + text: "Add the thread model file", + }, + { + modelSelection: { instanceId, model: "claude-haiku-5-5" }, + text: "Undo that", + status: "rolled_back", + }, + { + modelSelection: { + instanceId: ProviderInstanceId.make("claude_removed"), + model: "claude-sonnet-5-5", + }, + text: "Polish the file", + }, + ], + }), + threadId, + ); + + expect(prompt).toContain("Add the thread model file"); + expect(prompt).toContain('- model "claude-opus-5-5", harness Claude\n'); + expect(prompt).toContain('- model "claude-sonnet-5-5", harness unknown\n'); + expect(prompt).not.toContain("Work account"); + expect(prompt).not.toContain("claude_removed"); + expect(prompt).not.toContain("claude-haiku-5-5"); + }), + ); + + it.effect("create_pr credits the models a fork inherited its history from", () => + Effect.gen(function* () { + const sourceThreadId = ThreadId.make("thread:pr-fork-source"); + const forkThreadId = ThreadId.make("thread:pr-fork"); + const prompt = yield* createPrPrompt( + (worktreePath) => + Effect.gen(function* () { + yield* seedPrThread({ + threadId: sourceThreadId, + worktreePath, + runs: [ + { + modelSelection: { + instanceId: claudeWorkProvider.instanceId, + model: "claude-opus-5-5", + }, + text: "Implement the thread model file", + }, + ], + }); + yield* seedPrThread({ + threadId: forkThreadId, + worktreePath, + forkedFrom: { + threadId: sourceThreadId, + runId: RunId.make(`run:${sourceThreadId}:1`), + }, + runs: [ + { + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-6.2", + }, + text: "Review the change", + }, + ], + }); + // Rolling the source back afterwards leaves the work the fork inherited in place. + const store = yield* ProjectionStore.ProjectionStoreV2; + const [sourceRun] = (yield* store.getThreadRecords(sourceThreadId, ["runs"])).runs; + yield* store.apply({ + id: EventId.make(`event:${sourceThreadId}:rollback`), + type: "run.updated", + threadId: sourceThreadId, + runId: sourceRun!.id, + occurredAt: sourceRun!.requestedAt, + payload: { ...sourceRun!, status: "rolled_back" }, + }); + }), + forkThreadId, + ); + + expect(prompt).toContain("Implement the thread model file"); + expect(prompt).toContain('- model "claude-opus-5-5", harness Claude\n'); + expect(prompt).toContain('- model "gpt-6.2", harness Codex\n'); + }), + ); + it.effect.each(["commit", "short-commit", "tag", "revision"] as const)( "creates a PR against the default branch with a legacy %s base setting", (kind) => diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 11466ba34f300..8be7817ac69da 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -38,6 +38,8 @@ import { ModelSelection, type OrchestrationV2TurnItem, type ProjectId, + PROVIDER_DISPLAY_NAMES, + ProviderDriverKind, SourceControlProviderError, type SourceControlWritingStyleSettings, type ThreadId, @@ -67,7 +69,11 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; -import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts"; +import { + GitManagerError, + GitPullRequestMaterializationError, + trimAsciiWhitespace, +} from "@t3tools/contracts"; import { historicalMessage, renderHistory, @@ -239,6 +245,7 @@ const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15); // cannot fill the git and forge process slots that foreground work also needs. const BRANCH_PR_LOOKUP_CONCURRENCY = 4; const PR_THREAD_CONTEXT_BYTES = 16_000; +const NO_THREAD_CONTEXT = { history: undefined, producedBy: undefined }; const PR_THREAD_COMMAND_OUTPUT_CHARS = 2_000; const isSourceControlProviderError = Schema.is(SourceControlProviderError); @@ -284,7 +291,7 @@ const prLookupGitReads = Context.Reference( function parseRemoteNames(stdout: string): ReadonlyArray { return stdout .split("\n") - .map((name) => name.trim()) + .map(trimAsciiWhitespace) .filter((name) => name.length > 0); } @@ -844,8 +851,8 @@ export const make = Effect.gen(function* () { }); const readThreadContext = Effect.fnUntraced( function* (threadId: ThreadId | undefined) { - if (threadId === undefined) return undefined; - const { visibleTurnItems } = yield* threads.getThreadProjection(threadId); + if (threadId === undefined) return NO_THREAD_CONTEXT; + const { thread, runs, visibleTurnItems } = yield* threads.getThreadProjection(threadId); const selected = selectHistory({ messages: visibleTurnItems.flatMap( ({ item }) => historicalMessage(limitCommandOutput(item)) ?? [], @@ -853,9 +860,47 @@ export const make = Effect.gen(function* () { coverage: "Digest of the thread that made this change, oldest first.", budget: PR_THREAD_CONTEXT_BYTES, }); - return selected.messages.length === 0 - ? undefined - : renderHistory(selected.messages, selected.context); + // A thread can switch models mid-way, and a fork inherits its ancestors' history; credit + // every model behind a turn still visible here. Ancestor runs are best-effort. + const visibleRunIds = new Set(visibleTurnItems.flatMap(({ item }) => item.runId ?? [])); + const ancestorRuns = yield* Effect.forEach( + new Set( + visibleTurnItems.flatMap(({ item }) => (item.threadId === threadId ? [] : item.threadId)), + ), + (ancestorId) => + threads.getThreadRecords(ancestorId, ["runs"]).pipe( + Effect.map((records) => records.runs), + Effect.orElseSucceed(() => []), + ), + ); + // Visibility already hides local rollbacks; an ancestor's later rollback leaves the fork's + // inherited work in place. A queued run shows its message before it starts. + const runSelections = [...runs, ...ancestorRuns.flat()] + .filter((run) => visibleRunIds.has(run.id) && run.startedAt !== null) + .map((run) => run.modelSelection); + const providers = yield* providerRegistry.getProviders; + const producedBy = Arr.dedupeWith( + (runSelections.length > 0 ? runSelections : [thread.modelSelection]).map( + ({ instanceId, model }) => { + // The instance's displayName is a user label (often an account), not the harness. + // Default instances are named after their driver; a removed custom one names nothing. + const harness = + PROVIDER_DISPLAY_NAMES[ + providers.find((provider) => provider.instanceId === instanceId)?.driver ?? + ProviderDriverKind.make(instanceId) + ]; + return harness === undefined ? { model } : { model, harness }; + }, + ), + (left, right) => left.model === right.model && left.harness === right.harness, + ); + return { + producedBy, + history: + selected.messages.length === 0 + ? undefined + : renderHistory(selected.messages, selected.context), + }; }, (effect, threadId) => effect.pipe( @@ -863,7 +908,7 @@ export const make = Effect.gen(function* () { Effect.logWarning("GitManager.readThreadContext failed", { threadId, errorTag: error._tag, - }).pipe(Effect.as(undefined)), + }).pipe(Effect.as(NO_THREAD_CONTEXT)), ), ), ); @@ -2025,7 +2070,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, })).stdout .split("\n") - .map((ref) => ref.trim()) + .map(trimAsciiWhitespace) .filter((ref) => ref.length > 0), ); const matching = remoteNames.filter((name) => refs.has(`refs/remotes/${name}/${branch}`)); @@ -2062,7 +2107,7 @@ export const make = Effect.gen(function* () { const oidByRef = new Map( refs.stdout .split("\n") - .map((line) => line.trim().split("\u0000")) + .map((line) => trimAsciiWhitespace(line).split("\u0000")) .filter((entry): entry is [string, string] => entry.length === 2), ); const localOid = oidByRef.get(localRef); @@ -2882,7 +2927,7 @@ export const make = Effect.gen(function* () { yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }), ) : undefined; - const threadContext = yield* readThreadContext(threadId); + const { history: threadContext, producedBy } = yield* readThreadContext(threadId); return yield* textGeneration.generatePrContent({ cwd, @@ -2893,6 +2938,7 @@ export const make = Effect.gen(function* () { diffPatch: limitContext(rangeContext.diffPatch, 60_000), ...(changeRequestTemplate ? { changeRequestTemplate } : {}), ...(threadContext ? { threadContext } : {}), + producedBy, ...(policy ? { policy } : {}), modelSelection: settings.modelSelection, projectId: settings.projectId, @@ -3367,7 +3413,7 @@ export const make = Effect.gen(function* () { const refNames = new Set( trackingRefs.stdout .split("\n") - .map((remoteRef) => remoteRef.trim()) + .map(trimAsciiWhitespace) .filter((remoteRef) => remoteRef.length > 0), ); return remoteNames diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 4cf3e62d9a93f..ca7c0b03c13d4 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -29,6 +29,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; +import { trimAsciiWhitespace } from "@t3tools/contracts"; import * as GitManager from "./GitManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; @@ -365,7 +366,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, }); if (result.exitCode === 0) { - return result.stdout.trim().replace(/^refs\/heads\//, "") || null; + return trimAsciiWhitespace(result.stdout).replace(/^refs\/heads\//, "") || null; } if (result.exitCode === 1) return null; return yield* new GitCommandError({ diff --git a/apps/server/src/git/remoteRefs.ts b/apps/server/src/git/remoteRefs.ts index e3873effe475e..c5be08c165676 100644 --- a/apps/server/src/git/remoteRefs.ts +++ b/apps/server/src/git/remoteRefs.ts @@ -1,7 +1,9 @@ +import { trimAsciiWhitespace } from "@t3tools/contracts"; + export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray { const remoteNames: Array = []; for (const line of stdout.split("\n")) { - const remoteName = line.trim(); + const remoteName = trimAsciiWhitespace(line); if (remoteName.length > 0) { remoteNames.push(remoteName); } @@ -17,7 +19,7 @@ export function parseRemoteRefWithRemoteNames( ref: string, remoteNames: ReadonlyArray, ): { remoteRef: string; remoteName: string; branchName: string } | null { - const trimmedRef = ref.trim(); + const trimmedRef = trimAsciiWhitespace(ref); if (trimmedRef.length === 0) { return null; } @@ -27,7 +29,7 @@ export function parseRemoteRefWithRemoteNames( if (!trimmedRef.startsWith(remotePrefix)) { continue; } - const branchName = trimmedRef.slice(remotePrefix.length).trim(); + const branchName = trimmedRef.slice(remotePrefix.length); if (branchName.length === 0) { return null; } @@ -48,7 +50,7 @@ export function extractBranchNameFromRemoteRef( remoteNames?: ReadonlyArray; }, ): string { - const normalized = ref.trim(); + const normalized = trimAsciiWhitespace(ref); if (normalized.length === 0) { return ""; } @@ -67,5 +69,5 @@ export function extractBranchNameFromRemoteRef( if (firstSlash === -1) { return normalized; } - return normalized.slice(firstSlash + 1).trim(); + return normalized.slice(firstSlash + 1); } diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.ts index 363c9d84d4e2c..cb68cece707d8 100644 --- a/apps/server/src/guest/GuestShareService.test.ts +++ b/apps/server/src/guest/GuestShareService.test.ts @@ -546,6 +546,52 @@ it.effect("gives the guest a command's detail and output, but no file diffs", () }).pipe(Effect.provide(layerTest)), ); +it.effect("gives the guest a failed edit without the text it tried to write", () => + Effect.gen(function* () { + const { orchestrator, guestShares, credential } = yield* shareThread; + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" }); + const failedEdit = (id: string) => + writeItem(id, { + type: "file_change", + status: "failed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }); + const before = yield* failedEdit("item:failed-before"); + + const events = yield* guestShares.stream(session); + const during = yield* failedEdit("item:failed-during"); + const detail = (yield* guestShares.item(session, before)).item; + yield* orchestrator.dispatch({ + type: "thread.guest-share.close", + commandId: CommandId.make("close-after-failed-edit"), + threadId, + }); + const received = Array.from(yield* Stream.runCollect(events)); + const changes = received.flatMap((event) => { + if (event.type !== "thread") return []; + if (event.item.kind === "snapshot") { + return [ + ...event.item.projection.turnItems, + ...event.item.projection.visibleTurnItems.map((row) => row.item), + ]; + } + return event.item.kind === "event" && event.item.event.type === "turn-item.updated" + ? [event.item.event.payload] + : []; + }); + const failed = changes.filter((item) => item.type === "file_change"); + assert.includeMembers( + failed.map((item) => item.id), + [before, during], + ); + for (const change of [...failed, detail]) { + assert.deepInclude(change, { status: "failed", fileName: "src/auth.ts" }); + assert.doesNotHaveAnyKeys(change, ["diffStr", "oldStr", "newStr"]); + } + }).pipe(Effect.provide(layerTest)), +); + it.effect("gives a fork's guest the commands the fork shows from its source thread", () => Effect.gen(function* () { const { orchestrator, guestShares } = yield* shareThread; @@ -656,13 +702,19 @@ it.effect("pages the guest back through turns older than the stream's snapshot", }); yield* eventSink.write({ events: [ - turnItem("item:old-image", 1, { + turnItem("item:old-edit", 1, { + type: "file_change", + status: "failed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }), + turnItem("item:old-image", 2, { type: "assistant_message", text: `![Old](${shot})`, streaming: false, }), ...Array.from({ length: 30 }, (_, index) => - turnItem(`item:ask-${index}`, index + 2, { + turnItem(`item:ask-${index}`, index + 3, { type: "user_message", text: `Ask ${index}`, createdBy: "user", @@ -694,9 +746,10 @@ it.effect("pages the guest back through turns older than the stream's snapshot", while (cursor !== null) { const page: OrchestrationV2ThreadHistoryPage = yield* guestShares.history(session, cursor); older.push(...ids(page.items)); + for (const { item } of page.items) assert.notProperty(item, "diffStr"); cursor = page.hasMoreHistory ? page.nextCursor : null; } - assert.include(older, "item:old-image"); + assert.includeMembers(older, ["item:old-image", "item:old-edit"]); assert.deepStrictEqual(yield* guestShares.media(session, shot), { path: shot, mimeType: "image/png", diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index b5b21a7af2ae7..5ff7ae22770e2 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -52,7 +52,6 @@ import { coalesceThreadLiveStream } from "../orchestration-v2/ThreadLiveEventCoa import { buildBoundedThreadStreamSnapshot } from "../orchestration-v2/ThreadStream.ts"; import { projectTurnItemForDetail, - projectTurnItemForWire, threadStreamEventItem, } from "../orchestration-v2/WireProjection.ts"; import * as DocumentText from "../provider/DocumentText.ts"; @@ -218,6 +217,16 @@ const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | } }; +/** A guest sees that a file changed, never the text of the change, whatever its status. */ +const withoutFileText = (item: OrchestrationV2TurnItem): OrchestrationV2TurnItem => { + if (item.type !== "file_change") return item; + const { diffStr: _diff, oldStr: _old, newStr: _new, ...shown } = item; + return shown; +}; +const rowWithoutFileText = ( + row: Row, +): Row => ({ ...row, item: withoutFileText(row.item) }); + const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const commandOutputs = yield* CommandOutputHub.CommandOutputHub; @@ -566,12 +575,16 @@ const make = Effect.gen(function* () { if (item.kind !== "event") return []; if (endsShare(item.event)) return [ended]; if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]); + const shown = + item.event.type === "turn-item.updated" + ? { ...item, event: { ...item.event, payload: withoutFileText(item.event.payload) } } + : item; const updated = threadOf(item.event); const view = updated === null ? null : viewOf(updated); return view === null - ? [{ type: "thread", item }] + ? [{ type: "thread", item: shown }] : [ - { type: "thread", item }, + { type: "thread", item: shown }, { type: "view", view }, ]; }), @@ -585,7 +598,11 @@ const make = Effect.gen(function* () { ); const openingSnapshot = buildBoundedThreadStreamSnapshot({ snapshotSequence: snapshot.snapshotSequence, - projection: snapshot.projection, + projection: { + ...snapshot.projection, + turnItems: snapshot.projection.turnItems.map(withoutFileText), + visibleTurnItems: snapshot.projection.visibleTurnItems.map(rowWithoutFileText), + }, }); const opening: ReadonlyArray = [ { type: "view", view: initialView }, @@ -669,10 +686,7 @@ const make = Effect.gen(function* () { const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) { const { item } = yield* threadItem(session, itemId); - return { - item: - item.type === "file_change" ? projectTurnItemForWire(item) : projectTurnItemForDetail(item), - }; + return { item: projectTurnItemForDetail(withoutFileText(item)) }; }); const history = Effect.fn("GuestShareService.history")(function* ( @@ -687,7 +701,7 @@ const make = Effect.gen(function* () { share.id, page.items.map((row) => row.item), ); - return page; + return { ...page, items: page.items.map(rowWithoutFileText) }; }); const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* ( diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts index 4ef5d1d1db58e..e1ba0742f3c90 100644 --- a/apps/server/src/htmlRender/HtmlRender.test.ts +++ b/apps/server/src/htmlRender/HtmlRender.test.ts @@ -522,6 +522,33 @@ fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => { expect(error.message).toContain(`browser setup --base-dir ${baseDir}`); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.live("reports a root server's sandbox refusal as a root error", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-fake-browser-", + }); + const executable = path.join(directory, "chrome-headless-shell"); + const refusal = + "[1123/040735.447156:ERROR:content/browser/zygote_host/zygote_host_impl_linux.cc:103] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.\n"; + yield* fileSystem.writeFileString( + executable, + `#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(refusal)});\nprocess.exit(1);\n`, + { mode: 0o755 }, + ); + + const error = yield* HtmlRender.HtmlRender.use((htmlRender) => + htmlRender.preview({ html: "

hello

" }), + ).pipe( + Effect.flip, + Effect.provide(layerHtmlRender(executable)), + Effect.provideService(HostProcess.UserId, 0), + ); + expect(error).toBeInstanceOf(PreviewBrowserHost.PreviewBrowserRootError); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }, ); diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index 6e011aef39d26..2f2f6b8f85534 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -20,6 +20,7 @@ import { openMediaFile } from "./assets/MediaFile.ts"; import { injectMcpAppCsp, injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, injectMcpAppThemeBootstrap, MCP_APP_MAX_HTML_BYTES, } from "@t3tools/shared/mcpApp"; @@ -54,7 +55,9 @@ describe("MCP app asset responses", () => { method, ), ); - const expected = injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)); + const expected = injectMcpAppDocumentBootstrap( + injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)), + ); expect(response.status).toBe(200); expect(response.headers.get("content-length")).toBe( String(new TextEncoder().encode(expected).byteLength), @@ -842,7 +845,7 @@ describe("video asset byte ranges", () => { }); describe("assetResponseHeaders", () => { - it("sandboxes SVG assets", () => { + it("sandboxes SVG and other XML assets", () => { expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "X-Content-Type-Options": "nosniff", @@ -850,6 +853,15 @@ describe("assetResponseHeaders", () => { expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty( "Content-Security-Policy", ); + for (const name of ["page.xhtml", "page.XHT", "feed.xml", "sheet.xsl", "feed.rss"]) { + expect(assetResponseHeaders(`/workspace/${name}`)).toHaveProperty( + "Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; sandbox", + ); + } + expect(assetResponseHeaders("/workspace/photo.png")).not.toHaveProperty( + "Content-Security-Policy", + ); }); it("serves inline attachment documents with their declared mime type", () => { expect( diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 9227711a92d3e..2fec462edec1c 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -5,7 +5,11 @@ import { EnvironmentHttpApi, } from "@t3tools/contracts"; import { isDevProxiedPath } from "@t3tools/shared/devProxy"; -import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; +import { + injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, + injectMcpAppThemeBootstrap, +} from "@t3tools/shared/mcpApp"; import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender"; import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; import * as ByteSize from "effect/ByteSize"; @@ -29,6 +33,7 @@ import { HttpServerRequest, HttpServerRespondable, } from "effect/http"; +import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import { OtlpTracer, OtlpSerialization } from "effect/observability"; @@ -83,6 +88,13 @@ const isSafeInlineMediaMimeType = (mimeType: string): boolean => const isSafeInlineDocumentMimeType = (mimeType: string): boolean => mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html"; +// XML types render as documents, so they get the same policy as SVG. +const isScriptableXmlPath = (filePath: string): boolean => + Option.match(Mime.getType(filePath), { + onNone: () => false, + onSome: (mimeType) => /(?:\/xml(?:$|-)|\+xml$)/.test(mimeType), + }); + export function downloadContentDisposition(fileName?: string): string { if (fileName === undefined) { return "attachment"; @@ -145,7 +157,7 @@ export function assetResponseHeaders( "Content-Security-Policy": htmlContentSecurityPolicy, } : {}), - ...(!options?.download && lowerPath.endsWith(".svg") + ...(!options?.download && isScriptableXmlPath(lowerPath) ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY } : {}), }; @@ -201,6 +213,8 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( new TextDecoder().decode(bytes), injectMcpAppThemeBootstrap, injectMcpAppCookieBootstrap, + // Applied last so it is the document's first script. + injectMcpAppDocumentBootstrap, (html) => new TextEncoder().encode(html), ); headers["Content-Length"] = String(body.byteLength); @@ -285,6 +299,12 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers }); }); +// The default body limit for API routes. Routes that take more set their own limit. +export const API_MAX_BODY_BYTES = 1024 * 1024; +export const layerApiBodyLimit = HttpRouter.middleware( + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(API_MAX_BODY_BYTES)), +).layer; + export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compression(), { global: true, }); diff --git a/apps/server/src/httpResponseErrorGuard.test.ts b/apps/server/src/httpResponseErrorGuard.test.ts index 7227e03dade0a..6569829879e84 100644 --- a/apps/server/src/httpResponseErrorGuard.test.ts +++ b/apps/server/src/httpResponseErrorGuard.test.ts @@ -2,7 +2,10 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; import * as NodeNet from "node:net"; -import { afterEach, describe, expect, it } from "vite-plus/test"; +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { afterEach, describe, expect, it } from "@effect/vitest"; import * as HttpResponseErrorGuard from "./httpResponseErrorGuard.ts"; @@ -239,4 +242,30 @@ describe("rejectRequestsUntilServing", () => { expect(servingUpgrade.headers["retry-after"]).toBeUndefined(); expect(writeErrors).toEqual([]); }); + + it.effect( + "rejects early requests on NodeHttpServer, which adds its own listener before listening", + () => + Effect.scoped( + Effect.gen(function* () { + const server = yield* NodeHttpServer.make( + () => + HttpResponseErrorGuard.rejectRequestsUntilServing( + HttpResponseErrorGuard.keepIdleConnections( + guardHttpResponseWriteErrors(NodeHttp.createServer()), + ), + ), + { host: "127.0.0.1", port: 0 }, + ); + const port = (server.address as { readonly port: number }).port; + + const early = yield* Effect.promise(() => fetchResponse(port, "/")); + expect(early.statusCode).toBe(503); + expect(early.headers["retry-after"]).toBe("1"); + + yield* server.serve(Effect.succeed(HttpServerResponse.empty({ status: 204 }))); + expect(yield* Effect.promise(() => fetchStatus(port, "/"))).toBe(204); + }), + ), + ); }); diff --git a/apps/server/src/httpResponseErrorGuard.ts b/apps/server/src/httpResponseErrorGuard.ts index c75ccae660a55..b4596c16cd17f 100644 --- a/apps/server/src/httpResponseErrorGuard.ts +++ b/apps/server/src/httpResponseErrorGuard.ts @@ -25,7 +25,6 @@ export function guardHttpResponseWriteErrors( // into a closed connection, and a slow client reconnects in the middle of a connect. const HTTP_KEEP_ALIVE_TIMEOUT_MS = 95_000; -/** Install before `rejectRequestsUntilServing`, whose handoff starts at the next request listener. */ export function keepIdleConnections(server: T): T { server.keepAliveTimeout = HTTP_KEEP_ALIVE_TIMEOUT_MS; // `close` drops only the connections idle at that moment. One that finishes @@ -48,8 +47,8 @@ export function keepIdleConnections(server: T): T { /** * NodeHttpServer listens before serve() attaches its handlers, so requests in - * between would hang. Install this after the write-error guards so only the - * serving handlers trigger the handoff. + * between would hang. Its own pre-listen fallback stays silent while any other + * request listener exists, so only a listener added after listening takes over. */ export function rejectRequestsUntilServing(server: T): T { const rejectRequest = (_request: NodeHttp.IncomingMessage, response: NodeHttp.ServerResponse) => { @@ -64,6 +63,7 @@ export function rejectRequestsUntilServing(server: T) server.on("upgrade", rejectUpgrade); // Node emits newListener before adding the handler, making the handoff synchronous. server.on("newListener", function onNewListener(event) { + if (!server.listening) return; if (event === "request") server.off("request", rejectRequest); if (event === "upgrade") server.off("upgrade", rejectUpgrade); if ( diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 26d02c06bfe66..f658c26f6c63c 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -349,6 +349,27 @@ describe("IssueService", () => { }), ); + it.effect( + "does not call a GitHub issue URL unbrowsable when no project is a GitHub checkout", + () => + Effect.gen(function* () { + // A plain folder project, while GitHub itself is a supported tracker. + const service = yield* makeService({ + projects: [project({ id: "folder" })], + trackers: [fakeTracker()], + }); + const resolved = yield* service + .resolveUrl("https://github.com/acme/web/issues/1", "folder" as ProjectId) + .pipe(Effect.result); + if (resolved._tag === "Failure") { + expect(resolved.failure).not.toMatchObject({ + _tag: "IssueUnavailableError", + reason: "tracker-unsupported", + }); + } + }), + ); + it.effect("resolves both legacy Azure work item URLs through the bound project", () => Effect.gen(function* () { const tracker = IssueTrackerKind.make("azure-devops"); diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 01d8b47382eef..1a913c9b0725f 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -824,7 +824,10 @@ const make = Effect.gen(function* () { if (standalone === null) { const found = serve(onTracker); if (found === null) { - return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + return yield* new IssueOperationError({ + operation: "resolveUrl", + detail: `No project in T3 Code is on ${link.host}. Add any ${link.host} project to read its issues.`, + }); } return found.resolved; } diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 7e846811e1440..44048330c3ae2 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -182,6 +182,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => { { key: "mod+j", command: "terminal.toggle" }, { key: "mod+shift+d+o", command: "terminal.new" }, { key: "mod+x", command: "invalid.command" }, + { key: "mod+", command: "sidebar.toggle" }, + { key: "mod+a+++", command: "sidebar.toggle" }, ]), ); @@ -205,6 +207,16 @@ it.layer(NodeServices.layer)("keybindings", (it) => { index: 2, message: configState.issues[1]?.message ?? "", }, + { + kind: "keybindings.invalid-entry", + index: 3, + message: configState.issues[2]?.message ?? "", + }, + { + kind: "keybindings.invalid-entry", + index: 4, + message: configState.issues[3]?.message ?? "", + }, ]); }).pipe(Effect.provide(layerKeybindings())), ); diff --git a/apps/server/src/launcherWatch.test.ts b/apps/server/src/launcherWatch.test.ts index 1482804c61e0e..87592b2c4d588 100644 --- a/apps/server/src/launcherWatch.test.ts +++ b/apps/server/src/launcherWatch.test.ts @@ -1,9 +1,11 @@ -import { it } from "@effect/vitest"; +import { assert, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as TestClock from "effect/testing/TestClock"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { awaitLauncherLoss } from "./launcherWatch.ts"; +import { awaitLauncherLoss, stopOnLauncherLoss } from "./launcherWatch.ts"; const launcherPid = 4100; // Orphans are adopted by init or a subreaper, so the new parent is not always 1. @@ -21,3 +23,26 @@ it.effect("notices a launcher that was already gone when the watch began", () => yield* Fiber.join(fiber); }), ); + +it.effect("exits when shutdown after launcher loss outlasts the grace period", () => + Effect.gen(function* () { + let exits = 0; + const cleanupDone = yield* Deferred.make(); + const stuckCleanup = Effect.never.pipe(Effect.onInterrupt(() => Deferred.await(cleanupDone))); + const fiber = yield* Effect.forkChild( + stopOnLauncherLoss(stuckCleanup, { + launcherPid, + getParentPid: () => subreaperPid, + shutdownGrace: "5 seconds", + exit: () => void exits++, + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); + yield* Effect.yieldNow; + yield* TestClock.adjust("4 seconds"); + assert.strictEqual(exits, 0); + yield* TestClock.adjust("1 second"); + assert.strictEqual(exits, 1); + yield* Deferred.succeed(cleanupDone, undefined); + yield* Fiber.await(fiber); + }), +); diff --git a/apps/server/src/launcherWatch.ts b/apps/server/src/launcherWatch.ts index ca109422c95a8..fc2479e2e297a 100644 --- a/apps/server/src/launcherWatch.ts +++ b/apps/server/src/launcherWatch.ts @@ -3,20 +3,26 @@ import * as Effect from "effect/Effect"; import * as HostProcess from "@t3tools/shared/HostProcess"; const DEFAULT_POLL_INTERVAL = Duration.seconds(2); +// The desktop's SIGTERM grace before it escalates to SIGKILL; a lost launcher cannot escalate. +const DEFAULT_SHUTDOWN_GRACE = Duration.seconds(5); // Capture before config and bootstrap reads to detect launcher loss during startup. const startupParentPid = process.ppid; +interface LauncherWatchOptions { + readonly launcherPid?: number; + readonly getParentPid?: () => number; + readonly interval?: Duration.Input; +} + /** * Any parent change signals launcher loss, including adoption by a Linux subreaper; * otherwise an orphan backend keeps its ownership lock and blocks replacement launches. * Skip init-launched backends and Windows, which retains the exited parent's id. */ -export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(function* (options?: { - readonly launcherPid?: number; - readonly getParentPid?: () => number; - readonly interval?: Duration.Input; -}): Effect.fn.Return { +export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(function* ( + options?: LauncherWatchOptions, +): Effect.fn.Return { const platform = yield* HostProcess.Platform; const launcherPid = options?.launcherPid ?? startupParentPid; const getParentPid = options?.getParentPid ?? (() => process.ppid); @@ -33,3 +39,30 @@ export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(fu }); return yield* poll; }); + +/** + * Interrupts `run` when the launcher is lost, and exits the process if shutdown outlasts the + * grace period: a stuck cleanup step would otherwise keep holding the T3 home's ownership lock. + */ +export const stopOnLauncherLoss = ( + run: Effect.Effect, + options?: LauncherWatchOptions & { + readonly shutdownGrace?: Duration.Input; + readonly exit?: () => void; + }, +) => + Effect.raceFirst( + run, + awaitLauncherLoss(options).pipe( + Effect.andThen( + Effect.forkDetach( + Effect.sleep(options?.shutdownGrace ?? DEFAULT_SHUTDOWN_GRACE).pipe( + Effect.andThen(Effect.logWarning("backend shutdown timed out after launcher loss")), + Effect.andThen(Effect.sync(options?.exit ?? (() => process.exit(1)))), + ), + ), + ), + // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit). + Effect.andThen(Effect.interrupt), + ), + ); diff --git a/apps/server/src/legacyServerOwner.ts b/apps/server/src/legacyServerOwner.ts index 9ed24c9c838f2..0b0b195ad38e7 100644 --- a/apps/server/src/legacyServerOwner.ts +++ b/apps/server/src/legacyServerOwner.ts @@ -1,9 +1,14 @@ // Effect-free so the service launcher shares the pre-lock owner identity check with server startup. +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; -export const legacyOwnerStartTimeCommand = (pid: number, platform: NodeJS.Platform) => { +export const legacyOwnerStartTimeCommand = ( + pid: number, + platform: NodeJS.Platform, + hostEnv: NodeJS.ProcessEnv, +) => { const windows = platform === "win32"; return { - command: windows ? "powershell.exe" : "ps", + command: windows ? windowsPowerShellPath(hostEnv) : "ps", args: windows ? [ "-NoProfile", diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index eb721e2c7a078..3ff0f223ea9c3 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -56,6 +56,9 @@ import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; import * as McpWebhookTransport from "./McpWebhookTransport.ts"; +import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; +import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; @@ -292,8 +295,13 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { Effect.map((settings) => ({ linkedEnvironments: settings.linkedEnvironmentsEnabled, agentFeedback: settings.agentFeedback.mode, + workflows: settings.workflowsEnabled, + })), + Effect.orElseSucceed(() => ({ + linkedEnvironments: false, + agentFeedback: "off" as const, + workflows: false, })), - Effect.orElseSucceed(() => ({ linkedEnvironments: false, agentFeedback: "off" as const })), ); const pullRequests = yield* Effect.serviceOption(PullRequestService.PullRequestService); const projections = yield* Effect.serviceOption(ProjectionStore.ProjectionStoreV2); @@ -367,7 +375,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { const asked = withModeLimit(withSenderThread(invocation, request), request); if (asked === undefined) return invalidModeLimit; const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling); - const { linkedEnvironments, agentFeedback } = yield* settingsFlags; + const { linkedEnvironments, agentFeedback, workflows } = yield* settingsFlags; if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff; const origin = Option.getOrUndefined(Option.map(requestUrl(request), (url) => url.origin)); const forge = @@ -378,6 +386,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { ...limited, linkedEnvironments, agentFeedback, + workflows, origin, ...(forge === undefined ? {} : { forge }), }; @@ -1213,6 +1222,68 @@ const withToolAnalytics = return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer)); }); +/** + * ACP runtimes and Code Mode wrappers can drop or replace structured MCP tool results on + * completion. Recording each thread-scoped call's compact result before returning lets adapters + * recover sent messages, IDs, counts, and error flags without depending on output passthrough. + */ +const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(function* ( + registration: Effect.Effect, +) { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions); + if (Option.isNone(mcpSessions)) { + return yield* registration; + } + const capturingServer = McpServer.McpServer.of({ + ...server, + addTool: Effect.fn("McpServer.addTool")(function (options) { + const toolName = options.tool.name; + // html_render tracks its own path/hash recovery with publish cleanup in HtmlRender. + if (toolName === HTML_RENDER_TOOL_NAME) { + return server.addTool(options); + } + return server.addTool({ + ...options, + // Untraced: withToolSpans already opens a span per tool call. + handle: Effect.fnUntraced(function* (payload) { + const scopeOption = yield* Effect.serviceOption( + McpInvocationContext.McpInvocationContext, + ); + const thread = Option.getOrUndefined(scopeOption)?.thread; + const epoch = + thread === undefined + ? undefined + : yield* mcpSessions.value.toolResultEpoch(thread.threadId); + return yield* options.handle(payload).pipe( + Effect.onExit((exit) => { + if (thread === undefined) return Effect.void; + if (exit._tag === "Success" && exit.value instanceof McpSchema.InputRequired) { + return Effect.void; + } + if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) { + return Effect.void; + } + const output = + exit._tag === "Success" + ? (compactT3McpToolOutput(toolName, exit.value) ?? + SendToUser.capturedSuccessFallback(toolName)) + : { isError: true }; + return output === undefined + ? Effect.void + : mcpSessions.value.recordToolResult(thread.threadId, toolName, payload, output, { + providerSessionId: thread.providerSessionId, + epoch, + }); + }), + ); + }), + }); + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, capturingServer)); +}); + /** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */ const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* ( registration: Effect.Effect, @@ -1295,8 +1366,10 @@ export const toolkitRegistration = , EX, ) => Layer.effectDiscard( withToolAnalytics( - withToolSpans( - withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + withToolResultCapture( + withToolSpans( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ), ), ), ).pipe( @@ -1313,7 +1386,7 @@ const imageToolRegistration = , A, E, R, register: Effect.Effect, handlers: McpToolAccess.HandlersLayer, ) => - Layer.effectDiscard(withToolAnalytics(withToolSpans(register))).pipe( + Layer.effectDiscard(withToolAnalytics(withToolResultCapture(withToolSpans(register)))).pipe( Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), ); @@ -1346,7 +1419,7 @@ export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandl const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); // The fork's send_to_user replaces upstream's: display modes read its calls by name and `text`. -const layerMessageToolkit = toolkitRegistration( +export const layerMessageToolkit = toolkitRegistration( SendToUser.SendToUserToolkit, SendToUser.layerHandlers, ); @@ -1556,8 +1629,13 @@ export const layerMilestoneEvents = Layer.effectDiscard( for (const options of events.threads) { yield* McpServer.registerEvent({ ...options, annotations }); } + // Listed only while Labs → Workflows is on, since no run can reach them otherwise. + const workflowAnnotations = Context.make( + McpSchema.EnabledWhen, + McpInvocationContext.hiddenUnlessWorkflowEvents, + ); for (const options of events.workflows) { - yield* McpServer.registerEvent({ ...options, annotations }); + yield* McpServer.registerEvent({ ...options, annotations: workflowAnnotations }); } }), ).pipe( diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index f1a070e86b9e3..0ba10af2d8c45 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -155,6 +155,8 @@ export interface McpInvocationScope { readonly linkedEnvironments?: boolean; /** The Agent feedback mode here; `/mcp` reads it per request. Unset is off. */ readonly agentFeedback?: AgentFeedbackMode; + /** True while Labs → Workflows is on here; `/mcp` reads it per request. Unset is off. */ + readonly workflows?: boolean; /** * The origin this `/mcp` request reached, e.g. a T3 Connect tunnel. Hosted clients cannot * see the URL they were configured with, so links they must fetch carry it. Unset in-process. @@ -237,6 +239,13 @@ export const hiddenWhileFeedbackOff = (): boolean => { return scope?.agentFeedback !== undefined && scope.agentFeedback !== "off"; }; +/** `McpSchema.EnabledWhen` for workflow event types: outside clients only, while Workflows is on. */ +export const hiddenUnlessWorkflowEvents = (): boolean => { + const fiber = Fiber.getCurrent(); + const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext); + return scope !== undefined && scope.thread === undefined && scope.workflows === true; +}; + /** `McpSchema.EnabledWhen` for tools that act on the thread's forge, hidden where it has none. */ export const hiddenWithoutForge = (): boolean => { const fiber = Fiber.getCurrent(); diff --git a/apps/server/src/mcp/McpWebhookTransport.ts b/apps/server/src/mcp/McpWebhookTransport.ts index 8bdde7b1184da..abdfa995026b7 100644 --- a/apps/server/src/mcp/McpWebhookTransport.ts +++ b/apps/server/src/mcp/McpWebhookTransport.ts @@ -1,7 +1,7 @@ import * as NodeDns from "node:dns"; import * as NodeNet from "node:net"; -import { NodeHttpClient } from "@effect/platform-node"; +import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -122,6 +122,7 @@ export const make = (hosts: ReadonlyArray) => { return { check, allowsPlaintext: (url: URL) => allowed.has(hostOf(url)), - layerClient: NodeHttpClient.layerUndiciOptions({ connect: { lookup } }), + // The Undici client statically imports undici, which a single-executable cannot load. + layerClient: NodeHttpClient.layerNodeHttpOptions({ lookup }), }; }; diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index cbe4be1e4b42f..7c4a0f00eccfe 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -311,6 +311,8 @@ it("readThread preserves caller access errors and prefers activity-run status ov it("readThread pages cut-off text without splitting an emoji across pages", async () => { const text = "a😀bc"; const itemId = TurnItemId.make("turn-item-mcp-reasoning"); + const webhookToolItemId = TurnItemId.make("turn-item-mcp-webhook-tool"); + const webhookToken = "wJalrXUtnFEMI_K7MDENG-bPxRfiCYEXAMPLEKEY1234"; const projection = { thread: baseThread({ threadId: parentThreadId, @@ -349,6 +351,27 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn sourceItemId: TurnItemId.make(`turn-item-mcp-${index}`), item: { ...row.item, text: "x".repeat(600) }, })), + { + ...row, + position: 12, + sourceItemId: webhookToolItemId, + item: { + ...row.item, + type: "dynamic_tool", + toolName: "schedule_task", + input: { + prompt: "Triage {{body.action}}", + schedule: { + type: "webhook", + signature: { header: "x-hub-signature-256", encoding: "hex", prefix: "", secret: "s3" }, + }, + }, + output: { + webhookUrl: `https://relay.test/v1/hooks/0123456789abcdef/task-1/${webhookToken}`, + path: `/api/hooks/task-1/${webhookToken}`, + }, + }, + }, ]; const layer = layerOrchestratorService.pipe( @@ -429,6 +452,18 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn }); expect(first.items).toHaveLength(10); expect(first).toMatchObject({ nextPosition: 9, hasMore: true }); + + const webhookTool = yield* service.readThread(makeScope(), { + threadId: parentThreadId, + view: "activity", + itemId: webhookToolItemId, + maxCharsPerItem: 2_000, + }); + const webhookToolText = webhookTool.items[0]?.text ?? ""; + expect(webhookToolText).toContain("/v1/hooks/0123456789abcdef/task-1/[withheld]"); + expect(webhookToolText).toContain("/api/hooks/task-1/[withheld]"); + expect(webhookToolText).not.toContain(webhookToken); + expect(webhookToolText).not.toContain('"s3"'); }).pipe(Effect.provide(layer), Effect.runPromise); }); @@ -640,8 +675,15 @@ it("readThread returns the newest items that fit the response budget", async () maxCharsPerItem: 1_500, }; const result = yield* service.readThread(makeScope(), read); - // The CLI reads as a client without a cursor and follows only hasMore. - const first = yield* service.readThread({ ...makeScope(), thread: undefined }, read); + // An outside MCP client, such as claude.ai, reads without a thread or a link. + const outside = yield* service.readThread( + { + ...makeScope(), + thread: undefined, + client: { sessionId: "session-1", label: "claude.ai", access: "read-only" }, + }, + read, + ); const fromStart = yield* service.readThread(makeScope(), { ...read, afterPosition: -1 }); const linked = yield* service.readThread( { @@ -659,7 +701,7 @@ it("readThread returns the newest items that fit the response budget", async () expect(pageOptions).toEqual([ { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" }, - { limit: 100, view: "activity" }, + { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" }, { afterPosition: -1, limit: 100, view: "activity" }, { beforePosition: Number.POSITIVE_INFINITY, limit: 100, view: "activity" }, ]); @@ -669,10 +711,13 @@ it("readThread returns the newest items that fit the response budget", async () expect(result.items.at(-1)?.position).toBe(99); expect(result.earlierPosition).toBe(result.items[0]?.position); expect(result.hasMore).toBe(false); - expect(first.items[0]?.position).toBe(0); - expect(first.hasMore).toBe(true); - expect(first.nextPosition).toBe(first.items.at(-1)?.position); + expect(outside.items.at(-1)?.position).toBe(99); + expect(outside.earlierPosition).toBe(outside.items[0]?.position); + expect(outside.hasMore).toBe(false); + // The t3 thread CLI pages forward from here, following only hasMore. expect(fromStart.items[0]?.position).toBe(0); + expect(fromStart.hasMore).toBe(true); + expect(fromStart.nextPosition).toBe(fromStart.items.at(-1)?.position); expect(linked.items.at(-1)?.position).toBe(99); expect(linked.earlierPosition).toBe(linked.items[0]?.position); expect(linked.hasMore).toBe(false); diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 551a84109cfa2..c99f9b0a6e1ad 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3950,6 +3950,8 @@ describe("OrchestratorMcpService provider resolution", () => { boundThread: OrchestrationV2ThreadShell | null, upserted: Ref.Ref, saved: ScheduledTask = tasks[0]!, + /** Stores each keyed create under the id its key derives, as the real service does. */ + created?: Ref.Ref>, ) => OrchestratorMcpService.layer.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), @@ -3984,9 +3986,24 @@ describe("OrchestratorMcpService provider resolution", () => { Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({ - list: () => Effect.succeed({ tasks }), - upsert: () => - Ref.update(upserted, (count) => count + 1).pipe(Effect.as({ task: saved })), + list: () => + created === undefined + ? Effect.succeed({ tasks }) + : Ref.get(created).pipe(Effect.map((stored) => ({ tasks: stored }))), + upsert: (input) => + Ref.update(upserted, (count) => count + 1).pipe( + Effect.andThen( + created === undefined || input.commandId === undefined + ? Effect.void + : Ref.set(created, [ + { + ...saved, + id: ScheduledTaskService.scheduledTaskIdForCommand(input.commandId), + }, + ]), + ), + Effect.as({ task: saved }), + ), }), ), ), @@ -4084,6 +4101,39 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect( + "refuses to replay a creation over a task whose thread now runs above the caller", + () => + Effect.gen(function* () { + const upserted = yield* Ref.make(0); + const created = yield* Ref.make>([]); + const bound = task({ threadId: boundThreadId }); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + service( + [bound], + liveThreadShell(boundThreadId, { runtimeMode: "full-access" }), + upserted, + bound, + created, + ), + ), + ); + const create = (prompt: string) => + mcp.scheduleTask(supervisedClient, { + projectId, + prompt, + schedule: { type: "webhook" }, + freshSession: true, + clientRequestId: "nightly", + }); + yield* create("Check the build"); + const error = yield* create("Something else").pipe(Effect.flip); + assert.equal(error.code, "runtime_mode_escalation_denied"); + assert.equal(yield* Ref.get(upserted), 1); + }), + ); + it.effect("reports a saved task even when its bound thread cannot be read", () => Effect.gen(function* () { const upserted = yield* Ref.make(0); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 5cf9a66985aaf..54230d629bb41 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -139,6 +139,7 @@ import { } from "./delegatedTaskModes.ts"; import { assertTargetWithinLimits, isLiveCallerShell, threadNotFound } from "./threadAccess.ts"; import { fyiRunsByThread, fyiTimelineFields, sendFyi } from "../fork/fyi/FyiMcp.ts"; +import { WITHHELD, withoutWebhookUrlToken } from "../scheduledTasks/webhookUrlToken.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as PeerForwarding from "../peer/PeerForwarding.ts"; import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; @@ -1126,6 +1127,19 @@ function jsonText(value: unknown): string { } } +// Thread reads show a webhook's signing secret as withheld. + +const asRecord = (value: unknown) => + typeof value === "object" && value !== null ? (value as Readonly>) : null; + +function withoutWebhookSigningSecret(toolInput: unknown): unknown { + const input = asRecord(toolInput); + const schedule = asRecord(input?.schedule); + const signature = asRecord(schedule?.signature); + if (typeof signature?.secret !== "string") return toolInput; + return { ...input, schedule: { ...schedule, signature: { ...signature, secret: WITHHELD } } }; +} + function turnItemText(item: OrchestrationV2TurnItem): string | null { switch (item.type) { case "notification": @@ -1191,7 +1205,11 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null { case "subagent": return item.result ?? item.progress ?? item.prompt; case "dynamic_tool": - return jsonText({ toolName: item.toolName, input: item.input, output: item.output }); + return jsonText({ + toolName: item.toolName, + input: withoutWebhookSigningSecret(item.input), + output: item.output, + }); } } @@ -1212,7 +1230,8 @@ function timelineItem(input: { /** The runs FYI rows name, by the thread each row comes from. */ readonly runsByThreadId: ReadonlyMap; }): OrchestratorMcpThreadTimelineItem { - const text = turnItemText(input.row.item); + const itemText = turnItemText(input.row.item); + const text = itemText === null ? null : withoutWebhookUrlToken(itemText); const offset = input.textOffset ?? 0; const end = textPageEnd(text, offset, input.maxChars); const textTruncated = text !== null && text.length > end; @@ -2373,6 +2392,21 @@ const make = Effect.gen(function* () { }, ); + const requireScheduledTaskWithinLimits = Effect.fn( + "OrchestratorMcpService.requireScheduledTaskWithinLimits", + )(function* ( + task: ScheduledTask, + limits: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + }, + ) { + for (const modes of yield* scheduledTaskRunModes(task)) { + yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); + yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); + } + }); + /** * A scheduled task the caller may change: one whose runs execute at modes no * broader than the caller's own, so editing its prompt cannot run work above @@ -2396,10 +2430,7 @@ const make = Effect.gen(function* () { if (task === undefined) { return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`); } - for (const modes of yield* scheduledTaskRunModes(task)) { - yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); - } + yield* requireScheduledTaskWithinLimits(task, limits); return task; }); @@ -2427,6 +2458,16 @@ const make = Effect.gen(function* () { .slice(0, 80) .replace(/[\uD800-\uDBFF]$/, ""); const title = input.title ?? (derivedTitle.length > 0 ? derivedTitle : "Scheduled task"); + // Scope the idempotency key by provider session so two callers + // reusing the same clientRequestId cannot collide on one task row. + const commandId = + input.clientRequestId === undefined + ? undefined + : stableCommandId({ + scope, + requestKey: input.clientRequestId, + operation: "schedule-task", + }); const upsertInput: ScheduledTaskUpsertInput = { title, prompt: input.prompt, @@ -2445,18 +2486,22 @@ const make = Effect.gen(function* () { interactionMode: limits.interactionMode, createdBy: "agent", creationSource: "mcp", - // Scope the idempotency key by provider session so two callers - // reusing the same clientRequestId cannot collide on one task row. - ...(input.clientRequestId === undefined - ? {} - : { - commandId: stableCommandId({ - scope, - requestKey: input.clientRequestId, - operation: "schedule-task", - }), - }), + ...(commandId === undefined ? {} : { commandId }), }; + // A replayed key rewrites the task it created, which its user may since have raised or + // rebound: that is an edit of the task as it now stands. + if (commandId !== undefined) { + const replayedId = ScheduledTaskService.scheduledTaskIdForCommand(commandId); + const { tasks } = yield* scheduledTasks + .list() + .pipe( + Effect.mapError((error) => + failure("orchestration_error", `Could not load scheduled task: ${error.message}`), + ), + ); + const replayed = tasks.find((candidate) => candidate.id === replayedId); + if (replayed !== undefined) yield* requireScheduledTaskWithinLimits(replayed, limits); + } const { task } = yield* scheduledTasks .upsert(upsertInput) .pipe( @@ -3555,11 +3600,7 @@ const make = Effect.gen(function* () { const view = input.view ?? "messages"; const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT; const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS; - // Client callers (the CLI) page forward from a cursorless read. - const newestFirst = - input.beforePosition !== undefined || - (input.afterPosition === undefined && - (scope.thread !== undefined || scope.client?.linked === true)); + const newestFirst = input.beforePosition !== undefined || input.afterPosition === undefined; const timeline = yield* threadManagement .getTimelinePage(input.threadId, { ...(input.afterPosition === undefined ? {} : { afterPosition: input.afterPosition }), diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts index 0f86dfafa1a3c..ce64d5bf60d24 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts @@ -1109,3 +1109,178 @@ it.effect("keeps each thread's current tab when threads share a provider session expect(routed[0]!.agentSessionId).not.toBe(routed[1]!.agentSessionId); }), ); + +const connectTabHost = Effect.fn("connectTabHost")(function* ( + broker: PreviewAutomationBroker.PreviewAutomationBroker["Service"], +) { + const openTabs: PreviewTabId[] = []; + const routed: RoutedRequest[] = []; + const connected = yield* Deferred.make(); + const requests = requestsFrom( + yield* broker.connect(makeHost({ supportedOperations: ["open", "snapshot", "close"] })), + () => Deferred.doneUnsafe(connected, Effect.void), + ); + yield* Stream.runForEach(requests, (request) => { + routed.push(request); + const reply = { clientId: "client-1", connectionId: request.connectionId }; + if (request.operation === "open") { + const tabId = PreviewTabId.make(`tab-${routed.length}`); + openTabs.push(tabId); + return broker.respond({ + ...reply, + requestId: request.requestId, + ok: true, + result: { tabId }, + }); + } + const tabId = request.tabId ?? openTabs.at(-1); + if (tabId === undefined || !openTabs.includes(tabId)) { + return broker.respond({ + ...reply, + requestId: request.requestId, + ok: false, + error: { _tag: "PreviewAutomationTabNotFoundError", message: "No tab." }, + }); + } + if (request.operation === "close") openTabs.splice(openTabs.indexOf(tabId), 1); + return broker.respond({ ...reply, requestId: request.requestId, ok: true, result: {} }); + }).pipe(Effect.forkScoped); + yield* Deferred.await(connected); + return { routed, openTabs }; +}); + +const openTwoTabs = Effect.fn("openTwoTabs")(function* ( + broker: PreviewAutomationBroker.PreviewAutomationBroker["Service"], +) { + const first = yield* broker.invoke<{ tabId: PreviewTabId }>({ + scope, + operation: "open", + input: {}, + }); + const second = yield* broker.invoke<{ tabId: PreviewTabId }>({ + scope, + operation: "open", + input: { reuseExistingTab: false }, + }); + return [first.tabId, second.tabId] as const; +}); + +it.effect("forgets a current tab that closed elsewhere instead of naming it", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const { routed, openTabs } = yield* connectTabHost(broker); + yield* broker.invoke({ scope, operation: "open", input: {} }); + openTabs.splice(0); + + const error = yield* broker + .invoke({ scope, operation: "snapshot", input: {} }) + .pipe(Effect.flip); + yield* broker.invoke({ scope, operation: "snapshot", input: {} }).pipe(Effect.ignore); + + expect(error.message).toBe( + "No active preview tab was found for snapshot. Call preview_open first.", + ); + expect(routed.at(-1)?.tabId).toBeUndefined(); + }), + ), +); + +it.effect("closing the current tab leaves implicit calls to the remaining tab", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const { routed } = yield* connectTabHost(broker); + const [, second] = yield* openTwoTabs(broker); + yield* broker.invoke({ scope, operation: "close", input: {}, tabId: second }); + + yield* broker.invoke({ scope, operation: "snapshot", input: {} }); + + expect(routed.at(-1)?.tabId).toBeUndefined(); + }), + ), +); + +it.effect("closing another tab keeps the current tab", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const { routed } = yield* connectTabHost(broker); + const [first, second] = yield* openTwoTabs(broker); + yield* broker.invoke({ scope, operation: "close", input: {}, tabId: first }); + + yield* broker.invoke({ scope, operation: "snapshot", input: {} }); + + expect(routed.at(-1)?.tabId).toBe(second); + }), + ), +); + +it.effect("a late tab-not-found reply keeps a tab another call made current", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const tabA = PreviewTabId.make("tab-a"); + const tabB = PreviewTabId.make("tab-b"); + const connected = yield* Deferred.make(); + const explicitSeen = yield* Deferred.make(); + const implicitSeen = yield* Deferred.make(); + const releaseExplicit = yield* Deferred.make(); + const releaseImplicit = yield* Deferred.make(); + const events = yield* broker.connect(makeHost()); + yield* Stream.runForEach(events, (event) => { + if (event.type === "connected") return Deferred.succeed(connected, undefined); + const request = event.request; + const reply = { + clientId: "client-1", + connectionId: event.connectionId, + requestId: request.requestId, + }; + const marker = (request.input as { marker?: string }).marker; + return Effect.gen(function* () { + if (marker === "explicit") { + yield* Deferred.succeed(explicitSeen, undefined); + yield* Deferred.await(releaseExplicit); + yield* broker.respond({ ...reply, ok: true, result: { url: "tab-b" } }); + } else if (marker === "implicit") { + yield* Deferred.succeed(implicitSeen, undefined); + yield* Deferred.await(releaseImplicit); + yield* broker.respond({ + ...reply, + ok: false, + error: { _tag: "PreviewAutomationTabNotFoundError", message: "Tab A closed." }, + }); + } else { + yield* broker.respond({ + ...reply, + ok: true, + result: { url: request.tabId ?? "host-default" }, + }); + } + }).pipe(Effect.forkScoped, Effect.asVoid); + }).pipe(Effect.forkScoped); + yield* Deferred.await(connected); + yield* broker.invoke({ scope, operation: "snapshot", input: {}, tabId: tabA }); + const explicit = yield* broker + .invoke({ scope, operation: "snapshot", input: { marker: "explicit" }, tabId: tabB }) + .pipe(Effect.forkScoped); + yield* Deferred.await(explicitSeen); + const implicit = yield* broker + .invoke({ scope, operation: "snapshot", input: { marker: "implicit" } }) + .pipe(Effect.flip, Effect.forkScoped); + yield* Deferred.await(implicitSeen); + yield* Deferred.succeed(releaseExplicit, undefined); + yield* Fiber.join(explicit); + yield* Deferred.succeed(releaseImplicit, undefined); + yield* Fiber.join(implicit); + + const result = yield* broker.invoke<{ url: string }>({ + scope, + operation: "snapshot", + input: {}, + }); + + expect(result.url).toBe("tab-b"); + }), + ), +); diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.ts index cc3230e5b68b5..793daedc6d82b 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.ts @@ -678,35 +678,56 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { onSome: (value) => Effect.succeed(value as A), }); }); - const result = yield* awaitResponse().pipe(Effect.ensuring(removePending)); - if (input.updateCurrentTab === false) return result; - const responseTabId = readResultTabId(result); - const resultTabId = responseTabId === undefined ? input.tabId : responseTabId; - if (resultTabId === undefined) return result; const assignmentKey = hostAssignmentKey(input.scope); - yield* SynchronizedRef.update(state, (current) => { - const assignment = current.assignments.get(assignmentKey); - if ( - !assignment || - assignment.connectionId !== connection.connectionId || - assignment.queue !== connection.queue || - (assignment.tabSequence ?? -1) > requestSequence - ) { - return current; - } - const assignments = new Map(current.assignments); - if (resultTabId === null) { + const rememberCurrentTab = (tabId: PreviewTabId | null, replacing?: PreviewTabId) => + SynchronizedRef.update(state, (current) => { + const assignment = current.assignments.get(assignmentKey); + if ( + !assignment || + assignment.connectionId !== connection.connectionId || + assignment.queue !== connection.queue || + (assignment.tabSequence ?? -1) > requestSequence || + (replacing !== undefined && assignment.tabId !== replacing) + ) { + return current; + } const { tabId: _tabId, ...withoutTabId } = assignment; - assignments.set(assignmentKey, { ...withoutTabId, tabSequence: requestSequence }); - } else { + const assignments = new Map(current.assignments); assignments.set(assignmentKey, { - ...assignment, - ...(resultTabId === undefined ? {} : { tabId: resultTabId }), + ...withoutTabId, + ...(tabId === null ? {} : { tabId }), tabSequence: requestSequence, }); - } - return { ...current, assignments }; - }); + return { ...current, assignments }; + }); + const result = yield* awaitResponse().pipe( + Effect.ensuring(removePending), + Effect.catchTags({ + PreviewAutomationTabNotFoundError: (error) => { + if (input.tabId !== undefined || error.tabId === undefined) return Effect.fail(error); + // The tab came from the assignment, so neither name it nor keep targeting it. + const { tabId: _tabId, ...fields } = error; + const implicitError = new PreviewAutomationTabNotFoundError({ + ...fields, + cause: error.cause, + }); + return input.updateCurrentTab === false + ? Effect.fail(implicitError) + : rememberCurrentTab(null, error.tabId).pipe( + Effect.andThen(Effect.fail(implicitError)), + ); + }, + }), + ); + if (input.updateCurrentTab === false) return result; + if (input.operation === "close") { + // A closed tab never becomes current; closing the current one leaves none. + if (requestContext.tabId !== undefined) yield* rememberCurrentTab(null, requestContext.tabId); + return result; + } + const responseTabId = readResultTabId(result); + const resultTabId = responseTabId === undefined ? input.tabId : responseTabId; + if (resultTabId !== undefined) yield* rememberCurrentTab(resultTabId); return result; }); diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts index aff11dacad26e..b2e9a90bb7d3c 100644 --- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts @@ -378,7 +378,7 @@ const cancelBackgroundOnlyTask = ( (event) => event.type === "run.updated" && event.payload.id === child.turn.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ); const nativeSubagentEvents = [ { @@ -560,7 +560,8 @@ const cancelBackgroundOnlyTask = ( } const before = yield* service.taskStatus(scope, task.id); assert.equal(before.status, "running"); - assert.equal(before.workState, turnSettled ? "waiting_for_children" : "working"); + // The child's run completes when its turn ends, before its checkpoint capture runs. + assert.equal(before.workState, cancelAt === "turn" ? "working" : "waiting_for_children"); const parentTask = Effect.map(orchestrator.getThreadProjection(parentThreadId), (parent) => parent.subagents.find((entry) => entry.id === task.id), @@ -592,7 +593,8 @@ const cancelBackgroundOnlyTask = ( event.payload.type === "run_interrupt_request", ), ); - assert.equal((yield* parentTask)?.status, "running"); + // The child's turn already ended, so the cancel settles its finished run in this commit. + assert.equal((yield* parentTask)?.status, "interrupted"); return { scope, taskId: task.id, settled: undefined }; } if (cancelAt === "refused") { @@ -651,7 +653,11 @@ const cancelBackgroundOnlyTask = ( // Stop reached the provider turn that owns the shell. if (background === "command") assert.deepEqual(interrupted, [["bg-sleep"]]); assert.equal(childAfter.runs.length, cancelAt === "monitor" || cancelAt === "turn" ? 2 : 1); - assert.equal(childAfter.runs[0]!.status, "completed"); + // A Stop accepted before the run's checkpoint settled it ends that run as interrupted. + assert.equal( + childAfter.runs.find((run) => run.id === child.turn.runId)?.status, + cancelAt === "checkpoint" || cancelAt === "turn" ? "interrupted" : "completed", + ); assert.deepEqual( childAfter.runtimeRequests.map((request) => [request.id, request.status]), [ diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 33c356af4e7e1..5a946c60a6f83 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -57,6 +57,7 @@ import * as SecretRequests from "../../secrets/SecretRequests.ts"; import * as RemoteDelegation from "../../peer/RemoteDelegation.ts"; import * as ScheduledTaskService from "../../scheduledTasks/ScheduledTaskService.ts"; import * as ServerSettings from "../../serverSettings.ts"; +import { DisplayModeWrap } from "../../fork/displayModeWrap/DisplayModeWrap.ts"; import * as McpHttpServer from "../McpHttpServer.ts"; import * as McpInvocationContext from "../McpInvocationContext.ts"; import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts"; @@ -416,6 +417,52 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both ), ); +it.effect("captures send_to_user results for providers that drop MCP outputs", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const draft = "### Status\n\nAll checks passed."; + const result = yield* server + .callTool({ name: "send_to_user", arguments: { text: draft } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(result.isError).not.toBe(true); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: draft })).toEqual({ + sentMessage: draft, + }); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: draft })).toBe( + undefined, + ); + + const invalid = yield* server + .callTool({ name: "send_to_user", arguments: { text: "" } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + Effect.flip, + ); + expect(invalid).toMatchObject({ _tag: "InvalidParams" }); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: "" })).toEqual({ + isError: true, + }); + }).pipe( + Effect.provide( + McpHttpServer.layerMessageToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + // The fork's send_to_user reads the thread's display mode. + Layer.provide(ServerSettings.layerTest()), + Layer.provide( + Layer.mock(DisplayModeWrap)({ forgetNotesAfterCompaction: () => (ingest) => ingest }), + ), + ), + ), + ), +); + it.effect("records only failed calls of tools that hand off no work", () => { // Recording runs detached from the tool response, so the first event is awaited. const recorded = Deferred.makeUnsafe<{ event: string; properties: object }>(); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index d03b038ee0780..a40d15252fbb8 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off - a directory junction needs no privilege on Windows. +import * as NodeFSP from "node:fs/promises"; import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; import { expect, it } from "@effect/vitest"; import { @@ -567,10 +569,14 @@ it.effect("a launch binds only an existing checkout that is one of the project's Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" }); + // Git registers resolved paths, and a launch keeps the registered one. + const root = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" }), + ); const repo = path.join(root, "repo"); const worktree = path.join(root, "feature"); const outside = path.join(root, "outside"); + const alias = path.join(root, "alias"); yield* fileSystem.makeDirectory(repo); yield* fileSystem.makeDirectory(outside); @@ -615,9 +621,13 @@ it.effect("a launch binds only an existing checkout that is one of the project's code: "invalid_request", }); } + // The thread keeps the registered worktree path when launched through a link to it. + yield* Effect.promise(() => NodeFSP.symlink(worktree, alias, "junction")); + expect((yield* launchInto(alias)).at(-1)?.result).toMatchObject({ projectId }); expect(launched.map((launch) => launch.workspaceStrategy)).toEqual([ { type: "existing_worktree", worktreePath: worktree }, { type: "existing_worktree", worktreePath: repo }, + { type: "existing_worktree", worktreePath: worktree }, ]); yield* fileSystem.remove(worktree, { recursive: true }); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 511dcfe26c3df..f92df228a422f 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -87,24 +87,29 @@ function worktreeCheckHint( }`; } -/** Require project worktrees so launches cannot target arbitrary host directories. */ -const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* ( +/** + * Require project worktrees so launches cannot target arbitrary host directories. Returns the + * path Git registered, so the thread stays bound to that worktree. + */ +const projectWorktreePath = Effect.fn("mcp.assertProjectWorktree")(function* ( workspaceRoot: string, worktreePath: string, ) { const git = yield* GitVcsDriver.GitVcsDriver; const fileSystem = yield* FileSystem.FileSystem; const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path)); - const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe( - Effect.flatMap((paths) => Effect.forEach(paths, real)), - Effect.orElseSucceed((): ReadonlyArray => []), - ); - if (!worktrees.includes(yield* real(worktreePath))) - return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: - "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.", - }); + const registered = yield* git + .listWorktreePaths(workspaceRoot) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + const requested = yield* real(worktreePath); + for (const candidate of registered) { + if ((yield* real(candidate)) === requested) return candidate; + } + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.", + }); }); /** The composer falls back to the project's t3.json when no setting picks the mode. */ @@ -307,15 +312,23 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { }), ), ); - if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree") - yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath); + const workspaceStrategy = + project !== undefined && input.workspaceStrategy?.type === "existing_worktree" + ? { + ...input.workspaceStrategy, + worktreePath: yield* projectWorktreePath( + project.workspaceRoot, + input.workspaceStrategy.worktreePath, + ), + } + : input.workspaceStrategy; if (!replaying && input.modelSelection !== undefined) { const { instanceId, model } = input.modelSelection; const registry = yield* ProviderRegistry.ProviderRegistry; // The thread runs in this folder, whose own provider config can add models. const cwd = - input.workspaceStrategy?.type === "existing_worktree" - ? input.workspaceStrategy.worktreePath + workspaceStrategy?.type === "existing_worktree" + ? workspaceStrategy.worktreePath : project?.workspaceRoot; const requireModel = ( providers: ReadonlyArray, @@ -357,14 +370,14 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { // An outside caller that names no workspace follows the new-threads-in-a-worktree // default, as the composer does. const requestedStrategy = - input.workspaceStrategy === undefined && + workspaceStrategy === undefined && caller === undefined && project !== undefined && projectSettings !== undefined && (projectSettings.defaultThreadEnvMode ?? (yield* projectFileThreadEnvMode(project.workspaceRoot))) === "worktree" ? yield* defaultWorktreeStrategy(project.workspaceRoot) - : input.workspaceStrategy; + : workspaceStrategy; // An omitted startFromOrigin follows the new-worktree setting, as the composer and // t3_worktree_handoff do. Otherwise a stale local branch silently becomes the base. const strategy = diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index 7caa425d32f2e..95f816f151b9d 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -207,7 +207,10 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* ( Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null), dispatch, }), - Layer.mock(PullRequestService.PullRequestService)(options.pullRequests ?? {}), + Layer.mock(PullRequestService.PullRequestService)({ + addressedProject: () => Effect.succeed(project ?? undefined), + ...options.pullRequests, + }), Layer.mock(GitManager.GitManager)(options.git ?? {}), Layer.succeed(SecureRandom.SecureRandom, testCrypto), McpToolAccessTestkit.liveThreadsLayer, @@ -416,6 +419,18 @@ describe("pull request toolkit handlers", () => { }), ); + it.effect("says when repository is not owner/repo on a known host", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ project: makeProject() }); + const error = yield* harness + .call("link_pull_request", { repository: "github.com/org/repo", number: 1 }) + .pipe(Effect.flip); + expect(error).toMatchObject({ _tag: "PullRequestRepositoryInvalidError" }); + expect(error.message).toContain("owner/repo"); + expect(yield* Ref.get(harness.commands)).toEqual([]); + }), + ); + it.effect("treats a duplicate link as alreadyLinked rather than an error", () => Effect.gen(function* () { const harness = yield* makeHarness({ @@ -929,6 +944,40 @@ describe("source control tools", () => { }), ); + it.effect("reads an Azure DevOps PR by number at its organization and project", () => + Effect.gen(function* () { + const asked: Array = []; + const harness = yield* makeHarness({ + project: makeProject({ + canonicalKey: "dev.azure.com/contoso/project/_git/repo", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://contoso@dev.azure.com/contoso/project/_git/repo", + }, + provider: SourceControlProviderKind.make("azure-devops"), + displayName: "contoso/project/_git/repo", + owner: "contoso", + name: "repo", + }), + pullRequests: { + detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)), + activity: () => Effect.succeed(activity), + }, + }); + const result = yield* harness.call("pull_request_read", { number: 123 }); + expect(result).toMatchObject({ + host: "dev.azure.com", + repository: "contoso/project/_git/repo", + number: 123, + url: "https://dev.azure.com/contoso/project/_git/repo/pullrequest/123", + }); + expect(asked).toMatchObject([ + { host: "dev.azure.com", repository: "contoso/project/_git/repo", number: 123 }, + ]); + }), + ); + it.effect("pages a long conversation and the PR list through the cursors they return", () => Effect.gen(function* () { const comment = (body: string) => diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index ddb3f2a025d43..646f94de8e541 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -308,10 +308,9 @@ const make = Effect.gen(function* () { | typeof PullRequestUnlinkFailedError | typeof PullRequestForgeError, ) => - projects.getShell(thread.projectId).pipe( - Effect.map(Option.getOrUndefined), - Effect.mapError((cause) => new Failure({ cause })), - ); + pullRequests + .addressedProject(thread.projectId) + .pipe(Effect.mapError((cause) => new Failure({ cause }))); const dispatchFailure = (Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError) => @@ -361,7 +360,12 @@ const make = Effect.gen(function* () { const known = yield* projects .listShells() .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause }))); - const callerProject = known.find((project) => project.id === callerThread?.projectId); + const callerProject = + callerThread === undefined + ? undefined + : yield* pullRequests + .addressedProject(callerThread.projectId) + .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause }))); // A pull request named by host and repository builds its URL through the project that holds // it, which need not be the caller's. const urlProject = (input: PullRequestTargetInput) => @@ -417,10 +421,8 @@ const make = Effect.gen(function* () { // Layers below the target are pinned to the heads read here; the host refuses if any moved. const stackMergeScope = Effect.fnUntraced(function* ( ref: PullRequestRef, - input: { readonly expectedHeadSha: string; readonly auto?: boolean | undefined }, + input: { readonly expectedHeadSha: string }, ) { - if (input.auto === true) - return yield* new PullRequestForgeError({ detail: "A stack merge cannot wait with auto." }); const stack = yield* pullRequests .stack(ref, { bypassCache: true }) .pipe(Effect.mapError(forgeFailure)); diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 1e75c5bbaa19f..446b300b9a40b 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -38,6 +38,7 @@ import { PullRequestTargetIncompleteError, PullRequestHostRequiredError, PullRequestUrlUnavailableError, + PullRequestRepositoryInvalidError, } from "../../../pullRequest/pullRequestTarget.ts"; import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; @@ -181,6 +182,7 @@ export const PullRequestToolError = Schema.Union([ PullRequestTargetIncompleteError, PullRequestHostRequiredError, PullRequestUrlUnavailableError, + PullRequestRepositoryInvalidError, PullRequestThreadRequiredError, PullRequestLinkFailedError, PullRequestUnlinkFailedError, @@ -797,7 +799,7 @@ const MergePullRequestTool = Tool.make("pull_request_merge", { ), stack: Schema.optional( Schema.Boolean.annotate({ - description: "Merge this PR and every open stack layer below it at once. Not with auto.", + description: "Merge this PR and every open stack layer below it at once.", }), ), }), diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts new file mode 100644 index 0000000000000..77b7036681ad6 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -0,0 +1,102 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { expect, it } from "@effect/vitest"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import * as Workflows from "../../../workflows/Workflows.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; +import * as WorkflowHandlers from "./handlers.ts"; +import { WorkflowToolkit } from "./tools.ts"; + +const handlersWith = (workflows: Partial) => + McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + NodeCrypto.layer, + McpToolAccessTestkit.liveThreadsLayer, + Layer.succeed(McpInvocationContext.McpInvocationContext, { + environmentId: EnvironmentId.make("environment:workflow"), + requestNamespace: "client:workflow", + thread: undefined, + client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }), + Layer.mock(Workflows.Workflows)(workflows), + ), + ), + ); + +it.effect("start passes an explicit null payload through and defaults an omitted one to {}", () => + Effect.gen(function* () { + const payloads: Array = []; + yield* Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + for (const input of [{ input: null }, {}]) { + yield* toolkit + .handle("t3_workflow", { + action: "start", + workflow: "echo", + idempotencyKey: "trial", + ...input, + }) + .pipe(Stream.unwrap, Stream.runCollect); + } + }).pipe( + Effect.provide( + handlersWith({ + start: (_workflow, input) => + Effect.sync(() => { + payloads.push(input); + return { runId: "run-1" }; + }), + get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), + }), + ), + ); + expect(payloads).toEqual([null, {}]); + }), +); + +it.effect("signal refuses a run destination mixed with a channel destination", () => + Effect.gen(function* () { + const delivered: Array = []; + const results = yield* Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + return yield* Effect.forEach( + [ + { runId: "run-1", wait: "review", channel: "other" }, + { workflow: "other", channel: "other", runId: "run-1" }, + { runId: "run-1", wait: "review" }, + ], + (address) => + toolkit + .handle("t3_workflow", { action: "signal", value: { choice: "yes" }, ...address }) + .pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((parts) => parts.at(-1)?.result), + ), + ); + }).pipe( + Effect.provide( + handlersWith({ + signal: (address) => + Effect.sync(() => { + delivered.push(address); + return "delivered" as const; + }), + }), + ), + ); + for (const result of results.slice(0, -1)) { + expect(result).toMatchObject({ code: "invalid_request" }); + } + expect(results.at(-1)).toEqual({ delivery: "delivered" }); + expect(delivered).toEqual([{ runId: "run-1", wait: "review" }]); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index fe19b06108480..7ebc6ac0cf7a4 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -52,12 +52,19 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { const name = yield* required(input.workflow, "workflow"); const idempotencyKey = yield* required(input.idempotencyKey, "idempotencyKey"); const { runId } = yield* workflows - .start(name, input.input ?? {}, { idempotencyKey }) + .start(name, input.input === undefined ? {} : input.input, { idempotencyKey }) .pipe(Effect.mapError(refused)); return yield* workflows.get(runId).pipe(Effect.mapError(refused)); } if (input.action === "signal") { const value = yield* required(input.value, "value"); + const byRun = input.runId !== undefined || input.wait !== undefined; + const byChannel = input.workflow !== undefined || input.channel !== undefined; + if (byRun && byChannel) { + return yield* invalid( + "Address a signal with `runId` and `wait`, or with `workflow` and `channel`, not both.", + ); + } const address = input.runId !== undefined && input.wait !== undefined ? { runId: input.runId, wait: input.wait } diff --git a/apps/server/src/mcp/toolkits/workflow/tools.test.ts b/apps/server/src/mcp/toolkits/workflow/tools.test.ts new file mode 100644 index 0000000000000..929d205cce874 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/tools.test.ts @@ -0,0 +1,14 @@ +import { expect, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; + +import { WorkflowToolkit } from "./tools.ts"; + +it("keeps exact wait names, store keys and channels", () => { + const decode = Schema.decodeUnknownSync(WorkflowToolkit.tools.t3_workflow.parametersSchema); + expect(decode({ action: "signal", runId: "run-1", wait: "review " }).wait).toBe("review "); + expect(() => decode({ action: "signal", runId: "run-1", wait: " " })).toThrow(); + expect(decode({ action: "store", key: "team " }).key).toBe("team "); + expect(() => decode({ action: "store_set", key: " ", value: 1 })).toThrow(); + expect(decode({ action: "signal", workflow: "w", channel: "review " }).channel).toBe("review "); + expect(() => decode({ action: "signal", workflow: "w", channel: " " })).toThrow(); +}); diff --git a/apps/server/src/mcp/toolkits/workflow/tools.ts b/apps/server/src/mcp/toolkits/workflow/tools.ts index fa01dfb7c5712..40f6cb36ffccc 100644 --- a/apps/server/src/mcp/toolkits/workflow/tools.ts +++ b/apps/server/src/mcp/toolkits/workflow/tools.ts @@ -10,6 +10,11 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts"; export const WORKFLOW_READ_ACTIONS = ["list", "read", "questions", "store"] as const; +// Wait names, store keys and channels match exactly, so they keep their spaces. +const ExactName = Schema.String.check( + Schema.makeFilter((name: string) => name.trim().length > 0, { expected: "a non-blank string" }), +); + const WorkflowTool = Tool.make("t3_workflow", { description: "Durable workflow runs on this server. start: `workflow`, `input`, `idempotencyKey` (same key, same run). list: runs, by `status`. read: one run and its steps. questions: what runs ask a person. hooks: the URL paths that start runs. store: what workflows keep, under keys starting with `key`; store_set a `key` to `value`; store_delete. signal: wake a wait with `value`, addressed by `runId` and `wait`, or by `workflow` and `channel`; answers a question as `{choice, reason?}`. resume: run a paused run's failed step again. cancel.", @@ -29,9 +34,9 @@ const WorkflowTool = Tool.make("t3_workflow", { idempotencyKey: Schema.optional(TrimmedNonEmptyString), runId: Schema.optional(TrimmedNonEmptyString), status: Schema.optional(WorkflowRunStatus), - wait: Schema.optional(TrimmedNonEmptyString), - key: Schema.optional(TrimmedNonEmptyString), - channel: Schema.optional(TrimmedNonEmptyString), + wait: Schema.optional(ExactName), + key: Schema.optional(ExactName), + channel: Schema.optional(ExactName), value: Schema.optional(Schema.Json), signalId: Schema.optional( TrimmedNonEmptyString.annotate({ diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts index 06e7763023841..49f6c1c5c6b5a 100644 --- a/apps/server/src/milestones/MilestoneEvents.test.ts +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -128,7 +128,7 @@ type JsonRpcResponse = { readonly error?: { readonly code: number; readonly data?: unknown }; }; -const serve = Effect.gen(function* () { +const serveWith = Effect.fnUntraced(function* (settings: { readonly workflowsEnabled: boolean }) { const revoked = yield* Deferred.make(); const deliveries = yield* Queue.unbounded(); const replies = new Set(); @@ -164,7 +164,7 @@ const serve = Effect.gen(function* () { }), ), ), - Layer.provide(ServerSettings.layerTest()), + Layer.provide(ServerSettings.layerTest(settings)), Layer.provide( Layer.mock(SessionStore.SessionStore)({ cookieName: "t3-session", @@ -285,6 +285,7 @@ const serve = Effect.gen(function* () { subscribe, }; }); +const serve = serveWith({ workflowsEnabled: true }); const layerTest = Layer.mergeAll( MilestoneHub.layer, @@ -330,6 +331,18 @@ it.effect("advertises the extension and lists each milestone type to outside cli }).pipe(Effect.scoped, Effect.provide(layerTest)), ); +it.effect("lists workflow event types only while Labs → Workflows is on", () => + Effect.gen(function* () { + const { call } = yield* serveWith({ workflowsEnabled: false }); + const { events } = (yield* call("events/list")).result!; + const names = (events as ReadonlyArray<{ name: string }>).map((event) => event.name); + expect(names).toHaveLength(6); + expect(names.some((name) => name.startsWith("workflow."))).toBe(false); + const poll = yield* call("events/poll", { name: "workflow.run_ended", cursor: null }); + expect(poll.error).toBeDefined(); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + it.effect("polls from now, then pages forward and says when a cursor fell behind", () => Effect.gen(function* () { const hub = yield* MilestoneHub.MilestoneHub; diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 72573a28fb15a..269258b3101f2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -25,10 +25,12 @@ import { assert, beforeAll, describe, it } from "@effect/vitest"; import { CheckpointId, EnvironmentId, + MessageId, type ModelSelection, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, + RunId, ThreadId, type OrchestrationV2ProviderThread, type OrchestrationV2TurnItem, @@ -2957,10 +2959,161 @@ describe("AcpAdapterV2", () => { (error as ProviderAdapter.ProviderAdapterTurnStartError).cause, ProviderAdapter.ProviderCompactionUnsupportedError, ); + assert.isTrue( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + ); } }).pipe(Effect.provide(layerTest)), ); + // A start that cannot reopen its session may be on a session the agent lost. It is not a refusal + // before the prompt, so the server's recovery for an unusable session still runs. + it.live("does not mark a start whose session failed to reopen as refused before its prompt", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("acp-test-reopen-failure"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + environment: () => ({ T3_ACP_FAIL_LOAD_SESSION: "1" }), + }), + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-reopen-failure"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-reopen-failure"), + modelSelection, + runtimePolicy, + }); + const thread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); + const lostThread: OrchestrationV2ProviderThread = { + ...thread, + nativeThreadRef: { driver: ACP_TEST_DRIVER, nativeId: "lost-session", strength: "strong" }, + }; + const now = yield* DateTime.now; + const error = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread: lostThread, + instanceId, + runtimePolicy, + now, + ordinal: 1, + }), + ) + .pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError); + assert.notEqual( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + true, + ); + const methods = yield* pollProtocolMethods(protocolEvents); + assert.isTrue(methods.includes("session/load") || methods.includes("session/resume")); + assert.notInclude(methods, "session/prompt"); + }).pipe(Effect.provide(layerTest)), + ); + + // Only refusals that leave the session usable mark a start as refused before its prompt. A setup + // step other than the model can fail because the session is gone. + it.live("does not mark a start whose session setup failed as refused before its prompt", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("acp-test-setup-failure"); + const threadId = ThreadId.make("thread-acp-setup-failure"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + environment: { T3_ACP_FAIL_SET_MODE_CONFIG_OPTION: "1" }, + }), + }, + selfInvocation: yield* resolveSelfInvocation(), + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const opened = { instanceId, model: "composer-2" } as const; + const withMode = { + instanceId, + model: "composer-2", + options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: "code" }], + } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-setup-failure"), + modelSelection: opened, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: opened, + runtimePolicy, + }); + const now = yield* DateTime.now; + const error = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal: 1, + modelSelection: withMode, + }), + ) + .pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError); + assert.notInstanceOf( + (error as ProviderAdapter.ProviderAdapterTurnStartError).cause, + ProviderAdapter.ProviderCompactionUnsupportedError, + ); + assert.notEqual( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + true, + ); + // The start reached the mode step the agent rejected, and sent no prompt. + const outgoing = Array.from(yield* Queue.takeAll(protocolEvents)).filter( + (event) => event.direction === "outgoing", + ); + assert.isTrue( + outgoing.some( + (event) => + rawProtocolMethod(event) === "session/set_config_option" && + rawProtocolRequestParam(event, "configId") === "mode", + ), + ); + assert.notInclude(outgoing.map(rawProtocolMethod), "session/prompt"); + }).pipe(Effect.provide(layerTest)), + ); + it.live("reapplies a selection after a switch away from it failed partway", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -7313,11 +7466,9 @@ describe("AcpAdapterV2", () => { const event = yield* Queue.take(events); if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) break; } - const snapshotBeforeRollback = yield* runtime.readThreadSnapshot({ providerThread }); - const rolledBack = yield* runtime.rollbackThread({ providerThread: { ...providerThread, appThreadId: rollbackThreadId }, - providerThreadTurns: snapshotBeforeRollback.providerTurns, + providerThreadTurns: [], target: { type: "thread_start", checkpointId: CheckpointId.make("checkpoint-acp-rollback-session"), @@ -7325,7 +7476,6 @@ describe("AcpAdapterV2", () => { }, }); assert.isString(rolledBack.providerThread.nativeThreadRef?.nativeId); - assert.deepEqual(rolledBack.providerTurns, []); assert.equal( runtimeInputs[1]?.processEnvironment?.T3_ACP_MCP_AUTHORIZATION, "Bearer rollback-target-token", @@ -7349,7 +7499,6 @@ describe("AcpAdapterV2", () => { const snapshotAfterRollback = yield* runtime.readThreadSnapshot({ providerThread: rolledBack.providerThread, }); - assert.deepEqual(snapshotAfterRollback.providerTurns, []); assert.deepEqual(snapshotAfterRollback.messages, []); const sessionEventsBeforeSecondTurn = sessionEventCount; @@ -12639,6 +12788,798 @@ describe("AcpAdapterV2", () => { ]); }).pipe(Effect.provide(layerTest)), ); + + it.live( + "delivers MCP appContext once per session, skips slash commands, and resends after unsuccessful turns, compaction, or runtime restart", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + let runtimeCount = 0; + let cancelCalled: Deferred.Deferred | undefined; + const prompts: Array = []; + const queuedResponses: Array< + | { readonly _tag: "immediate"; readonly response: EffectAcpSchema.PromptResponse } + | { + readonly _tag: "gated"; + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred; + } + > = []; + const instanceId = ProviderInstanceId.make("acp-test-app-context-lifecycle"); + const threadId = ThreadId.make("thread-acp-app-context-lifecycle"); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + restartRuntimeAfterInterrupt: true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => { + runtimeCount += 1; + return { + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + cancel: Effect.suspend(() => + cancelCalled === undefined + ? Effect.void + : Deferred.succeed(cancelCalled, undefined).pipe(Effect.asVoid), + ), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = queuedResponses.shift(); + if (next === undefined) { + return { stopReason: "end_turn" as const }; + } + if (next._tag === "immediate") { + return next.response; + } + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }; + }, + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-app-context-lifecycle"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + let ordinal = 0; + const runTurn = (input: { + readonly text: string; + readonly note: string; + readonly response?: EffectAcpSchema.PromptResponse; + }) => + Effect.gen(function* () { + ordinal += 1; + if (input.response !== undefined) { + queuedResponses.push({ _tag: "immediate", response: input.response }); + } + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + messageText: input.text, + }), + appContext: [{ key: "mcp_app_item-1", text: input.note }], + }); + const events = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + return { + prompt: prompts.at(-1) ?? "", + status: terminal?.type === "turn.terminal" ? terminal.status : null, + }; + }); + + const tag = (note: string) => `${note}`; + + // An unsuccessful stop reason must not mark appContext delivered. + const refusedTurn = yield* runTurn({ + text: "Refused attempt", + note: "Created Jira issue PROJ-42", + response: { stopReason: "refusal" }, + }); + assert.include(refusedTurn.prompt, tag("Created Jira issue PROJ-42")); + + // Interrupted turns must not mark appContext delivered even if the prompt answers end_turn. + const interruptedStarted = yield* Deferred.make(); + const interruptedGate = yield* Deferred.make(); + cancelCalled = yield* Deferred.make(); + queuedResponses.push({ + _tag: "gated", + started: interruptedStarted, + gate: interruptedGate, + }); + ordinal += 1; + const interruptedOrdinal = ordinal; + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: interruptedOrdinal, + messageText: "Interrupted attempt", + }), + appContext: [{ key: "mcp_app_item-1", text: "Created Jira issue PROJ-42" }], + }); + yield* Deferred.await(interruptedStarted); + assert.include(prompts.at(-1) ?? "", tag("Created Jira issue PROJ-42")); + const interruptFiber = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId( + instanceId, + `${sessionId}:turn:${interruptedOrdinal}`, + ), + }), + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelCalled); + yield* Deferred.succeed(interruptedGate, { stopReason: "end_turn" }); + yield* Fiber.join(interruptFiber); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Native slash commands skip appContext injection; the next normal turn sends it. + const slashTurn = yield* runTurn({ + text: " /repro-skill", + note: "Created Jira issue PROJ-42", + }); + assert.equal(slashTurn.status, "completed"); + assert.notInclude(slashTurn.prompt, "external_mcp_app_item-1"); + + const deliveredTurn = yield* runTurn({ + text: "What did the app report?", + note: "Created Jira issue PROJ-42", + }); + assert.equal(deliveredTurn.status, "completed"); + assert.include(deliveredTurn.prompt, tag("Created Jira issue PROJ-42")); + + // Unchanged note is not resent; changed note is sent once. + const unchangedTurn = yield* runTurn({ + text: "Follow up", + note: "Created Jira issue PROJ-42", + }); + assert.notInclude(unchangedTurn.prompt, "external_mcp_app_item-1"); + + const changedTurn = yield* runTurn({ + text: "Updated check", + note: "Updated Jira issue PROJ-43", + }); + assert.include(changedTurn.prompt, tag("Updated Jira issue PROJ-43")); + + const afterChangeTurn = yield* runTurn({ + text: "Second follow up", + note: "Updated Jira issue PROJ-43", + }); + assert.notInclude(afterChangeTurn.prompt, "external_mcp_app_item-1"); + + // Compaction clears delivered appContext so the next turn resends it. + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "compaction_update", + compactionId: "compact-app-context", + status: "completed", + }, + }); + const postCompactTurn = yield* runTurn({ + text: "After compaction", + note: "Updated Jira issue PROJ-43", + }); + assert.include(postCompactTurn.prompt, tag("Updated Jira issue PROJ-43")); + + const afterPostCompactTurn = yield* runTurn({ + text: "Already resent after compaction", + note: "Updated Jira issue PROJ-43", + }); + assert.notInclude(afterPostCompactTurn.prompt, "external_mcp_app_item-1"); + + // Runtime restart clears delivered appContext even when resuming the same session id. + const restartStarted = yield* Deferred.make(); + const restartGate = yield* Deferred.make(); + cancelCalled = yield* Deferred.make(); + queuedResponses.push({ + _tag: "gated", + started: restartStarted, + gate: restartGate, + }); + ordinal += 1; + const restartOrdinal = ordinal; + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: restartOrdinal, + messageText: "Trigger restart", + }), + appContext: [{ key: "mcp_app_item-1", text: "Updated Jira issue PROJ-43" }], + }); + yield* Deferred.await(restartStarted); + const restartInterruptFiber = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${restartOrdinal}`), + }), + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelCalled); + yield* Deferred.succeed(restartGate, { stopReason: "cancelled" }); + yield* Fiber.join(restartInterruptFiber); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const postRestartTurn = yield* runTurn({ + text: "After runtime restart", + note: "Updated Jira issue PROJ-43", + }); + assert.isAbove(runtimeCount, 1); + assert.include(postRestartTurn.prompt, tag("Updated Jira issue PROJ-43")); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "delivers changed appContext on steersWithPrompt and preserves undelivered notes on slash or failed steer", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const prompts: Array = []; + const promptGates: Array<{ + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >; + }> = []; + const queueGate = () => + Effect.gen(function* () { + const entry = { + started: yield* Deferred.make(), + gate: yield* Deferred.make< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >(), + }; + promptGates.push(entry); + return entry; + }); + const instanceId = ProviderInstanceId.make("acp-test-app-context-steer-prompt"); + const threadId = ThreadId.make("thread-acp-app-context-steer-prompt"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + steersWithPrompt: () => true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = promptGates.shift(); + if (next === undefined) return { stopReason: "end_turn" as const }; + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-app-context-steer-prompt", + ), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + const tag = (note: string) => `${note}`; + const providerTurnIdFor = (ordinal: number) => + idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${ordinal}`), + }); + const steer = (ordinal: number, text: string, note: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId: providerTurnIdFor(ordinal), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`steer-${ordinal}-${prompts.length}`), + text, + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + + const turn1Initial = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + messageText: "Start turn 1", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note A" }], + }); + yield* Deferred.await(turn1Initial.started); + assert.include(prompts.at(-1) ?? "", tag("Note A")); + + // Unchanged note does not repeat on steer. + const steer1 = yield* queueGate(); + yield* steer(1, "Keep going", "Note A"); + yield* Deferred.await(steer1.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(turn1Initial.gate, { stopReason: "end_turn" }); + + // Slash steer skips appContext so the next normal steer carries the changed note. + const steerSlash = yield* queueGate(); + yield* steer(1, "/status", "Note B"); + yield* Deferred.await(steerSlash.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(steer1.gate, { stopReason: "end_turn" }); + + const steerChanged = yield* queueGate(); + yield* steer(1, "Use updated note", "Note B"); + yield* Deferred.await(steerChanged.started); + assert.include(prompts.at(-1) ?? "", tag("Note B")); + yield* Deferred.succeed(steerSlash.gate, { stopReason: "end_turn" }); + + // Second steer with the same note does not resend it. + const steerSame = yield* queueGate(); + yield* steer(1, "One more detail", "Note B"); + yield* Deferred.await(steerSame.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(steerChanged.gate, { stopReason: "end_turn" }); + yield* Deferred.succeed(steerSame.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 2 inherits delivered Note B; a failed prompt steer with Note C does not mark Note C delivered. + const turn2Initial = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "Start turn 2", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note B" }], + }); + yield* Deferred.await(turn2Initial.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + + const steerFailed = yield* queueGate(); + yield* steer(2, "Try Note C", "Note C"); + yield* Deferred.await(steerFailed.started); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + yield* Deferred.succeed(turn2Initial.gate, { stopReason: "end_turn" }); + yield* Deferred.fail( + steerFailed.gate, + new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Steer prompt rejected", + method: "session/prompt", + }), + ); + const turn2Events = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const turn2Terminal = turn2Events.at(-1); + assert.equal( + turn2Terminal?.type === "turn.terminal" ? turn2Terminal.status : null, + "failed", + ); + + // Turn 3 must resend Note C because the failed steer did not deliver it. + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageText: "Start turn 3", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note C" }], + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "delivers changed appContext on native flavor.steering and preserves undelivered notes on failure", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const prompts: Array = []; + const steeredTexts: Array = []; + const steerOutcomes: Array< + | { readonly _tag: "accept" } + | { readonly _tag: "fail" } + | { + readonly _tag: "waitId"; + readonly steerId: string; + readonly sent: Deferred.Deferred; + } + > = []; + const promptGates: Array<{ + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred; + }> = []; + const queueGate = () => + Effect.gen(function* () { + const entry = { + started: yield* Deferred.make(), + gate: yield* Deferred.make(), + }; + promptGates.push(entry); + return entry; + }); + const instanceId = ProviderInstanceId.make("acp-test-app-context-native-steer"); + const threadId = ThreadId.make("thread-acp-app-context-native-steer"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: { + ...AcpProviderCapabilitiesV2, + turns: { + ...AcpProviderCapabilitiesV2.turns, + supportsActiveSteering: true, + }, + }, + steering: { + send: (_runtime, _sessionId, text) => + Effect.gen(function* () { + steeredTexts.push(text); + const outcome = steerOutcomes.shift() ?? { _tag: "accept" as const }; + if (outcome._tag === "fail") { + return yield* new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Steering rejected", + method: "_test/steer", + }); + } + if (outcome._tag === "waitId") { + yield* Deferred.succeed(outcome.sent, undefined); + return outcome.steerId; + } + return undefined; + }), + injectedSteerId: (notification) => { + if (notification.update.sessionUpdate !== "session_info_update") return undefined; + const meta = notification.update._meta as + | { readonly injectedSteerId?: string } + | undefined; + return meta?.injectedSteerId; + }, + }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = promptGates.shift(); + if (next === undefined) return { stopReason: "end_turn" as const }; + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-app-context-native-steer", + ), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + const tag = (note: string) => `${note}`; + const providerTurnIdFor = (ordinal: number) => + idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${ordinal}`), + }); + const steer = (ordinal: number, text: string, note: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId: providerTurnIdFor(ordinal), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`native-steer-${ordinal}-${steeredTexts.length}`), + text, + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + + const turn1 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + messageText: "Start native turn 1", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note A" }], + }); + yield* Deferred.await(turn1.started); + assert.include(prompts.at(-1) ?? "", tag("Note A")); + + // Unchanged note is omitted on native steer. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "Keep working", "Note A"); + assert.equal(steeredTexts.at(-1), "Keep working"); + + // Slash steer skips appContext injection. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "/status", "Note B"); + assert.equal(steeredTexts.at(-1), "/status"); + + // Rejected steering.send must not mark Note B delivered. + steerOutcomes.push({ _tag: "fail" }); + const failedExit = yield* Effect.exit(steer(1, "Failed steer", "Note B")); + assert.isTrue(Exit.isFailure(failedExit)); + assert.include(steeredTexts.at(-1) ?? "", tag("Note B")); + + // Next steer with Note B resends it and marks it delivered once accepted. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "Retry Note B", "Note B"); + assert.include(steeredTexts.at(-1) ?? "", tag("Note B")); + + // Repeated steer with Note B omits it. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "After Note B", "Note B"); + assert.equal(steeredTexts.at(-1), "After Note B"); + + // Completing turn 1 must not clobber Note B with Turn 1's earlier Note A. + yield* Deferred.succeed(turn1.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const turn2 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "Start native turn 2", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note B" }], + }); + yield* Deferred.await(turn2.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + + // A queued steer whose turn settles before injection must not mark Note C delivered. + const droppedSteerSent = yield* Deferred.make(); + steerOutcomes.push({ + _tag: "waitId", + steerId: "steer-dropped-1", + sent: droppedSteerSent, + }); + const droppedSteerFiber = yield* Effect.forkScoped( + Effect.exit(steer(2, "Dropped steer", "Note C")), + ); + yield* Deferred.await(droppedSteerSent); + yield* Deferred.succeed(turn2.gate, { stopReason: "end_turn" }); + const droppedExit = yield* Fiber.join(droppedSteerFiber); + assert.isTrue(Exit.isFailure(droppedExit)); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 3 must resend Note C; also verify injected steerId delivery works when notified. + const turn3 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageText: "Start native turn 3", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note C" }], + }); + yield* Deferred.await(turn3.started); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + + const injectedSteerSent = yield* Deferred.make(); + steerOutcomes.push({ + _tag: "waitId", + steerId: "steer-injected-1", + sent: injectedSteerSent, + }); + const injectedSteerFiber = yield* Effect.forkScoped(steer(3, "Injected steer", "Note D")); + yield* Deferred.await(injectedSteerSent); + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "session_info_update", + _meta: { injectedSteerId: "steer-injected-1" }, + }, + }); + yield* Fiber.join(injectedSteerFiber); + assert.include(steeredTexts.at(-1) ?? "", tag("Note D")); + yield* Deferred.succeed(turn3.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 4 sees Note D already delivered. + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 4, + messageText: "Start native turn 4", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note D" }], + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 37c6f74cac2d6..ed7c69d39cd81 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -13,7 +13,12 @@ import { ThreadId, } from "@t3tools/contracts"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { + compactDynamicToolOutput, + htmlRenderFromToolItem, + previewRecordingIdFromToolItem, + sentMessageFromToolItem, +} from "@t3tools/shared/toolOutput"; import * as Digest from "effect/crypto/Digest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; @@ -1038,6 +1043,330 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined); }).pipe(Effect.provide(layerSession)), ); + + it.effect( + "recovers T3 MCP tool results across omitted outputs, replays, errors, and turn boundaries", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let promptIndex = 0; + let turn1Epoch = 0; + const instanceId = ProviderInstanceId.make("antigravity-mcp-result-test"); + const threadId = ThreadId.make("thread-antigravity-mcp-result"); + const statusUpdate = "### Current Status\n\nAll checks are passing."; + const inProgressText = "Streamed while running."; + const lateText = "Confirmed on a later completion."; + const lateErrorText = "Late explicit error."; + const unfinishedText = "Still running when turn ended."; + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + profileDirectory: unusedProfileDirectory, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptIndex += 1; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update, + }), + ); + const startTool = ( + toolCallId: string, + toolName: string, + rawInput: Record, + ) => + send({ + sessionUpdate: "tool_call", + toolCallId, + title: `Run mcp_t3-code_${toolName}`, + kind: "other", + status: "in_progress", + rawInput, + }); + const updateTool = ( + toolCallId: string, + status: "in_progress" | "completed" | "failed", + rawOutput?: unknown, + ) => + send({ + sessionUpdate: "tool_call_update", + toolCallId, + status, + ...(rawOutput === undefined ? {} : { rawOutput }), + }); + const recordSend = (message: string) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ); + + if (promptIndex === 2) { + // A Turn 1 handler finishing after Turn 1 closed must be rejected by epoch. + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: unfinishedText }, + { sentMessage: unfinishedText }, + { epoch: turn1Epoch }, + ); + yield* startTool("turn2-leaked-check", "send_to_user", { + message: unfinishedText, + }); + yield* updateTool("turn2-leaked-check", "completed", "Summary of turn 2"); + return { stopReason: "end_turn" as const }; + } + + turn1Epoch = yield* mcpSessions.toolResultEpoch(threadId); + + // agy 1.5.x adds toolSummary and omits output on completion, then may replay. + yield* startTool("send-empty", "send_to_user", { + message: statusUpdate, + toolSummary: "Send status update", + }); + yield* recordSend(statusUpdate); + yield* updateTool("send-empty", "completed"); + yield* updateTool("send-empty", "in_progress"); + yield* updateTool("send-empty", "completed", "Summary replay"); + + // Streaming output during in_progress still drains on completion. + yield* startTool("send-streaming", "send_to_user", { message: inProgressText }); + yield* recordSend(inProgressText); + yield* updateTool("send-streaming", "in_progress", { + sentMessage: inProgressText, + }); + yield* updateTool("send-streaming", "completed", { + sentMessage: inProgressText, + }); + yield* startTool("send-streaming-unpublished", "send_to_user", { + message: inProgressText, + }); + yield* updateTool("send-streaming-unpublished", "completed"); + + // Explicit MCP error preserves diagnostic content across summary replays. + yield* startTool("send-errored", "send_to_user", { message: "Denied" }); + yield* updateTool("send-errored", "completed", { + result: { + isError: true, + structuredContent: { sentMessage: "Denied" }, + content: [{ type: "text", text: "Denied by policy" }], + }, + }); + yield* updateTool("send-errored", "completed", "Summary of denied"); + + // Initial miss -> late explicit success or error still drains its new record. + yield* startTool("send-late", "send_to_user", { message: lateText }); + yield* updateTool("send-late", "completed"); + yield* recordSend(lateText); + yield* updateTool("send-late", "completed", { sentMessage: lateText }); + yield* startTool("send-late-unpublished", "send_to_user", { + message: lateText, + }); + yield* updateTool("send-late-unpublished", "completed"); + + yield* startTool("send-late-error", "send_to_user", { message: lateErrorText }); + yield* updateTool("send-late-error", "completed"); + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: lateErrorText }, + { isError: true }, + ); + yield* updateTool("send-late-error", "completed", { + result: { isError: true, content: [{ type: "text", text: "Denied late" }] }, + }); + yield* startTool("send-late-error-sibling", "send_to_user", { + message: lateErrorText, + }); + yield* updateTool("send-late-error-sibling", "completed"); + + // Empty-input completion that misses still recovers once a later completion brings arguments, + // and replacing arguments on the same call ID re-matches against the new arguments. + yield* startTool("send-late-args", "send_to_user", {}); + yield* recordSend("First args"); + yield* updateTool("send-late-args", "completed"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "First args" }, + }); + yield* recordSend("Second args"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "Second args" }, + rawOutput: "Summary of second", + }); + + // Bare failure without reported output must not consume a sibling call's cached result. + yield* startTool("send-bare-fail", "send_to_user", { message: "Shared ready" }); + yield* startTool("send-bare-fail-sibling", "send_to_user", { + message: "Shared ready", + }); + yield* recordSend("Shared ready"); + yield* updateTool("send-bare-fail", "failed"); + yield* updateTool("send-bare-fail-sibling", "completed"); + + // preview_recording_stop recovers its recording id. + yield* startTool("recording-stop", "preview_recording_stop", { + toolSummary: "Stop preview recording", + }); + yield* mcpSessions.recordToolResult( + threadId, + "preview_recording_stop", + {}, + { id: `${threadId}-rec-1` }, + ); + yield* updateTool("recording-stop", "completed"); + + // Unfinished call projected at turn end must not claim or leak to Turn 2. + yield* startTool("send-unfinished", "send_to_user", { + message: unfinishedText, + }); + yield* recordSend(unfinishedText); + + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-mcp-result"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal, + modelSelection, + }), + ); + return Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + }); + const turn1Events = yield* runTurn(1); + const turn2Events = yield* runTurn(2); + const toolIn = (events: ReadonlyArray<(typeof turn1Events)[number]>, nativeId: string) => { + const event = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId, + ); + return event?.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? event.turnItem + : undefined; + }; + const tool = (nativeId: string) => toolIn(turn1Events, nativeId); + + const sendEmptyUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-empty" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.deepEqual( + sendEmptyUpdates.map((update) => sentMessageFromToolItem(update)), + [statusUpdate, statusUpdate], + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming")!), inProgressText); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming-unpublished")!), undefined); + const erroredUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-errored" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.strictEqual(erroredUpdates.length, 2); + for (const update of erroredUpdates) { + assert.strictEqual(compactDynamicToolOutput(update.output)?.isError, true); + assert.include(JSON.stringify(update.output), "Denied by policy"); + assert.strictEqual(sentMessageFromToolItem(update), undefined); + } + assert.strictEqual(sentMessageFromToolItem(tool("send-late")!), lateText); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-unpublished")!), undefined); + const lateErrorSibling = tool("send-late-error-sibling"); + assert.isDefined(lateErrorSibling); + assert.strictEqual(lateErrorSibling.status, "completed"); + assert.strictEqual(lateErrorSibling.output, undefined); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-args")!), "Second args"); + assert.strictEqual( + sentMessageFromToolItem(tool("send-bare-fail-sibling")!), + "Shared ready", + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-unfinished")!), undefined); + assert.strictEqual( + sentMessageFromToolItem(toolIn(turn2Events, "turn2-leaked-check")!), + undefined, + ); + assert.strictEqual( + previewRecordingIdFromToolItem(tool("recording-stop")!), + `${threadId}-rec-1`, + ); + }).pipe(Effect.provide(layerSession)), + ); }); /** diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index ced2d1b25ad08..a39fb0178156e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -62,6 +62,8 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as SecureRandom from "effect/crypto/SecureRandom"; +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"; @@ -116,7 +118,10 @@ import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEve import { AGENT_FEEDBACK_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; -import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; +import { + makeProviderFailure, + PROVIDER_RETRY_BUDGET_MS, +} from "@t3tools/provider-core/server/failure"; import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; @@ -10663,6 +10668,76 @@ describe("ClaudeAdapterV2 background wake turns", () => { : [], ); + it.effect("measures Claude context from the last main-model pass in an advisor response", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-advisor-context"), + text: "Continue.", + attachments: [], + }), + ); + const usage = { + input_tokens: 4, + cache_read_input_tokens: 1087272, + cache_creation_input_tokens: 1222, + output_tokens: 711, + iterations: [ + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 543529, + cache_creation_input_tokens: 214, + output_tokens: 268, + }, + { type: "advisor_message", input_tokens: 545497, output_tokens: 3144 }, + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 543743, + cache_creation_input_tokens: 1008, + output_tokens: 443, + }, + ], + }; + for (const frame of [ + usageStreamFrame({ + type: "message_start", + message: { id: "msg_advisor", usage: zeroUsage }, + }), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage, + }), + usageSnapshotFrame("msg_snapshot_only", "00000000-0000-4000-8000-000000000690", { + ...zeroUsage, + iterations: [ + ...usage.iterations, + { type: "advisor_message", input_tokens: 547000, output_tokens: 25 }, + ], + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000691", result: "Done." }), + ]) + yield* Queue.offer(harness.sdkMessages, frame); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual(reportedContextTokens(harness.events), [545196, 545196]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("reports context from final stream usage when the request starts at zero", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; @@ -11426,6 +11501,213 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + describe("warm process after the session changed outside T3", () => { + const firstReply = "00000000-0000-4000-8000-000000000c01"; + const secondReply = "00000000-0000-4000-8000-000000000c02"; + const terminalPrompt = "00000000-0000-4000-8000-000000000c03"; + const terminalReply = "00000000-0000-4000-8000-000000000c04"; + const line = (entry: object) => + `${JSON.stringify({ isSidechain: false, sessionId: WAKE_NATIVE_SESSION, ...entry })}\n`; + const entry = ( + type: "user" | "assistant", + uuid: string, + parentUuid: string | null, + content: unknown, + extra?: object, + ) => line({ type, uuid, parentUuid, message: { role: type, content }, ...extra }); + const t3Turn = (promptUuid: string) => + entry("user", promptUuid, null, "Request 1") + + entry("assistant", firstReply, promptUuid, [{ type: "text", text: "Working." }]) + + entry("assistant", secondReply, firstReply, [{ type: "text", text: "Done." }]); + const terminalExchange = + entry("user", terminalPrompt, secondReply, "Typed in the terminal") + + entry("assistant", terminalReply, terminalPrompt, [{ type: "text", text: "Answered." }]); + + // Streams one T3 turn of two reply blocks, writes the transcript, then starts the next turn. + const nextTurnAfter = Effect.fnUntraced(function* (input: { + readonly transcript: ((promptUuid: string) => string) | null; + readonly backgroundShell?: boolean; + readonly scheduledWakeup?: boolean; + readonly wakeFiresDuringRead?: boolean; + readonly pinnedHead?: string; + }) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-stale-" }); + const projectDir = path.join(configDir, "projects", "-workspace"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + const transcriptOpened = yield* Deferred.make(); + const releaseTranscript = yield* Deferred.make(); + const heldFileSystem: FileSystem.FileSystem = { + ...fileSystem, + open: (filePath, options) => + filePath.endsWith(".jsonl") + ? Deferred.succeed(transcriptOpened, undefined).pipe( + Effect.andThen(Deferred.await(releaseTranscript)), + Effect.andThen(fileSystem.open(filePath, options)), + ) + : fileSystem.open(filePath, options), + }; + const harness = yield* makeWakeHarnessWithOptions({ + environment: { CLAUDE_CONFIG_DIR: configDir }, + freshQueueOnReopen: true, + }).pipe( + input.wakeFiresDuringRead === true + ? Effect.provideService(FileSystem.FileSystem, heldFileSystem) + : (effect) => effect, + ); + const providerThread = + input.pinnedHead === undefined + ? harness.providerThread + : { + ...harness.providerThread, + nativeConversationHeadRef: { + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeId: input.pinnedHead, + strength: "weak" as const, + }, + }; + const now = yield* DateTime.now; + const turn = (ordinal: number) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread, + now, + attemptId: RunAttemptId.make(`attempt-stale-process:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + }); + yield* harness.runtime.startTurn(turn(1)); + if (input.backgroundShell === true) yield* harness.offerAndWait(wakeTaskStarted); + if (input.scheduledWakeup === true || input.wakeFiresDuringRead === true) { + for (const frame of scheduleWakeupFrames({ + toolUseId: "toolu_stale_process_wakeup", + uuids: ["00000000-0000-4000-8000-000000000c05", "00000000-0000-4000-8000-000000000c06"], + toolInput: { delaySeconds: 3600, prompt: "check", reason: "wake", noop: false }, + scheduledFor: DateTime.toEpochMillis(now) + 3_600_000, + })) { + yield* harness.offerAndWait(frame); + } + } + yield* harness.offerAndWait(makeAssistantTextFrame({ uuid: firstReply, text: "Working." })); + yield* harness.offerAndWait(makeAssistantTextFrame({ uuid: secondReply, text: "Done." })); + yield* harness.offerAndWait(turnOneResult); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + if (input.transcript !== null) { + yield* fileSystem.writeFileString( + path.join(projectDir, `${WAKE_NATIVE_SESSION}.jsonl`), + input.transcript(harness.promptUuid(0)), + ); + } + if (input.wakeFiresDuringRead !== true) { + yield* harness.runtime.startTurn(turn(2)); + return harness; + } + yield* TestClock.adjust("1 hour"); + const nextTurn = yield* Effect.forkChild(harness.runtime.startTurn(turn(2))); + yield* Deferred.await(transcriptOpened); + yield* harness.offerAndWait(wakeTurnInit); + yield* Deferred.succeed(releaseTranscript, undefined); + yield* Fiber.join(nextTurn); + return harness; + }); + const layer = Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ); + + it.effect.each([ + { + name: "the session transcript gained messages outside T3", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + }, + { + // The terminal's rows alone are longer than the tail T3 reads first. + name: "a long terminal exchange followed its last message", + transcript: (promptUuid: string) => + t3Turn(promptUuid) + + entry("user", terminalPrompt, secondReply, "x".repeat(1_200_000)) + + entry("assistant", terminalReply, terminalPrompt, [ + { type: "text", text: "y".repeat(1_200_000) }, + ]), + }, + ])("replaces a warm process when $name", (row) => + Effect.gen(function* () { + const harness = yield* nextTurnAfter(row); + assert.lengthOf(harness.processQueues, 2, "the next turn must open a fresh process"); + assert.equal(harness.getOpenedOptions()?.resume, WAKE_NATIVE_SESSION); + assert.isUndefined(harness.getOpenedOptions()?.resumeSessionAt); + }).pipe(Effect.provide(layer)), + ); + + it.effect.each([ + { + name: "the file lags the stream", + transcript: (promptUuid: string) => + entry("user", promptUuid, null, "Request 1") + + entry("assistant", firstReply, promptUuid, [{ type: "text", text: "Working." }]), + }, + { + name: "only bookkeeping follows T3's reply", + transcript: (promptUuid: string) => + t3Turn(promptUuid) + + line({ + type: "system", + subtype: "turn_duration", + uuid: "sys-1", + parentUuid: secondReply, + }) + + line({ type: "last-prompt", leafUuid: secondReply }) + + entry("assistant", "side-1", secondReply, [{ type: "text", text: "x" }], { + isSidechain: true, + }) + + entry("user", "meta-1", secondReply, "Caveat", { isMeta: true }) + + entry("user", "stop-1", secondReply, "[Request interrupted by user]") + + JSON.stringify({ type: "user", uuid: "half-written", parentUuid: secondReply }).slice( + 0, + 30, + ), + }, + { name: "there is no transcript", transcript: null }, + { + name: "a pinned head decides where to resume", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + pinnedHead: firstReply, + }, + { + name: "replacing it would end background work", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + backgroundShell: true, + }, + { + name: "replacing it would cancel a scheduled wakeup", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + scheduledWakeup: true, + }, + { + name: "its scheduled wakeup fires while the transcript is read", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + wakeFiresDuringRead: true, + }, + { + // Longer than the tail T3 reads, and the process's own messages are not written yet. + name: "a long transcript's tail holds none of its messages", + transcript: () => + entry("user", "old-1", null, "x".repeat(1_200_000)) + + entry("assistant", "old-2", "old-1", [{ type: "text", text: "y".repeat(1_200_000) }]), + }, + ])("keeps the warm process when $name", (row) => + Effect.gen(function* () { + const harness = yield* nextTurnAfter(row); + assert.lengthOf(harness.processQueues, 1); + assert.lengthOf(harness.offeredMessages, 2); + }).pipe(Effect.provide(layer)), + ); + }); + // The passive row is the frame Claude 2.1.303 emits for a Stop hook returning a systemMessage. it.effect.each([ { name: "hides a passive summary", level: "notice", visible: false }, @@ -16825,6 +17107,82 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("releases the silence watch once Claude answers each request", () => + Effect.gen(function* () { + // Counts pending sleeps of the silence budget: each one holds the whole turn context. + const clock = yield* Clock.Clock; + let pendingWatches = 0; + const countingClock: Clock.Clock = { + currentTimeMillisUnsafe: () => clock.currentTimeMillisUnsafe(), + currentTimeMillis: clock.currentTimeMillis, + currentTimeNanosUnsafe: () => clock.currentTimeNanosUnsafe(), + currentTimeNanos: clock.currentTimeNanos, + monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(), + monotonicTimeNanos: clock.monotonicTimeNanos, + sleep: (duration) => + Duration.toMillis(duration) === PROVIDER_RETRY_BUDGET_MS + ? Effect.suspend(() => { + pendingWatches += 1; + return clock.sleep(duration); + }).pipe(Effect.ensuring(Effect.sync(() => (pendingWatches -= 1)))) + : clock.sleep(duration), + }; + yield* Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-silence-watch-released"), + text: "start again", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(0), + state: "started", + uuid: "00000000-0000-4000-8000-0000000007a0", + session_id: WAKE_NATIVE_SESSION, + }), + ); + for (let index = 1; index <= 5; index++) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "requesting", + uuid: `00000000-0000-4000-8000-0000000007a${index}`, + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "stream_event", + event: { type: "message_start", message: { id: `msg_watch_${index}` } }, + parent_tool_use_id: null, + session_id: WAKE_NATIVE_SESSION, + uuid: `00000000-0000-4000-8000-0000000007b${index}`, + }), + ); + } + assert.strictEqual(pendingWatches, 0, "answered requests left silence watches running"); + }).pipe(Effect.provideService(Clock.Clock, countingClock)); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #17531 a mod that holds a tool behind a focused pane must fail the turn, not hang it it.effect.each([ { case: "fails a turn whose mod requests focus for a pane T3 cannot show", focus: true }, @@ -19577,6 +19935,128 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("keeps a background subagent's card on the turn that launched it", () => + Effect.gen(function* () { + const FIRST_TASK = "task-card-turn-a"; + const FIRST_TOOL = "toolu-card-turn-a"; + const SECOND_TASK = "task-card-turn-b"; + const SECOND_TOOL = "toolu-card-turn-b"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-card-turn-1"), + text: "Audit in the background.", + attachments: [], + }), + ); + for (const frame of [ + makeSubagentTaskStartedFrame({ + taskId: FIRST_TASK, + toolUseId: FIRST_TOOL, + uuid: "00000000-0000-4000-8000-000000000a51", + }), + makeSubagentTaskStartedFrame({ + taskId: SECOND_TASK, + toolUseId: SECOND_TOOL, + uuid: "00000000-0000-4000-8000-000000000a52", + }), + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [ + { task_id: FIRST_TASK, task_type: "local_agent", description: "Audit" }, + { task_id: SECOND_TASK, task_type: "local_agent", description: "Audit" }, + ], + uuid: "00000000-0000-4000-8000-000000000a53", + session_id: WAKE_NATIVE_SESSION, + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a54", + result: "Auditing in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + yield* Queue.offer( + harness.sdkMessages, + makeSubagentNotificationFrame({ + taskId: FIRST_TASK, + toolUseId: FIRST_TOOL, + summary: "Audit done.", + uuid: "00000000-0000-4000-8000-000000000a55", + }), + ); + yield* harness.awaitContinuation(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-card-turn-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + for (const frame of [ + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: SECOND_TASK, + description: "Reading the last commits", + uuid: "00000000-0000-4000-8000-000000000a56", + session_id: WAKE_NATIVE_SESSION, + }), + makeSubagentNotificationFrame({ + taskId: SECOND_TASK, + toolUseId: SECOND_TOOL, + summary: "Audit done.", + uuid: "00000000-0000-4000-8000-000000000a57", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a58", + result: "Both auditors finished.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(2); + + const cards = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "subagent" + ? [event.turnItem] + : [], + ); + const turnIds = harness.events.flatMap((event) => + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], + ); + assert.equal(new Set(turnIds).size, 2); + assert.equal(new Set(cards.map((card) => card.subagentId)).size, 2); + assert.equal(cards.filter((card) => card.status === "completed").length, 2); + assert.deepEqual( + [...new Set(cards.map((card) => card.providerTurnId))], + [cards[0]?.providerTurnId], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // Claude reports a background subagent `completed` when its turn ends while // its own background shell still runs. When that shell finishes, Claude // resumes the subagent with a new task_started for the same task and launch @@ -21424,27 +21904,13 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("records a forked skill's model from its transcript instead of the parent's", () => - Effect.gen(function* () { - const harness = yield* makeWakeHarnessWithOptions({ - subagentModel: "claude-haiku-4-5-20251001", - }); - const now = yield* DateTime.now; - const parentModel = "claude-opus-4-6"; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-forked-skill-model"), - text: "/fork-probe go", - attachments: [], - modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: parentModel }, - }), - ); + it.effect.each([ + { + launch: "forked skill", + text: "/fork-probe go", // A `context: fork` skill has no Agent call and streams none of its own replies: // task_started carries no tool_use_id, and only its prompt echo names the fork. - for (const frame of [ + frames: [ claudeSdkFrame({ type: "system", subtype: "task_started", @@ -21475,28 +21941,93 @@ describe("ClaudeAdapterV2 background wake turns", () => { uuid: "00000000-0000-4000-8000-000000000233", session_id: WAKE_NATIVE_SESSION, }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.take(harness.terminalReceipts); + ], + }, + { + launch: "foreground Agent call with no streamed reply", + text: "Ask a subagent one thing.", + frames: [ + claudeSdkFrame({ + type: "assistant", + parent_tool_use_id: null, + message: { + model: "claude-opus-4-6", + id: "msg_unstreamed_model_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: "toolu-unstreamed-model", + name: "Agent", + input: { description: "One thing", prompt: "Check one thing." }, + }, + ], + }, + uuid: "00000000-0000-4000-8000-000000000235", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "task-unstreamed-model", + tool_use_id: "toolu-unstreamed-model", + description: "One thing", + task_type: "local_agent", + uuid: "00000000-0000-4000-8000-000000000236", + session_id: WAKE_NATIVE_SESSION, + }), + makeSubagentNotificationFrame({ + taskId: "task-unstreamed-model", + toolUseId: "toolu-unstreamed-model", + summary: "OK", + uuid: "00000000-0000-4000-8000-000000000237", + }), + ], + }, + ])( + "records the model of a $launch from its transcript instead of the parent's", + ({ text, frames }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + subagentModel: "claude-haiku-4-5-20251001", + }); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-transcript-model"), + text, + attachments: [], + modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: "claude-opus-4-6" }, + }), + ); + for (const frame of [ + ...frames, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.take(harness.terminalReceipts); - const fork = harness.events - .filter((event) => event.type === "subagent.updated") - .at(-1)?.subagent; - assert.equal(fork?.status, "completed"); - assert.equal(fork?.model, "claude-haiku-4-5"); - assert.equal(fork?.modelSelection?.model, "claude-haiku-4-5"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + const subagent = harness.events + .filter((event) => event.type === "subagent.updated") + .at(-1)?.subagent; + assert.equal(subagent?.status, "completed"); + assert.equal(subagent?.model, "claude-haiku-4-5"); + assert.equal(subagent?.modelSelection?.model, "claude-haiku-4-5"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), - ), ); it.effect.each([ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 614a24c73cd20..03d242f4a7227 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -325,6 +325,7 @@ function claudeMessageInputTokens(usage: { export function claudeProviderTurnTokenUsage( usage: { + readonly iterations?: SDKAssistantMessage["message"]["usage"]["iterations"] | undefined; readonly input_tokens?: number | null | undefined; readonly cache_creation_input_tokens?: number | null | undefined; readonly cache_read_input_tokens?: number | null | undefined; @@ -336,9 +337,11 @@ export function claudeProviderTurnTokenUsage( autoCompactWindow = "", requestedAt?: DateTime.Utc, ) { - const inputTokens = claudeMessageInputTokens(usage); - const outputTokens = optionalClaudeUsageTokenCount(usage.output_tokens) ?? 0; - const cachedInputTokens = optionalClaudeUsageTokenCount(usage.cache_read_input_tokens) ?? 0; + // After an advisor call, the response totals can count the same context twice. + const sample = usage.iterations?.findLast((iteration) => iteration.type === "message") ?? usage; + const inputTokens = claudeMessageInputTokens(sample); + const outputTokens = optionalClaudeUsageTokenCount(sample.output_tokens) ?? 0; + const cachedInputTokens = optionalClaudeUsageTokenCount(sample.cache_read_input_tokens) ?? 0; const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation); // The cache lifetime starts with the request, not when its response ends. const promptCacheExpiresAt = @@ -364,15 +367,11 @@ type ClaudeMessageUsage = Parameters[0]; // message_delta usage is per-message cumulative; null or absent fields retain message_start values and zeros replace them. function mergeClaudeStreamUsage( current: ClaudeMessageUsage, - delta: { - readonly input_tokens?: number | null | undefined; - readonly cache_creation_input_tokens?: number | null | undefined; - readonly cache_read_input_tokens?: number | null | undefined; - readonly output_tokens?: number | null | undefined; - }, + delta: ClaudeMessageUsage, ): ClaudeMessageUsage { return { ...current, + iterations: delta.iterations ?? current.iterations, input_tokens: optionalClaudeUsageTokenCount(delta.input_tokens) ?? optionalClaudeUsageTokenCount(current.input_tokens) ?? @@ -1438,25 +1437,22 @@ const decodeClaudeHistoryMessages = Schema.decodeUnknownEffect( ), ); +interface ClaudeHistoryMessage { + readonly type: string; + readonly uuid: string; + readonly message: { readonly content: unknown; readonly model?: unknown }; +} + // The placeholder reply the CLI records for a failed request. export function claudeHistoryEndsOnFailedRequest( - messages: ReadonlyArray<{ - readonly type: string; - readonly message: { readonly content: unknown; readonly model?: unknown }; - }>, + messages: ReadonlyArray, ): boolean { const last = messages.at(-1); return last?.type === "assistant" && last.message.model === ""; } // Claude's interactive reply-on-resume removes native abort rows before querying the saved history. -export function claudeResumeSessionAt( - messages: ReadonlyArray<{ - readonly type: string; - readonly uuid: string; - readonly message: { readonly content: unknown }; - }>, -): string | undefined { +function claudeMessagesBeforeTrailingAborts(messages: ReadonlyArray): number { let end = messages.length; let toolInterrupted = false; while (end > 0) { @@ -1495,9 +1491,57 @@ export function claudeResumeSessionAt( } break; } + return end; +} + +export function claudeResumeSessionAt( + messages: ReadonlyArray, +): string | undefined { + const end = claudeMessagesBeforeTrailingAborts(messages); return end === messages.length ? undefined : messages[end - 1]?.uuid; } +// Transcript lines can exceed 100 KB; the tail only has to reach this process's last message. +const CLAUDE_TRANSCRIPT_TAIL_BYTES = 2 * 1024 * 1024; +// A long terminal exchange pushes that message out of the tail; one wider read looks for it. +const CLAUDE_TRANSCRIPT_WIDE_TAIL_BYTES = 32 * 1024 * 1024; + +/** Whether a live process missed messages a terminal `claude --resume` appended to its session. + * Anchors on the last message the process emitted; Claude flushes the file after streaming, so + * an emitted message can be missing from it. Lines with no anchor before them prove nothing: + * they can all predate the process, so the answer is undefined. */ +function claudeTranscriptHasUnseenMessages( + lines: ReadonlyArray, + emittedUuids: ReadonlySet, +): boolean | undefined { + let anchored = false; + let unseen: Array = []; + for (const line of lines) { + let entry: unknown; + try { + entry = JSON.parse(line); + } catch { + continue; + } + const uuid = field(entry, "uuid"); + if (typeof uuid !== "string" || !isClaudeTranscriptConversationLine(entry)) continue; + if (emittedUuids.has(uuid)) { + anchored = true; + unseen = []; + continue; + } + if ( + field(entry, "isSidechain") === true || + field(entry, "isMeta") === true || + field(entry, "isCompactSummary") === true + ) { + continue; + } + unseen.push({ type: entry.type, uuid, message: { content: entry.message.content } }); + } + return anchored ? claudeMessagesBeforeTrailingAborts(unseen) > 0 : undefined; +} + const claudeConfigDirOf = ( path: Path.Path, environment: NodeJS.ProcessEnv, @@ -5292,6 +5336,8 @@ interface ActiveClaudeTurnContext { retryBudgetFailure?: OrchestrationV2ProviderFailure; // Set when the prompt starts or a request goes out; cleared by the turn's next frame. unansweredRequestSince?: DateTime.Utc | undefined; + // Interrupted once the silence clears, so the session scope stops holding this context. + unansweredRequestWatch?: Fiber.Fiber | undefined; readonly queryPolicy: ClaudeRuntimeQueryPolicy; readonly input: ProviderAdapter.ProviderAdapterV2TurnInput; readonly autoCompactWindow: string; @@ -5302,6 +5348,7 @@ interface ActiveClaudeTurnContext { readonly providerTurnOrdinal: number; readonly startedAt: DateTime.Utc; readonly itemOrdinals: Map; + readonly planIds: Map; readonly assistant: { fallbackText: string; // Result-only replies of steered segments that ended before the current one. @@ -5431,6 +5478,8 @@ interface ActiveClaudeSubagent { readonly childRootNodeId: OrchestrationV2ExecutionNode["id"]; readonly turnItemId: OrchestrationV2TurnItem["id"]; readonly turnItemOrdinal: number; + // Clients group cards by launching turn; later updates can arrive during another turn. + readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; readonly runToolUseId: string | null; readonly effort: string | undefined; nextChildItemOrdinal: number; @@ -5475,6 +5524,9 @@ interface ClaudeLiveQueryContext { // Per process, not per session: a relative temp dir follows the cwd this CLI // was launched in, and a later turn's cwd can differ. readonly taskOutputRoot: string | undefined; + // Root messages this process streamed; what it holds beyond the history it resumed. + readonly emittedMessageUuids: Set; + transcriptPath: string | undefined; } interface ActiveClaudeToolCall { @@ -6258,9 +6310,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const taskListsByNativeThread = yield* Ref.make( new Map(), ); - const planIdsByNativeItem = yield* Ref.make( - new Map(), - ); const providerRetries = yield* Ref.make( new Map(), ); @@ -6689,8 +6738,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( context.autoCompactWindow, context.streamUsage?.requestedAt, ); - if (typeof usage !== "number") { - if (claudeMessageInputTokens(usage) <= 0) return; + if ("inputTokens" in tokenUsage) { + if (tokenUsage.inputTokens <= 0) return; context.compactionTokens = undefined; } yield* emitProviderEvent({ @@ -6799,6 +6848,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); }); + const clearUnansweredRequestWatch = (context: ActiveClaudeTurnContext) => { + const watch = context.unansweredRequestWatch; + context.unansweredRequestWatch = undefined; + return watch === undefined ? Effect.void : Fiber.interrupt(watch); + }; + const failStalledTurn = Effect.fn("ClaudeAdapterV2.failStalledTurn")(function* ( context: ActiveClaudeTurnContext, failure: OrchestrationV2ProviderFailure, @@ -7619,9 +7674,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); - // A `context: fork` skill has no Agent call and streams none of its own frames; - // only its transcript records the model, written after the fork reports its outcome. - const forkedSkillModel = Effect.fnUntraced(function* ( + // A `context: fork` skill, or a foreground subagent whose replies were never streamed, + // leaves no model on any frame; only its transcript records it, written once it finishes. + const transcriptModel = Effect.fnUntraced(function* ( context: ActiveClaudeTurnContext, nativeThreadId: string, taskId: string, @@ -7629,7 +7684,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const registered = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId); if ( registered === undefined || - registered.runToolUseId !== null || registered.task.model !== null || registered.task.status === "running" ) { @@ -7728,6 +7782,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( resume.context, `task:${resume.taskId}:subagent`, ), + providerTurnId: resume.context.providerTurnId, runToolUseId: launchToolUseId, effort: undefined, nextChildItemOrdinal: 100, @@ -8379,6 +8434,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) : undefined)); const model = input.model ?? priorTask?.model ?? null; + const movesToCurrentRun = + input.reopen === true && input.status === "running" && existingSubagent !== undefined; const task = { ...(priorTask ?? { id: nodeId, @@ -8403,11 +8460,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( startedAt: now, }), status: input.status, - ...(input.reopen === true && - input.status === "running" && - existingSubagent !== undefined - ? { runId: input.context.input.runId } - : {}), + ...(movesToCurrentRun ? { runId: input.context.input.runId } : {}), ...(input.prompt === undefined ? {} : { prompt: input.prompt }), ...(input.title === undefined ? {} : { title: input.title }), model, @@ -8442,6 +8495,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( childRootNodeId, turnItemId: existingSubagent?.turnItemId ?? derivedIds.turnItemId, turnItemOrdinal, + providerTurnId: + existingSubagent === undefined || movesToCurrentRun + ? input.context.providerTurnId + : existingSubagent.providerTurnId, runToolUseId: existingSubagent === undefined ? (input.toolUseId ?? null) @@ -8629,7 +8686,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( runId: task.runId, nodeId: task.id, providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, + providerTurnId: subagent.providerTurnId, nativeItemRef: task.nativeTaskRef, parentItemId: null, ordinal: subagent.turnItemOrdinal, @@ -8689,8 +8746,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }) { const updatedAt = yield* DateTime.now; const projectionNativeItemId = `${input.kind}:${input.nativeItemId}`; - const planKey = `${input.context.input.threadId}:${projectionNativeItemId}`; - const existingPlanId = (yield* Ref.get(planIdsByNativeItem)).get(planKey); + const existingPlanId = input.context.planIds.get(projectionNativeItemId); const planId = existingPlanId ?? (yield* idAllocator.allocate.plan({ @@ -8698,13 +8754,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( runId: input.context.input.runId, driver: CLAUDE_PROVIDER, })); - if (existingPlanId === undefined) { - yield* Ref.update(planIdsByNativeItem, (current) => { - const updated = new Map(current); - updated.set(planKey, planId); - return updated; - }); - } + input.context.planIds.set(projectionNativeItemId, planId); const nodeId = idAllocator.derive.nodeFromProviderItem({ driver: CLAUDE_PROVIDER, nativeItemId: projectionNativeItemId, @@ -10112,6 +10162,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Ref.update(activeTurn, (current) => current?.providerTurnId === input.context.providerTurnId ? null : current, ); + yield* clearUnansweredRequestWatch(input.context); if (input.status === "completed") { settledTurnByNativeThread.set(input.context.nativeThreadId, input.context); } else { @@ -11164,10 +11215,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { const since = yield* DateTime.now; context.unansweredRequestSince = since; - yield* failUnansweredRequest(context, since).pipe( - Effect.delay(PROVIDER_RETRY_BUDGET_MS), + const previousWatch = context.unansweredRequestWatch; + // Only the wait is interruptible: a fired failure runs on its own fiber. + context.unansweredRequestWatch = yield* Effect.sleep(PROVIDER_RETRY_BUDGET_MS).pipe( + Effect.andThen( + failUnansweredRequest(context, since).pipe(Effect.forkIn(sessionScope)), + ), Effect.forkIn(sessionScope), ); + if (previousWatch !== undefined) yield* Fiber.interrupt(previousWatch); + // A turn that settled meanwhile already cleared its watch, so drop the new one too. + if ((yield* Ref.get(activeTurn)) !== context) { + yield* clearUnansweredRequestWatch(context); + } } else if ( // Background tasks from earlier turns keep streaming while the root request hangs. // Only the root starts depth-1 tasks, so such a start (a forked skill) is this turn's. @@ -11179,6 +11239,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) ) { context.unansweredRequestSince = undefined; + yield* clearUnansweredRequestWatch(context); } } const focusedPlugin = claudeFocusRequestedPanePlugin(message); @@ -12393,7 +12454,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return next; }); for (const taskId of context.subagentsByTaskId.keys()) { - const model = yield* forkedSkillModel(context, liveQuery.nativeThreadId, taskId); + const model = yield* transcriptModel(context, liveQuery.nativeThreadId, taskId); const status = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId)?.task.status; if ( model !== undefined && @@ -13263,6 +13324,73 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return false; }); + const claudeProjectsDir = Effect.gen(function* () { + const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; + return path.join( + configuredDir.length > 0 + ? path.resolve(session.cwd, configuredDir) + : path.join(yield* HostProcess.HomeDirectory, ".claude"), + "projects", + ); + }); + + const locateClaudeTranscript = Effect.fnUntraced(function* (nativeThreadId: string) { + const projectsDir = yield* claudeProjectsDir; + let newest: { readonly path: string; readonly mtime: number } | undefined; + for (const project of yield* fileSystem.readDirectory(projectsDir)) { + const candidate = path.join(projectsDir, project, `${nativeThreadId}.jsonl`); + const info = yield* fileSystem.stat(candidate).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "File") continue; + const mtime = Option.getOrUndefined(info.value.mtime)?.getTime() ?? 0; + if (newest === undefined || mtime > newest.mtime) newest = { path: candidate, mtime }; + } + return newest?.path; + }); + + // A failed read keeps the process: replacing it is only right when the file proves a miss. + const liveProcessMissedTranscriptMessages = Effect.fn( + "ClaudeAdapterV2.liveProcessMissedTranscriptMessages", + )( + function* (live: ClaudeLiveQueryContext) { + if (live.emittedMessageUuids.size === 0) return false; + live.transcriptPath ??= yield* locateClaudeTranscript(live.nativeThreadId); + const transcriptPath = live.transcriptPath; + if (transcriptPath === undefined) return false; + const readTail = (maxBytes: number) => + Effect.scoped( + Effect.gen(function* () { + const handle = yield* fileSystem.open(transcriptPath, { flag: "r" }); + const size = Number((yield* handle.stat).size); + const start = Math.max(0, size - maxBytes); + yield* handle.seek(BigInt(start), "start"); + const bytes = yield* handle.readAlloc(size - start); + const lines = ( + Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : "" + ).split("\n"); + // The last piece is empty or a line Claude is still writing; a cut tail starts + // mid-line. + lines.pop(); + if (start > 0) lines.shift(); + return { lines, wholeFile: start === 0 }; + }), + ); + for (const maxBytes of [ + CLAUDE_TRANSCRIPT_TAIL_BYTES, + CLAUDE_TRANSCRIPT_WIDE_TAIL_BYTES, + ]) { + const tail = yield* readTail(maxBytes); + const missed = claudeTranscriptHasUnseenMessages( + tail.lines, + live.emittedMessageUuids, + ); + if (missed !== undefined) return missed; + if (tail.wholeFile) break; + } + return false; + }, + Effect.orElseSucceed(() => false), + ); + const routedCatalogFor = (live: ClaudeLiveQueryContext) => routeModelCatalog(modelCatalog, live.settingsCwd, live.launchArgSettings); @@ -13329,6 +13457,35 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { return existing; } + let replaceStaleProcess = false; + if ( + !turnInput.resume && + existing !== null && + existing.nativeThreadId === nativeThreadId && + existing.queryPolicyKey === queryPolicyKey && + !existing.stopping && + // A pinned head already decides where a fresh process resumes. + resumeSessionAt === undefined + ) { + // Decided before the transcript read: with no pending wakeup then, none can fire during it. + const keepsWork = + (yield* liveProcessRunsBackgroundWork(existing)) || + scheduledWakeupsByNativeThread.has(nativeThreadId) || + (yield* holdsBufferedWake( + nativeThreadId, + (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [], + )); + if (yield* liveProcessMissedTranscriptMessages(existing)) { + if (keepsWork) { + yield* Effect.logWarning( + "orchestration-v2.claude-stale-process-kept-for-background-work", + { threadId: turnInput.threadId, nativeThreadId }, + ); + } else { + replaceStaleProcess = true; + } + } + } const reuseLaunchSettings = existing !== null && existing.nativeThreadId === nativeThreadId && @@ -13367,6 +13524,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing.nativeThreadId === nativeThreadId && existing.queryPolicyKey === queryPolicyKey && !existing.stopping && + !replaceStaleProcess && existing.selection.queryIdentity !== compiledSelection.queryIdentity && canApplyClaudeSelectionLive(existing.selection, compiledSelection) && (existing.selection.apiModelId === compiledSelection.apiModelId || @@ -13381,6 +13539,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing.nativeThreadId === nativeThreadId && existing.queryPolicyKey === queryPolicyKey && !existing.stopping && + !replaceStaleProcess && existing.selection.queryIdentity === compiledSelection.queryIdentity ) { // A denied ExitPlanMode leaves Claude in plan mode. Restore only from plan: @@ -13613,6 +13772,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( resolvedTurnCwd, hostPlatform, ), + emittedMessageUuids: new Set(), + transcriptPath: undefined, }; // One step, so the replaced process cannot exit between the install and the handoff. yield* Ref.update(queryContext, (replaced) => { @@ -13630,6 +13791,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( sdkMessageLock.withPermits(1)( Effect.suspend(() => { let firstInit = false; + if ( + (message.type === "assistant" || message.type === "user") && + message.parent_tool_use_id === null && + message.uuid !== undefined + ) { + context.emittedMessageUuids.add(message.uuid); + } if ( message.type === "system" && message.subtype === "init" && @@ -13884,6 +14052,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( providerTurnOrdinal, startedAt, itemOrdinals: new Map(), + planIds: new Map(), assistant: { fallbackText: "", earlierFallbackText: "", @@ -14564,13 +14733,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const claudeTranscriptState = Effect.fn("ClaudeAdapterV2.claudeTranscriptState")(function* ( nativeThreadId: string, ) { - const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; - const projectsDir = path.join( - configuredDir.length > 0 - ? path.resolve(session.cwd, configuredDir) - : path.join(yield* HostProcess.HomeDirectory, ".claude"), - "projects", - ); + const projectsDir = yield* claudeProjectsDir; // Any message in any transcript copy means Claude may still resume it. let found = false; let unreadable = false; @@ -15187,7 +15350,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), handoffIds: rollbackInput.providerThread.handoffIds, }, - providerTurns: [], messages: [], runtimeRequests: [], }; @@ -15209,7 +15371,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( lastRunOrdinal: rollbackInput.target.appRunOrdinal, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index aea174821f2a4..600740117b9d7 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -3609,6 +3609,99 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("keeps an asynchronous Codex alert distinguishable from the final answer", () => + Effect.gen(function* () { + const nativeThreadId = "async-alert-thread"; + const nativeTurnId = "async-alert-turn"; + const agentMessage = (id: string, text: string, delivery: "async" | null) => ({ + type: "emit_inbound" as const, + label: id, + frame: { + method: "item/completed", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + item: { + type: "agentMessage", + id, + text, + phase: "final_answer", + delivery, + questions: null, + }, + }, + }, + }); + const transcript = makeCodexReplayTranscript({ + scenario: "async-alert-and-final-answer", + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId, + prompt: "Alert me, then finish.", + }), + agentMessage("call_alert_1", "I found an important detail.", "async"), + agentMessage("msg_final", "Here is the ordinary final answer.", null), + { + type: "emit_inbound", + label: "complete", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("async-alert-attempt"), + text: "Alert me, then finish.", + }), + ); + yield* harness.firstTerminal; + const classification = (nativeId: string) => { + const item = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.nativeItemRef?.nativeId === nativeId, + ); + assert.equal(item?.type, "turn_item.updated"); + if (item?.type !== "turn_item.updated") return {}; + const { + id: _id, + nodeId: _nodeId, + messageId: _messageId, + nativeItemRef: _nativeItemRef, + ordinal: _ordinal, + text: _text, + startedAt: _startedAt, + completedAt: _completedAt, + updatedAt: _updatedAt, + ...rest + } = item.turnItem as typeof item.turnItem & { messageId?: unknown; text?: unknown }; + return rest; + }; + assert.notDeepEqual(classification("call_alert_1"), classification("msg_final")); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("returns a Codex question's answer under its native question id", () => Effect.gen(function* () { const nativeThreadId = "question-id-thread"; @@ -5612,7 +5705,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); const completed = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => event.type === "run.updated" && event.payload.status === "waiting", + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), @@ -5902,6 +5995,132 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each(["retry", "failure"] as const)( + "orders a later provider %s after progress from the same turn", + (tail) => + Effect.gen(function* () { + const scenario = `codex-provider-later-${tail}`; + const nativeThreadId = `native-${scenario}-thread`; + const nativeTurnId = `native-${scenario}-turn`; + const retryNotice = (message: string) => ({ + type: "emit_inbound" as const, + label: `error/retry/${message}`, + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message, + additionalDetails: "The response stream disconnected.", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 529 } }, + }, + }, + }, + }); + const commandItem = (status: "inProgress" | "completed") => ({ + type: "commandExecution", + id: "command-between-retries", + command: "pwd", + cwd: "/workspace", + processId: "42", + source: "unifiedExecStartup", + status, + commandActions: [{ type: "unknown", command: "pwd" }], + aggregatedOutput: status === "completed" ? "/workspace\n" : null, + exitCode: status === "completed" ? 0 : null, + durationMs: status === "completed" ? 10 : null, + }); + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Run pwd." }), + retryNotice("Reconnecting... 1/5"), + { + type: "emit_inbound", + label: "item/started", + frame: { + method: "item/started", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + startedAtMs: 1782622445000, + item: commandItem("inProgress"), + }, + }, + }, + { + type: "emit_inbound", + label: "item/completed", + frame: { + method: "item/completed", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + completedAtMs: 1782622445010, + item: commandItem("completed"), + }, + }, + }, + ...(tail === "retry" ? [retryNotice("Reconnecting... 1/5")] : []), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ + id: nativeTurnId, + status: tail === "retry" ? "completed" : "failed", + }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-${scenario}`), + text: "Run pwd.", + }), + ); + yield* harness.awaitTerminal(1); + + const items = harness.events.flatMap((event) => + event.type === "turn_item.updated" ? [event.turnItem] : [], + ); + const command = items.find((item) => item.type === "command_execution"); + assert.isDefined(command); + const terminal = harness.terminalEvents()[0]; + const firstRetry = items.find((item) => item.type === "error"); + const latest = + tail === "retry" + ? items.findLast((item) => item.type === "error") + : terminal?.status === "failed" + ? { id: terminal.failureItemId, ordinal: terminal.failureItemOrdinal } + : undefined; + assert.isAbove(latest?.ordinal ?? 0, command?.ordinal ?? Infinity); + // Stored positions are per row, so the later notice needs its own row to sort after. + assert.isDefined(latest?.id); + assert.notStrictEqual(latest?.id, firstRetry?.id); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("fails a stalled 429 provider retry as a usage limit and stops the Codex turn", () => Effect.gen(function* () { const scenario = "codex-provider-retry-stall"; @@ -7313,9 +7532,9 @@ describe("CodexAdapterV2 post-settle continuation", () => { createdBy: "user", creationSource: "web", }); - const waiting = yield* orchestrator.streamDomainEvents.pipe( + const completed = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => event.type === "run.updated" && event.payload.status === "waiting", + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), @@ -7333,7 +7552,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); yield* worker.drain(); assert.isNull((yield* Ref.get(replayDriver.state)).failure); - yield* Fiber.join(waiting); + yield* Fiber.join(completed); yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(threadId); const run = projection.runs.at(-1)!; @@ -7436,9 +7655,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); const settled = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => - event.type === "run.updated" && - (event.payload.status === "waiting" || event.payload.status === "completed"), + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), @@ -13031,6 +13248,120 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("shows what an approval grants apart from the reason the model gave", () => + Effect.gen(function* () { + const reason = "Needed to build the project."; + const permissions = { + fileSystem: { + write: ["/w/out"], + entries: [ + { access: "write", path: { type: "path", path: "/w/out" } }, + { access: "write", path: { type: "special", value: { kind: "root" } } }, + { access: "read", path: { type: "glob_pattern", pattern: "/w/docs/**/*.md" } }, + { access: "write", path: { type: "special", value: { kind: "unknown", path: "" } } }, + ], + }, + network: { enabled: true }, + } satisfies CodexSchema.PermissionsRequestApprovalParams["permissions"]; + const request = ( + id: number, + method: string, + params: Record, + result: Record, + ): Array => [ + { + type: "emit_inbound", + label: method, + frame: { + id, + method, + params: { threadId: nativeThreadId, turnId: nativeTurnId, startedAtMs: 2, ...params }, + }, + }, + { type: "expect_outbound", label: method, frame: { id, result } }, + ]; + const manyFiles = Array.from({ length: 21 }, (_, index) => ({ + ...addA, + path: `/w/${String(index).padStart(2, "0")}.ts`, + })); + const { harness, answerNext } = yield* startApprovalTurn("approval-scope", [ + ...request( + 0, + "item/permissions/requestApproval", + { itemId: "permissions", cwd: "/w", reason, permissions }, + { permissions, scope: "turn" }, + ), + ...request( + 1, + "item/commandExecution/requestApproval", + { + itemId: "command", + cwd: "/w/app", + reason, + command: "pnpm install", + networkApprovalContext: { host: "example.com", protocol: "https" }, + }, + { decision: "accept" }, + ), + fileChange("started", nativeTurnId, "patch", manyFiles), + ...request( + 2, + "item/fileChange/requestApproval", + { itemId: "patch", reason, grantRoot: "/w" }, + { decision: "accept" }, + ), + fileChange("completed", nativeTurnId, "patch", manyFiles), + ...request( + 3, + "execCommandApproval", + { + callId: "legacy", + conversationId: nativeThreadId, + command: ["pnpm", "run", "build"], + cwd: "/w/app", + parsedCmd: [], + reason, + }, + { decision: "approved" }, + ), + turnCompleted(nativeTurnId), + ]); + const requests = [ + yield* answerNext, + yield* answerNext, + yield* answerNext, + yield* answerNext, + ]; + yield* harness.firstTerminal; + + assert.deepEqual( + requests.map((pending) => { + const item = approvalItem(harness.events, pending); + return [item?.prompt, item?.reason]; + }), + [ + [ + "write /w/out\nwrite / (entire filesystem)\nread /w/docs/**/*.md\nwrite unknown path\nnetwork", + reason, + ], + ["pnpm install\ncwd /w/app\nnetwork https example.com", reason], + [[...manyFiles.map((file) => `add ${file.path}`), "write /w"].join("\n"), reason], + ["pnpm run build\ncwd /w/app", reason], + ], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("classifies permission requests that only list sandbox entries", () => Effect.gen(function* () { const permissionRequest = ( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 10b46bde3b866..4dd0d36e5e6cb 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -48,6 +48,7 @@ import { type ServerProviderModel, isDelegatedAppThread, ThreadId, + type TurnItemId, } from "@t3tools/contracts"; import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; import { AgentScope } from "@t3tools/shared/AgentScope"; @@ -221,25 +222,74 @@ function codexMultiFilePatch( .join(""); } +// The prompt states the operation being approved; Codex's `reason` goes to the item's `reason`. function codexFileChangeApprovalPrompt(input: { - readonly reason?: string | null; readonly grantRoot?: string | null; readonly fileChanges?: CodexFileChangeKinds; }): string | undefined { - const reason = input.reason?.trim(); - if (reason) return reason; const entries = Object.entries(input.fileChanges ?? {}).toSorted(([left], [right]) => left.localeCompare(right), ); - if (entries.length > 0) { - const described = entries.slice(0, 20).map(([path, change]) => { - const movePath = change.type === "update" ? change.move_path : undefined; - return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; - }); - const remaining = entries.length - described.length; - return remaining > 0 ? `${described.join("\n")}\n+${remaining} more` : described.join("\n"); + // The card scrolls, so every path is listed. + const described = entries.map(([path, change]) => { + const movePath = change.type === "update" ? change.move_path : undefined; + return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; + }); + const grantRoot = input.grantRoot?.trim(); + return [...described, ...(grantRoot ? [`write ${grantRoot}`] : [])].join("\n") || undefined; +} + +function codexCommandApprovalPrompt( + input: Pick< + CodexSchema.CommandExecutionRequestApprovalParams, + "command" | "cwd" | "networkApprovalContext" + >, +): string | undefined { + const network = input.networkApprovalContext; + return ( + [ + ...(input.command?.trim() ? [input.command] : []), + ...(input.cwd?.trim() ? [`cwd ${input.cwd}`] : []), + ...(network ? [`network ${network.protocol} ${network.host}`] : []), + ].join("\n") || undefined + ); +} + +function codexFileSystemPathLabel( + path: CodexSchema.PermissionsRequestApprovalParams__FileSystemPath, +): string { + if (path.type === "path") return path.path; + if (path.type === "glob_pattern") return path.pattern; + const special = path.value; + switch (special.kind) { + case "root": + return "/ (entire filesystem)"; + case "slash_tmp": + return "/tmp"; + case "tmpdir": + return "temporary directory"; + case "minimal": + return "minimal system paths"; + case "project_roots": + return ["project roots", special.subpath].filter(Boolean).join("/"); + case "unknown": + return [special.path, special.subpath].filter(Boolean).join("/") || "unknown path"; } - return input.grantRoot?.trim() || undefined; +} + +function codexPermissionsApprovalPrompt( + permissions: CodexSchema.PermissionsRequestApprovalParams["permissions"], +): string | undefined { + // Codex may list a path both in the legacy `read`/`write` lists and in `entries`. + const lines = new Set(); + for (const access of ["read", "write"] as const) { + for (const path of permissions.fileSystem?.[access] ?? []) lines.add(`${access} ${path}`); + } + for (const entry of permissions.fileSystem?.entries ?? []) { + lines.add(`${entry.access} ${codexFileSystemPathLabel(entry.path)}`); + } + if (permissions.network?.enabled) lines.add("network"); + return [...lines].join("\n") || undefined; } export function normalizeCodexThreadLoadModelSelection(selection: ModelSelection): ModelSelection { @@ -1427,6 +1477,7 @@ interface ActiveCodexTurnContext { capacityRetryAttempt?: number; capacityRetryPending?: Deferred.Deferred; closedCommandItemIds?: ReadonlySet; + recoveredProviderRetries?: number; latestProviderFailure?: { readonly nativeMessage: string; readonly nativeCode: string | null; @@ -1453,6 +1504,7 @@ interface ActiveCodexTurnContext { // Modern approval requests omit paths; keep the kinds without retaining patch bodies. readonly fileChangeKindsByItem: Map; readonly messagePhases: Map; + readonly asyncMessageIds: Set; readonly itemPositions: Map< string, { readonly ordinal: number; readonly startedAt: DateTime.Utc } @@ -1469,6 +1521,24 @@ interface ActiveCodexProviderRetry { readonly failure: OrchestrationV2ProviderFailure; readonly startedAt: DateTime.Utc; readonly itemOrdinal: number; + readonly id: TurnItemId | undefined; +} + +// Each retry episode after a recovery gets its own row, placed after the turn's progress so far. +function codexFailureItemKey(context: ActiveCodexTurnContext): string { + const key = `terminal-failure:${context.providerTurnId}`; + return context.recoveredProviderRetries === undefined + ? key + : `${key}:${context.recoveredProviderRetries}`; +} + +function codexFailureItemId(context: ActiveCodexTurnContext): TurnItemId | undefined { + return context.recoveredProviderRetries === undefined + ? undefined + : IdAllocator.derive.turnItemFromProviderItem({ + driver: CODEX_PROVIDER, + nativeItemId: codexFailureItemKey(context), + }); } function codexRetryTurnItem( @@ -1480,6 +1550,7 @@ function codexRetryTurnItem( // A continuation keeps the retry row attached to the native turn that failed. const context = state.context ?? activeContext; return makeProviderRetryTurnItem({ + ...(state.id === undefined ? {} : { id: state.id }), driver: CODEX_PROVIDER, threadId: context.projectionThreadId, runId: context.projectionRunId, @@ -2679,6 +2750,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (providerRetry === undefined) { return; } + context.recoveredProviderRetries = (context.recoveredProviderRetries ?? 0) + 1; yield* emitProviderEvent({ type: "turn_item.updated", driver: CODEX_PROVIDER, @@ -2719,6 +2791,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( itemPositions: new Map(), fileChangeKindsByItem: new Map(), messagePhases: new Map(), + asyncMessageIds: new Set(), runningCompactionItemIds: new Set(), runningWebSearchItems: new Map(), }; @@ -3355,6 +3428,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( itemPositions: new Map(), fileChangeKindsByItem: new Map(), messagePhases: new Map(), + asyncMessageIds: new Set(), runningCompactionItemIds: new Set(), runningWebSearchItems: new Map(), }; @@ -4037,6 +4111,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(context.messagePhases.has(item.id) ? { phase: context.messagePhases.get(item.id) } : {}), + ...(context.asyncMessageIds.has(item.id) ? { delivery: "async" as const } : {}), messageId, text: item.text, streaming: !completed, @@ -4892,10 +4967,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readonly nativeRequestId: string; readonly requestKind: ProviderRequestKind; readonly prompt?: string | null; + readonly reason?: string | null | undefined; readonly appName?: string; readonly options?: ReadonlyArray; }) { const createdAt = yield* DateTime.now; + const reason = trimText(input.reason); const { owner, subagent } = approvalOwnerCodexTurn(input.context); const parentNodeId = subagent?.subagentNodeId ?? @@ -4975,6 +5052,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(input.prompt === null || input.prompt === undefined ? {} : { prompt: input.prompt }), + ...(reason === undefined ? {} : { reason }), ...(input.appName === undefined ? {} : { appName: input.appName }), ...(input.options === undefined ? {} : { options: input.options }), }; @@ -5494,8 +5572,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); const itemOrdinal = previous?.itemOrdinal ?? - (yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`)); + (yield* resolveItemOrdinal(context, codexFailureItemKey(context))); const state: ActiveCodexProviderRetry = { + id: previous === undefined ? codexFailureItemId(context) : previous.id, ...(previous?.context === undefined ? {} : { context: previous.context }), nativeMessage: payload.error.message, nativeCode: code, @@ -5668,6 +5747,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (payload.item.type === "agentMessage") { if (payload.item.phase != null) context.messagePhases.set(payload.item.id, payload.item.phase); + if (payload.item.delivery === "async") context.asyncMessageIds.add(payload.item.id); if (payload.item.phase == null || payload.item.phase === "final_answer") { yield* Ref.update(finalAnswerItemIdsByTurn, (current) => { const updated = new Map(current); @@ -6072,6 +6152,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (payload.item.phase != null) context.messagePhases.set(payload.item.id, payload.item.phase); + if (payload.item.delivery === "async") context.asyncMessageIds.add(payload.item.id); const finalAnswer = payload.item.phase == null || payload.item.phase === "final_answer"; if (finalAnswer) { yield* Ref.update(finalAnswerItemIdsByTurn, (current) => { @@ -6154,9 +6235,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.itemId, nativeRequestId, requestKind: "command", - ...((payload.reason ?? payload.command) === undefined - ? {} - : { prompt: payload.reason ?? payload.command }), + prompt: codexCommandApprovalPrompt(payload) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6229,6 +6309,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...payload, fileChanges: context.fileChangeKindsByItem.get(payload.itemId) ?? {}, }) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6291,7 +6372,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.itemId, nativeRequestId: payload.itemId, requestKind, - ...(payload.reason === undefined ? {} : { prompt: payload.reason }), + prompt: codexPermissionsApprovalPrompt(payload.permissions) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6442,7 +6524,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.callId, nativeRequestId, requestKind: "command", - prompt: payload.reason ?? payload.command.join(" "), + prompt: + codexCommandApprovalPrompt({ + command: payload.command.join(" "), + cwd: payload.cwd, + }) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6511,6 +6598,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeRequestId: payload.callId, requestKind: "file-change", prompt: codexFileChangeApprovalPrompt(payload) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6675,6 +6763,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { failure = { ...failure, class: "transport_error" }; } + const failureItemId = codexFailureItemId(input.context); return { type: "turn.terminal", driver: CODEX_PROVIDER, @@ -6683,8 +6772,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( runOrdinal: input.context.input.runOrdinal, failureItemOrdinal: yield* resolveItemOrdinal( input.context, - `terminal-failure:${input.context.providerTurnId}`, + codexFailureItemKey(input.context), ), + ...(failureItemId === undefined ? {} : { failureItemId }), status: terminalStatus, failure: failure.class === "usage_limit" @@ -6740,6 +6830,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* emitProviderEvent(current); if (current.status === "failed" && current.failure.class === "usage_limit") { const item = makeProviderFailureTurnItem({ + ...(current.failureItemId === undefined ? {} : { id: current.failureItemId }), driver: CODEX_PROVIDER, threadId: context.input.threadId, runId: context.input.runId, @@ -7481,10 +7572,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( retry: { attempt, maxAttempts: CODEX_CAPACITY_MAX_RETRIES, retryDelayMs }, itemOrdinal: previous?.itemOrdinal ?? - (yield* resolveItemOrdinal( - context, - `terminal-failure:${context.providerTurnId}`, - )), + (yield* resolveItemOrdinal(context, codexFailureItemKey(context))), + id: previous === undefined ? codexFailureItemId(context) : previous.id, startedAt: previous?.startedAt ?? now, }; yield* Ref.update(providerRetries, (current) => @@ -7647,6 +7736,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( itemPositions: new Map(), fileChangeKindsByItem: new Map(), messagePhases: new Map(), + asyncMessageIds: new Set(), runningCompactionItemIds: new Set(), runningWebSearchItems: new Map(), }; @@ -9258,7 +9348,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef, updatedAt: codexTimestamp(response.thread.updatedAt), }, - providerTurns: [], messages: [], runtimeRequests: [], providerPayload: response.thread, @@ -9291,7 +9380,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef, status: "idle" as const, }, - providerTurns: [], messages: [], runtimeRequests: [], }; @@ -9334,7 +9422,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( status: "idle" as const, updatedAt: codexTimestamp(response.thread.updatedAt), }, - providerTurns: [], messages: [], runtimeRequests: [], providerPayload: response.thread, diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 0e4bc5d088048..33b2ecd4638c5 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -43,7 +43,7 @@ import { TestClock } from "effect/testing"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { htmlRenderFromToolItem, sentMessageFromToolItem } from "@t3tools/shared/toolOutput"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { @@ -1540,16 +1540,26 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("session.interrupt", { interrupted: true }), event("session.execution.interrupted", { sessionID: SESSION }), ]); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); const watch = yield* watchBackgroundTurn(runtime); yield* runtime.startTurn(withLineage(thread)); yield* watch.attached; + // The child's nested T3 MCP results live under the root thread and outlive its turn. + const childResult = { message: "Child note" }; + yield* mcpSessions.recordToolResult(threadId, "send_to_user", childResult, { + sentMessage: childResult.message, + }); yield* runtime.interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId, }); assert.equal((yield* watch.terminal)?.status, "interrupted"); assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - }), + assert.deepEqual(yield* mcpSessions.takeToolResult(threadId, "send_to_user", childResult), { + sentMessage: childResult.message, + }); + }).pipe(Effect.scoped), ); it.effect("stops background subagents on a user Stop", () => @@ -5321,6 +5331,188 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("shows send_to_user messages a Code Mode script sends without returning them", () => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); + const server = "t3-code-thread_opencode2-adapter"; + const messages = ["First mid-turn note", "Second mid-turn note"]; + yield* Effect.forEach(messages, (message) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ), + ); + const tool = { + sessionID: SESSION, + assistantMessageID: "msg_assistant", + id: "call-execute-send", + }; + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.tool.input.started", { ...tool, name: "execute" }), + event("session.tool.called", { ...tool, input: { code: "`, + ); + const keys = (selector: string) => + page.locator(selector).evaluate((field) => (field as unknown as { keys: string }).keys); + await ServerBrowserPage.type(page, { locator: "#a", text: "girona42" }); + expect(await keys("#a")).toBe("girona42"); + await ServerBrowserPage.type(page, { locator: "#b", text: "girona42", clear: true }); + expect(await keys("#b")).toBe("girona42"); + await ServerBrowserPage.type(page, { locator: "#b", text: "a".repeat(501), clear: true }); + expect(await keys("#b")).toBe(`girona42${"a".repeat(501)}`); + + await page.setContent( + `
`, + ); + await ServerBrowserPage.type(page, { locator: "text=Email", text: "a@b.c", clear: true }); + expect(await page.locator("#e").inputValue()).toBe("a@b.c"); + await ServerBrowserPage.type(page, { locator: "#d", text: "2026-01-31", clear: true }); + expect(await page.locator("#d").inputValue()).toBe("2026-01-31"); + await ServerBrowserPage.type(page, { locator: "text=Tint", text: "#ff0000", clear: true }); + expect(await page.locator("#c").inputValue()).toBe("#ff0000"); + await ServerBrowserPage.type(page, { locator: "#r", text: "70", clear: true }); + expect(await page.locator("#r").inputValue()).toBe("70"); + await ServerBrowserPage.type(page, { locator: "#e", text: "x\ny" }); + await ServerBrowserPage.type(page, { locator: "#t", text: "one\r\ntwo" }); + expect(await page.locator("#t").inputValue()).toBe("one\ntwo"); + expect(await page.locator("#sent").inputValue()).toBe(""); + }); + it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => { await page.setContent(`
password:
@@ -973,7 +1003,7 @@ describe("server browser type", () => { ({ locator: () => ({ last: () => ({ count: () => new Promise(() => {}) }) }), evaluate: focusAnswer, - keyboard: { insertText: async (text: string) => void typed.push(text) }, + keyboard: { type: async (text: string) => void typed.push(text) }, }) as unknown as Page; it("types into the focused field when Playwright's utility world never answers", async () => { @@ -1010,6 +1040,30 @@ describe("server browser type", () => { detail: { timeoutMs: 300 }, }); expect(typed).toEqual([]); + + // A target whose element is found but whose page then stops answering. + const fill = vi.fn(async () => {}); + const hung = { + locator: () => ({ evaluate: () => new Promise(() => {}), fill }), + keyboard: { type: async (text: string) => void typed.push(text) }, + } as unknown as Page; + void ServerBrowserPage.type(hung, { + locator: "#field", + text: "hello", + clear: true, + timeoutMs: 300, + }).then( + () => (outcome = "typed"), + (error: unknown) => (outcome = error), + ); + outcome = "pending"; + await vi.advanceTimersByTimeAsync(300); + expect(outcome).toMatchObject({ + tag: "PreviewAutomationTimeoutError", + detail: { timeoutMs: 300 }, + }); + expect(fill).not.toHaveBeenCalled(); + expect(typed).toEqual([]); } finally { vi.useRealTimers(); } diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index f5eed496da5fe..a633f4328d163 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -941,8 +941,8 @@ const focusTextTarget = (target: FocusCandidate | null) => { return active != null && (active === element || element.contains(active)); }; -// A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. -const focusedTextField = async (page: Page, timeout: number) => { +// Playwright's own timeout covers finding the element, not a page that stops answering the evaluation. +const pageAnswer = async (answer: Promise, timeout: number) => { let timer: ReturnType | undefined; const expired = new Promise((_, reject) => { timer = setTimeout( @@ -950,29 +950,77 @@ const focusedTextField = async (page: Page, timeout: number) => { reject( new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: `The page did not report its focused element within ${timeout}ms, so no text was typed.`, + message: `The page did not answer within ${timeout}ms, so no text was typed.`, detail: { timeoutMs: timeout }, }), ), timeout, ); }); - return await Promise.race([page.evaluate(focusTextTarget, null), expired]).finally(() => - clearTimeout(timer), + return await Promise.race([answer, expired]).finally(() => clearTimeout(timer)); +}; + +// Serialized into the page's main world, so it must not reference module scope. +const valueOnlyInput = ( + target: FocusCandidate & { + closest(selector: string): { readonly control: FocusCandidate | null } | null; + }, +) => { + // As fill does, a target that is not a control stands for its label's control. + const element = target.tagName === "INPUT" ? target : target.closest("label")?.control; + return ( + element?.tagName === "INPUT" && + ["color", "date", "datetime-local", "month", "range", "time", "week"].includes( + element.type ?? "", + ) ); }; +// Keys reach pages that build their value from keydown. Line breaks stay text: Enter would submit the form. +const typeKeys = async (page: Page, text: string, timeoutMs: number, deadline: number) => { + let typed = 0; + for (const [index, part] of text.split(/([\r\n]+)/u).entries()) { + // Keys cost about a millisecond each, so long text is sent in pieces that stop at the deadline. + const pieces = index % 2 === 1 ? [part] : (part.match(/[^]{1,64}/gu) ?? []); + for (const piece of pieces) { + if (Date.now() >= deadline) { + const reason = `Typing stopped after ${typed} of ${text.length} characters, which the field now holds. Type the rest in another call or raise timeoutMs.`; + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: reason, + detail: { timeoutMs, reason }, + }); + } + if (index % 2 === 1) await page.keyboard.insertText(piece); + else await page.keyboard.type(piece); + typed += piece.length; + } + } +}; + export const type = async (page: Page, input: PreviewAutomationTypeInput) => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + // One deadline across steps keeps the reply inside the broker's grace; Playwright reads 0 as none. + const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const deadline = Date.now() + timeoutMs; + const remaining = () => Math.max(1, deadline - Date.now()); const locator = targetLocator(page, input); if (locator !== null && input.clear) { - await locator.fill(input.text, { timeout }); + // Pickers and sliders take a value such as 2026-01-31 only from fill, and some reject an empty one. + const timeout = remaining(); + if (await pageAnswer(locator.evaluate(valueOnlyInput, undefined, { timeout }), timeout)) { + await locator.fill(input.text, { timeout: remaining() }); + return; + } + // fill follows a label to its control and leaves that control focused for the keys. + await locator.fill("", { timeout: remaining() }); + await typeKeys(page, input.text, timeoutMs, deadline); return; } const focused = locator === null - ? await focusedTextField(page, timeout) - : await locator.evaluate(focusTextTarget, undefined, { timeout }); + ? // A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. + await pageAnswer(page.evaluate(focusTextTarget, null), remaining()) + : await locator.evaluate(focusTextTarget, undefined, { timeout: remaining() }); if (focused !== true) { throw new ServerBrowserOperationError({ tag: "PreviewAutomationTargetNotEditableError", @@ -983,7 +1031,7 @@ export const type = async (page: Page, input: PreviewAutomationTypeInput) => { await page.keyboard.press("ControlOrMeta+A"); await page.keyboard.press("Delete"); } - await page.keyboard.insertText(input.text); + await typeKeys(page, input.text, timeoutMs, deadline); }; export const hover = async ( diff --git a/apps/server/src/process-launcher.ts b/apps/server/src/process-launcher.ts new file mode 100644 index 0000000000000..7399bdc7d72ce --- /dev/null +++ b/apps/server/src/process-launcher.ts @@ -0,0 +1,3 @@ +import { runProcessLauncher } from "./process/processLauncherWorker.ts"; + +runProcessLauncher(); diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts new file mode 100644 index 0000000000000..f62a3c8445da2 --- /dev/null +++ b/apps/server/src/process/ProcessLauncher.ts @@ -0,0 +1,380 @@ +// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - IPC and timer callbacks implement the spawner boundary, as in the native spawner. +import * as NodeChildProcess from "node:child_process"; +import * as NodeEvents from "node:events"; +import type * as NodeNet from "node:net"; +import type * as NodeStream from "node:stream"; +import * as NodeChildProcessSpawner from "@effect/platform-node-shared/NodeChildProcessSpawner"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import * as NonBlockingSpawner from "./NonBlockingSpawner.ts"; +import type { LauncherEvent, LauncherSpawnRequest } from "./processLauncherWorker.ts"; + +// A launcher that misses either is treated as hung; neither happens to a healthy one. +const READY_TIMEOUT = "10 seconds"; +const SPAWN_REPLY_TIMEOUT = "10 seconds"; + +/** A child of the launcher, presented to the native spawner as a Node ChildProcess. */ +class HostedChild + extends NodeEvents.EventEmitter + implements NodeChildProcessSpawner.SpawnedChildProcess +{ + pid: number | undefined; + exitCode: number | null = null; + signalCode: NodeJS.Signals | null = null; + stdin: NodeStream.Writable | null = null; + stdout: NodeStream.Readable | null = null; + stderr: NodeStream.Readable | null = null; + readonly stdio: Array = []; + referenced = true; + /** Its pipes are handed over and the native spawner owns it. */ + started = false; + /** No longer awaited: its spawn failed, timed out or it exited. */ + settled = false; + readonly launcher: Launcher; + /** The fds requested as pipes, each of which must arrive before the child counts as started. */ + readonly pipes: ReadonlyArray; + + constructor(launcher: Launcher, stdio: NodeChildProcess.SpawnOptions["stdio"]) { + super(); + this.launcher = launcher; + this.pipes = stdioModes(stdio).flatMap((mode, fd) => (isPipe(mode) ? [fd] : [])); + } + + kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean { + if (this.pid === undefined || this.exitCode !== null || this.signalCode !== null) return false; + try { + process.kill(this.pid, signal); + return true; + } catch { + return false; + } + } + + ref(): void { + this.referenced = true; + syncRef(this.launcher); + } + + unref(): void { + this.referenced = false; + syncRef(this.launcher); + } + + fail(error: Error): void { + this.settled = true; + this.emit("error", error); + } + + exit(code: number | null, signal: NodeJS.Signals | null): void { + this.settled = true; + this.exitCode = code; + this.signalCode = signal; + // Node destroys stdin at exit and drains output nobody reads, so pipes never hold a child. + this.stdin?.destroy(); + this.emit("exit", code, signal); + process.nextTick(() => { + for (const stream of [this.stdout, this.stderr]) { + if ( + stream && + stream.listenerCount("data") === 0 && + stream.listenerCount("readable") === 0 + ) { + stream.resume(); + } + } + }); + } +} + +const stdioModes = (stdio: NodeChildProcess.SpawnOptions["stdio"]) => + typeof stdio === "string" || stdio === undefined ? Array(3).fill(stdio) : stdio; + +const isPipe = (mode: unknown) => + mode === undefined || mode === null || mode === "pipe" || mode === "overlapped"; + +// The launcher's own stdin and stdout are /dev/null, so only pipes and "ignore" mean the same there. +const isHostable = (stdio: NodeChildProcess.SpawnOptions["stdio"]) => + stdioModes(stdio).every((mode) => isPipe(mode) || mode === "ignore"); + +interface Launcher { + readonly worker: NodeChildProcess.ChildProcess; + readonly children: Map; + readonly ready: Deferred.Deferred; + closed: boolean; + /** Counts messages from the launcher, so a slow server is not mistaken for a hung launcher. */ + heard: number; +} + +const syncRef = (launcher: Launcher) => { + if ([...launcher.children.values()].some((child) => child.referenced)) { + launcher.worker.channel?.ref(); + } else { + launcher.worker.channel?.unref(); + } +}; + +const killGroup = (pid: number) => { + try { + process.kill(-pid, "SIGKILL"); + } catch { + // The group is already gone. + } +}; + +const launcherArguments = Effect.fn("ProcessLauncher.launcherArguments")(function* () { + // A single executable has no sibling script, so it hosts the launcher as a hidden subcommand. + if (yield* HostProcess.IsExecutable) return ["__process-launcher"]; + const path = yield* Path.Path; + const fromSource = import.meta.url.endsWith(".ts"); + return [ + ...(fromSource ? ["--experimental-strip-types"] : []), + yield* path + .fromFileUrl( + new URL(fromSource ? "../process-launcher.ts" : "./process-launcher.mjs", import.meta.url), + ) + .pipe(Effect.orDie), + ]; +}); + +// On Linux, libuv forks the whole server for every spawn and blocks the event loop while the +// kernel copies its page tables, so commands are launched by a small long-lived helper instead. +// The helper passes each child's pipes back, so the native spawner keeps all of its semantics. +export const make = Effect.fn("ProcessLauncher.make")(function* ( + replyTimeout: Duration.Input = SPAWN_REPLY_TIMEOUT, +) { + const fallback = yield* ChildProcessSpawner.ChildProcessSpawner; + if ((yield* HostProcess.Platform) !== "linux") return fallback; + + const executablePath = yield* HostProcess.ExecutablePath; + const args = yield* launcherArguments(); + let current: Launcher | undefined; + // A launcher that never starts will not start next time either; stop forking for it. + let unavailable = false; + let warned = false; + let shutDown = false; + let nextId = 0; + + const close = (launcher: Launcher, hung = false) => { + if (launcher.closed) return; + launcher.closed = true; + if (current === launcher) current = undefined; + const ready = Deferred.isDoneUnsafe(launcher.ready); + if (!ready) unavailable = true; + Deferred.doneUnsafe(launcher.ready, Exit.succeed(false)); + const error = new Error( + hung ? "The process launcher did not respond." : "The process launcher exited.", + ); + for (const child of launcher.children.values()) { + if (child.settled) continue; + if (child.pid !== undefined) killGroup(child.pid); + if (child.started) { + child.exit(null, "SIGKILL"); + } else { + for (const stream of child.stdio) stream?.destroy(); + child.fail(error); + } + } + launcher.children.clear(); + if (launcher.worker.connected) launcher.worker.disconnect(); + // A started launcher kills its children and exits once disconnected; a hung one never reads that. + if (hung || !ready) launcher.worker.kill("SIGKILL"); + }; + + const onEvent = ( + launcher: Launcher, + event: LauncherEvent, + socket: NodeNet.Socket | undefined, + ) => { + launcher.heard++; + if (event.type === "ready") { + Deferred.doneUnsafe(launcher.ready, Exit.succeed(true)); + return; + } + const child = launcher.children.get(event.id); + if (child === undefined) { + socket?.destroy(); + return; + } + switch (event.type) { + case "stdio": + if (child.settled) socket?.destroy(); + else if (socket) { + child.stdio[event.fd] = socket; + if (event.fd === 0) { + // Unlike Node's own stdin pipe this socket also reads, and an unread write resets it. + socket.on("error", () => {}); + child.stdin = socket; + } else if (event.fd === 1) child.stdout = socket; + else if (event.fd === 2) child.stderr = socket; + } + break; + case "pid": + child.pid = event.pid; + break; + case "spawn": + // A lost handle would otherwise read as a command that printed nothing. + if (child.pipes.some((fd) => child.stdio[fd] == null)) { + if (child.pid !== undefined) killGroup(child.pid); + for (const stream of child.stdio) stream?.destroy(); + child.fail(new Error("The process launcher did not hand over the command's pipes.")); + break; + } + child.started = true; + child.emit("spawn"); + break; + case "exit": + launcher.children.delete(event.id); + syncRef(launcher); + if (!child.settled) child.exit(event.code, event.signal); + break; + case "error": + if (child.pid !== undefined || child.settled) break; + launcher.children.delete(event.id); + syncRef(launcher); + child.fail(Object.assign(new Error(event.error.message), event.error)); + break; + } + }; + + const launch = (): Launcher | undefined => { + if (unavailable || shutDown) return undefined; + if (current !== undefined) return current; + const env: NodeJS.ProcessEnv = { ...process.env, ELECTRON_RUN_AS_NODE: "1" }; + delete env.NODE_OPTIONS; + // `node --watch` children would report their imports over the launcher's IPC channel. + delete env.WATCH_REPORT_DEPENDENCIES; + let worker: NodeChildProcess.ChildProcess; + try { + worker = NodeChildProcess.spawn(executablePath, args, { + cwd: "/", + env, + stdio: ["ignore", "ignore", "inherit", "ipc"], + }); + } catch { + // Node throws some errnos, such as ENOMEM, instead of emitting "error". + unavailable = true; + return undefined; + } + const launcher: Launcher = { + worker, + children: new Map(), + ready: Deferred.makeUnsafe(), + closed: false, + heard: 0, + }; + worker.unref(); + worker.channel?.unref(); + worker.on("message", (event: LauncherEvent, socket: NodeNet.Socket | undefined) => + onEvent(launcher, event, socket), + ); + worker.on("error", () => close(launcher)); + worker.once("disconnect", () => close(launcher)); + worker.once("exit", () => close(launcher)); + current = launcher; + return launcher; + }; + + const spawnProcess = ( + command: string, + commandArgs: ReadonlyArray, + options: NodeChildProcess.SpawnOptions, + ): NodeChildProcessSpawner.SpawnedChildProcess => { + const launcher = current; + // Lost or replaced between the readiness check and the spawn; rare enough to fork for. + if ( + launcher === undefined || + launcher.closed || + !Deferred.isDoneUnsafe(launcher.ready) || + !isHostable(options.stdio) + ) { + return NodeChildProcess.spawn(command, [...commandArgs], options); + } + const id = ++nextId; + const child = new HostedChild(launcher, options.stdio); + launcher.children.set(id, child); + syncRef(launcher); + const request: LauncherSpawnRequest = { + type: "spawn", + id, + command, + args: commandArgs, + // The launcher runs in `/` with its own environment; children inherit the server's. + options: { ...options, cwd: options.cwd ?? process.cwd(), env: options.env ?? process.env }, + }; + launcher.worker.send(request, (error) => { + if (error) close(launcher); + }); + // The native spawner waits for the reply uninterruptibly, so a hung launcher must not hold it. + // Hung means silent for a whole window; replies queued behind a busy server count once read. + const watch = (heard: number) => + setTimeout( + () => + setImmediate(() => { + if (child.started || child.settled) return; + if (launcher.heard === heard) close(launcher, true); + else watch(launcher.heard); + }), + Duration.toMillis(replyTimeout), + ).unref(); + watch(launcher.heard); + return child; + }; + + // The trampoline keeps a hung cwd or PATH entry from stalling the launcher, and with it every command. + // Fresh: the server has already built this layer around the forking spawner. + const hosted = Context.get( + yield* Layer.build( + Layer.fresh(NonBlockingSpawner.layer).pipe( + Layer.provide(NodeChildProcessSpawner.layerWithSpawn(spawnProcess)), + ), + ), + ChildProcessSpawner.ChildProcessSpawner, + ); + + const warnUnavailable = Effect.suspend(() => { + if (!unavailable || warned || shutDown) return Effect.void; + warned = true; + return Effect.logWarning("The process launcher did not start; commands fork the server."); + }); + + const isReady = Effect.suspend(() => { + const launcher = launch(); + if (launcher === undefined) return Effect.as(warnUnavailable, false); + return Deferred.await(launcher.ready).pipe( + Effect.timeoutOption(READY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.tap((ready) => { + if (ready) return Effect.void; + close(launcher); + return warnUnavailable; + }), + ); + }); + + yield* Effect.addFinalizer(() => + Effect.sync(() => { + shutDown = true; + if (current) close(current); + }), + ); + // Start while the server is still small; the launcher's own fork is the last full-size one. + launch(); + return ChildProcessSpawner.make((command) => + Effect.flatMap(isReady, (ready) => (ready ? hosted : fallback).spawn(command)), + ); +}); + +/** Replaces the ChildProcessSpawner in context, which stays the fallback when the launcher cannot start. */ +export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make()); + +/** The server's one spawner: memoized, so every build site shares a single launcher. */ +export const layerServer = layer.pipe(Layer.provide(NonBlockingSpawner.layer)); diff --git a/apps/server/src/process/SpawnWorker.ts b/apps/server/src/process/SpawnWorker.ts index 5a391ab18ca1b..58373b5bdc0a8 100644 --- a/apps/server/src/process/SpawnWorker.ts +++ b/apps/server/src/process/SpawnWorker.ts @@ -8,6 +8,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { supportsEnvChdir } from "@t3tools/shared/envTrampoline"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; // Windows runs CreateProcess synchronously on the calling thread, and antivirus or a busy disk can // hold it for seconds; Linux's spawn waits for chdir and the PATH search, which a hung mount @@ -503,10 +504,14 @@ class SpawnWorkerPool { if (!killed) killPid(); done(); }; - this.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { - stdio: "ignore", - windowsHide: true, - }) + this.spawn( + windowsSystem32Path(process.env, "taskkill.exe"), + ["/pid", String(pid), "/T", "/F"], + { + stdio: "ignore", + windowsHide: true, + }, + ) .on("error", () => finish(false)) .on("exit", (code) => finish(code === 0)); } diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 033d83bc5f5c0..a637051ece58b 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -7,6 +7,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, expect, it } from "@effect/vitest"; import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -186,8 +187,12 @@ const exitedAgent = ( const stopsOf = (calls: ReadonlyArray>) => calls.filter(([, verb]) => verb === "stop"); -const launchCodex = (scope: Effect.Success, threadId: string) => - makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe( +const launchCodex = ( + scope: Effect.Success, + threadId: string, + env?: NodeJS.ProcessEnv, +) => + makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId, env }).pipe( Effect.provideService(AgentScope, scope), Effect.provideService(HostProcess.Platform, "linux"), Effect.map((command) => { @@ -227,7 +232,14 @@ describe("AgentScope service", () => { units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" }); expect(yield* scope.oomKilled("a")).toBe(true); - const codex = yield* launchCodex(scope, "a"); + const executable = String(agent.args.at(-1)); + const codex = yield* launchCodex(scope, "a", { + PATH: NodePath.relative(process.cwd(), NodePath.dirname(executable)), + }); + // Anchored to the cwd for systemd-run, with its ".." kept; it names the same file. + const anchored = String(codex.args.at(-2)); + expect(NodePath.isAbsolute(anchored)).toBe(true); + expect(NodePath.resolve(anchored)).toBe(executable); expect(codex.args).toContain("--property=OOMPolicy=continue"); expect(codex.args).not.toContain("--property=OOMPolicy=stop"); expect(codex.args).toContain("--property=TimeoutStopSec=10s"); @@ -243,6 +255,33 @@ describe("AgentScope service", () => { ), ); + it.effect.skipIf(!symlinksSupported)( + "keeps a symlinked parent in absolute and relative executable paths", + () => + withFakeSystemd(({ scope }) => + Effect.gen(function* () { + const plain = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "s" }); + const bin = NodePath.dirname(String(plain.args.at(-1))); + NodeFS.mkdirSync(NodePath.join(bin, "real", "sub"), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(bin, "real", "agent"), "", { mode: 0o755 }); + NodeFS.symlinkSync(NodePath.join(bin, "real", "sub"), NodePath.join(bin, "link")); + // The kernel follows the link before "..", so this names real/agent, not bin/agent. + const command = `${NodePath.join(bin, "link")}/../agent`; + const wrapped = yield* scope.wrap({ command, args: [], name: "t", threadId: "s" }); + expect(wrapped.args.at(-1)).toBe(command); + // A relative path is anchored to the cwd the same way, without collapsing "..". + const relative = `${NodePath.relative(process.cwd(), NodePath.join(bin, "link"))}/../agent`; + const anchored = yield* scope.wrap({ + command: relative, + args: [], + name: "t", + threadId: "s", + }); + expect(anchored.args.at(-1)).toBe(`${process.cwd()}${NodePath.sep}${relative}`); + }), + ), + ); + it.effect.each([{ oomPolicy: true }, { oomPolicy: false }])( "Force stop kills a thread's own scope but never a shared Codex scope (OOM policy $oomPolicy)", ({ oomPolicy }) => diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index 4bbb7d159cf0b..8a62f538cdee2 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -459,7 +459,15 @@ export const make = Effect.gen(function* () { ...(owned ? [] : ["--collect"]), ], }; - return { ...agentScopeCommand({ command: resolved, args, scope: systemdScope }), unit }; + // systemd-run does not search the caller's cwd, so anchor a relative path to it. Keep ".." + // as spelled: collapsing it would skip a symlinked parent directory. + const executable = path.isAbsolute(resolved) + ? resolved + : `${process.cwd()}${path.sep}${resolved}`; + return { + ...agentScopeCommand({ command: executable, args, scope: systemdScope }), + unit, + }; }), oomKilled, stop, diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 827d52bbda230..83e140161a499 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -161,6 +161,42 @@ it.effect.skipIf(windowsHost)("opens home-relative targets using the server home }).pipe(Effect.provide(NodeServices.layer)), ); +it.effect.skipIf(windowsHost)("reports a Finder reveal that open -R rejects", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + const open = path.join(binDir, "open"); + yield* fileSystem.writeFileString(open, "#!/bin/sh\n"); + yield* fileSystem.chmod(open, 0o755); + const target = path.join(binDir, "linked-file.txt"); + yield* fileSystem.writeFileString(target, ""); + + const exit = yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + return yield* launcher + .launchEditor({ editor: "file-manager", cwd: target, reveal: true }) + .pipe(Effect.exit); + }).pipe( + Effect.provide( + layerTest({ + platform: "darwin", + env: { PATH: binDir }, + spawnResult: (command) => { + assert.deepEqual(command.args, ["-R", target]); + return { exitCode: 1 }; + }, + }), + ), + ); + + assert.ok(Exit.isFailure(exit)); + const error = Cause.squash(exit.cause); + assert.instanceOf(error, ExternalLauncher.ExternalLauncherEditorSpawnError); + assert.include(String(error), target); + }).pipe(Effect.provide(NodeServices.layer)), +); + it.effect.skipIf(windowsHost)( "launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE", () => @@ -864,6 +900,67 @@ for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12 ); } +// Stand-ins for a `--version` check. The Cursor Agent CLI installs a cursor script that fails +// when no IDE is behind it, and a slow first start stays silent for longer than the check waits. +const scripts = { works: "", fails: "exit 1", stalls: "exec sleep 30" }; +// Each row: title, editor, script first on PATH, extra install, result on darwin, result on linux. +for (const [title, id, first, extra, onDarwin, onLinux = onDarwin] of [ + ["keeps a working cursor on PATH ahead of the bundle", "cursor", "works", "bundle", "cursor"], + ["keeps a cursor that never answers --version", "cursor", "stalls", "none", "cursor"], + ["skips a failing cursor for a later cursor on PATH", "cursor", "fails", "later", "later"], + ["skips a failing cursor for the Cursor bundle", "cursor", "fails", "bundle", "bundle", "none"], + ["rejects a zed that never answers --version", "zed", "stalls", "none", "none"], +] as const) { + for (const platform of ["darwin", "linux"] as const) { + it.effect.skipIf(windowsHost)(`${title} on ${platform}`, () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-check-" }); + const commands = { + cursor: "cursor", + none: undefined, + first: path.join(home, "bin", id), + later: path.join(home, "later-bin", id), + bundle: path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/cursor"), + }; + for (const key of ["first", extra] as const) { + if (key === "none") continue; + yield* fs.makeDirectory(path.dirname(commands[key]), { recursive: true }); + const script = key === "first" ? scripts[first] : scripts.works; + yield* fs.writeFileString(commands[key], `#!/bin/sh\n${script}\n`); + yield* fs.chmod(commands[key], 0o755); + } + const editor = EDITORS.find((editor) => editor.id === id)!; + const env = { HOME: home, PATH: `${home}/bin:${home}/later-bin` }; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const started = yield* Deferred.make(); + // Signal that the `--version` check has a running process. + const signal = Deferred.succeed(started, undefined); + const [resolved] = yield* Effect.all( + [ + resolveEditorCommand(editor, env).pipe( + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(Path.Path, withSystemBin(path, path.join(home, "system-bin"))), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((cmd) => spawner.spawn(cmd).pipe(Effect.tap(signal))), + ), + ), + // The check runs on the test clock, so its timeout passes only when the clock moves. + first === "stalls" + ? Deferred.await(started).pipe(Effect.andThen(TestClock.adjust("2 seconds"))) + : Effect.void, + ], + { concurrency: "unbounded" }, + ); + const expected = commands[platform === "darwin" ? onDarwin : onLinux]; + assert.equal(Option.getOrUndefined(resolved)?.command, expected); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + } +} + for (const { layout, pathNames, fallbackNames, expected } of [ { layout: "PATH", pathNames: ["zed", "zeditor"], fallbackNames: [], expected: "zeditor" }, { @@ -923,14 +1020,16 @@ for (const { layout, pathNames, fallbackNames, expected } of [ ); } -// Linux editor discovery also probes fixed system directories; tests point them at a temp -// directory so an editor installed on the host cannot satisfy the lookup. +// Editor discovery also probes fixed system directories (Linux bin folders, macOS /Applications); +// tests point them at a temp directory so an editor installed on the host cannot satisfy the lookup. const withSystemBin = (path: Path.Path, systemBin: string): Path.Path => ({ ...path, join: (...parts) => path.join( ...parts.map((part) => - ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part, + ["/Applications", "/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) + ? systemBin + : part, ), ), }); diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index b5ffaf82fcc10..09a53a51a24bd 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -49,12 +49,14 @@ interface EditorLaunch { readonly command: string; readonly args: ReadonlyArray; readonly detached?: boolean; + readonly waitForExit?: boolean; } interface ProcessLaunch { readonly command: string; readonly args: ReadonlyArray; readonly options: ChildProcess.CommandOptions; + readonly waitForExit?: boolean; } interface TargetPathAndPosition { @@ -663,7 +665,14 @@ const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner > { if (platform === "darwin") { - return { editor: "file-manager", target, command: "open", args: ["-R", target] }; + // `open -R` reports targets Finder cannot reveal only through its exit status. + return { + editor: "file-manager", + target, + command: "open", + args: ["-R", target], + waitForExit: true, + }; } if (platform === "win32") { @@ -881,7 +890,7 @@ const readGraphicalSessionEnv = Effect.fn("externalLauncher.readGraphicalSession Effect.orElseSucceed((): NodeJS.ProcessEnv => ({})), ); -const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* ( +const launchProcess = Effect.fn("externalLauncher.launchProcess")(function* ( launch: ProcessLaunch, onError: (cause: unknown) => ExternalLauncherError, ): Effect.fn.Return { @@ -894,6 +903,14 @@ const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* ( extendEnv: false, }); + if (launch.waitForExit) { + const exitCode = yield* spawner.exitCode(command).pipe(Effect.mapError(onError)); + if (exitCode !== 0) { + return yield* onError(new Error(`${launch.command} exited with status ${exitCode}`)); + } + return; + } + yield* spawner.spawn(command).pipe( Effect.flatMap((handle) => handle.unref), Effect.asVoid, @@ -906,7 +923,7 @@ const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* ( target: string, ): Effect.fn.Return { const launch = yield* resolveBrowserLaunch(target); - return yield* launchAndUnref( + return yield* launchProcess( launch, (cause) => new ExternalLauncherBrowserSpawnError({ @@ -937,10 +954,11 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) { return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor }); } - yield* launchAndUnref( + yield* launchProcess( { command: spawnCommand.command, args: spawnCommand.args, + waitForExit: launch.waitForExit ?? false, options: { detached: launch.detached ?? true, shell: spawnCommand.shell, diff --git a/apps/server/src/process/processLauncherWorker.ts b/apps/server/src/process/processLauncherWorker.ts new file mode 100644 index 0000000000000..58918127d90ad --- /dev/null +++ b/apps/server/src/process/processLauncherWorker.ts @@ -0,0 +1,112 @@ +// @effect-diagnostics nodeBuiltinImport:off - the launcher loads only Node builtins so it starts in milliseconds. +import * as NodeChildProcess from "node:child_process"; +import type * as NodeNet from "node:net"; + +export interface LauncherSpawnRequest { + readonly type: "spawn"; + readonly id: number; + readonly command: string; + readonly args: ReadonlyArray; + readonly options: NodeChildProcess.SpawnOptions; +} + +export interface LauncherError { + readonly message: string; + readonly code?: string | undefined; + readonly errno?: number | undefined; + readonly syscall?: string | undefined; + readonly path?: string | undefined; +} + +/** Per child, in order: `pid`, `stdio` per piped fd (carrying its socket), `spawn`, then `exit`; or `error`. */ +export type LauncherEvent = + | { readonly type: "ready" } + | { readonly type: "pid"; readonly id: number; readonly pid: number } + | { readonly type: "stdio"; readonly id: number; readonly fd: number } + | { readonly type: "spawn"; readonly id: number } + | { + readonly type: "exit"; + readonly id: number; + readonly code: number | null; + readonly signal: NodeJS.Signals | null; + } + | { readonly type: "error"; readonly id: number; readonly error: LauncherError }; + +// Leaves out spawnargs; the server's spawner redacts its own copy. +const toLauncherError = (cause: unknown): LauncherError => { + const error = cause as Partial | undefined; + return { + message: typeof error?.message === "string" ? error.message : String(cause), + code: error?.code, + errno: error?.errno, + syscall: error?.syscall, + path: error?.path, + }; +}; + +// Child stdio has no public paused option; this is what net's pauseOnCreate does. +const stopReading = (socket: NodeNet.Socket) => + (socket as unknown as { _handle?: { readStop?: () => void } | null })._handle?.readStop?.(); + +// Bundled import.meta.main is always true; importing this module must have no side effects. +export function runProcessLauncher(): void { + const channel = process.send?.bind(process); + if (!channel) { + process.stderr.write("The process launcher is started by the T3 server.\n"); + process.exitCode = 1; + return; + } + const send = (event: LauncherEvent, socket?: NodeNet.Socket) => + channel(event, socket, undefined, () => {}); + const children = new Map(); + + // Group signals target the server; this process exits when the server's channel closes. + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => {}); + process.on("disconnect", () => { + for (const child of children.values()) { + try { + process.kill(-child.pid!, "SIGKILL"); + } catch { + child.kill("SIGKILL"); + } + } + process.exit(0); + }); + + process.on("message", (request: LauncherSpawnRequest) => { + const { id } = request; + let child: NodeChildProcess.ChildProcess; + try { + child = NodeChildProcess.spawn(request.command, [...request.args], request.options); + } catch (cause) { + send({ type: "error", id, error: toLauncherError(cause) }); + return; + } + const stdio = child.stdio.map((socket) => socket as NodeNet.Socket | null); + // The server reads and writes these pipes itself, so no byte may be consumed here. + for (const socket of stdio) if (socket) stopReading(socket); + // Node flushes and destroys a child's stdio at exit, even while a socket waits to be sent. + child.stdin = null; + child.stdout = null; + child.stderr = null; + child.stdio.fill(null); + child.on("error", (cause) => { + if (child.pid === undefined) for (const socket of stdio) socket?.destroy(); + send({ type: "error", id, error: toLauncherError(cause) }); + }); + child.once("spawn", () => { + children.set(id, child); + // First, so the server can kill the child if this process dies while handing over its pipes. + send({ type: "pid", id, pid: child.pid! }); + stdio.forEach((socket, fd) => { + if (socket) send({ type: "stdio", id, fd }, socket); + }); + send({ type: "spawn", id }); + }); + child.once("exit", (code, signal) => { + children.delete(id); + send({ type: "exit", id, code, signal }); + }); + }); + send({ type: "ready" }); +} diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index 6768fa23c763b..bd4ad037defa6 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -1,17 +1,27 @@ +// @effect-diagnostics nodeBuiltinImport:off - A test kills the helper mid-handoff and watches its child through a FIFO. import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe"; +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodeNet from "node:net"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Cause from "effect/Cause"; +import * as FileSystem from "effect/FileSystem"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import { ChildProcessSpawner } from "effect/process"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; +import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import * as ProcessRunner from "./processRunner.ts"; type ChildProcessCommand = { @@ -288,6 +298,381 @@ describe("runProcess", () => { ); }); +// The server's spawner stack, as server.ts builds it. +const layerLaunched = ProcessRunner.layer.pipe(Layer.provide(ProcessLauncher.layerServer)); + +// A command's $PPID, required to be the helper: signalling a fallback's parent would hit the test runner. +const expectHelperPid = (stdout: string) => { + expect(stdout.trim()).toMatch(/^[1-9]\d*$/); + const pid = Number(stdout.trim()); + expect(pid, "the command's parent process is the server process itself").not.toBe(process.pid); + return pid; +}; + +describe("ProcessRunner.layer", () => { + // Forking the server for every git call stalls its event loop in proportion to its RSS. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "launches commands from a helper process instead of forking the server", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] }); + + expectHelperPid(result.stdout); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + ); + + // The helper's stdin and stdout are /dev/null, so inherited stdio must come from the server. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "forks the server for a command that inherits its stdio", + () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make("sh", ["-c", "echo $PPID >&2"], { stdin: "inherit" }), + ); + const parent = yield* handle.stderr.pipe(Stream.decodeText(), Stream.mkString); + + expect(Number(parent.trim())).toBe(process.pid); + }).pipe( + Effect.scoped, + Effect.provide(ProcessLauncher.layerServer.pipe(Layer.provideMerge(NodeServices.layer))), + ), + ); + + // Node throws some spawn errnos, such as ENOMEM, instead of emitting "error". + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs commands natively when starting the helper throws", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const launcherArgs = args[1]; + if ( + Array.isArray(launcherArgs) && + launcherArgs.some((arg) => String(arg).includes("process-launcher")) + ) { + throw Object.assign(new Error("spawn ENOMEM"), { code: "ENOMEM" }); + } + return spawn(...args); + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); + const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] }); + + expect(Number(result.stdout.trim())).toBe(process.pid); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + // Callers report a missing CLI from the NotFound reason. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "reports a missing command as a NotFound spawn failure", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const error = yield* runner + .run({ command: "t3code-missing-command", args: [] }) + .pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("NotFound"); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "kills descendants that ignore SIGTERM when a run is interrupted", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const runner = yield* ProcessRunner.ProcessRunner; + const started = yield* Deferred.make(); + const run = yield* runner + .run({ + command: "sh", + // The descendant prints its pid only once it ignores SIGTERM. + args: ["-c", `sh -c 'trap "" TERM; echo $$; exec sleep 1000' & wait`], + onStdoutChunk: (chunk) => + Deferred.doneUnsafe(started, Exit.succeed(Number(new TextDecoder().decode(chunk)))), + }) + .pipe(Effect.forkChild); + const descendant = yield* Deferred.await(started); + const ignored = (yield* fs.readFileString(`/proc/${descendant}/status`)).match( + /^SigIgn:\s*([0-9a-f]+)$/m, + )?.[1]; + expect( + BigInt(`0x${ignored ?? "0"}`) & (1n << 14n), + "the descendant ignores SIGTERM", + ).not.toBe(0n); + yield* Fiber.interrupt(run); + // A killed process stays a zombie until reaped, and a PID namespace's init may never reap it. + const state = yield* fs.readFileString(`/proc/${descendant}/stat`).pipe( + Effect.map((stat) => stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0]), + Effect.orElseSucceed(() => "gone"), + ); + + expect(["gone", "Z"]).toContain(state); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provideMerge(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs in the server's working directory and fails stdin a command never reads", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const result = yield* runner.run({ command: "pwd", args: [] }); + const error = yield* runner + .run({ command: "true", args: [], stdin: "x".repeat(16 * 1024 * 1024) }) + .pipe(Effect.flip); + + expect(result.stdout.trim()).toBe(process.cwd()); + expect(error._tag).toBe("ProcessStdinError"); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "rejects a NUL byte in an environment value without echoing the value", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const error = yield* runner + .run({ command: "true", args: [], env: { T3_TOKEN: "secret\0value" } }) + .pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("BadArgument"); + expect(String(error.cause)).toContain("T3_TOKEN"); + expect(String(error.cause)).not.toContain("secret"); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + ); + + // Descendants keep writing after the leader exits; losing the helper must not truncate that. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "delivers output written after the helper process dies", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make("sh", [ + "-c", + `d=$(mktemp -d); mkfifo "$d/f"; (cat "$d/f"; rm -r "$d") & echo "$PPID $d/f"`, + ]), + ); + expect(yield* handle.exitCode).toBe(0); + const output = yield* handle.stdout.pipe( + Stream.tap((chunk) => { + const [helper = "", fifo] = new TextDecoder().decode(chunk).trim().split(" "); + if (fifo === undefined) return Effect.void; + process.kill(expectHelperPid(helper), "SIGKILL"); + return fs.writeFileString(fifo, "complete\n"); + }), + Stream.decodeText(), + Stream.mkString, + ); + + expect(output).toMatch(/ \S+\ncomplete\n$/); + }).pipe( + Effect.scoped, + Effect.provide(ProcessLauncher.layer.pipe(Layer.provideMerge(NodeServices.layer))), + ), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "kills a command whose helper dies while handing over its pipes", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const fifo = `${yield* fs.makeTempDirectoryScoped()}/alive`; + NodeChildProcess.execFileSync("mkfifo", [fifo]); + // Reaches EOF once the command, its only writer, is gone. + const alive = new NodeNet.Socket({ + fd: NodeFS.openSync(fifo, NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK), + readable: true, + writable: false, + }); + const commandReady = Deferred.makeUnsafe(); + const commandGone = Deferred.makeUnsafe(); + alive.once("data", () => Deferred.doneUnsafe(commandReady, Exit.void)); + alive.once("end", () => Deferred.doneUnsafe(commandGone, Exit.void)); + + const helperPaused = Deferred.makeUnsafe(); + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + helper.on("message", (event: { readonly type: string }) => { + if (event.type !== "stdio" || Deferred.isDoneUnsafe(helperPaused)) return; + process.kill(helper.pid!, "SIGSTOP"); + Deferred.doneUnsafe(helperPaused, Exit.succeed(helper.pid!)); + }); + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); + const run = yield* runner + .run({ + command: "sh", + args: ["-c", `exec 3>"$0"; echo ready >&3; exec sleep 1000`, fifo], + }) + .pipe(Effect.forkChild); + const helper = yield* Deferred.await(helperPaused); + yield* Deferred.await(commandReady); + process.kill(helper, "SIGKILL"); + + expect((yield* Effect.flip(Fiber.join(run)))._tag).toBe("ProcessSpawnError"); + yield* Deferred.await(commandGone); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "fails a command whose output pipe never arrives instead of returning no output", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + const emit = helper.emit.bind(helper); + helper.emit = ((event: string, ...rest: Array) => { + const [message, socket] = rest as [{ type?: string; fd?: number }, NodeNet.Socket?]; + if (event !== "message" || message.type !== "stdio" || message.fd !== 1) { + return emit(event, ...rest); + } + socket?.destroy(); + return emit(event, message, undefined); + }) as typeof helper.emit; + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); + + const error = yield* runner.run({ command: "echo", args: ["output"] }).pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "replaces a helper that stops answering", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const parentPid = runner + .run({ command: "sh", args: ["-c", "echo $PPID"] }) + .pipe(Effect.map((result) => expectHelperPid(result.stdout))); + const helper = yield* parentPid; + process.kill(helper, "SIGSTOP"); + const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip); + const replacement = yield* parentPid; + + expect(error._tag).toBe("ProcessSpawnError"); + expect(replacement).not.toBe(helper); + expect(replacement).not.toBe(process.pid); + }).pipe( + Effect.provide( + ProcessRunner.layer.pipe( + Layer.provide( + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + ProcessLauncher.make("1 second"), + ), + ), + Layer.provide(NodeServices.layer), + ), + ), + ), + ); + + // Under load the server reads the helper's replies late; that is not a hung helper. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "keeps a helper whose replies wait behind a busy server", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + let blocked = false; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + helper.on("message", (event: { readonly type: string }) => { + if (event.type !== "pid" || blocked) return; + blocked = true; + // Holds the server's event loop past the reply deadline, as a loaded server does. + NodeChildProcess.execFileSync("sleep", ["1.5"]); + }); + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get( + yield* Layer.build( + ProcessRunner.layer.pipe( + Layer.provide( + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + ProcessLauncher.make("1 second"), + ), + ), + ), + ), + ProcessRunner.ProcessRunner, + ); + const parentPid = runner + .run({ command: "sh", args: ["-c", "echo $PPID"] }) + .pipe(Effect.map((result) => expectHelperPid(result.stdout))); + const first = yield* parentPid; + const second = yield* parentPid; + + expect(blocked).toBe(true); + expect(second).toBe(first); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); + describe("isWindowsCommandNotFound", () => { it.effect("matches the localized German cmd.exe error text", () => Effect.gen(function* () { diff --git a/apps/server/src/project/AgentSessionJson.ts b/apps/server/src/project/AgentSessionJson.ts index c9dc6baa5f5e6..35b2ac9fad1b0 100644 --- a/apps/server/src/project/AgentSessionJson.ts +++ b/apps/server/src/project/AgentSessionJson.ts @@ -49,7 +49,11 @@ export class TranscriptJsonLimitError extends Schema.TaggedError void, selectPath: (path: JsonPath) => boolean, - options?: { readonly maxDepth?: number }, + options?: { + readonly maxDepth?: number; + // Reports each selected top-level string field as soon as it ends, before the record does. + readonly onTopLevelString?: (key: string, value: string) => void; + }, ) { // 3.6.0 omits the synchronous tokenizer from types; parser() adds an unnecessary async generator. const { jsonParser } = StreamJson as typeof StreamJson & { @@ -133,7 +137,13 @@ export function createTranscriptJsonReader( return; case "endString": case "endNumber": - if (selectedValue) assemble(token); + if (selectedValue) { + const parent = stack[0]; + if (token.name === "endString" && stack.length === 1 && typeof parent?.key === "string") { + options?.onTopLevelString?.(parent.key, value); + } + assemble(token); + } endValue(); return; case "nullValue": diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 590672bb47237..1f7085e7548bf 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -2333,6 +2333,63 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("imports a Claude session whose first prompt carries an image over 1 MiB", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-large-image-claude-"); + const codexHomePath = yield* makeTempDir("t3code-large-image-codex-"); + const workspace = yield* makeTempDir("t3code-large-image-workspace-"); + const sessionId = "large-image-session"; + const contents = [ + { type: "queue-operation", operation: "enqueue", sessionId }, + { type: "queue-operation", operation: "dequeue", sessionId }, + { + type: "user", + cwd: workspace, + sessionId, + timestamp: "2026-08-24T10:00:00.000Z", + message: { + role: "user", + content: [ + { type: "text", text: "Look at this screenshot" }, + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "A".repeat(1_100 * 1024), + }, + }, + ], + }, + }, + { + type: "assistant", + sessionId, + timestamp: "2026-08-24T10:01:00.000Z", + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + }, + ] + .map((record) => encodeTranscriptRecord(record)) + .join("\n"); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-large-image", `${sessionId}.jsonl`), + contents, + mtimeMs: nowMs - 60 * 60 * 1000, + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect(threads.map((thread) => thread.providerSessionId)).toEqual([sessionId]); + }), + ); + it.effect("imports every transcript that fits the per-file record limit", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index baa4c1ad30432..f0fb1adb99d59 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -173,6 +173,17 @@ const decodePiEntryLinks = Schema.decodeUnknownOption( }), ); const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord); +// Only the fields extractCwd reads, so a cwd record carrying a large image stays small in memory. +const selectCwdPath = createTranscriptJsonSelector( + Schema.Struct({ + cwd: Schema.String, + type: Schema.String, + payload: Schema.Struct({ + cwd: Schema.String, + source: Schema.Struct({ subagent: Schema.Null, subAgent: Schema.Null }), + }), + }), +); const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata); export const decodeImportedTranscriptPayload = Schema.decodeUnknownOption( Schema.Struct({ @@ -836,13 +847,7 @@ function isT3ManagedWorktree( } // false stops metadata scanning for an excluded rollout, even if later records contain a cwd. -function extractCwd(line: string, source: AgentSessionSource): string | null | false { - let parsed: unknown; - try { - parsed = JSON.parse(line); - } catch { - return null; - } +function extractCwd(parsed: unknown, source: AgentSessionSource): string | null | false { if (typeof parsed !== "object" || parsed === null) return null; const record = parsed as Record; @@ -1226,11 +1231,28 @@ export const make = Effect.gen(function* () { const size = isCompressedTranscript(transcript.filePath) ? Number.POSITIVE_INFINITY : transcript.identity.size; - const decoder = new TextDecoder(); - let remaining = ""; let bytesRead = 0; let recordsRead = 0; - const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); + let selectedBytes = 0; + const reserveSelected = (bytes: number) => { + selectedBytes += bytes; + if (selectedBytes > MAX_TRANSCRIPT_SCAN_BYTES) { + throw new TranscriptJsonLimitError({ + message: "Transcript cwd fields exceed the scan limit", + }); + } + }; + // Claude writes cwd before message, so a record with a large image need not be read to its end. + let topLevelCwd: string | null = null; + const createReader = () => + createTranscriptJsonReader(reserveSelected, selectCwdPath, { + onTopLevelString: (key, value) => { + if (key === "cwd" && value.trim().length > 0) topLevelCwd ??= value; + }, + }); + let reader = createReader(); + let decoder = new TextDecoder(); + let recordStarted = false; const reserveRecord = () => { if ( recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT || @@ -1243,13 +1265,43 @@ export const make = Effect.gen(function* () { budget.recordsRemaining -= 1; return true; }; - const readLastRecord = () => { - const record = remaining + decoder.decode(); - return record.length === 0 || !reserveRecord() - ? null - : extractCwd(record.trim(), source); + const finishRecord = () => { + reader.write(decoder.decode()); + const value = reader.finish(); + reader = createReader(); + decoder = new TextDecoder(); + recordStarted = false; + selectedBytes = 0; + return extractCwd(value, source); }; + const scanChunk = (chunk: Uint8Array): string | false | null | undefined => { + let start = 0; + while (start < chunk.byteLength) { + const newline = chunk.indexOf(10, start); + const end = newline === -1 ? chunk.byteLength : newline; + if (end > start) { + recordStarted = true; + reader.write(decoder.decode(chunk.subarray(start, end), { stream: true })); + if (topLevelCwd !== null) return reserveRecord() ? topLevelCwd : null; + } + if (newline === -1) return undefined; + if (!reserveRecord()) return null; + const cwd = finishRecord(); + if (cwd !== null) return cwd; + start = newline + 1; + } + return undefined; + }; + const parse = (f: () => A) => + Effect.try({ + try: f, + catch: (cause) => + new TranscriptParseError({ filePath: transcript.filePath, cause }), + }); + const readLastRecord = () => + !recordStarted || !reserveRecord() ? null : finishRecord(); + const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); while (bytesRead < maxBytes) { if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) { budget.truncated = true; @@ -1264,26 +1316,19 @@ export const make = Effect.gen(function* () { budget.bytesRemaining -= readSize; const next = yield* readChunk(readSize); if (Option.isNone(next)) { - return readLastRecord(); + return yield* parse(readLastRecord); } bytesRead += next.value.byteLength; - remaining += decoder.decode(next.value, { stream: true }); - const lines = remaining.split("\n"); - remaining = lines.pop() ?? ""; - - for (const line of lines) { - if (!reserveRecord()) return null; - const cwd = extractCwd(line.trim(), source); - if (cwd !== null) return cwd; - } + const result = yield* parse(() => scanChunk(next.value)); + if (result !== undefined) return result; } if (bytesRead < size) { budget.truncated = true; return null; } - return readLastRecord(); + return yield* parse(readLastRecord); }), ), ), diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index 3b2e6f1179b86..df8bbeb72a912 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -183,6 +183,25 @@ describe("ProjectCloneTracker", () => { }).pipe(Effect.provide(harness.layer)); }); + it.effect("clamps a long failure without splitting a surrogate pair", () => { + const harness = makeHarness({ + clone: () => + Effect.fail( + new SourceControlRepositoryError({ + operation: "cloneRepository", + provider: SourceControlProviderKind.make("unknown"), + detail: `${"e".repeat(998)}\u{1F680}tail`, + }), + ), + }); + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.error).toBe(`${"e".repeat(998)}…`); + }).pipe(Effect.provide(harness.layer)); + }); + it.effect("cancel interrupts the clone and removes the partial checkout", () => { const harness = makeHarness({ clone: () => Effect.never }); return Effect.gen(function* () { diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index 367b839cf2a6b..ca9eb77a9566d 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -14,6 +14,7 @@ import { PROJECT_CLONE_ERROR_MAX_LENGTH, SourceControlRepositoryError, } from "@t3tools/contracts"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -74,7 +75,9 @@ const DONE_RETENTION = "30 seconds"; const STALL_AFTER = "20 seconds"; function clampText(text: string, maxLength: number): string { - return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}…`; + if (text.length <= maxLength) return text; + const end = splitsSurrogatePair(text, maxLength - 1) ? maxLength - 2 : maxLength - 1; + return `${text.slice(0, end)}…`; } const nowIso = Effect.map(DateTime.now, DateTime.formatIso); diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index d00147991cf5d..7c0207eed557d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -219,6 +219,42 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(yield* resolver.resolvePath(paddedCwd)).toBe( (yield* Path.Path).join(paddedCwd, "brand", "custom.svg"), ); + + const tokenListCwd = yield* makeTempDir; + yield* writeTextFile( + tokenListCwd, + "index.html", + ``, + ); + yield* writeTextFile(tokenListCwd, "touch.svg", "touch"); + yield* writeTextFile(tokenListCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(tokenListCwd)).toBe( + (yield* Path.Path).join(tokenListCwd, "brand.svg"), + ); + + const unquotedCwd = yield* makeTempDir; + yield* writeTextFile( + unquotedCwd, + "index.html", + ``, + ); + yield* writeTextFile(unquotedCwd, "app.css", "body {}"); + yield* writeTextFile(unquotedCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(unquotedCwd)).toBe( + (yield* Path.Path).join(unquotedCwd, "brand.svg"), + ); + + const quotedValueCwd = yield* makeTempDir; + yield* writeTextFile( + quotedValueCwd, + "index.html", + ``, + ); + yield* writeTextFile(quotedValueCwd, "app.css", "body {}"); + yield* writeTextFile(quotedValueCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(quotedValueCwd)).toBe( + (yield* Path.Path).join(quotedValueCwd, "brand.svg"), + ); }), ); @@ -248,7 +284,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { head: () => ({ links: [ { rel: "stylesheet", href: "/app.css" }, - { rel: "icon", href: "/brand/logo.svg" }, + { rel: "icon shortcut", href: "/brand/logo.svg" }, ], }), });`, diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 4554c308b4c19..12c8e2fc63ea2 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -77,9 +77,12 @@ const ICON_SOURCE_FILES = [ ] as const; const HTML_LINK_RE = /]*>/gi; -const HTML_ICON_REL_RE = /\brel=["'](?:icon|shortcut icon)["']/i; -const HTML_ICON_HREF_RE = /\bhref=["']([^"'?]+)/i; -const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i; +// `rel` is an unordered, whitespace-separated token list; any `icon` token marks an icon link. +const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])|'(?:[^']*[\t\n\f\r ])?icon(?=[\t\n\f\r ']))`; +// HTML attribute syntax: a name, then an optional double-quoted, single-quoted, or unquoted value. +const HTML_ATTRIBUTE_RE = + /([^\t\n\f\r "'<>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g; +const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i"); const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; export class ProjectFaviconResolutionError extends Schema.TaggedError()( @@ -121,9 +124,28 @@ export class ProjectFaviconResolver extends Context.Service< function extractIconHref(source: string): string | null { for (const [tag] of source.matchAll(HTML_LINK_RE)) { - if (!HTML_ICON_REL_RE.test(tag)) continue; - const hrefMatch = tag.match(HTML_ICON_HREF_RE); - if (hrefMatch?.[1]) return hrefMatch[1]; + const attributes = new Map(); + for (const [, name, doubleQuoted, singleQuoted, unquoted] of tag + .slice("; + readonly previousSession?: TerminalSessionSnapshot; readonly shell?: string | null; }) { const listeners = new Set<(event: TerminalEvent) => Effect.Effect>(); const opens: TerminalOpenInput[] = []; + const openedSessions: TerminalSessionSnapshot[] = []; + let session = options.previousSession; const writes = yield* Queue.unbounded(); const outputLines = yield* Queue.unbounded(); const terminals = Layer.mock(TerminalManager.TerminalManager)({ @@ -60,7 +63,11 @@ const makeHarness = Effect.fn(function* (options: { ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never)) : Effect.void, ), - Effect.as(openSnapshot(options.history ?? "")), + Effect.map(() => { + session ??= openSnapshot(options.history ?? ""); + openedSessions.push(session); + return session; + }), ), getShell: () => options.shell === null @@ -72,6 +79,16 @@ const makeHarness = Effect.fn(function* (options: { return () => listeners.delete(listener); }), write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid), + close: () => + Effect.sync(() => { + session = undefined; + }).pipe( + Effect.andThen( + Effect.forEach([...listeners], (listener) => listener({ ...event, type: "closed" }), { + discard: true, + }), + ), + ), closeIdle: () => Effect.void, closeOnSettle: () => Effect.void, }); @@ -108,13 +125,14 @@ const makeHarness = Effect.fn(function* (options: { }); const emit = (terminalEvent: TerminalEvent) => Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true }); - return { start, listeners, writes, outputLines, emit, opens }; + return { start, listeners, writes, outputLines, emit, openedSessions, opens }; }); const setup = Effect.fn(function* ( options: { readonly command?: string; readonly history?: string; + readonly previousSession?: TerminalSessionSnapshot; readonly shell?: string | null; } = {}, ) { @@ -138,7 +156,9 @@ describe("ProjectSetupScriptRunner", () => { const { writes } = yield* setup({ shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", }); - expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE"); + const submitted = yield* Queue.take(writes); + expect(submitted).toContain("$global:LASTEXITCODE"); + expect(submitted).not.toContain("\x1b[200~"); }), ); @@ -168,10 +188,13 @@ describe("ProjectSetupScriptRunner", () => { }), ); - it.effect("shows a startup prompt and types only once the line editor starts", () => + it.effect("replaces a surviving setup shell and types only once the line editor starts", () => Effect.gen(function* () { - const { result, writes, outputLines, emit } = yield* setup(); + const { result, completion, openedSessions, writes, outputLines, emit } = yield* setup({ + previousSession: openSnapshot("previous setup in the deleted checkout"), + }); expect(result).toMatchObject({ status: "started", terminalId }); + expect(openedSessions).toEqual([openSnapshot("")]); yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " }); yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" }); @@ -181,7 +204,12 @@ describe("ProjectSetupScriptRunner", () => { yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" }); yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" }); - expect(yield* Queue.take(writes)).toContain("vp i"); + const command = yield* Queue.take(writes); + expect(command).toContain("vp i"); + const sentinel = command.match(/__T3_SETUP_DONE___[a-f0-9]+:/)?.[0]; + expect(sentinel).toBeDefined(); + yield* emit({ ...event, type: "output", data: `${sentinel}0\r\n% ` }); + expect(yield* completion).toMatchObject({ exitCode: 0 }); }), ); @@ -209,9 +237,11 @@ describe("ProjectSetupScriptRunner", () => { it.effect("types into a quiet shell that has no line editor", () => Effect.gen(function* () { - const { writes } = yield* setup(); + const { writes } = yield* setup({ command: "printf '%s\\n' 'setup-ready'\n".repeat(120) }); yield* TestClock.adjust("3 seconds"); - expect(yield* Queue.take(writes)).toContain("vp i"); + const submitted = yield* Queue.take(writes); + expect(submitted).toContain("setup-ready"); + expect(submitted).not.toContain("\x1b[200~"); }), ); @@ -237,16 +267,32 @@ describe("ProjectSetupScriptRunner", () => { }), ); - it.effect("drops its terminal listeners when cancelled while the terminal opens", () => - Effect.gen(function* () { - const opening = yield* Deferred.make(); - const { start, listeners } = yield* makeHarness({ opening }); - const fiber = yield* Effect.forkChild(start); - yield* Deferred.await(opening); - expect(listeners.size).toBe(2); - yield* Fiber.interrupt(fiber); - expect(listeners.size).toBe(0); - }), + it.effect.each(["opening", "completion"] as const)( + "stops pending setup when cancelled during %s", + (phase) => + Effect.gen(function* () { + const opening = yield* Deferred.make(); + const { start, listeners, writes, emit } = yield* makeHarness( + phase === "opening" ? { opening } : {}, + ); + const pending = + phase === "opening" + ? start.pipe(Effect.asVoid) + : yield* start.pipe( + Effect.map((result) => + result.status === "started" && result.completion + ? result.completion.pipe(Effect.asVoid) + : Effect.die("setup did not start"), + ), + ); + const fiber = yield* pending.pipe(Effect.forkChild({ startImmediately: true })); + if (phase === "opening") yield* Deferred.await(opening); + expect(listeners.size).toBe(2); + yield* Fiber.interrupt(fiber); + expect(listeners.size).toBe(0); + yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" }); + expect(yield* Queue.size(writes)).toBe(0); + }), ); it.effect.each([false, true])( @@ -271,6 +317,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { const { writes, outputLines, emit, completion } = yield* setup({ command }); yield* emit({ ...event, type: "output", data: "\x1b[?2004h" }); const submitted = yield* Queue.take(writes); + const shellInput = submitted.replace("\x1b[200~", "").replace("\x1b[201~", ""); const cwd = yield* HostProcess.WorkingDirectory; const env = yield* HostProcess.Environment; @@ -281,7 +328,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { const handle = yield* spawner.spawn( ChildProcess.make( "/bin/bash", - ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")], + ["--noprofile", "--norc", "-c", shellInput.replaceAll("\r", "\n")], { cwd, env: { PATH: env.PATH }, @@ -302,6 +349,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { yield* emit({ ...event, type: "closed" }); return { submitted, + shellInput, lines: yield* Queue.clear(outputLines), exitCode: (yield* completion).exitCode, }; @@ -347,9 +395,10 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup co assert.deepEqual(result.lines, expected); assert.equal(result.exitCode, 0); assert.equal(result.submitted.at(-1), "\r"); - assert.notInclude(result.submitted, "\n"); - // The runner can write before the shell switches the terminal out of canonical mode. - for (const line of result.submitted.slice(0, -1).split("\r")) { + assert.isTrue(result.submitted.startsWith(" \x1b[200~")); + assert.isTrue(result.submitted.endsWith("\x1b[201~\r")); + assert.notInclude(result.submitted.slice(0, -1), "\r"); + for (const line of result.shellInput.slice(0, -1).split("\n")) { assert.isBelow(utf8.encode(line).byteLength, 1_024); } }), diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 1c94a3f118757..861750b7cb857 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -13,6 +13,7 @@ import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -412,7 +413,7 @@ export const make = Effect.gen(function* () { const seen = activity; yield* Effect.sleep(SHELL_QUIET_FALLBACK); if (activity !== seen) continue; - if (!busy) return "ready" as const; + if (!busy) return "quiet" as const; yield* input.onStartupPrompt; } }); @@ -506,6 +507,19 @@ export const make = Effect.gen(function* () { trigger === "settle" ? `settle-${script.id}-${(yield* random.uuidV4()).slice(0, 8)}` : `setup-${script.id}`; + // A surviving setup shell may still hold a deleted worktree directory. + if (trigger === "setup") { + yield* terminalManager.close({ threadId: input.threadId, terminalId }).pipe( + Effect.mapError( + (cause) => + new ProjectSetupScriptOperationError({ + ...errorContext, + operation: "openTerminal", + cause, + }), + ), + ); + } const cwd = input.worktreePath; const env = { ...projectScriptRuntimeEnv({ @@ -592,7 +606,7 @@ export const make = Effect.gen(function* () { // Return once the terminal exists so callers can show it while a startup prompt waits. // PowerShell and cmd have no line-editor signal. - yield* ( + const commandWriter = yield* ( completionShell === "powershell" || completionShell === null ? Effect.succeed("ready" as const) : readiness.wait @@ -603,7 +617,12 @@ export const make = Effect.gen(function* () { : terminalManager.write({ threadId: input.threadId, terminalId, - data: projectScriptTerminalInput(commandLine), + // macOS zsh garbles long typed-ahead multiline input; a live line editor takes it as one paste. + data: projectScriptTerminalInput( + shell === "ready" && completionShell === "posix" && commandLine.includes("\r") + ? `\x1b[200~${commandLine.replaceAll("\r", "\n")}\x1b[201~` + : commandLine, + ), }), ), Effect.catchCause((cause) => @@ -618,6 +637,13 @@ export const make = Effect.gen(function* () { ); const completion = observed?.completion.pipe( + Effect.onInterrupt(() => + Fiber.interrupt(commandWriter).pipe( + Effect.andThen(Effect.sync(() => readiness.unsubscribe())), + Effect.andThen(terminalManager.close({ threadId: input.threadId, terminalId })), + Effect.ignore, + ), + ), Effect.tap(({ exitCode }) => exitCode === 0 ? terminalManager.closeIdle({ threadId: input.threadId, terminalId }) diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 996f3f13fca06..b2cc2c2899fea 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -128,6 +128,47 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(ProcessRunner.layer)), ); + it.effect("keys a remote by its configured URL when insteadOf rewrites it", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-instead-of-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "https://github.com/T3Tools/t3code.git"]); + yield* git(cwd, ["config", "url.https://proxy.example/.insteadOf", "https://github.com/"]); + yield* git(cwd, ["config", "remote.origin.gh-resolved", "base"]); + const remotes = yield* git(cwd, ["remote", "-v"]); + expect(remotes.stdout).toContain("https://proxy.example/T3Tools/t3code.git (fetch)"); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + + expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(identity?.provider).toBe("github"); + expect(identity?.displayName).toBe("T3Tools/t3code"); + expect(identity?.locator).toEqual({ + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://github.com/T3Tools/t3code.git", + }); + + const shorthandCwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-instead-of-shorthand-test-", + }); + yield* git(shorthandCwd, ["init"]); + yield* git(shorthandCwd, ["remote", "add", "origin", "gh:T3Tools/t3code.git"]); + yield* git(shorthandCwd, ["config", "url.https://github.com/.insteadOf", "gh:"]); + + const shorthandIdentity = yield* resolver.resolve(shorthandCwd); + + expect(shorthandIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(shorthandIdentity?.provider).toBe("github"); + expect(shorthandIdentity?.locator.remoteUrl).toBe("https://github.com/T3Tools/t3code.git"); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + it.effect("keeps a literal .git in an Azure DevOps repository name", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -193,6 +234,35 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); + it.effect("keeps a login embedded in a remote URL out of the identity", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-credentials-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, [ + "remote", + "add", + "origin", + "https://me:origin-secret@github.com/me/t3code.git", + ]); + yield* git(cwd, [ + "remote", + "add", + "upstream", + "https://x-access-token:upstream-secret@github.com/T3Tools/t3code.git?token=query-secret", + ]); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + expect(identity?.locator.remoteUrl).toBe("https://github.com/T3Tools/t3code.git"); + expect(identity?.origin?.remoteUrl).toBe("https://github.com/me/t3code.git"); + expect(JSON.stringify(identity)).not.toContain("secret"); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + it.effect.each(["repo", "repo ", ...lineBreakSuffixes.map((suffix) => `repo${suffix}`)])( "returns the git top-level root path when resolving from a nested workspace in %j", (rootName) => diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index 22144cb6b9649..d09a9b590d04c 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -1,6 +1,7 @@ import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts"; import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; +import { withoutRemoteUrlCredentials } from "@t3tools/shared/cloneUrl"; import { canonicalRepositoryPath, normalizeGitRemoteUrl } from "@t3tools/shared/git"; import { isSshRemoteUrl } from "@t3tools/shared/sourceControl"; import * as Cache from "effect/Cache"; @@ -51,14 +52,35 @@ function isLocalRemoteUrl(url: string): boolean { return colonIndex === -1 || (slashIndex !== -1 && slashIndex < colonIndex); } -function parseRemoteFetchUrls(stdout: string): Map { +// `git remote -v` applies url.*.insteadOf, which can point a GitHub remote at a proxy or mirror. +// A configured URL that names a forge wins; a shorthand like `gh:` is known only once rewritten. +function parseConfiguredRemoteUrls(config: string): Map { + const urls = new Map(); + for (const line of config.split("\n")) { + const match = /^remote\.(\S+)\.url (.+)$/u.exec(line); + // Git fetches from the first of several configured URLs. + if (match?.[1] && match[2] && !urls.has(match[1])) urls.set(match[1], match[2]); + } + return urls; +} + +function parseRemoteFetchUrls( + stdout: string, + configuredUrls: ReadonlyMap, +): Map { const remotes = new Map(); for (const line of stdout.split(/\r?\n/)) { // Git uses a tab before the URL and one space before the direction; both can occur in URLs. // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line); if (!match) continue; - const [, remoteName = "", remoteUrl = "", direction = ""] = match; + const [, remoteName = "", fetchUrl = "", direction = ""] = match; + const configuredUrl = configuredUrls.get(remoteName); + const remoteUrl = + configuredUrl !== undefined && + (sourceControlDefinitions.recognizeRemote(configuredUrl)?.kind ?? "unknown") !== "unknown" + ? configuredUrl + : fetchUrl; if ( direction !== "fetch" || remoteName.length === 0 || @@ -67,7 +89,8 @@ function parseRemoteFetchUrls(stdout: string): Map { ) { continue; } - remotes.set(remoteName, remoteUrl); + // The identity names the remote, not the login used to reach it. + remotes.set(remoteName, withoutRemoteUrlCredentials(remoteUrl)); } return remotes; } @@ -332,20 +355,24 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn( timeoutBehavior: "timedOutResult", }) .pipe(Effect.option); - const [remoteResult, resolvedResult] = yield* Effect.all( - [runGit(["remote", "-v"]), runGit(["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"])], + const [remoteResult, configResult] = yield* Effect.all( + [ + runGit(["remote", "-v"]), + runGit(["config", "--get-regexp", "^remote\\..*\\.(url|gh-resolved)$"]), + ], { concurrency: "unbounded" }, ); if (remoteResult._tag === "None" || remoteResult.value.code !== 0) { return null; } - const remotes = parseRemoteFetchUrls(remoteResult.value.stdout); - // Exits 1 when no remote has a mark. + // Exits 1 when no key matches. const resolved = - resolvedResult._tag === "Some" && resolvedResult.value.code === 0 - ? resolvedResult.value.stdout - : ""; + configResult._tag === "Some" && configResult.value.code === 0 ? configResult.value.stdout : ""; + const remotes = parseRemoteFetchUrls( + remoteResult.value.stdout, + parseConfiguredRemoteUrls(resolved), + ); const remote = pickPrimaryRemote(remotes, resolved); if (!remote) return null; const originUrl = remotes.get("origin"); diff --git a/apps/server/src/project/WorktreeSetupTracker.test.ts b/apps/server/src/project/WorktreeSetupTracker.test.ts index ed3fcc027c720..956a9205fc1b9 100644 --- a/apps/server/src/project/WorktreeSetupTracker.test.ts +++ b/apps/server/src/project/WorktreeSetupTracker.test.ts @@ -140,4 +140,24 @@ describe("WorktreeSetupTracker", () => { yield* Fiber.interrupt(fiber); }), ); + + it.effect("clamps stage detail and finish error without splitting surrogate pairs", () => + Effect.gen(function* () { + const tracker = yield* WorktreeSetupTracker.make; + yield* tracker.begin({ + threadId, + branch: null, + baseRef: null, + stages: ["agent"], + fiber: null, + }); + + yield* tracker.stageStatus(threadId, "agent", "running", `${"a".repeat(198)}\u{1F680}tail`); + yield* tracker.finish(threadId, "failed", `${"e".repeat(998)}\u{1F680}tail`); + + const final = yield* tracker.get(threadId); + expect(final?.stages[0]?.detail).toBe(`${"a".repeat(198)}\u2026`); + expect(final?.error).toBe(`${"e".repeat(998)}\u2026`); + }), + ); }); diff --git a/apps/server/src/project/WorktreeSetupTracker.ts b/apps/server/src/project/WorktreeSetupTracker.ts index ff5580961d977..d742cad8e4361 100644 --- a/apps/server/src/project/WorktreeSetupTracker.ts +++ b/apps/server/src/project/WorktreeSetupTracker.ts @@ -11,6 +11,7 @@ import { WORKTREE_SETUP_STAGE_ORDER, WORKTREE_SETUP_TAIL_LINE_MAX_LENGTH, } from "@t3tools/contracts"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -67,7 +68,9 @@ export class WorktreeSetupTracker extends Context.Service< const TAIL_LINE_LIMIT = 4; function clampText(text: string, maxLength: number): string { - return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}\u2026`; + if (text.length <= maxLength) return text; + const end = splitsSurrogatePair(text, maxLength - 1) ? maxLength - 2 : maxLength - 1; + return `${text.slice(0, end)}\u2026`; } const clampDetail = (detail: string | null): string | null => diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 88589d1c9a773..219b4c0f5dbbd 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -32,6 +32,7 @@ import { buildAntigravityModelsFromSession, makeAntigravityProvider, } from "./AntigravityProvider.ts"; +import { mergeProviderSnapshot } from "./ProviderRegistry.ts"; const decodeSettings = Schema.decodeSync(AntigravitySettings); const instanceId = ProviderInstanceId.make("antigravity-test"); @@ -255,7 +256,7 @@ describe("Antigravity model catalog", () => { ]); }); - it("offers each model the thinking levels it reported when selected", () => { + it("offers each model only the thinking levels it reported when selected", () => { const thinking = (currentValue: string) => ({ id: "thinking_level", @@ -295,8 +296,70 @@ describe("Antigravity model catalog", () => { expect(thinkingOf("gemini")).toMatchObject({ id: "thinking_level", currentValue: "high" }); expect(thinkingOf("claude")).toMatchObject({ id: "thinking_level", currentValue: "low" }); expect(thinkingOf("plain")).toBeUndefined(); - expect(thinkingOf("unseen")).toMatchObject({ id: "thinking_level" }); - expect(thinkingOf("unseen")).not.toHaveProperty("currentValue"); + expect(thinkingOf("unseen")).toBeUndefined(); + }); + + it("keeps each model's probed thinking levels after a restart observes only the active model", () => { + const thinking = (levels: ReadonlyArray) => + ({ + id: "thinking_level", + name: "Thinking Level", + category: "thought_level", + type: "select", + currentValue: "low", + options: levels.map((value) => ({ value, name: value })), + }) satisfies EffectAcpSchema.SessionConfigOption; + const deep = thinking(["low", "medium", "high", "xhigh"]); + const models = { + ...modelConfig, + currentValue: "neon", + options: [ + { value: "neon", name: "Neon" }, + { value: "carbon", name: "Carbon" }, + { value: "fixed", name: "Fixed effort" }, + ], + } satisfies EffectAcpSchema.SessionConfigOption; + const setup = { configOptions: [models, deep] }; + const provider = { + instanceId, + driver, + status: "ready", + enabled: true, + installed: true, + version: null, + auth: { status: "authenticated" }, + checkedAt: "2026-11-23T00:00:00.000Z", + slashCommands: [], + skills: [], + } as const; + // Sign-in or Refresh models walks every model, so each reports its own levels. + const probed = { + ...provider, + models: buildAntigravityModelsFromSession( + setup, + new Map([ + ["carbon", thinking(["low", "medium", "high"])], + ["fixed", null], + ]), + ), + } satisfies ServerProvider; + // After a restart the provider has observed only the session's model. + const restarted = { + ...provider, + checkedAt: "2026-11-23T01:00:00.000Z", + models: buildAntigravityModelsFromSession(setup, new Map([["neon", deep]])), + } satisfies ServerProvider; + + const merged = mergeProviderSnapshot(probed, restarted); + const levelsOf = (slug: string) => { + const descriptor = merged.models.find((model) => model.slug === slug)?.capabilities + ?.optionDescriptors?.[0]; + return descriptor?.type === "select" ? descriptor.options.map((option) => option.id) : []; + }; + + expect(levelsOf("neon")).toEqual(["low", "medium", "high", "xhigh"]); + expect(levelsOf("carbon")).toEqual(["low", "medium", "high"]); + expect(levelsOf("fixed")).toEqual([]); }); }); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index f5e18f6bece9d..434a81a5123eb 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -65,14 +65,12 @@ type ThinkingConfig = NonNullable>; /** Thinking options each model reported when selected; `null` means it has none. */ export type AntigravityThinkingLevels = ReadonlyMap; -function thinkingCapabilities(config: ThinkingConfig | null | undefined, observed: boolean) { +function thinkingCapabilities(config: ThinkingConfig | null | undefined) { const descriptor = config ? acpProviderOptionDescriptors({ configOptions: [config], modeState: undefined })[0] : undefined; if (descriptor?.type !== "select") return EMPTY_MODEL_CAPABILITIES; - // Another model's selected level is not this model's default. - const { currentValue: _currentValue, ...unobserved } = descriptor; - return createModelCapabilities({ optionDescriptors: [observed ? descriptor : unobserved] }); + return createModelCapabilities({ optionDescriptors: [descriptor] }); } export function buildAntigravityModelsFromSession( @@ -113,10 +111,8 @@ export function buildAntigravityModelsFromSession( ...(entry.value === currentValue ? { isDefault: true, aliases: [ANTIGRAVITY_DEFAULT_MODEL] } : {}), - capabilities: - observed === undefined - ? thinkingCapabilities(currentThinking, false) - : thinkingCapabilities(observed, true), + // Levels differ per model; an unobserved model reports none so the registry keeps its cached ones. + capabilities: thinkingCapabilities(observed), }, ]; }); diff --git a/apps/server/src/provider/CodexManagedRuntime.ts b/apps/server/src/provider/CodexManagedRuntime.ts index 3704c919c2791..5fea80bc66b63 100644 --- a/apps/server/src/provider/CodexManagedRuntime.ts +++ b/apps/server/src/provider/CodexManagedRuntime.ts @@ -5,6 +5,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as ServerConfig from "../config.ts"; +import { resolveLocalOrigin } from "../startupAccess.ts"; import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime"; @@ -49,7 +50,7 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func instanceId: options.instanceId, defaultReturnUrl: new URL( "/welcome", - config.devUrl ?? `http://localhost:${config.port}`, + config.devUrl ?? resolveLocalOrigin(config.host, config.port), ).toString(), }); const homeLayout = yield* resolveManagedCodexHomeLayout( diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 40d78ab16b05f..aa717131c201c 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -400,6 +400,11 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { "---\nname: deploy\n---\n", ); yield* writeSkill(path.join(projectSkills, "internal"), "---\nname: internal\n---\n"); + const releasePath = yield* writeSkill( + path.join(projectSkills, "public"), + "---\nname: release\n---\n", + ); + yield* writeSkill(path.join(projectSkills, "excluded"), "---\nname: excluded-root\n---\n"); // agy does not expand ~, so a ~/ entry loads nothing. yield* writeSkill( @@ -442,6 +447,9 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { entries: [ { path: "tools/skills/deploy/SKILL.md", exclude: null }, { path: "tools/skills/internal/SKILL.md", exclude: ["internal"] }, + { path: "tools/skills/public", include_only: ["public"] }, + { path: "tools/skills/excluded", exclude: ["excluded"] }, + { path: "tools/skills/excluded", include_only: ["public"] }, ], }), ); @@ -455,6 +463,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { enabled: true, }, { name: "linter", path: inheritedPath, scope: "user", enabled: true }, + { name: "release", path: releasePath, scope: "project", enabled: true }, { name: "yagni", description: "Keep it simple.", diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index edbe5e34a7343..28c5d4f34d09c 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -305,7 +305,9 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( const sortedEntries = entries.toSorted(); const skillFileName = sortedEntries.find((entry) => entry.toLowerCase() === "skill.md"); if (skillFileName !== undefined) { - yield* addSkillFile(path.join(directory, skillFileName), scope); + if (matchesSkillFilter(path.basename(directory), filter)) { + yield* addSkillFile(path.join(directory, skillFileName), scope); + } return; } if (scanChildren) { diff --git a/apps/server/src/provider/ProviderHostPathWatcher.ts b/apps/server/src/provider/ProviderHostPathWatcher.ts new file mode 100644 index 0000000000000..b77d9ec39e31d --- /dev/null +++ b/apps/server/src/provider/ProviderHostPathWatcher.ts @@ -0,0 +1,18 @@ +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts"; +import * as ProviderRegistry from "./ProviderRegistry.ts"; + +/** The desktop's shell PATH can arrive after drivers were built and checked against a bare one. */ +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + const receiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver; + const providers = yield* ProviderRegistry.ProviderRegistry; + yield* receiver.pathChanges.pipe( + Stream.runForEach(() => providers.rebuildMissingAndRefresh), + Effect.forkScoped, + ); + }), +); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index f343093d7c9ef..37bf3881f9c73 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -709,7 +709,6 @@ export const makeProviderInstanceRegistry = Effect.fn( ), { reference, value }, ); - // Reading secrets can wait on a vault unlock, so the server does not wait for it to start. yield* semaphore.withPermits(1)( Ref.set(configMapRef, input.configMap).pipe( diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 4fe6da7f791a9..31ce877de6f72 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -79,6 +79,7 @@ import { } from "./providerStatusCache.ts"; import { COMPACT_SLASH_COMMAND } from "@t3tools/provider-core/server/snapshotProbe"; import type { + AnyProviderDriver, ProviderInstance, ProviderWorkspaceSnapshot, } from "@t3tools/provider-core/server/driver"; @@ -88,6 +89,10 @@ import * as ProviderRegistry from "./ProviderRegistry.ts"; import { ProviderDriverError } from "@t3tools/provider-core/server/errors"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as ProviderHostPathWatcher from "./ProviderHostPathWatcher.ts"; +import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts"; +import { providerHostEnvironment } from "../policy/managedProviders.ts"; vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); const decodeServerProvider = Schema.decodeSync(ServerProvider); @@ -245,7 +250,11 @@ const makeWorkspaceRescanHarness = Effect.gen(function* () { const nextScan = Effect.fnUntraced(function* (cwd: string) { const scan = yield* Queue.take(scans); assert.equal(scan.cwd, cwd); - return (name: string) => Deferred.succeed(scan.result, snapshot(name)); + return (name: string, workspaceModels?: ProviderWorkspaceSnapshot["workspaceModels"]) => + Deferred.succeed(scan.result, { + ...snapshot(name), + ...(workspaceModels ? { workspaceModels } : {}), + }); }); const refresh = (cwd: string, fresh = false) => registry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh }); @@ -1796,6 +1805,176 @@ it.layer( ); }); + it.effect.each([ + "replay", + "in-flight missing", + "in-flight installed", + "installed error", + ] as const)("recovers a copied driver environment after late PATH (%s)", (mode) => + Effect.gen(function* () { + // "installed error": the CLI is found on the early PATH but its check fails until the late + // PATH. Installed instances may hold live sessions, so it must not be rebuilt. + const failsEarly = mode === "installed error"; + const replay = mode === "replay" || failsEarly; + const host = { PATH: "/early/bin", T3CODE_CODEX_LAUNCH_ARGS: "hidden" }; + const environment = providerHostEnvironment( + { organization: "PATH test", lockedSettings: [] }, + host, + ); + const updates = yield* DesktopTelemetryReceiver.makeDesktopShellEnvironmentUpdates( + host, + "linux", + ); + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + const finished = yield* Deferred.make(); + const paths: Array = []; + let first = true; + const driverKind = ProviderDriverKind.make("pi"); + const instanceId = ProviderInstanceId.make("late-path"); + const driver: AnyProviderDriver = { + driverKind, + metadata: { displayName: "PATH fixture" }, + configSchema: Schema.Unknown, + defaultConfig: () => ({}), + create: (input) => + Effect.gen(function* () { + const copied = { ...environment }; + paths.push(copied.PATH); + const late = copied.PATH?.includes("/late/bin") === true; + const installed = mode === "in-flight installed" || failsEarly || late; + const ready = failsEarly ? late : installed; + const snapshot: ServerProvider = { + instanceId, + driver: driverKind, + enabled: true, + installed: false, + status: "warning", + auth: { status: "unknown" }, + version: null, + checkedAt: "2026-10-03T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + }; + const current = yield* Ref.make(snapshot); + return { + instanceId: input.instanceId, + driverKind, + enabled: true, + displayName: undefined, + continuationIdentity: { driverKind, continuationKey: `${driverKind}:late-path` }, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driverKind, + packageName: null, + }), + ), + getSnapshot: Ref.get(current), + refresh: Effect.gen(function* () { + if (first && !replay) { + first = false; + yield* Deferred.succeed(entered, undefined); + yield* Deferred.await(release); + } + const checked = { + ...snapshot, + installed, + status: ready ? ("ready" as const) : ("error" as const), + ...(ready + ? {} + : { + message: "Provider probe failed: transport failed.", + }), + }; + yield* Ref.set(current, checked); + return checked; + }), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + }), + }; + const built = yield* ProviderInstanceRegistry.makeProviderInstanceRegistry({ + drivers: [driver], + configMap: { [instanceId]: { driver: driverKind, enabled: true } }, + }).pipe(Effect.provide(Layer.mock(SecretResolver.SecretResolver)({}))); + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + const running = replay ? undefined : yield* registry.refresh().pipe(Effect.forkScoped); + if (running) yield* Deferred.await(entered); + yield* updates.apply({ + version: 1, + type: "shellEnvironment", + platform: "linux", + discovered: true, + environment: { PATH: "/early/bin:/late/bin" }, + }); + expect(paths).toEqual(["/early/bin"]); + if (replay) { + yield* Layer.build( + ProviderHostPathWatcher.layer.pipe( + Layer.provide( + DesktopTelemetryReceiver.layerTest({ pathChanges: updates.pathChanges }), + ), + Layer.provide( + Layer.succeed(ProviderRegistry.ProviderRegistry, { + ...registry, + rebuildMissingAndRefresh: registry.rebuildMissingAndRefresh.pipe( + Effect.tap(() => Deferred.succeed(finished, undefined)), + ), + }), + ), + ), + ); + } else { + yield* registry.rebuildMissingAndRefresh.pipe( + Effect.tap(() => Deferred.succeed(finished, undefined)), + Effect.forkScoped({ startImmediately: true }), + ); + expect(paths).toEqual(["/early/bin"]); + } + yield* Deferred.succeed(release, undefined); + if (running) yield* Fiber.join(running); + yield* Deferred.await(finished); + expect( + (yield* registry.getProviders).find((row) => row.instanceId === instanceId)?.installed, + ).toBe(true); + expect(paths).toEqual( + mode === "in-flight installed" || mode === "installed error" + ? ["/early/bin"] + : ["/early/bin", "/early/bin:/late/bin"], + ); + }).pipe( + Effect.provide( + ProviderRegistry.layer.pipe( + Layer.provide( + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, built.registry), + ), + Layer.provide( + Layer.succeed( + ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, + built.mutator, + ), + ), + ), + ), + ); + }).pipe( + Effect.scoped, + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-late-path-" }).pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), + ); + describe("Codex model inventories", () => { const cachedProvider = { instanceId: ProviderInstanceId.make("codex-personal"), @@ -2798,6 +2977,21 @@ it.layer( }), ); + it.effect("stamps a rescan that changed only the directory's models", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* h.seed("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + const complete = yield* h.nextScan("/workspace"); + yield* complete("initial", [ + { slug: "vendor/live", name: "Live", isCustom: false, capabilities: null }, + ]); + yield* h.drainRescans; + assert.isString(yield* h.rescannedAtOf); + }), + ); + it.effect("leaves workspaceRescannedAt unset when a rescan changes nothing", () => Effect.gen(function* () { const h = yield* makeWorkspaceRescanHarness; diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 172599fd29c88..27401b64e64d8 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -76,6 +76,12 @@ export class ProviderRegistry extends Context.Service< instanceId?: ProviderInstanceId, ) => Effect.Effect>; + /** + * Rebuilds and re-checks enabled instances not yet found installed after the host environment + * changed. Drivers copy the environment when built, so only a rebuild sees a later PATH. + */ + readonly rebuildMissingAndRefresh: Effect.Effect>; + /** Rebuilds and refreshes only the instances that read a secret, with the value the caller just read. */ readonly applySecretAndRefresh: ( reference: SecretReference, @@ -856,6 +862,35 @@ export const layer = Layer.effect( return yield* instanceId === undefined ? refresh() : refreshInstance(instanceId); }); + // Only instances whose CLI was not found are rebuilt; installed ones may have live sessions. + const rebuildMissingAndRefresh = Effect.fn("rebuildMissingAndRefresh")(function* () { + const instances = yield* instanceRegistry.listInstances; + yield* refresh().pipe(Effect.catchCause(recoverRefreshFailure)); + const missing = yield* Effect.filter(instances, (instance) => + Effect.gen(function* () { + // ACP also reports installed:false for setup states unrelated to executable discovery. + if ( + !instance.enabled || + instance.driverKind === "acpRegistry" || + !(yield* isCurrentInstance(instance)) + ) + return false; + const snapshot = yield* instance.snapshot.getSnapshot; + return !snapshot.installed; + }), + ); + if (missing.length === 0) return yield* Ref.get(providersRef); + yield* instanceRegistryMutator.rebuild(missing.map((instance) => instance.instanceId)); + // A shared pass already in flight may hold the retired instances, so probe each rebuilt one. + yield* Effect.forEach( + missing, + (instance) => + refreshInstance(instance.instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), + { concurrency: "unbounded", discard: true }, + ); + return yield* Ref.get(providersRef); + }); + const applySecretAndRefresh = Effect.fn("applySecretAndRefresh")(function* ( reference: SecretReference, value: string, @@ -1267,6 +1302,7 @@ export const layer = Layer.effect( return input.rescan && !( Equal.equals(rescanned?.skills, held?.skills) && + Equal.equals(rescanned?.models, held?.models) && Equal.equals(rescanned?.slashCommands, held?.slashCommands) ) ? { ...scanned, workspaceRescannedAt: scannedAt } @@ -1367,6 +1403,9 @@ export const layer = Layer.effect( refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), reloadSecretsAndRefresh: (instanceId?: ProviderInstanceId) => reloadSecretsAndRefresh(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), + rebuildMissingAndRefresh: rebuildMissingAndRefresh().pipe( + Effect.catchCause(recoverRefreshFailure), + ), applySecretAndRefresh: (reference: SecretReference, value: string) => applySecretAndRefresh(reference, value).pipe(Effect.catchCause(recoverRefreshFailure)), refreshWorkspaceSnapshot: (input) => diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index a000e05471bc6..c03435628ba12 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -29,7 +29,7 @@ import type * as EffectAcpProtocol from "effect-acp/protocol"; const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts"); -const mockAgentCommand = "node"; +const mockAgentCommand = process.execPath; const mockAgentArgs = [mockAgentPath]; const mockRuntimeOptions = { spawn: { command: mockAgentCommand, args: mockAgentArgs }, @@ -563,27 +563,34 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); - it.effect("does not restore ambient variables to a sanitized child environment", () => - Effect.gen(function* () { - yield* Effect.acquireRelease( - Effect.sync(() => setProcessEnv("T3_ACP_RUNTIME_AMBIENT", "sentinel")), - (restore) => Effect.sync(restore), - ); - const runtime = yield* AcpSessionRuntime.make({ - ...mockRuntimeOptions, - spawn: { - command: process.execPath, - args: mockAgentArgs, - extendEnv: false, - env: { T3_ACP_RUNTIME_EXPLICIT: "kept" }, - }, - }); - yield* runtime.initialize(); - expect(yield* runtime.request("_test/environment", {})).toEqual({ - inherited: false, - explicit: true, - }); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + // A provided env is the complete child environment, as in OpenCodeRuntime; the AppImage + // scrub deletes mount-only variables, which inheritance would put back. + it.effect.each([ + { label: "with extendEnv false", extendEnv: false as const }, + { label: "when extendEnv is unset", extendEnv: undefined }, + ])( + "does not restore ambient variables to a sanitized child environment $label", + ({ extendEnv }) => + Effect.gen(function* () { + yield* Effect.acquireRelease( + Effect.sync(() => setProcessEnv("T3_ACP_RUNTIME_AMBIENT", "sentinel")), + (restore) => Effect.sync(restore), + ); + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + spawn: { + command: process.execPath, + args: mockAgentArgs, + ...(extendEnv === undefined ? {} : { extendEnv }), + env: { T3_ACP_RUNTIME_EXPLICIT: "kept" }, + }, + }); + yield* runtime.initialize(); + expect(yield* runtime.request("_test/environment", {})).toEqual({ + inherited: false, + explicit: true, + }); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); it("selects explicit or agent-managed authentication without choosing terminal auth", () => { diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index d86ca3ead0f3c..902ad272aa548 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -732,4 +732,38 @@ describe("Antigravity served reads", () => { status: "completed", }); }); + + it("drops agy's toolSummary from T3 MCP call arguments only", () => { + const t3Call = normalizeAntigravityToolCall( + parseToolUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "call_t3_send", + title: "Run mcp_t3-code_send_to_user", + kind: "other", + status: "in_progress", + rawInput: { message: "Hello", toolSummary: "Send greeting" }, + }, + }), + ).toolCall, + ); + expect(t3Call.data.rawInput).toEqual({ message: "Hello" }); + + const foreignCall = normalizeAntigravityToolCall( + parseToolUpdate({ + sessionId: "session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "call_other", + title: "Run mcp_other_send_to_user", + kind: "other", + status: "in_progress", + rawInput: { message: "Hello", toolSummary: "Send greeting" }, + }, + }).toolCall, + ); + expect(foreignCall.data.rawInput).toEqual({ message: "Hello", toolSummary: "Send greeting" }); + }); }); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 008579d087f05..0b774bc4d5e2a 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -4,13 +4,17 @@ import type { UserInputQuestion, } from "@t3tools/contracts"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview"; +import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation"; import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as AcpWireSchema from "effect-acp/schema-v1"; -import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; +import { + extractMcpToolCallIdentity, + type AcpToolCallState, +} from "@t3tools/provider-acp/server/runtimeModel"; import { ANTIGRAVITY_EDIT_DIFF_OMITTED, @@ -376,6 +380,54 @@ export function makeAntigravityReadRepair() { }; } +function stripAntigravityToolSummary(value: unknown): unknown { + if (!Predicate.isObject(value) || Array.isArray(value)) return value; + const record = value as Record; + let next: Record = record; + if ("toolSummary" in next) { + const { toolSummary: _toolSummary, ...rest } = next; + next = rest; + } + if (Predicate.isObject(next.Arguments) && "toolSummary" in next.Arguments) { + const { toolSummary: _toolSummary, ...args } = next.Arguments; + next = { ...next, Arguments: args }; + } + return next; +} + +/** + * agy adds its own `toolSummary` to MCP call arguments. T3 records its MCP results under the + * arguments it received, so the summary is dropped before the shared adapter matches them. + * Untitled updates cannot be identified and are stripped too; titled non-T3 calls keep it. + */ +function withoutT3McpToolSummary( + update: Extract< + EffectAcpSchema.SessionNotification["update"], + { readonly sessionUpdate: "tool_call" | "tool_call_update" } + >, +): unknown { + const rawInput = update.rawInput; + if (!Predicate.isObject(rawInput) || Array.isArray(rawInput)) return rawInput; + if (typeof update.title === "string") { + const identity = extractMcpToolCallIdentity({ + toolCallId: update.toolCallId, + title: update.title, + data: { + title: update.title, + rawInput, + ...(Predicate.isObject(update._meta) ? { meta: update._meta } : {}), + }, + }); + if ( + identity === undefined || + resolveT3McpToolId(`${identity.server}.${identity.tool}`) === null + ) { + return rawInput; + } + } + return stripAntigravityToolSummary(rawInput); +} + export function normalizeAntigravitySessionUpdate( notification: EffectAcpSchema.SessionNotification, ): EffectAcpSchema.SessionNotification { @@ -397,7 +449,7 @@ export function normalizeAntigravitySessionUpdate( ...update, ...(typeof update.title === "string" ? { title: boundText(update.title) } : {}), ...(update.rawInput !== undefined - ? { rawInput: sanitizeAntigravityToolPayload(update.rawInput) } + ? { rawInput: sanitizeAntigravityToolPayload(withoutT3McpToolSummary(update)) } : {}), ...(update.rawOutput !== undefined ? { rawOutput: sanitizeAntigravityToolPayload(update.rawOutput) } diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 9ddc4254d9fea..f9f8bfa7b0e3f 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5945, "codexAdditionalContextBytes": 7339, - "mcpToolListJsonBytes": 67360 + "mcpToolListJsonBytes": 67345 } diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 0acffd168c07d..9ecef186efe77 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -115,6 +115,13 @@ function xml(source: string, extension: string): XmlNode { if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); if ( (extension === ".docx" && node.name === "del") || + (extension === ".docx" && + node.name === "r" && + children(node) + .flatMap((child) => (child.name === "rPr" ? children(child) : [])) + .some( + (prop) => prop.name === "vanish" && ["true", "1", "on"].includes(prop.attrs.val ?? "1"), + )) || (odf && node.name === "annotation" && parent.name !== "semantics") || (extension === ".odp" && node.name === "page-thumbnail" && @@ -142,6 +149,20 @@ function xml(source: string, extension: string): XmlNode { const children = (node: XmlNode | undefined) => node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? []; +function slideRelationshipId(slide: XmlNode, inheritedAttributes: XmlNode["attrs"]) { + for (const [name, value] of Object.entries(slide.attrs)) { + if (!name.endsWith(":id")) continue; + const binding = `xmlns:${name.slice(0, -3)}`; + const namespace = slide.attrs[binding] ?? inheritedAttributes[binding]; + if ( + namespace === "http://schemas.openxmlformats.org/officeDocument/2006/relationships" || + namespace === "http://purl.oclc.org/ooxml/officeDocument/relationships" + ) + return value; + } + return slide.attrs["r:id"] ?? slide.attrs.id; +} + function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean { // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes. // Keep one when no Choice carries text, such as a chart with a VML caption. @@ -442,6 +463,7 @@ function* notebook(source: string): Generator { // Per-byte decoding only supports the single-byte \fcharset values. const FONT_CODE_PAGES = new Map([ + [0, "windows-1252"], [77, "macintosh"], [161, "windows-1253"], [162, "windows-1254"], @@ -454,6 +476,18 @@ const FONT_CODE_PAGES = new Map([ [238, "windows-1250"], ]); +// Per-byte decoding only supports single-byte code pages. +const singleByteCodePage = (value: number) => + value === 0 + ? "windows-1252" + : value === 866 + ? "ibm866" + : value === 10000 + ? "macintosh" + : value === 874 || (value >= 1250 && value <= 1258) + ? `windows-${value}` + : undefined; + function* rtf(source: string): Generator { if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document"); let state = { @@ -463,10 +497,12 @@ function* rtf(source: string): Generator { uc: 1, font: 0, fontTable: false, + fontFile: false, decoder: new TextDecoder("windows-1252"), }; const stack: Array = []; - // A font's \fcharset, not the document code page, encodes the bytes written in that font. + // A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in + // that font. A \cpg inside \fontfile encodes the font's file name instead. const fonts = new Map(); let defaultFont = 0; const decoder = () => fonts.get(state.font) ?? state.decoder; @@ -540,6 +576,7 @@ function* rtf(source: string): Generator { ) state.skip = true; if (control === "fonttbl") state.fontTable = true; + else if (control === "fontfile") state.fontFile = true; else if (control === "deff") state.font = defaultFont = value; else if (control === "f") { state.font = value; @@ -547,6 +584,9 @@ function* rtf(source: string): Generator { } else if (control === "fcharset" && state.fontTable) { const codePage = FONT_CODE_PAGES.get(value); if (codePage) fonts.set(state.font, new TextDecoder(codePage)); + } else if (control === "cpg" && state.fontTable && !state.fontFile) { + const codePage = singleByteCodePage(value); + if (codePage) fonts.set(state.font, new TextDecoder(codePage)); } if (control === "deleted") state.deleted = value !== 0; else if (control === "v") state.hiddenText = value !== 0; @@ -558,10 +598,9 @@ function* rtf(source: string): Generator { if (control === "mac" || (control === "ansicpg" && value === 10000)) state.decoder = new TextDecoder("macintosh"); else if (control === "ansicpg") { - // Per-byte decoding only supports single-byte Windows code pages. - if (value !== 874 && (value < 1250 || value > 1258)) - throw new Error("Unsupported RTF code page"); - state.decoder = new TextDecoder(`windows-${value}`, { fatal: true }); + const label = singleByteCodePage(value); + if (!label) throw new Error("Unsupported RTF code page"); + state.decoder = new TextDecoder(label, { fatal: true }); } else if (control === "uc") { if (!Number.isSafeInteger(value) || value < 0) throw new Error("Invalid RTF fallback count"); @@ -599,12 +638,19 @@ async function* document(path: string, extension: string): AsyncGenerator name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase()); + const folded = new Map(); + for (const name of files.keys()) + if (!folded.has(foldAscii(name))) folded.set(foldAscii(name), name); + const part = (name: string) => (files.has(name) ? name : (folded.get(foldAscii(name)) ?? name)); + const has = (name: string) => files.has(part(name)); const notes: string[] = []; const skip = (name: string) => notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`); const read = (name: string): XmlNode => { try { - const data = files.get(name); + const data = files.get(part(name)); if (!data) throw new Error("Missing document part"); return xml(data, extension); } catch (error) { @@ -613,22 +659,31 @@ async function* document(path: string, extension: string): AsyncGenerator + NodePath.posix.join( + NodePath.posix.dirname(name), + "_rels", + `${NodePath.posix.basename(name)}.rels`, + ); const relations = (name: string) => new Map( [...all(read(name), "Relationship")] .filter((rel) => rel.attrs.TargetMode !== "External") - .map((rel) => [rel.attrs.Id, rel.attrs.Target]), + .map((rel) => [rel.attrs.Id, rel.attrs]), ); - if (extension === ".docx") { - // The package relationship names the main part; Word for the web saves word/document2.xml. - const target = files.has("_rels/.rels") + // The package relationship names the main part; Word for the web saves word/document2.xml. + const mainPart = (fallback: string) => { + const target = has("_rels/.rels") ? [...all(read("_rels/.rels"), "Relationship")].find( (rel) => rel.attrs.Type?.endsWith("/officeDocument") && rel.attrs.TargetMode !== "External", )?.attrs.Target : undefined; const main = target && NodePath.posix.normalize(target).replace(/^\//, ""); - yield* paragraphs(read(main && files.has(main) ? main : "word/document.xml")); + return main && has(main) ? main : fallback; + }; + if (extension === ".docx") { + yield* paragraphs(read(mainPart("word/document.xml"))); } else if ([".odt", ".ods", ".odp"].includes(extension)) { const content = read("content.xml"); if (extension === ".odt") yield* paragraphs(content); @@ -654,13 +709,24 @@ async function* document(path: string, extension: string): AsyncGenerator + NodePath.posix.resolve(`/${workbookDir}`, target).slice(1); + const workbook = read(workbookPath); + const rels = relations(partRels(workbookPath)); + const workbookRelations = [...rels.values()]; + const workbookPartPath = (part: string) => { + const target = workbookRelations.find((rel) => rel.Type?.endsWith(`/${part}`))?.Target; + return resolveWorkbookPart(target || `${part}.xml`); + }; const dateSystem = ["1", "true"].includes( all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "", ) ? "1904" : "1900"; - const styles = files.has("xl/styles.xml") ? read("xl/styles.xml") : undefined; + const stylesPath = workbookPartPath("styles"); + const styles = has(stylesPath) ? read(stylesPath) : undefined; const customFormats = new Map( styles ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode]) @@ -668,21 +734,17 @@ async function* document(path: string, extension: string): AsyncGenerator { const value = all(cell, "v").next().value; if (cell.attrs.t === "s") { @@ -744,27 +806,24 @@ async function* document(path: string, extension: string): AsyncGenerator node.name === "sldIdLst"); + const inheritedAttributes = { ...presentation?.attrs, ...slideList?.attrs }; let index = 0; for (const slide of children(slideList).filter((node) => node.name === "sldId")) { yield `\n\n## Slide ${++index}\n`; - const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id); + const target = rels.get(slideRelationshipId(slide, inheritedAttributes))?.Target; if (!target) { skip(`slide relationship ${index}`); continue; } - const name = target.startsWith("/") - ? target.slice(1) - : NodePath.posix.normalize(`ppt/${target}`); + const name = NodePath.posix.resolve(`/${presentationDir}`, target).slice(1); yield* paragraphs(read(name)); - const slideRels = NodePath.posix.join( - NodePath.posix.dirname(name), - "_rels", - `${NodePath.posix.basename(name)}.rels`, - ); - if (!files.has(slideRels)) continue; + const slideRels = partRels(name); + if (!has(slideRels)) continue; for (const rel of all(read(slideRels), "Relationship")) { const target = rel.attrs.Target; if ( @@ -786,7 +845,7 @@ async function* document(path: string, extension: string): AsyncGenerator [item.attrs.id, item.attrs.href]), @@ -808,7 +871,7 @@ async function* document(path: string, extension: string): AsyncGenerator Ref.get(providersRef), refreshInstance: () => Ref.get(providersRef), reloadSecretsAndRefresh: () => Ref.get(providersRef), + rebuildMissingAndRefresh: Ref.get(providersRef), applySecretAndRefresh: () => Ref.get(providersRef), refreshAfterUpdate: () => { const version = options?.installedVersionAfterUpdate; @@ -250,27 +253,25 @@ const makeTestRunner = ( }, latestVersions: Layer.Layer = ProviderLatestVersions.layer, ) => - Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe( - Effect.provide( - ProviderMaintenanceRunner.layer.pipe( - Layer.provide( - Layer.mergeAll( - Layer.succeed(ProviderRegistry.ProviderRegistry, registry), - Layer.succeed(ModelManifest.ModelManifest, { - current: Effect.succeed(manifest), - refresh: Effect.succeed(manifest), - forceRefresh: Effect.succeed(manifest), - refreshOnDemand: Effect.succeed(manifest), - refreshInBackground: Effect.void, - }), - latestVersions, - // Layers memoize by reference, so a test that provides the gate shares it. - ProviderInstallationGate.layer, - ), + Layer.build( + ProviderMaintenanceRunner.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(ProviderRegistry.ProviderRegistry, registry), + Layer.succeed(ModelManifest.ModelManifest, { + current: Effect.succeed(manifest), + refresh: Effect.succeed(manifest), + forceRefresh: Effect.succeed(manifest), + refreshOnDemand: Effect.succeed(manifest), + refreshInBackground: Effect.void, + }), + latestVersions, + // Layers memoize by reference, so a test that provides the gate shares it. + ProviderInstallationGate.layer, ), ), ), - ); + ).pipe(Effect.map(Context.get(ProviderMaintenanceRunner.ProviderMaintenanceRunner))); function layerFailingLatestLookupAfterFirst() { let lookups = 0; @@ -905,14 +906,15 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("an interrupted update ends failed instead of running forever", () => { + it.effect("an update stopped by server shutdown ends failed instead of running forever", () => { const started = Deferred.makeUnsafe(); return Effect.gen(function* () { const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); - const updater = yield* makeTestRunner(registry); - const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + const serverScope = yield* Scope.make(); + const updater = yield* makeTestRunner(registry).pipe(Scope.provide(serverScope)); + yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); yield* Deferred.await(started); - yield* Fiber.interrupt(update); + yield* Scope.close(serverScope, Exit.void); const last = (yield* Ref.get(updateStatesRef)).at(-1); assert.deepStrictEqual( [last?.status, last?.message], @@ -931,11 +933,12 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("a request dropped while the final state is written still records it", () => { + it.effect("a shutdown while the final state is written still records it", () => { const writing = Deferred.makeUnsafe(); const release = Deferred.makeUnsafe(); return Effect.gen(function* () { const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); + const serverScope = yield* Scope.make(); const updater = yield* makeTestRunner({ ...registry, setProviderMaintenanceActionState: (input) => @@ -945,13 +948,13 @@ describe("providerMaintenanceRunner", () => { Effect.andThen(registry.setProviderMaintenanceActionState(input)), ) : registry.setProviderMaintenanceActionState(input), - }); + }).pipe(Scope.provide(serverScope)); - const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); yield* Deferred.await(writing); - update.interruptUnsafe(); + const shutdown = yield* Scope.close(serverScope, Exit.void).pipe(Effect.forkScoped); yield* Deferred.succeed(release, undefined); - yield* Fiber.await(update); + yield* Fiber.join(shutdown); assert.strictEqual((yield* Ref.get(updateStatesRef)).at(-1)?.status, "succeeded"); }).pipe( @@ -1150,58 +1153,124 @@ describe("providerMaintenanceRunner", () => { ); }); + it.effect("finishes a queued update whose caller is interrupted", () => + Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseProvider, { + installedVersionAfterUpdate: "1.0.0", + }); + const firstFinished = yield* Deferred.make(); + let blockQueuedState = true; + const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} }; + const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} }; + const queuedStateWritten = new Promise((resolve) => { + queuedStateWrittenLatch.resolve = resolve; + }); + const releaseQueuedState = new Promise((resolve) => { + releaseQueuedStateLatch.resolve = resolve; + }); + + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: Effect.fn( + "providerMaintenanceRunner.test.blockQueuedState", + )(function* (input) { + const providers = yield* registry.setProviderMaintenanceActionState(input); + if (input.state?.status === "queued" && blockQueuedState) { + queuedStateWrittenLatch.resolve(); + yield* Effect.promise(() => releaseQueuedState); + } + if (input.state?.status === "succeeded") { + yield* Deferred.succeed(firstFinished, undefined); + } + return providers; + }), + }); + + const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); + yield* Effect.promise(() => queuedStateWritten); + blockQueuedState = false; + + yield* Fiber.interrupt(first); + releaseQueuedStateLatch.resolve(); + yield* Deferred.await(firstFinished); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ stdout: "updated" })), + ), + ), + ), + ); + it.effect( - "releases the running-provider marker when interrupted after queuing but before the lock run starts", + "keeps the update command running and records its result when the caller is interrupted", () => Effect.gen(function* () { - const { registry } = yield* makeRegistry(baseProvider, { - installedVersionAfterUpdate: "1.0.0", - }); - let blockQueuedState = true; - const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} }; - const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} }; - const queuedStateWritten = new Promise((resolve) => { - queuedStateWrittenLatch.resolve = resolve; - }); - const releaseQueuedState = new Promise((resolve) => { - releaseQueuedStateLatch.resolve = resolve; - }); + const kills: Array = []; + const spawned = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const finished = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Deferred.succeed(spawned, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Deferred.await(exit), + isRunning: Effect.succeed(true), + kill: () => Effect.sync(() => kills.push("kill")), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(encoder.encode("added 1 package")), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ), + ); - const updater = yield* makeTestRunner({ - ...registry, - setProviderMaintenanceActionState: Effect.fn( - "providerMaintenanceRunner.test.blockQueuedState", - )(function* (input) { - const providers = yield* registry.setProviderMaintenanceActionState(input); - if (input.state?.status === "queued" && blockQueuedState) { - queuedStateWrittenLatch.resolve(); - yield* Effect.promise(() => releaseQueuedState); - } - return providers; - }), - }); + yield* Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseOpenCodeProvider); + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: Effect.fn( + "providerMaintenanceRunner.test.recordFinishedState", + )(function* (input) { + const providers = yield* registry.setProviderMaintenanceActionState(input); + const status = input.state?.status; + if (input.state && status !== "queued" && status !== "running") { + yield* Deferred.succeed(finished, input.state); + } + return providers; + }), + }); - const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); - yield* Effect.promise(() => queuedStateWritten); - blockQueuedState = false; + const caller = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkChild); + yield* Deferred.await(spawned); + yield* Fiber.interrupt(caller); - yield* Fiber.interrupt(first); - releaseQueuedStateLatch.resolve(); + assert.deepStrictEqual( + kills, + [], + "interrupting the updateProvider caller killed the running npm install", + ); - const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit); - assert.strictEqual(Exit.isSuccess(second), true); - if (Exit.isSuccess(second)) { - assert.strictEqual(second.value.providers[0]?.updateState?.status, "succeeded"); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("1.0.0"), - layerMockSpawner(() => ({ stdout: "updated" })), + yield* Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)); + const finalState = yield* Deferred.await(finished); + assert.strictEqual(finalState.status, "succeeded"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("0.0.0"), + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), ), - ), - ), + ); + }), ); it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index 014aa67c26df0..a09bf1ee7dbba 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -13,6 +13,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -323,6 +324,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; + const serviceScope = yield* Effect.scope; const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate; const runMaintenanceCommand = ( update: ProviderMaintenanceCommandAction, @@ -685,7 +687,8 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { }, ); - return yield* commandCoordinator + // Installers cannot be safely killed mid-install, so the update outlives a disconnecting caller. + const updateFiber = yield* commandCoordinator .withCommandLock({ targetKey, lockKey: update.lockKey, @@ -693,10 +696,10 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { run: runProviderUpdate(), }) .pipe( - // A dropped request interrupts the update; a "running" state would spin until restart. + // Server shutdown interrupts the update; a "running" state would spin until restart. Effect.onInterrupt(() => Effect.gen(function* () { - // A finished state stays, even if the request drops while it is being written. + // A finished state stays, even if shutdown lands while it is being written. if (yield* Ref.get(settled)) return; yield* setUpdateState( makeUpdateState({ @@ -708,15 +711,18 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ); }).pipe(Effect.ignore), ), - Effect.mapError((error) => - isServerProviderUpdateError(error) - ? new ServerProviderUpdateError({ - provider, - reason: error.reason, - }) - : error, - ), + Effect.forkIn(serviceScope), ); + return yield* Fiber.join(updateFiber).pipe( + Effect.mapError((error) => + isServerProviderUpdateError(error) + ? new ServerProviderUpdateError({ + provider, + reason: error.reason, + }) + : error, + ), + ); }); return ProviderMaintenanceRunner.of({ diff --git a/apps/server/src/provider/testUtils/providerRegistryMock.ts b/apps/server/src/provider/testUtils/providerRegistryMock.ts index ccf4979937b35..0f8504e0b6200 100644 --- a/apps/server/src/provider/testUtils/providerRegistryMock.ts +++ b/apps/server/src/provider/testUtils/providerRegistryMock.ts @@ -12,6 +12,7 @@ const makeProviderRegistryMock = ( refresh: () => Effect.succeed(providers), refreshInstance: () => Effect.succeed(providers), reloadSecretsAndRefresh: () => Effect.succeed(providers), + rebuildMissingAndRefresh: Effect.succeed(providers), applySecretAndRefresh: () => Effect.succeed(providers), refreshAfterUpdate: () => Effect.succeed(providers), refreshWorkspaceSnapshot: () => Effect.succeed(providers), diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 8c8be7bf30534..22c6f05141e83 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -354,12 +354,38 @@ describe("question answer paths", () => { String.raw`{\rtf1\mac\ansicpg10000 Caf\'8e Cr\'8fme}`, "Café Crème", ], + ["default ANSI code page", String.raw`{\rtf1\ansi\ansicpg0 Caf\'e9}`, "Café"], + [ + "DOS Cyrillic code page", + String.raw`{\rtf1\ansi\ansicpg866 \'8f\'e0\'a8\'a2\'a5\'e2}`, + "Привет", + ], [ "font character set", String.raw`{\rtf1\ansi\ansicpg1252\deff1{\fonttbl\f0\fnil\fcharset178 GeezaPro;\f1\fnil\fcharset0 LucidaGrande;} \f0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : caf\'e9, \f0\plain\'c7a}`, "ملاحظة: café, Ça", ], + [ + "ANSI font under another code page", + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`, + "€5 café", + ], + [ + "font code page", + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`, + "Привет", + ], + [ + "ANSI font in a Macintosh document", + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`, + "pridržana", + ], + [ + "Macintosh font code page", + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0\cpg10000 Geneva;}\f0 Caf\'8e}`, + "Café", + ], [ "font character set outside the font table", String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset178 A;}{\f0\fcharset0 B;}{\f1\fcharset0 C;}{\f2\fcharset178 D;}{\f2 E;}}{\stylesheet{\s0\f1\fcharset178 N;}}\f0 \'e3\f1\'e3\f2\'e3}`, @@ -715,6 +741,44 @@ describe("question answer paths", () => { ], absent: ["[Extracted text truncated"], }, + { + ext: "epub", + parts: { + "META-INF/container.xml": '', + "book.opf": + '', + "q?1.xhtml": "

Encoded question mark chapter text.

", + }, + expected: ["Encoded question mark chapter text."], + absent: ["[Skipped document part", "[Extracted text truncated"], + }, + { + ext: "epub", + parts: { + "META-INF/container.xml": + '', + "My Book/book 1.opf": + '', + "My Book/ch1.xhtml": "

Percent-encoded rootfile chapter text.

", + }, + expected: ["Percent-encoded rootfile chapter text."], + absent: ["[Skipped document part", "[Extracted text truncated"], + }, + { + ext: "epub", + parts: { + "META-INF/container.xml": + '', + "OPS/book%201.opf": + '', + "ops/book 1.opf": + '', + "OPS/correct.xhtml": "

Correct primary chapter

", + "ops/other.xhtml": "

Wrong alternate chapter

", + }, + expected: ["Correct primary chapter"], + absent: ["Wrong alternate chapter", "[Skipped document part"], + }, ...[false, true].flatMap((bom) => [false, true].map((bigEndian) => { const encode = (source: string) => { @@ -854,6 +918,16 @@ describe("question answer paths", () => { expected: ["Intro 3\nFee $700\tdue"], absent: ["PAGEREF", "$500", "Moved", "\u2011"], }, + { + ext: "docx", + bounded: true, + parts: { + "word/document.xml": + 'Opening FormulaOmittedZero False Off DraftNoteAsideShown', + }, + expected: ["Opening Zero False Off Shown"], + absent: ["Omitted", "Draft", "Note", "Aside", "Formula"], + }, { ext: "odt", bounded: true, @@ -917,9 +991,9 @@ describe("question answer paths", () => { "xl/workbook.xml": '', "xl/_rels/workbook.xml.rels": - '', - "xl/sharedStrings.xml": "Lantern", - "xl/styles.xml": + '', + "catalog/items.xml": "Lantern", + "formatting/cells.xml": '', "xl/worksheets/second.xml": '037', @@ -936,6 +1010,27 @@ describe("question answer paths", () => { "45293 [Excel numFmtId=164; format=yyyy-mm-dd; date system 1900]", ], }, + { + ext: "xlsx", + bounded: true, + parts: { + "_rels/.rels": + '', + "docs/book.xml": '', + "docs/_rels/book.xml.rels": + '', + "docs/strings.xml": "Harbor", + "docs/styles.xml": + '', + "docs/sheets/data.xml": + '045293', + }, + expected: [ + "## Sheet: Data", + "Harbor\t45293 [Excel numFmtId=164; format=yyyy-mm-dd; date system 1900]", + ], + absent: ["[Skipped document part"], + }, { ext: "xlsx", bounded: true, @@ -1005,7 +1100,9 @@ describe("question answer paths", () => { "ppt/presentation.xml": ` - + + + @@ -1060,6 +1157,28 @@ describe("question answer paths", () => { expected: ["Slide text"], absent: ["Notes:", "57"], }, + ...[ + { target: "deck/main.xml", prefix: "deck/" }, + { target: "/main.xml", prefix: "" }, + ].map(({ target, prefix }) => ({ + ext: "pptx", + bounded: true, + parts: { + "_rels/.rels": ``, + [`${prefix}main.xml`]: + '', + [`${prefix}_rels/main.xml.rels`]: + '', + [`${prefix}slides/one.xml`]: + "Harbor launch", + [`${prefix}slides/_rels/one.xml.rels`]: + '', + [`${prefix}notes/n1.xml`]: + "Check tide table", + }, + expected: ["## Slide 1", "Harbor launch\nNotes:\nCheck tide table"], + absent: ["[Skipped document part"], + })), ...[false, true].map((missing) => ({ ext: "pptx", bounded: true, diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts index fb13edeafbda9..a6207db603329 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts @@ -421,48 +421,53 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic }), ); - it.effect("measures only the PR change using the renamed verified remote's fetch URL", () => - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const fork = `${repositories.root}/fork`; - yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); - yield* git(fork, ["branch", "stack-base", "main~1"]); - // The cached identity still names origin, which now belongs to the stale fork. - yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]); - yield* git(repositories.workspace, ["remote", "add", "origin", fork]); - yield* git(repositories.workspace, [ - "config", - `url.${repositories.remote}.insteadOf`, - "review-upstream:", - ]); - yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]); - const changed = yield* Deferred.make(); - const driver = yield* GitVcsDriver.GitVcsDriver; - const stored = yield* Deferred.make(); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - generate: (input) => - git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe( - Effect.provideService(GitVcsDriver.GitVcsDriver, driver), - Effect.orDie, - Effect.flatMap((names) => Deferred.succeed(changed, names)), - Effect.as({ stops: [] }), - ), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - yield* service.generate(reference); - assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); - yield* Deferred.await(stored); - const result = yield* service.get(reference); - assert.strictEqual(result.guide?.headSha, repositories.headSha); - assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); - }), + it.effect.each(["rewritten", "configured"] as const)( + "measures only the PR change through the renamed remote matched by its %s URL", + (locatorUrl) => + Effect.gen(function* () { + const repositories = yield* makeRepositories; + const fork = `${repositories.root}/fork`; + yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]); + yield* git(fork, ["branch", "stack-base", "main~1"]); + // The cached identity still names origin, which now belongs to the stale fork. + yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]); + yield* git(repositories.workspace, ["remote", "add", "origin", fork]); + yield* git(repositories.workspace, [ + "config", + `url.${repositories.remote}.insteadOf`, + "review-upstream:", + ]); + yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]); + const changed = yield* Deferred.make(); + const driver = yield* GitVcsDriver.GitVcsDriver; + const stored = yield* Deferred.make(); + const context = yield* Layer.build( + makeLayer({ + ...repositories, + ...(locatorUrl === "configured" + ? { locator: { ...ACME_APP.locator, remoteUrl: "review-upstream:" } } + : {}), + stored, + generate: (input) => + git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + Effect.orDie, + Effect.flatMap((names) => Deferred.succeed(changed, names)), + Effect.as({ stops: [] }), + ), + }), + ); + const service = Context.get( + context, + PullRequestReviewGuideService.PullRequestReviewGuideService, + ); + yield* service.generate(reference); + assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); + yield* Deferred.await(stored); + const result = yield* service.get(reference); + assert.strictEqual(result.guide?.headSha, repositories.headSha); + assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); + }), ); it.effect("keeps excerpts despite the checkout's diff driver and a failing hook", () => diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts index 0963b0aeaa52f..580816890a390 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts @@ -22,6 +22,7 @@ import { type ThreadPullRequestKey, } from "@t3tools/contracts"; import type { ReviewGuideStackLayer } from "@t3tools/provider-core/server/textGeneration"; +import { withoutRemoteUrlCredentials } from "@t3tools/shared/cloneUrl"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; @@ -146,7 +147,7 @@ const make = Effect.gen(function* () { stack: PullRequestStack | null, runId: string, ) { - // Identity names can be stale; match effective fetch URLs, including insteadOf rewrites. + // Identity names can be stale; the identity keeps a remote's URL before or after insteadOf. const names = yield* git .execute({ operation: "PullRequestReviewGuideService.listRemotes", @@ -157,16 +158,28 @@ const make = Effect.gen(function* () { const remote = yield* Effect.findFirst( [locator.remoteName, ...names.filter((name) => name !== locator.remoteName)], (name) => - git - .execute({ - operation: "PullRequestReviewGuideService.remoteUrl", - cwd: workspaceRoot, - args: ["remote", "get-url", "--", name], - }) - .pipe( - Effect.map((result) => result.stdout.trim() === locator.remoteUrl), - Effect.orElseSucceed(() => false), - ), + Effect.forEach( + [ + ["remote", "get-url", "--", name], + ["config", "--get-all", `remote.${name}.url`], + ], + (args) => + git + .execute({ + operation: "PullRequestReviewGuideService.remoteUrl", + cwd: workspaceRoot, + args, + }) + .pipe( + Effect.map( + (result) => + withoutRemoteUrlCredentials(result.stdout.split("\n")[0]?.trim() ?? "") === + locator.remoteUrl, + ), + Effect.orElseSucceed(() => false), + ), + { concurrency: "unbounded" }, + ).pipe(Effect.map((matches) => matches.includes(true))), ).pipe(Effect.map(Option.getOrUndefined)); if (remote === undefined) { return yield* new PullRequestOperationError({ diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index a1e04a9114b50..8852e5f1fe058 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -40,6 +40,7 @@ import { import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts"; import * as PullRequestService from "./PullRequestService.ts"; import * as PullRequestReadCache from "./PullRequestReadCache.ts"; +import { resolveTarget } from "./pullRequestTarget.ts"; function project(input: { readonly id: string; @@ -425,6 +426,12 @@ it.effect("lists GitHub Enterprise PRs for a stored unknown repository after hos // Agents get the forge tools only where the host is one T3 reads. assert.isTrue(yield* service.servesProject("p1" as ProjectId)); assert.isFalse(yield* service.servesProject("p2" as ProjectId)); + // ...and those tools build PR URLs through the same refined forge. + const target = yield* resolveTarget( + { repository: "team/project", number: 42 }, + yield* service.addressedProject("p1" as ProjectId), + ); + assert.strictEqual(target.url, "https://code.example.test/team/project/pull/42"); }), ); @@ -1548,10 +1555,11 @@ it.effect.each([false, true])( }), ); -it.effect("refuses a merge whose head moved past expectedHeadSha and pins the host merge", () => +it.effect("refuses a merge or review whose head moved past expectedHeadSha and pins the host", () => Effect.gen(function* () { const head = "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"; const pinned: Array = []; + const reviewed: Array = []; const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ @@ -1559,10 +1567,18 @@ it.effect("refuses a merge whose head moved past expectedHeadSha and pins the ho getChangeRequest: () => Effect.succeed({ ...hostedChangeRequest("Body"), headSha: head }), getChangeRequestSummary: () => Effect.succeed(changeRequest(1, "2026-09-03T00:00:00Z")), runAction: (input) => Effect.sync(() => void pinned.push(input.expectedHeadSha)), + submitReview: (input) => Effect.sync(() => void reviewed.push(input.expectedHeadSha)), }), ], }); const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const approval = { ...reference, verdict: "approve" as const, body: "", comments: [] }; + const unseen = yield* Effect.flip( + service.submitReview({ ...approval, expectedHeadSha: "0a1b2c4" }), + ); + assert.include(unseen.message, head); + yield* service.submitReview({ ...approval, expectedHeadSha: "0a1b2c3d4" }); + assert.deepStrictEqual(reviewed, [head]); const refused = yield* Effect.flip( service.runAction({ ...reference, action: "merge", expectedHeadSha: "0a1b2c4" }), ); @@ -3083,6 +3099,47 @@ it.effect("close and reopen notify subscribed readers after invalidating their c }), ); +it.effect("a refused merge notifies readers so they re-read the conflicting state", () => + Effect.gen(function* () { + let mergeable = true; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + Effect.succeed({ + ...changeRequest(1, "2026-09-16T00:00:00.000Z"), + mergeability: mergeable ? "mergeable" : "conflicting", + }), + runAction: () => + Effect.suspend(() => { + mergeable = false; + return Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "runAction", + reason: "failed", + detail: "Pull Request has merge conflicts", + }), + ); + }), + }), + ], + }); + + assert.strictEqual((yield* service.summary(reference)).mergeability, "mergeable"); + const refreshed = yield* service.subscribeRefreshes.pipe( + Stream.take(1), + Stream.mapEffect(() => service.summary(reference)), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* Effect.flip(service.runAction({ ...reference, action: "merge" })); + assert.strictEqual(Option.getOrThrow(yield* Fiber.join(refreshed)).mergeability, "conflicting"); + }), +); + it.effect("reads a host's repositories in one search, and files the rows back under each", () => Effect.gen(function* () { const asked: Array> = []; @@ -5116,6 +5173,66 @@ it.effect("authorizes cold source reads with paginated paths without fetching pa }), ); +const activityListing = (...oids: ReadonlyArray) => ({ + getChangeRequestActivity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: oids.map((oid) => ({ + oid, + messageHeadline: "Change", + committedDate: "2026-01-01T00:00:00.000Z", + })), + }), +}); + +it.effect("reads a commit's diff only for a commit the change request lists", () => + Effect.gen(function* () { + const listed = "a".repeat(40); + const read: Array = []; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + ...activityListing(listed, "b".repeat(40)), + getDiff: (input) => + Effect.sync(() => { + read.push(input.commit); + return { + patch: "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n+x\n", + truncated: false, + nextCursor: null, + }; + }), + getDiffFileContents: (input) => + Effect.sync(() => { + read.push(input.commit); + return { oldContents: "old", newContents: "new" }; + }), + }), + ], + }); + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const file = { changeType: "change" as const, oldPath: "a.ts", newPath: "a.ts" }; + + for (const commit of ["c".repeat(40), "abcdef", "A".repeat(41), ""]) { + const diff = yield* service.diff({ ...ref, commit }).pipe(Effect.flip); + const contents = yield* service + .diffFileContents({ ...ref, ...file, commit }) + .pipe(Effect.flip); + assert.strictEqual(diff.reason, "not-found"); + assert.strictEqual(contents.reason, "not-found"); + } + assert.deepStrictEqual(read, []); + + yield* service.diff({ ...ref, commit: "AAAAAAA" }); + yield* service.diffFileContents({ ...ref, ...file, commit: "aaaaaaa" }); + assert.deepStrictEqual(read, [listed, listed]); + }), +); + it.effect.each(["commit", "credential", "expiry", "refresh"] as const)( "keeps cold metadata membership in its original scope through an in-flight %s", (boundary) => @@ -5135,6 +5252,7 @@ it.effect.each(["commit", "credential", "expiry", "refresh"] as const)( Effect.suspend(() => use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }), ), + ...activityListing("a".repeat(40)), getDiff: () => Effect.die("Membership must not fetch patch hunks"), getDiffFilePaths: (input) => Effect.gen(function* () { @@ -5299,6 +5417,7 @@ it.effect.each(["commit", "credential"] as const)( Effect.suspend(() => use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }), ), + ...activityListing("a".repeat(40)), getDiff: () => Effect.sync(() => ({ patch: @@ -5356,6 +5475,7 @@ it.effect.each(["expiry", "commit expiry", "cache hit", "commit cache hit", "ref ], providers: [ fakePullRequestProvider(SourceControlProviderKind.make("github"), { + ...activityListing("a".repeat(40)), getDiff: () => Effect.gen(function* () { if (++diffReads !== 1) return { patch: "", truncated: false, nextCursor: null }; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 59ece029219df..f3ac5cbe0d3d0 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -258,6 +258,10 @@ export class PullRequestService extends Context.Service< readonly changes: (input: PullRequestRef) => Stream.Stream; /** Whether the project's checkout is on a forge T3 reads change requests from. */ readonly servesProject: (projectId: ProjectId) => Effect.Effect; + /** The project as `servesProject` sees it: identity resolved, its forge refined. */ + readonly addressedProject: ( + projectId: ProjectId, + ) => Effect.Effect; readonly threadComments: ( input: PullRequestThreadCommentsInput, ) => Effect.Effect; @@ -358,6 +362,7 @@ export interface SupportedProject { readonly cursorKey: string; readonly project: OrchestrationProjectShell; readonly api: PullRequestProviderApi; + readonly kind: SourceControlProviderKind; readonly repository: string; readonly host: string; /** Unlike Azure repository names, remotes are unique across an organization. */ @@ -366,6 +371,8 @@ export interface SupportedProject { } interface WorkspaceProjects { + /** Every project read, with its repository identity resolved. */ + readonly projects: ReadonlyArray; readonly supported: ReadonlyArray; readonly unimplemented: ReadonlyMap< string, @@ -1026,6 +1033,7 @@ export const make = Effect.gen(function* () { cursorKey: key, project, api: withRateLimitBackoff(api, host, rateLimits), + kind, repository, host, remote: @@ -1037,7 +1045,7 @@ export const make = Effect.gen(function* () { : sourceControlDefinitions.canonicalRepositoryKey(repositoryKey.toLowerCase()), }); } - return { supported, unimplemented, viewerRoots, refinedProjectIdsByHost }; + return { projects, supported, unimplemented, viewerRoots, refinedProjectIdsByHost }; }), ); @@ -1087,7 +1095,7 @@ export const make = Effect.gen(function* () { return Effect.gen(function* () { const publicHost = sourceControlDefinitions.findByPublicHost(host); const api = publicHost === undefined ? null : registry.get(publicHost.kind); - if (api?.readsPublicHostWithoutCheckout) { + if (publicHost !== undefined && api?.readsPublicHostWithoutCheckout) { const selected = yield* projects.getShell(ref.projectId).pipe( Effect.mapError( (cause) => @@ -1103,6 +1111,7 @@ export const make = Effect.gen(function* () { cursorKey: listCursorKey(host, repository), project: selected.value, api: withRateLimitBackoff(api, host, rateLimits), + kind: publicHost.kind, repository, host, remote: sourceControlDefinitions.repositoryKeyFromRemote( @@ -1166,6 +1175,18 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed(() => true), ); + const addressedProject: PullRequestService["Service"]["addressedProject"] = (projectId) => + listWorkspaceProjects({ projectId }).pipe( + Effect.map(({ projects, supported }) => { + const own = supported[0]; + if (own === undefined) return projects.find((project) => project.id === projectId); + const identity = own.project.repositoryIdentity; + return identity == null || identity.provider === own.kind + ? own.project + : { ...own.project, repositoryIdentity: { ...identity, provider: own.kind } }; + }), + ); + const changes: PullRequestService["Service"]["changes"] = (input) => Stream.unwrap( requireProject(input).pipe( @@ -2200,11 +2221,16 @@ export const make = Effect.gen(function* () { }), ); } + const stackAutoMerge = + input.action === "enable-auto-merge" || input.action === "disable-auto-merge"; if ( input.stackNumber !== undefined && (project.api.capabilities.stackActions !== true || - !["merge", "update-branch"].includes(input.action) || - input.expectedStackHeads === undefined || + !( + ["merge", "update-branch"].includes(input.action) || + (stackAutoMerge && project.api.capabilities.stackAutoMerge === true) + ) || + (input.expectedStackHeads === undefined && input.action !== "disable-auto-merge") || (input.action === "update-branch" && input.updateMethod !== "rebase")) ) { return Effect.fail( @@ -2294,32 +2320,7 @@ export const make = Effect.gen(function* () { ), ) : Effect.succeed(false); - // Hosts that cannot pin a merge to a commit still refuse a head that already moved. - const expected = input.expectedHeadSha; - const headPinned: Effect.Effect = - expected === undefined - ? Effect.undefined - : project.api - .getChangeRequest({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - number: input.number, - }) - .pipe( - Effect.mapError(toPullRequestError("runAction")), - Effect.flatMap((current) => - typeof current.headSha === "string" && isHeadSha(current.headSha, expected) - ? Effect.succeed(current.headSha) - : Effect.fail( - new PullRequestOperationError({ - operation: "runAction", - detail: `The head is now ${current.headSha ?? "unknown"}, not ${expected}. Review the new commits first.`, - }), - ), - ), - ); - return headPinned.pipe( + return pinnedHead(project, input, "runAction").pipe( Effect.flatMap((expectedHeadSha) => Effect.map(mergeSettings, (removeAgentCreditsOnMerge) => ({ expectedHeadSha, @@ -2386,6 +2387,37 @@ export const make = Effect.gen(function* () { }), ); + // Hosts that cannot pin a write to a commit still refuse a head that already moved. + const pinnedHead = ( + project: SupportedProject, + input: { readonly number: number; readonly expectedHeadSha?: string | undefined }, + operation: string, + ): Effect.Effect => { + const expected = input.expectedHeadSha; + return expected === undefined + ? Effect.undefined + : project.api + .getChangeRequest({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + }) + .pipe( + Effect.mapError(toPullRequestError(operation)), + Effect.flatMap((current) => + typeof current.headSha === "string" && isHeadSha(current.headSha, expected) + ? Effect.succeed(current.headSha) + : Effect.fail( + new PullRequestOperationError({ + operation, + detail: `The head is now ${current.headSha ?? "unknown"}, not ${expected}. Review the new commits first.`, + }), + ), + ), + ); + }; + const comment: PullRequestService["Service"]["comment"] = (input) => (input.body.trim().length === 0 ? Effect.fail( @@ -2545,17 +2577,22 @@ export const make = Effect.gen(function* () { "You need write access on this repository to comment on a line of a change request.", ); } - return project.api - .submitReview({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - number: input.number, - verdict: input.verdict, - body: input.body, - comments: input.comments, - }) - .pipe(Effect.mapError(toPullRequestError("submitReview"))); + return pinnedHead(project, input, "submitReview").pipe( + Effect.flatMap((expectedHeadSha) => + project.api + .submitReview({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + verdict: input.verdict, + body: input.body, + comments: input.comments, + ...(expectedHeadSha === undefined ? {} : { expectedHeadSha }), + }) + .pipe(Effect.mapError(toPullRequestError("submitReview"))), + ), + ); }), ); }), @@ -3686,10 +3723,40 @@ export const make = Effect.gen(function* () { ); return { key, read }; }; - const diff: PullRequestService["Service"]["diff"] = (input) => { - const { key, read } = readDiff(input); - return staleDiff.serve(key, read.pipe(Effect.map((read) => read.value))); + // A host reads a commit's diff from the repository, not from the change request, so a named + // commit is forwarded only as the one oid the change request's own commit list gives for it. + const withListedCommit = ( + operation: string, + input: I, + read: (input: I) => Effect.Effect, + ): Effect.Effect => { + const wanted = input.commit?.toLowerCase(); + if (wanted === undefined) return Effect.succeed(input); + return read(input).pipe( + Effect.flatMap(({ commits }) => { + const listed = /^[0-9a-f]{7,64}$/.test(wanted) + ? commits.filter((commit) => commit.oid.toLowerCase().startsWith(wanted)) + : []; + const [commit] = listed; + return commit !== undefined && listed.length === 1 + ? Effect.succeed({ ...input, commit: commit.oid }) + : Effect.fail( + new PullRequestOperationError({ + operation, + detail: "This commit is not part of the change request.", + reason: "not-found", + }), + ); + }), + ); }; + const diff: PullRequestService["Service"]["diff"] = (input) => + withListedCommit("diff", input, activity).pipe( + Effect.flatMap((input) => { + const { key, read } = readDiff(input); + return staleDiff.serve(key, read.pipe(Effect.map((read) => read.value))); + }), + ); const filesViewedCache = yield* Cache.makeWith( (key: string) => { @@ -3968,8 +4035,16 @@ export const make = Effect.gen(function* () { )(function* (input) { const ref = yield* canonicalRef(input); yield* readCache.invalidate(refScope(ref)); + // A refusal (e.g. a merge conflict) means readers hold stale state, so refresh them too. const { repository, summary } = yield* runAction(input).pipe( Effect.ensuring(readCache.invalidate(refScope(ref))), + Effect.tapError(() => + Effect.suspend(() => { + bumpRefEpoch(ref); + listingsEpoch = ++epochCounter; + return SubscriptionRef.set(pullRequestRefreshes, listingsEpoch); + }), + ), ); bumpRefEpoch({ ...ref, repository }); listingsEpoch = ++epochCounter; @@ -4101,18 +4176,23 @@ export const make = Effect.gen(function* () { return walk(undefined); }; // PR read access does not grant arbitrary repository reads with the project credential; restrict to changed files. + const listedActivity = credentialCached(activity); const diffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) => - changesFile(input).pipe( - Effect.flatMap((changed) => - changed - ? readDiffFileContents(input) - : Effect.fail( - new PullRequestOperationError({ - operation: "diffFileContents", - detail: "This file is not part of the change request.", - reason: "not-found", - }), - ), + withListedCommit("diffFileContents", input, listedActivity).pipe( + Effect.flatMap((input) => + changesFile(input).pipe( + Effect.flatMap((changed) => + changed + ? readDiffFileContents(input) + : Effect.fail( + new PullRequestOperationError({ + operation: "diffFileContents", + detail: "This file is not part of the change request.", + reason: "not-found", + }), + ), + ), + ), ), ); @@ -4156,6 +4236,7 @@ export const make = Effect.gen(function* () { activity: credentialCached(activity), changes, servesProject, + addressedProject, preview: credentialCached(preview), threadComments, diff: credentialCached(diff), diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts index 8982e795e2615..2a02bd7967952 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.test.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -14,7 +14,6 @@ import { describe, expect, it } from "@effect/vitest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; @@ -22,7 +21,6 @@ import { type PullRequestTestThread, v2PullRequestThread, } from "../orchestration-v2/testkit/pullRequestFixtures.ts"; -import * as ProjectService from "../project/ProjectService.ts"; import * as PullRequestService from "./PullRequestService.ts"; import * as PullRequestWatchService from "./PullRequestWatchService.ts"; import type { PullRequestTarget } from "./pullRequestTarget.ts"; @@ -124,9 +122,6 @@ const makeHarness = Effect.fn("makePullRequestWatchHarness")(function* ( const thread = options.thread === undefined ? makeThread([]) : options.thread; const project = options.project === undefined ? makeProject() : options.project; const dependencies = Layer.mergeAll( - Layer.mock(ProjectService.ProjectService)({ - getShell: () => Effect.succeed(Option.fromNullishOr(project)), - }), Layer.mock(Orchestrator.OrchestratorV2)({ getThreadShell: (id) => Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null), @@ -136,6 +131,7 @@ const makeHarness = Effect.fn("makePullRequestWatchHarness")(function* ( ), }), Layer.mock(PullRequestService.PullRequestService)({ + addressedProject: () => Effect.succeed(project ?? undefined), summary: (input) => options.readFailure !== undefined ? Effect.fail(options.readFailure) diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 32f51f540bf9f..878892d343d5c 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -11,11 +11,9 @@ import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; -import * as ProjectService from "../project/ProjectService.ts"; import * as PullRequestService from "./PullRequestService.ts"; import { resolveTarget, @@ -83,7 +81,6 @@ export class PullRequestWatchService extends Context.Service< const make = Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; - const projects = yield* ProjectService.ProjectService; const pullRequests = yield* PullRequestService.PullRequestService; const random = yield* SecureRandom.SecureRandom; @@ -108,10 +105,9 @@ const make = Effect.gen(function* () { }) { const { watching } = input; const thread = yield* requireThread(input.threadId); - const project = yield* projects.getShell(thread.projectId).pipe( - Effect.map(Option.getOrUndefined), - Effect.mapError((cause) => new PullRequestWatchFailedError({ cause })), - ); + const project = yield* pullRequests + .addressedProject(thread.projectId) + .pipe(Effect.mapError((cause) => new PullRequestWatchFailedError({ cause }))); const target = yield* resolveTarget(input.target, project); const watchedLink = (shell: OrchestrationV2ThreadShell) => threadPullRequestsOf(shell).find( diff --git a/apps/server/src/pullRequest/pullRequestTarget.ts b/apps/server/src/pullRequest/pullRequestTarget.ts index 4520b0523a369..45312f8304634 100644 --- a/apps/server/src/pullRequest/pullRequestTarget.ts +++ b/apps/server/src/pullRequest/pullRequestTarget.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts"; +import { pullRequestSyncKey } from "./pullRequestSyncKey.ts"; export interface PullRequestTarget { readonly url?: string | undefined; @@ -49,11 +50,21 @@ export class PullRequestUrlUnavailableError extends Schema.TaggedError()( + "PullRequestRepositoryInvalidError", + {}, +) { + override get message(): string { + return "Pass repository as owner/repo, without the host."; + } +} + export type PullRequestTargetError = | PullRequestUrlInvalidError | PullRequestTargetIncompleteError | PullRequestHostRequiredError - | PullRequestUrlUnavailableError; + | PullRequestUrlUnavailableError + | PullRequestRepositoryInvalidError; export interface ResolvedTarget { readonly host: string; @@ -92,29 +103,45 @@ export const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(func if (input.repository === undefined || input.number === undefined) { return yield* new PullRequestTargetIncompleteError({}); } + // Azure DevOps tools name the project's repository by its bare name, which no URL can be built + // from, so it is read as the project's full repository path. + const own = + project?.repositoryIdentity == null || input.repository.includes("/") + ? null + : pullRequestSyncKey( + { + projectId: project.id, + host: input.host, + repository: input.repository, + number: input.number, + }, + project.repositoryIdentity, + ); const projectHost = projectHostAndProvider(project); - const host = (input.host ?? projectHost.host)?.toLowerCase(); + const host = (own?.host ?? input.host ?? projectHost.host)?.toLowerCase(); if (host === undefined) { return yield* new PullRequestHostRequiredError({}); } - const repository = input.repository.toLowerCase(); + const repository = (own?.repository ?? input.repository).toLowerCase(); // Without a URL, a public forge host says what shape its change request URLs take; // any other host is taken to run the project's own forge. const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind; const kind = sourceControlDefinitions.findByPublicHost(host)?.kind ?? (recognizedKind === "gitcafe" ? recognizedKind : projectHost.kind); + const definition = kind === null ? null : sourceControlDefinitions.get(kind); const url = - kind === null - ? null - : sourceControlDefinitions.get(kind).changeRequestUrl({ - host, - repository, - number: input.number, - remoteUrl: project?.repositoryIdentity?.locator.remoteUrl, - }); + definition?.changeRequestUrl({ + host, + repository, + number: input.number, + remoteUrl: project?.repositoryIdentity?.locator.remoteUrl, + }) ?? null; if (url === null) { - return yield* new PullRequestUrlUnavailableError({}); + // A known forge returns no URL when the repository is not in its shape. + return yield* definition === null || definition.kind === "unknown" + ? new PullRequestUrlUnavailableError({}) + : new PullRequestRepositoryInvalidError({}); } return { ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }), diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts index ca77c9e26220c..845e484f36ba6 100644 --- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts +++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts @@ -175,6 +175,8 @@ export class DesktopTelemetryReceiver extends Context.Service< never, Scope.Scope >; + /** Emits when a desktop shell environment changes this process's PATH; replays the last one. */ + readonly pathChanges: Stream.Stream; readonly health: Effect.Effect; readonly subscribeHealth: Effect.Effect< { @@ -397,12 +399,31 @@ export function requireDesktopTelemetryWriteProgress( : Effect.fail(new DesktopTelemetryControlStalled({ fd, remainingBytes })); } +export const makeDesktopShellEnvironmentUpdates = Effect.fn( + "DesktopTelemetryReceiver.makeDesktopShellEnvironmentUpdates", +)(function* (environment: NodeJS.ProcessEnv, platform: NodeJS.Platform) { + const applyShellEnvironment = makeApplyDesktopShellEnvironmentSnapshot(environment, platform); + // Replayed, because the provider watcher may subscribe after the snapshot arrived. + const pathChanges = yield* Effect.acquireRelease( + PubSub.sliding({ capacity: 1, replay: 1 }), + PubSub.shutdown, + ); + const readPath = () => environment.PATH ?? environment.Path; + // Untraced: applyShellEnvironment already carries this operation's span. + const apply = Effect.fnUntraced(function* (message: DesktopShellEnvironmentSnapshot) { + const before = readPath(); + yield* applyShellEnvironment(message); + if (readPath() !== before) yield* PubSub.publish(pathChanges, undefined); + }); + return { apply, pathChanges: Stream.fromPubSub(pathChanges) }; +}); + /** @public */ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () { const config = yield* ServerConfig.ServerConfig; const environment = yield* HostProcess.Environment; const platform = yield* HostProcess.Platform; - const applyShellSnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, platform); + const shellEnvironment = yield* makeDesktopShellEnvironmentUpdates(environment, platform); const serverSettings = yield* ServerSettings.ServerSettingsService; const latest = yield* Ref.make(Option.none()); const receiverStartedAt = yield* DateTime.now; @@ -599,7 +620,7 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make") } if (message.type === "shellEnvironment") { - return recordContact.pipe(Effect.andThen(applyShellSnapshot(message))); + return recordContact.pipe(Effect.andThen(shellEnvironment.apply(message))); } if (message.type === "desktopUpdateStatus") { @@ -706,6 +727,7 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make") return DesktopTelemetryReceiver.of({ latest: Ref.get(latest), changes: Stream.fromPubSub(changes), + pathChanges: shellEnvironment.pathChanges, subscribe: snapshotMutex.withPermits(1)( Effect.gen(function* () { const initial = yield* Ref.get(latest); @@ -772,6 +794,7 @@ export const layerTest = ( DesktopTelemetryReceiver.of({ latest, changes, + pathChanges: overrides.pathChanges ?? Stream.empty, subscribe: overrides.subscribe ?? latest.pipe( diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 3db6f783f649a..488852884f69e 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -81,6 +81,10 @@ import { describeFailedWebhookFilter, findFailedWebhookFilter } from "./webhookF import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerification.ts"; export const WEBHOOK_ROUTE_PREFIX = "/api/hooks"; + +/** The task a create carrying this idempotency key writes, and rewrites when the key is replayed. */ +export const scheduledTaskIdForCommand = (commandId: CommandId) => + ScheduledTaskId.make(`scheduled-task:${commandId}`); const isScheduledTaskError = Schema.is(ScheduledTaskError); const isOrchestratorDispatchError = Schema.is(OrchestratorDispatchError); const PROMPT_TOO_LONG = "The filled-in prompt is too long."; @@ -1480,9 +1484,9 @@ export const layer = Layer.effect( : null; const id = input.id ?? - ScheduledTaskId.make( - input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`, - ); + (input.commandId + ? scheduledTaskIdForCommand(input.commandId) + : ScheduledTaskId.make(`scheduled-task:${uuid}`)); // Look up by the *resolved* id so idempotent creates (commandId replays) // keep their run history, and so real load failures propagate instead // of silently resetting an existing row. diff --git a/apps/server/src/scheduledTasks/webhookRoute.test.ts b/apps/server/src/scheduledTasks/webhookRoute.test.ts index 7fb2552a56074..e879ab35352c8 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.test.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.test.ts @@ -224,6 +224,30 @@ describe("webhook route", () => { }), ); + it("keeps a browser's session cookie out of the request a task reads", async () => { + const received: Array = []; + const { handler, dispose } = handlerFor((request) => { + received.push(request); + return Effect.succeed({ + _tag: "accepted", + deliveryId: ScheduledTaskWebhookDeliveryId.make("delivery:1"), + outcome: "accepted", + }); + }); + try { + const response = await handler( + new Request("http://env.local/api/hooks/id/tok", { + headers: { Cookie: "t3_session=session-secret", "x-github-event": "push" }, + }), + ); + expect(response.status).toBe(202); + expect(received[0]?.headers).not.toHaveProperty("cookie"); + expect(received[0]?.headers["x-github-event"]).toBe("push"); + } finally { + await dispose(); + } + }); + it("maps service outcomes to status codes and names each outcome for the relay", async () => { const deliveryId = ScheduledTaskWebhookDeliveryId.make("delivery:1"); const cases: ReadonlyArray<[WebhookTriggerResult, number, string]> = [ diff --git a/apps/server/src/scheduledTasks/webhookRoute.ts b/apps/server/src/scheduledTasks/webhookRoute.ts index e1650219eb598..9ace3227db21f 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.ts @@ -85,7 +85,10 @@ export const layer = HttpApiBuilder.group( const headers: Record = {}; for (const [name, value] of Object.entries(request.headers)) { - if (typeof value === "string") headers[name.toLowerCase()] = value; + // Webhook senders do not use cookies, so the request a task reads carries none. + if (typeof value === "string" && name.toLowerCase() !== "cookie") { + headers[name.toLowerCase()] = value; + } } const queryIndex = request.url.indexOf("?"); // The relay's delivery id and receive time count only with its signed diff --git a/apps/server/src/scheduledTasks/webhookUrlToken.ts b/apps/server/src/scheduledTasks/webhookUrlToken.ts new file mode 100644 index 0000000000000..1ec104a61bcfd --- /dev/null +++ b/apps/server/src/scheduledTasks/webhookUrlToken.ts @@ -0,0 +1,10 @@ +export const WITHHELD = "[withheld]"; +const WEBHOOK_URL_TOKEN = + /(\/(?:v1\/hooks\/[0-9a-f]{16}|api\/hooks)\/[^/\s"'\\]+\/)[A-Za-z0-9_-]+/g; + +/** + * Shows a webhook URL with its last segment withheld, as Settings is where the full URL lives. + * Matches the URL as the server prints it, not an escaped or split one. + */ +export const withoutWebhookUrlToken = (text: string) => + text.replace(WEBHOOK_URL_TOKEN, `$1${WITHHELD}`); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 285bea8b98013..20b6a2c10dcf7 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -33,7 +33,6 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; -import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; import * as KeepAwake from "./background/KeepAwake.ts"; import * as ServerConfig from "./config.ts"; import { withRootRequestSpans, withUntracedRequests } from "./http.ts"; @@ -48,6 +47,7 @@ import { fixPath } from "./os-jank.ts"; import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; +import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import * as SpawnWorker from "./process/SpawnWorker.ts"; import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts"; import * as PullRequestHttp from "./pullRequest/http.ts"; @@ -78,6 +78,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime"; import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger"; import * as ProviderHostLive from "./provider/ProviderHostLive.ts"; +import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; import * as DocumentText from "./provider/DocumentText.ts"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; @@ -90,6 +91,7 @@ import * as TextGeneration from "./textGeneration/TextGeneration.ts"; import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as SecretResolver from "./secrets/SecretResolver.ts"; import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceRegistryHydration.ts"; +import * as ProviderHostPathWatcher from "./provider/ProviderHostPathWatcher.ts"; import * as ProjectSettingsOverrideSweep from "./provider/ProjectSettingsOverrideSweep.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import * as McpHttpServer from "./mcp/McpHttpServer.ts"; @@ -411,11 +413,11 @@ const layerHttpServer = Layer.unwrap( ).pipe( Layer.provide(ManagedPolicy.layer), // NodeHttpServer.layer also outputs NodeServices, whose spawner would shadow the wrapped one. - (layer) => NonBlockingSpawner.layer.pipe(Layer.provideMerge(layer)), + (layer) => ProcessLauncher.layerServer.pipe(Layer.provideMerge(layer)), ); const layerPlatformServices = DocumentText.layer.pipe( - Layer.provideMerge(NonBlockingSpawner.layer), + Layer.provideMerge(ProcessLauncher.layerServer), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner)), ); @@ -728,6 +730,7 @@ const layerServerRestart = Layer.effect( const layerRuntimeCoreDependenciesBase = Layer.mergeAll( AgentAwarenessRelay.layer, + ProviderHostPathWatcher.layer.pipe(Layer.provide(layerDesktopTelemetryReceiver)), HeldHooksWaker.layer, layerThreadSettlementWorker, layerIdleCompactionWorker, @@ -901,6 +904,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(ServerHttp.layerServerEnvironmentHttpApi), Layer.provide(WebhookRoute.layer.pipe(Layer.provide(RelayDeliveryProof.layer))), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, @@ -960,6 +964,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(layerServerSettings), Layer.provide(PreviewAutomationBroker.layer), Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(layerDesktopAppUpdate))), + Layer.provide(ProviderMaintenanceRunner.layer), Layer.provide(layerCommandReadiness), Layer.provide(ServerHttp.layerBrowserApiCors), Layer.provide(ServerHttp.layerHttpCompression), @@ -1437,5 +1442,7 @@ const layerMakeServer = Layer.unwrap( export const runServer = Layer.launch( // For the layers above whose spawner requirement is not met by one of them. - layerMakeServer.pipe(Layer.provide(NonBlockingSpawner.layer.pipe(Layer.provide(layerSpawner)))), + layerMakeServer.pipe( + Layer.provide(ProcessLauncher.layerServer.pipe(Layer.provide(layerSpawner))), + ), ); diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts index 20bb46a45e66e..c39c4ee4428ff 100644 --- a/apps/server/src/serverOwnership.ts +++ b/apps/server/src/serverOwnership.ts @@ -88,7 +88,7 @@ const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* ( const runner = yield* ProcessRunner.ProcessRunner; const result = yield* runner .run({ - ...legacyOwnerStartTimeCommand(state.pid, platform), + ...legacyOwnerStartTimeCommand(state.pid, platform, yield* HostProcess.Environment), timeout: Duration.seconds(2), maxOutputBytes: 16_384, }) diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 182297e6bdf0a..0f5c52478b998 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -10,7 +10,6 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; -import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import * as Cause from "effect/Cause"; import * as Console from "effect/Console"; @@ -50,7 +49,11 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import { getServerOwners } from "./telemetry/Identify.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; -import { formatHeadlessServeOutput, issueHeadlessServeAccessInfo } from "./startupAccess.ts"; +import { + formatHeadlessServeOutput, + issueHeadlessServeAccessInfo, + resolveLocalOrigin, +} from "./startupAccess.ts"; export class ServerRuntimeStartupError extends Schema.TaggedError()( "ServerRuntimeStartupError", @@ -344,12 +347,8 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () { const resolveStartupBrowserTarget = Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; - const localUrl = `http://localhost:${serverConfig.port}`; - const bindUrl = - serverConfig.host && !isWildcardHost(serverConfig.host) - ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}` - : localUrl; - const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl; + const baseTarget = + serverConfig.devUrl?.toString() ?? resolveLocalOrigin(serverConfig.host, serverConfig.port); return serverConfig.mode === "desktop" ? baseTarget : yield* serverAuth.issueStartupPairingUrl(baseTarget); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 5d46c916c3990..e8efe5d2f91bc 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -2425,6 +2425,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" assert.isFalse(settings.projectSettingsFolded); assert.isFalse(settings.continueThreadsAfterServerUpdate); assert.equal(settings.usageHistoryRetentionDays, "unlimited"); + assert.isTrue(settings.requireConnectDeviceApproval); + assert.isFalse(settings.enablePreviewTunnel); + assert.isFalse(settings.enableAgentBrowserAccess); + assert.equal(settings.defaultRuntimeMode, "approval-required"); assert.deepEqual(settings.projectSettingsOverrides, {}); assert.equal(yield* fileSystem.readFileString(serverConfig.settingsPath), broken); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index dd65c7f03e4d4..759b5d2f48d3f 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -428,11 +428,15 @@ function decodeSettingsFile( const settings: ServerSettings = Exit.isSuccess(decoded) && failure === undefined ? decoded.value - : // The file may hold an opt-out we can no longer read; never resume threads on a guess. + : // The file may hold choices we can no longer read, so opt-in behaviour stays off. { ...managed.defaults, continueThreadsAfterServerUpdate: false, usageHistoryRetentionDays: "unlimited", + requireConnectDeviceApproval: true, + enablePreviewTunnel: false, + enableAgentBrowserAccess: false, + defaultRuntimeMode: "approval-required", }; return { settings, legacy: Exit.isSuccess(legacy) ? legacy.value : undefined, failure }; } diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index c7259b4bd84fb..86df5b092ac89 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -553,7 +553,7 @@ setInterval(() => {}, 1_000); ); yield* fs.writeFileString( path.join(bin, "systemctl"), - `#!/bin/sh\necho reload >> '${path.join(root, "reloads")}'\n`, + `#!/bin/sh\n[ "$*" = "--user daemon-reload" ] && echo reload >> '${path.join(root, "reloads")}'\n`, ); yield* fs.chmod(path.join(bin, "busctl"), 0o755); yield* fs.chmod(path.join(bin, "systemctl"), 0o755); @@ -896,6 +896,51 @@ process.exit(0); }), ); + it.effect("repoints a unit that names this T3 home through a symlink", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-alias-" }); + const alias = path.join(root, "alias"); + yield* fs.symlink(root, alias); + const statePath = path.join(root, "runtime", "service-state.json"); + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", "1.1.0"), + "setInterval(() => {}, 1_000);\n", + ); + yield* Effect.promise(() => + writeServiceState(statePath, { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.1.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + status: "committed", + }, + }), + ); + const unit = yield* fakeServiceUnit(fs, path, alias, "1.0.0"); + const launcher = new Launcher( + root, + yield* Effect.promise(() => readServiceState(statePath)), + { + serviceUnit: unit, + }, + ); + const running = launcher.run(); + yield* Effect.promise(() => launcher.stop("SIGTERM")); + yield* Effect.promise(() => running); + + assert.equal( + yield* fs.readFileString(unit.path), + renderBootServiceUnit(unitPlan(alias, "1.1.0")), + ); + }), + ); + it.effect("waits without exiting and restarts once the other owner releases the T3 home", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 8dcd7886fce51..61e52b19d63f6 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -8,6 +8,8 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; import { acquireServiceSelectionLock } from "./cloud/serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./cloud/userManagerOom.ts"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { isNoCopyOnWrite, markNoCopyOnWrite } from "./noCopyOnWrite.ts"; import type { @@ -136,8 +138,10 @@ export interface ServiceUnit { readonly reload: () => Promise; } +const SCHTASKS = () => windowsSystem32Path(process.env, "schtasks.exe"); + const runSchtasks = (...args: ReadonlyArray) => - NodeUtil.promisify(NodeChildProcess.execFile)("schtasks", args, { + NodeUtil.promisify(NodeChildProcess.execFile)(SCHTASKS(), args, { windowsHide: true, timeout: 30_000, }); @@ -224,8 +228,8 @@ async function serviceUnitFromEnvironment( ); return { path: NodePath.join(unitDir, unitName), - reload: () => - new Promise((resolve, reject) => { + reload: async () => { + await new Promise((resolve, reject) => { NodeChildProcess.spawn("systemctl", ["--user", "daemon-reload"], { stdio: "ignore", timeout: 30_000, @@ -236,7 +240,16 @@ async function serviceUnitFromEnvironment( ? resolve() : reject(new Error(`systemctl --user daemon-reload exited with ${code ?? signal}`)), ); - }), + }); + await new Promise((resolve) => { + NodeChildProcess.spawn("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + stdio: "ignore", + timeout: 30_000, + }) + .once("error", () => resolve()) + .once("exit", () => resolve()); + }); + }, }; } @@ -870,7 +883,7 @@ export async function stateDirOwned(baseDir: string): Promise { if (!Number.isFinite(recordedAt)) return true; // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. const platform = process.platform; - const { command, args, env } = legacyOwnerStartTimeCommand(pid, platform); + const { command, args, env } = legacyOwnerStartTimeCommand(pid, platform, process.env); const output = await new Promise((resolve) => NodeChildProcess.execFile( command, @@ -1406,9 +1419,10 @@ export class Launcher { } const contents = decodeServiceUnit(await NodeFSP.readFile(unit.path)); const installedBaseDir = serviceUnitBaseDirOf(contents); + const real = (dir: string) => NodeFSP.realpath(dir).catch(() => NodePath.resolve(dir)); if ( installedBaseDir === undefined || - NodePath.resolve(installedBaseDir) !== NodePath.resolve(this.#baseDir) + (await real(installedBaseDir)) !== (await real(this.#baseDir)) ) { return; } @@ -1643,7 +1657,7 @@ export async function main(options: LauncherOptions = {}): Promise { // lets the next repeating trigger start the service again. if (windows && options.serviceUnit !== undefined) { const taskName = serviceTaskName(process.env.USERDOMAIN ?? "", process.env.USERNAME ?? ""); - NodeChildProcess.spawnSync("schtasks", ["/End", "/TN", taskName], { + NodeChildProcess.spawnSync(SCHTASKS(), ["/End", "/TN", taskName], { stdio: "ignore", windowsHide: true, }); diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index 8bbf2d81bc065..c6d5405cfa82c 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -7,6 +7,7 @@ import { expect, vi } from "vite-plus/test"; import { AuthSessionId, AuthOrchestrationOperateScope, + AuthProvidersManageScope, AuthSettingsWriteScope, type AuthEnvironmentScope, CloudSpeechError, @@ -37,17 +38,18 @@ import { speechHttpApiLayer } from "./http.ts"; const decodeSessionId = Schema.decodeUnknownSync(AuthSessionId); -const principal = (...scopes: AuthEnvironmentScope[]) => +const principalWith = (scopes: ReadonlySet) => Layer.succeed(EnvironmentAuthenticatedAuth, (effect) => effect.pipe( Effect.provideService(EnvironmentAuthenticatedPrincipal, { sessionId: decodeSessionId("voice-test"), subject: "test", method: "bearer-access-token", - scopes: new Set(scopes), + scopes, }), ), ); +const principal = (...scopes: AuthEnvironmentScope[]) => principalWith(new Set(scopes)); const dependencies = Layer.mergeAll( Layer.mock(CloudSpeech.CloudSpeech)({}), @@ -145,6 +147,10 @@ effectIt.effect( Effect.gen(function* () { let stored = false; const reference = { provider: "work", reference: "op://Work/Voice/key" }; + const scopes = new Set([ + AuthOrchestrationOperateScope, + AuthSettingsWriteScope, + ]); const save = vi.fn(); const transcribe = vi.fn(); const cloud = Layer.mock(CloudSpeech.CloudSpeech)({ @@ -182,7 +188,7 @@ effectIt.effect( const { handler, dispose } = HttpRouter.toWebHandler( HttpApiBuilder.layer(HttpApi.make("environment").add(EnvironmentVoiceHttpApi)).pipe( Layer.provide(speechHttpApiLayer), - Layer.provide(principal(AuthOrchestrationOperateScope, AuthSettingsWriteScope)), + Layer.provide(principalWith(scopes)), Layer.provide( Layer.mock(SpeechService.SpeechService)({ models: () => Effect.succeed({ models: [linkedModel] }), @@ -220,6 +226,14 @@ effectIt.effect( headers: { "content-type": "application/json" }, body: JSON.stringify({ key }), }); + // A reference needs the scope that saving it through settings would. + const refused = yield* setReference(reference); + expect(refused.status).toBe(403); + expect(yield* Effect.promise(() => refused.json())).toMatchObject({ + requiredPermission: AuthProvidersManageScope, + }); + expect(save).toHaveBeenCalledTimes(1); + scopes.add(AuthProvidersManageScope); expect((yield* setReference(reference)).status).toBe(204); expect(save).toHaveBeenLastCalledWith("xai", reference); expect((yield* setReference(reference.reference)).status).toBe(400); diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 09c3d4dc23faa..f73640044be89 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -8,6 +8,7 @@ import { EnvironmentHttpApi, type EnvironmentSpeechModels, EnvironmentVoiceBodyLimit, + requiredScopesForServerSettingsPatch, SPEECH_MAX_OPTIONS_BYTES, TextGenerationError, } from "@t3tools/contracts"; @@ -15,6 +16,7 @@ import * as ByteSize from "effect/ByteSize"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; import * as Schema from "effect/Schema"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; @@ -102,6 +104,14 @@ export const speechHttpApiLayer = HttpApiBuilder.group( "setCloudKey", Effect.fn("environment.voice.setCloudKey")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); + // The key is a setting, so saving it needs what the same settings patch would. + const { key } = args.payload; + const value = key === null || Redacted.isRedacted(key) ? "" : key; + for (const scope of requiredScopesForServerSettingsPatch({ + cloudSpeechCredentials: { [args.params.provider]: value }, + })) { + yield* requireEnvironmentScope(scope); + } yield* cloud .setKey(args.params.provider, args.payload.key) .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error))); diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index c36c29e5f1278..c29c6ce04605b 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -14,6 +14,7 @@ import { closeNonPrivateNetworkConnections, loopbackUrlHostForAddress, resolveHeadlessConnectionString, + resolveLocalOrigin, } from "./startupAccess.ts"; const ipv4 = (address: string, internal = false): NodeOS.NetworkInterfaceInfo => ({ @@ -58,7 +59,17 @@ it("skips public and container addresses for a private-network listener", () => privateNetworkOnly: true, platform: "linux", }), - ).toBe("http://localhost:3773"); + ).toBe("http://127.0.0.1:3773"); +}); + +it("names the bound loopback address instead of localhost", () => { + const options = { interfaces: {}, platform: "linux" as const }; + expect(resolveHeadlessConnectionString(undefined, 3773, options)).toBe("http://127.0.0.1:3773"); + expect(resolveHeadlessConnectionString("::", 3773, options)).toBe("http://[::1]:3773"); + expect(resolveLocalOrigin(undefined, 3773)).toBe("http://127.0.0.1:3773"); + expect(resolveLocalOrigin("0.0.0.0", 3773)).toBe("http://127.0.0.1:3773"); + expect(resolveLocalOrigin("[::]", 3773)).toBe("http://[::1]:3773"); + expect(resolveLocalOrigin("192.168.1.42", 3773)).toBe("http://192.168.1.42:3773"); }); it("prefers a LAN address over a tailnet one for a private-network pairing URL", () => { diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index ce1b8be41938f..c3d52bed9b401 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -137,6 +137,15 @@ const isIpv4Family = (family: string | number): boolean => family === "IPv4" || const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6; +// A startup URL names the address the server bound; `localhost` can resolve to the other +// address family, where this server is not listening. +const loopbackAddressFor = (host: string | undefined): string => + host !== undefined && normalizeHost(host) === "::" ? "::1" : "127.0.0.1"; + +/** The origin a browser on this machine uses to reach a server bound to `host`. */ +export const resolveLocalOrigin = (host: string | undefined, port: number): string => + `http://${formatHostForUrl(host && !isWildcardHost(host) ? normalizeHost(host) : loopbackAddressFor(host))}:${port}`; + const resolveHeadlessConnectionHost = ( host: string | undefined, interfaces: NetworkInterfacesMap, @@ -144,7 +153,7 @@ const resolveHeadlessConnectionHost = ( platform: NodeJS.Platform, ): string => { if (!host) { - return "localhost"; + return loopbackAddressFor(host); } if (!isWildcardHost(host)) { @@ -171,13 +180,13 @@ const resolveHeadlessConnectionHost = ( return externalIpv4.address; } if (privateNetworkOnly) { - return "localhost"; + return loopbackAddressFor(host); } const externalIpv6 = interfaceEntries.find( (entry) => !entry.internal && isIpv6Family(entry.family), ); - return externalIpv6 ? normalizeHost(externalIpv6.address) : "localhost"; + return externalIpv6 ? normalizeHost(externalIpv6.address) : loopbackAddressFor(host); }; export const resolveHeadlessConnectionString = ( diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 0594597f43498..f1d1d60c23c69 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -370,6 +370,7 @@ const cleanupFixture = ( let onLiveCheck: Effect.Effect = Effect.void; let outboxStatus: string | null = null; let scheduledThreadIds: string[] = []; + let branchPullRequests: Record = {}; let fullStatusCalls = 0; let statusCommands = 0; let gitInspections = 0; @@ -525,6 +526,8 @@ const cleanupFixture = ( ), Effect.provideService(GitManager.GitManager, { invalidateStatus: () => Effect.void, + branchPullRequest: (input: { branch: string }) => + Effect.sync(() => branchPullRequests[input.branch] ?? null), } as unknown as GitManager.GitManager["Service"]), Effect.provideService(TerminalManager.TerminalManager, { subscribeMetadata: ( @@ -589,6 +592,9 @@ const cleanupFixture = ( setThreads: (next: typeof threads) => { threads = next; }, + setBranchPullRequests: (next: typeof branchPullRequests) => { + branchPullRequests = next; + }, threadBranches: () => threads.map((thread) => thread.branch), setOnLiveCheck: (hook: Effect.Effect) => { onLiveCheck = hook; @@ -1067,14 +1073,39 @@ it.live("removes a task folder's clean worktrees and keeps the one with uncommit expect((yield* taskFolders.find(root))?.repositories).toHaveLength(2); yield* command(`${root}/dist/api`, ["checkout", "--", "tracked.txt"]); + // Git deletes the checkout, then fails on metadata it cannot delete. + const adminDir = (yield* command(`${root}/dist/api`, [ + "rev-parse", + "--absolute-git-dir", + ])).stdout.trim(); + const stuck = `${adminDir}/scratch`; + yield* fs.makeDirectory(stuck); + yield* fs.writeFileString(`${stuck}/f`, "x\n"); + yield* fs.chmod(stuck, 0o555); + yield* Effect.addFinalizer(() => fs.chmod(stuck, 0o755).pipe(Effect.ignore)); const second = yield* service.runNow; expect(second.entries.filter((entry) => entry.path?.startsWith(root))).toEqual( [`${root}/dist/api`, root].map((path) => - expect.objectContaining({ path, outcome: "removed" }), + expect.objectContaining({ path, outcome: "kept" }), ), ); + expect(yield* fs.exists(`${root}/dist/api`)).toBe(false); + // The checkout is gone, so the folder goes and only the record keeps the metadata in view. + expect( + (yield* service.runNow).entries.filter((entry) => entry.path?.startsWith(root)), + ).toEqual( + [ + { path: `${root}/dist/api`, outcome: "failed" }, + { path: root, outcome: "removed" }, + ].map((entry) => expect.objectContaining(entry)), + ); expect(yield* fs.exists(root)).toBe(false); + yield* fs.chmod(stuck, 0o755); + expect((yield* service.runNow).entries).toEqual([ + expect.objectContaining({ path: `${root}/dist/api`, outcome: "removed" }), + ]); + expect(yield* fs.exists(adminDir)).toBe(false); expect(yield* fs.readFileString(`${api.path}/tracked.txt`)).toBe("original\n"); }), ), @@ -1402,6 +1433,87 @@ describe("subagent worktree ownership", () => { }).pipe(Effect.provide(cleanupTestLayer)), ); + it.effect.each(["merge", "squash"] as const)( + "removes an isolated subagent worktree whose branch reached the default branch through its parent's merged pull request (%s)", + (strategy) => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeOnMerge: true, + worktreeOnDelete: true, + worktreeAfterDays: 30, + }); + const { repo, worktree, command, fs } = fixture; + const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); + yield* command(remote, ["init", "--bare", "-b", "main"]); + yield* command(repo, ["remote", "add", "origin", remote]); + yield* command(repo, ["push", "origin", "main"]); + yield* fs.writeFileString(`${worktree}/tracked.txt`, "subagent work\n"); + yield* command(worktree, ["commit", "-am", "subagent work"]); + // The parent merges the subagent's branch into its own and ships one pull request. + yield* command(repo, ["branch", "parent-branch", "main"]); + yield* command(repo, ["checkout", "parent-branch"]); + yield* command(repo, ["merge", "--no-ff", "-m", "merge subagent", "feature"]); + yield* command(repo, ["checkout", "main"]); + if (strategy === "merge") { + yield* command(repo, [ + "merge", + "--no-ff", + "-m", + "merge parent pull request", + "parent-branch", + ]); + } else { + yield* command(repo, ["merge", "--squash", "parent-branch"]); + yield* command(repo, ["commit", "-m", "squash parent pull request"]); + } + yield* command(repo, ["push", "origin", "main"]); + const parentHead = (yield* command(repo, ["rev-parse", "parent-branch"])).stdout.trim(); + fixture.setBranchPullRequests({ + "parent-branch": { + number: 7, + title: "Parent work", + url: "https://github.com/example/repo/pull/7", + baseRef: "main", + headRef: "parent-branch", + headSha: parentHead, + state: "merged", + repositoryKey: null, + updatedAt: "2026-06-08T12:00:00.000Z", + } as GitManager.GitBranchPullRequest, + }); + const parent = shell({ + branch: "parent-branch", + status: "completed", + settledAt: at(-DAY_MS), + createdAt: at(-3 * DAY_MS), + updatedAt: at(-DAY_MS), + }); + const child = shell({ + id: ThreadId.make("child"), + branch: "feature", + worktreePath: worktree, + status: "completed", + createdAt: at(-3 * DAY_MS), + latestRunCompletedAt: at(-2 * DAY_MS), + updatedAt: at(-2 * DAY_MS), + lineage: { + parentThreadId: parent.id, + rootThreadId: parent.id, + relationshipToParent: "subagent", + }, + }); + fixture.setThreads([child, parent]); + + const report = yield* fixture.service.runNow; + expect(report.entries.find((entry) => entry.threadId === child.id)).toMatchObject({ + outcome: "removed", + }); + expect(yield* fs.exists(worktree)).toBe(false); + }).pipe(Effect.provide(cleanupTestLayer)), + ); + it.effect.each([ "parent-unsettled", "parent-resettled", @@ -2992,6 +3104,79 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps reporting a worktree whose git metadata cannot be deleted", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const adminDir = (yield* fixture.command(fixture.worktree, [ + "rev-parse", + "--absolute-git-dir", + ])).stdout.trim(); + // Stands in for root-owned files a container wrote into the worktree's git dir. + const stuck = `${adminDir}/scratch/fanal`; + yield* fixture.fs.makeDirectory(stuck, { recursive: true }); + yield* fixture.fs.writeFileString(`${stuck}/f`, "x\n"); + yield* fixture.fs.chmod(stuck, 0o555); + yield* Effect.addFinalizer(() => fixture.fs.chmod(stuck, 0o755).pipe(Effect.ignore)); + yield* fixture.service.runNow; + // Git may delete these before it reaches the folder it cannot, and then stops listing + // the worktree. + yield* fixture.fs.remove(`${adminDir}/gitdir`, { force: true }); + yield* fixture.fs.remove(`${adminDir}/HEAD`, { force: true }); + const later = yield* fixture.service.runNow; + expect(later.entries).toEqual([ + expect.objectContaining({ + path: fixture.worktree, + outcome: expect.stringMatching(/^(kept|failed)$/), + }), + ]); + expect((yield* fixture.service.runNow).entries).toEqual(later.entries); + expect(yield* fixture.fs.exists(stuck)).toBe(true); + yield* fixture.fs.chmod(stuck, 0o755); + expect((yield* fixture.service.runNow).entries).toEqual([ + expect.objectContaining({ path: fixture.worktree, outcome: "removed" }), + ]); + expect(yield* fixture.fs.exists(adminDir)).toBe(false); + expect((yield* fixture.service.runNow).entries).toEqual([]); + // An unreadable record may still name leftovers, so it is reported and kept as it is. + const record = `${fixture.config.stateDir}/storage-cleanup-leftovers.json`; + yield* fixture.fs.writeFileString(record, "{"); + expect((yield* fixture.service.runNow).entries).toEqual([ + expect.objectContaining({ path: record, outcome: "failed" }), + ]); + expect(yield* fixture.fs.readFileString(record)).toBe("{"); + }), + ), + ); + it.live("leaves git metadata that a recreated worktree took over from a failed removal", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const adminDir = (yield* fixture.command(fixture.worktree, [ + "rev-parse", + "--absolute-git-dir", + ])).stdout.trim(); + const stuck = `${adminDir}/scratch`; + yield* fixture.fs.makeDirectory(stuck); + yield* fixture.fs.writeFileString(`${stuck}/f`, "x\n"); + yield* fixture.fs.chmod(stuck, 0o555); + yield* Effect.addFinalizer(() => fixture.fs.chmod(stuck, 0o755).pipe(Effect.ignore)); + yield* fixture.service.runNow; + // The user repairs and prunes the leftover, then the thread resumes under the same name. + yield* fixture.fs.chmod(stuck, 0o755); + yield* fixture.command(fixture.repo, ["worktree", "prune"]); + yield* fixture.command(fixture.repo, ["worktree", "add", fixture.worktree, "feature"]); + // Only the cleanup rules remove it now: its metadata is no longer a leftover. + expect((yield* fixture.service.runNow).entries).toEqual([ + expect.objectContaining({ + path: fixture.worktree, + outcome: "removed", + reason: expect.stringMatching(/^Inactive for/), + }), + ]); + }), + ), + ); it.live("skips a stored worktree path whose parent is a regular file", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 25c5c7a7d0297..5963320953485 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -5,6 +5,7 @@ import { GitCommandError, OrchestrationV2AppThreadJson, OrchestrationV2ProviderSessionJson, + StorageCleanupReportEntry, } from "@t3tools/contracts"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Schema from "effect/Schema"; @@ -17,9 +18,9 @@ import type { TerminalSummary, WorktreeCleanupRules, StorageCleanupReport, - StorageCleanupReportEntry, ThreadId, } from "@t3tools/contracts"; +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; import { resolveWorktreeT3Home } from "@t3tools/shared/devHome"; import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; @@ -76,6 +77,11 @@ const decodeCleanupThread = Schema.decodeUnknownEffect( const decodeCleanupSession = Schema.decodeUnknownEffect( Schema.fromJsonString(OrchestrationV2ProviderSessionJson), ); +const decodeWorktreeLeftovers = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Array(Schema.Struct({ adminDir: Schema.String, entry: StorageCleanupReportEntry })), + ), +); // pnpm 11 writes this file as JSON, older versions as YAML. const decodePnpmModulesManifest = Schema.decodeUnknownEffect( Schema.Struct({ @@ -1101,6 +1107,103 @@ const make = Effect.gen(function* () { }); }); + // Git deletes a checkout before its metadata under `/.git/worktrees`. When the + // metadata then cannot be deleted, no checkout is left for a sweep to find and Git may no longer + // list the worktree, so the leftover is written down here and retried until it is gone. + const leftoversPath = path.join(config.stateDir, "storage-cleanup-leftovers.json"); + // Only a missing file is empty: an unreadable one may hold records a write would replace. + const readLeftovers = fs.readFileString(leftoversPath).pipe( + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed("[]")), + Effect.flatMap(decodeWorktreeLeftovers), + ); + const writeLeftovers = ( + leftovers: ReadonlyArray<{ + readonly adminDir: string; + readonly entry: StorageCleanupReportEntry; + }>, + ) => + leftovers.length === 0 + ? fs.remove(leftoversPath, { force: true }) + : writeFileStringAtomically({ + filePath: leftoversPath, + contents: `${JSON.stringify(leftovers, null, 2)}\n`, + }); + const worktreeAdminDir = Effect.fn("StorageCleanup.worktreeAdminDir")(function* ( + worktreePath: string, + ) { + const gitDir = yield* git.execute({ + operation: "StorageCleanup.worktreeAdminDir", + cwd: worktreePath, + args: ["rev-parse", "--absolute-git-dir"], + }); + return gitDir.stdout.trim(); + }); + const noteLeftover = Effect.fn("StorageCleanup.noteLeftover")( + function* (adminDir: string, entry: StorageCleanupReportEntry) { + if (entry.path === null || path.basename(path.dirname(adminDir)) !== "worktrees") return; + // A removal Git refused keeps its checkout, and the next sweep looks at it again. + if (yield* fs.exists(entry.path).pipe(Effect.orElseSucceed(() => true))) return; + if (!(yield* fs.exists(adminDir).pipe(Effect.orElseSucceed(() => true)))) return; + const others = (yield* readLeftovers).filter((leftover) => leftover.adminDir !== adminDir); + yield* writeLeftovers([...others, { adminDir, entry }]); + }, + Effect.catch((error) => + Effect.logWarning("storage cleanup could not record leftover git metadata", { error }), + ), + ); + const removeLeftover = Effect.fn("StorageCleanup.removeLeftover")(function* (adminDir: string) { + // Pruning by hand frees the name, and a worktree recreated since may have taken it. + const gitFile = yield* fs.readFileString(path.join(adminDir, "gitdir")).pipe( + Effect.map((gitdir) => path.resolve(adminDir, gitdir.trim())), + Effect.option, + ); + if (Option.isSome(gitFile) && (yield* fs.exists(gitFile.value))) { + const current = yield* worktreeAdminDir(path.dirname(gitFile.value)); + if ((yield* fs.realPath(current)) === (yield* fs.realPath(adminDir))) return false; + } + yield* fs.remove(adminDir, { recursive: true }); + return true; + }); + const retryLeftovers = Effect.fn("StorageCleanup.retryLeftovers")(function* ( + entries: StorageCleanupReportEntry[], + ) { + const leftovers = yield* readLeftovers; + const remaining: Array<(typeof leftovers)[number]> = []; + for (const leftover of leftovers) { + const { adminDir, entry } = leftover; + if (!(yield* fs.exists(adminDir).pipe(Effect.orElseSucceed(() => true)))) continue; + const failure = yield* removeLeftover(adminDir).pipe( + Effect.map((removed) => { + if (removed) + entries.push({ + ...entry, + outcome: "removed", + reason: "Deleted git metadata an earlier cleanup left behind", + }); + return null; + }), + Effect.catch((error) => Effect.succeed(error)), + ); + if (failure === null) continue; + remaining.push(leftover); + entries.push({ + ...entry, + outcome: "failed", + reason: `Git metadata at ${adminDir} could not be deleted: ${cleanupFailureReason(failure)}`, + }); + yield* Effect.logWarning("storage cleanup failed for leftover git metadata", { + threadId: entry.threadId, + error: failure, + }); + } + if (remaining.length !== leftovers.length) + yield* writeLeftovers(remaining).pipe( + Effect.catch((error) => + Effect.logWarning("storage cleanup could not update leftover git metadata", { error }), + ), + ); + }); + const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* ( serverSettings: ServerSettings, now: number, @@ -1560,18 +1663,24 @@ const make = Effect.gen(function* () { if (blockedSinceLease !== null) return keep(blockedSinceLease); if (yield* settingsChangedSinceCheck) return keep("settings changed since check"); const checkoutBytes = new Map(); + const adminDirs = new Map(); // Each checkout passes the checks a single worktree does, or it stays. const result = yield* taskFolders.remove({ root: taskFolder.root, force: false, forget: deleted, inspect: (checkout) => - inspectCheckout( - checkout.worktreePath, - thread.branch, - settings, - settingsChangedSinceCheck, - ).pipe( + worktreeAdminDir(checkout.worktreePath).pipe( + Effect.map((adminDir) => adminDirs.set(checkout.worktreePath, adminDir)), + Effect.ignore, + Effect.andThen( + inspectCheckout( + checkout.worktreePath, + thread.branch, + settings, + settingsChangedSinceCheck, + ), + ), Effect.tap(({ bytes }) => Effect.sync(() => checkoutBytes.set(checkout.worktreePath, bytes)), ), @@ -1587,12 +1696,16 @@ const make = Effect.gen(function* () { reason: sentence(removalReason), bytes: checkoutBytes.get(removedPath) ?? null, }); - for (const keptCheckout of result.kept) + for (const keptCheckout of result.kept) { entries.push({ ...entry, path: keptCheckout.path, reason: sentence(keptCheckout.reason), }); + const adminDir = adminDirs.get(keptCheckout.path); + if (adminDir !== undefined) + yield* noteLeftover(adminDir, { ...entry, path: keptCheckout.path }); + } if (result.kept.length > 0 && deleted && settings.worktreeOnDelete) kept.push(worktreePath); yield* gitManager.invalidateStatus(project.workspaceRoot); @@ -1704,6 +1817,16 @@ const make = Effect.gen(function* () { remote === null ? "no commits beyond the project branch" : "no commits beyond the default branch"; + // A subagent's isolated branch ships through its parent's pull request or a direct + // merge, never a pull request of its own, so a finished one counts once on the default. + const subagentFinished = + settings.worktreeOnMerge && + thread.lineage.relationshipToParent === "subagent" && + settledThread !== undefined; + if (!eligible && integrated && remote !== null && subagentFinished) { + eligible = true; + removalReason = "work is on the default branch"; + } if (!eligible && remote !== null && settings.worktreeOnMerge && thread.branch !== null) { const pullRequest = yield* gitManager.branchPullRequest( { cwd: worktreePath, branch: thread.branch }, @@ -1717,6 +1840,39 @@ const make = Effect.gen(function* () { }); if (eligible) removalReason = "pull request was merged"; } + // Squash and rebase merges leave a subagent's commits off the default branch, so + // its work counts as shipped when a parent's merged pull request head contains it. + if (!eligible && subagentFinished && remote !== null) { + const seen = new Set([thread.id]); + let child: Pick = thread; + while (!eligible && child.lineage.relationshipToParent === "subagent") { + const parent = threadsById.get(child.lineage.parentThreadId!); + if (parent === undefined || seen.has(parent.id)) break; + seen.add(parent.id); + child = parent; + if (parent.branch === null || parent.branch === thread.branch) continue; + const pullRequest = yield* gitManager.branchPullRequest( + { cwd: worktreePath, branch: parent.branch }, + { refresh: true, includeHeadRepository: true }, + ); + const headSha = pullRequest?.headSha; + if ( + pullRequest?.state !== "merged" || + pullRequest.baseRef !== branch || + typeof headSha !== "string" || + !/^[0-9a-f]{40,64}$/i.test(headSha) + ) + continue; + const shipped = yield* git.execute({ + operation: "StorageCleanup.shippedThroughParent", + cwd: worktreePath, + args: ["merge-base", "--is-ancestor", head.commitSha, headSha], + allowNonZeroExit: true, + }); + eligible = shipped.exitCode === 0; + if (eligible) removalReason = "parent's pull request was merged"; + } + } if (!eligible && remote === null) return keep(integrated ? notDueReason : "has commits beyond the project branch"); } @@ -1757,6 +1913,7 @@ const make = Effect.gen(function* () { // Forced removal already discards local files; do not widen its final-check window. if (settings.worktreeKeepWhen === "tracked-changes" && !submodules.force) yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean"); + const adminDir = yield* worktreeAdminDir(worktreePath); yield* removeLinkedWorktree({ operation: "StorageCleanup.cleanupGit", cwd: repository, @@ -1765,7 +1922,7 @@ const make = Effect.gen(function* () { force: submodules.force, execute: git.execute, run: (args) => cleanupGit(repository, [...args], "git worktree remove"), - }); + }).pipe(Effect.tapError(() => noteLeftover(adminDir, entry))); entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes }); yield* gitManager.invalidateStatus(project.workspaceRoot); // Preserve branch/path so ProviderTurnStartService can recreate the checkout on resume. @@ -1966,6 +2123,26 @@ const make = Effect.gen(function* () { yield* cleanCheckpointRefs().pipe( Effect.catch((cause) => Effect.logWarning("checkpoint ref cleanup failed", { cause })), ); + yield* retryLeftovers(entries).pipe( + Effect.catch((error) => + Effect.gen(function* () { + entries.push({ + kind: "worktree", + outcome: "failed", + reason: `Could not read the record of leftover git metadata: ${cleanupFailureReason(error)}`, + path: leftoversPath, + projectPath: null, + threadId: null, + threadTitle: null, + bytes: null, + files: null, + }); + yield* Effect.logWarning("storage cleanup could not read leftover git metadata", { + error, + }); + }), + ), + ); const deletedWorktrees = yield* cleanWorktrees(serverSettings, now, entries, trigger).pipe( Effect.catch((error) => Effect.gen(function* () { diff --git a/apps/server/src/telemetry/ProviderDimensions.test.ts b/apps/server/src/telemetry/ProviderDimensions.test.ts index 00e59c11228cb..e24bb480d1e24 100644 --- a/apps/server/src/telemetry/ProviderDimensions.test.ts +++ b/apps/server/src/telemetry/ProviderDimensions.test.ts @@ -37,7 +37,7 @@ const thread = ( ...overrides, }); -it("omits custom, user-configured, and unknown models and instance names", () => { +it("reports every model name but never instance names", () => { expect( agentToolProperties({ tool: "t3_thread_send", @@ -54,13 +54,13 @@ it("omits custom, user-configured, and unknown models and instance names", () => ).toEqual([ { callerProvider: "claudeAgent", - callerModel: undefined, + callerModel: "my-private-finetune", targetProvider: "opencode", - targetModel: undefined, + targetModel: "ollama/acme-internal", }, { callerProvider: "claudeAgent", - callerModel: undefined, + callerModel: "my-private-finetune", targetProvider: "unknown", targetModel: undefined, }, diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.ts index 49faea7e688c0..7aa44cd46727b 100644 --- a/apps/server/src/telemetry/ProviderDimensions.ts +++ b/apps/server/src/telemetry/ProviderDimensions.ts @@ -6,19 +6,6 @@ import type { import { BUNDLED_MODEL_MANIFEST } from "../provider/ModelManifest.ts"; -/** - * Drivers whose model catalogs are published by the vendor. Other drivers - * (OpenCode, Pi, ACP agents) list models from the user's own configuration, - * such as local Ollama tags, so their model names stay out of analytics. - */ -const VENDOR_CATALOG_DRIVERS: ReadonlySet = new Set([ - "codex", - "claudeAgent", - "cursor", - "grok", - "antigravity", -]); - export interface ProviderDimensions { readonly provider: string; readonly model?: string; @@ -26,8 +13,7 @@ export interface ProviderDimensions { /** * Anonymous provider and model for a model selection. Instance ids are - * user-defined, so only the driver kind is reported. The model is reported - * only when it comes from a vendor catalog and is not a user-added custom model. + * user-defined, so only the driver kind is reported. */ export function providerDimensions( providers: ReadonlyArray, @@ -35,17 +21,16 @@ export function providerDimensions( ): ProviderDimensions { const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); if (provider === undefined) return { provider: "unknown" }; - const model = provider.models.find((candidate) => candidate.slug === selection.model); - return VENDOR_CATALOG_DRIVERS.has(provider.driver) && model !== undefined && !model.isCustom - ? { provider: provider.driver, model: model.slug } - : { provider: provider.driver }; + return { provider: provider.driver, model: modelLabel(providers, selection.model) }; } const DATED_SNAPSHOT = /-\d{8}$/u; +// Absolute, home, relative, or Windows paths, such as a local GGUF file. Directories can name the user. +const FILE_PATH = /^(?:[/~]|\.{1,2}[/\\]|[A-Za-z]:[\\/])|\\/u; + +const fileName = (model: string) => + FILE_PATH.test(model) ? model.slice(model.search(/[^/\\]*$/u)) : model; -// The bundled manifest is reviewed in this repo. Codex lists whatever its configured -// model provider serves, so only the manifest vouches for Codex and Claude. Cursor, Grok, -// and Antigravity list their vendor's catalog, which ships models before the manifest does. const MANIFEST_LABELS: ReadonlyMap = new Map( Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) => catalog.models.flatMap((model) => @@ -53,18 +38,18 @@ const MANIFEST_LABELS: ReadonlyMap = new Map( ), ), ); -const REGISTRY_LABEL_DRIVERS: ReadonlySet = new Set(["cursor", "grok", "antigravity"]); /** - * The vendor catalog slug that a native or routed model id names, such as - * `anthropic/claude-opus-5-5` or a dated snapshot. Models outside the bundled - * manifest and the Cursor, Grok, and Antigravity catalogs, including user-added ones, - * return undefined. + * The model name analytics reports. A routed id, alias, or dated snapshot that the + * bundled manifest or a provider's model list knows, such as `anthropic/claude-opus-5-5` + * or `antigravity-default`, maps to its catalog slug. A file path reports only its file + * name. Any other id is reported as is. */ -export function catalogModelLabel( - providers: ReadonlyArray, - model: string, -): string | undefined { +export function modelLabel(providers: ReadonlyArray, model: string): string { + return fileName(catalogSlug(providers, model) ?? model); +} + +function catalogSlug(providers: ReadonlyArray, model: string) { const leaf = model.slice(model.lastIndexOf("/") + 1); const candidates = [model, leaf, leaf.replace(DATED_SNAPSHOT, "")]; for (const candidate of candidates) { @@ -72,12 +57,10 @@ export function catalogModelLabel( if (label !== undefined) return label; } for (const provider of providers) { - if (!REGISTRY_LABEL_DRIVERS.has(provider.driver)) continue; const match = provider.models.find( (entry) => - !entry.isCustom && - (candidates.includes(entry.slug) || - entry.aliases?.some((alias) => candidates.includes(alias)) === true), + candidates.includes(entry.slug) || + entry.aliases?.some((alias) => candidates.includes(alias)) === true, ); if (match !== undefined) return match.slug; } diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 249ec86f3724c..14e4a8b68633b 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -15,7 +15,7 @@ import * as Layer from "effect/Layer"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; -import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { modelLabel } from "./ProviderDimensions.ts"; import { ProviderTurnAnalytics, RequestUsageLedger, @@ -26,10 +26,9 @@ import { } from "./ProviderUsageAnalytics.ts"; const providers = [ - // Codex lists whatever its configured model provider serves, including private deployments. - { driver: "codex", models: [{ slug: "gpt-6-sol" }, { slug: "acme-azure-deployment" }] }, + { driver: "codex", models: [{ slug: "gpt-6-sol" }] }, + { driver: "pi", models: [{ slug: "/Users/jane/models/llama.gguf", aliases: ["pi-local"] }] }, { driver: "claudeAgent", models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }] }, - { driver: "opencode", models: [{ slug: "ollama/acme-internal" }] }, // Antigravity ships models before the bundled manifest lists them. { driver: "antigravity", @@ -46,7 +45,7 @@ const providers = [ models: models.map((model) => ({ ...model, isCustom: false })), }) as unknown as ServerProvider, ); -const label = (model: string) => catalogModelLabel(providers, model); +const label = (model: string) => modelLabel(providers, model); const at = (ms: number) => DateTime.makeUnsafe(ms); const complete = (input: number, output: number, extra: Partial = {}) => @@ -305,7 +304,7 @@ describe("provider usage reporting", () => { }); }); - it("reports routed catalog models and closed efforts only", () => { + it("reports every model name and closed efforts only", () => { const routed = (model: string, variant: string) => providerTurnProperties( { @@ -326,20 +325,22 @@ describe("provider usage reporting", () => { observedModel: "claude-opus-5-5", effort: "high", }); - for (const local of [ - routed("ollama/acme-internal", "secret-variant"), - routed("acme-azure-deployment", "high"), - ]) { - expect(local).not.toHaveProperty("model"); - expect(local).not.toHaveProperty("observedModel"); - } - expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort"); + const local = routed("ollama/acme-internal", "secret-variant"); + expect(local).toMatchObject({ + model: "ollama/acme-internal", + observedModel: "ollama/acme-internal", + }); + expect(local).not.toHaveProperty("effort"); }); - it("reports Antigravity catalog models the bundled manifest does not list", () => { + it("maps provider catalog aliases to their slug and file paths to their file name", () => { expect(label("gemini-4-hydrogen")).toBe("gemini-4-hydrogen"); expect(label("antigravity-default")).toBe("gemini-4-neon"); - expect(label("gemini-4-unlisted")).toBeUndefined(); + expect(label("/Users/jane/models/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("~/models/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("C:\\Users\\jane\\qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("../jane/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("pi-local")).toBe("llama.gguf"); }); it("reports closed service tiers from a tier option or a fast mode toggle", () => { diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts index ce7f29ba1f8d5..a281f40479b55 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -26,7 +26,7 @@ import { } from "@t3tools/shared/model"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; -import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { modelLabel } from "./ProviderDimensions.ts"; // Bump when a field changes meaning, so reports can split old and new rows. const REPORT_VERSION = 2; @@ -74,8 +74,8 @@ export interface RunSettledReport { } type Properties = Readonly>; -/** Maps a native model id to a vendor catalog label, or undefined to keep it out. */ -export type ModelLabeler = (model: string) => string | undefined; +/** Maps a native model id to the name analytics reports. */ +export type ModelLabeler = (model: string) => string; const TERMINAL_STATUSES: ReadonlySet = new Set([ "completed", @@ -403,7 +403,7 @@ export const layer = Layer.effect( registry.getProviders, (providers): ModelLabeler => (model) => - catalogModelLabel(providers, model), + modelLabel(providers, model), ); return { runStarted: Effect.fn("ProviderTurnAnalytics.runStarted")((input) => diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 3524fef8fa2df..0966320452860 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -3,6 +3,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + DEFAULT_MAX_TERMINAL_BUFFER_BYTES, DEFAULT_TERMINAL_ID, ProjectId, ThreadId, @@ -488,6 +489,98 @@ it("restores bounded history across append compaction, clears and split Unicode" expect(persisted).toBe("z".repeat(maxBytes)); }); +it("stops holding a control sequence that outgrows its limit", () => { + const limit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; + // No final byte for a CSI and no terminator for a string. + const filler = "0123456789 123\r\n".repeat(64); + const fed = filler.repeat(Math.ceil(limit / filler.length) + 2); + // The terminal runs the line breaks inside a CSI while it waits for the final byte. + const lineBreaks = fed.replaceAll(/[^\r\n]/g, ""); + for (const { name, open, end, history } of [ + { name: "OSC, BEL", open: ["\u001b]0;"], end: ["\u0007"], history: "\u001b\\" }, + { + name: "OSC, split ST", + open: ["\u001b]0;"], + end: ["\u001b", "\\\u001b[31m"], + history: "\u001b\\\u001b[31m", + }, + // The last UTF-8 byte of U+20805 is 0x85, NEL, which ends the DCS and replays as ESC E. + { + name: "DCS, split code point", + open: ["\u001bPstuck"], + end: ["\ud842", "\udc05"], + history: "\u001b\\\u001bE", + }, + // The dropped CSI's ESC ended the title, so history ends it too. Its final byte would have + // made it a query that the replay answers. + { + name: "CSI after a title its ESC cuts short", + open: ["\u001b]0;title", "\u001b["], + end: ["\n6n"], + history: `\u001b]0;title\u001b\\${lineBreaks}\n`, + }, + { + name: "CSI, ESC", + open: ["\u001b["], + end: ["\n\u001b[31m"], + history: `\u001b\\${lineBreaks}\n\u001b[31m`, + }, + ]) { + let held = ""; + let visible = ""; + const feed = (data: string) => { + const sanitized = TerminalManager.sanitizeTerminalHistoryChunk(held, data); + held = sanitized.pendingControlSequence; + visible += sanitized.visibleText; + }; + + feed("before\n"); + for (const data of open) feed(data); + for (let offset = 0; offset < fed.length; offset += filler.length) { + feed(fed.slice(offset, offset + filler.length)); + } + expect(held.length, name).toBeLessThanOrEqual(3); + + for (const data of end) feed(data); + feed("after\n"); + expect(held, name).toBe(""); + expect(visible, name).toBe(`before\n${history}after\n`); + } + + // Held text of exactly the limit stays held, and a sequence that ends in the chunk where it + // passes the limit is kept whole. + for (const atLimit of ["\u001b]".padEnd(limit, "0"), "\u001b[".padEnd(limit, "0")]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", atLimit)).toEqual({ + visibleText: "", + pendingControlSequence: atLimit, + }); + const ended = `${atLimit}0${atLimit[1] === "]" ? "\u0007" : "m"}`; + expect(TerminalManager.sanitizeTerminalHistoryChunk("", ended)).toEqual({ + visibleText: ended, + pendingControlSequence: "", + }); + } + + // An escape sequence keeps its first four intermediates, the only ones libghostty reads. + const escape = '\u001b!"#$'; + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&")).toEqual({ + visibleText: "", + pendingControlSequence: escape, + }); + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&B")).toEqual({ + visibleText: `${escape}%&B`, + pendingControlSequence: "", + }); + + // A completed escape sequence stays when another ESC follows it at once. + for (const kept of ["OLD\u001bc\u001b[31mNEW", "abc\u001b7\u001b[2;5HB\u001b8Z"]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", kept)).toEqual({ + visibleText: kept, + pendingControlSequence: "", + }); + } +}); + it.layer( Layer.mergeAll( NodeServices.layer, @@ -1625,6 +1718,8 @@ it.layer( // BEL is DCS payload, not a terminator: only ST ends the string. process.emitData("\u001bP$qm\u0007hidden\u001b\\\u001bP+q544e\u0007hidden\u001b\\"); process.emitData('\u001b[!p\u001b["p\u001b[4 q\u001b[u'); + process.emitData("\u001b]11;rgb:44/55/66\u0007\u001b]12;rgb:A/BC/def\u001b\\"); + process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007\u001b]10;rgb:1/2/3\n;?\u0007"); // Ghostty sets a colour beside a query, skips an LF, an empty field and a last index with no // colour in an OSC, and runs an OSC that CAN ends or that the next ESC cuts short. process.emitData("\u001b]4;1;red;2;?\u0007\u001b]0;t\u001b]\n4;1;?;;2;?;3\u0018\u001b]4;3;?"); @@ -1640,6 +1735,7 @@ it.layer( expect( reopened.history.startsWith( 'prompt \u001b[!p\u001b["p\u001b[4 q\u001b[u' + + "\u001b]11;rgb:44/55/66\u0007\u001b]12;rgb:A/BC/def\u001b\\" + "\u001b]4;1;red;2;?\u0007\u001b]0;t\u001b\\\u001b]4;3;?\u001b]0;x\u001b" + `\u001b[${"0".repeat(5000)}31mXdone\n`, ), @@ -1757,6 +1853,39 @@ it.layer( }), ); + it.effect("starts a snapshot inside the sequence the terminal has not finished", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const outputs = yield* Queue.unbounded(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" ? Queue.offer(outputs, undefined).pipe(Effect.asVoid) : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + const historyAfter = Effect.fnUntraced(function* (data: string) { + process.emitData(data); + yield* Queue.take(outputs); + return (yield* manager.open(openInput())).history; + }); + + expect(yield* historyAfter("A\u001b]0;ti")).toBe("A\u001b]0;ti"); + // A long string would push history out of the client's budget, so its payload is left out. + expect(yield* historyAfter("x".repeat(4_096))).toBe("A\u001b]"); + // Past the limit only the introducer is left to replay. + expect(yield* historyAfter("x".repeat(DEFAULT_MAX_TERMINAL_BUFFER_BYTES))).toBe( + "A\u001b\\\u001b]", + ); + expect(yield* historyAfter("\u0007B")).toBe("A\u001b\\B"); + + // Saved history has no live output to finish the sequence. + process.emitData("\u001b]0;open"); + yield* Queue.take(outputs); + yield* manager.close({ threadId: "thread-1" }); + expect(yield* readFileString(yield* historyLogPath(logsDir))).toBe("A\u001b\\B"); + }), + ); + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index e87ba67cf5837..968cbf4b3f78a 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -42,6 +42,7 @@ import { import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { AgentScope } from "@t3tools/shared/AgentScope"; +import { stripAppImageRuntimeEnv } from "@t3tools/shared/appImageRuntimeEnv"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution, mergePathEntries } from "@t3tools/shared/shell"; @@ -415,7 +416,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { worktreePath: session.worktreePath, status: session.status, pid: session.pid, - history: session.history.value(), + history: session.history.value() + unfinishedSequenceReplay(session), exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -918,11 +919,12 @@ const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnaps ProcessRunner.ProcessRunner > { const processRunner = yield* ProcessRunner.ProcessRunner; + const powershell = windowsPowerShellPath(yield* HostProcess.Environment); const command = '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }'; const result = yield* processRunner .run({ - command: "powershell.exe", + command: powershell, args: ["-NoProfile", "-NonInteractive", "-Command", command], timeout, maxOutputBytes: 262_144, @@ -1270,8 +1272,12 @@ function shouldStripDcsSequence(content: string): boolean { return /^[01]?[$+][qr]/.test(content); } +// Ghostty reports colours as `rgb:rrrr/gggg/bbbb`; a lone shorter `rgb:` value only sets one. +const LONE_SHORT_RGB_SETTER = + /^\d+;rgb:(?![\da-f]{4}\/[\da-f]{4}\/[\da-f]{4}$)[\da-f]{1,4}\/[\da-f]{1,4}\/[\da-f]{1,4}$/i; + function shouldStripOscSequence(content: string): boolean { - return /^(10|11|12);(?:\?|rgb:)/.test(content); + return /^(10|11|12);(?:\?|rgb:)/.test(content) && !LONE_SHORT_RGB_SETTER.test(content); } // An OSC 4 whose every colour is "?" reports palette entries and sets none. Ghostty skips C0 @@ -1394,7 +1400,32 @@ function findEscapeSequenceEndIndex(input: string, start: number): number | null const HISTORY_SEQUENCE_START = /\u001b/; const NEXT_HISTORY_SEQUENCE_START = new RegExp(HISTORY_SEQUENCE_START.source, "g"); -function sanitizeTerminalHistoryChunk( +// Clients keep this much output and drop a sequence their trim cuts through, so none of them +// could replay a longer string or CSI whole. +const MAX_HELD_SEQUENCE_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; +// ESC and four intermediates: libghostty ignores every intermediate past the fourth. +const MAX_HELD_ESCAPE_LENGTH = 5; +// Leads the held text of a string or CSI that outgrew its limit and stays out of history. Only its +// introducer is still held, with a final ESC or high surrogate that may begin its end. Other held +// text starts with ESC. +const OVERSIZED_SEQUENCE = "\u0018"; +// Stands in for the ESC of an oversized sequence, which ended any string history left open. +const STRING_TERMINATOR = "\u001b\\"; + +// Longer held text is cut to its introducer in a snapshot, so it cannot push history out of the +// client's budget or add its size to every resync. +const MAX_SNAPSHOT_SEQUENCE_LENGTH = 4_096; + +// History leaves out the sequence the terminal is still inside. A client that starts from a +// snapshot needs it, or it prints the rest of the sequence as text. +function unfinishedSequenceReplay(session: TerminalSessionState): string { + const held = session.pendingHistoryControlSequence; + if (held.startsWith(OVERSIZED_SEQUENCE)) return held.slice(1); + if (held.length <= MAX_SNAPSHOT_SEQUENCE_LENGTH) return held; + return held.slice(0, 2) + (/[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""); +} + +export function sanitizeTerminalHistoryChunk( pendingControlSequence: string, data: string, ): { visibleText: string; pendingControlSequence: string } { @@ -1402,9 +1433,12 @@ function sanitizeTerminalHistoryChunk( return { visibleText: data, pendingControlSequence: "" }; } - const input = `${pendingControlSequence}${data}`; - // Only the pending prefix's final ESC can begin a terminator split across chunks. - const pendingScanStart = Math.max(0, pendingControlSequence.length - 1); + const resumesOversized = pendingControlSequence.startsWith(OVERSIZED_SEQUENCE); + const held = resumesOversized ? pendingControlSequence.slice(1) : pendingControlSequence; + const input = `${held}${data}`; + // Only the held text's final code unit, an ESC or a high surrogate, can begin an end split + // across chunks. + const pendingScanStart = Math.max(0, held.length - 1); let visibleText = ""; let index = 0; // Set when a C1 code point began the sequence at `index`: the ESC form that stands in for it. @@ -1421,6 +1455,7 @@ function sanitizeTerminalHistoryChunk( // Empty for a sequence the input introduces itself, which starts with ESC at `index`. const prefix = c1Introducer; c1Introducer = ""; + const oversized = resumesOversized && index === 0; const contentStart = prefix.length > 0 ? index : index + 2; const nextCodePoint = (prefix || input).charCodeAt(prefix.length > 0 ? 1 : index + 1); if (Number.isNaN(nextCodePoint)) { @@ -1428,19 +1463,21 @@ function sanitizeTerminalHistoryChunk( } if (nextCodePoint === 0x5b) { - let cursor = contentStart; + // A held CSI has not ended, so only its last code unit is scanned again. + let cursor = index === 0 ? Math.max(contentStart, pendingScanStart) : contentStart; // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would // print in ground state. None join the parameters; only executed ones survive a strip. - let body = ""; - let executedControls = ""; + const executedControls = () => + input.slice(contentStart, cursor).replace(/[^\x00-\x0f]+/g, ""); while (cursor < input.length) { const cursorCodePoint = input.charCodeAt(cursor); const cancelled = isControlSequenceCancel(cursorCodePoint); if (cancelled || isCsiFinalByte(cursorCodePoint)) { - if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { + const body = input.slice(contentStart, cursor).replace(/[^\x20-\x7e]+/g, ""); + if (!oversized && (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? ""))) { append(prefix + input.slice(index, cursor + 1)); } else { - append(executedControls); + append(executedControls()); } index = cursor + 1; break; @@ -1452,10 +1489,10 @@ function sanitizeTerminalHistoryChunk( if (c1) { // The CSI ends here undispatched, so it is kept only when the terminal is back in // ground with nothing to answer. - if (c1.next.length === 0 && !c1.query) { + if (!oversized && c1.next.length === 0 && !c1.query) { append(prefix + input.slice(index, end)); } else { - append(executedControls + c1.safe); + append(executedControls() + c1.safe); } c1Introducer = c1.next; index = end; @@ -1466,19 +1503,24 @@ function sanitizeTerminalHistoryChunk( } // An ESC abandons the CSI and starts the next sequence, which may be stripped. if (cursorCodePoint === 0x1b) { - append(executedControls); + append(executedControls()); index = cursor; break; } - if (cursorCodePoint < 0x10) { - executedControls += input[cursor]; - } else if (cursorCodePoint >= 0x20 && cursorCodePoint !== 0x7f) { - body += input[cursor]; - } cursor += 1; } if (cursor >= input.length) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + // The terminal has run these controls already, so history takes them as they come. + append((oversized ? "" : STRING_TERMINATOR) + executedControls()); + const endStart = /[\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: `${OVERSIZED_SEQUENCE}\u001b[${endStart}`, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } continue; } @@ -1495,7 +1537,16 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5d, ); if (stringEnd === null) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + append(oversized ? "" : STRING_TERMINATOR); + const endStart = /[\u001b\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: OVERSIZED_SEQUENCE + unfinished.slice(0, 2) + endStart, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } const { end, c1 } = stringEnd; const content = stripStringTerminator( @@ -1505,6 +1556,7 @@ function sanitizeTerminalHistoryChunk( // has its own terminator. Without one, the query ends at the next ESC, which history may // strip, so ST would not replay the same and the query stays. if ( + !oversized && nextCodePoint === 0x5d && isOscPaletteQuery(content) && /[\x07\x18\x1a]$|\x1b\\$/.test(input.slice(index, end)) @@ -1514,6 +1566,7 @@ function sanitizeTerminalHistoryChunk( continue; } const strip = + oversized || (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { @@ -1532,7 +1585,10 @@ function sanitizeTerminalHistoryChunk( const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1); if (escapeSequenceEndIndex === null) { - return { visibleText, pendingControlSequence: input.slice(index) }; + return { + visibleText, + pendingControlSequence: input.slice(index, index + MAX_HELD_ESCAPE_LENGTH), + }; } // ESC Z (DECID) is the legacy primary device attributes query. if (nextCodePoint !== 0x5a) { @@ -1588,46 +1644,6 @@ function shouldExcludeTerminalEnvKey(key: string): boolean { return TERMINAL_ENV_BLOCKLIST.has(normalizedKey); } -const APPIMAGE_RUNTIME_ENV_KEYS = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"] as const; -const APPIMAGE_PATH_LIKE_ENV_KEYS = [ - "PATH", - "LD_LIBRARY_PATH", - "XDG_DATA_DIRS", - "GSETTINGS_SCHEMA_DIR", -] as const; - -function isPathSegmentUnderAppDir(segment: string, appDir: string): boolean { - return segment === appDir || segment.startsWith(`${appDir}/`); -} - -// AppImage mount paths would make PTY tools resolve against the mount instead of the user's system. -function stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { - if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env; - - const scrubbed: NodeJS.ProcessEnv = { ...env }; - for (const key of APPIMAGE_RUNTIME_ENV_KEYS) { - delete scrubbed[key]; - } - - const appDir = env.APPDIR?.replace(/\/+$/, ""); - if (appDir) { - for (const key of APPIMAGE_PATH_LIKE_ENV_KEYS) { - const value = scrubbed[key]; - if (value === undefined) continue; - const kept = value - .split(":") - .filter((segment) => segment.length > 0 && !isPathSegmentUnderAppDir(segment, appDir)); - if (kept.length > 0) { - scrubbed[key] = kept.join(":"); - } else { - delete scrubbed[key]; - } - } - } - - return scrubbed; -} - function createTerminalSpawnEnv( baseEnv: NodeJS.ProcessEnv, runtimeEnv: Record | null | undefined, diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 882469b57a5c0..9ef6c1e7a9324 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -25,6 +25,7 @@ import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as ServerConfig from "../config.ts"; import { gitCommandDuration, gitCommandsTotal } from "../observability/Metrics.ts"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; import type * as VcsDriver from "./VcsDriver.ts"; @@ -154,6 +155,33 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +// Forking the server for every git call stalls its event loop in proportion to its RSS. +it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs git from the process launcher instead of forking the server", + () => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const result = yield* driver.execute({ + operation: "GitVcsDriver.test.parentPid", + cwd: process.cwd(), + args: ["-c", "alias.parent-pid=!awk '{print $4}' /proc/$PPID/stat", "parent-pid"], + }); + + assert.match(result.stdout.trim(), /^[1-9]\d*$/); + assert.notStrictEqual(Number(result.stdout.trim()), process.pid); + }).pipe( + Effect.provide( + GitVcsDriver.layer.pipe( + Layer.provide(layerServerConfig), + Layer.provideMerge(VcsProcess.layer), + // The server's spawner stack, as server.ts builds it. + Layer.provide(ProcessLauncher.layerServer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + interface UntrackedBlobChange { readonly git: Effect.Success>["git"]; readonly write: ( @@ -341,6 +369,187 @@ it.effect.each(["interrupt", "timeout", "success"] as const)( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.each(["interrupt", "timeout"] as const)( + "checkpoint staging $0 removes the Git LFS temp files its clean filter wrote", + (stop) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const lfsTmp = path.join(cwd, ".git/lfs/tmp"); + yield* fs.makeDirectory(lfsTmp, { recursive: true }); + const otherOperation = path.join(lfsTmp, "owned-by-another-git-lfs"); + yield* fs.writeFileString(otherOperation, "another git-lfs process is hashing this"); + + const connected = Promise.withResolvers(); + const sockets = new Set(); + const server = yield* Effect.acquireRelease( + Effect.sync(() => + NodeNet.createServer((socket) => { + sockets.add(socket); + connected.resolve(); + }), + ), + (server) => + Effect.sync(() => { + for (const socket of sockets) socket.destroy(); + server.close(); + }), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }), + ); + const address = server.address(); + assert.isTrue(address !== null && typeof address !== "string"); + if (address === null || typeof address === "string") return; + // Like git-lfs clean: copy the content into /tmp while hashing, and only + // move or remove that copy once hashing finishes. A killed filter strands it. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, Buffer.alloc(1024 * 1024));", + `const s = require('node:net').connect(${address.port}, '127.0.0.1');`, + "s.resume(); process.stdin.resume();", + "s.on('close', () => process.exit(0));", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const fiber = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.promise(() => connected.promise); + const laterOperation = path.join(lfsTmp, "started-during-capture"); + yield* fs.writeFileString(laterOperation, "another git-lfs process started later"); + if (stop === "interrupt") yield* Fiber.interrupt(fiber); + else yield* TestClock.adjust("30 seconds"); + const result = yield* Fiber.await(fiber); + if (stop === "interrupt") + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + else assert.isTrue(Exit.isSuccess(result) && Exit.isFailure(result.value)); + + assert.sameMembers(yield* fs.readDirectory(lfsTmp), [ + "owned-by-another-git-lfs", + "started-during-capture", + ]); + assert.strictEqual( + yield* fs.readFileString(otherOperation), + "another git-lfs process is hashing this", + ); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint staging moves Git LFS objects its clean filter wrote into LFS storage", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // Like git-lfs clean: hash through /tmp, then move the copy into objects. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "const content = fs.readFileSync(0);", + "const oid = require('node:crypto').createHash('sha256').update(content).digest('hex');", + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "const dir = storage + '/objects/' + oid.slice(0, 2) + '/' + oid.slice(2, 4);", + "fs.mkdirSync(dir, { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, content);", + "fs.renameSync(storage + '/tmp/' + process.pid, dir + '/' + oid);", + "process.stdout.write('oid sha256:' + oid + '\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + const pointer = yield* git(["show", `${checkpointRef}:weights.npz`]); + const oid = pointer.stdout.trim().slice("oid sha256:".length); + assert.strictEqual( + yield* fs.readFileString( + path.join(cwd, ".git/lfs/objects", oid.slice(0, 2), oid.slice(2, 4), oid), + ), + "large untracked data\n", + ); + assert.isFalse(yield* fs.exists(path.join(cwd, ".git/lfs/tmp"))); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint capture fails instead of dropping Git LFS objects it cannot list", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // A file where git-lfs keeps its objects makes the store unreadable without being absent. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.readFileSync(0);", + "fs.mkdirSync(storage, { recursive: true });", + "fs.writeFileSync(storage + '/objects', 'not a directory');", + "process.stdout.write('pointer\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const result = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit); + + const error = Exit.isFailure(result) ? Cause.findErrorOption(result.cause) : Option.none(); + assert.isTrue( + Option.isSome(error) && + error.value._tag === "VcsCheckpointStorageError" && + error.value.stage === "publish", + ); + const ref = yield* driver.execute({ + operation: "checkpoint-test", + cwd, + args: ["rev-parse", "--verify", "--quiet", checkpointRef], + allowNonZeroExit: true, + }); + assert.strictEqual(ref.exitCode, 1); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect.each(["failure", "interrupt"] as const)( "checkpoint publication $0 preserves existing refs and permits retry", (stop) => @@ -2070,6 +2279,51 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "checkpoint capture keeps whitespace at the end of Git paths", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-edge-space-capture-", + }); + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const git = (cwd: string, args: ReadonlyArray) => + driver.execute({ + operation: "test", + cwd, + args: ["-c", "user.name=Test", "-c", "user.email=test@test.com", ...args], + }); + const library = path.join(parent, "library"); + yield* fileSystem.makeDirectory(library); + yield* git(library, ["init"]); + yield* git(library, ["commit", "--allow-empty", "-m", "initial"]); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/edge-space"); + // The newline name takes the per-path fallback; the other takes the one-spawn answer. + for (const name of ["repo ", "multi\nline "]) { + const cwd = path.join(parent, name); + yield* fileSystem.makeDirectory(cwd); + yield* git(cwd, ["init", `--separate-git-dir=${path.join(parent, `${name.trim()} git `)}`]); + yield* git(cwd, ["-c", "protocol.file.allow=always", "submodule", "add", library, "lib"]); + yield* git(cwd, ["commit", "-m", "initial"]); + yield* fileSystem.writeFileString(path.join(cwd, "dirty.txt"), "pending\n"); + yield* fileSystem.writeFileString(path.join(cwd, "lib", "dirty.txt"), "nested\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + assert.strictEqual( + (yield* git(cwd, ["show", `${checkpointRef}:dirty.txt`])).stdout, + "pending\n", + ); + assert.strictEqual( + (yield* git(path.join(cwd, "lib"), ["show", `${checkpointRef}:dirty.txt`])).stdout, + "nested\n", + ); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("restores empty checkpoints without changing paths outside the workspace", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -2407,6 +2661,28 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "GitVcsDriver keeps whitespace at the end of repository paths", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-edge-space-repo-" }); + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + // The newline name takes the per-path fallback; the others take the one-spawn answer. + for (const name of ["repo ", "repo\r", "multi\nline "]) { + const cwd = path.join(parent, name); + const gitDir = path.join(parent, `${name.replace("\n", "")} metadata\u00a0`); + yield* fileSystem.makeDirectory(cwd); + yield* runGit(cwd, ["init", `--separate-git-dir=${gitDir}`]); + + const repository = yield* driver.detectRepository(cwd); + assert.strictEqual(repository?.rootPath, yield* fileSystem.realPath(cwd)); + assert.strictEqual(repository?.metadataPath, yield* fileSystem.realPath(gitDir)); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "GitVcsDriver still fails detection when git exists but cannot be spawned", () => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 6e5105d9c1730..486a24a73dff2 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -762,7 +762,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( 16_384, ); if (stdout === null) return null; - const lines = stdout.replace(/\r?\n$/u, "").split(/\r?\n/u); + const lines = stdout.replace(/\n$/, "").split("\n"); if (lines[0]?.trim() !== "true") return null; // A newline inside a path breaks the line framing; ask for each path on its own. if (lines.length !== 3) { @@ -776,16 +776,16 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ]).pipe(Effect.orElseSucceed(() => null)); return { kind: "git" as const, - rootPath: root.stdout.trim(), - metadataPath: gitCommonDir?.stdout.trim() || null, + rootPath: root.stdout.replace(/\n$/, ""), + metadataPath: gitCommonDir?.stdout.replace(/\n$/, "") || null, freshness: yield* nowFreshness(), }; } return { kind: "git" as const, - rootPath: lines[1]!.trim(), - metadataPath: lines[2]!.trim() || null, + rootPath: lines[1]!, + metadataPath: lines[2] || null, freshness: yield* nowFreshness(), }; }); @@ -995,7 +995,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( cwd, args: ["rev-parse", "--git-common-dir"], }); - const gitCommonDir = result.stdout.trim(); + const gitCommonDir = result.stdout.replace(/\n$/, ""); if (path.isAbsolute(gitCommonDir)) return gitCommonDir; const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); return path.resolve(physicalCwd, gitCommonDir); @@ -1028,9 +1028,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const [gitCommonDir = "", indexPath = "", topLevel = "", prefix = "", head = ""] = lines; if (headChecked && lines.length === (headExists ? 6 : 5) && lines.at(-1) === "") { return { - gitCommonDir: gitCommonDir.trim(), - indexPath: indexPath.trim(), - topLevel: topLevel.trim(), + gitCommonDir, + indexPath, + topLevel, prefix, headExists, head: headExists ? head : undefined, @@ -1262,6 +1262,71 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ), ), ); + // git-lfs's clean filter copies each file into /tmp while hashing it and strands + // that copy when killed. Give it storage that is removed with the capture's private objects. + const privateLfs = path.join(privateObjects, "lfs"); + const publishLfsObjects = Effect.gen(function* () { + const source = path.join(privateLfs, "objects"); + const objects = (yield* fileSystem.readDirectory(source, { recursive: true }).pipe( + // Absent when no file went through the filter; any other failure must stop publication. + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + () => Effect.succeed([]), + ), + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ + operation, + cwd: input.cwd, + stage: "publish", + cause, + }), + ), + )).filter((entry) => /^[0-9a-f]{2}[\\/][0-9a-f]{2}[\\/][0-9a-f]{64}$/.test(entry)); + if (objects.length === 0) return; + const configured = yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--get", "lfs.storage"], + allowNonZeroExit: true, + }); + // git-lfs resolves a relative lfs.storage against the common Git directory. + const storage = path.resolve(gitCommonDir, configured.stdout.trim() || "lfs"); + yield* Effect.forEach( + objects, + (entry) => + Effect.gen(function* () { + const from = path.join(source, entry); + const to = path.join(storage, "objects", entry); + if (yield* fileSystem.exists(to)) return; + yield* fileSystem.makeDirectory(path.dirname(to), { recursive: true }); + // Identical oids are interchangeable, so losing a race to another writer is fine. + // lfs.storage may be on another volume, where only a copy can move the object. + const partial = `${to}.${indexId}`; + yield* fileSystem.rename(from, to).pipe( + Effect.catch((cause) => + Effect.flatMap(fileSystem.exists(to), (exists) => + exists + ? Effect.void + : fileSystem.copyFile(from, partial).pipe( + Effect.andThen(fileSystem.rename(partial, to)), + Effect.ensuring( + fileSystem.remove(partial, { force: true }).pipe(Effect.ignore), + ), + Effect.mapError(() => cause), + ), + ), + ), + ); + }), + { concurrency: 16, discard: true }, + ).pipe( + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ operation, cwd: input.cwd, stage: "publish", cause }), + ), + ); + }); const commitEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: tempIndexPath, GIT_OBJECT_DIRECTORY: privateObjects, @@ -1275,6 +1340,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", GIT_COMMITTER_NAME: "T3 Code", GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + // Any command on the scratch index can run the clean filter, not just add. + ...VcsProcess.gitConfigEnv(hostEnv, "lfs.storage", privateLfs, hostPlatform), }; const cleanupTempIndex = Effect.forEach( @@ -1794,6 +1861,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } + yield* publishLfsObjects; // Git writers have exited; bound publication by fanout directory. yield* fileSystem.readDirectory(privateObjects).pipe( Effect.flatMap((directories) => diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b3ad640db4c7a..1ae6c7dfb0883 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1014,6 +1014,203 @@ it.effect("resolves a branch's base once while its refs and branch config are un ).pipe(Effect.provide(layerTest)), ); +it.effect("keeps a branch's base cached while only other refs' commits move", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["remote", "add", "origin", cwd]); + yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "HEAD"]); + yield* git(cwd, ["update-ref", "refs/remotes/origin/develop", "HEAD"]); + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/origin/HEAD", + `refs/remotes/origin/${initialBranch}`, + ]); + const other = `${yield* makeTmpDir()}/other`; + yield* git(cwd, ["worktree", "add", "-b", "other", other]); + yield* git(cwd, ["checkout", "-b", "feature/x"]); + yield* git(cwd, ["pack-refs", "--all"]); + const lookups = () => { + const count = spawnedArgs.filter((args) => + args.includes("branch.feature/x.t3-merge-base-ref"), + ).length; + spawnedArgs.length = 0; + return count; + }; + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + + // Another worktree's commits and a fetch moving a packed base ref add or remove no name. + yield* git(other, ["commit", "--allow-empty", "-m", "other"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(spawnedArgs.length, 6); + assert.equal(lookups(), 0); + yield* git(other, ["commit", "--allow-empty", "-m", "other again"]); + yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "other"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + + yield* git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/develop"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + yield* git(cwd, ["branch", "master"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + // Deleting a packed ref rewrites packed-refs without touching a loose file. + yield* git(cwd, ["update-ref", "-d", "refs/remotes/origin/develop"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + yield* git(cwd, ["config", "branch.feature/x.t3-merge-base", "other"]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + }), + ).pipe(Effect.provide(layerTest)), +); + +it.effect("rereads the base after a nested remote's HEAD is retargeted", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["remote", "add", "team/origin", cwd]); + yield* git(cwd, ["update-ref", `refs/remotes/team/origin/${initialBranch}`, "HEAD"]); + yield* git(cwd, ["update-ref", "refs/remotes/team/origin/develop", "HEAD"]); + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/team/origin/HEAD", + `refs/remotes/team/origin/${initialBranch}`, + ]); + yield* git(cwd, ["checkout", "-b", "feature/x"]); + const lookups = () => { + const count = spawnedArgs.filter((args) => + args.includes("branch.feature/x.t3-merge-base-ref"), + ).length; + spawnedArgs.length = 0; + return count; + }; + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/team/origin/HEAD", + "refs/remotes/team/origin/develop", + ]); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + }), + ).pipe(Effect.provide(layerTest)), +); + +it.effect("keeps the base cached when a remote branch has a HEAD path component", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["remote", "add", "origin", cwd]); + yield* git(cwd, ["update-ref", `refs/remotes/origin/${initialBranch}`, "HEAD"]); + // A valid ref whose path has a directory named HEAD under refs/remotes. + yield* git(cwd, ["update-ref", "refs/remotes/origin/topic/HEAD/child", "HEAD"]); + yield* git(cwd, ["checkout", "-b", "feature/x"]); + const lookups = () => { + const count = spawnedArgs.filter((args) => + args.includes("branch.feature/x.t3-merge-base-ref"), + ).length; + spawnedArgs.length = 0; + return count; + }; + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 1); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + }), + ).pipe(Effect.provide(layerTest)), +); + +it.effect("keeps one cached base per branch however often its refs change", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let lookupCount = 0; + const spawner = ChildProcessSpawner.make((command) => { + if ( + ChildProcess.isStandardCommand(command) && + command.args.map(String).includes("branch.feature/x.t3-merge-base-ref") + ) { + lookupCount++; + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const other = `${yield* makeTmpDir()}/other`; + yield* git(cwd, ["worktree", "add", "-b", "other", other]); + yield* git(cwd, ["checkout", "-b", "feature/x"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "feature 1"]); + yield* git(cwd, ["branch", "develop"]); + const read = Effect.fnUntraced(function* () { + lookupCount = 0; + const status = yield* driver.statusDetailsLocal(cwd); + return { lookups: lookupCount, aheadCount: status.aheadCount }; + }); + const useBase = (base: string) => + git(cwd, ["config", "branch.feature/x.t3-merge-base", base]); + + yield* useBase(initialBranch); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: 1 }); + for (let round = 1; round <= 4; round++) { + // Commits here and in another worktree keep every ref name, so the base stays cached. + yield* git(cwd, ["commit", "--allow-empty", "-m", `feature ${round + 1}`]); + yield* git(other, ["commit", "--allow-empty", "-m", `other ${round}`]); + assert.deepStrictEqual(yield* read(), { lookups: 0, aheadCount: round + 1 }); + + yield* useBase("develop"); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: round }); + // Returning to an earlier stamp resolves again: the entry under it was overwritten, not kept. + yield* useBase(initialBranch); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: round + 1 }); + yield* git(cwd, ["branch", `scratch-${round}`]); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: round + 1 }); + yield* git(cwd, ["branch", "-D", `scratch-${round}`]); + assert.deepStrictEqual(yield* read(), { lookups: 1, aheadCount: round + 1 }); + } + }), + ).pipe(Effect.provide(layerTest)), +); + it.effect.each([ { kind: "working-tree", request: { sourceKind: "working-tree" } }, { kind: "commit", request: { sourceKind: "commit", commitSha: "HEAD" } }, @@ -4503,6 +4700,25 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "loads working-tree contents in a repository whose folder name ends in a space", + () => + Effect.gen(function* () { + const pathService = yield* Path.Path; + const cwd = pathService.join(yield* makeTmpDir(), "repo "); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* writeTextFile(cwd, "app/.keep", ""); + yield* writeTextFile(cwd, "README.md", "# changed\n"); + + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(pathService.join(cwd, "app")), + ); + + assert.strictEqual(contents.newContents, "# changed\n"); + }), + ); + it.effect.each([ { scenario: "kept", before: "\uFEFFold\n", after: "\uFEFFnew\n" }, { scenario: "added", before: "same\n", after: "\uFEFFsame\n" }, @@ -6053,7 +6269,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { { fetch: "statusDetailsRemote" }, // Storage cleanup's merge check fetches the default branch on every sweep. { fetch: "fetchRemoteTrackingBranch" }, - ] as const)("does not start Git auto-maintenance from background $fetch fetches", ({ fetch }) => + // Startup pulls each project's default branch. + { fetch: "pullCurrentBranch" }, + ] as const)("does not start Git auto-maintenance from $fetch", ({ fetch }) => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-vcs-driver-remote-"); @@ -6079,6 +6297,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const driver = yield* GitVcsDriver.GitVcsDriver; if (fetch === "statusDetailsRemote") yield* driver.statusDetailsRemote(cwd); + else if (fetch === "pullCurrentBranch") yield* driver.pullCurrentBranch(cwd); else yield* driver.fetchRemoteTrackingBranch({ cwd, @@ -6482,24 +6701,36 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("marks the origin default ref as default when no local copy exists", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "-u", "origin", initialBranch]); - yield* git(cwd, ["remote", "set-head", "origin", initialBranch]); - yield* git(cwd, ["checkout", "-b", "feature/only-local"]); - yield* git(cwd, ["branch", "-D", initialBranch]); - const driver = yield* GitVcsDriver.GitVcsDriver; + it.effect.each(["trunk", "feature/memo\u3000", "\u00a0release"])( + "marks the origin default ref %s as default when no local copy exists", + (defaultBranch) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", defaultBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", defaultBranch]); + yield* git(cwd, ["remote", "set-head", "origin", defaultBranch]); + const driver = yield* GitVcsDriver.GitVcsDriver; - const refs = yield* driver.listRefs({ cwd }); - const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`); - assert.equal(remoteDefault?.isRemote, true); - assert.equal(remoteDefault?.isDefault, true); - }), + const localStatus = yield* driver.statusDetails(cwd); + const remoteStatus = yield* driver.statusDetailsRemote(cwd); + for (const status of [localStatus, remoteStatus]) { + assert.equal(status.branch, defaultBranch); + assert.equal(status.upstreamRef, `origin/${defaultBranch}`); + assert.isTrue(status.isDefaultBranch); + } + + yield* git(cwd, ["checkout", "-b", "feature/only-local"]); + yield* git(cwd, ["branch", "-D", defaultBranch]); + + const refs = yield* driver.listRefs({ cwd }); + const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${defaultBranch}`); + assert.equal(remoteDefault?.isRemote, true); + assert.equal(remoteDefault?.isDefault, true); + }), ); it.effect("preserves exact custom names and refuses collisions without a suffix", () => @@ -7150,6 +7381,14 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["add", "."]); yield* git(cwd, ["commit", "-m", "more files"]); const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "fresh"); + // A refresh still inside the checkout's second finishes in the background. + const worktreesDir = path.join(cwd, ".git", "worktrees"); + yield* fs.makeDirectory(worktreesDir, { recursive: true }); + const indexChanges = yield* Queue.unbounded(); + yield* fs.watch(worktreesDir, { recursive: true }).pipe( + Stream.runForEach(() => Queue.offer(indexChanges, undefined)), + Effect.forkScoped, + ); // The refresh waits on the clock that stamps the files. yield* TestClock.withLive( @@ -7166,17 +7405,20 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { worktreePath, yield* git(worktreePath, ["rev-parse", "--git-path", "index"]), ); - const indexMtime = Option.getOrThrow((yield* fs.stat(indexPath)).mtime); - const indexSecond = Math.floor(indexMtime.getTime() / 1000); - const entrySeconds = Array.from( - (yield* git(worktreePath, ["ls-files", "--debug"])).matchAll(/^ {2}mtime: (\d+):/gm), - ([, seconds]) => Number(seconds), - ); - assert.equal(entrySeconds.length, 51); - assert.deepEqual( - entrySeconds.filter((seconds) => seconds >= indexSecond), - [], - ); + const racyEntries = Effect.gen(function* () { + const indexMtime = Option.getOrThrow((yield* fs.stat(indexPath)).mtime); + const indexSecond = Math.floor(indexMtime.getTime() / 1000); + const entrySeconds = Array.from( + (yield* git(worktreePath, ["ls-files", "--debug"])).matchAll(/^ {2}mtime: (\d+):/gm), + ([, seconds]) => Number(seconds), + ); + assert.equal(entrySeconds.length, 51); + return entrySeconds.filter((seconds) => seconds >= indexSecond); + }); + while ((yield* racyEntries).length > 0 || (yield* fs.exists(`${indexPath}.t3-refresh`))) { + yield* Queue.take(indexChanges); + } + assert.isFalse(yield* fs.exists(`${indexPath}.lock`)); }), ); it.effect("returns the worktree when its index refresh fails", () => @@ -7441,37 +7683,42 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect.each(["release/v2", "origin/release/v2", "refs/remotes/origin/release/v2"])( - "records a remote-only PR base when creating a worktree from %s", - (baseRef) => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const remote = yield* makeTmpDir("git-remote-"); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", "HEAD:refs/heads/release/v2"]); - const commit = yield* git(cwd, ["rev-parse", "origin/release/v2"]); - const path = yield* Path.Path; - const driver = yield* GitVcsDriver.GitVcsDriver; - const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); - yield* driver.createWorktree({ - cwd, - path: worktreePath, - refName: commit, - newRefName: "feature/remote", - baseRefName: baseRef, - }); + it.effect.each([ + "release/v2", + "origin/release/v2", + "refs/remotes/origin/release/v2", + "origin/release/v2\u3000", + ])("records a remote-only PR base when creating a worktree from %s", (baseRef) => + Effect.gen(function* () { + const branch = baseRef.replace(/^(refs\/remotes\/)?origin\//, ""); + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", `HEAD:refs/heads/${branch}`]); + const commit = yield* git(cwd, ["rev-parse", `origin/${branch}`]); + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: commit, + newRefName: "feature/remote", + baseRefName: baseRef, + }); - const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); - const comparisonBase = preview.sources.find( - (source) => source.kind === "branch-range", - )!.baseRef; - assert.equal( - yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), - commit, - ); - }), + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/remote.t3-merge-base"), + branch, + ); + const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); + const comparisonBase = preview.sources.find( + (source) => source.kind === "branch-range", + )!.baseRef; + assert.equal(yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), commit); + }), ); it("parses checkout progress lines from git's stderr", () => { diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 983006e8ff903..71c05547b9259 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -34,6 +34,7 @@ import { type ReviewDiffPreviewInput, type ReviewDiffFileStat, type ReviewDiffPreviewSource, + trimAsciiWhitespace, type VcsRef, } from "@t3tools/contracts"; import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; @@ -47,11 +48,7 @@ import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observabil import * as GitVcsDriver from "./GitVcsDriver.ts"; import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; -import { - explicitBareRepositoryEnv, - gitConfigEnv, - unsetInheritedRepositoryEnv, -} from "./VcsProcess.ts"; +import { gitConfigEnv, serverGitConfigEnv, unsetInheritedRepositoryEnv } from "./VcsProcess.ts"; import { makeWorktreeCheckoutSites } from "../fork/reflinkWorktrees/worktreeCheckoutSites.ts"; import { removeLinkedWorktree } from "./worktreeRemoval.ts"; import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; @@ -196,7 +193,6 @@ class BaseBranchCacheKey extends Data.Class<{ cwd: string; refName: string; allowRemoteOfCurrent: boolean; - inputsStamp: string; }> {} class GitRefsSnapshotCacheKey extends Data.Class<{ @@ -456,8 +452,8 @@ function parseUpstreamRefByFirstSeparator( return null; } - const remoteName = upstreamRef.slice(0, separatorIndex).trim(); - const branchName = upstreamRef.slice(separatorIndex + 1).trim(); + const remoteName = upstreamRef.slice(0, separatorIndex); + const branchName = upstreamRef.slice(separatorIndex + 1); if (remoteName.length === 0 || branchName.length === 0) { return null; } @@ -471,13 +467,13 @@ function parseUpstreamRefByFirstSeparator( function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null { for (const line of stdout.split("\n")) { - const trimmedLine = line.trim(); + const trimmedLine = trimAsciiWhitespace(line); if (trimmedLine.length === 0) { continue; } const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t"); - const branchName = branchNameRaw?.trim() ?? ""; - const candidateUpstreamRef = upstreamBranchRaw.trim(); + const branchName = branchNameRaw ?? ""; + const candidateUpstreamRef = upstreamBranchRaw; if (branchName.length === 0 || candidateUpstreamRef.length === 0) { continue; } @@ -494,7 +490,7 @@ function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null { if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) { return null; } - const localBranch = branchName.slice(separatorIndex + 1).trim(); + const localBranch = branchName.slice(separatorIndex + 1); return localBranch.length > 0 ? localBranch : null; } @@ -596,19 +592,19 @@ function classifyGitFailure(stderr: string): GitCommandFailureReason | null { // `--short` and `--abbrev-ref` print `heads/` when a tag shares the branch's name, so // branch reads take the full ref and strip the prefix themselves. function branchNameFromHeadRef(value: string): string | null { - const ref = value.trim(); + const ref = trimAsciiWhitespace(value); return ref.startsWith("refs/heads/") && ref.length > "refs/heads/".length ? ref.slice("refs/heads/".length) : null; } function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null { - const trimmed = value.trim(); + const trimmed = trimAsciiWhitespace(value); const prefix = `refs/remotes/${remoteName}/`; if (!trimmed.startsWith(prefix)) { return null; } - const refName = trimmed.slice(prefix.length).trim(); + const refName = trimmed.slice(prefix.length); return refName.length > 0 && refName !== "HEAD" ? refName : null; } @@ -1095,7 +1091,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ...input.env, ...trace2Monitor.env, }; - const env = { ...baseEnv, ...explicitBareRepositoryEnv(baseEnv, hostPlatform) }; + const env = { ...baseEnv, ...serverGitConfigEnv(baseEnv, hostPlatform) }; const spawnEnv = { ...env, ...windowsLongPathConfigEnv(hostPlatform, env) }; const resolved = yield* resolveSpawnCommand("git", [], { env: spawnEnv }); const spawnError = (cause: unknown) => @@ -1473,7 +1469,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"], true, - ).pipe(Effect.map((stdout) => stdout.trim().replace(/^refs\/(?:remotes|heads)\//, ""))); + ).pipe( + Effect.map((stdout) => trimAsciiWhitespace(stdout).replace(/^refs\/(?:remotes|heads)\//, "")), + ); if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { return null; @@ -1555,17 +1553,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) { const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; - // `--no-auto-gc` (a synonym of `--no-auto-maintenance` that older Git also knows) keeps - // this poll from starting `git gc --auto`. When that gc fails, for example on a repository - // with missing objects, Git retries it on every fetch and leaves a full-size `tmp_pack_*` - // behind each time, so a background poll could fill the disk. const fetchArgs = (mode: "--dry-run" | "--quiet") => [ "--git-dir", gitCommonDir, "fetch", mode, "--no-tags", - "--no-auto-gc", // FETCH_HEAD is written without a lock; overlapping a user's `git pull` makes that pull fail. "--no-write-fetch-head", "--", @@ -2062,7 +2055,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["symbolic-ref", "--quiet", "HEAD"], true, - ).pipe(Effect.map((stdout) => stdout.trim()))); + ).pipe(Effect.map(trimAsciiWhitespace))); if (headRef.length === 0) return undefined; const upstreamRemote = yield* executeGit( "GitVcsDriver.refreshStatusUpstreamIfStale.upstreamRemote", @@ -2071,7 +2064,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true }, ); if (upstreamRemote.exitCode !== 0) return undefined; - const remoteName = upstreamRemote.stdout.trim(); + const remoteName = trimAsciiWhitespace(upstreamRemote.stdout); // Empty means no upstream; `.` means the upstream is a local branch. if (remoteName.length === 0 || remoteName === ".") return remoteName; const gitCommonDir = yield* resolveGitCommonDir(cwd); @@ -2208,7 +2201,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", `branch.${refName}.pushRemote`], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); if (branchPushRemote.length > 0) { return branchPushRemote; } @@ -2218,7 +2211,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", "remote.pushDefault"], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); return pushDefaultRemote.length > 0 ? pushDefaultRemote : null; }); @@ -2357,7 +2350,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["rev-parse", "--symbolic-full-name", `${refName}@{upstream}`], { allowNonZeroExit: true }, ); - const comparisonRef = upstream.stdout.trim(); + const comparisonRef = trimAsciiWhitespace(upstream.stdout); if (upstream.exitCode !== 0 || !comparisonRef.startsWith("refs/remotes/")) return null; return { baseRef: comparisonRef.slice("refs/remotes/".length), comparisonRef }; }); @@ -2480,10 +2473,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return null; }); - // The effective config listing covers included, global, system and worktree config. Git writes - // packed-refs and each loose ref by rename, so their stats change whenever a ref could. Directory - // stats are left out: Git for Windows' no-op fetch touches refs/remotes/. - // Cost: one git process, a listing per refs directory and a stat per loose ref. + // Base selection reads config, which refs exist and each remote's HEAD target, never where a ref + // points, so commits and fetches keep the stamp. packed-refs names are re-read only when the file + // changes (repack, packed delete); a loose ref shadowing a packed one adds no name. Reftable keeps + // no names in files, so its table list's stat stands in for them. + const packedRefNames = new Map< + string, + { readonly token: string; readonly hash: string; readonly names: ReadonlySet } + >(); + const sha256Hex = (text: string) => + Effect.map(digest.digest(Digest.sha256, new TextEncoder().encode(text)), Hex.encode); const readBaseBranchInputsStamp = Effect.fn("GitVcsDriverCore.readBaseBranchInputsStamp")( function* (cwd: string, gitCommonDir: string) { const effectiveConfig = yield* executeGit( @@ -2493,9 +2492,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true }, ); if (effectiveConfig.exitCode !== 0 || effectiveConfig.stdoutTruncated) return null; - const configHash = Hex.encode( - yield* digest.digest(Digest.sha256, new TextEncoder().encode(effectiveConfig.stdout)), - ); const statToken = (target: string) => fileSystem.stat(target).pipe( Effect.map( @@ -2507,16 +2503,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed("-")), ); - const tokens = yield* Effect.forEach( - ["packed-refs", "reftable/tables.list"], - (name) => statToken(path.join(gitCommonDir, name)), + const packedRefsPath = path.join(gitCommonDir, "packed-refs"); + const [packedToken, reftableToken] = yield* Effect.all( + [statToken(packedRefsPath), statToken(path.join(gitCommonDir, "reftable", "tables.list"))], { concurrency: "unbounded" }, ); - const directories = [ - path.join(gitCommonDir, "refs", "heads"), - path.join(gitCommonDir, "refs", "remotes"), - ]; - const looseRefs: Array = []; + let packed = packedRefNames.get(gitCommonDir); + if (packed?.token !== packedToken) { + const contents = + packedToken === "-" + ? "" + : yield* fileSystem + .readFileString(packedRefsPath) + .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(""))); + const names = contents + .split("\n") + .map((line) => line.slice(line.indexOf(" ") + 1)) + .filter((name) => name.startsWith("refs/heads/") || name.startsWith("refs/remotes/")); + packed = { + token: packedToken, + hash: yield* sha256Hex(names.join("\0")), + names: new Set(names), + }; + packedRefNames.set(gitCommonDir, packed); + } + const remotesDirectory = path.join(gitCommonDir, "refs", "remotes"); + const directories = [path.join(gitCommonDir, "refs", "heads"), remotesDirectory]; + const looseNames: Array = []; + const remoteHeads: Array = []; for (let index = 0; index < directories.length; index++) { const directory = directories[index]!; const entries = yield* fileSystem @@ -2524,23 +2538,53 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed([]))); for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) { const entryPath = path.join(directory, entry.name); - if (entry.type === "Directory") directories.push(entryPath); - else looseRefs.push(entryPath); + if (entry.type === "Directory") { + directories.push(entryPath); + continue; + } + const name = path.relative(gitCommonDir, entryPath).split(path.sep).join("/"); + if (!packed.names.has(name)) looseNames.push(name); + // A remote name may contain "/", so its HEAD can sit deeper than refs/remotes/. + if (entry.name === "HEAD" && directory.startsWith(remotesDirectory + path.sep)) { + remoteHeads.push(entryPath); + } } } - tokens.push( - ...(yield* Effect.forEach( - looseRefs, - (ref) => Effect.map(statToken(ref), (token) => `${ref}=${token}`), - { concurrency: 16 }, - )), + const remoteHeadTargets = yield* Effect.forEach( + remoteHeads, + (head) => + fileSystem.readFileString(head).pipe( + Effect.map((target) => `${head}=${target}`), + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(`${head}=-`)), + ), + { concurrency: "unbounded" }, + ); + // Hashed: names alone reach ~1 MB in busy repositories, and keys behind a stale stamp + // linger in the cache until its capacity evicts them. + return yield* sha256Hex( + [ + effectiveConfig.stdout, + packed.hash, + reftableToken, + ...looseNames, + ...remoteHeadTargets, + ].join("\0"), ); - tokens.push(configHash); - return tokens.join("\0"); }, ); + const readCurrentBaseBranchInputsStamp = Effect.fnUntraced(function* (cwd: string) { + const gitCommonDir = (yield* resolveRepositoryPaths(cwd).pipe(Effect.orElseSucceed(() => null))) + ?.gitCommonDir; + if (gitCommonDir === undefined) return null; + return yield* readBaseBranchInputsStamp(cwd, gitCommonDir).pipe( + Effect.orElseSucceed(() => null), + ); + }); + // The stamp lives in the value, not the key: a key per stamp would leave every superseded + // stamp's entry behind until capacity evicts it, since TTL only expires a key that is read again. const baseBranchCache = yield* Cache.makeWith( Effect.fnUntraced(function* (key: BaseBranchCacheKey) { + const inputsStamp = yield* readCurrentBaseBranchInputsStamp(key.cwd); const trace = { dependsOnRemoteOfCurrent: false, degraded: false }; const base = yield* findBaseBranchForNoUpstream( key.cwd, @@ -2548,7 +2592,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowRemoteOfCurrent: key.allowRemoteOfCurrent }, trace, ); - return { base, ...trace }; + return { base, inputsStamp, ...trace }; }), { capacity: 2_048, @@ -2564,28 +2608,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* refName: string, options?: { readonly allowRemoteOfCurrent?: boolean }, ) { - const gitCommonDir = (yield* resolveRepositoryPaths(cwd).pipe( - Effect.orElseSucceed(() => null), - ))?.gitCommonDir; - const inputsStamp = - gitCommonDir === undefined - ? null - : yield* readBaseBranchInputsStamp(cwd, gitCommonDir).pipe( - Effect.orElseSucceed(() => null), - ); - if (inputsStamp === null) { - return yield* findBaseBranchForNoUpstream(cwd, refName, options); - } - const key = { - cwd: normalizeRepositoryPathsCacheKey(cwd), - refName, - inputsStamp, - }; + const key = { cwd: normalizeRepositoryPathsCacheKey(cwd), refName }; const allowRemoteOfCurrent = options?.allowRemoteOfCurrent === true; const cacheKey = new BaseBranchCacheKey({ ...key, allowRemoteOfCurrent }); + const cached = yield* Cache.getOption(baseBranchCache, cacheKey); + if (Option.isSome(cached)) { + const inputsStamp = yield* readCurrentBaseBranchInputsStamp(cwd); + if (inputsStamp !== null && inputsStamp === cached.value.inputsStamp) { + return cached.value.base; + } + yield* Cache.invalidate(baseBranchCache, cacheKey); + } const entry = yield* Cache.get(baseBranchCache, cacheKey); // A fallback forced by a failed remote lookup must not outlive the failure. - if (entry.degraded) { + if (entry.degraded || entry.inputsStamp === null) { yield* Cache.invalidate(baseBranchCache, cacheKey); } else if (!entry.dependsOnRemoteOfCurrent) { yield* Cache.set( @@ -2671,7 +2707,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* headRef = ""; } else { branch = branchNameFromHeadRef(branchResult.stdout); - headRef = branchResult.stdout.trim(); + headRef = trimAsciiWhitespace(branchResult.stdout); } let upstreamRemoteName: string | undefined; if (refreshUpstream) { @@ -2951,13 +2987,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* continue; } if (line.startsWith("# branch.head ")) { - const value = line.slice("# branch.head ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.head ".length)); // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`. refName = value === "(detached)" || value === "(unknown)" ? null : value; continue; } if (line.startsWith("# branch.upstream ")) { - const value = line.slice("# branch.upstream ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.upstream ".length)); upstreamRef = value.length > 0 ? value : null; continue; } @@ -4037,7 +4073,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get-all", `branch.${refName}.merge`], true, - ).pipe(Effect.map((stdout) => stdout.trim().split("\n").filter(Boolean))), + ).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout).split("\n").filter(Boolean))), runGitStdout( "GitVcsDriver.pullCurrentBranch.currentBranch", cwd, @@ -5191,7 +5227,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "GitVcsDriver.getReviewDiffFileContents.repositoryRoot", input.cwd, ["rev-parse", "--show-toplevel"], - ).pipe(Effect.map((value) => value.trim())); + ).pipe(Effect.map((value) => value.replace(/\n$/, ""))); if (repositoryRoot.length === 0) { return yield* reviewDiffFileError(input, "Could not resolve the Git repository root."); } @@ -5239,7 +5275,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readConfigValue: GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"] = (cwd, key) => runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe( - Effect.map((stdout) => stdout.trim()), + Effect.map(trimAsciiWhitespace), Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); @@ -5285,7 +5321,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* input.cwd, ["rev-parse", "--symbolic-full-name", startPoint], { allowNonZeroExit: true }, - ).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : ""))); + ).pipe( + Effect.map((result) => (result.exitCode === 0 ? trimAsciiWhitespace(result.stdout) : "")), + ); if (!startRef.startsWith("refs/remotes/")) return; yield* executeGitWithStableDiagnostics( `${operation}.track`, @@ -5332,7 +5370,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? { baseRef: `refs/remotes/${remoteName}/${refName}`, branchName: refName } : null; } - const ref = result.stdout.trim(); + const ref = trimAsciiWhitespace(result.stdout); if (ref.startsWith("refs/heads/")) { const branchName = ref.slice("refs/heads/".length); return { baseRef: ref, branchName }; @@ -5768,14 +5806,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); // Older Git (such as 2.30) skips the write when racy entries merely check out clean. // A refresh re-reads every checked-out file, so allow five minutes outside shared permits. - const refresh = runGit( - "GitVcsDriver.createWorktree.refreshIndex", - worktreePath, - ["update-index", "-q", "--refresh", "--force-write-index"], - { timeoutMs: WORKTREE_INDEX_REFRESH_TIMEOUT_MS }, - ); + const refresh = (env?: NodeJS.ProcessEnv) => + runGit( + "GitVcsDriver.createWorktree.refreshIndex", + worktreePath, + ["update-index", "-q", "--refresh", "--force-write-index"], + { timeoutMs: WORKTREE_INDEX_REFRESH_TIMEOUT_MS, env }, + ); const checkoutSecond = yield* indexSecond; - yield* refresh; + yield* refresh(); const refreshedSecond = yield* indexSecond; if ( Option.isNone(checkoutSecond) || @@ -5788,10 +5827,44 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // second out (file timestamps can trail the clock by a kernel tick) and refresh again. Two // seconds or more means this clock does not match the file timestamps, as on a share stamped // by another machine, so it cannot say when that second ends. - const delay = (checkoutSecond.value + 1) * 1000 + 50 - (yield* Clock.currentTimeMillis); + const checkoutTime = checkoutSecond.value; + const delay = (checkoutTime + 1) * 1000 + 50 - (yield* Clock.currentTimeMillis); if (delay >= 2_000) return; - if (delay > 0) yield* Effect.sleep(Duration.millis(delay)); - yield* refresh; + if (delay <= 0) return yield* refresh(); + // Waiting here would hold up the thread's agent, and refreshing in place later would hold the + // index lock while its setup script and agent run Git. So refresh a copy in the background and + // take the lock only to swap it in, unless Git holds it or the index changed since the copy. + const copyPath = `${indexPath}.t3-refresh`; + const lockPath = `${indexPath}.lock`; + const stamp = (info: FileSystem.File.Info) => + `${info.size}:${Option.getOrUndefined(info.ino)}:${Option.getOrUndefined(info.mtime)?.getTime()}`; + yield* Effect.gen(function* () { + yield* Effect.sleep(Duration.millis(delay)); + const copied = stamp(yield* fileSystem.stat(indexPath)); + yield* fileSystem.copyFile(indexPath, copyPath); + // Keep the checkout's timestamp so this refresh still re-reads the files stamped in it. + yield* fileSystem.utimes(copyPath, checkoutTime, checkoutTime); + yield* refresh({ GIT_INDEX_FILE: copyPath }); + yield* Effect.uninterruptible( + // link fails when the lock exists; once it is ours, release it on any failure. + fileSystem.link(copyPath, lockPath).pipe( + Effect.andThen( + fileSystem.stat(indexPath).pipe( + Effect.flatMap((current) => + stamp(current) === copied + ? fileSystem.rename(lockPath, indexPath) + : fileSystem.remove(lockPath), + ), + Effect.tapError(() => fileSystem.remove(lockPath).pipe(Effect.ignore)), + ), + ), + ), + ); + }).pipe( + Effect.ensuring(fileSystem.remove(copyPath).pipe(Effect.ignore)), + Effect.ignore({ log: "Debug" }), + Effect.forkIn(serviceScope), + ); }); // Git writes the lock reason during registration, before checkout or user hooks can run. @@ -6531,13 +6604,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fetchRemoteTrackingBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteTrackingBranch"] = Effect.fn("fetchRemoteTrackingBranch")(function* (input) { - // Storage cleanup runs this every sweep: like the status fetch, a killed fetch strands a - // `tmp_pack_*` and a failing `gc --auto` repeats each time, so allow time and skip gc. + // Storage cleanup runs this every sweep, and a killed fetch strands a `tmp_pack_*`. const args = [ "fetch", "--quiet", "--no-tags", - "--no-auto-gc", "--", input.remoteName, `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, @@ -6908,7 +6979,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, [ "branch", "--show-current", - ]).pipe(Effect.map((stdout) => stdout.trim() || null)); + ]).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout) || null)); return { refName }; }, @@ -6948,7 +7019,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((stdout) => { const branchNames: Array = []; for (const line of stdout.split("\n")) { - const branchName = line.trim(); + const branchName = trimAsciiWhitespace(line); if (branchName.length > 0) { branchNames.push(branchName); } diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts index 91e21e8f07a97..28b46c8c5482a 100644 --- a/apps/server/src/vcs/VcsProcess.ts +++ b/apps/server/src/vcs/VcsProcess.ts @@ -140,6 +140,22 @@ export const gitConfigEnv = ( export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => gitConfigEnv(env, "safe.bareRepository", "explicit", platform); +// A failing `gc --auto` (say, missing objects) reruns after every fetch and strands a full-size +// `tmp_pack_*` each time, so T3's frequent background Git calls could fill the disk. +const SERVER_GIT_CONFIG = [ + ["safe.bareRepository", "explicit"], + ["maintenance.auto", "false"], + ["gc.auto", "0"], +] as const; + +export const serverGitConfigEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => { + const added: NodeJS.ProcessEnv = {}; + for (const [key, value] of SERVER_GIT_CONFIG) { + Object.assign(added, gitConfigEnv({ ...env, ...added }, key, value, platform)); + } + return added; +}; + const REPOSITORY_SELECTORS = new Set([ "GIT_DIR", "GIT_WORK_TREE", @@ -248,7 +264,7 @@ export const make = Effect.gen(function* () { // LANGUAGE leaves LC_CTYPE, which hooks inherit, alone. ...(input.command === "git" ? { LANGUAGE: "C" } : {}), ...input.env, - ...explicitBareRepositoryEnv({ ...process.env, ...input.env }, hostPlatform), + ...serverGitConfigEnv({ ...process.env, ...input.env }, hostPlatform), }, timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 455dadc1766ba..54c9330a099f2 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -89,7 +89,7 @@ function layerTestFor(state: { beforeLocalStatus?: Effect.Effect; beforeCurrentBranch?: Effect.Effect; beforeInvalidate?: Effect.Effect; - branchRead?: () => Effect.Effect; + branchRead?: () => Effect.Effect; fileSystem?: FileSystem.FileSystem; pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"]; headPath?: string; @@ -2091,10 +2091,15 @@ describe("VcsStatusBroadcaster", () => { state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName: "repro" }; yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); yield* Deferred.await(failed); - const failedCalls = state.localStatusCalls; // Removing index.lock moves no HEAD, and no remote poll runs for this subscriber. state.failLocalStatus = false; + // A subscriber joining before the retry must not get the cached pre-checkout branch. + const joined = yield* broadcaster + .streamStatus({ cwd: "/repo", includeRemote: false }) + .pipe(Stream.take(1), Stream.runCollect); + assert.strictEqual(joined[0]?._tag === "snapshot" && joined[0].local.refName, "repro"); + const failedCalls = state.localStatusCalls; yield* TestClock.adjust(Duration.seconds(30)); yield* Deferred.await(checkedOut); assert.strictEqual(state.localStatusCalls, failedCalls + 1); @@ -2102,22 +2107,183 @@ describe("VcsStatusBroadcaster", () => { }), ); - it.effect("subscribers share one HEAD watch that ends with the last of them", () => + it.effect("a branch read that a checkout overtakes does not confirm the old branch", () => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const failures = yield* Queue.unbounded(); + const readStarted = yield* Deferred.make(); + const releaseRead = yield* Deferred.make(); + let gateNextRead = false; + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" }, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath: "/repo/.git/HEAD", + fileSystem: FileSystem.makeNoop({ + realPath: (target) => Effect.succeed(target), + exists: () => Effect.succeed(true), + watch: (_target, options) => + Stream.fromQueue(events).pipe(Stream.onStart(Effect.sync(() => options?.onReady?.()))), + }), + failLocalStatus: false, + onLocalStatusFailure: Queue.offer(failures, undefined).pipe(Effect.asVoid), + branchRead: () => { + const refName = state.currentLocalStatus.refName; + if (!gateNextRead) return Effect.succeed(refName); + gateNextRead = false; + return Deferred.succeed(readStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRead)), + Effect.as(refName), + ); + }, + }; + const snapshotBranch = (broadcaster: VcsStatusBroadcaster.VcsStatusBroadcaster["Service"]) => + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe( + Stream.take(1), + Stream.runCollect, + Effect.map(([event]) => (event?._tag === "snapshot" ? event.local.refName : null)), + ); + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const subscribed = yield* Deferred.make(); + yield* Stream.runForEach( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + () => Deferred.succeed(subscribed, undefined), + ).pipe(Effect.forkScoped); + yield* Deferred.await(subscribed); + const sawRepro = yield* Deferred.make(); + yield* broadcaster.streamBranchChanges.pipe( + Stream.runForEach((change) => + change.refName === "repro" ? Deferred.succeed(sawRepro, undefined) : Effect.void, + ), + Effect.forkScoped({ startImmediately: true }), + ); + + // index.lock is held, so every reconcile read fails and the cache keeps "main". + state.failLocalStatus = true; + yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); + yield* Queue.take(failures); + + // A joining subscriber's branch read starts on "main"; the checkout lands before it ends. + gateNextRead = true; + const overtaken = yield* snapshotBranch(broadcaster).pipe(Effect.forkScoped); + yield* Deferred.await(readStarted); + state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName: "repro" }; + yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); + yield* Deferred.await(sawRepro); + yield* Deferred.succeed(releaseRead, undefined); + yield* Fiber.join(overtaken); + + // The reconcile retry is still backing off, so only a fresh branch check finds "repro". + state.failLocalStatus = false; + assert.strictEqual(yield* snapshotBranch(broadcaster), "repro"); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }), + ); + + it.effect("a HEAD change while a checkout publish backs off unconfirms the branch", () => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const pulls = yield* Queue.unbounded(); + const failedRead = yield* Deferred.make(); + let failBranchRead = false; + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" }, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath: "/repo/.git/HEAD", + fileSystem: FileSystem.makeNoop({ + realPath: (target) => Effect.succeed(target), + exists: () => Effect.succeed(true), + // One event per pull: the next pull starts only after the last event passed the + // invalidation and reached the first buffer. + watch: (_target, options) => + Stream.fromEffectRepeat( + Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))), + ).pipe(Stream.onStart(Effect.sync(() => options?.onReady?.()))), + }), + branchRead: () => + failBranchRead + ? Deferred.succeed(failedRead, undefined).pipe( + Effect.andThen( + Effect.fail( + new GitCommandError({ + operation: "VcsStatusBroadcaster.test", + command: "git symbolic-ref", + cwd: "/repo", + detail: "HEAD is being rewritten", + }), + ), + ), + ) + : Effect.sync(() => state.currentLocalStatus.refName), + }; + const snapshotBranch = (broadcaster: VcsStatusBroadcaster.VcsStatusBroadcaster["Service"]) => + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe( + Stream.take(1), + Stream.runCollect, + Effect.map(([event]) => (event?._tag === "snapshot" ? event.local.refName : null)), + ); + const checkout = (refName: string) => + Effect.gen(function* () { + state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName }; + yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); + yield* Queue.take(pulls); + }); + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const subscribed = yield* Deferred.make(); + yield* Stream.runForEach( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + () => Deferred.succeed(subscribed, undefined), + ).pipe(Effect.forkScoped); + yield* Deferred.await(subscribed); + yield* Queue.take(pulls); + + // The checkout's own HEAD read fails, so its publish backs off on the test clock. + failBranchRead = true; + yield* checkout("one"); + yield* Deferred.await(failedRead); + failBranchRead = false; + assert.strictEqual(yield* snapshotBranch(broadcaster), "one"); + + // The next checkout waits behind that retry, yet a joining subscriber must not get "one". + yield* checkout("two"); + assert.strictEqual(yield* snapshotBranch(broadcaster), "two"); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }), + ); + + it.effect("subscribers share one HEAD watch and branch check until the last leaves", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" }); const headPath = path.join(gitDir, "HEAD"); yield* fs.writeFileString(headPath, "ref: refs/heads/main\n"); - const state = { + let branchReads = 0; + const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus as VcsStatusRemoteResult | null, + currentRemoteStatus: baseRemoteStatus, localStatusCalls: 0, remoteStatusCalls: 0, localInvalidationCalls: 0, remoteInvalidationCalls: 0, headPath, headPathCalls: 0, + branchRead: () => + Effect.sync(() => { + branchReads += 1; + return baseLocalStatus.refName; + }), }; yield* Effect.gen(function* () { @@ -2135,11 +2301,15 @@ describe("VcsStatusBroadcaster", () => { const first = yield* subscribe; const second = yield* subscribe; assert.strictEqual(state.headPathCalls, 1); + // The live watch reports any checkout, so the cached branch needs no re-check. + assert.strictEqual(branchReads, 0); yield* Fiber.interrupt(first); yield* Fiber.interrupt(second); yield* subscribe; + yield* subscribe; assert.strictEqual(state.headPathCalls, 2); + assert.strictEqual(branchReads, 1); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index d1e9a9c5496c6..4de51428a132f 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -481,18 +481,46 @@ export const make = Effect.gen(function* () { return yield* updateCachedLocalStatus(cwd, yield* readLocalStatus(cwd), observation, options); }); + // A branch read while a HEAD watch was ready stays current for that watch's lifetime: any + // checkout after it reaches the cache through the watch. A reconnect burst then forks git once. + const branchConfirmedUnder = new Map>(); + // Bumped on every HEAD event, so a read that a checkout overtook cannot confirm its branch. + const headGenerations = new Map(); + const readyHeadWatch = (cwd: string) => + SynchronizedRef.get(headWatchersRef).pipe( + Effect.map((watchers) => { + const watcher = watchers.get(cwd); + return watcher && + watcher.fiber.pollUnsafe() === undefined && + Deferred.isDoneUnsafe(watcher.ready) + ? watcher.fiber + : undefined; + }), + ); + const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")( function* (cwd: string) { + const watch = yield* readyHeadWatch(cwd); + const generation = headGenerations.get(cwd); + const confirm =
(value: A) => { + if (watch !== undefined && headGenerations.get(cwd) === generation) { + branchConfirmedUnder.set(cwd, watch); + } + return value; + }; const cached = yield* getCachedStatus(cwd); if (cached?.local) { if (cached.local.includesBranchChanges || !wantsBranchChanges(cwd)) { + if (watch !== undefined && branchConfirmedUnder.get(cwd) === watch) { + return cached.local.value; + } const branch = yield* workflow.currentBranch(cwd); - if (branch === cached.local.value.refName) return cached.local.value; + if (branch === cached.local.value.refName) return confirm(cached.local.value); } yield* workflow.invalidateLocalStatus(cwd); - return yield* loadLocalStatus(cwd, { publish: true }); + return confirm(yield* loadLocalStatus(cwd, { publish: true })); } - return yield* loadLocalStatus(cwd); + return confirm(yield* loadLocalStatus(cwd)); }, ); @@ -1121,6 +1149,13 @@ export const make = Effect.gen(function* () { : Effect.succeed(false), ), Stream.filter((event) => path.basename(event.path) === "HEAD"), + // On arrival: the cache keeps the old branch until reads below land, and they can retry. + Stream.tap(() => + Effect.sync(() => { + branchConfirmedUnder.delete(cwd); + headGenerations.set(cwd, (headGenerations.get(cwd) ?? 0) + 1); + }), + ), // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh. Stream.buffer({ capacity: 1, strategy: "sliding" }), Stream.mapEffect(() => retryCheckedOutRef(cwd, publishCheckedOutRef(cwd))), @@ -1179,6 +1214,9 @@ export const make = Effect.gen(function* () { return [null, nextWatchers] as const; } nextWatchers.delete(cwd); + // In this step, so a watch that registers next for cwd cannot lose its generation. + if (branchConfirmedUnder.get(cwd) === existing.fiber) branchConfirmedUnder.delete(cwd); + headGenerations.delete(cwd); return [existing.fiber, nextWatchers] as const; }); if (watcherToInterrupt) { diff --git a/apps/server/src/watchDirectoryReplacements.test.ts b/apps/server/src/watchDirectoryReplacements.test.ts new file mode 100644 index 0000000000000..09c5c2522b34e --- /dev/null +++ b/apps/server/src/watchDirectoryReplacements.test.ts @@ -0,0 +1,105 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; + +import { watchDirectoryPath } from "./watchDirectoryReplacements.ts"; + +it.live.skipIf(!symlinksSupported)( + "backs off stopped watches for an unchanged linked directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const base = yield* fs.makeTempDirectoryScoped(); + const entry = path.join(base, "linked"); + const first = path.join(base, "first", "themes"); + const second = path.join(base, "second", "themes"); + yield* fs.makeDirectory(first, { recursive: true }); + yield* fs.makeDirectory(second, { recursive: true }); + yield* fs.symlink(first, entry); + const firstIdentity = yield* fs.stat(first); + const secondIdentity = yield* fs.stat(second); + let identity = firstIdentity; + const events = yield* Queue.unbounded<"probe" | "refresh">(); + + // An ended child emits a final refresh, as it does when registration fails. + yield* watchDirectoryPath(entry, Stream.succeed(undefined), Effect.succeed(false)).pipe( + Stream.runForEach(() => Queue.offer(events, "refresh")), + Effect.provideService( + FileSystem.FileSystem, + FileSystem.FileSystem.of({ + ...fs, + stat: (file) => + file === entry + ? Queue.offer(events, "probe").pipe(Effect.map(() => identity)) + : fs.stat(file), + }), + ), + Effect.forkScoped, + ); + assert.deepEqual( + yield* Queue.takeN(events, 10), + // Each acquire stats too: the first, a retry after 1 tick, then after 2 more. + [ + "probe", + "probe", + "refresh", + "probe", + "probe", + "refresh", + "probe", + "probe", + "probe", + "refresh", + ], + ); + + identity = secondIdentity; + assert.deepEqual(yield* Queue.takeN(events, 3), ["probe", "probe", "refresh"]); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.live.skipIf(!symlinksSupported)( + "rebuilds when a probe sees a tree other than the one the watches were acquired on", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const base = yield* fs.makeTempDirectoryScoped(); + const entry = path.join(base, "linked"); + const first = path.join(base, "first"); + const second = path.join(base, "second"); + yield* fs.makeDirectory(first); + yield* fs.makeDirectory(second); + yield* fs.symlink(first, entry); + const a = yield* fs.stat(first); + const b = yield* fs.stat(second); + // Probe A, acquire A, probe B, swap back and acquire A, then B returns for the next probe. + const identities = [a, a, b, a, b, b]; + const refreshes = yield* Queue.unbounded(); + + yield* watchDirectoryPath( + entry, + Stream.concat(Stream.succeed(undefined), Stream.never), + Effect.succeed(false), + ).pipe( + Stream.runForEach(() => Queue.offer(refreshes, undefined)), + Effect.provideService( + FileSystem.FileSystem, + FileSystem.FileSystem.of({ + ...fs, + stat: (file) => + file === entry ? Effect.sync(() => identities.shift() ?? b) : fs.stat(file), + }), + ), + Effect.forkScoped, + ); + yield* Queue.takeN(refreshes, 3); + assert.deepEqual(identities, []); + }).pipe(Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/watchDirectoryReplacements.ts b/apps/server/src/watchDirectoryReplacements.ts index ca2d9c88941d7..315069ec5e72c 100644 --- a/apps/server/src/watchDirectoryReplacements.ts +++ b/apps/server/src/watchDirectoryReplacements.ts @@ -77,43 +77,116 @@ const realPath = (entry: string) => }); }); -const resolveWatchTarget = Effect.fn("watchDirectoryReplacements.resolveWatchTarget")(function* ( +const resolveLinkedPath = Effect.fn("watchDirectoryReplacements.resolveLinkedPath")(function* ( entry: string, + link: string, ) { - const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const link = yield* fs.readLink(entry).pipe(Effect.option); - if (Option.isNone(link)) return entry; - const resolved = yield* realPath(entry).pipe(Effect.option); if (Option.isSome(resolved)) return resolved.value; // A dangling link needs a watch on the directory where its target should appear. - const rawTarget = path.isAbsolute(link.value) - ? link.value - : `${path.dirname(entry)}${path.sep}${link.value}`; + const rawTarget = path.isAbsolute(link) ? link : `${path.dirname(entry)}${path.sep}${link}`; const parent = yield* realPath(path.dirname(rawTarget)).pipe(Effect.option); - const unresolved = Option.isSome(parent) - ? path.join(parent.value, path.basename(rawTarget)) - : entry; + if (Option.isNone(parent)) return entry; + + const unresolved = path.join(parent.value, path.basename(rawTarget)); return yield* resolveSymlinkTarget(unresolved).pipe(Effect.orElseSucceed(() => unresolved)); }); -/** Watch replacements of a configured directory, its symlink target, and the target's parent. */ -export const watchDirectoryPath = (directory: string, watchChild: Stream.Stream) => { +/** Watch replacements of a configured directory and nearby ancestors of its symlink target. */ +export const watchDirectoryPath = ( + directory: string, + watchChild: Stream.Stream, + consumeMissingObservation: Effect.Effect, +) => { const entry = NodePath.resolve(directory); return watchDirectoryReplacements( (ready) => watchDirectoryEntry(entry, ready), Stream.unwrap( - resolveWatchTarget(entry).pipe( - Effect.map((target) => { - if (target === entry) return watchChild; - return watchDirectoryReplacements( - (ready) => watchDirectoryEntry(NodePath.dirname(target), ready), - watchDirectoryReplacements((ready) => watchDirectoryEntry(target, ready), watchChild), + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const link = yield* fs.readLink(entry).pipe(Effect.option); + if (Option.isNone(link)) return watchChild; + + let childEnded = false; + const watchContents = Stream.suspend(() => { + childEnded = false; + return watchChild.pipe( + Stream.onEnd( + Effect.sync(() => { + childEnded = true; + }), + ), ); - }), - ), + }); + + // One stat per second for linked paths catches ancestor replacements the watches cannot see. + const identity = fs.stat(entry).pipe( + Effect.map( + (info) => + `${info.dev}:${info.ino.valueOrUndefined}:${info.birthtime.valueOrUndefined?.getTime()}`, + ), + Effect.orElseSucceed(() => null), + ); + // The identity of the tree the current watches were acquired on. + let previous: string | null | undefined; + return watchDirectoryReplacements( + (ready) => { + let retryDelay = 1; + let nextRetry = 0; + return Stream.tick("1 second").pipe( + Stream.mapEffect(() => identity), + Stream.zipWithIndex, + Stream.mapEffect(([current, tick]) => + Effect.gen(function* () { + // A catalog read can see the path missing even if both probes see the same inode. + const sawMissing = current !== null && (yield* consumeMissingObservation); + const replaced = previous !== undefined && current !== previous; + const firstProbe = previous === undefined; + previous = current; + + if (replaced || sawMissing || !childEnded) { + retryDelay = 1; + nextRetry = tick + 1; + } + if (firstProbe) return false; + if (replaced || sawMissing) return true; + if (!childEnded || current === null || tick < nextRetry) return false; + + // A stable inode can stay unwatchable due to permissions or OS watch limits. + retryDelay = Math.min(60, retryDelay * 2); + nextRetry = tick + retryDelay; + return true; + }), + ), + Stream.tap(() => Deferred.succeed(ready, undefined)), + Stream.filter((rebuild) => rebuild), + ); + }, + Stream.unwrap( + // Probe before resolving so a tree swapped in between reads as a replacement. + identity.pipe( + Effect.tap((acquired) => + Effect.sync(() => { + previous = acquired; + }), + ), + Effect.andThen(resolveLinkedPath(entry, link.value)), + Effect.map((target) => { + if (target === entry || target === NodePath.dirname(target)) return watchContents; + return watchDirectoryReplacements( + (ready) => watchDirectoryEntry(NodePath.dirname(target), ready), + watchDirectoryReplacements( + (ready) => watchDirectoryEntry(target, ready), + watchContents, + ), + ); + }), + ), + ), + ); + }), ), ); }; diff --git a/apps/server/src/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts index 92b7a4f7b2fff..8fcba6dc9f3f8 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.test.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -113,26 +113,55 @@ it.effect("starts a thread there by the project's folder, with the step's key as ); it.effect("registers a folder that is not a project there yet", () => + Effect.gen(function* () { + for (const [project, title] of [ + [input.project, "app"], + ["/work/team\\api", "team\\api"], + ["C:\\work\\app", "app"], + ]) { + const there = peer({ + t3_project_list: [{ projects: [], nextCursor: null }], + t3_project_create: [{ id: "p-new", workspaceRoot: project }], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start({ ...input, project }, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ); + assert.deepStrictEqual( + there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), + [ + ["t3_project_list", undefined], + ["t3_project_create", title], + ["t3_thread_launch", "p-new"], + ], + ); + } + }), +); + +it.effect("finds a Windows folder there however its separators are written", () => Effect.gen(function* () { const there = peer({ - t3_project_list: [{ projects: [], nextCursor: null }], - t3_project_create: [{ id: "p-new", workspaceRoot: "/work/app" }], + t3_project_list: [ + { projects: [{ id: "p-app", workspaceRoot: "C:\\work\\app" }], nextCursor: null }, + ], t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], }); yield* Effect.provide( Effect.flatMap(WorkflowAgentLinks.make, (links) => - links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + links.start( + { ...input, project: "C:/work/app" }, + "env-b", + "workflow:k", + EnvironmentId.make("env-a"), + ), ), there.layer, ); - assert.deepStrictEqual( - there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), - [ - ["t3_project_list", undefined], - ["t3_project_create", "app"], - ["t3_thread_launch", "p-new"], - ], - ); + assert.equal(there.calls.at(-1)?.arguments.projectId, "p-app"); }), ); diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts index 17afc658b2cd4..c88fe93d7d0aa 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -7,6 +7,11 @@ import { OrchestratorMcpThreadSendRunResult, OrchestratorMcpThreadWaitResult, } from "@t3tools/contracts"; +import { + fileBasename, + isWindowsDrivePath, + normalizeProjectPathForComparison, +} from "@t3tools/shared/path"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -77,6 +82,7 @@ export const make = Effect.gen(function* () { environment: string, path: string, ) { + const target = normalizeProjectPathForComparison(path); let cursor: number | null = 0; while (cursor !== null) { const page: Schema.Schema.Type = @@ -86,7 +92,9 @@ export const make = Effect.gen(function* () { ProjectToolkit.tools.t3_project_list.successSchema, { cursor, limit: 100 }, ); - const found = page.projects.find((project) => project.workspaceRoot === path); + const found = page.projects.find( + (project) => normalizeProjectPathForComparison(project.workspaceRoot) === target, + ); if (found !== undefined) return found.id; cursor = page.nextCursor; } @@ -104,7 +112,9 @@ export const make = Effect.gen(function* () { ) { const known = yield* listed(environment, path); if (known !== undefined) return known; - const title = path.split("/").findLast((part) => part.length > 0) ?? path; + const title = isWindowsDrivePath(path) + ? fileBasename(path) + : (path.split("/").findLast((part) => part.length > 0) ?? path); const created = yield* call( environment, "t3_project_create", diff --git a/apps/server/src/workflows/WorkflowAgents.ts b/apps/server/src/workflows/WorkflowAgents.ts index 674b72c69aa3d..834a781340269 100644 --- a/apps/server/src/workflows/WorkflowAgents.ts +++ b/apps/server/src/workflows/WorkflowAgents.ts @@ -4,6 +4,7 @@ import type { ProviderInteractionMode, RuntimeMode, } from "@t3tools/contracts"; +import { isWindowsDrivePath } from "@t3tools/shared/path"; import * as Context from "effect/Context"; import type * as Duration from "effect/Duration"; import type * as Effect from "effect/Effect"; @@ -67,7 +68,8 @@ export const launchOnContinue = new WorkflowAgentError({ }); /** A project named by its folder instead of its id. */ -export const isProjectPath = (project: string) => project.startsWith("/"); +export const isProjectPath = (project: string) => + project.startsWith("/") || isWindowsDrivePath(project); /** Where agent steps run. The server implements it with threads; tests stand in for it. */ export class WorkflowAgents extends Context.Service< diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts index 77ff4cf0ada2e..5e6509dd33647 100644 --- a/apps/server/src/workflows/WorkflowEngine.ts +++ b/apps/server/src/workflows/WorkflowEngine.ts @@ -44,6 +44,7 @@ import { import { issueReference, noteFor, stepReferences } from "./runReferences.ts"; import { forStep, KeyValues, layerKeyValues, EngineLink, layerEngineLink } from "./stepServices.ts"; import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { settleTurn, TurnEnd, TurnWatch } from "./workflowAgent.ts"; import { type Issue, isSettled, @@ -87,6 +88,8 @@ const DELIVERY_HEADERS = [ "idempotency-key", ]; const CANCEL_WAITS = Duration.seconds(30); +const decodeTurnWatch = Schema.decodeUnknownEffect(Schema.toCodecJson(TurnWatch)); +const encodeTurnEnd = Schema.encodeEffect(Schema.toCodecJson(TurnEnd)); // Times of day are the server's own, as they are for scheduled tasks. const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone); @@ -193,6 +196,49 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( yield* send(wait, value); }); + // Agent turns being watched now, by run and wait. The fibers live in the engine's scope, so a + // reload stops them at once and the next engine picks the turns up from their open waits. + const watchingTurns = new Set(); + const seeTurn = Effect.fn("WorkflowEngine.seeTurn")(function* (wait: WorkflowStore.WaitRow) { + const id = `${wait.run_id}/${wait.name}`; + // Taken before the first yield: the wait's own step and the sweep can both ask at once. + if (watchingTurns.has(id)) return; + watchingTurns.add(id); + const watch = yield* decodeTurnWatch(WorkflowStore.jsonValue(wait.watch_json ?? "null")).pipe( + Effect.option, + ); + if (Option.isNone(watch)) { + watchingTurns.delete(id); + return; + } + yield* settleTurn(watch.value).pipe( + Effect.flatMap(encodeTurnEnd), + Effect.catch((error) => encodeTurnEnd({ lost: text(error) })), + Effect.flatMap( + Effect.fnUntraced(function* (end) { + const woke = { expired: false, value: end as Schema.Json }; + if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke); + }), + ), + Effect.provideService(WorkflowAgents, agents), + Effect.provideContext(stepReferences(store, wait.run_id, watch.value.agent.step)), + Effect.provideService(SqlClient.SafeIntegers, false), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : Effect.logWarning("A workflow could not see an agent's turn through", cause).pipe( + Effect.annotateLogs({ wait: id }), + ), + ), + Effect.ensuring(Effect.sync(() => watchingTurns.delete(id))), + Effect.forkIn(scope), + ); + }); + const watchTurn = Effect.fn("WorkflowEngine.watchTurn")(function* (runId: string, name: string) { + const wait = yield* store.waitAt({ runId, wait: name }); + if (wait !== undefined) yield* seeTurn(wait); + }); + const start: Workflows["Service"]["start"] = Effect.fn("Workflows.start")( function* (name, input, options) { // A parent written against one version of a child must not get another one's payload. @@ -450,13 +496,17 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( const fireWatches = Effect.gen(function* () { const now = DateTime.toEpochMillis(yield* DateTime.now); for (const wait of yield* store.watches) { + const watched = WorkflowStore.jsonValue(wait.watch_json ?? "null"); + // An agent's turn is watched by a fiber of its own, started again here after a reload. + if (typeof watched === "object" && watched !== null && "agent" in watched) { + yield* seeTurn(wait); + continue; + } const id = `watch:${wait.run_id}/${wait.name}`; const last = lookedAt.get(id); if (last !== undefined && now - last < Duration.toMillis(LOOK_EVERY)) continue; lookedAt.set(id, now); - const watch = WorkflowStore.jsonValue( - wait.watch_json ?? "null", - ) as unknown as PullRequestWatch; + const watch = watched as unknown as PullRequestWatch; yield* forge.pullRequests.read(watch.pullRequest as PullRequestAddress).pipe( // Each look keeps where the pull request stands on the wait's own step. Effect.provideContext(stepReferences(store, wait.run_id, wait.name)), @@ -939,6 +989,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( signalAll, start, ended, + watchTurn, cancel: (runId, reason) => cancel(runId, reason), list: Effect.fn("WorkflowEngine.list")(function* (filter) { return (yield* store.runsWhere(filter)).map((row) => ({ diff --git a/apps/server/src/workflows/WorkflowForge.test.ts b/apps/server/src/workflows/WorkflowForge.test.ts index 58f9626423510..1d402227c57b4 100644 --- a/apps/server/src/workflows/WorkflowForge.test.ts +++ b/apps/server/src/workflows/WorkflowForge.test.ts @@ -85,6 +85,27 @@ it.effect("what a step does through the forge is kept against it, one key per th }).pipe(Effect.provide(forge)), ); +it.effect("a step can name its project by a Windows folder", () => + Effect.gen(function* () { + const { pullRequests } = yield* WorkflowForge.WorkflowForge; + const noted: Array = []; + const inStep = Context.make(StepReferences, { + note: (reference) => Effect.sync(() => void noted.push(reference)), + }); + for (const project of ["C:\\Users\\me\\app", "C:/Users/me/app"]) { + yield* Effect.provideContext( + pullRequests.act({ project, url: "https://github.com/Me/App/pull/7" }, "merge"), + inStep, + ); + } + const address = { projectId, host: "github.com", repository: "me/app", number: 7 }; + assert.deepStrictEqual( + noted.map((reference) => reference.address), + [address, address], + ); + }).pipe(Effect.provide(forge)), +); + it("a step's pull requests are the ones its thread was linked to while it ran", () => { const link = (number: number, linkedAt: string, source = "agent") => ({ host: "github.com", diff --git a/apps/server/src/workflows/WorkflowRuntime.test.ts b/apps/server/src/workflows/WorkflowRuntime.test.ts index 344e6d871efd9..62403042de1bc 100644 --- a/apps/server/src/workflows/WorkflowRuntime.test.ts +++ b/apps/server/src/workflows/WorkflowRuntime.test.ts @@ -3,7 +3,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -15,7 +18,7 @@ import * as TestClock from "effect/testing/TestClock"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; -import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { type AgentResult, WorkflowAgents } from "./WorkflowAgents.ts"; import * as WorkflowEngine from "./WorkflowEngine.ts"; import * as WorkflowRuntime from "./WorkflowRuntime.ts"; import { engineTag, type WorkflowDefinition } from "./workflow.ts"; @@ -39,6 +42,7 @@ workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.Stri const setup = Effect.fn("setup")(function* ( wrap: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem = (fileSystem) => fileSystem, engine?: (definitions: ReadonlyArray) => Layer.Layer, + agents?: WorkflowAgents["Service"], ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -54,7 +58,11 @@ const setup = Effect.fn("setup")(function* ( (definitions: ReadonlyArray) => engine?.(definitions) ?? WorkflowEngine.layer(definitions).pipe( - Layer.provide(Layer.mock(WorkflowAgents)({})), + Layer.provide( + agents === undefined + ? Layer.mock(WorkflowAgents)({}) + : Layer.succeed(WorkflowAgents, agents), + ), Layer.provide(database), Layer.provide(NodeCrypto.layer), ), @@ -424,6 +432,68 @@ it.effect("a change held back by a run goes in once that run ends, with no furth }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); +it.effect( + "a reload does not wait for an agent that is still at work, and its step ends with the turn", + () => + Effect.gen(function* () { + const ended = yield* Deferred.make(); + const started = yield* Deferred.make(); + const { fileSystem, at, runtime } = yield* setup(undefined, undefined, { + start: (input) => + Effect.as(Deferred.succeed(started, undefined), { + threadId: "thread", + turnId: input.key, + }), + result: () => Deferred.await(ended), + interrupt: () => Effect.succeed("stopped" as const), + }); + yield* fileSystem.writeFileString( + at("helper.ts"), + `T3.workflow("helper", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map(T3.agent("work", { brief: "Do it.", project: "p" }), (done) => done.value), +); +`, + ); + const ticking = (effect: Effect.Effect) => + Effect.raceFirst(effect, Effect.forever(TestClock.adjust("1 second"))); + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const helped = yield* ticking( + Effect.gen(function* () { + const run = yield* workflows.start("helper", {}, { idempotencyKey: "a" }); + yield* Deferred.await(started); + yield* workflows.waitFor(run.runId, (row) => row.status === "waiting"); + return run; + }), + ); + + // The test clock stands still during the save, so an engine that waited for the agent's + // step to finish would never stop: the step is not given up on, and the turn does not end. + // The swap cannot be interrupted, so a stuck save is unblocked by ending the turn. + const saving = yield* Effect.forkChild(definitions.save("greet.ts", greet("hello"))); + const saved = yield* Fiber.await(saving).pipe( + Effect.timeoutOption("10 seconds"), + TestClock.withLive, + ); + if (Option.isNone(saved)) { + yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "late" }); + yield* ticking(Fiber.await(saving)); + assert.fail("The reload waited for the agent's turn to end."); + } + assert.isTrue(Exit.isSuccess(saved.value) && saved.value.value.changed); + assert.equal((yield* workflows.get(helped.runId)).run.status, "waiting"); + + // The turn ends after the reload, and the new engine carries its result into the run. + yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "all done" }); + const done = yield* ticking( + workflows.waitFor(helped.runId, (run) => run.status === "completed"), + ); + assert.equal(done.result, "all done"); + }).pipe(Effect.provide(runtime), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + it.effect( "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again", () => diff --git a/apps/server/src/workflows/WorkflowStore.test.ts b/apps/server/src/workflows/WorkflowStore.test.ts index 7fa6daa8c0208..594e8074ee3f9 100644 --- a/apps/server/src/workflows/WorkflowStore.test.ts +++ b/apps/server/src/workflows/WorkflowStore.test.ts @@ -224,6 +224,55 @@ it.effect("counts what waits on a person, and finds the run's latest agent threa ), ); +it.effect("a long step result is cut without leaving half an emoji", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + yield* store.stepStarted("r1", "write", "step"); + yield* store.stepResult("r1", "write", `${"a".repeat(7_998)}\u{1F680}tail`); + const [step] = yield* store.steps("r1"); + // The cut is of the JSON text, which opens with a quote. + assert.equal(WorkflowStore.jsonValue(step?.result_json ?? "null"), `"${"a".repeat(7_998)}…`); + }), + ), +); + +it.effect("what a long agent step said is cut without leaving half an emoji", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + yield* store.stepStarted("r1", "write", "agent"); + yield* store.stepResult("r1", "write", null, `${"a".repeat(7_999)}\u{1F680}tail`); + const [step] = yield* store.steps("r1"); + assert.equal(step?.said, `${"a".repeat(7_999)}…`); + }), + ), +); + +it.effect("a long failure detail is cut without leaving half an emoji", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + yield* store.runStarted({ + runId: "r1", + workflow: "fail", + version: 1, + engineTag: "fail@1", + idempotencyKey: "k", + input: {}, + }); + yield* store.stepStarted("r1", "work", "step"); + const detail = `${"a".repeat(1_999)}\u{1F680}tail`; + yield* store.stepEnded("r1", "work", "failed", detail); + yield* store.runPaused("r1", detail); + const [step] = yield* store.steps("r1"); + const run = yield* store.run("r1"); + assert.equal(step?.detail, "a".repeat(1_999)); + assert.equal(run?.detail, "a".repeat(1_999)); + }), + ), +); + it.effect("one buffered signal goes to one wait, and a claimed wait keeps what woke it", () => withStore( Effect.gen(function* () { diff --git a/apps/server/src/workflows/WorkflowStore.ts b/apps/server/src/workflows/WorkflowStore.ts index 17d2b4c4bf358..79dfd1dc3de36 100644 --- a/apps/server/src/workflows/WorkflowStore.ts +++ b/apps/server/src/workflows/WorkflowStore.ts @@ -7,6 +7,7 @@ import { WorkflowRunStatus, WorkflowStep, } from "@t3tools/contracts"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; @@ -130,6 +131,15 @@ const WAKE_REDONE_AFTER = Duration.seconds(30); // Long enough for a sender's retries, short enough that the table stays small. // Enough to read what a step said; the page that shows it is not a place for a whole report. const STEP_RESULT_KEPT = 8_000; +const stepResultCut = (text: string) => { + const end = splitsSurrogatePair(text, STEP_RESULT_KEPT) ? STEP_RESULT_KEPT - 1 : STEP_RESULT_KEPT; + return `${text.slice(0, end)}…`; +}; +const DETAIL_KEPT = 2_000; +export const detailCut = (text: string) => + text.length <= DETAIL_KEPT + ? text + : text.slice(0, splitsSurrogatePair(text, DETAIL_KEPT) ? DETAIL_KEPT - 1 : DETAIL_KEPT); const SIGNAL_IDS_KEPT = Duration.days(7); const REFERENCE_TITLE_KEPT = 300; const idsKeptUntil = Effect.map(DateTime.now, (at) => @@ -493,7 +503,7 @@ export const make = Effect.gen(function* () { }), runPaused: Effect.fn("WorkflowStore.runPaused")(function* (runId, detail, held) { const at = yield* now; - const reason = detail.slice(0, 2000); + const reason = detailCut(detail); const paused = yield* sql` UPDATE workflow_runs SET status = 'paused', detail = ${reason}, pauses = pauses + 1, @@ -589,7 +599,7 @@ export const make = Effect.gen(function* () { Effect.andThen( sql` UPDATE workflow_steps - SET status = ${status}, detail = ${detail === null ? null : detail.slice(0, 2000)}, ended_at = ${at} + SET status = ${status}, detail = ${detail === null ? null : detailCut(detail)}, ended_at = ${at} WHERE run_id = ${runId} AND name = ${name} `, // A step that finished is progress: the next pause is the first in a row again. @@ -909,15 +919,10 @@ export const make = Effect.gen(function* () { ), stepResult: Effect.fn("WorkflowStore.stepResult")(function* (runId, name, value, said) { const full = jsonText(value); - const kept = - full.length <= STEP_RESULT_KEPT ? full : jsonText(`${full.slice(0, STEP_RESULT_KEPT)}…`); + const kept = full.length <= STEP_RESULT_KEPT ? full : jsonText(stepResultCut(full)); const words = said?.trim() ?? ""; const keptSaid = - words === "" - ? null - : words.length <= STEP_RESULT_KEPT - ? words - : `${words.slice(0, STEP_RESULT_KEPT)}…`; + words === "" ? null : words.length <= STEP_RESULT_KEPT ? words : stepResultCut(words); yield* sql` UPDATE workflow_steps SET result_json = ${kept}, said = ${keptSaid} WHERE run_id = ${runId} AND name = ${name} diff --git a/apps/server/src/workflows/Workflows.test.ts b/apps/server/src/workflows/Workflows.test.ts index cc56f6cd79a8a..3fdd50321923a 100644 --- a/apps/server/src/workflows/Workflows.test.ts +++ b/apps/server/src/workflows/Workflows.test.ts @@ -21,8 +21,19 @@ import * as TestClock from "effect/testing/TestClock"; import { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; import { issues, pullRequests } from "./forgeApi.ts"; -import { cancel, runs, signal, signalAll, start, store } from "./stepServices.ts"; -import { type InRun, invoke, skip, sleep, step, stop, title, wait, workflow } from "./workflow.ts"; +import { cancel, runs, signalAll, start } from "./stepServices.ts"; +import { + type InRun, + invoke, + skip, + sleep, + step, + stop, + text, + title, + wait, + workflow, +} from "./workflow.ts"; import { type AgentResult, WorkflowAgentError, WorkflowAgents } from "./WorkflowAgents.ts"; import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; import * as WorkflowEngine from "./WorkflowEngine.ts"; @@ -244,85 +255,6 @@ const definitions = ( ]; }; -/** Write a change, ask a person whether to merge it, then land it in the writer's own thread. */ -const tally = store.entry("tally", Schema.Number); -const stored = [ - /** Counts itself in the store, with the first try of the step failing after it counted. */ - workflow( - "tally", - { - version: 1, - payload: Schema.Struct({ wrong: Schema.optional(Schema.Boolean) }), - returns: Schema.Number, - }, - (payload) => - payload.wrong === true - ? step( - "read", - { returns: Schema.Number, ...once }, - Effect.as(store.entry("tally", Schema.String).get, 0), - ) - : step( - "count", - { returns: Schema.Number, ...once }, - tally - .update((current) => Option.getOrElse(current, () => 0) + 1) - .pipe(Effect.map(Option.getOrElse(() => 0))), - ), - ), - /** Waits in line for a door that `opener` opens. */ - workflow( - "door", - { version: 1, payload: Schema.Struct({ door: Schema.String }), returns: Schema.String }, - (payload) => - Effect.map( - wait("open", { returns: Schema.String, channel: payload.door }), - Option.getOrElse(() => "never"), - ), - ), - workflow( - "opener", - { version: 1, payload: Schema.Struct({ door: Schema.String, fail: Schema.Boolean }) }, - (payload) => - step( - "open", - { returns: Schema.Void, retry: { times: 1 } }, - Effect.gen(function* () { - // Written and taken back together when the step fails after writing. - yield* store.transaction( - Effect.gen(function* () { - yield* store.entry(`doors/${payload.door}`, Schema.String).set("open"); - const tries = yield* store - .entry(`tries/${payload.door}`, Schema.Number) - .update((current) => Option.getOrElse(current, () => 0) + 1); - if (payload.fail && Option.contains(tries, 1)) return yield* Effect.fail("slipped"); - }), - ); - yield* signal({ workflow: "door", channel: payload.door }, "came in"); - }), - ), - ), - /** Opens two doors, fails, and on its second try opens the second and a third. */ - workflow( - "relay", - { version: 1, payload: Schema.Struct({ doors: Schema.Array(Schema.String) }) }, - (payload) => - step( - "pass", - { returns: Schema.Void, retry: { times: 1 } }, - Effect.gen(function* () { - const tries = yield* store - .entry("relay-tries", Schema.Number) - .update((current) => Option.getOrElse(current, () => 0) + 1); - const [a, b, c] = payload.doors; - const doors = Option.contains(tries, 1) ? [a!, b!] : [b!, c!]; - for (const door of doors) yield* signal({ workflow: "door", channel: door }, "came in"); - if (Option.contains(tries, 1)) return yield* Effect.fail("slipped"); - }), - ), - ), -]; - const kid = workflow( "kid", { @@ -788,7 +720,6 @@ const harness = Effect.fnUntraced(function* (store?: typeof WorkflowStore.layer) ...definitions(counts, failures, latch), fix, ...triggered, - ...stored, ...family, ...control, ]; @@ -1638,84 +1569,6 @@ it.effect( }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); -it.effect( - "the store is shared by runs, survives a restart, and a failed transaction writes nothing", - () => - Effect.gen(function* () { - const { boot } = yield* harness(); - yield* boot( - Effect.gen(function* () { - const workflows = yield* Workflows.Workflows; - const runs = yield* Effect.forEach(["a", "b", "c"], (key) => - workflows.start("tally", {}, { idempotencyKey: key }), - ); - const counted = yield* Effect.forEach(runs, (run) => - workflows.waitFor(run.runId, status("completed")), - ); - assert.sameMembers( - counted.map((run) => run.result), - [1, 2, 3], - ); - }), - ); - yield* boot( - Effect.gen(function* () { - const workflows = yield* Workflows.Workflows; - const next = yield* workflows.start("tally", {}, { idempotencyKey: "d" }); - assert.equal((yield* workflows.waitFor(next.runId, status("completed"))).result, 4); - // A key read with another schema is the step's failure, with the key in the reason. - const wrong = yield* workflows.start("tally", { wrong: true }, { idempotencyKey: "w" }); - const paused = yield* workflows.waitFor(wrong.runId, status("paused")); - assert.include(paused.detail ?? "", "The stored value at tally does not fit its schema"); - - // The first try fails inside the transaction, so the door it opened is not there, and - // the try count it raised is 1 again on the second try, which is the one that signals. - const waiting = yield* workflows.start("door", { door: "east" }, { idempotencyKey: "e" }); - yield* workflows.waitFor(waiting.runId, status("waiting")); - const opener = yield* workflows.start( - "opener", - { door: "east", fail: true }, - { idempotencyKey: "o" }, - ); - yield* workflows.waitFor(opener.runId, status("paused")); - assert.equal((yield* workflows.get(waiting.runId)).run.status, "waiting"); - const clean = yield* workflows.start( - "opener", - { door: "east", fail: false }, - { idempotencyKey: "o2" }, - ); - yield* workflows.waitFor(clean.runId, status("completed")); - assert.equal( - (yield* workflows.waitFor(waiting.runId, status("completed"))).result, - "came in", - ); - - // A retry sends again what the first try sent, and what it sends anew is new. - const doors = ["ra", "rb", "rc"]; - const held = yield* Effect.forEach(doors, (door) => - workflows.start("door", { door }, { idempotencyKey: door }), - ); - yield* Effect.forEach(held, (run) => workflows.waitFor(run.runId, status("waiting"))); - const relay = yield* workflows.start("relay", { doors }, { idempotencyKey: "relay" }); - yield* workflows.waitFor(relay.runId, status("completed")); - // Each try is an attempt, though both were one run of the step. - assert.equal((yield* workflows.get(relay.runId)).steps[0]?.attempts, 2); - assert.equal( - yield* workflows.signal({ workflow: "door", channel: "rc" }, "late", { id: "rc-late" }), - "buffered", - ); - const opened = yield* Effect.forEach(held, (run) => - workflows.waitFor(run.runId, status("completed")), - ); - assert.deepStrictEqual( - opened.map((run) => run.result), - ["came in", "came in", "came in"], - ); - }), - ); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), -); - it.effect("an invoked run reports how it ended, and cancelling the parent cancels it", () => Effect.gen(function* () { const { boot } = yield* harness(); @@ -2422,3 +2275,11 @@ it.effect("a workflow can take an agent's failure as an answer and go on", () => ); }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); + +it("error text cuts at 2,000 units without leaving half an emoji", () => { + assert.equal(text(`${"a".repeat(1_999)}\u{1F680}tail`), "a".repeat(1_999)); + assert.equal( + text(new Error("outer", { cause: `${"a".repeat(1_992)}\u{1F680}tail` })), + `outer: ${"a".repeat(1_992)}`, + ); +}); diff --git a/apps/server/src/workflows/stepServices.ts b/apps/server/src/workflows/stepServices.ts index 53c6773494c3b..bdfd63b23d856 100644 --- a/apps/server/src/workflows/stepServices.ts +++ b/apps/server/src/workflows/stepServices.ts @@ -117,6 +117,8 @@ export class EngineLink extends Context.Service< readonly list: ListRuns; /** Tell the run that invoked `runId`, if one did, how it ended. */ readonly ended: (runId: string) => Effect.Effect; + /** Watch the agent turn behind an open wait of `runId` until it ends. */ + readonly watchTurn: (runId: string, wait: string) => Effect.Effect; } | undefined; /** The steps of each run that are running in this process right now. */ diff --git a/apps/server/src/workflows/workflow.ts b/apps/server/src/workflows/workflow.ts index 3359307875999..34bb7ffb20a18 100644 --- a/apps/server/src/workflows/workflow.ts +++ b/apps/server/src/workflows/workflow.ts @@ -67,6 +67,8 @@ export class RunContext extends Context.Service< readonly forStep: (name: string) => Context.Context; /** The steps running now, which a cancelled run's cleanup waits for. */ readonly inFlight: InFlight; + /** Have the engine see the agent turn behind the open wait `wait` through, and wake it. */ + readonly watchTurn: (wait: string) => Effect.Effect; } >()("t3/workflows/workflow/RunContext") {} @@ -101,7 +103,7 @@ export const claim = (name: string, cleanup = false) => /** An error as one line for a person, with what caused it when the error only wraps something. */ export const text = (error: unknown): string => { - if (typeof error === "string") return error.slice(0, 2000); + if (typeof error === "string") return WorkflowStore.detailCut(error); if (typeof error !== "object" || error === null) return String(error); // Also an error that came back from the journal, which is its fields and no longer an Error. const fields = error as { @@ -115,9 +117,8 @@ export const text = (error: unknown): string => { : typeof fields.reason === "string" ? fields.reason : "Unknown error"; - return (fields.cause === undefined ? message : `${message}: ${text(fields.cause)}`).slice( - 0, - 2000, + return WorkflowStore.detailCut( + fields.cause === undefined ? message : `${message}: ${text(fields.cause)}`, ); }; @@ -537,7 +538,7 @@ const waitClaimed = Effect.fnUntraced(function* ( name: `wait/${name}/again/${again}`, execute: Effect.gen(function* () { yield* run.store.waitReopened(run.runId, name, token); - yield* run.store.stepDetail(run.runId, name, problem.slice(0, 2000)); + yield* run.store.stepDetail(run.runId, name, WorkflowStore.detailCut(problem)); yield* deliverEarly(next, token); }), }); @@ -868,6 +869,9 @@ export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWo names: new Set(), forStep: (name) => forStep(store, keyValues, link, forge, runId, name), inFlight: link.inFlight, + watchTurn: Effect.fn("RunContext.watchTurn")(function* (wait: string) { + if (link.current !== undefined) yield* link.current.watchTurn(runId, wait); + }), }), ), ); diff --git a/apps/server/src/workflows/workflowAgent.ts b/apps/server/src/workflows/workflowAgent.ts index 03956086b03c8..e53b68d571391 100644 --- a/apps/server/src/workflows/workflowAgent.ts +++ b/apps/server/src/workflows/workflowAgent.ts @@ -6,6 +6,7 @@ import { identity } from "effect/Function"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import { Activity, DurableDeferred } from "effect/workflow"; import { checkOptions } from "./options.ts"; import { stepReferences } from "./runReferences.ts"; @@ -17,6 +18,7 @@ import { type StepFailed, text, waitAs, + wakeOf, } from "./workflow.ts"; import type { IssueAddress } from "./WorkflowForge.ts"; import { @@ -26,6 +28,7 @@ import { AgentTurn, WorkflowAgents, } from "./WorkflowAgents.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; /** A thread an agent step ran in, to hand to a later step that should continue it. */ export interface AgentThread { @@ -92,6 +95,97 @@ const NEW_THREAD_OPTIONS = [ "interactionMode", ] as const; +/** What the engine needs to see one turn of an agent step through to its end. */ +export const TurnWatch = Schema.Struct({ + agent: Schema.Struct({ + step: Schema.String, + turn: AgentTurn, + startedAt: Schema.optional(Schema.Number), + timeoutMs: Schema.optional(Schema.Number), + quietMs: Schema.optional(Schema.Number), + owesOutput: Schema.Boolean, + onFailure: Schema.Literals(["pause", "return"]), + }), +}); +export type TurnWatch = typeof TurnWatch.Type; + +/** How a watched turn ended: its result, or why it could not be read, which pauses the run. */ +export const TurnEnd = Schema.Union([ + Schema.Struct({ result: AgentResult }), + Schema.Struct({ lost: Schema.String }), +]); +export type TurnEnd = typeof TurnEnd.Type; + +/** The turn's result, or its thread stopped when the step's time is up. */ +export const settleTurn = Effect.fn("workflow.agent.settle")(function* ({ + agent: watch, +}: TurnWatch): Effect.fn.Return { + const agents = yield* WorkflowAgents; + const { turn, startedAt } = watch; + const threadOf = { threadId: turn.threadId, environment: turn.environment }; + const resultOf = (quiet: number | undefined) => + agents + .result(turn, { quiet: quiet === undefined ? undefined : Duration.millis(quiet) }) + .pipe( + watch.onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), + ), + ); + const settled = Effect.gen(function* () { + if (watch.timeoutMs === undefined || startedAt === undefined) { + return yield* resultOf(watch.quietMs); + } + const limit = Duration.millis(watch.timeoutMs); + const left = startedAt + watch.timeoutMs - (yield* Clock.currentTimeMillis); + const result = yield* resultOf(watch.quietMs).pipe( + Effect.timeoutOption(Duration.millis(Math.max(0, left))), + ); + if (Option.isSome(result)) return result.value; + // A stop that still fails pauses the run, so resuming tries the stop again. A step that + // returns its failure says the turn may still be running. + const stopping = agents + .interrupt({ ...threadOf, turnId: turn.turnId }) + .pipe(Effect.retry({ times: 2 })); + const stop: "stopped" | "ended" | "failed" = yield* watch.onFailure === "pause" + ? stopping + : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); + const late = `it was not done after ${Duration.format(limit)}`; + if (stop === "ended") { + // The turn ended before it could be stopped, maybe long ago, as a run that resumes late + // finds it. What it left is the answer when it is one. + const ended = yield* resultOf(undefined); + if (ended.ending !== "completed" || !watch.owesOutput || ended.output !== undefined) { + return ended; + } + // Stopping the later turn it may answer from could stop someone else's. + return { + ending: "stopped" as const, + detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, + reply: "", + }; + } + return { + ending: "stopped" as const, + detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, + reply: "", + }; + }); + return yield* settled.pipe( + Effect.map((result): TurnEnd => ({ result })), + Effect.catch((error) => Effect.succeed({ lost: text(error) })), + ); +}); + +// An agent turn's wait takes no signal from outside: only the engine's watch ends it. +const NOTHING_FITS = WorkflowStore.jsonText({ not: {} }); +// A result journaled when the wait for a turn still ran inside its activity, which kept the +// engine from stopping, and every workflow call with it, until the turn ended. +const Opened = Schema.Union([AgentResult, Schema.Struct({ ending: Schema.Literal("watching") })]); +const decodeTurnEnd = Schema.decodeUnknownEffect(Schema.toCodecJson(TurnEnd)); +const encodeWatch = Schema.encodeEffect(Schema.toCodecJson(TurnWatch)); + const attempt = Effect.fn("workflow.agent")(function* ( name: string, options: AgentOptions, @@ -121,6 +215,10 @@ const attempt = Effect.fn("workflow.agent")(function* ( const outputCodec = options.returns === undefined ? undefined : Schema.toCodecJson(options.returns); const decodeOutput = outputCodec === undefined ? undefined : Schema.decodeEffect(outputCodec); + const timeoutMs = + options.timeout === undefined + ? undefined + : Duration.toMillis(Duration.fromInputUnsafe(options.timeout)); const threadOf = (turn: AgentTurn): AgentThread => ({ threadId: turn.threadId, ...(turn.environment === undefined ? {} : { environment: turn.environment }), @@ -174,61 +272,73 @@ const attempt = Effect.fn("workflow.agent")(function* ( Effect.succeed({ threadId: "", turnId: "", failed: text(error) }), ), ); - const resultOf = (turn: AgentTurn, wait = { quiet }) => - agents - .result(turn, wait) - .pipe( - Effect.provideContext(touches), - onFailure === "pause" - ? identity - : Effect.catch((error) => - Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), - ), - ); - /** The turn's result, or its thread stopped when the step's time is up. */ - const within = Effect.fn("workflow.agent.within")(function* ( + /** + * The turn's result. The engine watches the turn outside the run and wakes the run once it + * ends, so an engine that stops while an agent works is not held up by it. + */ + const ended = Effect.fn("workflow.agent.ended")(function* ( turn: AgentTurn, startedAt: number | undefined, + round: number, + correction: number, ) { - if (options.timeout === undefined || startedAt === undefined) return yield* resultOf(turn); - const limit = Duration.fromInputUnsafe(options.timeout); - const left = startedAt + Duration.toMillis(limit) - (yield* Clock.currentTimeMillis); - const result = yield* resultOf(turn).pipe( - Effect.timeoutOption(Duration.millis(Math.max(0, left))), + const watch = WorkflowStore.jsonText( + yield* encodeWatch({ + agent: { + step: name, + turn, + startedAt, + timeoutMs, + quietMs: quiet === undefined ? undefined : Duration.toMillis(quiet), + owesOutput: outputSchema !== undefined, + onFailure, + }, + }).pipe(Effect.orDie), ); - if (Option.isSome(result)) return result.value; - // A stop that still fails pauses the run unrecorded, so resuming tries the stop again. A step - // that returns its failure says the turn may still be running. - const stopping = agents - .interrupt({ ...threadOf(turn), turnId: turn.turnId }) - .pipe(Effect.retry({ times: 2 })); - const stop: "stopped" | "ended" | "failed" = yield* onFailure === "pause" - ? stopping - : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); - const late = `it was not done after ${Duration.format(limit)}`; - if (stop === "ended") { - // The turn ended before it could be stopped, maybe long ago, as a run that resumes late - // finds it. What it left is the answer when it is one. - const ended = yield* resultOf(turn, { quiet: undefined }); - if ( - ended.ending !== "completed" || - outputSchema === undefined || - ended.output !== undefined - ) { - return ended; - } - // Stopping the later turn it may answer from could stop someone else's. - return { - ending: "stopped" as const, - detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, - reply: "", - }; + const first = `agent/${name}/${round}/result/${correction}`; + for (let lost = 0; ; lost++) { + const at = lost === 0 ? first : `${first}/again/${lost}`; + const wake = wakeOf(at); + const token = yield* DurableDeferred.token(wake); + const opened = yield* journaled( + run, + name, + at, + Opened, + Effect.gen(function* () { + yield* run.store.runStatus(run.runId, "waiting", `agent ${name}`); + yield* run.store.waitOpened({ + runId: run.runId, + name: at, + workflow: run.workflow, + key: undefined, + token, + schemaJson: NOTHING_FITS, + requestJson: null, + watchJson: watch, + deadline: null, + }); + yield* run.watchTurn(at); + return { ending: "watching" as const }; + }), + ); + if (opened.ending !== "watching") return opened; + const woke = yield* DurableDeferred.await(wake); + const end = yield* Effect.orDie(decodeTurnEnd(woke.value)); + yield* Activity.make({ name: `${at}/close`, execute: run.store.waitClosed(run.runId, at) }); + if ("result" in end) return end.result; + // Fails the first time it is reached, which pauses the run here. Resuming the run reaches + // it again, and the turn is watched once more. + yield* journaled( + run, + name, + `${at}/lost`, + Schema.Void, + Effect.flatMap(run.store.mark(run.runId, `${at}/lost`), (arrivals) => + arrivals > 1 ? Effect.void : Effect.fail(end.lost), + ), + ); } - return { - ending: "stopped" as const, - detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, - reply: "", - }; }); const done = (round: number, produced: Schema.Json, said?: string) => journaled( @@ -263,16 +373,7 @@ const attempt = Effect.fn("workflow.agent")(function* ( let stopped = false; let died = false; for (let correction = 0; turn.failed === undefined; correction++) { - const result = yield* journaled( - run, - name, - `agent/${name}/${round}/result/${correction}`, - AgentResult, - Effect.andThen( - run.store.runStatus(run.runId, "waiting", `agent ${name}`), - within(turn, startedAt), - ), - ); + const result = yield* ended(turn, startedAt, round, correction); if (result.ending !== "completed") { stopped = result.ending === "stopped"; died = result.ending === "failed"; diff --git a/apps/server/src/workspace/IgnorePatterns.test.ts b/apps/server/src/workspace/IgnorePatterns.test.ts index 35dba03ca1fb3..c4e0361ad2434 100644 --- a/apps/server/src/workspace/IgnorePatterns.test.ts +++ b/apps/server/src/workspace/IgnorePatterns.test.ts @@ -42,6 +42,12 @@ describe("parseIgnoreFile", () => { expect(decide("dist/", "dist", true)).toBe("ignored"); }); + it("drops trailing spaces unless a backslash escapes them, like git", () => { + expect(decide("build ", "build")).toBe("ignored"); + expect(decide("keep\\ ", "keep ")).toBe("ignored"); + expect(decide("dir\\\\ ", "dir\\")).toBe("ignored"); + }); + it("matches adversarial patterns in linear time", () => { // A backtracking regex takes seconds to reject this pair; the vitest timeout catches that. const pattern = `${"a*".repeat(20)}b\n`; diff --git a/apps/server/src/workspace/IgnorePatterns.ts b/apps/server/src/workspace/IgnorePatterns.ts index b303c5bf1fa23..5ca1f7b56ec01 100644 --- a/apps/server/src/workspace/IgnorePatterns.ts +++ b/apps/server/src/workspace/IgnorePatterns.ts @@ -52,8 +52,13 @@ function parseClass(chars: ReadonlyArray, start: number) { function parseLine(rawLine: string): Pattern | undefined { let line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine; - // Trailing spaces are dropped unless escaped. - while (line.endsWith(" ") && !line.endsWith("\\ ")) line = line.slice(0, -1); + // Trailing spaces are dropped unless escaped; `\\ ` escapes the backslash, not the space. + while (line.endsWith(" ")) { + let backslashes = 0; + while (line[line.length - 2 - backslashes] === "\\") backslashes += 1; + if (backslashes % 2 === 1) break; + line = line.slice(0, -1); + } if (line === "" || line.startsWith("#")) return undefined; const negated = line.startsWith("!"); if (negated) line = line.slice(1); diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 75c12d8a7409b..b202bd38d7f65 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -14,6 +14,7 @@ import { import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import * as Cause from "effect/Cause"; @@ -309,7 +310,7 @@ const make = Effect.gen(function* () { processes .run({ operation: "TaskFolders.worktreeLayout", - command: onWindows ? "cmd.exe" : "sh", + command: onWindows ? windowsSystem32Path(hostEnvironment, "cmd.exe") : "sh", args: onWindows ? ["/d", "/s", "/c", command] : ["-c", command], cwd: taskFolder.projectRoot, env: { diff --git a/apps/server/src/workspace/restoreMissingWorktree.ts b/apps/server/src/workspace/restoreMissingWorktree.ts index 6aa4b11350efb..ea803cbdac680 100644 --- a/apps/server/src/workspace/restoreMissingWorktree.ts +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -1,4 +1,9 @@ -import { ThreadId, type ProjectId, type TerminalCwdNotFoundError } from "@t3tools/contracts"; +import { + ThreadId, + type Project, + type ProjectId, + type TerminalCwdNotFoundError, +} from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -42,6 +47,11 @@ class WorktreeRecreateNoBaseError extends Schema.TaggedError Effect.Effect; + /** A checkout this service recreated for the thread whose setup has not run yet. */ + readonly takeRecreated: (threadId: ThreadId) => Effect.Effect; } >()("t3/workspace/restoreMissingWorktree/ThreadWorktreeRestore") {} @@ -258,11 +271,21 @@ export const layerThreadWorktreeRestore = Layer.effect( Effect.gen(function* () { const path = yield* Path.Path; const restore = yield* makeRestoreMissingWorktree; + // Sends restore before dispatch, so turn start finds the checkout present and runs setup from here. + const recreated = new Map(); return { restore: Effect.fn("ThreadWorktreeRestore.restore")(function* (thread: WorktreeThread) { - return yield* thread.worktreePath === null + const result = yield* thread.worktreePath === null ? restore(thread) : withWorkspaceLease(path.resolve(thread.worktreePath), restore(thread)); + if (result !== undefined) recreated.set(thread.id, result); + }), + takeRecreated: Effect.fn("ThreadWorktreeRestore.takeRecreated")(function* ( + threadId: ThreadId, + ) { + const result = recreated.get(threadId); + recreated.delete(threadId); + return result; }), }; }), @@ -296,6 +319,7 @@ export const makePrepareTerminalLaunch = Effect.fn( } const recover = (error: TerminalCwdNotFoundError) => restoreMissingWorktree(thread).pipe( + Effect.asVoid, Effect.catch((cause) => Effect.logWarning("failed to recreate missing worktree", { threadId: thread.id, diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 746adba793b54..09a1b48a5bb91 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -11,6 +11,8 @@ import { type AuthEnvironmentScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + AuthProvidersManageScope, + type ManagedPolicySummary, type WorkflowRun, type WorkflowStep, AuthSessionId, @@ -2170,6 +2172,61 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); +it.effect("thread resume replays a deleted thread's deletion and nothing recorded before it", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const now = "2026-10-13T00:00:00.000Z"; + const threadId = ThreadId.make("thread:deleted-resume"); + const insert = (version: number, type: string, payload: object) => sql` + INSERT INTO orchestration_events ( + event_id, aggregate_kind, stream_id, stream_version, event_type, + occurred_at, actor_kind, payload_json, metadata_json, application_event_version + ) VALUES ( + ${`deleted-resume:${version}`}, 'thread', ${threadId}, ${version}, ${type}, + ${now}, 'server', ${JSON.stringify(payload)}, '{}', 2 + ) + `; + const detached = { providerSessionId: "session:deleted-resume", detachedAt: now }; + yield* insert(0, "provider-session.detached", detached); + yield* insert(1, "provider-session.detached", detached); + yield* insert(2, "thread.deleted", { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: "project:deleted-resume", + title: "Deleted", + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "default" }, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: now, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + }); + + const items = yield* subscribeOrchestrationV2Thread({ threadId, afterSequence: 0 }).pipe( + Effect.flatMap(Stream.runCollect), + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + streamStoredEventsFrom: () => Stream.empty, + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + ); + assert.deepEqual( + Array.from(items).map((item) => item.kind === "event" && item.event.type), + ["thread.deleted"], + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + // A prune pass can delete replayed rows after the boundary check; the read must not be trusted. it.effect.each(["thread", "shell"] as const)( "%s resume loads a snapshot when pruning advances during the replay read", @@ -2382,6 +2439,7 @@ const acpSessionTags = [ WS_METHODS.serverListAcpRegistrySessions, WS_METHODS.serverImportAcpRegistrySession, WS_METHODS.serverDeleteAcpRegistrySession, + WS_METHODS.serverPrepareAcpRegistryAgent, ] as const; const acpSessionRpcs = WsRpcGroup.omit( ...[...WsRpcGroup.requests.keys()].filter( @@ -2517,7 +2575,9 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i const instance = { driverKind: acpDriver, snapshot: { - getSnapshot: Effect.succeed({ nativeSessions: { canLoad: true, canDelete: true } }), + getSnapshot: Effect.succeed({ + nativeSessions: { canList: true, canLoad: true, canDelete: true }, + }), }, acpSessionManagement: { listSessions: () => @@ -2754,6 +2814,127 @@ const layerWorkflowRpcTest = Layer.mergeAll( Layer.mock(ServerBrowser.ServerBrowser)({}), ); +/** A client for the ACP Registry RPCs; `calls` records what reached the agent or the catalog. */ +const makeAcpRegistryClient = Effect.fn("test.makeAcpRegistryClient")(function* ( + calls: Array, + options: { + readonly nativeSessions?: { readonly canList: boolean }; + readonly managedPolicy?: ManagedPolicySummary; + }, +) { + const scopes = [AuthOrchestrationReadScope, AuthProvidersManageScope]; + const instance = { + driverKind: acpDriver, + snapshot: { getSnapshot: Effect.succeed({ nativeSessions: options.nativeSessions }) }, + } as unknown as ProviderInstance; + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + ServerSettings.layerTest({}, options.managedPolicy), + Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({ + prepare: ({ agentId }) => + Effect.sync(() => calls.push(`prepare:${agentId}`)).pipe( + Effect.as({ agentId, version: "1.0.0", distribution: "npx", prepared: true } as const), + ), + }), + Layer.mock(AcpRegistrySessions.AcpRegistrySessions)({ + project: () => Effect.succeed({ workspaceRoot: "/workspace/acp" } as never), + sessionManager: () => + Effect.succeed({ + instance, + manager: { + listSessions: () => + Effect.sync(() => calls.push("listSessions")).pipe( + Effect.as({ sessions: [], nextCursor: null }), + ), + } as unknown as NonNullable, + }), + }), + ); + return yield* RpcTest.makeClient(acpSessionRpcs).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("acp-test"), + subject: "acp-test", + method: "browser-session-cookie", + scopes, + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe(Layer.provide(services), Layer.merge(RpcAuthorization.layer(scopes))), + ), + ); +}); + +it.effect("listing ACP sessions reaches only an agent that advertises listing", () => + Effect.gen(function* () { + const calls: Array = []; + const input = { instanceId: acpInstanceId, projectId: acpProjectId }; + + const unprobed = yield* makeAcpRegistryClient(calls, {}); + const refused = yield* unprobed[WS_METHODS.serverListAcpRegistrySessions](input).pipe( + Effect.flip, + ); + assert.strictEqual( + refused._tag === "AcpRegistryOperationError" ? refused.reason : refused._tag, + "session_list_unsupported", + ); + assert.deepEqual(calls, []); + + const probed = yield* makeAcpRegistryClient(calls, { nativeSessions: { canList: true } }); + yield* probed[WS_METHODS.serverListAcpRegistrySessions](input); + assert.deepEqual(calls, ["listSessions"]); + }).pipe(Effect.provide(layerWorkflowRpcTest)), +); + +it.effect("preparing an ACP Registry agent follows the policy's allowed providers", () => + Effect.gen(function* () { + const calls: Array = []; + const policy = (...allowedDrivers: ReadonlyArray): ManagedPolicySummary => ({ + organization: "Example Corp", + lockedSettings: [], + limits: { + providers: { + allowedDrivers: [ + ProviderDriverKind.make("codex"), + ...allowedDrivers.map((driver) => ProviderDriverKind.make(driver)), + ], + lockedInstanceFields: {}, + }, + }, + }); + + const excluded = yield* makeAcpRegistryClient(calls, { managedPolicy: policy() }); + const refused = yield* excluded[WS_METHODS.serverPrepareAcpRegistryAgent]({ + agentId: "example-agent", + }).pipe(Effect.flip); + assert.strictEqual( + refused._tag === "AcpRegistryOperationError" ? refused.message : refused._tag, + "Example Corp's policy does not allow the ACP Registry provider.", + ); + assert.deepEqual(calls, []); + + const included = yield* makeAcpRegistryClient(calls, { + managedPolicy: policy("acpRegistry"), + }); + yield* included[WS_METHODS.serverPrepareAcpRegistryAgent]({ agentId: "example-agent" }); + const unmanaged = yield* makeAcpRegistryClient(calls, {}); + yield* unmanaged[WS_METHODS.serverPrepareAcpRegistryAgent]({ agentId: "example-agent" }); + assert.deepEqual(calls, ["prepare:example-agent", "prepare:example-agent"]); + }).pipe(Effect.provide(layerWorkflowRpcTest)), +); + it.effect("workflow RPCs read a run and pass an answer, a resume and a cancel to the service", () => Effect.gen(function* () { const calls: Array = []; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1ea6af9cf5b1f..b6c58a145b761 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -36,6 +36,7 @@ import { AuthOrchestrationOperateScope, AuthProvidersManageScope, type AuthEnvironmentScope, + ProviderDriverKind, type ScheduledTaskListResult, WorkflowRequestError, AuthSessionId, @@ -200,6 +201,7 @@ import * as NpmRelease from "./cloud/npmRelease.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as ManagedProviders from "./policy/managedProviders.ts"; import * as ServerSettings from "./serverSettings.ts"; import { invalidateSettingsSecrets } from "./sourceControl/sourceControlHostSecrets.ts"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; @@ -1139,7 +1141,11 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs ) { return yield* snapshotThenLive(); } - const replay = coalesceLiveUpdatedEvents(replayed); + // A deleted thread reads as gone: its replay starts at the deletion. + const deletion = replayed.findLastIndex((item) => item.event.type === "thread.deleted"); + const replay = coalesceLiveUpdatedEvents( + deletion === -1 ? replayed : replayed.slice(deletion), + ); const plan = decideThreadResume({ afterSequence: input.afterSequence, highWater, @@ -1655,6 +1661,14 @@ export const layerWsRpc = ( ) { const project = yield* acpRegistrySessions.project(input.projectId); const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); + // Only a probed agent advertises listing, so a read never installs or first-starts one. + const snapshot = yield* instance.snapshot.getSnapshot; + if (snapshot.nativeSessions?.canList !== true) { + return yield* new AcpRegistryOperationError({ + reason: "session_list_unsupported", + message: "The ACP agent does not advertise session listing.", + }); + } const listed = yield* manager.listSessions({ cwd: project.workspaceRoot, ...(input.cursor === undefined ? {} : { cursor: input.cursor }), @@ -1897,6 +1911,7 @@ export const layerWsRpc = ( auth, cwd: config.cwd, hostname: yield* HostProcess.Hostname, + homeDirectory: yield* HostProcess.HomeDirectory, keybindingsConfigPath: config.keybindingsConfigPath, keybindings: keybindingsConfig.keybindings, issues: keybindingsConfig.issues, @@ -2452,9 +2467,19 @@ export const layerWsRpc = ( [WS_METHODS.serverPrepareAcpRegistryAgent]: (input) => Effect.annotateCurrentSpan({ "acp_registry.agent_id": input.agentId }).pipe( Effect.andThen( - acpRegistryCatalog - .prepare(input) - .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)), + Effect.suspend(() => { + const blocked = ManagedProviders.disallowedDriverReason( + serverSettings.managedPolicy, + ProviderDriverKind.make("acpRegistry"), + ); + return blocked === undefined + ? acpRegistryCatalog + .prepare(input) + .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)) + : Effect.fail( + new AcpRegistryOperationError({ reason: "install_failed", message: blocked }), + ); + }), ), ), [WS_METHODS.serverUninstallAcpRegistryManagedBinary]: (input) => @@ -3744,6 +3769,7 @@ export const layer = Layer.unwrap( Effect.gen(function* () { const serverBrowser = yield* ServerBrowser.ServerBrowser; const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate; + const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner; const npmRelease = yield* NpmRelease.NpmRelease; const pullRequests = yield* PullRequestService.PullRequestService; const issues = yield* IssueService.IssueService; @@ -3835,7 +3861,13 @@ export const layer = Layer.unwrap( Layer.provide(DefectReporter.layer), Layer.provide(AcpRegistrySessions.layer), Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)), - Layer.provide(ProviderMaintenanceRunner.layer), + // Installs outlive the connection that started them and lock across clients. + Layer.provide( + Layer.succeed( + ProviderMaintenanceRunner.ProviderMaintenanceRunner, + providerMaintenanceRunner, + ), + ), Layer.provide(Layer.succeed(NpmRelease.NpmRelease, npmRelease)), Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)), // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs. diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 2715d2987b604..2bec8830d86c5 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -110,12 +110,12 @@ export default mergeConfig( }, }, ], - // SEA embeds one entry; expose the history worker as a hidden subcommand. + // SEA embeds one entry; expose the workers as hidden subcommands. entry: packBootstrap ? ["src/bin.ts"] : packExecutable ? ["src/binMain.ts"] - : ["src/bin.ts", "src/claude-history-worker.ts"], + : ["src/bin.ts", "src/claude-history-worker.ts", "src/process-launcher.ts"], outDir: packBootstrap ? "dist-exe" : packExecutable ? cliAssetDir : "dist", sourcemap: !packExecutable, clean: true, diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index cce59f08f6d12..76e7bc9e5cff1 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -90,6 +90,9 @@ function startClientAppearance(): void { if (previous?.chatWidth !== settings.chatWidth) { root.dataset.chatWidth = settings.chatWidth; } + if (previous?.htmlPreviewWidth !== settings.htmlPreviewWidth) { + root.dataset.htmlPreviewWidth = settings.htmlPreviewWidth; + } if (previous?.appearanceContrast !== settings.appearanceContrast) { applyAppearanceContrast(root, settings.appearanceContrast); } diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index b20d737095116..572e8d926955e 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -13,6 +13,7 @@ import { } from "~/components/preview/thumbButtons"; import { usePreviewBridge } from "~/components/preview/usePreviewBridge"; import { useClientSettingsHydrated } from "~/hooks/useSettings"; +import { useViewportSize } from "~/hooks/useViewportSize"; import { cn, isMacPlatform } from "~/lib/utils"; import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore"; @@ -22,6 +23,8 @@ import { resolveBrowserViewportLayout, resolveBrowserViewportTransform, resolveFittedBrowserViewport, + resolveHiddenBrowserViewportFitScale, + resolveHiddenBrowserViewportSize, } from "./browserViewportLayout"; import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar"; import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles"; @@ -243,18 +246,14 @@ export function HostedBrowserWebview(props: { setAspectRatioLocked(aspectRatio !== null); }; const content = presentation.content; - const hiddenWidth = - viewport._tag !== "fill" - ? viewport.width * layoutZoomFactor - : content - ? content.width / content.scale - : (lastRect?.width ?? 1280); - const hiddenHeight = - viewport._tag !== "fill" - ? viewport.height * layoutZoomFactor - : content - ? content.height / content.scale - : (lastRect?.height ?? 800); + const windowSize = useViewportSize(); + const { width: hiddenWidth, height: hiddenHeight } = resolveHiddenBrowserViewportSize({ + setting: viewport, + zoomFactor: layoutZoomFactor, + content, + lastRect, + windowSize, + }); // Build from primitives on each side of the resize hook to keep both objects cached. const containerSize = active && lastRect ? lastRect : { width: hiddenWidth, height: hiddenHeight }; @@ -350,7 +349,16 @@ export function HostedBrowserWebview(props: { }; const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive; - const viewportTransform = resolveBrowserViewportTransform(layout.viewportScale, fullDetail); + // Electron clips a guest's native surface at the window edge, so a hidden guest draws scaled to fit. + const fitScale = + active && lastRect + ? 1 + : resolveHiddenBrowserViewportFitScale( + { width: hiddenWidth, height: hiddenHeight }, + windowSize, + ); + const viewportScale = layout.viewportScale * fitScale; + const viewportTransform = resolveBrowserViewportTransform(viewportScale, fullDetail); const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({ active, renderingActive, @@ -388,10 +396,10 @@ export function HostedBrowserWebview(props: { key={webviewGeneration} className="absolute" style={{ - left: layout.viewportX, - top: layout.viewportY, - width: layout.viewportWidth, - height: layout.viewportHeight, + left: layout.viewportX * fitScale, + top: layout.viewportY * fitScale, + width: layout.viewportWidth * fitScale, + height: layout.viewportHeight * fitScale, transformStyle: viewportTransform && fullDetail ? "preserve-3d" : undefined, }} > diff --git a/apps/web/src/browser/browserViewportLayout.test.ts b/apps/web/src/browser/browserViewportLayout.test.ts index c72f68e1e20da..595d25da089fe 100644 --- a/apps/web/src/browser/browserViewportLayout.test.ts +++ b/apps/web/src/browser/browserViewportLayout.test.ts @@ -2,8 +2,11 @@ import { describe, expect, it } from "vite-plus/test"; import { resizeBrowserViewportFromRail, + resolveBrowserViewportLayout, resolveBrowserViewportTransform, resolveFittedBrowserViewport, + resolveHiddenBrowserViewportFitScale, + resolveHiddenBrowserViewportSize, } from "./browserViewportLayout"; describe("resolveBrowserViewportLayout", () => { @@ -43,6 +46,43 @@ describe("resolveBrowserViewportLayout", () => { ), ).toEqual({ width: 460, height: 409 }); }); + + it("fits a hidden fixed viewport larger than the window inside the window", () => { + const setting = { _tag: "freeform", width: 1440, height: 1700 } as const; + const windowSize = { width: 1400, height: 1000 }; + const hidden = resolveHiddenBrowserViewportSize({ + setting, + zoomFactor: 1, + content: null, + lastRect: null, + windowSize, + }); + expect(hidden).toEqual({ width: 1400, height: 1000 }); + const layout = resolveBrowserViewportLayout(hidden, setting); + expect(layout.viewportHeight).toBeLessThanOrEqual(windowSize.height); + expect(layout.viewportScale).toBeCloseTo(1000 / 1700); + expect( + resolveHiddenBrowserViewportSize({ + setting: { _tag: "freeform", width: 1280, height: 800 }, + zoomFactor: 1, + content: null, + lastRect: null, + windowSize, + }), + ).toEqual({ width: 1280, height: 800 }); + }); + + it.each([ + { hidden: { width: 1440, height: 900 }, window: { width: 1840, height: 1016 }, scale: 1 }, + { hidden: { width: 3440, height: 1440 }, window: { width: 1720, height: 1016 }, scale: 0.5 }, + { hidden: { width: 1000, height: 2000 }, window: { width: 1840, height: 500 }, scale: 0.25 }, + { hidden: { width: 3440, height: 1440 }, window: { width: 0, height: 0 }, scale: 1 }, + ])( + "fits a $hidden.width x $hidden.height hidden guest in a $window.width x $window.height window", + ({ hidden, window, scale }) => { + expect(resolveHiddenBrowserViewportFitScale(hidden, window)).toBe(scale); + }, + ); }); describe("resolveBrowserViewportTransform", () => { diff --git a/apps/web/src/browser/browserViewportLayout.ts b/apps/web/src/browser/browserViewportLayout.ts index 7fe6b170c671d..c3c56582bade5 100644 --- a/apps/web/src/browser/browserViewportLayout.ts +++ b/apps/web/src/browser/browserViewportLayout.ts @@ -71,6 +71,39 @@ export function resolveFittedBrowserViewport( return { _tag: "freeform", width: 1280, height: 800 }; } +export function resolveHiddenBrowserViewportSize(input: { + readonly setting: PreviewViewportSetting; + readonly zoomFactor: number; + readonly content: { + readonly width: number; + readonly height: number; + readonly scale: number; + } | null; + readonly lastRect: { readonly width: number; readonly height: number } | null; + readonly windowSize: { readonly width: number; readonly height: number }; +}): { readonly width: number; readonly height: number } { + const { content, lastRect, setting, windowSize, zoomFactor } = input; + if (setting._tag !== "fill") { + // Chromium paints a guest only near the window, so a capture of a larger one loses its far edge. + return { + width: Math.min(windowSize.width, setting.width * zoomFactor), + height: Math.min(windowSize.height, setting.height * zoomFactor), + }; + } + if (content) + return { width: content.width / content.scale, height: content.height / content.scale }; + return { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 }; +} + +export function resolveHiddenBrowserViewportFitScale( + hiddenSize: { readonly width: number; readonly height: number }, + windowSize: { readonly width: number; readonly height: number }, +): number { + // A minimized window can report a zero viewport; scale(0) would stop the guest compositing. + if (windowSize.width <= 0 || windowSize.height <= 0) return 1; + return Math.min(1, windowSize.width / hiddenSize.width, windowSize.height / hiddenSize.height); +} + export function resolveBrowserDeviceViewportArea(container: { readonly width: number; readonly height: number; diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts index c0c22fc2558a4..92e16d76243e6 100644 --- a/apps/web/src/browserHistoryStore.browser.test.ts +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -2,6 +2,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { resetBrowserHistoryForTests, useBrowserHistoryStore } from "./browserHistoryStore"; +import { randomUUID } from "./lib/utils"; const storageKey = "t3code:browser-history:v1"; const oldEntry = { url: "http://example.test/removed", lastVisitedAt: 1 }; @@ -117,8 +118,7 @@ it("refreshes the open history when another document adds a visit", async () => JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); - using documents = new DisposableStack(); - const otherStore = await openHistoryDocument(documents); + const otherStore = await openHistoryDocument(); await vi.waitFor(() => expect(otherStore.getState().byProjectKey).toEqual({ a: [page] })); otherStore.getState().recordVisit("a", page.url, page.lastVisitedAt); @@ -164,29 +164,15 @@ it("bounds saved thread mappings while keeping live registrations", async () => } }); -async function openHistoryDocument( - disposables: DisposableStack, - { withoutIndexedDB = false } = {}, -) { - const source = new URL(import.meta.url); - source.pathname = source.pathname.replace(/\.browser\.test\.ts$/, ".ts"); - source.search = ""; - const frame = document.createElement("iframe"); - disposables.defer(() => frame.remove()); - frame.srcdoc = `${withoutIndexedDB ? '' : ""} - `; - await new Promise((resolve) => { - frame.onload = () => resolve(); - document.body.append(frame); - }); - const store = ( - frame.contentWindow as (Window & { historyStore?: typeof useBrowserHistoryStore }) | null - )?.historyStore; - if (!store) throw new Error("The history document did not load."); - return store; +// A fresh module instance stands in for another tab: it gets its own store, IndexedDB connection +// and BroadcastChannel without an iframe reloading the app's whole module graph. +async function openHistoryDocument() { + const source = new URL("./browserHistoryStore.ts", import.meta.url); + source.searchParams.set("document", randomUUID()); + const module: typeof import("./browserHistoryStore") = await import( + /* @vite-ignore */ source.href + ); + return module.useBrowserHistoryStore; } function deleteHistoryDatabase() { @@ -210,14 +196,13 @@ it("moves the legacy snapshot into the shared database", async () => { JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const first = await openHistoryDocument(documents); + const first = await openHistoryDocument(); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); expect(localStorage.getItem(storageKey)).toBeNull(); first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), ); @@ -233,8 +218,7 @@ it("persists new visits from an open document after its history database is dele JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const first = await openHistoryDocument(documents); + const first = await openHistoryDocument(); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); first.getState().removeUrl("a", page.url); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({})); @@ -243,7 +227,7 @@ it("persists new visits from an open document after its history database is dele first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ b: [otherEntry] })); } finally { await resetHistoryFixture(); @@ -257,11 +241,7 @@ it("keeps overlapping visits from independent documents", async () => { JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const [first, second] = await Promise.all([ - openHistoryDocument(documents), - openHistoryDocument(documents), - ]); + const [first, second] = await Promise.all([openHistoryDocument(), openHistoryDocument()]); first.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); second.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); const expected = { a: [page, oldEntry], b: [otherEntry] }; @@ -272,7 +252,7 @@ it("keeps overlapping visits from independent documents", async () => { // A fresh document should read the committed visits even after the legacy seed is gone. localStorage.removeItem(storageKey); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual(expected)); } finally { await resetHistoryFixture(); @@ -282,16 +262,25 @@ it("keeps overlapping visits from independent documents", async () => { it("keeps visits saved while IndexedDB could not open", async () => { await resetHistoryFixture(); try { - using documents = new DisposableStack(); - const db = await openHistoryFixture(documents); + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: {} }); - const offline = await openHistoryDocument(documents, { withoutIndexedDB: true }); - offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); - await vi.waitFor(() => - expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), - ); + vi.stubGlobal("indexedDB", { + open() { + throw new Error("blocked"); + }, + }); + try { + const offline = await openHistoryDocument(); + offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), + ); + } finally { + vi.unstubAllGlobals(); + } - const online = await openHistoryDocument(documents); + const online = await openHistoryDocument(); await vi.waitFor(() => expect(online.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), ); diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx index 0982ab1e1ccab..1baf3122a4d12 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.tsx @@ -18,6 +18,7 @@ import { type CloneProtocol, cloneUrlForProtocol, cloneUrlProtocol, + withoutRemoteUrlCredentials, } from "@t3tools/shared/cloneUrl"; import { ArrowRightIcon } from "lucide-react"; import { useId, useState } from "react"; @@ -107,10 +108,12 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const [targetId, setTargetId] = useState(request.targetEnvironmentId); const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null; const source = environments.find((env) => env.environmentId === request.projectRef.environmentId); - const sourceUrl = + // An environment on an older version reports the remote URL as configured, login included. + const sourceUrl = withoutRemoteUrlCredentials( project?.repositoryIdentity?.origin?.remoteUrl ?? - project?.repositoryIdentity?.locator.remoteUrl ?? - ""; + project?.repositoryIdentity?.locator.remoteUrl ?? + "", + ); const [protocol, setProtocol] = useState(() => cloneUrlProtocol(sourceUrl)); const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh"); const httpsUrl = cloneUrlForProtocol(sourceUrl, "https"); diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index c6006d36295db..05e49aa667b88 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -21,6 +21,7 @@ import { sanitizeNewRefName, shouldIncludeBranchPickerItem, isBranchHoldCurrent, + offersWorkspaceModes, toBranchActionErrorMessage, } from "./BranchToolbar.logic"; @@ -138,6 +139,19 @@ describe("resolveEffectiveEnvMode", () => { }); }); +describe("offersWorkspaceModes", () => { + it("offers worktrees from a repository or tracked repositories, never in No project", () => { + const folder = { isScratchProject: false, isGitRepo: false, tracksGitRepositories: false }; + expect(offersWorkspaceModes(folder)).toBe(false); + expect(offersWorkspaceModes({ ...folder, isGitRepo: true })).toBe(true); + expect(offersWorkspaceModes({ ...folder, tracksGitRepositories: true })).toBe(true); + // Git status assumes a repository until it loads. + expect(offersWorkspaceModes({ ...folder, isScratchProject: true, isGitRepo: true })).toBe( + false, + ); + }); +}); + describe("resolveLockedWorkspaceLabel", () => { it.each([ ["/home/me/.t3/worktrees/app/t3-ff466c42", "t3-ff466c42"], diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index 21e75c4d8ed56..944ebe8b937be 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -81,6 +81,16 @@ export function shouldShowEnvironmentIndicator(input: { return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary; } +/** Whether a new thread here may choose between Current checkout and New worktree. */ +export function offersWorkspaceModes(input: { + isScratchProject: boolean; + isGitRepo: boolean; + tracksGitRepositories: boolean; +}): boolean { + // No project never has git, even while its status loads and isGitRepo still assumes it does. + return !input.isScratchProject && (input.isGitRepo || input.tracksGitRepositories); +} + export function shouldShowComposerContextStrip(input: { isDraftHeroState: boolean; persistInActiveThreads: boolean; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 43ea99b07480b..4899873f06388 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -1,4 +1,5 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import { contextMenuSourceOf } from "../contextMenuSource"; import { ClipboardApiUnavailableError, ClipboardWriteError, @@ -126,10 +127,11 @@ function showWorkspaceContextMenu(event: ReactMouseEvent, workspacePath: string) event.preventDefault(); event.stopPropagation(); void api.contextMenu - .show([{ id: "copy-path", label: resolveMessage(msg("Copy full path")), icon: "copy" }], { - x: event.clientX, - y: event.clientY, - }) + .show( + [{ id: "copy-path", label: resolveMessage(msg("Copy full path")), icon: "copy" }], + { x: event.clientX, y: event.clientY }, + contextMenuSourceOf(event), + ) .then((action) => { if (action !== "copy-path") return; const clipboardPath = formatFilePathForClipboard(workspacePath); @@ -158,6 +160,8 @@ interface RunContextSelectorProps { displayMode?: "toolbar" | "panel"; workspaceRoot?: string; forceNewWorktree: boolean; + /** False when the folder has no repository a worktree could come from. */ + offersWorkspaceModes: boolean; autoEnvironmentLabel?: string | undefined; onAutoEnvironment?: (() => void) | undefined; envLocked: boolean; @@ -180,7 +184,8 @@ interface RunContextSelectorProps { const RunContextSelector = memo(function RunContextSelector({ displayMode = "toolbar", workspaceRoot, - forceNewWorktree, + forceNewWorktree: requestedForceNewWorktree, + offersWorkspaceModes, autoEnvironmentLabel, onAutoEnvironment, envLocked, @@ -190,7 +195,7 @@ const RunContextSelector = memo(function RunContextSelector({ showEnvironmentPicker, showEnvironmentIndicator, onEnvironmentChange, - effectiveEnvMode, + effectiveEnvMode: requestedEnvMode, activeWorktreePath, onEnvModeChange, previousWorktreeLabel, @@ -204,10 +209,13 @@ const RunContextSelector = memo(function RunContextSelector({ const composerFloatingLayerProps = useComposerMenuProps(); const activeEnvironment = availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null; + // A folder no worktree can come from runs threads in place, whatever mode was requested. + const forceNewWorktree = offersWorkspaceModes && requestedForceNewWorktree; + const effectiveEnvMode = offersWorkspaceModes ? requestedEnvMode : "local"; const WorkspaceIcon = effectiveEnvMode === "worktree" ? FolderGit2Icon - : activeWorktreePath + : activeWorktreePath && offersWorkspaceModes ? FolderGitIcon : FolderIcon; const workspaceLabel = forceNewWorktree @@ -218,7 +226,8 @@ const RunContextSelector = memo(function RunContextSelector({ ? resolveEnvModeLabel("worktree", m) : resolveCurrentWorkspaceLabel(activeWorktreePath, m); const isPanel = displayMode === "panel"; - const isLocked = envLocked || (envModeLocked && (!isPanel || !showEnvironmentPicker)); + const workspaceModesLocked = envModeLocked || !offersWorkspaceModes; + const isLocked = envLocked || (workspaceModesLocked && (!isPanel || !showEnvironmentPicker)); const workspacePath = forceNewWorktree || (effectiveEnvMode === "worktree" && !activeWorktreePath) ? null @@ -328,7 +337,7 @@ const RunContextSelector = memo(function RunContextSelector({ data-composer-context-control data-composer-shortcut={[ showEnvironmentPicker && !envLocked ? "composer.host" : "", - !envModeLocked ? "composer.workspace" : "", + !workspaceModesLocked ? "composer.workspace" : "", ].join(" ")} > {triggerContent} @@ -419,46 +428,52 @@ const RunContextSelector = memo(function RunContextSelector({ ) : null} - + {offersWorkspaceModes ? : null} ) : null} - - - Workspace - - { - if (value === "previous-worktree") { - onUsePreviousWorktree(); - return; - } - onEnvModeChange(value as EnvMode); - }} - > - - - {activeWorktreePath ? ( - - ) : ( - - )} - - - - - - - {resolveEnvModeLabel("worktree", m)} - - - {previousWorktreeLabel ? ( - - + {offersWorkspaceModes ? ( + + + Workspace + + { + if (value === "previous-worktree") { + onUsePreviousWorktree(); + return; + } + onEnvModeChange(value as EnvMode); + }} + > + + + {activeWorktreePath ? ( + + ) : ( + + )} + + + + + + + {resolveEnvModeLabel("worktree", m)} + - ) : null} - - + {previousWorktreeLabel ? ( + + + + ) : null} + + + ) : null} ); @@ -740,6 +755,7 @@ export const BranchToolbar = memo(function BranchToolbar({ displayMode="panel" workspaceRoot={activeProject.workspaceRoot} forceNewWorktree={forceNewWorktree} + offersWorkspaceModes={showGitControls} autoEnvironmentLabel={autoEnvironmentLabel} onAutoEnvironment={onAutoEnvironment} envLocked={envLocked} @@ -790,6 +806,7 @@ export const BranchToolbar = memo(function BranchToolbar({
[] = [ { id: "copy-branch-name", label: gt("Copy branch name"), icon: "copy" }, ]; - void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => { - if (action === "copy-branch-name") copyBranchName(branchName); - }); + void api.contextMenu + .show(items, { x: event.clientX, y: event.clientY }, contextMenuSourceOf(event)) + .then((action) => { + if (action === "copy-branch-name") copyBranchName(branchName); + }); }; const runBranchAction = (action: () => Promise) => { diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index c849678fd0b1d..7edc665210618 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -24,6 +24,16 @@ const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ filesystemMetadata: vi.fn(), })); const parsedSources = vi.hoisted(() => [] as string[]); +const nativeFileDrag = vi.hoisted(() => ({ enabled: false })); +vi.mock(import("../useNativeFileDrag"), async (original) => { + const actual = await original(); + return { + useNativeFileDrag: (...args: Parameters) => { + const drag = actual.useNativeFileDrag(...args); + return nativeFileDrag.enabled ? { ...drag, draggable: true } : drag; + }, + }; +}); vi.mock(import("../markdown/wordsHast"), async (original) => { const actual = await original(); return { @@ -180,6 +190,7 @@ function setup() { appearance.value = "light"; parsedSources.length = 0; settingsOverrides.mathRenderingEnabled = false; + nativeFileDrag.enabled = false; renderDiagram.mockReset(); threadWorktrees.clear(); workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] })); @@ -852,6 +863,43 @@ describe("ChatMarkdown inline code selection", () => { } expect(selections).toEqual(lines); }); + + it("selects the whole line on triple-click beside a desktop-draggable inline-code file chip", async () => { + setup(); + // Desktop on macOS and Windows makes local file chips draggable for native file drags. + nativeFileDrag.enabled = true; + filesystemMetadata.mockResolvedValue(AsyncResult.success({ entries: [{ kind: "file" }] })); + await using screen = await renderText( + "The template (`config/app.yaml.example`) and two docs still say 5 fps.", + { + threadRef: { + environmentId: EnvironmentId.make("workspace"), + threadId: ThreadId.make("thread"), + }, + }, + ); + await vi.waitFor(() => + expect( + screen.container.querySelector("a.chat-markdown-file-link")?.getAttribute("draggable"), + ).toBe("true"), + ); + const paragraph = screen.container.querySelector("p")!; + const text = [...paragraph.childNodes].find((node) => + node.textContent?.includes("and two docs"), + )!; + const range = document.createRange(); + range.setStart(text, text.textContent!.indexOf("and")); + range.setEnd(text, text.textContent!.indexOf("and") + 3); + const wordBox = range.getBoundingClientRect(); + const paragraphBox = paragraph.getBoundingClientRect(); + await userEvent.tripleClick(paragraph, { + position: { + x: wordBox.left - paragraphBox.left + wordBox.width / 2, + y: wordBox.top - paragraphBox.top + wordBox.height / 2, + }, + }); + expect(window.getSelection()?.toString().trim()).toBe(paragraph.textContent?.trim()); + }); }); describe("ChatMarkdown copy", () => { diff --git a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx index a072ecc107e26..645d53d630c74 100644 --- a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx @@ -96,6 +96,7 @@ vi.mock(import("../localApi"), async (original) => ({ shell: { openExternal: state.openExternal }, }) as never, })); +vi.mock(import("../env"), async (original) => ({ ...(await original()), isElectron: true })); vi.mock(import("@t3tools/client-runtime/change-request-links"), async (original) => ({ ...(await original()), resolvePullRequestPreviewTarget: () => null, @@ -323,3 +324,19 @@ it("preserves keyboard activation of a file-options button", async () => { await userEvent.click(button); await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("mouse")); }); + +it("opens an editor link over the desktop bridge on a click and on a middle-click", async () => { + using _setup = setup(); + const href = "vscode://file/work/docs/readme.md:3"; + await using screen = await renderMarkdown(`[Open in editor](${href})`); + for (const [type, button] of [ + ["click", 0], + ["auxclick", 1], + ] as const) { + const event = new MouseEvent(type, { bubbles: true, cancelable: true, button }); + await act(async () => screen.anchor().dispatchEvent(event)); + expect(event.defaultPrevented).toBe(true); + expect(state.openExternal).toHaveBeenLastCalledWith(href); + } + expect(state.openExternal).toHaveBeenCalledTimes(2); +}); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 3bd1e8d6cd9f7..c9049df115698 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -123,7 +123,7 @@ import { SharedTooltipProvider, SharedTooltipTrigger } from "./ui/shared-tooltip import { Button } from "./ui/button"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { recordVisitForThread } from "../browserHistoryStore"; -import { contextMenuSourceOf } from "../contextMenuSource"; +import { contextMenuSourceOf, openContextMenuFromKeyboard } from "../contextMenuSource"; import { PreferredEditorEnvironmentRequiredError, useOpenInPreferredEditor, @@ -722,7 +722,7 @@ function useChatMarkdownState( target !== null && resolveRemoteOpenState({ target, - sshTarget: null, + routes: [], remoteOpenTargets: undefined, isDesktopRenderer: window.desktopBridge !== undefined, hostEnvironmentId: appAtomRegistry.get(hostEnvironmentIdAtom), @@ -819,7 +819,7 @@ function useChatMarkdownState( const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null, fileLinkPeerPaths, hostFileOrigins)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); - const fileLinkPrefix = useFileLinkPrefix(fileLinkParentSuffixByPath); + const fileLinkPrefix = useFileLinkPrefix(fileLinkParentSuffixByPath, environmentId); const resolveThreadPullRequest = ( href: string, ): (ThreadPullRequestKey & { readonly url: string }) | null => { @@ -1499,7 +1499,8 @@ const CHAT_MARKDOWN_COMPONENTS = { }) !== "app" ) { // Open desktop Alt-clicks before Chromium downloads them so link routers can read the held key. - if (isElectron && event.altKey) { + // Editor links also go over IPC: the desktop popup handler only passes web links. + if (isElectron && (event.altKey || isLocalEditorFileHref(href))) { event.preventDefault(); event.stopPropagation(); void readLocalApi() @@ -1525,6 +1526,22 @@ const CHAT_MARKDOWN_COMPONENTS = { void readLocalApi()?.shell.openExternal(href); }); }} + onAuxClick={(event) => { + // A middle-click raises no click event, and the desktop popup handler only passes web links. + if (!isElectron || event.button !== 1 || !href || !isLocalEditorFileHref(href)) return; + event.preventDefault(); + void readLocalApi() + ?.shell.openExternal(href) + .catch((cause) => + reportMarkdownActionFailure( + { operation: "open-link-external", target: href }, + cause, + ), + ); + }} + onKeyDown={(event) => { + if (href && faviconHost) openContextMenuFromKeyboard(event); + }} onContextMenu={(event) => { if (!href || !faviconHost) return; event.preventDefault(); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6b0ffa7767869..971fbbb6eb33f 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2,6 +2,7 @@ import { m } from "../i18n/messages"; import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { useGT, useMessages } from "gt-react"; import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; +import { draftSupportedRuntimeModes } from "./chat/runtimeModeConfig"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; @@ -325,6 +326,7 @@ import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { + offersWorkspaceModes, resolveEffectiveEnvMode, resolveLocalCheckoutBranchMismatch, shouldShowComposerContextStrip, @@ -2348,6 +2350,11 @@ export default function ChatView(props: ChatViewProps) { activeProjectSettings.settings.newWorktreesStartFromOrigin) : false; const worktreeRepositoryChoices = useWorktreeRepositoryChoices(activeProject); + const workspaceModesOffered = offersWorkspaceModes({ + isScratchProject: activeProjectIsScratch, + isGitRepo, + tracksGitRepositories: worktreeRepositoryChoices.tracksGitRepositories, + }); const rememberedWorktreeRepositories = useRememberedWorktreeRepositories(activeProject ?? null); const sendEnvMode = resolveSendEnvMode({ requestedEnvMode: envMode, @@ -2493,7 +2500,6 @@ export default function ChatView(props: ChatViewProps) { createBrowserSurfaceStable, duplicateBrowserSurfaceStable, onOpenToolDiffStable, - onOpenTurnDiffStable, openChangesFromThreadPanelStable, openFileSurfaceStable, toggleRightPanelStable, @@ -3603,6 +3609,11 @@ export default function ChatView(props: ChatViewProps) { ? messages(activeActivityRun.providerStartingLabelMsg) : null } + providerStarting={ + activeActivityRun?.providerStartingLabelMsg + ? (activeActivityRun.providerStarting ?? null) + : null + } worktreeSetup={worktreeSetup} onCancelWorktreeSetup={onCancelWorktreeSetupStable} retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds} @@ -3633,10 +3644,8 @@ export default function ChatView(props: ChatViewProps) { {...(parentPanel === undefined || parentPanel.openToolDiff ? { onOpenToolDiff: parentPanel?.openToolDiff ?? onOpenToolDiffStable } : {})} - // Side chat runs keep no checkpoints to diff, and a fork would promote the side chat. - {...(embedded - ? {} - : { onOpenTurnDiff: onOpenTurnDiffStable, onForkFromRun: onForkFromRunStable })} + // A fork would promote the side chat. + {...(embedded ? {} : { onForkFromRun: onForkFromRunStable })} onOpenThread={onOpenRelatedThreadStable} parentThreadLink={parentThreadLink} workflowOpening={workflowOpening} @@ -3960,9 +3969,7 @@ export default function ChatView(props: ChatViewProps) { projectId={activeThread.projectId} worktreePath={activeThread.worktreePath} isServerThread={isServerThread} - showGitControls={ - isGitRepo || worktreeRepositoryChoices.tracksGitRepositories - } + showGitControls={workspaceModesOffered} showBranchControls={isGitRepo} {...(routeKind === "draft" && draftId ? { draftId } : {})} onEnvModeChange={onEnvModeChangeStable} @@ -4001,9 +4008,11 @@ export default function ChatView(props: ChatViewProps) { ), @@ -4075,6 +4084,7 @@ export default function ChatView(props: ChatViewProps) { gitCwd={gitCwd} workspaceMutationId={workspaceRevision.revision} isGitRepo={isGitRepo} + offersWorkspaceModes={workspaceModesOffered} envLocked={envLocked} availableEnvironments={logicalProjectEnvironments} autoEnvironmentLabel={autoEnvironmentLabel} diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index ff5b426c0bf3f..5047c88556353 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -555,6 +555,7 @@ it("keeps unknown dollar names editable when restoring and pasting a draft", asy it.each([ "Read https://example.com/_handle_/status/1 and open src/__test__.tsx", "see `**x**` now", + "signal = (7 * 2**3 * 5)**4", ])("sends pasted %s as pasted", async (pasted) => { await using screen = await mountEditor(""); const { editor } = screen; @@ -566,6 +567,146 @@ it.each([ expect(serializeEditorDoc(editor.state.doc).value).toBe(pasted); }); +// regression: #31079 paste rules restyled dropped text, and dropped Markdown skipped the composer's parser +it.each([ + // Shown bold like the same paste; the sent text stays verbatim. + ["signal = (7 * 2**3 * 5)**4", "signal = (7 * 23 * 5)4"], + ["a **bold** and *soft* word", "a bold and soft word"], +])("drops %s like a paste", async (dropped, shown) => { + await using screen = await mountEditor(""); + const { editor } = screen; + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", dropped); + const { left, top } = editor.view.coordsAtPos(1); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: left, + clientY: top + 1, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe(dropped); + expect(editor.state.doc.textContent).toBe(shown); + expect(editor.view.hasFocus()).toBe(true); +}); + +it("parses markdown dropped below the first line of an empty composer", async () => { + await using screen = await mountEditor(""); + const { editor } = screen; + const box = editor.view.dom.getBoundingClientRect(); + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", "a **bold** word"); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: box.left + 4, + clientY: box.bottom - 1, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe("a **bold** word"); + expect(editor.state.doc.textContent).toBe("a bold word"); +}); + +it("drops plain text on a new line below the last line", async () => { + await using screen = await mountEditor("before"); + const { editor } = screen; + const box = editor.view.dom.getBoundingClientRect(); + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", "Docs https://example.com/document\n\nsecond"); + dataTransfer.setData("text/html", 'Docs'); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: box.left + 4, + clientY: box.bottom - 1, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe( + "before\nDocs https://example.com/document\n\nsecond", + ); + await act(async () => { + editor.commands.undo(); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe("before"); +}); + +it("drops text on a list marker inside the list", async () => { + await using screen = await mountEditor("- one\n- two"); + const { editor } = screen; + const item = editor.view.dom.querySelectorAll("li")[1]!.getBoundingClientRect(); + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", "added"); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: item.left - 8, + clientY: item.top + item.height / 2, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(serializeEditorDoc(editor.state.doc).value).toMatch(/^- one\n.*added[\s\S]*- two$/); +}); + +it("drops text on a rule's edge without replacing the rule", async () => { + await using screen = await mountEditor("before\n\n---\n\nafter"); + const { editor } = screen; + let rulePos = -1; + editor.state.doc.forEach((node, offset) => { + if (node.type.name === "horizontalRule") rulePos = offset; + }); + const rule = (editor.view.nodeDOM(rulePos) as HTMLElement).getBoundingClientRect(); + await act(async () => { + const dataTransfer = new DataTransfer(); + dataTransfer.setData("text/plain", "dropped"); + editor.view.dom.dispatchEvent( + new DragEvent("drop", { + dataTransfer, + clientX: rule.left + rule.width / 2, + clientY: rule.top, + bubbles: true, + cancelable: true, + }), + ); + }); + const value = serializeEditorDoc(editor.state.doc).value; + expect(value).toContain("---"); + expect(value).toContain("dropped"); +}); + +it.each([ + ["**DEV**", "**DEV**!"], + ["*DEV*", "*DEV*!"], + ["~~DEV~~", "~~DEV~~!"], + ["`DEV`", "`DEV`!"], + ["***DEV***", "***DEV***!"], +])("types after the closing markers of pasted %s", async (pasted, typed) => { + await using screen = await mountEditor(""); + const { editor } = screen; + await act(async () => { + editor.view.focus(); + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", pasted); + editor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true })); + }); + await userEvent.keyboard("!"); + expect(serializeEditorDoc(editor.state.doc).value).toBe(typed); +}); + it.each([ { literalText: false, imports: 1 }, { literalText: true, imports: 0 }, @@ -682,6 +823,54 @@ it("reopens a long draft scrolled to its caret without taking focus", async () = expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1); }); +it.each(["none", "caret", "selection"] as const)( + "keeps the reading position when a draft rewraps (focus: %s)", + async (focus) => { + const focused = focus !== "none"; + const value = "A long wrapped paragraph should keep the sentence being read in view. ".repeat( + 100, + ); + const style = document.head.appendChild(document.createElement("style")); + style.textContent = ".composer-tiptap { width: 700px; max-height: 160px; overflow-y: auto; }"; + using _style = { [Symbol.dispose]: () => style.remove() }; + await using screen = await mountEditor(value); + const { editor } = screen; + const scroller = editor.view.dom; + await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(500)); + if (focused) await focusAt(editor, 2000); + scroller.scrollTop = 300; + scroller.dispatchEvent(new Event("scroll")); + const box = scroller.getBoundingClientRect(); + const position = editor.view.posAtCoords({ + left: box.left + box.width / 2, + top: box.top + 25, + })!; + const before = editor.view.coordsAtPos(position.pos).top - box.top; + if (focused) await focusAt(editor, position.pos); + if (focus === "selection") { + editor.commands.setTextSelection({ from: position.pos, to: position.pos + 20 }); + } + document.dispatchEvent(new Event("selectionchange")); + const selection = editor.state.selection.toJSON(); + for (const width of [420, 700]) { + // The panel toggle shortcut reaches the focused editor before the width changes. + if (focused) { + scroller.dispatchEvent( + new KeyboardEvent("keydown", { key: "b", ctrlKey: true, altKey: true, bubbles: true }), + ); + } + scroller.style.width = `${width}px`; + await vi.waitFor(() => { + const after = + editor.view.coordsAtPos(position.pos).top - scroller.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(25); + }); + expect(editor.state.selection.toJSON()).toEqual(selection); + expect(editor.view.hasFocus()).toBe(focused); + } + }, +); + 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; diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 10e5f68be5b06..4621d1f9ddf42 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -64,6 +64,7 @@ import { pastedPathQueryLength, } from "~/composer-logic"; import { useStableCallback } from "~/hooks/useStableCallback"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction"; import { collapseShownMarkdownSource, @@ -1172,6 +1173,114 @@ function ComposerPromptEditorTiptapInner( "aria-placeholder": placeholder, }; + /** `newLineAt` inserts on a fresh line created at that block boundary, in the same undo step. */ + const insertClipboardText = ( + view: EditorView, + clipboardData: DataTransfer, + newLineAt?: number, + ): boolean => { + const pastedText = readPastedPlainText(clipboardData); + if (!pastedText) return false; + const onNewLine = newLineAt !== undefined; + // Paste verbatim inside fences; markdown parsing would split blocks and create unsupported chips. + if (!onNewLine && isInCodeBlock(view)) { + const { from, to } = view.state.selection; + view.dispatch( + markAsClipboardEdit( + view.state.tr.insertText(pastedText, from, to), + "paste", + ).scrollIntoView(), + ); + return true; + } + // Shown Markdown source is parsed when the caret leaves, so paste one line into it as text. + const sourceType = view.state.schema.marks[MARKDOWN_SOURCE_MARK]; + const { from: pasteFrom, to: pasteTo, $from: $pasteFrom } = view.state.selection; + if ( + !onNewLine && + sourceType?.isInSet($pasteFrom.marks()) && + !pastedText.includes("\n") && + collectComposerPromptInlineTokens(`${pastedText}\n`).length === 0 + ) { + view.dispatch( + markAsClipboardEdit( + view.state.tr.insertText(pastedText, pasteFrom, pasteTo), + "paste", + ).scrollIntoView(), + ); + return true; + } + const importFragment = readCallbacks().importContextFragment; + let text = + !literalText && importFragment + ? importPastedComposerText(clipboardData, importFragment) + : pastedText; + const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`); + const isChip = (token: (typeof tokens)[number] | undefined) => + token?.type === "mention" || + (token?.type === "skill" && skillLabelFor(token.value) !== null) || + (token?.type === "model" && isKnownModel(token.instanceId, token.model)); + const lastToken = tokens.at(-1); + if (isChip(lastToken) && lastToken?.end === text.length) { + text += " "; + } + if (!onNewLine && isChip(tokens[0]) && tokens[0]?.start === 0) { + const map = serializeEditorDoc(view.state.doc); + const offset = flatToMarkdown(map, pmToFlat(map, view.state.selection.from)); + if (offset > 0 && !/\s/.test(map.value[offset - 1]!)) text = ` ${text}`; + } + const { $from } = view.state.selection; + const lineBefore = onNewLine + ? "" + : $from.parent.textBetween(0, $from.parentOffset, undefined, "\uFFFC"); + const literalLength = literalText + ? 0 + : pastedPathQueryLength(lineBefore, text, readCallbacks().isPathQueryActive?.()); + const editorInstance = (view.dom as TiptapEditorHTMLElement).editor; + if (editorInstance) { + const $paste = onNewLine ? view.state.doc.resolve(newLineAt) : view.state.selection.$from; + const nested = ["listItem", "taskItem", "blockquote"].some((name) => + hasAncestor($paste, name), + ); + insertMarkdownParagraphs( + text, + skillLabelFor, + { styling: richText, blocks: !nested, literalText, literalLength, isKnownModel }, + (content) => { + editorInstance + .chain() + .command(({ tr }) => { + markAsClipboardEdit(tr, "paste"); + if (onNewLine) { + tr.insert(newLineAt, tr.doc.type.schema.nodes.paragraph!.create()); + tr.setSelection(TextSelection.create(tr.doc, newLineAt + 1)); + } + return true; + }) + // Pasted chips and lines would split shown Markdown, so parse it first. + .command(collapseShownMarkdownSource) + .insertContent(content) + .command(({ tr }) => { + // Move after a pasted rule so the next keystroke cannot replace it; add a trailing line + // if needed. + const { selection } = tr; + if (!(selection instanceof NodeSelection) || !selection.node.isBlock) { + return true; + } + if (!tr.doc.resolve(selection.to).nodeAfter?.isTextblock) { + tr.insert(selection.to, tr.doc.type.schema.nodes.paragraph!.create()); + } + tr.setSelection(TextSelection.create(tr.doc, selection.to + 1)); + return true; + }) + .run(); + }, + ); + scrollTiptapCaretIntoView(editorInstance); + } + return true; + }; + const editor = useEditor( { extensions: richText ? RICH_TEXT_EXTENSIONS : PLAIN_TEXT_EXTENSIONS, @@ -1181,6 +1290,8 @@ function ComposerPromptEditorTiptapInner( isKnownModel: (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)), }), editable: !disabled, + // The composer parses pasted and dropped text itself; paste rules would restyle literal `*`. + enablePasteRules: false, editorProps: { attributes: editorAttributes, handleDOMEvents: { @@ -1468,100 +1579,39 @@ function ComposerPromptEditorTiptapInner( (literalText || !readPastedComposerContext(clipboardData)?.records.length) ) return false; - const pastedText = readPastedPlainText(clipboardData); - if (!pastedText) return false; + if (!insertClipboardText(view, clipboardData)) return false; event.preventDefault(); - // Paste verbatim inside fences; markdown parsing would split blocks and create unsupported chips. - if (isInCodeBlock(view)) { - const { from, to } = view.state.selection; - view.dispatch( - markAsClipboardEdit( - view.state.tr.insertText(pastedText, from, to), - "paste", - ).scrollIntoView(), - ); - return true; - } - // Shown Markdown source is parsed when the caret leaves, so paste one line into it as text. - const sourceType = view.state.schema.marks[MARKDOWN_SOURCE_MARK]; - const { from: pasteFrom, to: pasteTo, $from: $pasteFrom } = view.state.selection; - if ( - sourceType?.isInSet($pasteFrom.marks()) && - !pastedText.includes("\n") && - collectComposerPromptInlineTokens(`${pastedText}\n`).length === 0 - ) { - view.dispatch( - markAsClipboardEdit( - view.state.tr.insertText(pastedText, pasteFrom, pasteTo), - "paste", - ).scrollIntoView(), - ); - return true; - } - const importFragment = readCallbacks().importContextFragment; - let text = - !literalText && importFragment - ? importPastedComposerText(clipboardData, importFragment) - : pastedText; - const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`); - const isChip = (token: (typeof tokens)[number] | undefined) => - token?.type === "mention" || - (token?.type === "skill" && skillLabelFor(token.value) !== null) || - (token?.type === "model" && isKnownModel(token.instanceId, token.model)); - const lastToken = tokens.at(-1); - if (isChip(lastToken) && lastToken?.end === text.length) { - text += " "; - } - if (isChip(tokens[0]) && tokens[0]?.start === 0) { - const map = serializeEditorDoc(view.state.doc); - const offset = flatToMarkdown(map, pmToFlat(map, view.state.selection.from)); - if (offset > 0 && !/\s/.test(map.value[offset - 1]!)) text = ` ${text}`; - } - const { $from } = view.state.selection; - const lineBefore = $from.parent.textBetween(0, $from.parentOffset, undefined, "\uFFFC"); - const literalLength = literalText - ? 0 - : pastedPathQueryLength(lineBefore, text, readCallbacks().isPathQueryActive?.()); - const editorInstance = (view.dom as TiptapEditorHTMLElement).editor; - if (editorInstance) { - const $paste = view.state.selection.$from; - const nested = ["listItem", "taskItem", "blockquote"].some((name) => - hasAncestor($paste, name), - ); - insertMarkdownParagraphs( - text, - skillLabelFor, - { styling: richText, blocks: !nested, literalText, literalLength, isKnownModel }, - (content) => { - editorInstance - .chain() - .command(({ tr }) => { - markAsClipboardEdit(tr, "paste"); - return true; - }) - // Pasted chips and lines would split shown Markdown, so parse it first. - .command(collapseShownMarkdownSource) - .insertContent(content) - .command(({ tr }) => { - // Move after a pasted rule so the next keystroke cannot replace it; add a trailing line - // if needed. - const { selection } = tr; - if (!(selection instanceof NodeSelection) || !selection.node.isBlock) { - return true; - } - if (!tr.doc.resolve(selection.to).nodeAfter?.isTextblock) { - tr.insert(selection.to, tr.doc.type.schema.nodes.paragraph!.create()); - } - tr.setSelection(TextSelection.create(tr.doc, selection.to + 1)); - return true; - }) - .run(); - }, - ); - scrollTiptapCaretIntoView(editorInstance); - } return true; }, + handleDrop: (view, event, _slice, moved) => { + const data = event.dataTransfer; + // Files and drags that start inside the editor keep ProseMirror's own drop. + if (moved || view.dragging || !data || data.files.length > 0) return false; + const target = view.posAtCoords({ left: event.clientX, top: event.clientY }); + if (!target || !readPastedPlainText(data)) return false; + let pos = target.pos; + const $target = view.state.doc.resolve(pos); + if (!$target.parent.inlineContent) { + // Between blocks, fill an adjacent empty paragraph (the padding of an empty composer) or start + // a new line at the drop point; a nearby selection would replace or join a block. + const isEmptyParagraph = (node: typeof $target.nodeAfter) => + node?.type.name === "paragraph" && node.content.size === 0; + if (isEmptyParagraph($target.nodeAfter)) pos += 1; + else if (isEmptyParagraph($target.nodeBefore)) pos -= 1; + else { + const index = $target.index(); + const paragraph = view.state.schema.nodes.paragraph!; + // Between list items a paragraph does not fit; ProseMirror's drop adds an item there. + if (!$target.parent.canReplaceWith(index, index, paragraph)) return false; + view.focus(); + return insertClipboardText(view, data, pos); + } + } + view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, pos))); + // Handling the drop skips ProseMirror's own focus call. + view.focus(); + return insertClipboardText(view, data); + }, }, onUpdate: ({ editor: updated, transaction }) => { // Undo can restore a chip for a skill or model the environment no longer offers. @@ -1778,6 +1828,11 @@ function ComposerPromptEditorTiptapInner( if (replacements.length > 0) replaceSkillChips(editor, replacements); }, [editor, literalText, modelKeys, skills]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the mounted editor's visible text anchored while its DOM width changes + useLayoutEffect(() => { + if (editor) return preserveReadingPosition(editor.view.dom); + }, [editor]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown useLayoutEffect(() => { if (!editor) return; diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 13b6ed8982513..87b076271807e 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -128,6 +128,22 @@ describe("when: on default ref without open PR", () => { }); }); + it("resolveQuickAction pushes without committing when the tree is clean and ahead", () => { + const withUpstream = resolveQuickAction( + status({ refName: "main", aheadCount: 1 }), + false, + true, + ); + assert.deepInclude(withUpstream, { kind: "run_action", action: "push", label: "Push" }); + + const withoutUpstream = resolveQuickAction( + status({ refName: "main", aheadCount: 1, hasUpstream: false }), + false, + true, + ); + assert.deepInclude(withoutUpstream, { kind: "run_action", action: "push", label: "Push" }); + }); + it("offers a feature branch only to actions that commit the changes", () => { const reason = (action: DefaultBranchConfirmableAction, hasWorkingTreeChanges: boolean) => resolveFeatureBranchUnavailableReason({ action, branchName: "main", hasWorkingTreeChanges }); diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index 81ab7a51ad3db..eb13b53f95d7d 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -401,7 +401,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultRef ? "commit_push" : "push", + action: "push", }; } return { @@ -439,7 +439,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultRef ? "commit_push" : "push", + action: "push", }; } return { diff --git a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx index d2a15729b0df2..eac4340104929 100644 --- a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx @@ -24,9 +24,22 @@ describe("HistorySwipeNavigation", () => { false, ], ["scrolling left inside a scroller keeps the thread", "light", 100, -130, false], - ["swiping back at a shadow-root scroller's left edge navigates", "shadow", 0, -130, true], + ["scrolling at a shadow-root scroller's left edge keeps the thread", "shadow", 0, -130, false], + [ + "scrolling at a shadow-root scroller's right edge keeps the thread", + "shadow", + 800, + 130, + false, + ], + ["scrolling at a scroller's left edge keeps the thread", "light", 0, -130, false], + ["scrolling at a scroller's right edge keeps the thread", "light", 800, 130, false], + ["scrolling over a preview panel keeps the thread", "preview-panel", 0, -130, false], + ["scrolling over a desktop preview keeps the thread", "preview-viewport", 0, 130, false], + ["scrolling over a streamed preview keeps the thread", "server-browser", 0, -130, false], ["swiping back over a panel without overflow navigates", "none", 0, -130, true], ["a swipe that started in a closed dialog keeps the thread", "closed-dialog", 0, -130, false], + ["swiping back over an open alert dialog keeps the thread", "alertdialog", 0, -130, false], ] as const)("%s", async (_name, scroller, scrollLeft, deltaX, navigates) => { navigateHistory.mockReset(); using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); @@ -34,7 +47,11 @@ describe("HistorySwipeNavigation", () => { const panel = screen.container.appendChild(document.createElement("div")); const root = scroller.startsWith("shadow") ? panel.attachShadow({ mode: "open" }) : panel; const viewport = root.appendChild(document.createElement("div")); - const noOverflow = scroller === "none" || scroller === "closed-dialog"; + const noOverflow = !scroller.startsWith("shadow") && scroller !== "light"; + if (scroller === "preview-panel") panel.setAttribute("data-preview-panel-mode", "inline"); + if (scroller === "preview-viewport") panel.setAttribute("data-preview-viewport", "tab"); + if (scroller === "server-browser") panel.setAttribute("data-server-browser-surface", "tab"); + if (scroller === "alertdialog") panel.setAttribute("role", "alertdialog"); viewport.style.cssText = `width: 200px; overflow-x: ${noOverflow ? "visible" : "auto"}`; const content = viewport.appendChild(document.createElement("div")); content.style.cssText = `height: 20px; width: ${noOverflow ? 100 : 1000}px`; @@ -72,6 +89,32 @@ describe("HistorySwipeNavigation", () => { expect(navigateHistory).not.toHaveBeenCalled(); }); + it.each([ + ["Shift-scroll keeps the thread", [[-130, true]]], + [ + "pressing Shift during a swipe cancels navigation", + [ + [-130, false], + [-1, true], + ], + ], + [ + "releasing Shift during a scroll keeps the thread", + [ + [-1, true], + [-130, false], + ], + ], + ] as const)("%s", async (_name, events) => { + navigateHistory.mockReset(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await using screen = await render(); + for (const [deltaX, shiftKey] of [...events, [0, false] as const]) { + screen.container.dispatchEvent(new WheelEvent("wheel", { deltaX, shiftKey, bubbles: true })); + } + expect(navigateHistory).not.toHaveBeenCalled(); + }); + // A vertical scroll 15° off vertical. const drift = Array.from({ length: 30 }, () => [-4, 15] as const); it.each([ diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx index 2924f82cd3136..537cdcd57afc6 100644 --- a/apps/web/src/components/HistorySwipeNavigation.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -44,16 +44,12 @@ function readMainContentBounds(): SwipeBounds { } // `event.target` stops at a shadow host; the composed path also reaches scrollers inside it. -function canScrollHorizontally(path: readonly EventTarget[], deltaX: number): boolean { +function hasHorizontalScroller(path: readonly EventTarget[]): boolean { for (const element of path) { if (!(element instanceof Element) || element.scrollWidth <= element.clientWidth) continue; const { overflowX } = getComputedStyle(element); if (overflowX !== "auto" && overflowX !== "scroll") continue; - const canScroll = - deltaX < 0 - ? element.scrollLeft > 0 - : element.scrollLeft + element.clientWidth < element.scrollWidth - 1; - if (canScroll) return true; + return true; } return false; } @@ -71,10 +67,19 @@ function lockSwipeAxis( if (Math.abs(sumX) <= Math.abs(sumY) || isVerticalScroll(Math.abs(sumX), Math.abs(sumY))) { return { kind: "ignored" }; } - if (path.some((node) => node instanceof Element && node.matches('[role="dialog"]'))) { + // Preview contents can scroll in another document or on the server, outside this DOM. + if ( + path.some( + (node) => + node instanceof Element && + node.matches( + '[role="dialog"], [role="alertdialog"], [data-preview-panel-mode], [data-preview-viewport], [data-server-browser-surface]', + ), + ) + ) { return { kind: "ignored" }; } - if (canScrollHorizontally(path, sumX)) return { kind: "ignored" }; + if (hasHorizontalScroller(path)) return { kind: "ignored" }; const direction = sumX < 0 ? "back" : "forward"; if (!canNavigateHistory(direction)) return { kind: "ignored" }; return { @@ -134,6 +139,11 @@ export function HistorySwipeNavigation() { gesture = null; }); const onWheel = (event: WheelEvent) => { + if (event.shiftKey) { + if (gesture?.kind === "tracking") hideIndicator(); + gesture = { kind: "ignored" }; + return; + } if (gesture === null) { gesture = event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index 515d5cdbfb32b..347971993c7c3 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -68,7 +68,7 @@ const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ( })); describe("RightPanelTabs", () => { - it("a flick that scrolls the tab strip to its left edge keeps the thread, a swipe from the edge goes back", async () => { + it("a flick that scrolls the tab strip to its left edge keeps the thread, and so does a swipe from the edge", async () => { navigateHistory.mockReset(); const { bridge, scroll } = trackpad(); using _bridge = stubGlobal("desktopBridge", bridge); @@ -139,7 +139,7 @@ describe("RightPanelTabs", () => { viewport.scrollLeft = 0; scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]); - expect(navigateHistory).toHaveBeenCalledExactlyOnceWith("back"); + expect(navigateHistory).not.toHaveBeenCalled(); }); }); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 34963cd73af99..62606cdb2cebe 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1,4 +1,5 @@ import { msg, T, useGT, useMessages } from "gt-react"; +import { contextMenuSourceOf } from "../contextMenuSource"; import { m, type MessageResolver } from "../i18n/messages"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; @@ -1419,10 +1420,11 @@ export function RightPanelTabs(props: RightPanelTab ...(pane?.tabMenu.items(surface) ?? []), ); - const action = await api.contextMenu.show(withChatClosing(items, surface, props.surfaces), { - x: event.clientX, - y: event.clientY, - }); + const action = await api.contextMenu.show( + withChatClosing(items, surface, props.surfaces), + { x: event.clientX, y: event.clientY }, + contextMenuSourceOf(event), + ); switch (action) { case "open-in-main-view": if (surface.kind === "thread" || surface.kind === "linked-thread") { diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index fb975ed3b767d..6c32f4d6ab604 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -25,6 +25,7 @@ import { useNowMinute } from "../hooks/useNowMinute"; import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities"; +import { useConnectedEnvironmentIds, usePrimaryEnvironmentId } from "../state/environments"; import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; @@ -40,6 +41,7 @@ vi.mock(import("../state/olderSettledShelf"), async (original) => { return { ...actual, useOlderSettledShelf: vi.fn(actual.useOlderSettledShelf) }; }); vi.mock("../state/entities", { spy: true }); +vi.mock("../state/environments", { spy: true }); vi.mock("../hooks/useHandleNewThread", { spy: true }); vi.mock("../hooks/useNowMinute", { spy: true }); vi.mock("../hooks/useThreadRouteTarget", { spy: true }); @@ -132,6 +134,65 @@ describe("sidebar header new thread", () => { }); }); +// regression: #41549 a grouped project's folder New thread went to the primary copy +describe("sidebar project folder new thread", () => { + it("starts in the copy of the viewed thread, as the new-thread shortcut does", async () => { + using stack = new DisposableStack(); + const previousSettings = getClientSettings(); + stack.defer(() => __setClientSettingsForTests(previousSettings)); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, boringSidebarEnabled: true }); + const primary = EnvironmentId.make("local"); + const dev1 = EnvironmentId.make("dev1"); + const repositoryIdentity = { + canonicalKey: "github.com/acme/demo-repo", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "https://github.com/acme/demo-repo.git", + }, + displayName: "acme/demo-repo", + }; + const primaryCopy = { ...project("demo-primary"), repositoryIdentity }; + const dev1Copy = { + ...project("demo-dev1"), + environmentId: dev1, + repositoryIdentity, + }; + vi.mocked(usePrimaryEnvironmentId).mockReturnValue(primary); + vi.mocked(useConnectedEnvironmentIds).mockReturnValue([primary, dev1]); + vi.mocked(useProjects).mockReturnValue([primaryCopy, dev1Copy]); + const dev1Thread = makeThreadFixture({ + environmentId: dev1, + id: ThreadId.make("dev1-thread"), + projectId: dev1Copy.id, + title: "dev1 work", + }); + vi.mocked(useQuietThreadShells).mockReturnValue([dev1Thread]); + const threadRef = scopeThreadRef(dev1, dev1Thread.id); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef }); + const dev1ProjectRef = scopeProjectRef(dev1, dev1Copy.id); + const startThread = vi.fn().mockResolvedValue(null); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: dev1Thread, + defaultProjectRef: dev1ProjectRef, + defaultProjectFallbackReady: true, + handleNewThread: startThread, + routeDraftId: null, + routeThreadRef: threadRef, + }); + + await using screen = await render( + + + , + ); + await userEvent.click(screen.getByRole("button", { name: "New thread in acme/demo-repo" })); + + expect(startThread).toHaveBeenCalledExactlyOnceWith(dev1ProjectRef); + }); +}); + // regression: #38623 unsent drafts are listed above threads but mod+1..9 skipped them describe("sidebar numbered jumps", () => { it("numbers the unsent draft at the top before the threads below it", async () => { @@ -337,6 +398,57 @@ describe("sidebar thread rename", () => { ); }); +describe("sidebar thread click", () => { + // regression: #40715 macOS counts quick clicks on different rows, so the next row got detail 2 and was ignored + it("opens another thread when the click arrives with a double-click count", async () => { + const activeProject = project("active"); + const threads = [threadShell(activeProject.id, 0), threadShell(activeProject.id, 1)]; + const routeThreadRef: ScopedThreadRef = { + environmentId: activeProject.environmentId, + threadId: threads[0]!.id, + }; + vi.mocked(useProjects).mockReturnValue([activeProject]); + vi.mocked(useQuietThreadShells).mockReturnValue(threads); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef, + }); + await using screen = await render( + + + , + { router: "/local/thread-0" }, + ); + const navigate = vi.spyOn(screen.router!, "navigate").mockResolvedValue(undefined); + + const openRow = screen.getByText("Thread 0").first().element(); + await act(() => { + openRow.dispatchEvent( + new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 }), + ); + }); + expect(navigate).not.toHaveBeenCalled(); + + const row = screen.getByText("Thread 1").first().element(); + await act(() => { + row.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 })); + }); + + expect(navigate).toHaveBeenCalledWith( + expect.objectContaining({ params: expect.objectContaining({ threadId: "thread-1" }) }), + ); + }); +}); + describe("sidebar thread menu", () => { it("tells the menu whether the keyboard opened it", async () => { const activeProject = project("active"); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 2f28e35ceb0ef..403653fb3c170 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -114,6 +114,7 @@ import { selectProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; import { + buildSidebarProjectPickerEntries, projectGroupsSpanEnvironments, resolveSidebarProjectScopeKeys, getSidebarProjectSettingsKey, @@ -135,7 +136,7 @@ import { useProjectPin } from "../hooks/useProjectGroupUpdate"; import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { registerSettleAndAdvance } from "../settleAndAdvance"; -import { startNewThreadFromContext } from "../lib/chatThreadActions"; +import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions"; import { useClientSettings } from "../hooks/useSettings"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; @@ -1271,7 +1272,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const startThreadInProjectFolder = useStableCallback((group: SidebarProjectSnapshot) => { if (isMobile) setOpenMobile(false); - void handleNewThread(scopeProjectRef(group.environmentId, group.id)); + const [entry] = buildSidebarProjectPickerEntries({ + groups: [group], + preferredProjectRef: resolveThreadActionProjectRef({ + ...newThreadContext, + activeThread: newThreadContext.activeThread ?? undefined, + }), + }); + const target = entry?.targetProject ?? group; + void handleNewThread(scopeProjectRef(target.environmentId, target.id)); }); const handleProjectFolderContextMenu = useStableCallback( ( @@ -1616,7 +1625,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve rangeSelectTo(threadKey, orderedThreadKeysRef.current); return; } - if (isTrailingDoubleClick(event.detail)) { + // macOS keeps counting quick clicks across rows, so only the open row's trailing click is a double-click. + if (isTrailingDoubleClick(event.detail) && routeThreadKey === threadKey) { return; } navigateToThread(threadRef); @@ -2718,6 +2728,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), isRegeneratingTitle, isRunning: !threadRuntimeCanArchive(thread.runtime), + hasCompletedRun: thread.latestRun?.completedAt != null, canShareWithGuest: appAtomRegistry.get( canShareWithGuestAtom(threadRef.environmentId), ), diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index 7da8504990fe6..6b2414dfaf38b 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -16,6 +16,7 @@ const state = vi.hoisted(() => ({ shells: null as unknown as { set: (id: string, value: unknown) => void }, navigate: vi.fn(), sound: vi.fn(), + unlock: vi.fn(), badge: vi.fn(), settingsListeners: new Set<() => void>(), })); @@ -80,7 +81,7 @@ vi.mock(import("../hooks/useSettings"), async (original) => ({ vi.mock(import("../threadNotifications"), async (original) => ({ ...(await original()), playNotificationSound: state.sound, - unlockNotificationAudio: vi.fn(), + unlockNotificationAudio: state.unlock, setNotificationBadge: state.badge, })); @@ -293,6 +294,19 @@ it("presents completion notifications and sound as soon as the shell completes", expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function)); }); +it.each([ + { client: "desktop app", when: "at startup", bridge: {}, beforeGesture: 1 }, + { client: "browser", when: "on the first gesture", bridge: undefined, beforeGesture: 0 }, +])("readies notification sound in the $client $when", async ({ bridge, beforeGesture }) => { + await using app = setup(); + using _bridge = stubGlobal("desktopBridge", bridge); + state.mode = "sound"; + app.start(); + expect(state.unlock).toHaveBeenCalledTimes(beforeGesture); + document.dispatchEvent(new Event("pointerdown")); + expect(state.unlock).toHaveBeenCalledTimes(beforeGesture + 1); +}); + it.each([false, true])( "presents one completion when a monitor ends with a final wake (disconnected: %s)", async (disconnect) => { diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index e2801c97d6e8d..7f91d48643bbf 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -408,6 +408,8 @@ export function startThreadNotifications( }); } if (hasNotificationSound(nextMode)) { + // Electron's default autoplay policy needs no gesture, unlike browsers. + if (window.desktopBridge) unlockNotificationAudio(); document.addEventListener("pointerdown", unlockNotificationAudio); document.addEventListener("keydown", unlockNotificationAudio); stops.push(() => { diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 905d9cb2131fe..71d626fd4c1ac 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -479,7 +479,7 @@ function PullRequestBadge({ className={cn("contents font-normal text-xs tabular-nums", presentation.toneClassName)} > - {presentation.text} + {presentation.text} ({ connect: vi.fn() })); + +vi.mock("../../connection/onboarding", () => ({ connectPairing: {} })); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.connect })); +vi.mock("../../environments/primary", () => ({ + peekPairingTokenFromUrl: () => null, + stripPairingTokenFromUrl: () => undefined, + submitServerAuthCredential: () => Promise.resolve(), +})); +vi.mock("../../hostedPairing", () => ({ + readHostedPairingRequest: () => ({ host: "backend.example.com", token: "one-time", label: "" }), +})); + +import { HostedPairingRouteSurface } from "./PairingRouteSurface"; + +it("sends a link's pairing token only after the user confirms the backend", async () => { + state.connect.mockReset(); + state.connect.mockResolvedValue(AsyncResult.success(undefined)); + await using screen = await render(); + + await expect.element(screen.getByText("https://backend.example.com")).toBeVisible(); + expect(state.connect).not.toHaveBeenCalled(); + + await screen.getByRole("button", { name: "Add backend" }).click(); + await vi.waitFor(() => + expect(state.connect).toHaveBeenCalledExactlyOnceWith({ + host: "backend.example.com", + pairingCode: "one-time", + }), + ); +}); diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx index 57a5e79241ac3..f6ec70432ad8b 100644 --- a/apps/web/src/components/auth/PairingRouteSurface.tsx +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -11,6 +11,7 @@ import { submitServerAuthCredential, } from "../../environments/primary"; import { readHostedPairingRequest } from "../../hostedPairing"; +import { resolveRemotePairingTarget } from "@t3tools/shared/remote"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page"; @@ -146,17 +147,31 @@ export function HostedPairingRouteSurface() { reportFailure: false, }); const [request] = useState(readHostedPairingRequest); + // The origin shows the scheme along with the host. + const [origin] = useState(() => { + if (!request) return null; + try { + return new URL( + resolveRemotePairingTarget({ host: request.host, pairingCode: request.token }).httpBaseUrl, + ).origin; + } catch { + return null; + } + }); const gt = useGT(); - const [status, setStatus] = useState<"pairing" | "paired" | "error">( - request ? "pairing" : "error", + const [status, setStatus] = useState<"confirm" | "pairing" | "paired" | "error">( + origin ? "confirm" : "error", ); const [message, setMessage] = useState(() => - request - ? m(msg("Connecting to this backend.")) - : m(msg("This pairing link is missing its backend host or token.")), + origin + ? m(msg("This link adds a backend to this browser. Continue only if you trust it.")) + : request + ? m(msg("This pairing link has an invalid backend host.")) + : m(msg("This pairing link is missing its backend host or token.")), ); const [canRetry, setCanRetry] = useState(false); - const submitAttemptedRef = useRef(false); + // Nothing is sent to the link's host until the user confirms. + // The token stays in the URL until then: the root route picks this page from it. const tokenSubmittedRef = useRef(false); const submitHostedPairingRequest = async () => { @@ -180,6 +195,7 @@ export function HostedPairingRouteSurface() { setMessage(gt("Connecting to this backend.")); setCanRetry(false); tokenSubmittedRef.current = true; + stripPairingTokenFromUrl(); const result = await connectPairingEnvironment({ host: request.host, @@ -206,21 +222,6 @@ export function HostedPairingRouteSurface() { ); }; - const submitOnMount = useEffectEvent(() => { - void submitHostedPairingRequest(); - }); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- strips the pairing token from the URL and submits the hosted pairing request once on mount - useEffect(() => { - if (submitAttemptedRef.current) { - return; - } - submitAttemptedRef.current = true; - - stripPairingTokenFromUrl(); - submitOnMount(); - }, []); - return ( @@ -239,7 +242,7 @@ export function HostedPairingRouteSurface() { Host:{" "} - {request.host} + {origin ?? request.host}
@@ -257,7 +260,23 @@ export function HostedPairingRouteSurface() { ) : null}
- {status === "pairing" ? ( + {status === "confirm" ? ( + <> + + + + ) : status === "pairing" ? ( diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx deleted file mode 100644 index 387c3b3d51868..0000000000000 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ /dev/null @@ -1,548 +0,0 @@ -import { useSyncLayout } from "@legendapp/list/react"; -import { type OrchestrationV2CheckpointFileTotals, type RunId } from "@t3tools/contracts"; -import { T, useGT } from "gt-react"; -import { type MouseEvent, type ReactNode, memo, useLayoutEffect, useRef, useState } from "react"; -import { type TurnDiffFileChange } from "../../types"; -import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree"; -import { - ChevronRightIcon, - FileDiffIcon, - ChevronsDownUpIcon, - ChevronsUpDownIcon, - FolderClosedIcon, - FolderGit2Icon, - FolderIcon, -} from "lucide-react"; -import { cn } from "~/lib/utils"; -import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel"; -import { PierreEntryIcon } from "./PierreEntryIcon"; -import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { MiddleTruncate } from "../ui/middle-truncate"; -import { observeResize } from "~/lib/observeResize"; -import { repositoryFilePath } from "@t3tools/client-runtime/state/thread-repositories"; - -const EMPTY_DIRECTORY_OVERRIDES: Record = {}; -const VIRTUALIZE_AFTER_ROWS = 250; -const ROW_OVERSCAN = 8; - -interface ChangedFileRow { - node: TurnDiffTreeNode; - depth: number; -} - -/** One folder's share of a turn that changed several repositories. */ -export interface ChangedFilesGroup { - readonly key: string; - readonly name: string; - /** Paths relative to this group's folder. */ - readonly files: ReadonlyArray; - readonly totals: OrchestrationV2CheckpointFileTotals; - /** The folder from the thread's folder; undefined when the diff cannot be opened at a file. */ - readonly relativePath: string | undefined; - /** Shown in place of the files when they cannot be listed. */ - readonly note?: string | undefined; -} - -type ChangedFileContextMenuHandler = ( - filePath: string, - event: MouseEvent, - group?: ChangedFilesGroup, -) => void; - -function groupDiffPath(group: ChangedFilesGroup, filePath: string | undefined) { - return filePath === undefined || group.relativePath === undefined - ? undefined - : repositoryFilePath(group.relativePath, filePath); -} - -export const ChangedFilesCard = memo(function ChangedFilesCard(props: { - runId: RunId; - /** May be a prefix of the changed files; `totals` covers all of them. */ - files: ReadonlyArray; - totals: OrchestrationV2CheckpointFileTotals; - /** Set when the turn changed tracked repositories; replaces the single tree built from `files`. */ - groups?: ReadonlyArray | undefined; - allDirectoriesExpanded: boolean; - resolvedTheme: "light" | "dark"; - onToggleAllDirectories: () => void; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; - onFileContextMenu?: ChangedFileContextMenuHandler | undefined; -}) { - const { - runId, - files, - totals, - groups, - allDirectoriesExpanded, - resolvedTheme, - onToggleAllDirectories, - onOpenTurnDiff, - onFileContextMenu, - } = props; - const gt = useGT(); - const syncTimelineLayout = useSyncLayout(); - const listedFiles = groups ? groups.flatMap((group) => group.files) : files; - const hiddenFileCount = totals.count - listedFiles.length; - const hasDirectories = listedFiles.some((file) => /[/\\]/.test(file.path)); - const firstGroup = groups?.find((group) => group.files.length > 0); - const firstFilePath = groups - ? firstGroup && groupDiffPath(firstGroup, firstGroup.files[0]?.path) - : files[0]?.path; - - return ( -
-
-
- - {gt( - "{count, plural, one {{formattedCount} changed file} other {{formattedCount} changed files}}", - { count: totals.count, formattedCount: totals.count.toLocaleString() }, - )} - - {hasNonZeroStat(totals) && ( - - )} -
-
- {hasDirectories && ( - - { - onToggleAllDirectories(); - syncTimelineLayout(); - }} - /> - } - > - {allDirectoriesExpanded ? ( - - ) : ( - - )} - - - {allDirectoriesExpanded ? gt("Collapse all folders") : gt("Expand all folders")} - - - )} - - onOpenTurnDiff(runId, firstFilePath)} - /> - } - > - - - Open diff - - - - Open the full diff - - -
-
-
- {groups ? ( - groups.map((group) => ( - - )) - ) : ( - - )} -
- {hiddenFileCount > 0 && ( -
- -
- )} -
- ); -}); - -function ChangedFilesGroupSection(props: { - runId: RunId; - group: ChangedFilesGroup; - allDirectoriesExpanded: boolean; - resolvedTheme: "light" | "dark"; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; - onFileContextMenu?: ChangedFileContextMenuHandler | undefined; -}) { - const { runId, group, allDirectoriesExpanded, resolvedTheme, onOpenTurnDiff, onFileContextMenu } = - props; - const [collapsed, setCollapsed] = useState(false); - const syncTimelineLayout = useSyncLayout(); - return ( -
- - {collapsed ? null : group.note !== undefined ? ( -

{group.note}

- ) : ( - onOpenTurnDiff(run, groupDiffPath(group, filePath))} - onFileContextMenu={ - onFileContextMenu - ? (filePath, event) => onFileContextMenu(filePath, event, group) - : undefined - } - /> - )} -
- ); -} - -const ChangedFilesTree = memo(function ChangedFilesTree(props: { - runId: RunId; - files: ReadonlyArray; - /** Rows start this deep, below the row of the folder the files belong to. */ - baseDepth?: number; - allDirectoriesExpanded: boolean; - resolvedTheme: "light" | "dark"; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; - onFileContextMenu?: ChangedFileContextMenuHandler | undefined; -}) { - const baseDepth = props.baseDepth ?? 0; - const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId, onFileContextMenu } = - props; - // Place state before tree derivation to preserve its compiler cache. - const [directoryExpansionState, setDirectoryExpansionState] = useState<{ - key: string | null; - overrides: Record; - }>({ key: null, overrides: {} }); - const syncTimelineLayout = useSyncLayout(); - const treeNodes = buildTurnDiffTree(files); - const directoryPathsKey = collectDirectoryPaths(treeNodes).join("\u0000"); - const hasDirectoryNodes = directoryPathsKey.length > 0; - const expansionStateKey = `${allDirectoriesExpanded ? "expanded" : "collapsed"}\u0000${directoryPathsKey}`; - const expandedDirectories = - directoryExpansionState.key === expansionStateKey - ? directoryExpansionState.overrides - : EMPTY_DIRECTORY_OVERRIDES; - - const toggleDirectory = (pathValue: string) => { - setDirectoryExpansionState((current) => { - const nextOverrides = current.key === expansionStateKey ? current.overrides : {}; - return { - key: expansionStateKey, - overrides: { - ...nextOverrides, - [pathValue]: !(nextOverrides[pathValue] ?? allDirectoriesExpanded), - }, - }; - }); - // Measure before paint instead of waiting for LegendList's deferred shrink measurement. - syncTimelineLayout(); - }; - - const rows = collectExpandedRows(treeNodes, expandedDirectories, allDirectoriesExpanded); - const virtualized = rows.length > VIRTUALIZE_AFTER_ROWS; - - const renderRow = ({ node, depth }: ChangedFileRow) => { - const leftPadding = 8 + (baseDepth + depth) * 14; - if (node.kind === "directory") { - const isExpanded = expandedDirectories[node.path] ?? allDirectoriesExpanded; - return ( - - ); - } - - return ( - - ); - }; - - return ; -}); - -function ChangedFilesRows({ - rows, - renderRow, - virtualized, -}: { - rows: ReadonlyArray; - renderRow: (row: ChangedFileRow) => ReactNode; - virtualized: boolean; -}) { - const containerRef = useRef(null); - const rowSizeRef = useRef(null); - const [range, setRange] = useState({ start: 0, end: 40, rowHeight: 28 }); - const [focusedPath, setFocusedPath] = useState(null); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes scroll, window resize and ancestor resizes to compute the virtualized row range - useLayoutEffect(() => { - const container = containerRef.current; - const rowSize = rowSizeRef.current; - if (!virtualized || !container || !rowSize) return; - - // The card is inside a virtualized timeline item, so its own scrollTop is always zero. - // Observe its ancestors too: streaming text and timeline layout can move the card. - const ancestors: HTMLElement[] = [container, rowSize]; - let scrollElement: HTMLElement | null = null; - for (let parent = container.parentElement; parent; parent = parent.parentElement) { - ancestors.push(parent); - if (/auto|scroll/.test(getComputedStyle(parent).overflowY)) { - scrollElement = parent; - break; - } - } - - const measure = () => { - const rowHeight = rowSize.getBoundingClientRect().height; - if (rowHeight <= 0) return; - const listTop = container.getBoundingClientRect().top; - const viewportTop = scrollElement - ? scrollElement.getBoundingClientRect().top + scrollElement.clientTop - : 0; - const viewportHeight = scrollElement?.clientHeight ?? document.documentElement.clientHeight; - const start = Math.max( - 0, - Math.min(rows.length, Math.floor((viewportTop - listTop) / rowHeight) - ROW_OVERSCAN), - ); - const end = Math.max( - start, - Math.min( - rows.length, - Math.ceil((viewportTop + viewportHeight - listTop) / rowHeight) + ROW_OVERSCAN, - ), - ); - setRange((current) => - current.start === start && current.end === end && current.rowHeight === rowHeight - ? current - : { start, end, rowHeight }, - ); - }; - measure(); - const scrollTarget = scrollElement ?? globalThis.window; - let frame = 0; - const onScroll = () => { - if (frame) return; - frame = requestAnimationFrame(() => { - frame = 0; - measure(); - }); - }; - scrollTarget.addEventListener("scroll", onScroll, { passive: true }); - globalThis.window.addEventListener("resize", onScroll); - const stopObserving = observeResize(ancestors, measure); - return () => { - scrollTarget.removeEventListener("scroll", onScroll); - globalThis.window.removeEventListener("resize", onScroll); - if (frame) cancelAnimationFrame(frame); - stopObserving(); - }; - }, [virtualized, rows.length]); - - const focusedIndex = - focusedPath === null ? -1 : rows.findIndex((row) => row.node.path === focusedPath); - const start = virtualized ? range.start : 0; - const end = virtualized ? Math.min(rows.length, range.end) : rows.length; - const indices = Array.from({ length: Math.max(0, end - start) }, (_, index) => start + index); - // Keep keyboard focus on its row when mouse scrolling moves it outside the render window. - if (focusedIndex >= 0 && focusedIndex < start) indices.unshift(focusedIndex); - if (focusedIndex >= end) indices.push(focusedIndex); - return ( -
{ - const row = event.target.closest("[data-changed-file-row]"); - setFocusedPath(row?.dataset.changedFileRow ?? null); - }} - onBlurCapture={(event) => { - if (!event.currentTarget.contains(event.relatedTarget)) setFocusedPath(null); - }} - > - {virtualized && ( - - ); -} - -function collectExpandedRows( - nodes: ReadonlyArray, - overrides: Readonly>, - allDirectoriesExpanded: boolean, - depth = 0, - rows: ChangedFileRow[] = [], -): ChangedFileRow[] { - for (const node of nodes) { - rows.push({ node, depth }); - if (node.kind === "directory" && (overrides[node.path] ?? allDirectoriesExpanded)) { - collectExpandedRows(node.children, overrides, allDirectoriesExpanded, depth + 1, rows); - } - } - return rows; -} - -function collectDirectoryPaths(nodes: ReadonlyArray): string[] { - const paths: string[] = []; - for (const node of nodes) { - if (node.kind !== "directory") continue; - paths.push(node.path); - paths.push(...collectDirectoryPaths(node.children)); - } - return paths; -} diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index 7848009308750..c1fa62bdd5668 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -61,6 +61,7 @@ export function ChatCanvas({ }) { const elementRef = useRef(null); const widthProbeRef = useRef(null); + const htmlPreviewWidthProbeRef = useRef(null); const [timelineElement, registerTimeline] = useState(null); const measurements = useStore(store, (state) => state.measurements); const detailsCardMeasurement = useStore(store, (state) => state.detailsCardMeasurement); @@ -68,7 +69,8 @@ export function ChatCanvas({ useLayoutEffect(() => { const element = elementRef.current; const probe = widthProbeRef.current; - if (!element || !probe) return; + const htmlPreviewProbe = htmlPreviewWidthProbeRef.current; + if (!element || !probe || !htmlPreviewProbe) return; const findBar = detailsCardTopInset > 0 ? element.querySelector("[data-thread-find-bar]") : null; let disposed = false; @@ -116,6 +118,7 @@ export function ChatCanvas({ height: element.clientHeight, padding: Number.parseFloat(styles.paddingLeft), maxChatWidth: Number.parseFloat(styles.width), + maxHtmlPreviewWidth: Number.parseFloat(getComputedStyle(htmlPreviewProbe).width), minChatWidth: Number.parseFloat(styles.minWidth), composerHeight: composerOverlayElement?.getBoundingClientRect().height ?? 0, timelineGutter: timelineElement @@ -124,7 +127,7 @@ export function ChatCanvas({ }); }; measure(); - const observed: Element[] = [element, probe]; + const observed: Element[] = [element, probe, htmlPreviewProbe]; if (findBar) observed.push(findBar); if (composerOverlayElement) observed.push(composerOverlayElement); if (timelineElement) observed.push(timelineElement); @@ -158,6 +161,13 @@ export function ChatCanvas({ detailsCardPlacement: model.detailsCardPlacement, }; const { layout } = context; + const htmlPreviewLane = + layout.htmlPreview.width > layout.chat.width + ? { + "--html-preview-lane-offset": `${layout.htmlPreview.left - layout.chat.left}px`, + "--html-preview-lane-width": `${layout.htmlPreview.width}px`, + } + : null; return (
@@ -179,6 +190,11 @@ export function ChatCanvas({ aria-hidden className="pointer-events-none invisible absolute h-0 w-(--chat-content-max-width) min-w-[40rem] box-content ps-3 sm:ps-12" /> +
{children}
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 30f73a9a2c4c8..63caf8e9d252f 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -6,6 +6,7 @@ import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; import { BackgroundThreadContext, HiddenThreadContext } from "./backgroundThread"; import { + draftSupportedRuntimeModes, resolveCompatibleRuntimeMode, runtimeModeConfig, resolveRuntimeModeOptions, @@ -1008,7 +1009,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = resolveCompatibleRuntimeMode( runtimeMode, - selectedProviderEntry?.snapshot.supportedRuntimeModes, + draftSupportedRuntimeModes( + selectedProviderEntry?.snapshot.supportedRuntimeModes, + multipleModelSelections, + providerStatuses, + ), ); // Modes above an administrator's ceiling stay listed, disabled with the reason. const compatibleRuntimeModeOptions = resolveRuntimeModeOptions( @@ -2699,9 +2704,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) => { if (isTrailingDoubleClick(event.detail)) return; const rect = event.currentTarget.getBoundingClientRect(); - openMenu({ x: rect.left, y: rect.bottom + 4 }); + openMenu({ x: rect.left, y: rect.bottom + 4 }, contextMenuSourceOf(event)); }; // A native menu takes the second click, so only the in-page menu lets a double-click reach here. const handleTitleDoubleClick = (event: ReactMouseEvent) => { @@ -221,16 +222,17 @@ export const ChatHeader = memo(function ChatHeader({ const api = readLocalApi(); if (!api) return; void api.contextMenu - .show([{ id: "project-settings", label: gt("Project settings"), icon: "settings" }], { - x: event.clientX, - y: event.clientY, - }) + .show( + [{ id: "project-settings", label: gt("Project settings"), icon: "settings" }], + { x: event.clientX, y: event.clientY }, + contextMenuSourceOf(event), + ) .then((action) => { if (action === "project-settings") onOpenProjectSettings?.(); }); return; } - openMenu({ x: event.clientX, y: event.clientY }); + openMenu({ x: event.clientX, y: event.clientY }, contextMenuSourceOf(event)); }; const handleRenameKeyDown = (event: ReactKeyboardEvent) => { if (event.nativeEvent.isComposing || event.keyCode === 229) return; diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.tsx index b414ddd1b63df..01b0beefebbf2 100644 --- a/apps/web/src/components/chat/ChatMarkdownMedia.tsx +++ b/apps/web/src/components/chat/ChatMarkdownMedia.tsx @@ -86,6 +86,16 @@ export function authoredImageSizeStyle( return undefined; } +/** + * An unavailable file has no dimensions, so its `aspect-video w-full` frame + * would fill the row and `max-height` would squash it. Bound the width so the + * frame stays 16:9 at the height cap. + */ +function unavailableImageSizeStyle(maxHeightRem: number): CSSProperties | undefined { + if (maxHeightRem === 30) return undefined; + return { maxWidth: `min(100%, 30rem, ${(maxHeightRem * 16) / 9}rem)` }; +} + const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn( CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME, CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME, @@ -447,13 +457,16 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props : fallbackSrc + (props.srcFragment ?? ""); const knownSize = assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined; const maxHeightRem = props.maxHeightRem ?? 30; + const unavailable = assetUrl._tag === "Failure" && fallbackSrc === undefined; const style = props.style ?? (knownSize ? authoredImageSizeStyle(knownSize.width, knownSize.height, maxHeightRem) - : maxHeightRem !== 30 - ? { maxHeight: `${maxHeightRem}rem` } - : undefined); + : unavailable + ? unavailableImageSizeStyle(maxHeightRem) + : maxHeightRem !== 30 + ? { maxHeight: `${maxHeightRem}rem` } + : undefined); const actionsSource = assetMediaActionsSource({ environmentId: props.environmentId, resource, @@ -470,7 +483,7 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props return ( } > diff --git a/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx b/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx index 79e43bba74314..9b23e1360f201 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx @@ -108,3 +108,30 @@ it("leaves dialog, unrelated input and question button shortcuts alone while the expect(stash().element().textContent).toContain("second prompt"); await expect.element(editor()).toHaveValue("Unsent draft"); }); + +it("leaves IME composition keys in the composer alone while the stash is open", async () => { + for (const composing of [{ isComposing: true }, { keyCode: 229 }]) { + for (const key of ["ArrowDown", "Enter", "Escape"]) { + await using _screen = await render(); + const textarea = editor().element(); + await focus(textarea); + const event = new KeyboardEvent("keydown", { + key, + ...composing, + bubbles: true, + cancelable: true, + }); + await act(async () => { + textarea.dispatchEvent(event); + }); + expect(event.defaultPrevented, `${key} ${JSON.stringify(composing)}`).toBe(false); + await expect.element(stash()).toBeInTheDocument(); + await expect.element(editor()).toHaveValue("Unsent draft"); + } + } + + await using _control = await render(); + await focus(editor().element()); + await press("{Enter}"); + await expect.element(editor()).toHaveValue("first prompt"); +}); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index 46e3fec307bf1..8aa139f84efcf 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -89,6 +89,7 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { }); const handleKeyDown = useEffectEvent((event: KeyboardEvent) => { + if (event.isComposing || event.keyCode === 229) return; const drawer = drawerRef.current; if (!drawer) return; const target = event.target; diff --git a/apps/web/src/components/chat/DiffStatLabel.tsx b/apps/web/src/components/chat/DiffStatLabel.tsx index 4e03e8407cc5a..dfe0a6d03f2c5 100644 --- a/apps/web/src/components/chat/DiffStatLabel.tsx +++ b/apps/web/src/components/chat/DiffStatLabel.tsx @@ -2,10 +2,6 @@ import { useGT } from "gt-react"; import { memo } from "react"; import { cn } from "~/lib/utils"; -export function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean { - return stat.additions > 0 || stat.deletions > 0; -} - export function formatCompactDiffCount(value: number): string { if (value < 1000) return String(value); if (value < 999_500) { diff --git a/apps/web/src/components/chat/LinkedThreadPage.tsx b/apps/web/src/components/chat/LinkedThreadPage.tsx index 08d216a212650..0749f199083ee 100644 --- a/apps/web/src/components/chat/LinkedThreadPage.tsx +++ b/apps/web/src/components/chat/LinkedThreadPage.tsx @@ -26,7 +26,9 @@ export function LinkedThreadPage(props: { const gt = useGT(); const own = useEnvironment(environmentId); const connected = own?.connection.phase === "connected"; - const linkedLabel = useLinkedEnvironments(connected ? null : viaEnvironmentId).get(environmentId); + const linkedLabel = useLinkedEnvironments(connected ? null : viaEnvironmentId, environmentId).get( + environmentId, + ); if (connected) { return ( { parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/initialized" }, "*"); `; +const sizeChanged = (height: number) => + `parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/size-changed", params: { height: ${height} } }, "*");`; +// What the app's frame shows after the app follows a link: another page in the same window. +// Its nested frame keeps `load`, which stops the app, from firing before its message arrives. +const REPLACEMENT_URL = `data:text/html,${encodeURIComponent(``)}`; +// Served as the server serves an app: the document bootstrap is its first script. +const NAVIGATING_APP_HTML = injectMcpAppDocumentBootstrap(``); + +const asset = vi.hoisted(() => ({ html: "" })); +const setup = (html: string) => { + asset.html = html; +}; + vi.mock(import("~/assets/longLivedAssetUrls"), () => ({ useLongLivedAssetUrl: () => ({ _tag: "Success", - url: `data:text/html,${encodeURIComponent(APP_HTML)}`, + url: `data:text/html,${encodeURIComponent(asset.html)}`, expiresAt: Date.now() + 60 * 60_000, }), })); @@ -44,6 +65,7 @@ const nextInitializedFrom = () => describe("McpAppFrame", () => { it("keeps a reopened app when the old document's second teardown finishes late", async () => { + setup(APP_HTML); const firstInitialized = nextInitializedFrom(); await using screen = await render( { expect(screen.getByRole("button", { name: "Show app" }).query()).toBeNull(); await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument(); }); + + it("ignores a page the app's frame navigated to", async () => { + setup(NAVIGATING_APP_HTML); + const element = () => ( + + ); + await using screen = await render(element()); + const frame = screen.getByTitle("Demo app").element() as HTMLIFrameElement; + const row = frame.parentElement!.parentElement!; + // The app resizes only after the host's answer reached it, so the bridge works both ways. + await expect.element(row).toHaveStyle({ height: "321px" }); + + // A tool update hands the row an equal app in a new object, which re-attaches the host. + await screen.rerender(element()); + frame.contentWindow!.postMessage("leave", "*"); + await expect + .element(screen.getByText("The Demo app left its page and was stopped")) + .toBeInTheDocument(); + expect(row.style.height).toBe("321px"); + }); }); diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsx index c0893c2d6f7c3..3d90a688f717c 100644 --- a/apps/web/src/components/chat/McpAppFrame.tsx +++ b/apps/web/src/components/chat/McpAppFrame.tsx @@ -38,6 +38,7 @@ import { useTurnItemDetail } from "~/state/queries"; import { mcpAppEnvironment } from "~/state/mcpApps"; import { useAtomCommand } from "~/state/use-atom-command"; import { observeResize } from "~/lib/observeResize"; +import { attachMcpAppDocumentLink } from "./mcpAppDocumentLink"; import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay"; const commandFailure = (result: { @@ -269,16 +270,15 @@ export function McpAppFrame(props: { } return approved; }; - const target = () => frameRef.current?.contentWindow ?? null; const scope = () => { const { environmentId, threadId, itemId } = readLive().props; return { environmentId, input: { threadId, itemId } }; }; + const documentLink = attachMcpAppDocumentLink(frame, (data) => host.receive(data)); const host = makeMcpAppHost({ app, hostVersion: APP_VERSION, - // Opaque origins require "*"; the window reference scopes delivery to this frame. - post: (message) => target()?.postMessage(message, "*"), + post: documentLink.post, hostContext, callTool: async ({ name, arguments: args }) => { const { environmentId, input } = scope(); @@ -401,12 +401,9 @@ export function McpAppFrame(props: { }, }); hostRef.current = host; - const receive = (event: MessageEvent) => { - if (event.source !== null && event.source === target()) host.receive(event.data); - }; - window.addEventListener("message", receive); + window.addEventListener("message", documentLink.receive); return () => { - window.removeEventListener("message", receive); + window.removeEventListener("message", documentLink.receive); void host.teardown(); hostRef.current = null; frameRef.current = null; diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 49428f7c87c0c..670a407deef70 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -1,6 +1,5 @@ import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender"; import { HtmlRenderDocument } from "../files/BrowserDocumentFrame"; -import { flushSync } from "react-dom"; import { AudioPreview } from "../files/AudioPreview"; import { cdp, page, userEvent } from "vite-plus/test/browser"; import { @@ -18,7 +17,7 @@ import { ThreadId, type OrchestrationV2Subagent, } from "@t3tools/contracts"; -import { LegendList, type LegendListRef } from "@legendapp/list/react"; +import { type LegendListRef } from "@legendapp/list/react"; import { createRef, Profiler, @@ -35,7 +34,6 @@ import "~/index.css"; import { environmentThreadDetails } from "../../state/threads"; import { act, fakeTimers, render, stubGlobal } from "../../../test/render"; -import { ChangedFilesCard } from "./ChangedFilesTree"; import { MessagesTimeline } from "./MessagesTimeline"; import { createWorkspaceFocusController, workspaceAreaProps } from "../../lib/workspaceFocus"; import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic"; @@ -78,15 +76,17 @@ vi.mock(import("~/state/query"), async (original) => ({ })) as never, })); -const stubbedAsset = vi.hoisted(() => ({ url: "" })); +const stubbedAsset = vi.hoisted(() => ({ url: "", failed: false })); vi.mock(import("~/assets/assetUrls"), async (original) => { const actual = await original(); return { ...actual, useAssetUrlState: ((...args: Parameters) => - stubbedAsset.url - ? { _tag: "Success", url: stubbedAsset.url } - : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState, + stubbedAsset.failed + ? { _tag: "Failure" } + : stubbedAsset.url + ? { _tag: "Success", url: stubbedAsset.url } + : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState, useAssetUrls: ((...args: Parameters) => stubbedAsset.url ? args[1].map(() => stubbedAsset.url) @@ -110,7 +110,6 @@ function baseProps(): Omit { turnDiffSummaries: [], runs: [], routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`, - onOpenTurnDiff: () => {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, @@ -626,6 +625,56 @@ describe("MessagesTimeline messages", () => { await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd)); }); + it("keeps the visible sentence in a long message when the chat width changes", async () => { + setup(); + const size = { width: window.innerWidth, height: window.innerHeight }; + onTestFinished(() => page.viewport(size.width, size.height)); + await page.viewport(1200, 1400); + const props = { ...baseProps(), liveFollowEnabled: false }; + const paragraphs = Array.from( + { length: 30 }, + (_, index) => + `Paragraph ${index + 1}. ${"A side panel should not move the sentence being read out of view. ".repeat(5)}`, + ); + await using screen = await renderTimeline( + [message(paragraphs.join("\n\n"), { role: "assistant" })], + props, + ); + screen.container.style.width = "900px"; + const viewport = props.listRef.current!.getScrollableNode()!; + const target = page.getByText(paragraphs[15]!.trim(), { exact: true }).element(); + await vi.waitFor(() => { + expect(viewport.scrollHeight).toBeGreaterThan(1000); + expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); + }); + await props.listRef.current!.scrollToOffset({ + offset: + viewport.scrollTop + + target.getBoundingClientRect().top - + viewport.getBoundingClientRect().top - + 24, + animated: false, + }); + viewport.dispatchEvent(new Event("scroll")); + const before = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(before - 24)).toBeLessThan(2); + // The fork's reader line holds the line only once the scroll has rested for 100 ms. + let rested = 0; + let lastTop = Number.NaN; + await vi.waitFor(() => { + rested = viewport.scrollTop === lastTop ? rested + 1 : 0; + lastTop = viewport.scrollTop; + expect(rested).toBeGreaterThanOrEqual(3); + }); + for (const width of [500, 900]) { + screen.container.style.width = `${width}px`; + await vi.waitFor(() => { + const after = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(30); + }); + } + }); + it("disables the minimap's next turn button at the bottom of the thread", async () => { setup(); const props = baseProps(); @@ -774,6 +823,51 @@ describe("MessagesTimeline messages", () => { expectItemOrder(); }); + it("opens a working parent thread at its end without landing short", async () => { + setup(); + const props = baseProps(); + const parent = Array.from({ length: 30 }, (_, index) => + message( + `Parent turn ${index}:\n\n${"x ".repeat(200)}`, + { role: index % 2 === 0 ? "user" : "assistant" }, + `parent-${index}`, + ), + ); + await using screen = await renderElement( + {} }} + timelineEntries={[message("Short child reply.", { role: "assistant" }, "child-0")]} + />, + ); + expect(screen.text()).toContain("Subagent of"); + const viewport = props.listRef.current!.getScrollableNode()!; + const end = () => viewport.scrollHeight - viewport.clientHeight; + // Distance from the end as each scroll lands, against the content height at that moment. + const shortfalls: number[] = []; + viewport.addEventListener("scroll", () => + shortfalls.push(Math.round(end() - viewport.scrollTop)), + ); + + // A working parent's footer (queued turns, its subagents) is taller than the child's. + await screen.rerender( + Waiting on 4 subagents
} + isWorking + />, + ); + await vi.waitFor(() => { + expect(screen.text()).toContain("Parent turn 29:"); + expect(end() - viewport.scrollTop).toBeLessThanOrEqual(1); + }); + + expect(shortfalls.length).toBeGreaterThan(0); + expect(shortfalls).toEqual(shortfalls.map(() => 0)); + }); + it("puts rows back in item order soon after a continuous scroll stops", async () => { setup(); const props = baseProps(); @@ -1799,6 +1893,47 @@ describe("MessagesTimeline attachments", () => { ); }); + it("keeps an unavailable viewed image inside the 10rem work-log strip", async () => { + stubbedAsset.failed = true; + onTestFinished(() => { + stubbedAsset.failed = false; + }); + await using screen = await renderElement( + + + , + ); + const frame = await vi.waitFor(() => { + const element = screen.container.querySelector( + '[data-image-gallery] [role="alert"]', + ); + expect(element).toBeTruthy(); + return element!; + }); + const size = await vi.waitFor(() => { + const rect = frame.getBoundingClientRect(); + expect(rect.width).toBeGreaterThan(0); + return rect; + }); + expect(size.height).toBeLessThanOrEqual(161); + expect(size.width).toBeLessThanOrEqual(285); + expect(Math.abs(size.width / size.height - 16 / 9)).toBeLessThan(0.02); + }); + it("opens an image from an expanded tool row as a gallery of the turn's viewed images", async () => { stubbedAsset.url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; @@ -2238,73 +2373,6 @@ it("renders automatic compaction as one live divider that finishes with its reas expect(container.textContent).not.toContain("Compacting before"); }); -function TimelineChangedFilesCard() { - const [expanded, setExpanded] = useState(true); - return ( - ({ - path, - kind: "modified", - additions: 1, - deletions: 0, - }))} - totals={{ count: 3, additions: 3, deletions: 0 }} - allDirectoriesExpanded={expanded} - resolvedTheme="light" - onToggleAllDirectories={() => setExpanded((value) => !value)} - onOpenTurnDiff={() => {}} - /> - ); -} - -function ChangedFilesTimeline() { - return ( - item} - estimatedItemSize={100} - recycleItems={false} - className="h-[600px]" - renderItem={({ item }) => - item === "files" ? :
After
- } - /> - ); -} - -describe("ChangedFilesCard", () => { - it.each(["folder", "all folders"])( - "measures %s collapse and expansion in the same commit", - async (toggle) => { - await using screen = await render(); - const after = () => - screen.container.querySelector('[data-testid="after"]')!.getBoundingClientRect().top; - const cardBottom = () => - screen.container.querySelector("[data-changed-files-state]")!.getBoundingClientRect() - .bottom; - await vi.waitFor(() => expect(after()).toBe(cardBottom())); - const topBefore = after(); - const button = () => - screen.container.querySelector( - toggle === "folder" - ? '[data-changed-file-row="src"] button' - : 'button[aria-label$="all folders"]', - )!; - await act(() => { - flushSync(() => button().click()); - expect(screen.container.textContent).not.toContain("a.ts"); - expect(after()).toBe(topBefore - 3 * 28); - }); - await act(() => { - flushSync(() => button().click()); - expect(screen.container.textContent).toContain("a.ts"); - expect(after()).toBe(topBefore); - }); - }, - ); -}); - it("keeps concurrent approvals actionable outside collapsed work and restores settled rows", async () => { setup(); const fixture = makeStreamingTimelineFixture(); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index f1726cbbb92b2..37005359592cd 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1084,8 +1084,8 @@ describe("deriveMessagesTimelineRows", () => { expect(assistantRows[1]?.showAssistantCopyButton).toBe(true); }); - it("projects assistant diffs and rewinds the first visible run to thread start after a rewind", () => { - const assistantTurnDiffSummary = { + it("rewinds the first visible run to thread start after a rewind", () => { + const checkpoint = { runId: "turn-1" as never, completedAt: "2026-01-01T00:00:30Z", assistantMessageId: "assistant-1" as never, @@ -1129,7 +1129,7 @@ describe("deriveMessagesTimelineRows", () => { ], isWorking: false, activeTurnStartedAt: null, - turnDiffSummaries: [assistantTurnDiffSummary], + turnDiffSummaries: [checkpoint], supportsConversationRollback: true, threadStartCheckpointAvailable: true, }); @@ -1138,13 +1138,7 @@ describe("deriveMessagesTimelineRows", () => { (row): row is Extract<(typeof rows)[number], { kind: "message" }> => row.kind === "message" && row.message.role === "user", ); - const assistantRow = rows.find( - (row): row is Extract<(typeof rows)[number], { kind: "message" }> => - row.kind === "message" && row.message.role === "assistant", - ); - expect(userRow?.revertTurnCount).toBe(0); - expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary); }); it("folds the first assistant message and settled work before the terminal response", () => { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 7fb3ffba14d95..0d978de1f82b7 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -640,7 +640,6 @@ type MessagesTimelineRowContent = suppressEmptyResponse?: boolean; showAssistantCopyButton: boolean; assistantCopyStreaming: boolean; - assistantTurnDiffSummary?: TurnDiffSummary | undefined; revertTurnCount?: number | undefined; /** Another of your messages follows directly, so the two sit closer together. */ groupedWithNext?: boolean; @@ -1650,12 +1649,6 @@ export function deriveMessagesTimelineRows( input.pendingApprovalRequestIds?.has(item.requestId) === true ); }; - const turnDiffSummaryByAssistantMessageId = new Map(); - for (const summary of input.turnDiffSummaries) { - if (summary.assistantMessageId) { - turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary); - } - } const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null); const revertTurnCountByUserMessageId = input.supportsConversationRollback ? deriveRevertTurnCountByUserMessageId({ @@ -2332,10 +2325,6 @@ export function deriveMessagesTimelineRows( embeddedResultRunIds.has(timelineEntry.message.runId), showAssistantCopyButton: showAssistantMeta, assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress, - assistantTurnDiffSummary: - timelineEntry.message.role === "assistant" - ? turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id) - : undefined, revertTurnCount: timelineEntry.message.role === "user" ? revertTurnCountByUserMessageId.get(timelineEntry.message.id) @@ -2925,7 +2914,6 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.suppressEmptyResponse === bm.suppressEmptyResponse && a.showAssistantCopyButton === bm.showAssistantCopyButton && a.assistantCopyStreaming === bm.assistantCopyStreaming && - a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary && a.revertTurnCount === bm.revertTurnCount && a.groupedWithNext === bm.groupedWithNext && a.groupedWithPrevious === bm.groupedWithPrevious && diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 2bcdd663da63f..28c9d35653f49 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,5 +1,6 @@ import { T, useGT, useMessages, Var } from "gt-react"; import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/models"; import { threadErrorText } from "@t3tools/client-runtime/state/threads"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -247,6 +248,7 @@ interface MessagesTimelineProps { activeTurnStartedAt?: string | null; /** Replaces "Thinking" while the active run's provider has not started a turn. */ providerStartingLabel?: string | null; + providerStarting?: NonNullable | null; worktreeSetup?: WorktreeSetupSnapshot | null; onCancelWorktreeSetup?: () => void; retryableWorkspacePreparationRunIds?: ReadonlySet; @@ -275,7 +277,6 @@ interface MessagesTimelineProps { /** Off where another region already speaks the thread's status, like a subagent's bar. */ announceTurnStatus?: boolean; onOpenToolDiff?: (target: ToolCallDiffTarget) => void; - onOpenTurnDiff?: (runId: RunId, filePath?: string) => void; onOpenThread: ( threadId: OrchestrationV2TurnItem["threadId"], environmentId?: EnvironmentId, @@ -373,6 +374,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ runlessWorkActive = false, activeTurnStartedAt = null, providerStartingLabel = null, + providerStarting = null, worktreeSetup = null, footer = null, onCancelWorktreeSetup, @@ -402,7 +404,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ displayThreadKey, announceTurnStatus = true, onOpenToolDiff, - onOpenTurnDiff, onOpenThread, renderHtmlRender, turnItemSource, @@ -1155,7 +1156,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ onFileDownload, openPullRequest, onOpenToolDiff, - onOpenTurnDiff, onOpenThread, renderHtmlRender, turnItemSource, @@ -1208,6 +1208,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ awaitingUser: awaitingUser !== null, isPreparingWorktree, providerStartingLabel, + providerStarting, latestRunId: latestRun?.runId ?? null, liveAnswerPreview: isWorking && toolCallVisibility === "zen" ? liveAnswerPreview(timelineEntries) : null, @@ -1412,7 +1413,8 @@ const ConversationTimeline = memo(function ConversationTimeline({ >
@@ -1519,10 +1521,10 @@ const ConversationTimeline = memo(function ConversationTimeline({ ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH : TIMELINE_MAINTAIN_SCROLL_AT_END } + // A restore owns the scroll position until it lands. Anchoring would + // move it for the previous thread's header as the list swaps threads. maintainVisibleContentPosition={ - findActive || - citationPositioning || - (restoringThreadPosition && rememberedPosition?.atEnd === false) + findActive || citationPositioning || restoringThreadPosition ? false : maintainVisibleContentPosition } diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index cc246a1f9967c..51d06370dd838 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -66,6 +66,7 @@ vi.mock(import("../../remoteOpen"), async (importOriginal) => ({ })); import { OpenInPicker } from "./OpenInPicker"; +import type { FileManagerAction } from "./OpenInPicker.logic"; import { registerOpenFavoriteEditorCommand, useOpenFavoriteEditorShortcut, @@ -98,7 +99,7 @@ async function setup() { async function renderPicker( availableEditors: readonly EditorId[] = editors, panel = false, - { openInCwd = "/work/project", revealFileManager = false } = {}, + { openInCwd = "/work/project", fileManagerAction = "open" as FileManagerAction } = {}, ) { await act(async () => { for (const listener of state.listeners) listener(); @@ -108,7 +109,7 @@ async function setup() { keybindings={DEFAULT_RESOLVED_KEYBINDINGS} availableEditors={availableEditors} openInCwd={openInCwd} - revealFileManager={revealFileManager} + fileManagerAction={fileManagerAction} displayMode={panel ? "panel" : "toolbar"} compact={!panel} /> @@ -189,6 +190,34 @@ describe("host editor access", () => { }); }); +describe("file manager", () => { + it("waits for the path's type, then shows a file in its folder", async () => { + await using fixture = await setup(); + const { renderPicker, primaryButton, click, pressOpenFavorite } = fixture; + state.allowed.add(selected); + const openInCwd = "/work/project/notes.md"; + await renderPicker(["file-manager"], false, { openInCwd, fileManagerAction: "unavailable" }); + + expect(primaryButton().disabled).toBe(true); + await click(primaryButton()); + expect((await pressOpenFavorite()).defaultPrevented).toBe(false); + expect(state.run).not.toHaveBeenCalled(); + + // A failed open is not announced, so no timer outlives the test. + state.run.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("No file manager")))); + await renderPicker(["file-manager"], false, { openInCwd, fileManagerAction: "reveal" }); + await click(primaryButton()); + expect(state.run.mock.calls).toEqual([ + [ + { + environmentId: selected, + input: { cwd: openInCwd, editor: "file-manager", reveal: true }, + }, + ], + ]); + }); +}); + describe("remote editor links", () => { it("opens the link from the fallback when the picker is not mounted", async () => { await using fixture = await setup(); diff --git a/apps/web/src/components/chat/OpenInPicker.logic.test.ts b/apps/web/src/components/chat/OpenInPicker.logic.test.ts index 10595e2f8cdbe..3b5536c78f396 100644 --- a/apps/web/src/components/chat/OpenInPicker.logic.test.ts +++ b/apps/web/src/components/chat/OpenInPicker.logic.test.ts @@ -1,7 +1,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { shouldShowOpenInPicker } from "./OpenInPicker.logic"; +import { fileManagerActionForPath, shouldShowOpenInPicker } from "./OpenInPicker.logic"; describe("shouldShowOpenInPicker", () => { it("shows both local environments when the primary has a separate WSL home", () => { @@ -24,3 +24,16 @@ describe("shouldShowOpenInPicker", () => { } }); }); + +describe("fileManagerActionForPath", () => { + it("opens only folders and shows a file once its read settled on a server that can", () => { + for (const [isFolder, isSettled, canReveal, action] of [ + [true, false, false, "open"], + [false, false, true, "unavailable"], + [false, true, false, "unavailable"], + [false, true, true, "reveal"], + ] as const) { + expect(fileManagerActionForPath({ isFolder, isSettled, canReveal })).toBe(action); + } + }); +}); diff --git a/apps/web/src/components/chat/OpenInPicker.logic.ts b/apps/web/src/components/chat/OpenInPicker.logic.ts index 5978a5986030a..8e49592e05866 100644 --- a/apps/web/src/components/chat/OpenInPicker.logic.ts +++ b/apps/web/src/components/chat/OpenInPicker.logic.ts @@ -18,3 +18,18 @@ export function shouldShowOpenInPicker(input: { } return input.remoteOpenMode !== "local-exec"; } + +export type FileManagerAction = "open" | "reveal" | "unavailable"; + +/** + * The file manager opens folders and shows files in their folder. A path whose read has not + * settled may be either, and a file needs the server's reveal support, so both wait. + */ +export function fileManagerActionForPath(input: { + readonly isFolder: boolean; + readonly isSettled: boolean; + readonly canReveal: boolean; +}): FileManagerAction { + if (input.isFolder) return "open"; + return input.isSettled && input.canReveal ? "reveal" : "unavailable"; +} diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index 711f1e4cb3e63..a4b7322aa5dda 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -10,6 +10,7 @@ import { T, useGT, useMessages, Var } from "gt-react"; import { memo, use, useRef } from "react"; import { BackgroundThreadContext } from "./backgroundThread"; import { shortcutLabelForCommand } from "../../keybindings"; +import type { FileManagerAction } from "./OpenInPicker.logic"; import { OPEN_FAVORITE_EDITOR_ATTRIBUTE } from "./OpenInPickerShortcut"; import { usePreferredEditor } from "../../editorPreferences"; import { editorLabelForPlatform } from "../../editorLabels"; @@ -21,7 +22,7 @@ import { useRemoteOpenState, } from "../../remoteOpen"; import { useEnvironment } from "../../state/environments"; -import { ChevronDownIcon, FolderClosedIcon, SquareArrowOutUpRightIcon } from "lucide-react"; +import { ChevronDownIcon, SquareArrowOutUpRightIcon } from "lucide-react"; import { Group, GroupSeparator } from "../ui/group"; import { @@ -36,35 +37,9 @@ import { MenuTrigger, } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { - AntigravityIcon, - CursorIcon, - FileExplorerIcon, - FinderIcon, - Icon, - KiroIcon, - TraeIcon, - VisualStudioCode, - VisualStudioCodeInsiders, - VSCodium, - Zed, -} from "../Icons"; -import { - AquaIcon, - CLionIcon, - DataGripIcon, - DataSpellIcon, - GoLandIcon, - IntelliJIdeaIcon, - PhpStormIcon, - PyCharmIcon, - RiderIcon, - RubyMineIcon, - RustRoverIcon, - WebStormIcon, -} from "../JetBrainsIcons"; +import { type EditorIconOption, editorIconOptions } from "../editorIcons"; import { announce } from "~/lib/announce"; -import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils"; +import { cn } from "~/lib/utils"; import { shellEnvironment } from "~/state/shell"; import { useAtomCommand } from "~/state/use-atom-command"; import { @@ -77,131 +52,15 @@ import { import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { useComposerMenuState } from "./useComposerMenuState"; -type OpenInOption = { - label: string; - Icon: Icon; - value: EditorId; - kind: "brand" | "generic"; -}; +type OpenInOption = EditorIconOption & { label: string }; const resolveOpenInOptions = ( platform: string, availableEditors: ReadonlyArray, resolve: MessageResolver, -) => { - const baseOptions: ReadonlyArray> = [ - { - Icon: CursorIcon, - value: "cursor", - kind: "brand", - }, - { - Icon: TraeIcon, - value: "trae", - kind: "brand", - }, - { - Icon: KiroIcon, - value: "kiro", - kind: "brand", - }, - { - Icon: VisualStudioCode, - value: "vscode", - kind: "brand", - }, - { - Icon: VisualStudioCodeInsiders, - value: "vscode-insiders", - kind: "brand", - }, - { - Icon: VSCodium, - value: "vscodium", - kind: "brand", - }, - { - Icon: Zed, - value: "zed", - kind: "brand", - }, - { - Icon: AntigravityIcon, - value: "antigravity", - kind: "brand", - }, - { - Icon: IntelliJIdeaIcon, - value: "idea", - kind: "brand", - }, - { - Icon: AquaIcon, - value: "aqua", - kind: "brand", - }, - { - Icon: CLionIcon, - value: "clion", - kind: "brand", - }, - { - Icon: DataGripIcon, - value: "datagrip", - kind: "brand", - }, - { - Icon: DataSpellIcon, - value: "dataspell", - kind: "brand", - }, - { - Icon: GoLandIcon, - value: "goland", - kind: "brand", - }, - { - Icon: PhpStormIcon, - value: "phpstorm", - kind: "brand", - }, - { - Icon: PyCharmIcon, - value: "pycharm", - kind: "brand", - }, - { - Icon: RiderIcon, - value: "rider", - kind: "brand", - }, - { - Icon: RubyMineIcon, - value: "rubymine", - kind: "brand", - }, - { - Icon: RustRoverIcon, - value: "rustrover", - kind: "brand", - }, - { - Icon: WebStormIcon, - value: "webstorm", - kind: "brand", - }, - { - Icon: isMacPlatform(platform) - ? FinderIcon - : isWindowsPlatform(platform) - ? FileExplorerIcon - : FolderClosedIcon, - value: "file-manager", - kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic", - }, - ]; +): ReadonlyArray => { const availableEditorSet = new Set(availableEditors); - return baseOptions + return editorIconOptions(platform) .filter((option) => availableEditorSet.has(option.value)) .map((option) => ({ ...option, @@ -223,7 +82,7 @@ export const OpenInPicker = memo(function OpenInPicker({ compact = false, enableShortcut = true, displayMode = "toolbar", - revealFileManager = false, + fileManagerAction = "open", }: { environmentId: EnvironmentId; keybindings: ResolvedKeybindingsConfig; @@ -234,7 +93,7 @@ export const OpenInPicker = memo(function OpenInPicker({ compact?: boolean; enableShortcut?: boolean; displayMode?: "toolbar" | "panel"; - revealFileManager?: boolean; + fileManagerAction?: FileManagerAction; }) { const gt = useGT(); const messages = useMessages(); @@ -253,11 +112,13 @@ export const OpenInPicker = memo(function OpenInPicker({ // Remote editors run on the viewing machine; only desktop can probe that PATH. const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors; const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors); + const isEditorUnavailable = (editor: EditorId | null) => + editor === "file-manager" && fileManagerAction === "unavailable"; const openInEditor = async (editorId: EditorId | null): Promise => { if (!openInCwd) return false; const editor = editorId ?? preferredEditor; - if (!editor) return false; + if (!editor || isEditorUnavailable(editor)) return false; if (remote.mode === "remote-unavailable") return false; if (remote.mode === "remote-links") { const url = buildRemoteOpenUrl({ @@ -281,7 +142,7 @@ export const OpenInPicker = memo(function OpenInPicker({ input: { cwd: openInCwd, editor, - ...(revealFileManager && editor === "file-manager" ? { reveal: true } : {}), + ...(fileManagerAction === "reveal" && editor === "file-manager" ? { reveal: true } : {}), }, }); setPreferredEditor(editor); @@ -329,7 +190,11 @@ export const OpenInPicker = memo(function OpenInPicker({ {options.map(({ label, Icon, value, kind }) => ( { if (presentation === "menu") { @@ -365,8 +230,7 @@ export const OpenInPicker = memo(function OpenInPicker({ {primaryOption && ( openInEditor(preferredEditor)} > @@ -403,7 +267,9 @@ export const OpenInPicker = memo(function OpenInPicker({ variant={isPanel ? "ghost" : "outline"} part="primary" panel={isPanel} - disabled={!preferredEditor || !openInCwd || !canOpenEditor} + disabled={ + !preferredEditor || !openInCwd || !canOpenEditor || isEditorUnavailable(preferredEditor) + } {...(enableShortcut && !backgroundThread ? { [OPEN_FAVORITE_EDITOR_ATTRIBUTE]: "" } : {})} onClick={() => { if (!preferredEditor) return; diff --git a/apps/web/src/components/chat/ProviderStartingIcon.tsx b/apps/web/src/components/chat/ProviderStartingIcon.tsx new file mode 100644 index 0000000000000..634f1f742f1d6 --- /dev/null +++ b/apps/web/src/components/chat/ProviderStartingIcon.tsx @@ -0,0 +1,67 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + type EnvironmentId, + PROVIDER_DISPLAY_NAMES, + type ProviderDriverKind, + type ProviderInstanceId, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { Atom } from "effect/reactivity"; + +import { brandProviderInstanceEntries, deriveProviderInstanceEntries } from "~/providerInstances"; +import { serverEnvironment } from "~/state/server"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; + +interface ProviderStartingPresentation { + readonly displayName: string; + readonly acpRegistryAgentId: string | undefined; + readonly acpRegistryIconUrl: string | undefined; +} + +// Keyed per instance so provider status pushes don't rerender the live row. +const providerStartingPresentationAtom = Atom.family((key: string) => + Atom.make((get): ProviderStartingPresentation | null => { + const [environmentId, instanceId] = key.split("\u0000") as [string, string]; + const config = get(serverEnvironment.configValueAtom(environmentId as EnvironmentId)); + const provider = config?.providers.find((candidate) => candidate.instanceId === instanceId); + if (!config || !provider) return null; + const [entry] = brandProviderInstanceEntries( + deriveProviderInstanceEntries([provider]), + config.settings, + ); + if (!entry) return null; + const next = { + displayName: entry.displayName, + acpRegistryAgentId: entry.acpRegistryAgentId, + acpRegistryIconUrl: entry.acpRegistryIconUrl, + }; + const previous = Option.getOrNull(get.self()); + return previous && + previous.displayName === next.displayName && + previous.acpRegistryAgentId === next.acpRegistryAgentId && + previous.acpRegistryIconUrl === next.acpRegistryIconUrl + ? previous + : next; + }).pipe(Atom.withLabel("provider-starting-presentation")), +); + +/** The logo of the provider a run is waiting on, shown in place of the thinking icon. */ +export function ProviderStartingIcon(props: { + readonly environmentId: EnvironmentId | null; + readonly instanceId: ProviderInstanceId; + readonly driver: ProviderDriverKind; +}) { + const presentation = useAtomValue( + providerStartingPresentationAtom(`${props.environmentId ?? ""}\u0000${props.instanceId}`), + ); + return ( + + ); +} diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index 25c1fe59d5e6b..49dff6b6a1c16 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -18,10 +18,11 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { - EnvironmentId, - OrchestrationV2ProjectedTurnItem, - SecretProviderId, +import { + AuthProvidersManageScope, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; @@ -38,6 +39,7 @@ import { import { useId, useRef, useState, type FormEvent } from "react"; import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -80,7 +82,9 @@ const NO_SOURCES: ReadonlyArray = []; function useSecretRequestSources(environmentId: EnvironmentId) { const config = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const messages = useMessages(); - return hasFeatureFlag(config, "secretProviders") + // The server accepts a reference answer only with this scope; without it the card is typed. + const canUseReferences = useEnvironmentScope(environmentId, AuthProvidersManageScope); + return canUseReferences && hasFeatureFlag(config, "secretProviders") ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages) : NO_SOURCES; } diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx index 52e5033d58d4d..b5fb3de136f59 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx @@ -125,7 +125,24 @@ function setup(input: { }; } -function Panel({ fixture }: { fixture: ReturnType }) { +const machines = (["This Mac", "Server"] as const).map((label, index) => ({ + environmentId: EnvironmentId.make(index === 0 ? "environment" : "other"), + projectId: ProjectId.make("project"), + label, + isPrimary: index === 0, + machine: "server" as const, +})); + +function Panel({ + fixture, + draftEnvMode, + onMachines = false, +}: { + fixture: ReturnType; + /** Renders an unsent draft in this mode instead of a started thread. */ + draftEnvMode?: "local" | "worktree"; + onMachines?: boolean; +}) { const noop = () => {}; const scriptResult = async () => ({ ok: true }) as never; return ( @@ -149,8 +166,8 @@ function Panel({ fixture }: { fixture: ReturnType }) { threadId={threadRef.threadId} projectId={ProjectId.make("project")} composerDraftTarget={threadRef} - worktreePath={state.folder} - isServerThread + worktreePath={draftEnvMode === undefined ? state.folder : null} + isServerThread={draftEnvMode === undefined} activeProjectName={state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain"} activeProjectScripts={undefined} preferredScriptId={null} @@ -161,10 +178,12 @@ function Panel({ fixture }: { fixture: ReturnType }) { gitCwd={state.folder} workspaceMutationId={null} isGitRepo={false} - envLocked - availableEnvironments={[]} + offersWorkspaceModes={false} + envLocked={draftEnvMode === undefined} + availableEnvironments={onMachines ? machines : []} + {...(onMachines ? { onEnvironmentChange: noop } : {})} onEnvModeChange={noop} - envMode="local" + envMode={draftEnvMode ?? "local"} startFromOrigin={false} onStartFromOriginChange={noop} onComposerFocusRequest={noop} @@ -191,6 +210,23 @@ it("offers no git controls in a No project thread, but shows its linked pull req .not.toBeInTheDocument(); }); +it("shows Current checkout where no worktree can come from, even when New worktree is the default", async () => { + using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT }); + await using _screen = await render(); + await expect.element(page.getByLabelText("Run context: Current checkout")).toBeVisible(); + await expect.element(page.getByRole("button", { name: /Run context/ })).not.toBeInTheDocument(); +}); + +it("offers only machines where no worktree can come from and several machines exist", async () => { + using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT }); + await using _screen = await render( + , + ); + await page.getByRole("button", { name: "Run context: This Mac, Current checkout" }).click(); + await expect.element(page.getByText("Run on")).toBeVisible(); + await expect.element(page.getByText("New worktree")).not.toBeInTheDocument(); +}); + it("shows a linked pull request in a folder that is not a git repository", async () => { using fixture = setup({ workspaceRoot: "/work/plain", diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 085815bed02cf..69c3cd7133aff 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -71,6 +71,8 @@ interface ThreadDetailsPanelProps extends Pick< gitCwd: string | null; workspaceMutationId: string | null; isGitRepo: boolean; + /** False when no worktree can come from this folder, so it offers no workspace modes. */ + offersWorkspaceModes: boolean; envLocked: boolean; availableEnvironments: readonly EnvironmentOption[]; autoEnvironmentLabel?: string | undefined; @@ -220,6 +222,8 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { autoEnvironmentLabel={props.autoEnvironmentLabel} onAutoEnvironment={props.onAutoEnvironment} {...branchToolbarProps} + // Workspace modes follow the composer's rule, not this folder's own status. + showGitControls={props.offersWorkspaceModes} /> ) : null} diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index b17067affb96f..666bbccd13684 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -17,6 +17,7 @@ import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ issuesSupported: false, isDraft: false, + headSha: "shown-head", status: "success" as PullRequestCheck["status"], extraStatus: null as PullRequestCheck["status"] | null, mergeMethods: ["merge"] as Array<"merge" | "squash" | "rebase">, @@ -59,6 +60,7 @@ const queryData = () => ({ title: "Test PR", state: "open", isDraft: state.isDraft, + headSha: state.headSha, mergeability: "mergeable", headBranch: "feature", baseBranch: "main", @@ -178,19 +180,21 @@ it("merges with the last selected merge method", async () => { const { container } = screen; state.mergeMethods = ["merge", "squash"]; useUiStateStore.getState().setPullRequestMergeMethod("squash"); - await act(async () => { - await screen.rerender( - , - ); - }); + const rerender = () => + act(async () => { + await screen.rerender( + , + ); + }); + await rerender(); const clickMerge = async (scope: ParentNode) => await act(async () => { [...scope.querySelectorAll("button")] @@ -200,10 +204,17 @@ it("merges with the last selected merge method", async () => { await clickMerge(container); const dialog = document.querySelector('[role="alertdialog"]')!; expect(dialog.textContent).toContain("using squash"); + // A push that a background refresh picks up while the confirmation is open. + state.headSha = "pushed-head"; + await rerender(); await clickMerge(dialog); expect(state.perform).toHaveBeenCalledWith( expect.objectContaining({ - input: expect.objectContaining({ action: "merge", mergeMethod: "squash" }), + input: expect.objectContaining({ + action: "merge", + mergeMethod: "squash", + expectedHeadSha: "shown-head", + }), }), ); }); @@ -260,6 +271,7 @@ async function setup() { state.updateToast.mockReset(); state.issuesSupported = false; + state.headSha = "shown-head"; state.isDraft = false; state.status = "success"; state.extraStatus = null; diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index 3b7836b32293d..dd3e93ca9a578 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -166,14 +166,19 @@ export function ThreadDetailsPrRow({ checks: detail?.checks ?? [], }); + const [armedMergeHead, setArmedMergeHead] = useState(); const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId, reference, + // The row shows no diff, so a merge lands the head it had when the confirmation opened. + headSha: armedMergeHead ?? detail?.headSha, terminology, onSuccess: () => { checksQuery.refresh(); onActed?.(); }, + // A refused merge usually means the row is stale, so show what the host has now. + onFailure: () => detailQuery.refresh(), }); const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail }); const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod); @@ -449,7 +454,10 @@ export function ThreadDetailsPrRow({ method: mergeMethodKey, }, ), - onClick: () => setConfirmingMerge(true), + onClick: () => { + setArmedMergeHead(detail?.headSha); + setConfirmingMerge(true); + }, } : null; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 666ce784b3afc..da8035c458d70 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -66,7 +66,7 @@ vi.mock(import("../../state/use-atom-command"), () => ({ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { render } from "../../../test/render"; +import { fakeTimers, render } from "../../../test/render"; import { isMacPlatform } from "../../lib/utils"; import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore"; import { makeThreadProjectionFixture } from "../../test-fixtures"; @@ -405,6 +405,58 @@ it("shows a remote subagent's full title in its tooltip even when its environmen expect(screen.router?.state.location.pathname).toBe("/environment/fork"); }); +it("shows how long a running remote subagent has been running, as a local one does", async () => { + setup(); + const remoteTitle = "Remote subagent running on a linked machine"; + using _timers = fakeTimers(); + vi.setSystemTime(new Date("2026-11-23T12:12:00.000Z")); + const startedAt = DateTime.makeUnsafe("2026-11-23T12:00:00.000Z"); + state.projection = { + ...(state.projection as Record), + subagents: [ + { + id: NodeId.make("remote-agent"), + threadId, + runId: null, + parentNodeId: NodeId.make("parent"), + origin: "app_owned", + createdBy: "agent", + driver: "remote", + providerInstanceId: "provider", + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Run remote task", + title: remoteTitle, + model: null, + status: "running", + result: null, + startedAt, + completedAt: null, + updatedAt: startedAt, + remoteChild: { + environmentId: EnvironmentId.make("remote-env"), + threadId: ThreadId.make("remote-thread"), + label: "127x05", + }, + }, + ], + }; + await using screen = await render( + , + { router: "/environment/fork" }, + ); + + // Assert synchronously: expect.element polls on timers this test fakes. + const row = screen.getByRole("button", { name: new RegExp(remoteTitle) }); + expect(row.element().textContent).toContain("12m"); +}); + it("explains why Merge back is unavailable before the fork completes a run", async () => { setup(); state.projection = { ...(state.projection as Record), runs: [] }; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index b005fa877b745..0aefaa8cea2ab 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -307,6 +307,12 @@ function RemoteSubagentRow(props: { const { remoteChild } = props.agent; const status = props.agent.status; const failed = status === "failed"; + const timing = { + status, + startedAt: props.agent.startedAt ? DateTime.formatIso(props.agent.startedAt) : null, + completedAt: props.agent.completedAt ? DateTime.formatIso(props.agent.completedAt) : null, + }; + const showElapsed = !failed && deriveSubagentElapsedMs(timing, 0) !== null; const title = relationshipThreadTitle({ title: props.agent.title ?? gt("Subagent"), isSubagent: true, @@ -348,7 +354,14 @@ function RemoteSubagentRow(props: { on {remoteChild.label} - · {threadRelationshipStatusLabel(status, m)} + + ·{" "} + {showElapsed ? ( + + ) : ( + threadRelationshipStatusLabel(status, m) + )} + diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 3a5ff70fa433d..ccd7451132bbf 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -1,10 +1,10 @@ import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights"; -import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts"; +import { MessageId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup"; import { T, useGT, useMessages } from "gt-react"; -import { memo, use, useState } from "react"; -import { type ChatMessage, type TurnDiffSummary } from "../../types"; +import { use, useState } from "react"; +import { type ChatMessage } from "../../types"; import ChatMarkdown from "../ChatMarkdown"; import { GitForkIcon, ReplyIcon } from "lucide-react"; import { captureAssistantMessageOpening } from "~/lib/assistantTextSelection"; @@ -13,40 +13,21 @@ import { Button } from "../ui/button"; import { ProposedPlanCard } from "./ProposedPlanCard"; import { HtmlRenderFrame } from "./HtmlRenderFrame"; import { McpAppFrame } from "./McpAppFrame"; -import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints"; -import { ChangedFilesCard, type ChangedFilesGroup } from "./ChangedFilesTree"; -import { - changedFileTotals, - turnChanges, - turnHasChanges, -} from "@t3tools/client-runtime/state/thread-repositories"; -import { useFileContextMenuHandler } from "../../fileContextMenu"; -import { - readResponseSubagents, - useAssistantMessageText, - useProject, - useQuietThreadShell, -} from "../../state/entities"; +import { readResponseSubagents, useAssistantMessageText } from "../../state/entities"; import { MessageCopyButton } from "./MessageCopyButton"; import { AssistantCitationSource } from "./AssistantCitationSource"; import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; -import { useUiStateStore } from "~/uiStateStore"; import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat"; import { readThreadTurnItems } from "../../state/entities"; import { useV2ItemSupport } from "../../state/v2ItemSupport"; import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"; -import { useAtomValue } from "@effect/atom-react"; -import { AsyncResult, Atom } from "effect/reactivity"; -import { vcsEnvironment } from "../../state/vcs"; import { SubThreadMetaReply, SubThreadReplyLine } from "../../fork/subThreads/SubThreadReplyLine"; import { AgentMessageDivider } from "../../fork/displayMode/AgentMessageDivider"; import { EditedMark } from "../../fork/displayMode/EditedMark"; -const NO_VCS_STATUS = Atom.make(AsyncResult.initial()); - export function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const gt = useGT(); @@ -94,14 +75,6 @@ export function AssistantTimelineRow({ row }: { row: Extract
- {ctx.onOpenTurnDiff ? ( - - ) : null} {!row.showAssistantMeta && row.projectedItem?.item.status === "interrupted" ? (
@@ -409,7 +382,7 @@ export function HtmlRenderTimelineRow({ return
{ctx.renderHtmlRender(row)}
; } return ( -
+
); } - -/** Subscribes directly to the UI state store for expand/collapse state, - * so toggling re-renders only this component — not the entire list. */ -const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection({ - turnSummary, - routeThreadKey, - resolvedTheme, - onOpenTurnDiff, -}: { - turnSummary: TurnDiffSummary | undefined; - routeThreadKey: string; - resolvedTheme: "light" | "dark"; - displayThreadKey?: string; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; -}) { - if (!turnSummary) return null; - const checkpointFiles = turnSummary.files; - if (!turnHasChanges(turnSummary)) return null; - - return ( - - ); -}); - -function AssistantChangedFilesSectionInner({ - turnSummary, - checkpointFiles, - routeThreadKey, - resolvedTheme, - onOpenTurnDiff, -}: { - turnSummary: TurnDiffSummary; - checkpointFiles: TurnDiffSummary["files"]; - routeThreadKey: string; - resolvedTheme: "light" | "dark"; - displayThreadKey?: string; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; -}) { - const ctx = use(TimelineRowCtx); - const gt = useGT(); - const persistedExpanded = useUiStateStore( - (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId], - ); - const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded); - const allDirectoriesExpanded = persistedExpanded ?? false; - - const thread = useQuietThreadShell(ctx.threadRef); - const activeProject = useProject( - thread && thread.projectId - ? { environmentId: thread.environmentId, projectId: thread.projectId } - : null, - ); - const onFileContextMenu = useFileContextMenuHandler(ctx.activeThreadEnvironmentId); - const repositoryRoot = useAtomValue( - ctx.workspaceRoot - ? vcsEnvironment.status({ - environmentId: ctx.activeThreadEnvironmentId, - input: { cwd: ctx.workspaceRoot }, - }) - : NO_VCS_STATUS, - (status) => AsyncResult.getOrElse(status, () => null)?.workingTree.rootPath, - ); - const repositories = turnSummary.repositories; - const rootGroupName = activeProject?.title ?? gt("Project folder"); - const groups: ReadonlyArray | undefined = - repositories === undefined - ? undefined - : [ - ...(checkpointFiles.length === 0 - ? [] - : [ - { - key: ".", - name: rootGroupName, - files: checkpointFiles, - totals: checkpointFileTotals(turnSummary), - relativePath: "", - }, - ]), - ...repositories.map((repository) => ({ - key: repository.scopeId, - name: repository.name, - files: repository.files, - totals: changedFileTotals(repository), - relativePath: repository.relativePath, - ...(repository.baselineMissing - ? { note: gt("This turn's changes in this repository cannot be listed.") } - : {}), - })), - ]; - const repositoryCwdByGroupKey = new Map( - repositories?.map((repository) => [repository.scopeId as string, repository.cwd]), - ); - - return ( - - setExpanded(routeThreadKey, turnSummary.runId, !allDirectoriesExpanded) - } - onOpenTurnDiff={onOpenTurnDiff} - onFileContextMenu={(filePath, event, group) => { - const repositoryCwd = group && repositoryCwdByGroupKey.get(group.key); - onFileContextMenu( - repositoryCwd === undefined - ? { - environmentId: ctx.activeThreadEnvironmentId, - filePath, - workspaceRoot: ctx.workspaceRoot, - repositoryRoot: - repositoryRoot ?? - (thread?.worktreePath == null - ? activeProject?.repositoryIdentity?.rootPath - : undefined), - } - : { - environmentId: ctx.activeThreadEnvironmentId, - filePath, - workspaceRoot: repositoryCwd, - }, - event, - ); - }} - /> - ); -} diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 6db09e06bf235..3692ed3004334 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -42,6 +42,7 @@ import { type TimelineWorkEntry, type TimelineRow, } from "./timelineRowContext"; +import { ProviderStartingIcon } from "./ProviderStartingIcon"; import { TimelineRowTimestamp, ActivityShimmerOverlay } from "./TimelineRowParts"; import { failedToolIconClassName, @@ -446,8 +447,13 @@ export function ThinkingTimelineRow({ row }: { row: Extract; // A failed group keeps this disclosure while an approval waits, but nothing is thinking then. const live = ctx.pendingApprovals.size === 0; @@ -460,6 +466,15 @@ export function ThinkingTimelineRow({ row }: { row: Extract + ) + } active={live} shimmer={live} /> @@ -481,6 +496,7 @@ export function ThinkingTimelineRow({ row }: { row: Extract {showShimmer ? ( - + ) : null}
@@ -520,6 +545,7 @@ function LiveActivityRow({ function LiveActivityContent({ label, iconName, + iconNode, toolIcon, failed = false, announceFailure = false, @@ -528,6 +554,7 @@ function LiveActivityContent({ }: { label: ReactNode; iconName: WorkEntryIconName | undefined; + iconNode?: ReactNode; toolIcon?: ToolActivityIcon | undefined; failed?: boolean; announceFailure?: boolean; @@ -554,12 +581,16 @@ function LiveActivityContent({ role={announceFailure ? "img" : undefined} aria-label={announceFailure ? gt("Tool call failed") : undefined} > - + {iconNode ? ( + {iconNode} + ) : ( + + )} ) : null } diff --git a/apps/web/src/components/chat/canvasStore.test.ts b/apps/web/src/components/chat/canvasStore.test.ts index c7620f1db5c87..f1e9d4160f2e4 100644 --- a/apps/web/src/components/chat/canvasStore.test.ts +++ b/apps/web/src/components/chat/canvasStore.test.ts @@ -17,6 +17,7 @@ const measurements = (width: number, height = 900): ChatCanvasMeasurements => ({ height, padding: 48, maxChatWidth: 768, + maxHtmlPreviewWidth: 768, minChatWidth: 640, composerHeight: 180, timelineGutter: 0, diff --git a/apps/web/src/components/chat/canvasStore.ts b/apps/web/src/components/chat/canvasStore.ts index 6b350cf95f22f..88811d1a41706 100644 --- a/apps/web/src/components/chat/canvasStore.ts +++ b/apps/web/src/components/chat/canvasStore.ts @@ -17,6 +17,7 @@ export interface ChatCanvasMeasurements { readonly height: number; readonly padding: number; readonly maxChatWidth: number; + readonly maxHtmlPreviewWidth: number; readonly minChatWidth: number; readonly composerHeight: number; readonly timelineGutter: number; @@ -36,6 +37,7 @@ const INITIAL_MEASUREMENTS: ChatCanvasMeasurements = { height: 0, padding: 48, maxChatWidth: 768, + maxHtmlPreviewWidth: 768, minChatWidth: 640, composerHeight: 0, timelineGutter: 0, @@ -52,6 +54,7 @@ const sameMeasurements = (a: ChatCanvasMeasurements, b: ChatCanvasMeasurements) a.height === b.height && a.padding === b.padding && a.maxChatWidth === b.maxChatWidth && + a.maxHtmlPreviewWidth === b.maxHtmlPreviewWidth && a.minChatWidth === b.minChatWidth && a.composerHeight === b.composerHeight && a.timelineGutter === b.timelineGutter && @@ -135,6 +138,7 @@ export function resolveChatCanvasModel({ preview, padding: measurements.padding, maxChatWidth: measurements.maxChatWidth, + maxHtmlPreviewWidth: measurements.maxHtmlPreviewWidth, minChatWidth: measurements.minChatWidth, composerHeight: measurements.composerHeight, detailsCard, diff --git a/apps/web/src/components/chat/chatCanvasLayout.test.ts b/apps/web/src/components/chat/chatCanvasLayout.test.ts index 2f9e82a9e600b..53ee3f6b1ac7b 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.test.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.test.ts @@ -326,6 +326,53 @@ describe("chat canvas layout", () => { }); }); +describe("html preview lane", () => { + const wide = ( + width: number, + options: Partial[0]> = {}, + maxHtmlPreviewWidth = 1152, + ) => + resolveChatCanvasLayout({ + container: { width, height: 900 }, + preview: null, + maxChatWidth: 736, + maxHtmlPreviewWidth, + composerHeight: 180, + ...options, + }); + it("matches the chat column unless the setting allows more", () => { + const result = wide(1600, {}, 736); + expect(result.htmlPreview).toEqual({ left: result.chat.left, width: result.chat.width }); + }); + it("widens around a chat column that stays where it was", () => { + const result = wide(1600); + expect(result.chat).toEqual(wide(1600, {}, 736).chat); + expect(result.htmlPreview).toEqual({ left: 224, width: 1152 }); + expect(wide(1200).htmlPreview).toEqual({ left: 48, width: 1104 }); + expect(wide(1600, {}, 1600).htmlPreview).toEqual({ left: 48, width: 1504 }); + }); + it("is never narrower than the chat column", () => { + const result = wide(1600, { maxChatWidth: 1600 }, 1152); + expect(result.htmlPreview).toEqual({ left: result.chat.left, width: result.chat.width }); + }); + it("stops short of the details card", () => { + const detailsCard = { left: 1308, right: 1588, bottom: 400 }; + const result = wide(1600, { detailsCard }); + expect(result.chat).toEqual(wide(1600, { detailsCard }, 736).chat); + expect(result.htmlPreview).toEqual({ left: 124, width: 1152 }); + expect(wide(1600, { detailsCard }, 1600).htmlPreview).toEqual({ left: 48, width: 1228 }); + }); + it("stops short of a mini player beside the chat and matches chat under one over it", () => { + const beside = wide(1900, { preview: { ...preview, position: { x: 1500, y: 600 } } }); + expect(beside.overlapsChat).toBe(false); + expect(beside.htmlPreview.left + beside.htmlPreview.width).toBe(beside.frame!.x - 12); + expect(beside.htmlPreview.width).toBeGreaterThan(beside.chat.width); + const over = wide(1000, { preview: { ...preview, position: { x: 12, y: 700 } } }); + expect(over.overlapsChat).toBe(true); + expect(over.htmlPreview).toEqual({ left: over.chat.left, width: over.chat.width }); + }); +}); + describe("workspace card beside chat", () => { const withCard = (width: number, player: ChatCanvasPreview | null = null, maxChatWidth = 736) => resolveChatCanvasLayout({ diff --git a/apps/web/src/components/chat/chatCanvasLayout.ts b/apps/web/src/components/chat/chatCanvasLayout.ts index 77e276ee817f4..a1fc0b54b4ab1 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.ts @@ -26,6 +26,7 @@ export function resolveChatCanvasLayout({ preview, padding = 48, maxChatWidth = 768, + maxHtmlPreviewWidth = maxChatWidth, minChatWidth = 640, composerHeight = 0, detailsCard = null, @@ -35,6 +36,7 @@ export function resolveChatCanvasLayout({ preview: ChatCanvasPreview | null; padding?: number; maxChatWidth?: number; + maxHtmlPreviewWidth?: number; minChatWidth?: number; composerHeight?: number; detailsCard?: PreviewMiniPlayerObstacles["detailsCard"]; @@ -176,5 +178,19 @@ export function resolveChatCanvasLayout({ frame.x + frame.width > detailsCard.left && frame.y < detailsCard.bottom, ); - return { chat, frame, overlapsChat, overlapsDetailsCard }; + // A wider HTML preview stays centered on the chat column while that fits, and + // clear of the details card and a mini player the chat column sits beside. + const laneEnd = frame ? Math.min(laneRight, frame.x - GAP) : laneRight; + const htmlPreviewWidth = overlapsChat ? 0 : Math.min(maxHtmlPreviewWidth, laneEnd - padding); + const htmlPreview = + htmlPreviewWidth > chat.width + ? { + left: Math.max( + padding, + Math.min(chat.left + (chat.width - htmlPreviewWidth) / 2, laneEnd - htmlPreviewWidth), + ), + width: htmlPreviewWidth, + } + : { left: chat.left, width: chat.width }; + return { chat, htmlPreview, frame, overlapsChat, overlapsDetailsCard }; } diff --git a/apps/web/src/components/chat/composerFocusRedirect.ts b/apps/web/src/components/chat/composerFocusRedirect.ts index cb187e73ea6a7..2fc544a31c9b4 100644 --- a/apps/web/src/components/chat/composerFocusRedirect.ts +++ b/apps/web/src/components/chat/composerFocusRedirect.ts @@ -12,6 +12,7 @@ const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [ "button", "a[href]", "summary", + "video[controls]", '[role="application"]', '[role="button"]', '[role="checkbox"]', diff --git a/apps/web/src/components/chat/mcpAppDocumentLink.ts b/apps/web/src/components/chat/mcpAppDocumentLink.ts new file mode 100644 index 0000000000000..6982dd3e12a80 --- /dev/null +++ b/apps/web/src/components/chat/mcpAppDocumentLink.ts @@ -0,0 +1,67 @@ +import { MCP_APP_DOCUMENT_MESSAGE } from "@t3tools/shared/mcpApp"; + +const MAX_UNCONFIRMED_MESSAGES = 256; + +interface DocumentLink { + link: MessagePort | "window" | null; + nextProbe: number; + deliver: (data: unknown) => void; + readonly unconfirmed: Map; +} + +// Kept per frame, not per host: a host that re-attaches to the same frame must not take the +// frame's next message for a first one. +const documentLinks = new WeakMap(); + +/** + * Ties the bridge to the frame's first document. A frame's window outlives its document, so the + * bridge follows the port that document's bootstrap sends first, not the window. Servers without + * the bootstrap keep the plain window bridge. + */ +export function attachMcpAppDocumentLink( + frame: HTMLIFrameElement, + deliver: (data: unknown) => void, +) { + let state = documentLinks.get(frame); + if (state === undefined) { + state = { link: null, nextProbe: 0, deliver, unconfirmed: new Map() }; + documentLinks.set(frame, state); + } + const current = state; + current.deliver = deliver; + return { + receive: (event: MessageEvent) => { + if (event.source === null || event.source !== frame.contentWindow) return; + if (current.link === null) { + const port = event.data?.t3 === MCP_APP_DOCUMENT_MESSAGE ? (event.ports[0] ?? null) : null; + if (port !== null) { + current.link = port; + port.onmessage = (reply: MessageEvent) => { + const probe: unknown = reply.data?.alive; + if (typeof probe !== "number" || !current.unconfirmed.has(probe)) return; + const data = current.unconfirmed.get(probe); + current.unconfirmed.delete(probe); + current.deliver(data); + }; + return; + } + current.link = "window"; + } + if (current.link === "window") { + current.deliver(event.data); + return; + } + // Only the first document can answer, so a reply proves it sent this message. + if (current.unconfirmed.size >= MAX_UNCONFIRMED_MESSAGES) return; + current.unconfirmed.set(current.nextProbe, event.data); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- A MessagePort takes no target origin. + current.link.postMessage({ alive: current.nextProbe }); + current.nextProbe += 1; + }, + post: (message: unknown) => { + // Opaque origins require "*"; the window reference scopes delivery to this frame. + if (current.link === "window") frame.contentWindow?.postMessage(message, "*"); + else current.link?.postMessage({ message, origin: window.location.origin }); + }, + }; +} diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts index 0ebfdacdbb607..b752b63ef0bbc 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.test.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -3,6 +3,7 @@ import { ComposerContextId, EnvironmentId, MessageId, + ProviderInstanceId, ThreadId, TurnItemId, } from "@t3tools/contracts"; @@ -27,6 +28,11 @@ import { const environmentId = EnvironmentId.make("remote-environment"); const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit")); const editTarget = DraftId.make("queued-edit:test"); +const originalModelSelection = { + instanceId: ProviderInstanceId.make("codex"), + model: "original-model", +}; +const changedModelSelection = { ...originalModelSelection, model: "changed-model" }; const originalMessage = { editTarget, threadTarget, @@ -153,6 +159,20 @@ describe("queued message file edits", () => { }); it.each([ + { + edit: "changed model", + originalReplyTo: null, + replyTo: null, + modelSelection: changedModelSelection, + result: "kept", + }, + { + edit: "unchanged model", + originalReplyTo: null, + replyTo: null, + modelSelection: originalModelSelection, + result: "clean", + }, { edit: "added reply", originalReplyTo: null, @@ -169,13 +189,25 @@ describe("queued message file edits", () => { }, ])( "reports $result for a queued edit with $edit", - ({ originalReplyTo, replyTo, originalText = "Original message", result }) => { + ({ originalReplyTo, replyTo, originalText = "Original message", modelSelection, result }) => { const store = useComposerDraftStore.getState(); store.setPrompt(editTarget, originalText); store.setReplyTo(editTarget, replyTo); + if (modelSelection) store.setModelSelection(editTarget, modelSelection, { explicit: true }); expect( - recoverQueuedMessageEdit({ editTarget, threadTarget, originalText, originalReplyTo }), + recoverQueuedMessageEdit({ + editTarget, + threadTarget, + originalText, + originalReplyTo, + originalModelSelection, + }), ).toBe(result); + if (result === "kept" && modelSelection) { + expect( + store.getComposerDraft(threadTarget)?.modelSelectionByProvider[modelSelection.instanceId], + ).toEqual(modelSelection); + } expect(store.getComposerDraft(editTarget)).toBeNull(); expect(store.getComposerDraft(threadTarget)).toEqual( result === "kept" ? expect.objectContaining({ prompt: originalText, replyTo }) : null, diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts index ca58777dcb44a..4ea76f7000dcf 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -6,6 +6,7 @@ import type { ComposerContextId, ComposerContextRecord, EnvironmentId, + ModelSelection, OrchestrationMessageContext, ResponseContextRecord, } from "@t3tools/contracts"; @@ -94,12 +95,14 @@ export function discardQueuedEditDraft(target: ComposerThreadTarget): void { } } store.clearComposerContent(target); + store.clearDraftThread(target); } export function recoverQueuedMessageEdit(input: { readonly editTarget: ComposerThreadTarget; readonly threadTarget: ComposerThreadTarget; readonly originalText: string; + readonly originalModelSelection?: ModelSelection; readonly originalReplyTo: ResponseContextRecord | null; readonly removedExistingAttachment?: boolean; readonly existingAttachmentContextIds?: ReadonlyArray; @@ -117,8 +120,14 @@ export function recoverQueuedMessageEdit(input: { draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt ? { ...draft, prompt: strippedPrompt } : draft; + const modelSelection = draft?.activeProvider + ? draft.modelSelectionByProvider[draft.activeProvider] + : undefined; + const modelChanged = + modelSelection !== undefined && !Equal.equals(modelSelection, input.originalModelSelection); const recovery = resolveQueuedEditExit({ editChanged: + modelChanged || input.removedExistingAttachment === true || !Equal.equals(draft?.replyTo ?? null, input.originalReplyTo) || (draft !== null && @@ -133,7 +142,13 @@ export function recoverQueuedMessageEdit(input: { store.setPrompt(input.editTarget, strippedPrompt); } store.moveComposerContent(input.editTarget, input.threadTarget); + if (modelChanged) + store.setModelSelection(input.threadTarget, modelSelection, { + explicit: true, + replaceOptions: true, + }); store.clearComposerContent(input.editTarget); + store.clearDraftThread(input.editTarget); } else { discardQueuedEditDraft(input.editTarget); } diff --git a/apps/web/src/components/chat/runtimeModeConfig.test.ts b/apps/web/src/components/chat/runtimeModeConfig.test.ts new file mode 100644 index 0000000000000..580fe7e43a268 --- /dev/null +++ b/apps/web/src/components/chat/runtimeModeConfig.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { draftSupportedRuntimeModes, resolveCompatibleRuntimeMode } from "./runtimeModeConfig"; + +describe("draftSupportedRuntimeModes", () => { + const supervisedOnly = { + instanceId: "fx", + supportedRuntimeModes: ["approval-required"], + } as const; + const noAuto = { + instanceId: "muse", + supportedRuntimeModes: ["approval-required", "full-access"], + } as const; + const everyMode = { instanceId: "codex" }; + const providers = [supervisedOnly, noAuto, everyMode]; + + it.each([ + { label: "one provider that supports it", selections: [supervisedOnly, noAuto] }, + { label: "a provider that reports no modes", selections: [supervisedOnly, everyMode] }, + ])("shows Full access when a multi-model draft includes $label", ({ selections }) => { + const modes = draftSupportedRuntimeModes( + supervisedOnly.supportedRuntimeModes, + selections, + providers, + ); + expect(resolveCompatibleRuntimeMode("full-access", modes).mode).toBe("full-access"); + }); + + it("falls back only when no selected provider can run the mode", () => { + const modes = draftSupportedRuntimeModes(undefined, [supervisedOnly, noAuto], providers); + expect(resolveCompatibleRuntimeMode("auto", modes).mode).toBe("approval-required"); + }); +}); diff --git a/apps/web/src/components/chat/runtimeModeConfig.ts b/apps/web/src/components/chat/runtimeModeConfig.ts index b4f77f2ca5d62..89655258ff935 100644 --- a/apps/web/src/components/chat/runtimeModeConfig.ts +++ b/apps/web/src/components/chat/runtimeModeConfig.ts @@ -51,6 +51,31 @@ export function resolveCompatibleRuntimeMode( return { modes, mode: modes.includes(runtimeMode) ? runtimeMode : (modes[0] ?? runtimeMode) }; } +/** + * The modes a draft's send can run in. A multi-model send gives every thread the draft's mode + * and only that thread's provider narrows it, so the composer offers what any of them supports. + */ +export function draftSupportedRuntimeModes( + activeProviderModes: ReadonlyArray | undefined, + multipleModelSelections: ReadonlyArray<{ readonly instanceId: string }> | null, + providers: ReadonlyArray<{ + readonly instanceId: string; + readonly supportedRuntimeModes?: ReadonlyArray | undefined; + }>, +) { + if (multipleModelSelections === null || multipleModelSelections.length === 0) { + return activeProviderModes; + } + const supported = multipleModelSelections.map( + (selection) => + providers.find((provider) => provider.instanceId === selection.instanceId) + ?.supportedRuntimeModes ?? [], + ); + // A provider that reports no modes supports them all. + if (supported.some((modes) => modes.length === 0)) return undefined; + return runtimeModeOptions.filter((mode) => supported.some((modes) => modes.includes(mode))); +} + export function resolveRuntimeModeOption( mode: RuntimeMode, resolve: MessageResolver = m, diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 456bcff3ffa90..7d12a79757f77 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -1,5 +1,6 @@ import type { ToolCallDiffTarget } from "../../diffPanelStore"; import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/models"; import type { ProviderApprovalDecision, ResponseContextRecord, @@ -77,8 +78,6 @@ export interface TimelineRowSharedState { onImageExpand: (preview: ExpandedImagePreview) => void; displayThreadKey?: string; onOpenToolDiff: ((target: ToolCallDiffTarget) => void) | undefined; - /** Unset where there is no diff to open, so the timeline shows no "Open diff" button. */ - onOpenTurnDiff: ((runId: RunId, filePath?: string) => void) | undefined; /** * Draws a published HTML visual. Unset, the row loads it from the environment; the guest page * loads it through its own route. @@ -120,6 +119,7 @@ export interface TimelineRowActivityState { awaitingUser: boolean; isPreparingWorktree: boolean; providerStartingLabel: string | null; + providerStarting: NonNullable | null; latestRunId: RunId | null; backgroundWorktreeSetup: WorktreeSetupSnapshot | null; liveAnswerPreview: string | null; diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx index 61127d1a9d9c8..378bc2b5cce74 100644 --- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx +++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx @@ -245,3 +245,21 @@ it("runs right panel commands from inside a side chat pane, but not thread comma expect(ran).toEqual(["toggle", "close", "toggle"]); }); + +it("leaves keys to a focused video player with controls", async () => { + const composerKeys: string[] = []; + await using _screen = await render( + <> + +
+ {unseenHeadSha !== undefined && shownHeadSha !== undefined ? ( +
+ + + + {gt("New commits were pushed. A merge or review still applies to {sha}.", { + sha: shownHeadSha.slice(0, 7), + })} + + + + + +
+ ) : null} {detail ? ( void; }) { const gt = useGT(); - const shownQuery = query.length > 48 ? `${query.slice(0, 48)}…` : query; + const shownQuery = + query.length > 48 ? `${query.slice(0, splitsSurrogatePair(query, 48) ? 47 : 48)}…` : query; if (!hasProjects) { return ( diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx index e2c222acbcbe2..8a34e35eff968 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.browser.test.tsx @@ -37,6 +37,7 @@ it("submits only the line comments still in the draft when dictation finishes", active environmentId={EnvironmentId.make("test")} reference={reference} + headSha="reviewed-head" completionScope={null} term="pr" verdicts={["comment"]} @@ -45,6 +46,7 @@ it("submits only the line comments still in the draft when dictation finishes", pending={false} onPendingChange={vi.fn()} onSubmitted={vi.fn()} + onRefused={vi.fn()} />, ); await screen.getByRole("button", { name: "Submit review" }).click(); @@ -52,7 +54,11 @@ it("submits only the line comments still in the draft when dictation finishes", await act(() => mocks.queue.mock.calls[0]![0]("Dictated summary")); expect(mocks.submit).toHaveBeenCalledWith( expect.objectContaining({ - input: expect.objectContaining({ body: "Dictated summary", comments: [] }), + input: expect.objectContaining({ + body: "Dictated summary", + comments: [], + expectedHeadSha: "reviewed-head", + }), }), ); }); diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx index d581c6c9e2f06..6cedcd7a1d492 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx @@ -63,6 +63,7 @@ export function PullRequestReviewForm({ environmentId, active, reference, + headSha, completionScope, term, verdicts, @@ -71,11 +72,14 @@ export function PullRequestReviewForm({ pending, onPendingChange, onSubmitted, + onRefused, }: { environmentId: EnvironmentId; /** False while the form stays mounted but hidden; dictation is cancelled then. */ active: boolean; reference: PullRequestRef; + /** The head on screen, which the review is pinned to. */ + headSha: string | undefined; completionScope: PullRequestCompletionScope | null; term: ChangeRequestTermKind; verdicts: ReadonlyArray; @@ -84,6 +88,7 @@ export function PullRequestReviewForm({ pending: boolean; onPendingChange: (pending: boolean) => void; onSubmitted: () => void; + onRefused: () => void; }) { const gt = useGT(); const resolve = useMessages(); @@ -125,6 +130,7 @@ export function PullRequestReviewForm({ environmentId, input: { ...reference, + ...(headSha === undefined ? {} : { expectedHeadSha: headSha }), verdict: verdict.value, body: submittedBody, comments: submittedComments, @@ -140,6 +146,7 @@ export function PullRequestReviewForm({ m(msg("The host refused the review. Your draft is still here to try again.")), ), }); + onRefused(); return; } // Preserve comments and summary edits made during submission. diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsx index cd1aae26dfc95..872cd534de991 100644 --- a/apps/web/src/components/pullRequest/PullRequestRow.tsx +++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx @@ -1,4 +1,5 @@ import type { PullRequestAction } from "@t3tools/contracts"; +import { contextMenuSourceOf } from "../../contextMenuSource"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { T } from "gt-react"; import { SearchIcon } from "lucide-react"; @@ -153,6 +154,7 @@ function PullRequestRowImpl({ url: entry.url, openLabel: openOnHostLabel(sourceControlClients.get(entry.provider)), position: { x: event.clientX, y: event.clientY }, + source: contextMenuSourceOf(event), }); }} > diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx index 2aed048ba9662..fd4278c219538 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx @@ -3,17 +3,19 @@ import { EnvironmentId, ProjectId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; -const state = vi.hoisted(() => ({ detail: "" })); +const state = vi.hoisted(() => ({ detail: "", sent: [] as unknown[] })); vi.mock(import("~/state/use-atom-command"), async () => { const { PullRequestOperationError } = await import("@t3tools/contracts"); const { Cause } = await import("effect"); const { AsyncResult } = await import("effect/reactivity"); return { - useAtomCommand: (() => async () => - AsyncResult.failure( + useAtomCommand: (() => async (call: { readonly input: unknown }) => { + state.sent.push(call.input); + return AsyncResult.failure( Cause.fail(new PullRequestOperationError({ operation: "runAction", detail: state.detail })), - )) as never, + ); + }) as never, }; }); @@ -24,6 +26,7 @@ import { PullRequestStackMenu } from "./PullRequestStackMenu"; function setup(detail: string) { state.detail = detail; + state.sent = []; } const HEAD_MOVED = "The stack head moved. Refresh the stack before trying again."; @@ -58,8 +61,13 @@ it.each([ layers: [{ number: 2, headBranch: "feature", headSha: "abc123", state: "open" }], }} canMerge + shownHeadSha="shown" stale={false} canRebase + canAutoMerge={false} + preferAutoMerge={false} + autoMergeArmed={false} + canCancelAutoMerge={false} mergeMethod="squash" onActed={() => {}} /> @@ -73,4 +81,13 @@ it.each([ } await page.getByRole("dialog").getByRole("button", { name: row.label, exact: true }).click(); await expect.element(page.getByText(row.description, { exact: true })).toBeInTheDocument(); + // The stack's own read can be ahead of the head the reader was shown; a merge lands only that one. + expect(state.sent).toEqual([ + expect.objectContaining( + row.label === "Merge stack" + ? { expectedHeadSha: "shown", expectedStackHeads: [{ number: 2, headSha: "abc123" }] } + : { action: "update-branch" }, + ), + ]); + if (row.label !== "Merge stack") expect(state.sent[0]).not.toHaveProperty("expectedHeadSha"); }); diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx index e2300578f4b76..299f919bfab87 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx @@ -6,7 +6,7 @@ import type { PullRequestMergeMethod, } from "@t3tools/contracts"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; -import { RefreshCwIcon, TriangleAlertIcon } from "lucide-react"; +import { ClockIcon, RefreshCwIcon, TriangleAlertIcon, XIcon } from "lucide-react"; import { msg, T, useGT, Var } from "gt-react"; import { useState } from "react"; @@ -30,7 +30,7 @@ import { PullRequestStackLayers } from "./PullRequestStackLayers"; import { PullRequestStackHeader } from "./PullRequestStackHeader"; import { PullRequestStackLayerContent } from "./PullRequestStackLayerContent"; import { PullRequestGlyph } from "./pullRequestIcons"; -import { readableFailure } from "./pullRequestDetail.logic"; +import { mergeHeadPin, readableFailure } from "./pullRequestDetail.logic"; import { changeRequestTermKind } from "./changeRequestTerm"; @@ -40,9 +40,14 @@ export function PullRequestStackMenu({ stack, reference, environmentId, + shownHeadSha, stale, canMerge, canRebase, + canAutoMerge, + preferAutoMerge, + autoMergeArmed, + canCancelAutoMerge, mergeMethod, onSelect, onActed, @@ -56,16 +61,27 @@ export function PullRequestStackMenu({ stack: PullRequestStack; reference: PullRequestRef; environmentId: EnvironmentId; + /** The head of `reference` the reader was shown; the stack read can run ahead of it. */ + shownHeadSha: string | undefined; stale: boolean; canMerge: boolean; canRebase: boolean; + /** The host can arm auto-merge for this layer and the open layers below it. */ + canAutoMerge: boolean; + /** Checks are still running, so arming auto-merge leads over merging now. */ + preferAutoMerge: boolean; + /** This layer carries a stack auto-merge request, which covers the layers below it. */ + autoMergeArmed: boolean; + canCancelAutoMerge: boolean; mergeMethod: PullRequestMergeMethod; onSelect?: ((reference: PullRequestRef) => void) | undefined; onActed: () => void; }) { const gt = useGT(); const [open, setOpen] = useState(false); - const [confirmation, setConfirmation] = useState<"merge" | "update-branch" | null>(null); + const [confirmation, setConfirmation] = useState< + "merge" | "enable-auto-merge" | "update-branch" | null + >(null); const [pending, setPending] = useState(false); const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false }); const top = stack.layers.at(-1); @@ -93,20 +109,30 @@ export function PullRequestStackMenu({ if ( pending || !confirmation || - (confirmation === "merge" ? !canMerge || mergeDisabled : !canRebase || rebaseDisabled) + (confirmation === "merge" + ? !canMerge || mergeDisabled + : confirmation === "enable-auto-merge" + ? !canAutoMerge || autoMergeArmed || mergeDisabled + : !canRebase || rebaseDisabled) ) return; const action = confirmation; - const target = action === "merge" ? selectedLayer : top; + const merging = action !== "update-branch"; + const target = merging ? selectedLayer : top; if (!target?.headSha) return; - const actionHeads = (action === "merge" ? mergeLayers : unmerged).flatMap((layer) => + const actionHeads = (merging ? mergeLayers : unmerged).flatMap((layer) => layer.headSha ? [{ number: layer.number, headSha: layer.headSha }] : [], ); setPending(true); setConfirmation(null); const toastId = toastManager.add({ type: "loading", - title: action === "merge" ? m(msg("Merging stack...")) : m(msg("Rebasing stack...")), + title: + action === "merge" + ? m(msg("Merging stack...")) + : action === "enable-auto-merge" + ? m(msg("Enabling stack auto-merge...")) + : m(msg("Rebasing stack...")), }); const result = await runAction({ environmentId, @@ -115,8 +141,9 @@ export function PullRequestStackMenu({ number: target.number, stackNumber: stack.number, expectedStackHeads: actionHeads, + ...mergeHeadPin(action, shownHeadSha), action, - ...(action === "merge" ? { mergeMethod } : { updateMethod: "rebase" }), + ...(merging ? { mergeMethod } : { updateMethod: "rebase" }), }, }); setPending(false); @@ -127,10 +154,12 @@ export function PullRequestStackMenu({ title: action === "merge" ? m(msg("Could not merge the stack")) - : m(msg("Could not rebase the stack")), + : action === "enable-auto-merge" + ? m(msg("Could not enable stack auto-merge")) + : m(msg("Could not rebase the stack")), description: readableFailure( squashAtomCommandFailure(result), - action === "merge" + merging ? m( msg( "The host refused the merge. Check that you have write access, that the checks it requires have passed, and that the branch is not conflicting.", @@ -147,15 +176,47 @@ export function PullRequestStackMenu({ toastManager.update(toastId, { type: "success", title: - action === "merge" ? m(msg("Stack merge request completed")) : m(msg("Stack rebased")), + action === "merge" + ? m(msg("Stack merge request completed")) + : action === "enable-auto-merge" + ? m(msg("Stack auto-merge enabled")) + : m(msg("Stack rebased")), description: action === "merge" ? m(msg("{host} merged the stack or added it to its merge queue.", { host: hostLabel })) - : undefined, + : action === "enable-auto-merge" + ? m( + msg("{host} merges the stack through #{number} once its requirements are met.", { + host: hostLabel, + number: reference.number, + }), + ) + : undefined, + }); + } + }; + const cancelAutoMerge = async () => { + if (pending || !canCancelAutoMerge) return; + setPending(true); + const result = await runAction({ + environmentId, + input: { ...reference, stackNumber: stack.number, action: "disable-auto-merge" }, + }); + setPending(false); + onActed(); + if (result._tag === "Failure") { + toastManager.add({ + type: "error", + title: m(msg("Could not cancel stack auto-merge")), + description: readableFailure( + squashAtomCommandFailure(result), + m(msg("The host refused to cancel auto-merge. Refresh and try again.")), + ), }); } }; - const confirmationLayers = confirmation === "merge" ? mergeLayers : unmerged; + const confirmationLayers = confirmation === "update-branch" ? unmerged : mergeLayers; + const leadsWithAutoMerge = canAutoMerge && preferAutoMerge; return ( <> @@ -211,10 +272,10 @@ export function PullRequestStackMenu({ } /> - {canMerge || canRebase ? ( + {canMerge || canRebase || canAutoMerge || canCancelAutoMerge ? ( <> - {canMerge ? ( + {canMerge && !autoMergeArmed ? ( setConfirmation("merge")}> @@ -222,6 +283,23 @@ export function PullRequestStackMenu({ ) : null} + {canAutoMerge && !autoMergeArmed ? ( + setConfirmation("enable-auto-merge")} + > + + + Auto-merge stack ({mergeLayers.length}) + + + ) : null} + {autoMergeArmed && canCancelAutoMerge ? ( + void cancelAutoMerge()}> + + Cancel stack auto-merge + + ) : null} {canRebase ? ( - {canMerge && selectedLayer?.state === "open" ? ( + {(leadsWithAutoMerge || canMerge) && !autoMergeArmed && selectedLayer?.state === "open" ? ( setConfirmation("merge")} + onClick={ + mergeDisabled + ? undefined + : () => setConfirmation(leadsWithAutoMerge ? "enable-auto-merge" : "merge") + } > - - Merge stack + {leadsWithAutoMerge ? ( + + ) : ( + + )} + {leadsWithAutoMerge ? Auto-merge stack : Merge stack} } @@ -291,13 +377,21 @@ export function PullRequestStackMenu({ term: changeRequestTermKind(terminology), }, ) - : gt( - "{count, plural, one {Rebase {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Rebase {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", - { - count: unmerged.length, - term: changeRequestTermKind(terminology), - }, - )} + : confirmation === "enable-auto-merge" + ? gt( + "{count, plural, one {Auto-merge {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Auto-merge {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + { + count: mergeLayers.length, + term: changeRequestTermKind(terminology), + }, + ) + : gt( + "{count, plural, one {Rebase {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Rebase {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + { + count: unmerged.length, + term: changeRequestTermKind(terminology), + }, + )} {confirmation === "merge" @@ -310,10 +404,20 @@ export function PullRequestStackMenu({ host: hostLabel, }, ) - : gt( - "Rebase the remote branches from bottom to top onto {base}. This rewrites branch history and may restart checks. If a layer fails, earlier updates remain.", - { base: stack.base }, - )} + : confirmation === "enable-auto-merge" + ? gt( + "Merge #{number} and its unmerged layers below into {base} using {method} once every one of them meets the requirements on {host}. This may happen immediately.", + { + number: reference.number, + base: stack.base, + method: mergeMethod, + host: hostLabel, + }, + ) + : gt( + "Rebase the remote branches from bottom to top onto {base}. This rewrites branch history and may restart checks. If a layer fails, earlier updates remain.", + { base: stack.base }, + )} @@ -333,7 +437,11 @@ export function PullRequestStackMenu({ Cancel diff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx new file mode 100644 index 0000000000000..1e4de32289e69 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx @@ -0,0 +1,59 @@ +import { createRef, type RefObject } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../../test/render"; +import { PullRequestsColumn } from "./PullRequestsColumn"; + +function createColumn(maximizedAway: boolean, scrollRef: RefObject) { + return ( + {}} + searchValue="" + involvement="all" + state="open" + host={undefined} + hostMenuOptions={[]} + onInvolvement={() => {}} + onState={() => {}} + onHost={() => {}} + searchInput={} + sortMenu={null} + filtersMenu={null} + savedViewsMenu={null} + rightPanelControl={null} + titlebarControls={null} + rightPanelOpen={maximizedAway} + maximizedAway={maximizedAway} + listBody={null} + scrollRef={scrollRef} + /> + ); +} + +function dispatchFindShortcut() { + const event = new KeyboardEvent("keydown", { + key: "f", + ctrlKey: true, + bubbles: true, + cancelable: true, + }); + window.dispatchEvent(event); + return event; +} + +describe("PullRequestsColumn find shortcut", () => { + it("leaves Cmd/Ctrl+F to the browser while the detail panel is maximized", async () => { + const scrollRef = createRef(); + await using screen = await render(createColumn(false, scrollRef)); + + await screen.rerender(createColumn(true, scrollRef)); + expect(dispatchFindShortcut().defaultPrevented).toBe(false); + + await screen.rerender(createColumn(false, scrollRef)); + expect(dispatchFindShortcut().defaultPrevented).toBe(true); + await expect + .element(screen.getByRole("textbox", { name: "Search pull requests" })) + .toHaveFocus(); + }); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx index fdfe825790ba6..d4ca6d0d3b7e2 100644 --- a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx @@ -138,6 +138,7 @@ export function PullRequestsColumn({ const searchExpanded = searchOpen || searchValue.length > 0; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener focuses the visible search input on Cmd/Ctrl+F useEffect(() => { + if (maximizedAway) return; const onKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented) return; if (event.key.toLowerCase() !== "f" || !(event.metaKey || event.ctrlKey)) return; @@ -151,7 +152,7 @@ export function PullRequestsColumn({ }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [condensed]); + }, [condensed, maximizedAway]); if (!condensed && searchOpen) setSearchOpen(false); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves DOM focus to the in-flow search when the topbar search it was typed in unmounts useEffect(() => { diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 3d0ae22b15017..a71bc0d2db367 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -60,6 +60,7 @@ import { pullRequestLinkSubject, writePullRequestDetailSnapshot, readableFailure, + seenPullRequestHead, } from "./pullRequestDetail.logic"; import type { ReviewCommentContext } from "~/reviewCommentContext"; @@ -2058,6 +2059,19 @@ describe("single-PR merge compatibility during stack discovery", () => { ); }); +describe("seenPullRequestHead", () => { + it("takes the first settled head and keeps it until another pull request is shown", () => { + // A stored answer paints before the read settles, and is not what the reader ends up seeing. + const loading = seenPullRequestHead(null, "pr-1", undefined); + expect(loading).toEqual({ key: "pr-1", sha: undefined }); + const seen = seenPullRequestHead(loading, "pr-1", "a"); + expect(seen).toEqual({ key: "pr-1", sha: "a" }); + expect(seenPullRequestHead(seen, "pr-1", "b")).toBe(seen); + expect(seenPullRequestHead(seen, "pr-1", undefined)).toBe(seen); + expect(seenPullRequestHead(seen, "pr-2", "c")).toEqual({ key: "pr-2", sha: "c" }); + }); +}); + describe("readableFailure", () => { it("replaces a host tool's bare failure with the hint, for every host", () => { for (const message of [ diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index d98ec3ff114ec..ad9285f6fc322 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -1543,6 +1543,27 @@ const TOOL_NOISE = [ const FAILURE_DETAIL_MAX_LENGTH = 320; +/** + * The head a reader was first shown. A background refresh does not move it, so a merge or review + * keeps applying to the commits they read until they load the newer ones. + */ +export function seenPullRequestHead( + seen: { readonly key: string; readonly sha: string | undefined } | null, + key: string, + settledHead: string | undefined, +) { + return seen !== null && seen.key === key && (seen.sha !== undefined || settledHead === undefined) + ? seen + : { key, sha: settledHead }; +} + +/** A merge lands the head the reader was shown, so it refuses a head that moved since. */ +export function mergeHeadPin(action: PullRequestAction, headSha: string | undefined) { + return (action === "merge" || action === "enable-auto-merge") && headSha !== undefined + ? { expectedHeadSha: headSha } + : {}; +} + export function readableFailure(failure: unknown, hint: string): string { const raw = failure instanceof Error ? failure.message : typeof failure === "string" ? failure : ""; diff --git a/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts index a830180ccb96c..8e883ca8cde8c 100644 --- a/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts +++ b/apps/web/src/components/pullRequest/pullRequestLinkContextMenu.ts @@ -1,4 +1,4 @@ -import type { ContextMenuItem } from "@t3tools/contracts"; +import type { ContextMenuItem, ContextMenuSource } from "@t3tools/contracts"; import { type SourceControlDefinition, UNKNOWN_SOURCE_CONTROL_CLIENT, @@ -35,16 +35,22 @@ export async function showPullRequestLinkContextMenu({ url, openLabel, position, + source, }: { readonly url: string; readonly openLabel: string; readonly position: { readonly x: number; readonly y: number }; + readonly source: ContextMenuSource; }): Promise { const api = readLocalApi(); if (!api) return; let action: PullRequestLinkContextMenuAction | null = null; try { - action = await api.contextMenu.show(pullRequestLinkContextMenuItems(openLabel), position); + action = await api.contextMenu.show( + pullRequestLinkContextMenuItems(openLabel), + position, + source, + ); } catch { return; } diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx index 79089c0a858c6..4b62dd0ae3266 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx @@ -35,6 +35,7 @@ function MergeButton({ reference }: { reference: PullRequestRef }) { const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId: EnvironmentId.make("environment"), reference, + headSha: `head-${reference.number}`, terminology: sourceControlClients.get(undefined).changeRequest, }); return ( @@ -81,6 +82,11 @@ it("keeps pending merges with their pull request when navigating between threads await expect.element(button).toBeEnabled(); await userEvent.click(button); expect(state.runAction).toHaveBeenCalledTimes(2); + // Each merge is pinned to the head its own row showed. + expect(state.runAction.mock.calls.map(([call]) => call.input.expectedHeadSha)).toEqual([ + "head-1", + "head-2", + ]); await screen.rerender(); await expect.element(button).toHaveTextContent("Merging..."); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index f7885e098d3c3..3c016af497c0f 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -44,6 +44,7 @@ import { offHeadPullRequestCheckoutToast } from "./pullRequestCheckoutToast"; import { checkoutFailureDescription, appendHandoff, + mergeHeadPin, readableFailure, } from "./pullRequestDetail.logic"; import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic"; @@ -187,12 +188,17 @@ const actionFailureHints = (term: ChangeRequestTermKind): Record void; terminology: ChangeRequestTerminology; onSuccess?: (action: PullRequestAction, reply: PullRequestSummary | undefined) => void; /** Resolve repository settings on click to avoid per-row reads. */ @@ -227,6 +233,7 @@ export function usePullRequestActionRunner({ input: { ...reference, action, + ...mergeHeadPin(action, headSha), ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}), }, }); @@ -241,6 +248,7 @@ export function usePullRequestActionRunner({ actionFailureHints(changeRequestTermKind(terminology))[action], ), }); + onFailure?.(action); return; } toastManager.add({ diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index af04218c5545d..5aeb865f2cf94 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -5,6 +5,7 @@ import { DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE, DEFAULT_UNIFIED_SETTINGS, type ChatWidth, + type HtmlPreviewWidth, type EffortDisplay, type EnvironmentIdentificationMode, MAX_APPEARANCE_CONTRAST, @@ -81,6 +82,12 @@ const CHAT_WIDTH_LABELS: Record = { full: msg("Full", { $context: "chat width" }), }; +const HTML_PREVIEW_WIDTH_LABELS: Record = { + chat: msg("Match chat", { $context: "HTML preview width" }), + wide: CHAT_WIDTH_LABELS.wide, + full: CHAT_WIDTH_LABELS.full, +}; + const EFFORT_DISPLAY_LABELS: Record = { label: msg("Word", { $context: "show effort as a word" }), bars: msg("Bars", { $context: "show effort as bars" }), @@ -295,6 +302,48 @@ export function AppearanceSettingsPanel() {
} /> + + updateSettings({ htmlPreviewWidth: DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth }) + } + /> + ) : null + } + control={ +
+ +
+ } + /> ReactNode; +}) { + const { rowCount } = props; + const [view, setView] = useState({ + near: props.initiallyMounted, + rowHeight: ESTIMATED_ARCHIVED_ROW_PX, + }); + return ( +
{ + if (!node) return; + return observeIntersection( + node, + (entry) => + setView({ + near: entry.isIntersecting, + rowHeight: entry.boundingClientRect.height / rowCount, + }), + { root: node.closest("[data-settings-page-scroll]"), rootMargin: "1200px 0px" }, + ); + }} + className="*:not-first:border-t *:not-first:border-border/50" + style={view.near ? undefined : { height: view.rowHeight * rowCount }} + > + {view.near ? props.renderRows() : null} +
+ ); +} + export function ArchivedThreadsPanel() { const searchableSetting = useSearchableSetting(); const gt = useGT(); @@ -139,15 +179,21 @@ export function ArchivedThreadsPanel() { } } } - const sortedGroups = Array.from(groups, ([key, group]) => ({ - ...group, - key, - threads: group.threads.toSorted((left, right) => { - const leftKey = left.archivedAt ?? left.createdAt; - const rightKey = right.archivedAt ?? right.createdAt; - return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id); - }), - })); + const sortedGroups = []; + let firstRow = 0; + for (const [key, group] of groups) { + sortedGroups.push({ + ...group, + key, + firstRow, + threads: group.threads.toSorted((left, right) => { + const leftKey = left.archivedAt ?? left.createdAt; + const rightKey = right.archivedAt ?? right.createdAt; + return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id); + }), + }); + firstRow += group.threads.length; + } return { groups: sortedGroups, hasMultipleEnvironments }; })(); @@ -192,7 +238,11 @@ export function ArchivedThreadsPanel() { ); }; - const handleContextMenu = async (thread: ArchivedThread, position: { x: number; y: number }) => { + const handleContextMenu = async ( + thread: ArchivedThread, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => { const pending = pendingActionsRef.current; if (pending.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)))) return; const result = await settlePromise(async () => { @@ -203,6 +253,7 @@ export function ArchivedThreadsPanel() { destructive: action === "delete", })), position, + source, ); if (clicked === "unarchive" || clicked === "delete") await handleThreadAction(clicked, thread); @@ -210,6 +261,58 @@ export function ArchivedThreadsPanel() { reportFailure(result, gt("Archived thread action failed")); }; + const renderRow = (thread: ArchivedThread) => { + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + return ( + { + event.preventDefault(); + void handleContextMenu( + thread, + { x: event.clientX, y: event.clientY }, + contextMenuSourceOf(event), + ); + }} + title={thread.title} + description={ + + {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null} + + Archived + {" \u00b7 Created "} + + + + } + control={ +
+ {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => ( + + void handleThreadAction(action, thread)} + /> + } + > + + + {m(label)} + + ))} +
+ } + /> + ); + }; + return ( {archivedGroups.length === 0 ? ( @@ -240,59 +343,28 @@ export function ArchivedThreadsPanel() { /> ) : ( - archivedGroups.map(({ key, project, title, threads: projectThreads }, index) => ( + archivedGroups.map(({ key, project, title, firstRow, threads: projectThreads }, index) => ( } > - {projectThreads.map((thread) => { - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - return ( - { - event.preventDefault(); - void handleContextMenu(thread, { x: event.clientX, y: event.clientY }); - }} - title={thread.title} - description={ - - {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null} - - Archived - {" \u00b7 Created "} - - - - } - control={ -
- {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => ( - - void handleThreadAction(action, thread)} - /> - } - > - - - {m(label)} - - ))} -
- } - /> - ); - })} + {Array.from( + { length: Math.ceil(projectThreads.length / ARCHIVED_ROW_CHUNK_SIZE) }, + (_, chunkIndex) => { + const start = chunkIndex * ARCHIVED_ROW_CHUNK_SIZE; + const rows = projectThreads.slice(start, start + ARCHIVED_ROW_CHUNK_SIZE); + return ( + rows.map(renderRow)} + /> + ); + }, + )}
)) )} diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 0a992f4f93b61..3d41537abf182 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -13,6 +13,7 @@ import { } from "@t3tools/client-runtime/voice-input"; import { AuthOrchestrationOperateScope, + AuthProvidersManageScope, AuthSettingsWriteScope, CloudSpeechApiKey, CloudSpeechModelId, @@ -176,6 +177,7 @@ export function CloudVoiceConfiguration({ const prepared = Option.getOrNull(usePreparedConnection(id)); const canUse = useEnvironmentScope(id, AuthOrchestrationOperateScope); const canManage = useEnvironmentScope(id, AuthSettingsWriteScope); + const canUseReferences = useEnvironmentScope(id, AuthProvidersManageScope); const [presence, refresh] = useCloudRead(canUse ? prepared : null, getCloudSpeechKeys); const [models, refreshModels] = useCloudRead( routed && canUse ? prepared : null, @@ -194,6 +196,7 @@ export function CloudVoiceConfiguration({ const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined; const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider]; const sources = + canUseReferences && hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) diff --git a/apps/web/src/components/settings/CustomModelEditor.tsx b/apps/web/src/components/settings/CustomModelEditor.tsx index aab653ac9f695..31b67ee8afd69 100644 --- a/apps/web/src/components/settings/CustomModelEditor.tsx +++ b/apps/web/src/components/settings/CustomModelEditor.tsx @@ -308,8 +308,10 @@ export function CustomModelEditor({
{ + if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Escape") { event.preventDefault(); + event.stopPropagation(); onCancel(); } }} diff --git a/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx b/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx index 39b9cac03ede1..17689eb8581fb 100644 --- a/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx +++ b/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx @@ -3,6 +3,7 @@ import { BearerConnectionTarget, type ConnectionCatalogEntry, type ConnectionRoute, + mergeLearnedRoutes, } from "@t3tools/client-runtime/connection"; import { EnvironmentId } from "@t3tools/contracts"; import * as Option from "effect/Option"; @@ -91,3 +92,22 @@ it("shows a route added after a reorder was saved, once another route is removed .element(screen.getByRole("button", { name: "Remove desk.example.com route" })) .toBeVisible(); }); + +it("does not offer to remove the only route a found-automatically route depends on", async () => { + const paired: ConnectionCatalogEntry = { + target: LAN.target, + profile: LAN.profile, + alternateRoutes: [], + enabled: true, + }; + const learned = mergeLearnedRoutes({ + entry: paired, + activeRoute: LAN, + reported: [{ httpBaseUrl: "https://desk.tail1234.ts.net/", kind: "tailnet" }], + allowInsecure: true, + })!; + await using screen = await render(routesList(learned)); + await expect.element(screen.getByText(/found automatically/)).toBeVisible(); + + expect(screen.getByRole("button", { name: "Remove LAN route" }).elements()).toHaveLength(0); +}); diff --git a/apps/web/src/components/settings/EnvironmentRoutesList.tsx b/apps/web/src/components/settings/EnvironmentRoutesList.tsx index f559f85ce80f7..f4b9a1593b9d8 100644 --- a/apps/web/src/components/settings/EnvironmentRoutesList.tsx +++ b/apps/web/src/components/settings/EnvironmentRoutesList.tsx @@ -17,6 +17,7 @@ import { } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { + canRemoveRoute, type ConnectionRoute, connectionRouteAddress, connectionRouteId, @@ -121,7 +122,7 @@ export function EnvironmentRoutesList({ position={index + 1} inUse={connectionRouteId(route.target) === activeRouteId} refused={environment.refusedRouteIds.includes(connectionRouteId(route.target))} - removable={routes.length > 1 && !isLearned(route)} + removable={canRemoveRoute(routes, route)} onRemove={() => void confirmRemove(route)} /> ))} diff --git a/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx b/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx index 1e47713c6ab72..6f7d2c24174d4 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx @@ -2,7 +2,7 @@ import { RegistryProvider } from "@effect/atom-react"; import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent, type Locator } from "vite-plus/test/browser"; -import { render } from "../../../test/render"; +import { act, render } from "../../../test/render"; import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; import * as atomCommands from "../../state/use-atom-command"; @@ -169,6 +169,26 @@ it("Esc in the keybindings search clears the query without closing Settings", as ); const search = page.getByRole("searchbox", { name: "Search keybindings" }); await search.fill("sidebar"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + const keydown = new KeyboardEvent("keydown", { + ...composition, + bubbles: true, + cancelable: true, + }); + await act(() => { + // Safari ends the composition just before the Escape keydown. + if (!composition.isComposing) + search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + search.element().dispatchEvent(keydown); + }); + expect(keydown.defaultPrevented).toBe(false); + await expect.element(search).toHaveValue("sidebar"); + await expect.element(search).toHaveFocus(); + } + expect(search.element().getAttribute("type")).toBe("text"); await userEvent.keyboard("{Escape}"); diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 64984a238c251..4d940f657901d 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -2,6 +2,7 @@ import { assert, describe, expect, it } from "vite-plus/test"; import type { ResolvedKeybindingsConfig } from "@t3tools/contracts"; import { compileResolvedKeybindingsConfig, + mergeWithDefaultKeybindings, parseKeybindingShortcut, } from "@t3tools/shared/keybindings"; @@ -40,6 +41,35 @@ describe("KeybindingsSettings.logic", () => { ); }); + it("resets an edited shortcut to the built-in one its command no longer has", () => { + const rows = buildKeybindingRows( + mergeWithDefaultKeybindings( + compileResolvedKeybindingsConfig([ + { command: "chat.new", key: "mod+n", when: "!terminalFocus" }, + { command: "chat.new", key: "f8", when: "!terminalFocus" }, + ]), + ), + ); + expect( + rows + .filter((row) => row.command === "chat.new") + .map(({ key, defaultKey }) => ({ key, defaultKey })), + ).toEqual([ + { key: "f8", defaultKey: "mod+shift+o" }, + { key: "mod+n", defaultKey: "mod+n" }, + ]); + const unassigned = buildKeybindingRows( + mergeWithDefaultKeybindings( + compileResolvedKeybindingsConfig([ + { command: "chat.new", key: "mod+n", when: "!terminalFocus" }, + { command: "chat.new", key: "mod+shift+o", when: "false" }, + { command: "chat.new", key: "f8", when: "!terminalFocus" }, + ]), + ), + ); + expect(unassigned.find((row) => row.key === "f8")?.defaultKey).toBe("mod+n"); + }); + it("shares a stable editor for resolved duplicates but separates commands, shortcuts, and conditions", () => { const bindings = compileResolvedKeybindingsConfig([ { command: "terminal.toggle", key: "mod+esc", when: "terminalFocus" }, diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 4e5f68fabbb58..61af412396829 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -176,9 +176,22 @@ function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource { function defaultBindingForBinding( binding: ResolvedKeybindingRule, + keybindings: ResolvedKeybindingsConfig, ): ResolvedKeybindingRule | undefined { const bindingKey = shortcutToKeybindingInput(binding.shortcut); const bindingWhen = whenAstToExpression(binding.whenAst); + const isBound = (entry: ResolvedKeybindingRule) => + keybindings.some( + (other) => + other.command === entry.command && + shortcutToKeybindingInput(other.shortcut) === shortcutToKeybindingInput(entry.shortcut) && + [whenAstToExpression(entry.whenAst), "false"].includes(whenAstToExpression(other.whenAst)), + ); + // An edited row does not record which default it replaced; a default the command still has, + // or that is unassigned, cannot be it. + const findDefault = (matches: (entry: ResolvedKeybindingRule) => boolean) => + DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => matches(entry) && !isBound(entry)) ?? + DEFAULT_RESOLVED_KEYBINDINGS.find(matches); return ( DEFAULT_RESOLVED_KEYBINDINGS.find( @@ -194,11 +207,11 @@ function defaultBindingForBinding( shortcutToKeybindingInput(entry.shortcut) === bindingKey, ) : undefined) ?? - DEFAULT_RESOLVED_KEYBINDINGS.find( + findDefault( (entry) => entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen, ) ?? - DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command) + findDefault((entry) => entry.command === binding.command) ); } @@ -315,7 +328,7 @@ export function buildKeybindingRows( } const rowsById = new Map(); for (const [index, binding] of keybindings.entries()) { - const defaultBinding = defaultBindingForBinding(binding); + const defaultBinding = defaultBindingForBinding(binding, keybindings); const key = shortcutToKeybindingInput(binding.shortcut); const when = whenAstToExpression(binding.whenAst); const id = keybindingRowId(binding.command, key, when); @@ -564,8 +577,9 @@ function titleCaseCommandSegment(segment: string): string { function recordedLayoutShortcutKey( event: Pick, + platform: string, ): string { - const physicalKey = shortcutKeyFromEvent(event); + const physicalKey = shortcutKeyFromEvent(event, platform); const layoutKey = event.key.toLowerCase(); if (event.altKey || layoutKey.length !== 1) return physicalKey; // Normalize only US shifted glyphs at their US position. Other layouts can @@ -612,7 +626,9 @@ export function keybindingFromKeyboardEvent( }, ): string | null { const keyToken = normalizeShortcutKeyToken( - options?.layoutCharacter ? recordedLayoutShortcutKey(event) : shortcutKeyFromEvent(event), + options?.layoutCharacter + ? recordedLayoutShortcutKey(event, platform) + : shortcutKeyFromEvent(event, platform), ); if (!keyToken) return null; diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index ebf45fe0f62a4..4ccec35912731 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -150,13 +150,17 @@ function KeybindingsSearchInput({ + {/* Native search inputs clear on Escape even during IME composition. */} onChange(event.currentTarget.value)} onKeyDown={(event) => { - if (event.key !== "Escape") return; + if (event.key !== "Escape" || event.nativeEvent.isComposing || event.keyCode === 229) + return; event.preventDefault(); if (query.length > 0) { event.stopPropagation(); diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 5ab6debec7255..71afddaa33b32 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -329,8 +329,20 @@ export function LinkEnvironmentDialog({ const throughCandidate = prefilledThrough ?? (targetId === null || canMint ? null : (routes.get(targetId) ?? null)); const via = useEnvironment(throughCandidate?.viaEnvironmentId ?? null); + // The environment holding the link refuses a level this client's session there does not hold. + const mayPairThrough = useAtomValue( + peerLinkEnvironment.pairLink.permissionAtom( + throughCandidate?.viaEnvironmentId ?? null, + throughCandidate === null + ? undefined + : { environmentId: throughCandidate.environmentId, access }, + ), + ); const through = - throughCandidate !== null && via !== null && !throughFailed.has(throughCandidate.environmentId) + throughCandidate !== null && + via !== null && + mayPairThrough && + !throughFailed.has(throughCandidate.environmentId) ? throughCandidate : null; const linkBack = useLinkBackOffers(environmentId, targetId === null ? [] : [targetId], open); diff --git a/apps/web/src/components/settings/OpenSourceLicenses.browser.test.tsx b/apps/web/src/components/settings/OpenSourceLicenses.browser.test.tsx new file mode 100644 index 0000000000000..7b65c59e0c23a --- /dev/null +++ b/apps/web/src/components/settings/OpenSourceLicenses.browser.test.tsx @@ -0,0 +1,61 @@ +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { render, stubGlobal } from "../../../test/render"; +import { AppRouteModal } from "../AppRouteModal"; +import { OpenSourceLicensesPanel } from "./OpenSourceLicenses"; + +vi.mock("../chat/GlobalVoiceInputIndicator", () => ({ GlobalVoiceInputIndicator: () => null })); + +it("Esc in the license search closes it without closing Settings", async () => { + const entry = { + bundles: ["web"], + kind: "package", + license: "MIT", + name: "react", + noticeText: "MIT License", + sourceUrl: null, + version: "19.0.0", + }; + const realFetch = globalThis.fetch.bind(globalThis); + using _fetch = stubGlobal("fetch", (input: RequestInfo | URL, init?: RequestInit) => + (input instanceof Request ? input.url : String(input)).endsWith("/third-party-licenses.json") + ? Promise.resolve(Response.json({ schemaVersion: 1, entries: [entry] })) + : realFetch(input, init), + ); + await using _screen = await render( + + + , + { router: "/settings/open-source-licenses" }, + ); + const settings = page.getByRole("dialog", { name: "Settings" }); + const search = page.getByRole("searchbox", { name: "Search open-source licenses" }); + const openSearch = async () => { + const button = page.getByRole("button", { name: "Search open-source licenses" }); + await expect.element(button).toBeVisible(); + (button.element() as HTMLElement).focus(); + await userEvent.keyboard("{Enter}"); + await expect.element(search).toHaveFocus(); + }; + await openSearch(); + await search.fill("react"); + + await userEvent.keyboard("{Escape}"); + + await expect.element(settings).toHaveAttribute("data-open"); + await expect.element(search).not.toBeInTheDocument(); + await expect.element(settings).toHaveFocus(); + + await openSearch(); + await expect.element(search).toHaveValue(""); + await userEvent.keyboard("{Escape}"); + + await expect.element(settings).toHaveAttribute("data-open"); + await expect.element(search).not.toBeInTheDocument(); + await expect.element(settings).toHaveFocus(); + + await userEvent.keyboard("{Escape}"); + + await expect.element(settings).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/settings/OpenSourceLicenses.tsx b/apps/web/src/components/settings/OpenSourceLicenses.tsx index fa7b8afe816e8..43e759e083941 100644 --- a/apps/web/src/components/settings/OpenSourceLicenses.tsx +++ b/apps/web/src/components/settings/OpenSourceLicenses.tsx @@ -215,6 +215,10 @@ function LicenseHeaderAction({ onKeyDown={(event) => { if (event.key !== "Escape") return; event.preventDefault(); + event.stopPropagation(); + // Unmounting the focused input lets the dialog move focus to a control whose + // tooltip would swallow the next Esc; the surface keeps Esc closing Settings. + event.currentTarget.closest("[data-app-modal]")?.focus(); onQueryChange(""); onSearchOpenChange(false); }} diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx new file mode 100644 index 0000000000000..a45214f545ca6 --- /dev/null +++ b/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx @@ -0,0 +1,50 @@ +import { page, userEvent } from "vite-plus/test/browser"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { ProjectIconPickerDialog } from "./ProjectIconPickerDialog"; + +import "~/index.css"; + +it("Escape in the icon search clears it without closing the dialog", async () => { + const onOpenChange = vi.fn(); + await using _screen = await render( + {}} + />, + ); + const search = page.getByRole("searchbox", { name: "Search Lucide icons" }); + await expect.element(search).toHaveAttribute("type", "text"); + await userEvent.fill(search, "rocket"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + search + .element() + .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true })); + }); + await expect.element(search).toHaveValue("rocket"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + await expect.element(search).toHaveFocus(); + // Holding Escape repeats the keydown, which must not also close the dialog. + await act(() => { + search + .element() + .dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true })); + }); + expect(onOpenChange).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + expect(onOpenChange.mock.calls.map(([open]) => open)).toEqual([false]); +}); diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.tsx index 44942c2ce0c47..258f975a31905 100644 --- a/apps/web/src/components/settings/ProjectIconPickerDialog.tsx +++ b/apps/web/src/components/settings/ProjectIconPickerDialog.tsx @@ -171,12 +171,25 @@ function ProjectIconPickerBody({ {mode === "lucide" ? ( <> + {/* Native search inputs clear on Escape even during IME composition. */} setQuery(event.currentTarget.value)} + onKeyDown={(event) => { + if ( + event.key !== "Escape" || + event.nativeEvent.isComposing || + event.keyCode === 229 + ) + return; + if (!query && !event.repeat) return; + event.stopPropagation(); + setQuery(""); + }} />
diff --git a/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx b/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx index be347bef3bf5d..4c0f25762fef3 100644 --- a/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx +++ b/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx @@ -5,12 +5,15 @@ import { } from "@t3tools/contracts"; import { type ComponentProps, useState } from "react"; import { expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { act, render } from "../../../test/render"; +import { AppRouteModal } from "../AppRouteModal"; import { ProviderModelsSection } from "./ProviderModelsSection"; +vi.mock("../chat/GlobalVoiceInputIndicator", () => ({ GlobalVoiceInputIndicator: () => null })); + function section(props: Partial>) { return ( model.slug)); }); + +it("cancels adding or editing a custom model on Escape without closing Settings", async () => { + const kept = { slug: "kept-model", name: "kept-model", capabilities: null }; + await using _screen = await render( + + {section({ models: [{ ...kept, isCustom: true }], customModels: [kept] })} + , + { router: "/settings/providers" }, + ); + const settings = page.getByRole("dialog", { name: "Settings" }); + + await userEvent.click(page.getByRole("button", { name: "Add custom model" })); + const addInput = page.getByRole("textbox"); + await userEvent.type(addInput, "draft-model"); + await userEvent.keyboard("{Escape}"); + await expect.element(addInput).not.toBeInTheDocument(); + await expect.element(settings).toHaveAttribute("data-open"); + + await userEvent.click(page.getByRole("button", { name: "Edit kept-model", exact: true })); + const displayName = page.getByRole("textbox", { name: "Display name", exact: true }); + await userEvent.click(displayName); + await expect.element(displayName).toHaveFocus(); + await userEvent.keyboard("{Escape}"); + await expect.element(displayName).not.toBeInTheDocument(); + await expect.element(settings).toHaveAttribute("data-open"); + + await userEvent.keyboard("{Escape}"); + await expect.element(settings).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/settings/ProviderModelsSection.tsx b/apps/web/src/components/settings/ProviderModelsSection.tsx index 12cff57e0c2bf..921955c29dc9f 100644 --- a/apps/web/src/components/settings/ProviderModelsSection.tsx +++ b/apps/web/src/components/settings/ProviderModelsSection.tsx @@ -471,8 +471,10 @@ export function ProviderModelsSection({ if (error) setError(null); }} onKeyDown={(event) => { + if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Escape") { event.preventDefault(); + event.stopPropagation(); cancelAdd(); return; } diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx index 417868799a18d..9f774250922e9 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx @@ -6,6 +6,9 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, + ProviderDriverKind, + type ServerProvider, + type UnifiedSettings, ScheduledTaskId, ThreadId, type ScheduledTask, @@ -14,6 +17,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; +import { createModelCapabilities } from "@t3tools/shared/model"; import { act, render } from "../../../test/render"; import { ScheduledTasksSettings } from "./ScheduledTasksSettings"; import { ConfirmDialogHost } from "../ConfirmDialogHost"; @@ -58,8 +62,12 @@ const threadFamilyRead = { const state = vi.hoisted(() => ({ connected: true, tasksLoaded: true, - secondary: false, remove: vi.fn(), + tasks: [] as ScheduledTask[], + secondary: false, + providers: null as unknown as Atom.Writable>, + settings: null as unknown as UnifiedSettings, + upsert: vi.fn(), })); const secondaryId = EnvironmentId.make("secondary"); const permissions = new Map>(); @@ -68,7 +76,11 @@ function setup() { state.connected = true; state.tasksLoaded = true; state.remove.mockReset().mockReturnValue(Effect.succeed({ id: task.id })); + state.tasks = [task]; state.secondary = false; + state.providers = Atom.make>([]); + state.settings = DEFAULT_UNIFIED_SETTINGS; + state.upsert.mockReset().mockReturnValue(Effect.succeed({ id: task.id })); permissions.clear(); permissions.set(environmentId, Atom.make(true)); permissions.set(secondaryId, Atom.make(true)); @@ -127,8 +139,10 @@ vi.mock(import("../../state/server"), async (original) => { ...actual.serverEnvironment.deleteScheduledTask, run: state.remove, }, + providersValueAtom: (() => state.providers) as never, upsertScheduledTask: { ...actual.serverEnvironment.upsertScheduledTask, + run: state.upsert, permissionAtom: (id: string | null) => permissions.get(id ?? "")!, }, }, @@ -148,7 +162,7 @@ vi.mock(import("../../state/query"), async (original) => ({ data: request === null || request === threadFamilyRead ? request - : { tasks: state.tasksLoaded ? [task] : [] }, + : { tasks: state.tasksLoaded ? state.tasks : [] }, error: null, isPending: false, refresh: vi.fn(), @@ -165,9 +179,62 @@ vi.mock(import("../../state/entities"), async (original) => ({ })); vi.mock(import("../../hooks/useSettings"), async (original) => ({ ...(await original()), - useEnvironmentSettings: (() => DEFAULT_UNIFIED_SETTINGS) as never, + useEnvironmentSettings: (() => state.settings) as never, })); +function setupEffortTask() { + setup(); + const selection = { + ...task.modelSelection, + options: [{ id: "reasoningEffort", value: "high" }], + }; + state.tasks = [{ ...task, threadId: null, modelSelection: selection }]; + state.settings = { ...DEFAULT_UNIFIED_SETTINGS, defaultModelSelection: selection }; + state.providers = Atom.make>([ + { + instanceId: selection.instanceId, + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-03T00:00:00.000Z", + models: [ + { + slug: selection.model, + name: "GPT-5.4", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + { + id: "reasoningEffort", + label: "Reasoning effort", + type: "select", + options: [ + { id: "low", label: "Low", isDefault: true }, + { id: "high", label: "High" }, + ], + currentValue: "low", + }, + ], + }), + }, + { slug: "plain", name: "Plain model", isCustom: false, capabilities: null }, + { slug: "gpt-5.5", name: "Bound model", isCustom: false, capabilities: null }, + ], + skills: [], + slashCommands: [], + }, + ]); + return selection; +} + +async function fillTitleAndPrompt() { + await userEvent.fill(page.getByRole("textbox", { name: "Name" }), "Effort task"); + await userEvent.fill(page.getByRole("textbox", { name: "Prompt", exact: true }), "Review issues"); +} + describe("ScheduledTasksSettings", () => { it("only deletes a scheduled task after confirmation, including after cancelling", async () => { setup(); @@ -197,6 +264,67 @@ describe("ScheduledTasksSettings", () => { ); }); + it.each([false, true])( + "keeps model options when the same model is reselected (existing task: %s)", + async (editing) => { + const selection = setupEffortTask(); + await using screen = await render( + , + ); + if (!editing) { + await screen.getByRole("button", { name: "New task" }).click(); + await page.getByRole("combobox", { name: "Workspace" }).click(); + await page.getByRole("option", { name: "Use the project checkout" }).click(); + } + await fillTitleAndPrompt(); + await page.getByRole("button", { name: "GPT-5.4", exact: true }).click(); + await page.getByRole("option", { name: /GPT-5.4/ }).click(); + await expect.element(page.getByRole("button", { name: "High", exact: true })).toBeVisible(); + await page.getByRole("button", { name: editing ? "Save task" : "Create task" }).click(); + await vi.waitFor(() => + expect(state.upsert).toHaveBeenLastCalledWith(expect.anything(), { + environmentId, + input: expect.objectContaining({ modelSelection: selection }), + }), + ); + }, + ); + + it("saves a changed effort and drops options when switching models", async () => { + const selection = setupEffortTask(); + await using screen = await render(); + await fillTitleAndPrompt(); + await page.getByRole("button", { name: "High", exact: true }).click(); + await page.getByRole("menuitemradio", { name: /^Low/ }).click(); + await expect.element(page.getByRole("button", { name: "Low", exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Save task" }).click(); + await vi.waitFor(() => + expect(state.upsert).toHaveBeenLastCalledWith(expect.anything(), { + environmentId, + input: expect.objectContaining({ + modelSelection: { + ...selection, + options: expect.arrayContaining([{ id: "reasoningEffort", value: "low" }]), + }, + }), + }), + ); + + await screen.rerender(); + await screen.rerender(); + await page.getByRole("button", { name: "GPT-5.4", exact: true }).click(); + await page.getByRole("option", { name: /Plain model/ }).click(); + expect(page.getByRole("button", { name: "High", exact: true }).query()).toBeNull(); + await page.getByRole("button", { name: "Save task" }).click(); + await vi.waitFor(() => + expect(state.upsert).toHaveBeenLastCalledWith(expect.anything(), { + environmentId, + input: expect.objectContaining({ + modelSelection: { instanceId: selection.instanceId, model: "plain" }, + }), + }), + ); + }); it("creates on a permitted secondary and reacts to permission changes", async () => { setup(); state.secondary = true; @@ -252,15 +380,17 @@ describe("ScheduledTasksSettings", () => { }); it("offers no model choice for a task bound to a thread, whose runs use the thread's model", async () => { - setup(); + setupEffortTask(); + state.tasks = [{ ...state.tasks[0]!, threadId: task.threadId }]; await using _screen = await render(); await expect.element(page.getByRole("dialog").getByText("Fix login bug")).toBeVisible(); const enabledPicker = document.querySelector( '[role="dialog"] [data-chat-provider-model-picker]:not(:disabled)', ); expect(enabledPicker).toBeNull(); + expect(page.getByRole("button", { name: "High", exact: true }).query()).toBeNull(); await expect - .element(page.getByRole("dialog").getByRole("button", { name: "gpt-5.5", exact: true })) + .element(page.getByRole("dialog").getByRole("button", { name: "Bound model", exact: true })) .toBeDisabled(); }); diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index a2ffce32e68cd..fc7be80a59c38 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -18,7 +18,6 @@ import { import { type ReactNode, useRef, useState } from "react"; import type { EnvironmentId, - ModelSelection, OrchestrationV2ThreadLaunchWorkspaceStrategy, ProjectId, ScheduledTask, @@ -55,7 +54,7 @@ import { m, type MessageResolver } from "../../i18n/messages"; import { formatRelativeTime } from "../../timestampFormat"; import { useClientSettings, useEnvironmentSettings } from "../../hooks/useSettings"; -import { getCustomModelOptionsByInstance } from "../../modelSelection"; +import { getCustomModelOptionsByInstance, selectsPlanAgent } from "../../modelSelection"; import { providerInstanceEntriesFor } from "../../providerInstances"; import { usePrimaryCloudLinkState } from "../../cloud/cloudLinkState"; import { requestConfirmDialog } from "../../confirmDialog"; @@ -119,6 +118,8 @@ import { Menu, MenuTrigger, MenuPopup, MenuItem, MenuSeparator } from "../ui/men import { ToggleGroup, Toggle } from "../ui/toggle-group"; import { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyMedia } from "../ui/empty"; import { ProviderModelPicker } from "../chat/ProviderModelPicker"; +import { TraitsPicker } from "../chat/TraitsPicker"; +import { createModelSelection } from "@t3tools/shared/model"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { @@ -200,10 +201,9 @@ const EMPTY_DRAFT: DraftState = { baseRef: "", startFromOrigin: true, existingWorktreePath: "", - modelKey: "", + modelSelection: null, runtimeMode: "full-access", interactionMode: "default", - baseModelSelection: null, signatureEnabled: false, ...WEBHOOK_SIGNATURE_DEFAULTS, signatureSecret: "", @@ -342,15 +342,6 @@ function Field({ ); } -function splitModelKey(value: string): ModelSelection | null { - const index = value.indexOf(":"); - if (index <= 0 || index === value.length - 1) return null; - return { - instanceId: ProviderInstanceId.make(value.slice(0, index)), - model: value.slice(index + 1), - }; -} - /** formatRelativeTime handles only the past; upcoming runs need future labels. */ function relativeLabel(value: string | null, nowMs: number, resolve: MessageResolver = m): string { if (!value) return resolve(msg("Not scheduled")); @@ -1563,7 +1554,7 @@ function ScheduledTaskEditorForm({ ); const firstInstance = instanceEntries[0]; - const draftSelection = draft.modelKey ? splitModelKey(draft.modelKey) : null; + const draftSelection = draft.modelSelection; const activeSelection = draftSelection && instanceEntries.some((entry) => entry.instanceId === draftSelection.instanceId && entry.enabled) @@ -1582,6 +1573,7 @@ function ScheduledTaskEditorForm({ : { instanceId: activeInstanceId, model: activeModel }; const shownInstanceId = shownSelection?.instanceId ?? activeInstanceId; const shownModel = shownSelection?.model ?? ""; + const activeEntry = instanceEntries.find((entry) => entry.instanceId === activeInstanceId); const modelOptionsByInstance = getCustomModelOptionsByInstance( settings, providers, @@ -1667,12 +1659,6 @@ function ScheduledTaskEditorForm({ ); return; } - const modelSelection = - draft.baseModelSelection !== null && - draft.baseModelSelection.instanceId === selection.instanceId && - draft.baseModelSelection.model === selection.model - ? draft.baseModelSelection - : selection; const workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy = draft.workspaceMode === "root" ? { type: "root" } @@ -1694,7 +1680,7 @@ function ScheduledTaskEditorForm({ ...(draft.threadId === "" && draft.savedThreadId !== "" ? { unbindThread: true } : {}), ...(offersThreadModes ? { threadMode: draft.threadMode } : {}), workspaceStrategy, - modelSelection, + modelSelection: selection, // Tasks have no mode picker; a mode above the administrator's ceiling would fail every run. runtimeMode: clampManagedRuntimeMode(environment?.serverConfig?.managedPolicy, draft.runtimeMode) ?? @@ -1748,8 +1734,7 @@ function ScheduledTaskEditorForm({ setDraft((current) => ({ ...unbindDraftFromThread(current), projectId: defaultScheduledTaskProjectId(projectsOn(next.environmentId), scope), - modelKey: "", - baseModelSelection: null, + modelSelection: null, baseRef: "", startFromOrigin: true, existingWorktreePath: "", @@ -1951,7 +1936,7 @@ function ScheduledTaskEditorForm({ -
+
- setDraft((current) => ({ ...current, modelKey: `${instanceId}:${model}` })) - } + onInstanceModelChange={(instanceId, model) => { + if (instanceId === activeSelection?.instanceId && model === activeSelection.model) + return; + setDraft((current) => ({ + ...current, + modelSelection: createModelSelection(instanceId, model), + })); + }} /> + {!draft.threadId && activeSelection && activeEntry ? ( + + setDraft((current) => ({ + ...current, + modelSelection: createModelSelection(activeInstanceId, activeModel, options), + })) + } + /> + ) : null}
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index ec05bfeca77fe..d9b2456d48d90 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -43,9 +43,11 @@ import { CliCommandSettingsRow } from "./CliCommandSettingsRow"; import { MobileAppSettingsRow } from "./MobileAppSettingsRow"; import { canCheckForUpdate, + getDesktopUpdateActionError, getDesktopUpdateButtonTooltip, getDesktopUpdateDisabledReason, getDesktopUpdateInstallConfirmationMessage, + installDesktopUpdate, isDesktopUpdateButtonDisabled, resolveDesktopUpdateButtonAction, } from "../../components/desktopUpdate.logic"; @@ -263,8 +265,18 @@ function AboutVersionSection() { setIsUpdateActionPending(false); return; } - void bridge - .installUpdate() + void installDesktopUpdate(bridge) + .then((result) => { + const actionError = getDesktopUpdateActionError(result); + if (!actionError) return; + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Could not install update"), + description: actionError, + }), + ); + }) .catch((error: unknown) => { toastManager.add( stackedThreadToast({ @@ -508,6 +520,9 @@ export function useSettingsRestore(onRestored?: () => void) { ? [gt("Diff colors")] : []), ...(settings.chatWidth !== DEFAULT_UNIFIED_SETTINGS.chatWidth ? [gt("Chat width")] : []), + ...(settings.htmlPreviewWidth !== DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth + ? [gt("HTML preview width")] + : []), ...(settings.effortDisplay !== DEFAULT_UNIFIED_SETTINGS.effortDisplay ? [gt("Effort display")] : []), @@ -708,6 +723,7 @@ export function useSettingsRestore(onRestored?: () => void) { appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast, diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme, chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, + htmlPreviewWidth: DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth, effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay, mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, fileLinkPathDepth: DEFAULT_UNIFIED_SETTINGS.fileLinkPathDepth, diff --git a/apps/web/src/components/settings/ThemeCssEditor.tsx b/apps/web/src/components/settings/ThemeCssEditor.tsx index ba7349faa3ef3..314a5e26f5cba 100644 --- a/apps/web/src/components/settings/ThemeCssEditor.tsx +++ b/apps/web/src/components/settings/ThemeCssEditor.tsx @@ -32,7 +32,7 @@ export function ThemeCssEditor({ function handleKeyDown(event: KeyboardEvent) { if (event.nativeEvent.isComposing || event.ctrlKey || event.metaKey || event.altKey) return; const editor = event.currentTarget; - if (event.key === "Escape") { + if (event.key === "Escape" && (tabIndents || event.repeat)) { event.preventDefault(); event.stopPropagation(); setTabIndents(false); diff --git a/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx b/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx index 34bbceffc0a71..78a68f40936ff 100644 --- a/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx @@ -251,4 +251,36 @@ describe("ThemeEditorPanel", () => { expect(view.onEditorOpenChange).not.toHaveBeenCalled(); expect(view.onSettingsOpenChange).not.toHaveBeenCalled(); }); + + it("closes on a second Escape from the Custom CSS editor without closing Settings", async () => { + await using view = await renderBesideSettings(); + await editorElement("button[aria-expanded]"); + const cssToggle = Array.from( + document.querySelectorAll( + "[data-theme-editor-panel] button[aria-expanded]", + ), + ).find((button) => button.textContent?.includes("Custom CSS")); + expect(cssToggle).toBeDefined(); + cssToggle!.click(); + + const editor = await editorElement('textarea[aria-label="Custom CSS"]'); + editor.focus(); + await userEvent.keyboard("{Escape}"); + editor.dispatchEvent( + new KeyboardEvent("keydown", { + bubbles: true, + cancelable: true, + key: "Escape", + repeat: true, + }), + ); + + expect(view.onEditorOpenChange).not.toHaveBeenCalled(); + expect(view.onSettingsOpenChange).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + + expect(view.onEditorOpenChange).toHaveBeenCalledWith(false); + expect(view.onSettingsOpenChange).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index fd5b90f9c6c19..805899095444a 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -63,6 +63,37 @@ describe("ThemeImportDialog", () => { expect.objectContaining({ sortBy: "downloadCount" }), ); }); + + it("clears the search on Escape before closing the dialog", async () => { + searchOpenVsxThemes.mockReset(); + searchOpenVsxThemes.mockResolvedValue([]); + const onOpenChange = vi.fn(); + await using _screen = await render( + true} + onImportedMany={() => {}} + />, + ); + const search = page.getByRole("searchbox", { name: "Search Open VSX themes" }); + await expect.element(search).toHaveAttribute("type", "text"); + await userEvent.fill(search, "nord"); + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + search.element().dispatchEvent( + new KeyboardEvent("keydown", { + bubbles: true, + cancelable: true, + key: "Escape", + repeat: true, + }), + ); + expect(onOpenChange).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + expect(onOpenChange).toHaveBeenCalledWith(false); + }); }); const theme = (name: string, accent = "#3b82f6", css?: string) => ({ diff --git a/apps/web/src/components/settings/ThemeSearchSection.tsx b/apps/web/src/components/settings/ThemeSearchSection.tsx index 47e73e4939237..fa54b9a88b59d 100644 --- a/apps/web/src/components/settings/ThemeSearchSection.tsx +++ b/apps/web/src/components/settings/ThemeSearchSection.tsx @@ -321,18 +321,25 @@ export function ThemeSearchSection({ {isSearching ? : } + {/* Native search inputs clear on Escape even during IME composition. */} changeQuery(event.currentTarget.value)} onKeyDown={(event) => { if (event.nativeEvent.isComposing || event.keyCode === 229) return; + if (event.key === "Escape" && (query || event.repeat)) { + event.preventDefault(); + event.stopPropagation(); + changeQuery(""); + } if (event.key === "Enter" && !isSearching && installingId === null) themeSearch.searchNow(); }} placeholder={gt("Search themes...")} + role="searchbox" size="lg" - type="search" + type="text" value={query} /> diff --git a/apps/web/src/components/settings/TypographySettings.browser.test.tsx b/apps/web/src/components/settings/TypographySettings.browser.test.tsx index bf6f03b367062..cbc863654b557 100644 --- a/apps/web/src/components/settings/TypographySettings.browser.test.tsx +++ b/apps/web/src/components/settings/TypographySettings.browser.test.tsx @@ -1,9 +1,10 @@ import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; import * as Schema from "effect/Schema"; import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; import "~/index.css"; -import { render } from "../../../test/render"; +import { act, render } from "../../../test/render"; import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts"; import { getLocalStorageItem, removeLocalStorageItem } from "../../hooks/useLocalStorage"; import { TypographySection } from "./TypographySettings"; @@ -40,4 +41,27 @@ describe("TypographySection", () => { await expect.element(screen.getByRole("heading", { name: "Terminal font" })).toBeVisible(); expect(getLocalStorageItem(TYPOGRAPHY_ADVANCED_STORAGE_KEY, Schema.Boolean)).toBe(true); }); + + it("keeps the typed font family when an IME Escape cancels a conversion", async () => { + using _storage = setup(null); + await using screen = await render(); + const input = screen.getByRole("textbox", { name: "Interface font family" }); + await input.fill("Noto ゴシック"); + + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + const event = new KeyboardEvent("keydown", { + ...composition, + bubbles: true, + cancelable: true, + }); + await act(() => input.element().dispatchEvent(event)); + await expect.element(input).toHaveValue("Noto ゴシック"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(input).toHaveValue(DEFAULT_UNIFIED_SETTINGS.fontFamilySans); + }); }); diff --git a/apps/web/src/components/settings/TypographySettings.tsx b/apps/web/src/components/settings/TypographySettings.tsx index 5487991aea670..b9e3cfce9f2b9 100644 --- a/apps/web/src/components/settings/TypographySettings.tsx +++ b/apps/web/src/components/settings/TypographySettings.tsx @@ -517,6 +517,7 @@ function FontFamilySettingsRow({ }; }} onKeyDown={(event) => { + if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Enter") flushDraft(); if (event.key === "Escape") { // Discard uncommitted typing without closing the settings page, diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts index 6c7038f8ed191..0651d13ad7a73 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts @@ -136,11 +136,9 @@ export interface DraftState { readonly baseRef: string; readonly startFromOrigin: boolean; readonly existingWorktreePath: string; - readonly modelKey: string; + readonly modelSelection: ModelSelection | null; readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; - /** Retain the source selection's provider options when the picker leaves instanceId:model unchanged. */ - readonly baseModelSelection: ModelSelection | null; readonly signatureEnabled: boolean; readonly signatureHeader: string; readonly signatureEncoding: "hex" | "base64"; @@ -344,10 +342,9 @@ export function taskToDraft(task: ScheduledTask): DraftState { task.workspaceStrategy.type === "existing_worktree" ? task.workspaceStrategy.worktreePath : "", - modelKey: `${task.modelSelection.instanceId}:${task.modelSelection.model}`, + modelSelection: task.modelSelection, runtimeMode: task.runtimeMode, interactionMode: task.interactionMode, - baseModelSelection: task.modelSelection, ...(schedule.type === "webhook" && schedule.signature !== null ? { signatureEnabled: true, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index e06f4ee839125..522a6672a6d1a 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -407,6 +407,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/appearance", searchTerms: [msg("wide full width column layout messages composer monitor")], }, + { + id: "html-preview-width", + title: msg("HTML preview width"), + to: "/settings/appearance", + searchTerms: [msg("wide full width inline page render chart dashboard artifact centered")], + }, { id: "thread-details-items", title: msg("Thread details"), diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx index 71fce36f3ed43..156e89364670c 100644 --- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx @@ -22,6 +22,7 @@ import { getDesktopUpdateDownloadedVersion, getDesktopUpdateIdleTooltip, getDesktopUpdateInstallConfirmationMessage, + installDesktopUpdate, isDesktopUpdateButtonDisabled, resolveDesktopUpdateButtonAction, shouldShowArm64IntelBuildWarning, @@ -176,7 +177,7 @@ export async function installLocalUpdate( expectedVersion?: string, ): Promise { try { - const result = await bridge.installUpdate(expectedVersion); + const result = await installDesktopUpdate(bridge, expectedVersion); if (!result.accepted) { showDesktopUpdateDownloadedToast(bridge, result.state); return false; diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts index f4b1d0053b22b..ea44f1592a956 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts @@ -45,6 +45,20 @@ function machine( }; } +// A desktop-mode server the desktop app cannot control, such as a WSL backend or an older app. +function withoutDesktopControl(base: UpdateEverythingMachine): UpdateEverythingMachine { + return { + ...base, + serverConfig: { + ...base.serverConfig!, + environment: { + ...base.serverConfig!.environment, + capabilities: { repositoryIdentity: true, serverSelfUpdate: "desktop-managed" }, + }, + }, + }; +} + describe("collectServerUpdateTargets", () => { it("updates remote servers that can move to the target and names every skipped one", () => { const { targets, skipped } = collectServerUpdateTargets( @@ -67,6 +81,7 @@ describe("collectServerUpdateTargets", () => { machine("current", "0.0.50", "boot-service"), machine("current-offline", "0.0.50", "boot-service", { connected: false }), machine("manual", "0.0.40", undefined), + withoutDesktopControl(machine("wsl-backend", "0.0.40", "desktop-managed")), ], "0.0.50", ); @@ -82,6 +97,7 @@ describe("collectServerUpdateTargets", () => { ["no-scope", "no permission"], ["busy", "already updating"], ["manual", "needs a manual update"], + ["wsl-backend", "update T3 Code on that machine"], ]); }); @@ -230,15 +246,9 @@ describe("collectChannelSwitchTargets", () => { host(machine("service", "0.1.2", "boot-service"), 70), // A Stable tag built a migration the latest Nightly does not have yet. host(machine("ahead", "0.1.3", "boot-service"), 73), - machine("old-desktop", "0.1.2", "desktop-managed", { - serverConfig: { - ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!, - environment: { - ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!.environment, - capabilities: { repositoryIdentity: true, serverSelfUpdate: "desktop-managed" }, - }, - }, - }), + withoutDesktopControl(machine("old-desktop", "0.1.2", "desktop-managed")), + // Already on Nightly, so it needs an update rather than a channel switch. + withoutDesktopControl(machine("behind-desktop", OLD_NIGHTLY, "desktop-managed")), machine("current", NIGHTLY, "boot-service"), // The server refuses a track its policy rules out, so the dialog skips it up front. managedHost(host(machine("no-nightly", "0.1.2", "boot-service"), 70)), @@ -254,7 +264,8 @@ describe("collectChannelSwitchTargets", () => { "ahead", `its database has changes ${NIGHTLY} does not support yet; stay on Stable until Nightly has them`, ], - ["old-desktop", "needs a newer desktop app"], + ["old-desktop", "change the update track on that machine"], + ["behind-desktop", "update T3 Code on that machine"], [ "no-nightly", "Example Corp manages T3 Code updates. Only stable releases can be installed.", diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts index 6930549adf19b..f9bf0976a22e4 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.ts @@ -70,6 +70,10 @@ export interface SkippedMachine { readonly reason: string; } +// Desktop servers without the desktop control fd (older apps, WSL backends: wsl.exe cannot pass +// fds) cannot be updated from here, and their desktop app is not necessarily the stale part. +const UPDATE_ON_THAT_MACHINE = msg("update T3 Code on that machine"); + /** Skip current and app-hosted servers; the latter update with the app and would relaunch mid-run. * Desktop-managed servers use their own feed. Each server's updater checks that it can install the * release before it restarts, so no registry precheck runs here. */ @@ -115,7 +119,7 @@ export function collectServerUpdateTargets( continue; } if (selfUpdate === "desktop-managed" && !desktopAppUpdate) { - skip(resolve(msg("needs a newer desktop app"))); + skip(resolve(UPDATE_ON_THAT_MACHINE)); continue; } const serverChannel = cliReleaseChannelOf(config.environment.serverVersion); @@ -425,7 +429,11 @@ function trackSwitchMove( if (selfUpdate === null) return { skip: resolve(msg("needs a manual update")) }; if (selfUpdate !== "desktop-managed") return { selfUpdate }; if (config.environment.capabilities.desktopAppChannelSwitch !== true) { - return { skip: resolve(msg("needs a newer desktop app")) }; + return { + skip: resolve( + sameTrack ? UPDATE_ON_THAT_MACHINE : msg("change the update track on that machine"), + ), + }; } // Squirrel.Mac renames the bundle for the new track and then cannot relaunch it. if (!sameTrack && config.environment.platform.os === "darwin") { diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index 0c13e765131cc..d73a50f7a1b34 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -13,6 +13,7 @@ const baseState: ThreadActionMenuState = { canSnoozeNow: true, isRegeneratingTitle: false, isRunning: false, + hasCompletedRun: true, supports: { settlement: true, autoSettleOptOut: true, @@ -75,6 +76,14 @@ describe("buildThreadActionMenuItems", () => { expect(items.find((item) => item.id === "turn-into-project")?.disabled).toBe(true); }); + it.each([ + ["while the thread is running", { isRunning: true }], + ["before any run has completed", { hasCompletedRun: false }], + ])("omits mark unread %s", (_, overrides) => { + const items = buildThreadActionMenuItems({ ...baseState, ...overrides }); + expect(items.map((item) => item.id)).not.toContain("mark-unread"); + }); + it("disables only rename where no inline title editor exists", () => { const items = buildThreadActionMenuItems({ ...baseState, canRename: false }); expect(items.filter((item) => item.disabled).map((item) => item.id)).toEqual(["rename"]); diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 2b15dafb3eb1c..e3512151513ea 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -113,6 +113,8 @@ export interface ThreadActionMenuState { readonly isRegeneratingTitle: boolean; /** Archive rejects attached providers, so disable it while running. */ readonly isRunning: boolean; + /** The server marks unread against the latest run's completion, so in-flight runs cannot be. */ + readonly hasCompletedRun: boolean; readonly supports: { readonly settlement: boolean; readonly autoSettleOptOut: boolean; @@ -222,7 +224,9 @@ export function buildThreadActionMenuItems( }, ] : []), - { id: "mark-unread", label: resolve(msg("Mark unread")), icon: "mail-open" }, + ...(state.hasCompletedRun && !state.isRunning + ? [{ id: "mark-unread" as const, label: resolve(msg("Mark unread")), icon: "mail-open" }] + : []), ...(state.canShareWithGuest ? [{ id: "share-guest" as const, label: resolve(msg("Share with guest")), icon: "user-plus" }] : []), diff --git a/apps/web/src/components/usage/UsagePriceOverrides.browser.test.tsx b/apps/web/src/components/usage/UsagePriceOverrides.browser.test.tsx index 7418b5207b1fe..34fde5fc9980d 100644 --- a/apps/web/src/components/usage/UsagePriceOverrides.browser.test.tsx +++ b/apps/web/src/components/usage/UsagePriceOverrides.browser.test.tsx @@ -26,7 +26,12 @@ vi.mock(import("~/state/presentation"), async (original) => { vi.mock(import("~/state/server"), async (original) => { const { Atom } = await import("effect/reactivity"); const actual = await original(); - const settings = Atom.make({ usagePriceOverrides: {}, usageModelAliases: {} }); + const settings = Atom.make({ + usagePriceOverrides: { + "priced-model": { inputCostPerMillionTokens: 1, outputCostPerMillionTokens: 4 }, + }, + usageModelAliases: { "my-preview": "gpt-4o" }, + }); return { ...actual, serverEnvironment: { @@ -82,4 +87,48 @@ describe("UsagePriceOverrides", () => { .toHaveTextContent("Output is required on workstation."); await expect.element(page.getByRole("button", { name: "Save changes" })).toBeDisabled(); }); + + it("asks for a model ID once a new row maps to a model", async () => { + await using _screen = await renderPrices(); + await page.getByRole("button", { name: "Add model price" }).click(); + const modelId = page.getByLabelText("New model ID"); + await expect.element(modelId).toHaveValue(""); + + expect(page.getByRole("alert").elements()).toEqual([]); + await expect.element(modelId).not.toHaveAttribute("aria-invalid"); + + await userEvent.type(page.getByLabelText("Map new model to model"), "gpt-4o"); + await expect.element(page.getByRole("alert")).toHaveTextContent("Enter a model ID."); + await expect.element(modelId).toHaveAttribute("aria-invalid", "true"); + await expect.element(page.getByRole("button", { name: "Save changes" })).toBeDisabled(); + }); + + it("leaves no pending change when a mapping goes back to its saved model", async () => { + await using _screen = await renderPrices(); + const mapTo = page.getByLabelText("Map my-preview to model"); + await userEvent.clear(mapTo); + await userEvent.type(page.getByLabelText("Input price for my-preview"), "2"); + await userEvent.type(mapTo, "gpt-4o"); + + await expect + .element(page.getByRole("button", { name: "Discard changes" })) + .not.toBeInTheDocument(); + expect(page.getByRole("alert").elements()).toEqual([]); + await expect + .element(page.getByRole("button", { name: "Apply to All environments" })) + .toBeEnabled(); + }); + + it("keeps typed prices when a priced model's new mapping is cleared", async () => { + await using _screen = await renderPrices(); + const input = page.getByLabelText("Input price for priced-model"); + await userEvent.clear(input); + await userEvent.type(input, "2"); + const mapTo = page.getByLabelText("Map priced-model to model"); + await userEvent.type(mapTo, "gpt-4o"); + await userEvent.clear(mapTo); + + await expect.element(input).toHaveValue("2"); + await expect.element(page.getByRole("button", { name: "Save changes" })).toBeEnabled(); + }); }); diff --git a/apps/web/src/components/usage/UsagePriceOverrides.tsx b/apps/web/src/components/usage/UsagePriceOverrides.tsx index d7557288ac589..c964460862e49 100644 --- a/apps/web/src/components/usage/UsagePriceOverrides.tsx +++ b/apps/web/src/components/usage/UsagePriceOverrides.tsx @@ -232,7 +232,12 @@ export function UsagePriceOverrides({ const editAlias = (row: UsagePriceDraft, value: string) => { const { alias: _alias, ...rest } = row; const original = usageAliasCell(selected, row.model, messages); - updateOrDropDraft(matchesSaved(row, original, value) ? rest : { ...rest, alias: value }); + updateOrDropDraft( + matchesSaved(row, original, value) + ? // A restored mapping hides the price inputs, so their typed values go too. + { ...rest, values: value === "" ? rest.values : {} } + : { ...rest, alias: value }, + ); }; const save = async (retry = false) => { if (pending) return; @@ -439,9 +444,7 @@ export function UsagePriceOverrides({ } }} aria-label={gt("New model ID")} - aria-invalid={ - (row.model.trim() !== "" && error !== undefined) || undefined - } + aria-invalid={error !== undefined || undefined} list="usage-price-models" placeholder={gt("Model ID")} autoComplete="off" @@ -461,9 +464,7 @@ export function UsagePriceOverrides({ {row.model} )} - {error !== undefined && - (row.model.trim() !== "" || - Object.values(row.values).some((value) => value !== "")) ? ( + {error !== undefined ? (

{error}

diff --git a/apps/web/src/composer-markdown-source.ts b/apps/web/src/composer-markdown-source.ts index c57985f12e345..542bc4be7fc23 100644 --- a/apps/web/src/composer-markdown-source.ts +++ b/apps/web/src/composer-markdown-source.ts @@ -27,6 +27,7 @@ import { type RichTextMark, } from "~/composer-rich-text"; import { caretTakesMarksBefore, serializeEditorDoc } from "~/composer-rich-text-doc"; +import { isPasteTransaction } from "~/composer-undo-grouping"; // Styled text the selection touches becomes source text with the source mark, // parsed back once the selection leaves. History steps only replay on the shape @@ -496,9 +497,10 @@ function markdownSourcePlugin(type: MarkType): Plugin { if (!transactions.some((tr) => tr.docChanged || tr.selectionSet)) return null; const source = markdownSourceKey.getState(state); if (source?.detached) return normalizeDetached(state, source.revealed); + // A paste is not typing: the caret ends past the pasted text's closing markers. const tr = normalizeMarkdownSource( state, - transactions.some((item) => item.docChanged), + transactions.some((item) => item.docChanged && !isPasteTransaction(item)), ); // With nothing to undo, a recorded rewrite would only add a no-op undo. if (tr && undoDepth(state) === 0) tr.setMeta("addToHistory", false); diff --git a/apps/web/src/composer-rich-text-doc.ts b/apps/web/src/composer-rich-text-doc.ts index f99337382f0b1..428b6185336d7 100644 --- a/apps/web/src/composer-rich-text-doc.ts +++ b/apps/web/src/composer-rich-text-doc.ts @@ -16,7 +16,7 @@ import { Blockquote } from "@tiptap/extension-blockquote"; import { CodeBlock } from "@tiptap/extension-code-block"; import { Heading } from "@tiptap/extension-heading"; import { HorizontalRule } from "@tiptap/extension-horizontal-rule"; -import { Italic, starInputRegex, starPasteRegex } from "@tiptap/extension-italic"; +import { Italic, starInputRegex } from "@tiptap/extension-italic"; import { combineTransactionSteps, getChangedRanges, @@ -24,7 +24,6 @@ import { type Editor, InputRule, markInputRule, - markPasteRule, mergeAttributes, } from "@tiptap/core"; import { isHistoryTransaction } from "@tiptap/pm/history"; @@ -352,9 +351,6 @@ export const ComposerItalicExtension = Italic.extend({ addInputRules() { return [markInputRuleOutsideCode(starInputRegex, this.type)]; }, - addPasteRules() { - return [markPasteRule({ find: starPasteRegex, type: this.type })]; - }, }); export const ComposerBoldExtension = Bold.extend({ diff --git a/apps/web/src/composer-undo-grouping.ts b/apps/web/src/composer-undo-grouping.ts index 708b4f41fe52a..5d33ee4c62762 100644 --- a/apps/web/src/composer-undo-grouping.ts +++ b/apps/web/src/composer-undo-grouping.ts @@ -10,14 +10,15 @@ export type ComposerChangeKind = "insert" | "delete" | "other"; const CLIPBOARD_EDIT_META = "composerClipboardEdit"; const COMPOSITION_REPLACE_META = "composerCompositionReplace"; -/** - * Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths. - * Not `uiEvent`: Tiptap's paste rules would style the already parsed paste a second time. - */ +/** Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths. */ export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Transaction { return tr.setMeta(CLIPBOARD_EDIT_META, event); } +export function isPasteTransaction(tr: Transaction): boolean { + return tr.getMeta("uiEvent") === "paste" || tr.getMeta(CLIPBOARD_EDIT_META) === "paste"; +} + /** Start a replacement undo group, keeping the IME edits together and prior typing separate. */ export function markAsCompositionReplace(tr: Transaction): Transaction { return closeHistory(tr).setMeta(COMPOSITION_REPLACE_META, true); diff --git a/apps/web/src/contextMenuFallback.keyboard.browser.test.ts b/apps/web/src/contextMenuFallback.keyboard.browser.test.ts index 078d9f2539e4b..6c553ad17c547 100644 --- a/apps/web/src/contextMenuFallback.keyboard.browser.test.ts +++ b/apps/web/src/contextMenuFallback.keyboard.browser.test.ts @@ -1,9 +1,11 @@ import { expect, it } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; import { dismissContextMenu, isContextMenuOpen, showContextMenuFallback, } from "./contextMenuFallback"; +import { createLocalApi } from "./localApi"; const items = [ { id: "heading", label: "Thread actions", header: true }, @@ -116,3 +118,14 @@ it("takes thumb Back and Forward presses so the app router stays put", () => { } expect(isContextMenuOpen()).toBe(true); }); + +// NVDA browse mode sends Shift+F10 without keyboard focus on the opener, so the opener does +// not match :focus-visible; the caller's keyboard source must still start on the first action. +it("starts a keyboard-sourced menu on its first action when the opener was focused by pointer", async () => { + using fixture = setup(); + fixture.origin.blur(); + await userEvent.click(fixture.origin); + expect(fixture.origin.matches(":focus-visible")).toBe(false); + void createLocalApi().contextMenu.show(items, { x: 0, y: 0 }, "keyboard"); + expect(label()).toBe("Rename"); +}); diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index aa70065eb62f3..e7e846975cb0c 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -1,4 +1,4 @@ -import type { ContextMenuItem } from "@t3tools/contracts"; +import type { ContextMenuItem, ContextMenuSource } from "@t3tools/contracts"; import { msg } from "gt-react"; import { m } from "./i18n/messages"; @@ -247,6 +247,7 @@ export function dismissContextMenu(restoreFocus = true): void { export function showContextMenuFallback( items: readonly ContextMenuItem[], position?: { x: number; y: number }, + source?: ContextMenuSource, ): Promise { dismissContextMenu(); return new Promise((resolve) => { @@ -471,6 +472,12 @@ export function showContextMenuFallback( spacer.setAttribute("aria-hidden", "true"); button.appendChild(spacer); } + } else if (typeof item.iconImage === "string") { + const image = document.createElement("img"); + image.src = item.iconImage; + image.alt = ""; + image.className = "size-4.5 shrink-0 sm:size-4"; + button.appendChild(image); } else if (typeof item.icon === "string") { const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral"); if (icon) { @@ -622,12 +629,15 @@ export function showContextMenuFallback( openMenu(items, position?.x ?? 0, position?.y ?? 0, 0); activeContextMenuDismiss = dismiss; // A keyboard-opened menu starts on its first action, a pointer-opened one on the menu itself. + // Without a source, guess from :focus-visible, which screen reader browse mode does not set. // Text fields always match :focus-visible, so they say nothing about how the menu opened. - const firstAction = - previouslyFocusedElement?.matches(":focus-visible") && - !previouslyFocusedElement.matches('input, textarea, select, [contenteditable="true"]') - ? menuStack[0]?.querySelector("button:not(:disabled)") - : null; + const openedFromKeyboard = + source === "keyboard" || + (previouslyFocusedElement?.matches(":focus-visible") && + !previouslyFocusedElement.matches('input, textarea, select, [contenteditable="true"]')); + const firstAction = openedFromKeyboard + ? menuStack[0]?.querySelector("button:not(:disabled)") + : null; (firstAction ?? menuStack[0])?.focus({ preventScroll: true }); document.addEventListener("focusin", onFocusIn); window.addEventListener("blur", onWindowBlur); diff --git a/apps/web/src/contextMenuSource.ts b/apps/web/src/contextMenuSource.ts index 11ecfbdf336f8..8e959003d1418 100644 --- a/apps/web/src/contextMenuSource.ts +++ b/apps/web/src/contextMenuSource.ts @@ -1,8 +1,38 @@ import type { ContextMenuSource } from "@t3tools/contracts"; +// Menus opened by openContextMenuFromKeyboard; a script-made event cannot keep button -1. +const keyboardContextMenus = new WeakSet(); + // Chromium uses no button for keyboard context menus and zero clicks for keyboard activation. export function contextMenuSourceOf( - event: Pick, + event: Pick & { readonly nativeEvent?: Event }, ): ContextMenuSource { + if (event.nativeEvent !== undefined && keyboardContextMenus.has(event.nativeEvent)) { + return "keyboard"; + } return (event.type === "click" ? event.detail === 0 : event.button === -1) ? "keyboard" : "mouse"; } + +/** + * Opens an element's context menu from the keyboard. Chromium on macOS turns neither + * Shift+F10 nor the ContextMenu key into a `contextmenu` event, so the key is handled + * here and the element's own handler receives a menu event that reads as keyboard-opened. + * Preventing the key keeps other platforms from opening the menu a second time. + */ +export function openContextMenuFromKeyboard( + event: Pick & { + readonly currentTarget: Element; + }, +): void { + if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return; + event.preventDefault(); + const bounds = event.currentTarget.getBoundingClientRect(); + const menu = new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: bounds.left, + clientY: bounds.bottom, + }); + keyboardContextMenus.add(menu); + event.currentTarget.dispatchEvent(menu); +} diff --git a/apps/web/src/editorMenuIcons.tsx b/apps/web/src/editorMenuIcons.tsx new file mode 100644 index 0000000000000..adbabbcabecb6 --- /dev/null +++ b/apps/web/src/editorMenuIcons.tsx @@ -0,0 +1,95 @@ +import type { EditorId } from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { Atom } from "effect/reactivity"; +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; + +import { editorIconOptions } from "./components/editorIcons"; +import { useTheme } from "./hooks/useTheme"; + +const ICON_PIXELS = 32; +const SVG_NS = "http://www.w3.org/2000/svg"; +const NO_ICONS: ReadonlyMap = new Map(); + +// Logos are styled by Tailwind and the theme, so render them in the document and inline the +// computed paint before rasterizing; native menus only accept bitmaps. +async function rasterizeEditorIcon(editor: EditorId): Promise { + const option = editorIconOptions(navigator.platform).find(({ value }) => value === editor); + if (option === undefined) return null; + const host = document.createElement("div"); + host.setAttribute("aria-hidden", "true"); + host.style.cssText = "position:fixed;left:-10000px;top:0;width:16px;height:16px;"; + document.body.append(host); + const root = createRoot(host); + try { + flushSync(() => + root.render( + , + ), + ); + const svg = host.querySelector("svg"); + if (svg === null) return null; + const clone = svg.cloneNode(true) as SVGSVGElement; + const sources = [svg, ...svg.querySelectorAll("*")]; + const targets = [clone, ...clone.querySelectorAll("*")]; + sources.forEach((source, index) => { + const computed = getComputedStyle(source); + const target = targets[index]; + target?.setAttribute( + "style", + `${target.getAttribute("style") ?? ""};fill:${computed.fill};stroke:${computed.stroke}`, + ); + }); + clone.removeAttribute("class"); + clone.setAttribute("xmlns", SVG_NS); + clone.setAttribute("width", String(ICON_PIXELS)); + clone.setAttribute("height", String(ICON_PIXELS)); + const image = new Image(); + image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(clone))}`; + await image.decode(); + const canvas = document.createElement("canvas"); + canvas.width = ICON_PIXELS; + canvas.height = ICON_PIXELS; + const context = canvas.getContext("2d"); + if (context === null) return null; + context.drawImage(image, 0, 0, ICON_PIXELS, ICON_PIXELS); + return canvas.toDataURL("image/png"); + } catch { + return null; + } finally { + root.unmount(); + host.remove(); + } +} + +// Keyed by theme and editor list; both change rarely, and each key rasterizes once. +const editorMenuIconsAtom = Atom.family((key: string) => + Atom.make((get): ReadonlyMap => { + const editors = key + .slice(key.indexOf("|") + 1) + .split(",") + .filter(Boolean) as EditorId[]; + // Render outside the reading component's render pass. + void Promise.resolve().then(async () => { + const icons = new Map(); + for (const editor of editors) { + const icon = await rasterizeEditorIcon(editor); + if (icon !== null) icons.set(editor, icon); + } + if (icons.size > 0) get.setSelf(icons); + }); + return NO_ICONS; + }).pipe(Atom.keepAlive, Atom.withLabel(`editor-menu-icons:${key}`)), +); + +/** PNG data URLs of editor logos for context menus; empty until rendered. */ +export function useEditorMenuIcons( + editors: ReadonlyArray, +): ReadonlyMap { + const { resolvedTheme } = useTheme(); + return useAtomValue(editorMenuIconsAtom(`${resolvedTheme}|${editors.join(",")}`)); +} diff --git a/apps/web/src/fileContextMenu.test.ts b/apps/web/src/fileContextMenu.test.ts index a5c74929d48ad..903c8c7bff7a4 100644 --- a/apps/web/src/fileContextMenu.test.ts +++ b/apps/web/src/fileContextMenu.test.ts @@ -1,7 +1,39 @@ import { EnvironmentId } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; -import { resolveFileContextMenuAbsolutePath } from "./fileContextMenu"; +import { resolveFileContextMenuAbsolutePath, useFileContextMenu } from "./fileContextMenu"; +import type { RemoteOpenResolution } from "./remoteOpen"; + +const state = vi.hoisted(() => ({ + remoteOpen: { state: { mode: "local-exec" }, isResolved: true } as RemoteOpenResolution, + openInEditor: vi.fn(async () => ({ _tag: "Success" })), + openRemoteEditorUrl: vi.fn(async (_url: string) => true), +})); + +vi.mock("@effect/atom-react", () => ({ + useAtomValue: () => ({ + availableEditors: ["cursor", "file-manager"], + shellRevealInFileManager: true, + shellRevealInFileManagerKind: "xdg-open", + environment: { platform: { os: "linux" } }, + }), +})); +vi.mock("gt-react", async (importOriginal) => ({ + ...(await importOriginal()), + useMessages: () => (text: string) => text, +})); +vi.mock(import("./state/session"), async (original) => ({ + ...(await original()), + useEnvironmentScope: () => true, +})); +vi.mock("./editorMenuIcons", () => ({ useEditorMenuIcons: () => new Map() })); +vi.mock("./state/use-atom-command", () => ({ useAtomCommand: () => state.openInEditor })); +vi.mock(import("./remoteOpen"), async (original) => ({ + ...(await original()), + useRemoteOpenResolution: () => state.remoteOpen, + useRemoteCapableEditors: () => ["vscode"], + openRemoteEditorUrl: state.openRemoteEditorUrl, +})); const BASE_TARGET = { environmentId: EnvironmentId.make("environment-local"), @@ -42,3 +74,62 @@ describe("resolveFileContextMenuAbsolutePath", () => { ).toBeNull(); }); }); + +describe("useFileContextMenu", () => { + it.each<[string, RemoteOpenResolution]>([ + ["remote-unavailable", { state: { mode: "remote-unavailable" }, isResolved: true }], + ["unresolved", { state: { mode: "local-exec" }, isResolved: false }], + ])("offers no open actions when remote open is %s", async (_mode, resolution) => { + state.remoteOpen = resolution; + state.openInEditor.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET)).toEqual([]); + await menu.activate("open", BASE_TARGET); + await menu.activate("editor:vscode", BASE_TARGET); + expect(state.openInEditor).not.toHaveBeenCalled(); + }); + + it("opens files over SSH remote links instead of on the server host", async () => { + state.remoteOpen = { + state: { mode: "remote-links", host: { kind: "ssh-alias", host: "box", username: "me" } }, + isResolved: true, + }; + state.openInEditor.mockClear(); + state.openRemoteEditorUrl.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET)).toEqual([ + { + id: "open-with", + label: "Open with", + children: [{ id: "editor:vscode", label: "VS Code" }], + }, + ]); + await menu.activate("open", BASE_TARGET); + await menu.activate("editor:vscode", BASE_TARGET); + await menu.activate("editor:vscode", { ...BASE_TARGET, filePath: "src", isDirectory: true }); + expect(state.openInEditor).not.toHaveBeenCalled(); + expect(state.openRemoteEditorUrl.mock.calls).toEqual([ + ["vscode://vscode-remote/ssh-remote+me%40box/workspace/project/src/index.ts:1:1"], + ["vscode://vscode-remote/ssh-remote+me%40box/workspace/project/src?windowId=_blank"], + ]); + }); + + it("opens files on the server host when remote open is local-exec", async () => { + state.remoteOpen = { state: { mode: "local-exec" }, isResolved: true }; + state.openInEditor.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET).map((item) => item.id)).toEqual([ + "open", + "reveal-in-folder", + "open-with", + ]); + await menu.activate("open", BASE_TARGET); + expect(state.openInEditor).toHaveBeenCalledWith({ + environmentId: BASE_TARGET.environmentId, + input: { cwd: "/workspace/project/src/index.ts", editor: "file-manager" }, + }); + }); +}); diff --git a/apps/web/src/fileContextMenu.ts b/apps/web/src/fileContextMenu.ts index 452a6bbd516f6..28b1b4d2c950b 100644 --- a/apps/web/src/fileContextMenu.ts +++ b/apps/web/src/fileContextMenu.ts @@ -1,17 +1,28 @@ import { + AuthOrchestrationOperateScope, + buildRemoteOpenUrl, EDITORS, type ContextMenuItem, type EditorId, type EnvironmentId, + type ContextMenuSource, } from "@t3tools/contracts"; +import { contextMenuSourceOf } from "./contextMenuSource"; import { resolveDiffPathForWorkspace } from "./diffFileActions"; import { revealInFileExplorerLabelForKind, revealInFileExplorerLabelForOs, } from "~/components/preview/fileExplorerLabel"; +import { useEditorMenuIcons } from "./editorMenuIcons"; import { readLocalApi } from "./localApi"; +import { + openRemoteEditorUrl, + useRemoteCapableEditors, + useRemoteOpenResolution, +} from "./remoteOpen"; import { serverEnvironment } from "./state/server"; +import { useEnvironmentScope } from "./state/session"; import { shellEnvironment } from "./state/shell"; import { useAtomCommand } from "./state/use-atom-command"; import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; @@ -34,6 +45,7 @@ export interface FileContextMenuTarget { readonly filePath: string; readonly workspaceRoot: string | undefined; readonly repositoryRoot?: string | undefined; + readonly isDirectory?: boolean; } export function resolveFileContextMenuAbsolutePath(target: FileContextMenuTarget): string | null { @@ -62,6 +74,7 @@ export interface FileContextMenuCapabilities { function buildFileContextMenuItems(input: { readonly hasAbsolutePath: boolean; readonly capabilities: FileContextMenuCapabilities; + readonly editorIcons: ReadonlyMap; readonly resolve: MessageResolver; }): readonly ContextMenuItem[] { if (!input.hasAbsolutePath) return []; @@ -85,10 +98,14 @@ function buildFileContextMenuItems(input: { items.push({ id: "open-with", label: input.resolve(msg("Open with")), - children: editorIds.map((editorId) => ({ - id: `editor:${editorId}` as FileContextMenuAction, - label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId, - })), + children: editorIds.map((editorId) => { + const iconImage = input.editorIcons.get(editorId); + return { + id: `editor:${editorId}` as FileContextMenuAction, + label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId, + ...(iconImage === undefined ? {} : { iconImage }), + }; + }), }); } return items; @@ -99,20 +116,40 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const resolve = useMessages(); - const availableEditors = serverConfig?.availableEditors ?? []; + const remoteOpen = useRemoteOpenResolution(environmentId); + const remoteCapableEditors = useRemoteCapableEditors(); + const mode = environmentId !== null && remoteOpen.isResolved ? remoteOpen.state.mode : null; + // Shell actions run on the server host, which is the viewer's machine only in local-exec. + const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const isLocalExec = mode === "local-exec" && canOperateHost; + const remoteHost = remoteOpen.state.mode === "remote-links" ? remoteOpen.state.host : null; + + const availableEditors = isLocalExec + ? (serverConfig?.availableEditors ?? []) + : mode === "remote-links" + ? remoteCapableEditors + : []; const capabilities: FileContextMenuCapabilities = { // WSL can reveal in Windows Explorer despite reporting Linux; use server wording. revealLabel: - environmentId !== null && + isLocalExec && serverConfig?.shellRevealInFileManager === true && serverConfig.availableEditors.includes("file-manager") ? serverConfig.shellRevealInFileManagerKind === undefined ? revealInFileExplorerLabelForOs(serverConfig.environment.platform.os, resolve) : revealInFileExplorerLabelForKind(serverConfig.shellRevealInFileManagerKind, resolve) : undefined, - canOpenDefault: availableEditors.includes("file-manager"), + canOpenDefault: isLocalExec && availableEditors.includes("file-manager"), editorIds: availableEditors, }; + const editorIcons = useEditorMenuIcons(availableEditors); + + const editorFailureTitle = (editor: EditorId) => + resolve( + msg("Could not open in {editor}", { + editor: EDITOR_LABEL_BY_ID.get(editor) ?? editor, + }), + ); const activate = async ( action: FileContextMenuAction, @@ -126,8 +163,26 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { action === "open" || reveal ? ("file-manager" as const) : (action.slice("editor:".length) as EditorId); + if (action === "open" && !capabilities.canOpenDefault) return; + if (reveal && capabilities.revealLabel === undefined) return; if (action !== "open" && !reveal && !capabilities.editorIds.includes(editor)) return; + if (remoteHost !== null) { + const url = buildRemoteOpenUrl({ + editor, + ...remoteHost, + absolutePath, + isFile: target.isDirectory !== true, + }); + if (url !== undefined && (await openRemoteEditorUrl(url))) return; + toastManager.add({ + type: "error", + title: editorFailureTitle(editor), + description: absolutePath, + }); + return; + } + const result = await openInEditor({ environmentId, input: { cwd: absolutePath, editor, ...(reveal ? { reveal: true } : {}) }, @@ -140,11 +195,7 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { ? resolve(msg("Could not open file")) : reveal ? resolve(msg("Unable to reveal file")) - : resolve( - msg("Could not open in {editor}", { - editor: EDITOR_LABEL_BY_ID.get(editor) ?? editor, - }), - ), + : editorFailureTitle(editor), description: absolutePath, }); }; @@ -152,15 +203,17 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { const show = async ( target: FileContextMenuTarget, position?: { x: number; y: number }, + source?: ContextMenuSource, ): Promise => { const api = readLocalApi(); const items = buildFileContextMenuItems({ hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null, capabilities, + editorIcons, resolve, }); if (items.length === 0 || api === undefined) return; - const clicked = await api.contextMenu.show(items, position); + const clicked = await api.contextMenu.show(items, position, source); if (clicked === null) return; await activate(clicked as FileContextMenuAction, target); }; @@ -170,6 +223,7 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { buildFileContextMenuItems({ hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null, capabilities, + editorIcons, resolve, }), capabilities, @@ -180,7 +234,14 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { export function useFileContextMenuHandler(environmentId: EnvironmentId | null) { const contextMenu = useFileContextMenu(environmentId); - return (target: FileContextMenuTarget, event?: { clientX: number; clientY: number }) => { - void contextMenu.show(target, event ? { x: event.clientX, y: event.clientY } : undefined); + return ( + target: FileContextMenuTarget, + event?: Pick, + ) => { + void contextMenu.show( + target, + event ? { x: event.clientX, y: event.clientY } : undefined, + event ? contextMenuSourceOf(event) : undefined, + ); }; } diff --git a/apps/web/src/fork/FileLinkPathPrefix.tsx b/apps/web/src/fork/FileLinkPathPrefix.tsx index 2604a8f409de4..99537e8f53ec2 100644 --- a/apps/web/src/fork/FileLinkPathPrefix.tsx +++ b/apps/web/src/fork/FileLinkPathPrefix.tsx @@ -1,9 +1,33 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + import { useClientSettings } from "../hooks/useSettings"; -import { type FileLinkPathMeta, fileLinkPathPrefix } from "./fileLinkPathDepth"; +import { serverEnvironment } from "../state/server"; +import { type FileLinkPathMeta, fileLinkPathPrefix, repeatedFileNames } from "./fileLinkPathDepth"; + +// Only the home string and the OS flag, so other config updates do not re-render every message. +const serverHomeAtom = Atom.family((environmentId: EnvironmentId | null) => + Atom.make( + (get) => get(serverEnvironment.configValueAtom(environmentId))?.homeDirectory || null, + ).pipe(Atom.withLabel(`file-link-server-home:${environmentId}`)), +); +const serverWindowsAtom = Atom.family((environmentId: EnvironmentId | null) => + Atom.make( + (get) => + get(serverEnvironment.configValueAtom(environmentId))?.environment.platform.os === "windows", + ).pipe(Atom.withLabel(`file-link-server-windows:${environmentId}`)), +); -export function useFileLinkPrefix(parentSuffixByPath: ReadonlyMap) { +export function useFileLinkPrefix( + parentSuffixByPath: ReadonlyMap, + environmentId: EnvironmentId | null, +) { const depth = useClientSettings((settings) => settings.fileLinkPathDepth); - return (meta: FileLinkPathMeta) => fileLinkPathPrefix(meta, parentSuffixByPath, depth); + const home = useAtomValue(serverHomeAtom(environmentId)); + const windows = useAtomValue(serverWindowsAtom(environmentId)); + const view = { depth, home, windows, repeatedNames: repeatedFileNames(parentSuffixByPath) }; + return (meta: FileLinkPathMeta) => fileLinkPathPrefix(meta, view); } /** diff --git a/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx b/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx index af72174a28980..d858608526063 100644 --- a/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx +++ b/apps/web/src/fork/displayMode/displayModeTimeline.browser.test.tsx @@ -110,7 +110,6 @@ function props(): Omit { turnDiffSummaries: [], runs: [], routeThreadKey: `environment-local:display-mode-${Math.random().toString(36).slice(2)}`, - onOpenTurnDiff: () => {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, diff --git a/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts b/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts index a0b8761592f29..0e20c9db867a7 100644 --- a/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts +++ b/apps/web/src/fork/displayMode/useThreadDisplayMode.test.ts @@ -34,6 +34,7 @@ const menuState: ThreadActionMenuState = { canSnoozeNow: true, isRegeneratingTitle: false, isRunning: false, + hasCompletedRun: true, supports: { settlement: true, autoSettleOptOut: true, diff --git a/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx b/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx index 44e3ed546c4f1..7eb9e95bbf89f 100644 --- a/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx +++ b/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx @@ -1,5 +1,10 @@ -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; -import { expect, it } from "vite-plus/test"; +import { + DEFAULT_CLIENT_SETTINGS, + EnvironmentId, + type EditorId, + ThreadId, +} from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; import "~/index.css"; @@ -9,34 +14,67 @@ import ChatMarkdown from "../components/ChatMarkdown"; import { collectThreadFindRanges } from "../components/chat/threadFindHighlights"; import { __setClientSettingsForTests, persistClientSettingsPatch } from "../hooks/useSettings"; +const SERVER_HOME_ENVIRONMENT = vi.hoisted(() => "server-home"); + +// One environment reports a home folder that its thread's cwd does not reveal. +vi.mock(import("../state/server"), async (original) => { + const actual = await original(); + const { Atom } = await import("effect/reactivity"); + const config = Atom.make({ + availableEditors: [] as readonly EditorId[], + environment: { platform: { os: "linux" }, capabilities: {} }, + homeDirectory: "/srv/me", + }); + const configValueAtom = actual.serverEnvironment.configValueAtom; + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + configValueAtom: ((environmentId: EnvironmentId | null) => + environmentId === SERVER_HOME_ENVIRONMENT + ? config + : configValueAtom(environmentId)) as never, + }, + }; +}); + const TEXT = [ - "See [glossary](docs/review-pipeline/glossary.md#L12), [web](src/web/index.ts), [server](src/server/index.ts) and [readme](README.md).", + "See [glossary](docs/review-pipeline/glossary.md#L12), [web](src/web/index.ts), [server](src/server/index.ts), [readme](README.md) and [hosts](/etc/hosts).", "The review is done.", ].join("\n\n"); -it("draws the chosen folders before file names, outside the label text", async () => { +function withDefaultSettings(): Disposable { __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); - using _settings = { - [Symbol.dispose]: () => __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS), - }; + return { [Symbol.dispose]: () => __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS) }; +} + +function chipPrefixes(container: HTMLElement) { + return [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) => { + const prefix = chip.querySelector("[data-file-link-prefix]"); + return [prefix && getComputedStyle(prefix, "::after").content, chip.textContent]; + }); +} + +it("draws the chosen folders before file names, outside the label text", async () => { + using _settings = withDefaultSettings(); await using screen = await render(
, ); - const chips = () => - [...screen.container.querySelectorAll(".chat-markdown-file-link")].map((chip) => { - const prefix = chip.querySelector("[data-file-link-prefix]"); - return [prefix && getComputedStyle(prefix, "::after").content, chip.textContent]; - }); - const labels = ["glossary.md · L12", "index.ts · src/web", "index.ts · src/server", "README.md"]; - expect(chips()).toEqual(labels.map((label) => [null, label])); - - await act(() => persistClientSettingsPatch({ fileLinkPathDepth: 2 }, async () => {})); - - expect(chips()).toEqual([ + const labels = [ + "glossary.md · L12", + "index.ts · src/web", + "index.ts · src/server", + "README.md", + "hosts", + ]; + expect(chipPrefixes(screen.container)).toEqual([ ['"review-pipeline/"', labels[0]], - ...labels.slice(1).map((label) => [null, label]), + [null, labels[1]], + [null, labels[2]], + [null, labels[3]], + ['"/etc/"', labels[4]], ]); await expect .element( @@ -60,4 +98,32 @@ it("draws the chosen folders before file names, outside the label text", async ( position: { x: word.left - box.left + 4, y: word.top - box.top + word.height / 2 }, }); expect(window.getSelection()?.toString().trim()).toBe(paragraph.textContent?.trim()); + + await act(() => persistClientSettingsPatch({ fileLinkPathDepth: 1 }, async () => {})); + + expect(chipPrefixes(screen.container)).toEqual(labels.map((label) => [null, label])); +}); + +it("draws ~/ at the home folder the thread's server reports", async () => { + using _settings = withDefaultSettings(); + const text = "See [a](/srv/me/notes/a.md) and [b](/srv/other/notes/b.md)."; + await using screen = await render( + <> + + + , + ); + expect(chipPrefixes(screen.container)).toEqual([ + ['"~/notes/"', "a.md"], + ['"notes/"', "b.md"], + ['"notes/"', "a.md"], + ['"notes/"', "b.md"], + ]); }); diff --git a/apps/web/src/fork/fileLinkPathDepth.test.ts b/apps/web/src/fork/fileLinkPathDepth.test.ts index 189bc91934497..cd335702e4ddd 100644 --- a/apps/web/src/fork/fileLinkPathDepth.test.ts +++ b/apps/web/src/fork/fileLinkPathDepth.test.ts @@ -1,45 +1,177 @@ import type { FileLinkPathDepth } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { fileLinkPathPrefix } from "./fileLinkPathDepth"; +import { type FileLinkPathMeta, fileLinkPathPrefix, repeatedFileNames } from "./fileLinkPathDepth"; -type Meta = Parameters[0]; - -const inWorkspace = (workspaceRelativePath: string): Meta => ({ - filePath: `/home/me/project/${workspaceRelativePath}`, +const HOME = "/home/me"; +const inWorkspace = ( + workspaceRelativePath: string, + root = "/home/me/project", +): FileLinkPathMeta => ({ + filePath: `${root}/${workspaceRelativePath}`, workspaceRelativePath, + workspaceLookupPath: null, +}); +// A link written relative to the workspace, which may open a search match elsewhere. +const written = (workspaceRelativePath: string, root = "/home/me/project"): FileLinkPathMeta => ({ + ...inWorkspace(workspaceRelativePath, root), + workspaceLookupPath: workspaceRelativePath, +}); +const outside = (filePath: string): FileLinkPathMeta => ({ + filePath, + workspaceRelativePath: null, + workspaceLookupPath: null, }); -const outside = (filePath: string): Meta => ({ filePath, workspaceRelativePath: null }); const collisions = new Map([ ["/home/me/project/src/web/index.ts", "src/web"], ["C:/repo/src/server/index.ts", "src/server"], ]); describe("fileLinkPathPrefix", () => { - it.each<[string, Meta, FileLinkPathDepth, string | undefined]>([ - ["depth 1 shows no folder", inWorkspace("docs/review-pipeline/glossary.md"), 1, undefined], - ["depth 2", inWorkspace("docs/review-pipeline/glossary.md"), 2, "review-pipeline/"], - ["depth 3", inWorkspace("docs/review-pipeline/glossary.md"), 3, "docs/review-pipeline/"], - ["a workspace root file", inWorkspace("README.md"), 3, undefined], - ["fewer folders than the depth", inWorkspace("docs/glossary.md"), 5, "docs/"], - [ - "an absolute path outside the workspace", - outside("/etc/nginx/sites/app.conf"), + it.each< + [string, FileLinkPathMeta, FileLinkPathDepth, string | null, string | undefined, boolean?] + >([ + // Home and root examples at the default depth. + ["a file in home", outside("/home/me/a.md"), 2, HOME, "~/"], + ["a folder in home", outside("/home/me/dir/a.md"), 2, HOME, "~/dir/"], + ["a file at root", outside("/a.md"), 2, HOME, "/"], + ["a folder at root", outside("/etc/a.conf"), 2, HOME, "/etc/"], + ["past home", outside("/home/me/x/dir/a.md"), 2, HOME, "dir/"], + ["reaching home after two folders", outside("/home/me/x/dir/a.md"), 3, HOME, "~/x/dir/"], + ["past root", outside("/etc/x/a.conf"), 2, HOME, "x/"], + ["fewer folders than the depth at home", outside("/home/me/a.md"), 5, HOME, "~/"], + ["fewer folders than the depth at root", outside("/etc/nginx/a.conf"), 5, HOME, "/etc/nginx/"], + ["depth 1 shows no folder", outside("/home/me/dir/a.md"), 1, HOME, undefined], + ["depth 1 shows no root", outside("/a.md"), 1, HOME, undefined], + ["another user's home", outside("/home/bob/a.md"), 2, HOME, "bob/"], + ["another user's home reaching root", outside("/home/bob/a.md"), 3, HOME, "/home/bob/"], + ["a folder that only starts like home", outside("/home/me2/a.md"), 2, HOME, "me2/"], + ["the folder above home", outside("/home/a.md"), 2, HOME, "/home/"], + ["home unknown", outside("/home/me/a.md"), 2, null, "me/"], + ["home at /root", outside("/root/notes/a.md"), 2, "/root", "~/notes/"], + ["a home at root", outside("/etc/hosts"), 2, "/", "/etc/"], + ["a home at a drive root", outside("C:\\x\\a.md"), 2, "C:\\", "C:/x/"], + ["home given with a trailing slash", outside("/home/me/dir/a.md"), 2, "/home/me/", "~/dir/"], + // An unexpanded `~/` link. + ["a literal ~ file", outside("~/a.md"), 2, null, "~/"], + ["a literal ~ folder", outside("~/notes/a.md"), 2, null, "~/notes/"], + ["past a literal ~", outside("~/x/notes/a.md"), 2, null, "notes/"], + ["a literal ~ with home known", outside("~/notes/a.md"), 3, HOME, "~/notes/"], + // The workspace no longer stops the walk. + [ + "a workspace file", + inWorkspace("docs/review-pipeline/glossary.md"), + 2, + HOME, + "review-pipeline/", + ], + [ + "a workspace file, deeper", + inWorkspace("docs/review-pipeline/glossary.md"), + 3, + HOME, + "docs/review-pipeline/", + ], + ["a workspace root file", inWorkspace("README.md", "/home/me/code/proj"), 2, HOME, "proj/"], + [ + "a workspace root file reaching home", + inWorkspace("README.md", "/home/me/code/proj"), + 3, + HOME, + "~/code/proj/", + ], + ["a workspace in home", inWorkspace("README.md", "/home/me/proj"), 2, HOME, "~/proj/"], + ["a workspace at home", inWorkspace("README.md", HOME), 2, HOME, "~/"], + ["a workspace at home, one folder", inWorkspace("notes/a.md", HOME), 2, HOME, "~/notes/"], + ["a workspace at root", inWorkspace("a.md", ""), 2, null, "/"], + ["a POSIX folder named like a drive", inWorkspace("C:/a.md", ""), 2, null, "/C:/"], + ["a workspace folder named like a drive", inWorkspace("C:/docs/a.md"), 3, HOME, "C:/docs/"], + // `..` and `.` fold before the walk. + ["a .. reaching home", outside("/home/me/proj/../a.md"), 2, HOME, "~/"], + ["a .. outside home", outside("/home/me/proj/../x/y/a.ts"), 2, HOME, "y/"], + ["a .. past root", outside("/a/../../b/c.md"), 3, HOME, "/b/"], + ["a .. that names a parent", inWorkspace("docs/guides/../glossary.md"), 2, HOME, "docs/"], + ["folders after a leading ..", outside("../../shared/lib/util.ts"), 4, HOME, "shared/lib/"], + ["a dot folder", outside("./src/./app.ts"), 3, HOME, "src/"], + // Windows. + ["a Windows drive root file", outside("C:\\a.md"), 2, null, "C:/"], + ["a Windows drive path", outside("C:\\Users\\me\\notes.md"), 2, null, "me/"], + [ + "a Windows drive path reaching the drive", + outside("C:\\Users\\me\\notes.md"), + 4, + null, + "C:/Users/me/", + ], + ["a Windows home", outside("C:\\Users\\me\\notes.md"), 2, "C:\\Users\\me", "~/"], + [ + "a Windows home in another case", + outside("c:\\users\\ME\\d\\notes.md"), + 2, + "C:\\Users\\me", + "~/d/", + ], + [ + "a Windows path on another drive", + outside("D:\\Users\\me\\notes.md"), 3, - "nginx/sites/", - ], - ["a POSIX name with a backslash", outside("/tmp/notes/a\\b.md"), 2, undefined], - ["a workspace folder named like a drive", inWorkspace("C:/docs/a.md"), 3, "C:/docs/"], - ["a slash-prefixed Windows drive path", outside("/C:/Users/me/notes.md"), 3, "Users/me/"], - ["a Windows drive path", outside("C:\\Users\\me\\notes.md"), 4, "Users/me/"], - ["a UNC path", outside("\\\\server\\share\\docs\\a.md"), 3, "share/docs/"], - ["folders after a leading ..", outside("../../shared/lib/util.ts"), 4, "shared/lib/"], - ["a .. that names a parent", inWorkspace("docs/guides/../glossary.md"), 2, "docs/"], - ["a .. past the folders", outside("/a/../../b/c.md"), 3, "b/"], - ["a dot folder", outside("./src/./app.ts"), 3, "src/"], - ["a colliding path", inWorkspace("src/web/index.ts"), 3, undefined], - ["a colliding Windows path", outside("C:\\repo\\src\\server\\index.ts"), 3, undefined], - ])("%s", (_name, meta, depth, expected) => { - expect(fileLinkPathPrefix(meta, collisions, depth)).toBe(expected); + "C:\\Users\\me", + "D:/Users/me/", + ], + ["a POSIX home for a Windows path", outside("C:\\home\\me\\a.md"), 2, HOME, "me/"], + ["a .. at a drive root", outside("C:\\..\\a.md"), 2, null, "C:/"], + ["a slash-prefixed Windows drive", outside("/C:/Users/me/notes.md"), 3, null, "C:/Users/me/"], + ["a slash-prefixed Windows home", outside("/C:/Users/me/notes.md"), 3, "C:\\Users\\me", "~/"], + ["a UNC path", outside("\\\\server\\share\\docs\\a.md"), 3, null, "share/docs/"], + [ + "a UNC path shows its server", + outside("\\\\server\\share\\docs\\a.md"), + 5, + null, + "server/share/docs/", + ], + // A written workspace link shows only the folders it names. + [ + "a written workspace link", + written("docs/review-pipeline/glossary.md"), + 5, + HOME, + "docs/review-pipeline/", + ], + ["a written file name", written("README.md"), 3, HOME, undefined], + ["a written file name at home", written("README.md", HOME), 2, HOME, undefined], + [ + "a written ./ link walks on", + { ...written("./docs/a.md"), filePath: "/home/me/project/docs/a.md" }, + 3, + HOME, + "~/project/docs/", + ], + // An unexpanded `~/` link and a Windows server's Git Bash path use the reported home. + ["a literal ~ with home at root", outside("~/notes.md"), 2, "/", "/"], + ["a literal ~ with a .. past home", outside("~/../notes.md"), 2, "/srv/me", "/srv/"], + [ + "a Git Bash path on a Windows server", + outside("/c/Users/alex/notes.md"), + 2, + "C:\\Users\\alex", + "~/", + true, + ], + ["a Git Bash drive root", outside("/d/a.md"), 2, "C:\\Users\\alex", "D:/", true], + ["a Git Bash path with no reported home", outside("/d/a.md"), 2, null, "D:/", true], + ["a /c folder on a POSIX server", outside("/c/a.md"), 2, HOME, "/c/"], + ["a written link past its own folders", written("docs/../../notes.md"), 5, HOME, undefined], + ["a link to home itself", outside("~/"), 2, "/srv/me", undefined], + // No prefix. + ["a root file named like a repeated file", outside("/home/me/index.ts"), 2, HOME, undefined], + ["a link to a parent folder", outside("/home/me/one/project/../"), 2, HOME, undefined], + ["a link to a current folder", outside("/home/me/one/."), 2, HOME, undefined], + ["a POSIX name with a backslash", outside("/tmp/notes/a\\b.md"), 2, HOME, undefined], + ["a colliding path", inWorkspace("src/web/index.ts"), 3, HOME, undefined], + ["a colliding Windows path", outside("C:\\repo\\src\\server\\index.ts"), 3, null, undefined], + ])("%s", (_name, meta, depth, home, expected, windows = false) => { + const repeatedNames = repeatedFileNames(collisions); + expect(fileLinkPathPrefix(meta, { depth, home, windows, repeatedNames })).toBe(expected); }); }); diff --git a/apps/web/src/fork/fileLinkPathDepth.ts b/apps/web/src/fork/fileLinkPathDepth.ts index 171c1c49bf3fe..ac19bb975901c 100644 --- a/apps/web/src/fork/fileLinkPathDepth.ts +++ b/apps/web/src/fork/fileLinkPathDepth.ts @@ -3,29 +3,145 @@ import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "@t3tools/ import type { MarkdownFileLinkMeta } from "../markdown-links"; -export type FileLinkPathMeta = Pick; +export type FileLinkPathMeta = Pick< + MarkdownFileLinkMeta, + "filePath" | "workspaceRelativePath" | "workspaceLookupPath" +>; -/** The last `depth - 1` folders of a file link as `a/b/`, or undefined when there are none to show. */ +export interface FileLinkPathView { + readonly depth: FileLinkPathDepth; + readonly home: string | null; + // The server runs on Windows, where Git Bash writes `C:\x` as `/c/x`. + readonly windows: boolean; + // File names that repeat in the message, from `repeatedFileNames`. + readonly repeatedNames: ReadonlySet; +} + +/** The file names of a message's repeated-name folder hints. */ +export function repeatedFileNames(parentSuffixByPath: ReadonlyMap): Set { + return new Set([...parentSuffixByPath.keys()].map(lastName)); +} + +type PathKind = "posix" | "relative" | "drive" | "unc"; + +interface FoldedPath { + readonly kind: PathKind; + // `.` dropped and `..` folded; a drive path starts with its drive (`C:`), a UNC path with its server. + readonly names: readonly string[]; + // The walk shows no folder before this index. + readonly floor: number; +} + +function foldPath(raw: string): FoldedPath { + const kind: PathKind = raw.startsWith("\\\\") + ? "unc" + : isWindowsAbsolutePath(raw) + ? "drive" + : raw.startsWith("/") + ? "posix" + : "relative"; + const windows = kind === "drive" || kind === "unc"; + // `..` never climbs above a drive or a UNC share. + const top = kind === "drive" ? 1 : kind === "unc" ? 2 : 0; + const names: string[] = []; + for (const part of raw.split(windows ? /[\\/]/ : "/")) { + if (part === "" || part === ".") continue; + if (part !== "..") names.push(part); + else if (names.length > top && names.at(-1) !== "..") names.pop(); + else if (kind === "relative") names.push(part); + } + // A UNC path shows its server and share like folders, as before; it draws no root marker. + const floor = kind === "relative" ? names.lastIndexOf("..") + 1 : 0; + return { kind, names, floor }; +} + +// How many leading names of `path` are the home folder; undefined when it is not under home. +function homeLength(path: FoldedPath, home: string | null): number | undefined { + if (path.kind === "relative") return path.floor === 0 && path.names[0] === "~" ? 1 : undefined; + if (home === null) return undefined; + const homePath = foldPath(home); + // A home at `/` or at a drive root is that root, which draws its own marker. + if (homePath.names.length <= (homePath.kind === "drive" ? 1 : 0)) return undefined; + if (homePath.kind !== path.kind || homePath.names.length > path.names.length) return undefined; + const same = + path.kind === "posix" + ? (a: string, b: string) => a === b + : (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); + return homePath.names.every((name, i) => same(name, path.names[i]!)) + ? homePath.names.length + : undefined; +} + +/** + * Returns the path prefix before a file link's name, with up to `depth - 1` folders, ending in `/`. + * Stops early at home with `~/`, at POSIX root with `/`, or at a Windows drive root such as `C:/`. + * Returns `undefined` at depth 1, for a repeated file name, or when there is nothing to show. + */ export function fileLinkPathPrefix( meta: FileLinkPathMeta, - parentSuffixByPath: ReadonlyMap, - depth: FileLinkPathDepth, + view: FileLinkPathView, ): string | undefined { - if (depth === 1 || parentSuffixByPath.has(meta.filePath.replaceAll("\\", "/"))) return undefined; - // Workspace-relative paths already use `/`; a POSIX name may contain `\`. - const path = meta.workspaceRelativePath ?? stripSlashPrefixedWindowsDrive(meta.filePath); - const windows = meta.workspaceRelativePath === null && isWindowsAbsolutePath(path); - const segments = path - .split(windows ? /[\\/]/ : "/") - .filter((segment) => segment !== "" && segment !== "."); - if (windows && /^[A-Za-z]:$/.test(segments[0] ?? "")) segments.shift(); + if (view.depth === 1) return undefined; + // A repeated file name keeps its folder hint after the name instead. The hint map leaves out a + // copy that has no folder above it, so the check goes by name. + const name = lastName(meta.filePath); + if (view.repeatedNames.has(name)) return undefined; + // The label of a link ending in `.`, `..` or a bare `~` is that name, not the folder it + // reaches, so any folders drawn before it would name another path. + if (name === "." || name === ".." || /^~[\\/]*$/.test(meta.filePath)) return undefined; + const path = foldPath(hostPath(meta, view)); // The label names such a file by its last `\` part, so folders before it would misname the path. - if (!windows && segments.at(-1)?.includes("\\")) return undefined; - const resolved: string[] = []; - for (const segment of segments) { - if (segment === ".." && resolved.length > 0 && resolved.at(-1) !== "..") resolved.pop(); - else resolved.push(segment); + if ((path.kind === "posix" || path.kind === "relative") && path.names.at(-1)?.includes("\\")) { + return undefined; + } + const folders = path.names.length - 1; + const home = homeLength(path, view.home); + // A link written relative to the workspace may open a search match in another folder, so only + // the folders it names are sure, and no marker is drawn above them. + const lookup = meta.workspaceLookupPath; + const written = + lookup !== null && !/^(?:\.{1,2}|~)[\\/]/.test(lookup) && !/[\\/]$/.test(lookup) + ? foldPath(lookup) + : null; + // Names before any leading `..` the link keeps are not folders it names. + const unsure = written === null ? -1 : path.names.length - (written.names.length - written.floor); + // `above` counts the folders still hidden; the walk moves up one folder at a time. + let above = folders; + let marker = ""; + while (above > unsure) { + if (above === home) marker = "~/"; + else if (path.kind === "posix" && above === 0) marker = "/"; + else if (path.kind === "drive" && above === 1) marker = `${path.names[0]}/`; + if (marker !== "" || above <= path.floor || folders - above === view.depth - 1) break; + above -= 1; + } + const shown = path.names.slice(Math.max(above, unsure), folders); + const prefix = marker + shown.map((folder) => `${folder}/`).join(""); + return prefix === "" ? undefined : prefix; +} + +function lastName(path: string): string { + return ( + path + .split(/[\\/]/) + .filter((part) => part !== "") + .at(-1) ?? "" + ); +} + +// The file's path as the server reads it, as far as display needs it. +function hostPath(meta: FileLinkPathMeta, { home, windows }: FileLinkPathView): string { + // An unexpanded `~/` link names the reported home. + if (/^~[\\/]/.test(meta.filePath) && home) { + return `${home.replace(/[\\/]+$/, "")}/${meta.filePath.slice(2)}`; + } + // Only a path outside the workspace may be a Windows drive written after a slash; inside a + // workspace at `/`, `/C:/a.md` names a POSIX folder `C:`. + if (meta.workspaceRelativePath !== null) return meta.filePath; + // A Windows server reads Git Bash's `/c/x` as `C:/x`. + if (windows) { + const drive = /^\/([a-zA-Z])(?=\/|$)/.exec(meta.filePath); + if (drive !== null) return `${drive[1]!.toUpperCase()}:${meta.filePath.slice(2) || "/"}`; } - const folders = resolved.slice(resolved.lastIndexOf("..") + 1, -1).slice(1 - depth); - return folders.length === 0 ? undefined : `${folders.join("/")}/`; + return stripSlashPrefixedWindowsDrive(meta.filePath); } diff --git a/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx b/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx index fb4654c66c175..8840c1e4dcb0a 100644 --- a/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx +++ b/apps/web/src/fork/idleCompactionTimeline.browser.test.tsx @@ -102,7 +102,6 @@ describe("whileIdle compaction in the timeline", () => { turnDiffSummaries={[]} runs={[]} routeThreadKey="environment-local:thread-while-idle" - onOpenTurnDiff={() => {}} onOpenThread={() => {}} onForkFromRun={async () => {}} supportsConversationRollback={false} diff --git a/apps/web/src/fork/singleTilde.browser.test.tsx b/apps/web/src/fork/singleTilde.browser.test.tsx index cf415cbc7404e..77511f698447e 100644 --- a/apps/web/src/fork/singleTilde.browser.test.tsx +++ b/apps/web/src/fork/singleTilde.browser.test.tsx @@ -133,7 +133,6 @@ function singleTildeTimeline(stage: Stage) { turnDiffSummaries={[]} runs={[]} routeThreadKey="environment-local:thread-single-tilde" - onOpenTurnDiff={() => {}} onOpenThread={() => {}} onForkFromRun={async () => {}} supportsConversationRollback={false} diff --git a/apps/web/src/fork/timelineReaderLine.browser.test.tsx b/apps/web/src/fork/timelineReaderLine.browser.test.tsx index 4cbbfbd8de2cd..8f00b86785fac 100644 --- a/apps/web/src/fork/timelineReaderLine.browser.test.tsx +++ b/apps/web/src/fork/timelineReaderLine.browser.test.tsx @@ -68,7 +68,6 @@ function props(listRef: TimelineProps["listRef"]): Omit {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index bc0543b136047..94326fa47f678 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -13,6 +13,7 @@ import { AuthOrchestrationOperateScope, type ScopedThreadRef, type ThreadId, + type ContextMenuSource, } from "@t3tools/contracts"; import { useRouter } from "@tanstack/react-router"; import { msg } from "gt-react"; @@ -119,7 +120,7 @@ export function useThreadActionMenu(input: { onError: (error) => failureToast(m(msg("Failed to copy thread ID")), error), }); - const openMenu = (position: { x: number; y: number }) => { + const openMenu = (position: { x: number; y: number }, source?: ContextMenuSource) => { if (threadRef === null) return; void (async () => { const api = readLocalApi(); @@ -155,13 +156,14 @@ export function useThreadActionMenu(input: { canSnoozeNow: canSnooze(thread, { now: now.toISOString() }), isRegeneratingTitle, isRunning: !threadRuntimeCanArchive(thread.runtime), + hasCompletedRun: thread.latestRun?.completedAt != null, supports, snoozePresets, canShareWithGuest, canTurnIntoProject: canTurnThreadIntoProject(threadRef), displayModeItems: displayModeMenuItems(threadRef), }); - const clicked = await settlePromise(() => api.contextMenu.show(items, position)); + const clicked = await settlePromise(() => api.contextMenu.show(items, position, source)); if (clicked._tag === "Failure" || clicked.value === null) return; const action: ThreadActionMenuId = clicked.value; if ( diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index caa82b0777d44..5a01bceadb34c 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Fertig", "d4d89c139de812a8": "Fehlgeschlagen", "c1e03a860c856245": "Gestoppt", - "f1d27d127ab27ac6": "Wird gestartet", + "7e5abc299ead1d09": "{provider}-Plugins werden geladen", + "21872f69ccbc711d": "{provider}-MCP-Server werden gestartet", + "fedaa29ff8815a77": "{provider}-Hooks werden geladen", + "57025ae4de5beb57": "{provider}-Regeln und -Skills werden geladen", + "4729a188600f1501": "Verbindung zu {provider} wird hergestellt", "8c8977097681630f": "{provider} wird gestartet", + "f1d27d127ab27ac6": "Wird gestartet", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Wartet", "54002bf654ddbab1": "Abgeschlossen", @@ -2162,7 +2167,7 @@ "b878f0bae5cf772e": "Editor kann nicht geöffnet werden.", "707dcfa79035726d": "Datei kann nicht geöffnet werden", "0282c27e763f6e1d": "Git-Initialisierung fehlgeschlagen", - "72941c977ef9beab": "{term, select, mr {Detached HEAD: Erstelle einen Branch und checke ihn aus, um Push- und Merge Request-Aktionen zu aktivieren.} cr {Detached HEAD: Erstelle einen Branch und checke ihn aus, um Push- und Änderungsanfrage-Aktionen zu aktivieren.} other {Detached HEAD: Erstelle einen Branch und checke ihn aus, um Push- und Pull Request-Aktionen zu aktivieren.}}", + "72941c977ef9beab": "{term, select, mr {Detached HEAD: Erstelle einen Branch und checke ihn aus, um Push- und Merge-Request-Aktionen zu aktivieren.} cr {Detached HEAD: Erstelle einen Branch und checke ihn aus, um Push- und Änderungsanfrage-Aktionen zu aktivieren.} other {Detached HEAD: Erstelle einen Branch und checke ihn aus, um Push- und Pull-Request-Aktionen zu aktivieren.}}", "9130ab3c1d3a51e4": "Git-Aktionen für {name}", "511aca627fadc47d": "Git-Aktionen", "02310c860a9eb34f": "Optionen für Git-Aktionen", @@ -2370,8 +2375,8 @@ "d3ce1a00115898a6": "Alle aktualisieren", "6d8832b5eb303f7f": "{term, select, mr {Merge Request #{number}} cr {Änderungsanfrage #{number}} other {Pull Request #{number}}}", "3255abe463a83a3f": "{term, select, mr {Thread für den Merge Request konnte nicht vorbereitet werden.} cr {Thread für die Änderungsanfrage konnte nicht vorbereitet werden.} other {Thread für den Pull Request konnte nicht vorbereitet werden.}}", - "cfc6b8e4d302189c": "{term, select, mr {Füge eine Merge Request-URL oder einen Checkout-Befehl ein oder gib 123 / #123 ein.} cr {Füge eine Änderungsanfrage-URL oder einen Checkout-Befehl ein oder gib 123 / #123 ein.} other {Füge eine Pull Request-URL oder einen Checkout-Befehl ein oder gib 123 / #123 ein.}}", - "5e3cb0bfcee48466": "{term, select, mr {Verwende eine Merge Request-URL, einen Checkout-Befehl, 123 oder #123.} cr {Verwende eine Änderungsanfrage-URL, einen Checkout-Befehl, 123 oder #123.} other {Verwende eine Pull Request-URL, einen Checkout-Befehl, 123 oder #123.}}", + "cfc6b8e4d302189c": "{term, select, mr {Füge eine Merge-Request-URL oder einen Checkout-Befehl ein oder gib 123 / #123 ein.} cr {Füge eine Änderungsanfrage-URL oder einen Checkout-Befehl ein oder gib 123 / #123 ein.} other {Füge eine Pull-Request-URL oder einen Checkout-Befehl ein oder gib 123 / #123 ein.}}", + "5e3cb0bfcee48466": "{term, select, mr {Verwende eine Merge-Request-URL, einen Checkout-Befehl, 123 oder #123.} cr {Verwende eine Änderungsanfrage-URL, einen Checkout-Befehl, 123 oder #123.} other {Verwende eine Pull-Request-URL, einen Checkout-Befehl, 123 oder #123.}}", "3c113f34f37bd489": "{term, select, mr {Löse einen Merge Request von {provider} auf und erstelle dann den Entwurfs-Thread im Haupt-Repository oder in einem eigenen Worktree.} cr {Löse eine Änderungsanfrage von {provider} auf und erstelle dann den Entwurfs-Thread im Haupt-Repository oder in einem eigenen Worktree.} other {Löse einen Pull Request von {provider} auf und erstelle dann den Entwurfs-Thread im Haupt-Repository oder in einem eigenen Worktree.}}", "25d251408808632c": "{term, select, mr {Merge Request} cr {Änderungsanfrage} other {Pull Request}}", "79af20c22805d206": "{term, select, mr {MR-URL, Checkout-Befehl oder #42} cr {Änderungsanfrage-URL, Checkout-Befehl oder #42} other {PR-URL, Checkout-Befehl oder #42}}", @@ -3233,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Zugriff", "9699d255b374e215": "Was es tun darf", "86f5769278f5fa4d": "Über das reine Lesen hinaus kann es Threads starten, Nachrichten senden und Threads stoppen, und keiner davon kann mit mehr als dem gewählten Modus laufen.", - "693a1983e099523a": "Verbindung mit diesem Backend.", + "4f3982f640dfed5b": "Dieser Link fügt diesem Browser ein Backend hinzu. Fahre nur fort, wenn du ihm vertraust.", + "41b32a424841adb7": "Dieser Kopplungslink enthält einen ungültigen Backend-Host.", "ec2a82b05e616aa0": "Diesem Kopplungslink fehlen Backend-Host oder Token.", "630d4f04309bc19a": "Authentifizierung fehlgeschlagen.", "63bc32e8544f4de1": "Diese Umgebung erwartet vertrauenswürdige Kopplungsdaten, bevor die App sich verbinden kann.", @@ -3247,11 +3253,13 @@ "55c59743f7fdd7fa": "Einmaltoken oder Kopplungsgeheimnis einfügen", "ca6a0c94398d763d": "Wird gekoppelt...", "989f56b8297dd684": "Dieses einmalige Kopplungstoken wurde bereits übermittelt. Fordere einen neuen Kopplungslink an.", + "693a1983e099523a": "Verbindung mit diesem Backend.", "db3dcafc90d10405": "{environment} ist in diesem Browser gespeichert.", "47d4ab320c4c394c": "Die Umgebung ist in diesem Browser gespeichert.", "d235c6bfa25870a4": "{error} Falls das Backend dieses Einmaltoken akzeptiert hat, fordere vor einem neuen Versuch einen neuen Kopplungslink an.", "00c1dcaef4762f18": "Backend gekoppelt", "aac4a30e5912c01c": "Kopplung fehlgeschlagen", + "c142c3f3bed15f8d": "Dieses Backend hinzufügen?", "dbb27f4ee8ecfa8e": "Backend wird gekoppelt", "8049e9ba2e8b4867": "Kopplungstoken", "0528294df7656322": [ @@ -3268,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Prüfe, ob das Backend von diesem Browser aus erreichbar ist, CORS für gehostete Clients unterstützt und über HTTPS ausgeliefert wird, wenn du diese Seite über HTTPS öffnest.", + "984c25ffcae69300": "Backend hinzufügen", "08570ee0982df89d": "Wird gekoppelt...", "3bbae7c96b6cbfc3": "App öffnen", "49cc06e79f21f85a": "{seconds} s", @@ -3313,13 +3322,9 @@ "b90e87f4b7125237": "Details", "16dc67f5429d8bae": "Hintergrundarbeit", "2188eee8f81b0f51": "Subagent öffnen", - "3b03fc47eba632b4": "{count, plural, one {{formattedCount} geänderte Datei} other {{formattedCount} geänderte Dateien}}", "ec9e0be8ec693302": "Alle Ordner einklappen", "b791dd86f7991cc0": "Alle Ordner ausklappen", - "afaf1bc8535e0adf": "Diff öffnen", - "d31b3c7be099ca82": "{count, plural, one {{formattedCount} weitere Datei im vollständigen Diff} other {{formattedCount} weitere Dateien im vollständigen Diff}}", "55b936e3014e16c8": "Diff öffnen", - "452dc9eaa945693b": "Vollständigen Diff öffnen", "28bb7ce40dfd349a": "Terminal-Ausgabe kann nicht zu einer Antwort auf eine Frage hinzugefügt werden.", "801cb8edea94b8f6": "Beantworte oder verwirf zuerst die Frage und füge sie dann zum Chat hinzu.", "aa5507f20d94d5a9": "Aktualisiere diesen Server, um Dateien mit Antworten auf Fragen zu senden", @@ -4401,7 +4406,6 @@ "991cc9fb37606c91": "(leere Antwort)", "36e4b8d2db087296": "Ab dieser Antwort forken", "c92a0bab54261695": "Auf diese Antwort antworten", - "405a3e88ee6e62b3": "Die Änderungen dieser Runde in diesem Repository können nicht aufgelistet werden.", "f6958f38dc87c712": "Ab dieser Antwort forken", "72f8e14b1246d224": "Auf diese Antwort antworten", "01d7728e893c281d": "Zur Nachricht springen: {text}", @@ -6780,7 +6784,7 @@ "355609f8b425cc4c": "Dieser Branch konnte nicht aktualisiert werden", "7e020f5d0edfb882": "Auto-Merge konnte nicht aktiviert werden", "d199769cab7a15e5": "Auto-Merge konnte nicht deaktiviert werden", - "3a46604447a50543": "{term, select, mr {Revert-Merge Request konnte nicht geöffnet werden} cr {Revert-Änderungsanfrage konnte nicht geöffnet werden} other {Revert-Pull Request konnte nicht geöffnet werden}}", + "3a46604447a50543": "{term, select, mr {Revert-Merge-Request konnte nicht geöffnet werden} cr {Revert-Änderungsanfrage konnte nicht geöffnet werden} other {Revert-Pull-Request konnte nicht geöffnet werden}}", "a5da35efc3a916ab": "Dieser Branch konnte nicht gelöscht werden", "1e0999a44da5da23": "Workflows konnten nicht genehmigt werden", "afa463ad6fb2cee7": "Der Host hat den Merge abgelehnt. Prüfe, ob du Schreibzugriff hast, die erforderlichen Checks bestanden sind und der Branch keine Konflikte hat.", @@ -6803,9 +6807,9 @@ "60fe94d1196c74a2": "Zeitleiste", "f4c3bb3c5b9e34b7": "Code", "e2d518f339db4c72": "Checkout-Befehl konnte nicht kopiert werden", - "f79f304cce33b8df": "{term, select, mr {Die Zwischenablage-API ist beim Kopieren der Merge Request-Referenz nicht verfügbar.} cr {Die Zwischenablage-API ist beim Kopieren der Änderungsanfrage-Referenz nicht verfügbar.} other {Die Zwischenablage-API ist beim Kopieren der Pull Request-Referenz nicht verfügbar.}}", - "58b58ae0e6ecca0a": "{term, select, mr {Die Merge Request-Referenz konnte nicht in die Zwischenablage kopiert werden.} cr {Die Änderungsanfrage-Referenz konnte nicht in die Zwischenablage kopiert werden.} other {Die Pull Request-Referenz konnte nicht in die Zwischenablage kopiert werden.}}", - "107720b9e48556f4": "{term, select, mr {Revert-Merge Request geöffnet} cr {Revert-Änderungsanfrage geöffnet} other {Revert-Pull Request geöffnet}}", + "f79f304cce33b8df": "{term, select, mr {Die Zwischenablage-API ist beim Kopieren der Merge-Request-Referenz nicht verfügbar.} cr {Die Zwischenablage-API ist beim Kopieren der Änderungsanfrage-Referenz nicht verfügbar.} other {Die Zwischenablage-API ist beim Kopieren der Pull-Request-Referenz nicht verfügbar.}}", + "58b58ae0e6ecca0a": "{term, select, mr {Die Merge-Request-Referenz konnte nicht in die Zwischenablage kopiert werden.} cr {Die Änderungsanfrage-Referenz konnte nicht in die Zwischenablage kopiert werden.} other {Die Pull-Request-Referenz konnte nicht in die Zwischenablage kopiert werden.}}", + "107720b9e48556f4": "{term, select, mr {Revert-Merge-Request geöffnet} cr {Revert-Änderungsanfrage geöffnet} other {Revert-Pull-Request geöffnet}}", "96ef3535e6352a4a": "Branch gelöscht", "e3b55a78e79e96f0": "Die Frage steht im Eingabefeld. Lies sie durch und sende sie dann.", "672f08c2325b2730": "{term, select, mr {Der Merge Request ist im Eingabefeld. Gib deine Frage ein und sende sie.} cr {Die Änderungsanfrage ist im Eingabefeld. Gib deine Frage ein und sende sie.} other {Der Pull Request ist im Eingabefeld. Gib deine Frage ein und sende sie.}}", @@ -6824,17 +6828,19 @@ "6af44ad0dda1af38": "Checkout bereit", "b87fb0086b61296b": "Branch {branch} löschen?", "aba09c3ce3311a68": "Dadurch wird {branch} aus {repository} gelöscht. Lokale Branches und Worktrees bleiben unverändert.", - "a08abd0f82d7806b": "{term, select, mr {Die Zwischenablage-API ist beim Kopieren des Merge Request-Checkout-Befehls nicht verfügbar.} cr {Die Zwischenablage-API ist beim Kopieren des Änderungsanfrage-Checkout-Befehls nicht verfügbar.} other {Die Zwischenablage-API ist beim Kopieren des Pull Request-Checkout-Befehls nicht verfügbar.}}", - "25fa8592a887a29b": "{term, select, mr {Der Merge Request-Checkout-Befehl konnte nicht in die Zwischenablage kopiert werden.} cr {Der Änderungsanfrage-Checkout-Befehl konnte nicht in die Zwischenablage kopiert werden.} other {Der Pull Request-Checkout-Befehl konnte nicht in die Zwischenablage kopiert werden.}}", + "a08abd0f82d7806b": "{term, select, mr {Die Zwischenablage-API ist beim Kopieren des Merge-Request-Checkout-Befehls nicht verfügbar.} cr {Die Zwischenablage-API ist beim Kopieren des Änderungsanfrage-Checkout-Befehls nicht verfügbar.} other {Die Zwischenablage-API ist beim Kopieren des Pull-Request-Checkout-Befehls nicht verfügbar.}}", + "25fa8592a887a29b": "{term, select, mr {Der Merge-Request-Checkout-Befehl konnte nicht in die Zwischenablage kopiert werden.} cr {Der Änderungsanfrage-Checkout-Befehl konnte nicht in die Zwischenablage kopiert werden.} other {Der Pull-Request-Checkout-Befehl konnte nicht in die Zwischenablage kopiert werden.}}", "ff49cda2006d155a": "Zugehörigkeit zum Stack konnte nicht geprüft werden", "be49947d8fca9505": "Zugehörigkeit zum Stack wird geprüft…", "a2e58d83bc5daf36": "Auto-Merge", - "6a2b21500ebf1305": "{term, select, mr {Merge Request-Bereich einklappen} cr {Änderungsanfrage-Bereich einklappen} other {Pull Request-Bereich einklappen}}", + "6a2b21500ebf1305": "{term, select, mr {Merge-Request-Bereich einklappen} cr {Änderungsanfrage-Bereich einklappen} other {Pull-Request-Bereich einklappen}}", "9f07c0e2e791c6b0": "{count, plural, one {{formatted} geänderte Datei} other {{formatted} geänderte Dateien}}", "1f7445dfeeb0502d": "Checkout-Befehl kopieren", "45674081908ac8aa": "Checkout-Befehl kopiert", "d2970574ef7860d0": "{term, select, mr {Branch des Merge Requests kopieren} cr {Branch der Änderungsanfrage kopieren} other {Branch des Pull Requests kopieren}}", "45c92416a82cf22c": "Branch-Name kopiert", + "43a18c0bc37988f4": "Neue Commits wurden gepusht. Ein Merge oder Review gilt weiterhin für {sha}.", + "c930a7ffa49054f0": "Neue Commits laden", "63e533a9db74e8dc": "Checks", "4f7ca990d538a8bc": "Kommentare nicht verfügbar", "95601ce075194611": "{count, plural, one {{formatted} Kommentar} other {{formatted} Kommentare}}", @@ -7195,8 +7201,8 @@ "15edc3a1b4b9d332": "Alle", "54f15ec501a87fa2": "Pull Requests aktualisieren", "3e68dc9ebf575f54": "Pull Requests", - "17254ae3d749b406": "{term, select, mr {Die Zwischenablage-API ist beim Kopieren des Merge Request-Links nicht verfügbar.} cr {Die Zwischenablage-API ist beim Kopieren des Änderungsanfrage-Links nicht verfügbar.} other {Die Zwischenablage-API ist beim Kopieren des Pull Request-Links nicht verfügbar.}}", - "f6d18335a8487ec9": "{term, select, mr {Der Merge Request-Link konnte nicht in die Zwischenablage kopiert werden.} cr {Der Änderungsanfrage-Link konnte nicht in die Zwischenablage kopiert werden.} other {Der Pull Request-Link konnte nicht in die Zwischenablage kopiert werden.}}", + "17254ae3d749b406": "{term, select, mr {Die Zwischenablage-API ist beim Kopieren des Merge-Request-Links nicht verfügbar.} cr {Die Zwischenablage-API ist beim Kopieren des Änderungsanfrage-Links nicht verfügbar.} other {Die Zwischenablage-API ist beim Kopieren des Pull-Request-Links nicht verfügbar.}}", + "f6d18335a8487ec9": "{term, select, mr {Der Merge-Request-Link konnte nicht in die Zwischenablage kopiert werden.} cr {Der Änderungsanfrage-Link konnte nicht in die Zwischenablage kopiert werden.} other {Der Pull-Request-Link konnte nicht in die Zwischenablage kopiert werden.}}", "cde5898c2d720e4d": "Pull Requests durchsuchen oder label:bug", "0e7bc29c7ba8e55d": "Wähle zuerst einen Pull Request", "e853db3f751bf5e4": "Pull Requests werden geladen…", @@ -7553,6 +7559,11 @@ "03338c6aec8edacd": "Lege fest, wie breit Nachrichten und das Eingabefeld auf großen Bildschirmen werden können.", "92785adb251da88c": "Chatbreite auf Standard zurücksetzen", "4d457bcce0c0e272": "Chatbreite", + "7d7f65967cc821e3": "Breite der HTML-Vorschau", + "70ce0af7f78d5957": "Lässt HTML-Vorschauen in einem Chat breiter werden als die Nachrichten, die zentriert bleiben.", + "f2b119bf02ae2558": "Breite der HTML-Vorschau auf Standard zurücksetzen", + "6287212fed0deec6": "Wie Chat", + "dc8e85ea0364649c": "Wie Chat (Standard)", "81f3a196537bbee0": "Komfortabel (Standard)", "e79e5388f669495f": "Den Denkaufwand im Eingabefeld als Namen, etwa Hoch, oder als Balken anzeigen.", "7f0365c7e4e8bcbf": "Anzeige des Aufwands auf Standard zurücksetzen", @@ -8380,7 +8391,7 @@ "ead636d5ac1ea127": "{signal} konnte nicht gesendet werden.", "ce61f2be38d43077": "{signal} konnte nicht gesendet werden", "497c6dcfe55b312e": "Prozess wurde bereits beendet", - "43f5924e467db619": "Der Prozess ist kein Unterprozess des T3 Servers. Er wurde möglicherweise bereits beendet.", + "43f5924e467db619": "Der Prozess ist kein Unterprozess des T3-Servers. Er wurde möglicherweise bereits beendet.", "34129a7937593351": "Verbinde eine Umgebung, um die Diagnose zu sehen.", "d36455bbdd68ca55": "Diagnosezugriff wird geprüft…", "8285f89d29299305": "Laufende Prozesse", @@ -10593,7 +10604,7 @@ "6224c735e72641ce": "Erweiterung aktualisieren", "1ee9ce39d7a9968d": "Installiere das Update und melde dich dann ab und wieder an.", "68dc148ee629e72c": "GNOME-Erweiterungen erlauben", - "e8ce3a0ea5970cbd": "Öffne GNOME Erweiterungen, schalte Erweiterungen ein und prüfe dann erneut.", + "e8ce3a0ea5970cbd": "Öffne GNOME-Erweiterungen, schalte Erweiterungen ein und prüfe dann erneut.", "8e2a1daf5ae4e253": "Erweiterung aktivieren", "badde72b8abcf6f1": "Aktiviere T3 Code SnapShots, um Fenster aufzunehmen.", "c650f0ca645ce2fd": "Aufnahme ist bereit", @@ -10601,7 +10612,7 @@ "1deaba200c76a0f5": "Automatische Aufnahme ist nicht verfügbar", "8545cc747cd78679": "Verwende „Snapshot aufnehmen“ in der Befehlspalette, um ein Fenster zu wählen.", "c7151ea6cfcea431": "Erweiterung konnte nicht eingerichtet werden", - "ccf65aac5ca40975": "Prüfe T3 Code SnapShots in GNOME Erweiterungen und versuch es dann erneut.", + "ccf65aac5ca40975": "Prüfe T3 Code SnapShots in GNOME-Erweiterungen und versuch es dann erneut.", "c8cce66adf416be2": "Versuchen wir es noch einmal", "5ac7cec1cc3c4589": "Snapshots konnten nicht geprüft werden. Versuch es erneut, um fortzufahren.", "3317366cc6a44aab": "Aufnahmezugriff prüfen", @@ -11820,6 +11831,7 @@ "9cf8308531b4ff31": "transparent transparenz deckend menüs dialoge eingabefeld", "d8d6cfd630cff22d": "rot grün blau orange hinzufügungen löschungen änderungen anzahl palette farbenblind", "717e49895cfee1c7": "breit volle breite spalte layout nachrichten eingabefeld monitor", + "9d5c7430a7ff76cf": "breit volle breite inline seite rendern diagramm dashboard artefakt zentriert", "88365077fd80787b": "anpassen anzeigen ausblenden panel karte umgebung editor skripte branch pull request git änderungen server automatisierungen herkunft nutzung limits 5 stunden wöchentlich kontingent tokens kontextfenster", "d561f74efa5f3920": "reasoning aufwand denken balken grafik wort bezeichnung stufe eingabefeld", "6113c17109ee0d57": "latex tex katex gleichungen formeln markdown", @@ -12021,7 +12033,7 @@ "9c73aa0c2e2b4e7d": "Tastenkürzel wählen", "300a948f90c4d75c": "Zurück", "2a50e229df85d553": "Vorwärts", - "8aa6404c8018ea67": "T3 Code Startseite", + "8aa6404c8018ea67": "T3-Code-Startseite", "8e9626aa27cb188a": "Issues", "9d2fc1003e82feb1": "Nutzung", "20283eb1dd6119f9": "{count, plural, one {{count} Anhang} other {{count} Anhänge}}", @@ -12137,7 +12149,8 @@ "f938bb483eb3d189": "startet zuletzt neu", "9bca02be2b4d612a": "nicht verbunden", "2dcc418b6a13b83c": "erfordert manuelles Update", - "5c8ebc36f84dee7a": "erfordert eine neuere Desktop-App", + "f13e08bd3614112e": "T3 Code auf diesem Rechner aktualisieren", + "3c3348c36a2695af": "Update-Kanal auf diesem Rechner ändern", "fa8faa732a2688ef": "im Kanal {channel}", "9b961309baafa09d": "keine Berechtigung", "9bafb2622c22d145": "wird bereits aktualisiert", @@ -12779,5 +12792,24 @@ "99d51127f573296b": "Weiteres Konto", "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", "99963c0142e17f00": "Für das neue {tracker}-Konto.", - "6d8e4ebc889bace9": "Konto hinzufügen" + "6d8e4ebc889bace9": "Konto hinzufügen", + "8a883c4fbc127b68": "Auto-Merge für den Stack wird aktiviert...", + "5fb2a26ae31e8983": "Auto-Merge für den Stack konnte nicht aktiviert werden", + "986d0dcbf4dd0098": "Auto-Merge für den Stack aktiviert", + "f3ed1f63c8a3eef2": "{host} mergt den Stack bis #{number}, sobald die Anforderungen erfüllt sind.", + "bd536a0a1754f6cb": "Auto-Merge für den Stack konnte nicht abgebrochen werden", + "bb90ac3b2f3a72d5": "Der Host hat das Abbrechen des Auto-Merge abgelehnt. Aktualisiere und versuche es erneut.", + "9c28753c777c37b7": "{count, plural, one {Auto-Merge für {count} {term, select, mr {Merge Request} cr {Änderungsanfrage} other {Pull Request}}?} other {Auto-Merge für {count} {term, select, mr {Merge Requests} cr {Änderungsanfragen} other {Pull Requests}}?}}", + "a86b49982e18784d": "#{number} und die darunterliegenden nicht gemergten Ebenen per {method} in {base} mergen, sobald jede davon die Anforderungen auf {host} erfüllt. Das kann sofort passieren.", + "b1afda5c964deee4": [ + "Auto-Merge für Stack (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Auto-Merge für Stack abbrechen", + "012c67c7f1a99e33": "Auto-Merge für Stack" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 3ee3c357e42b6..68fbb078975b4 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Done", "d4d89c139de812a8": "Failed", "c1e03a860c856245": "Stopped", - "f1d27d127ab27ac6": "Starting", + "7e5abc299ead1d09": "Loading {provider} plugins", + "21872f69ccbc711d": "Starting {provider} MCP servers", + "fedaa29ff8815a77": "Loading {provider} hooks", + "57025ae4de5beb57": "Loading {provider} rules and skills", + "4729a188600f1501": "Connecting to {provider}", "8c8977097681630f": "Starting {provider}", + "f1d27d127ab27ac6": "Starting", "86d60d42f6cb4a40": "Idle", "0e8eab930d79d8b4": "Waiting", "54002bf654ddbab1": "Completed", @@ -3232,7 +3237,8 @@ "49e3cf16b3ac3e5f": "Access", "9699d255b374e215": "What it may do", "86f5769278f5fa4d": "Beyond read only, it can start, message and stop threads, and none of them can run with more than the mode you pick.", - "693a1983e099523a": "Connecting to this backend.", + "4f3982f640dfed5b": "This link adds a backend to this browser. Continue only if you trust it.", + "41b32a424841adb7": "This pairing link has an invalid backend host.", "ec2a82b05e616aa0": "This pairing link is missing its backend host or token.", "630d4f04309bc19a": "Authentication failed.", "63bc32e8544f4de1": "This environment expects a trusted pairing credential before the app can connect.", @@ -3246,11 +3252,13 @@ "55c59743f7fdd7fa": "Paste a one-time token or pairing secret", "ca6a0c94398d763d": "Pairing...", "989f56b8297dd684": "This one-time pairing token was already submitted. Request a new pairing link.", + "693a1983e099523a": "Connecting to this backend.", "db3dcafc90d10405": "{environment} is saved in this browser.", "47d4ab320c4c394c": "The environment is saved in this browser.", "d235c6bfa25870a4": "{error} If the backend accepted this one-time token, request a new pairing link before retrying.", "00c1dcaef4762f18": "Backend paired", "aac4a30e5912c01c": "Pairing failed", + "c142c3f3bed15f8d": "Add this backend?", "dbb27f4ee8ecfa8e": "Pairing backend", "8049e9ba2e8b4867": "Pairing token", "0528294df7656322": [ @@ -3267,6 +3275,7 @@ } ], "ff5f1c260e87ecde": "Verify the backend is reachable from this browser, supports CORS for hosted clients, and is served over HTTPS when opening this page from HTTPS.", + "984c25ffcae69300": "Add backend", "08570ee0982df89d": "Pairing...", "3bbae7c96b6cbfc3": "Open app", "49cc06e79f21f85a": "{seconds}s", @@ -3312,13 +3321,9 @@ "b90e87f4b7125237": "Details", "16dc67f5429d8bae": "Background work", "2188eee8f81b0f51": "Open subagent", - "3b03fc47eba632b4": "{count, plural, one {{formattedCount} changed file} other {{formattedCount} changed files}}", "ec9e0be8ec693302": "Collapse all folders", "b791dd86f7991cc0": "Expand all folders", - "afaf1bc8535e0adf": "Open diff", - "d31b3c7be099ca82": "{count, plural, one {{formattedCount} more file in the full diff} other {{formattedCount} more files in the full diff}}", "55b936e3014e16c8": "Open diff", - "452dc9eaa945693b": "Open the full diff", "28bb7ce40dfd349a": "Terminal output can't be added to a question answer.", "801cb8edea94b8f6": "Answer or dismiss the question first, then add it to chat.", "aa5507f20d94d5a9": "Update this server to send files with question answers", @@ -4400,7 +4405,6 @@ "991cc9fb37606c91": "(empty response)", "36e4b8d2db087296": "Fork from this response", "c92a0bab54261695": "Reply to this response", - "405a3e88ee6e62b3": "This turn's changes in this repository cannot be listed.", "f6958f38dc87c712": "Fork from this response", "72f8e14b1246d224": "Reply to this response", "01d7728e893c281d": "Jump to message: {text}", @@ -6842,6 +6846,8 @@ "45674081908ac8aa": "Checkout command copied", "d2970574ef7860d0": "Copy {term, select, mr {merge request} cr {change request} other {pull request}} branch", "45c92416a82cf22c": "Branch name copied", + "43a18c0bc37988f4": "New commits were pushed. A merge or review still applies to {sha}.", + "c930a7ffa49054f0": "Load new commits", "63e533a9db74e8dc": "Checks", "4f7ca990d538a8bc": "Comments unavailable", "95601ce075194611": "{count, plural, one {{formatted} comment} other {{formatted} comments}}", @@ -7561,6 +7567,11 @@ "03338c6aec8edacd": "Set how wide messages and the composer can grow on large screens.", "92785adb251da88c": "Reset chat width to default", "4d457bcce0c0e272": "Chat width", + "7d7f65967cc821e3": "HTML preview width", + "70ce0af7f78d5957": "Let HTML previews in a chat grow wider than its messages, which stay centered.", + "f2b119bf02ae2558": "Reset HTML preview width to default", + "6287212fed0deec6": "Match chat", + "dc8e85ea0364649c": "Match chat (default)", "81f3a196537bbee0": "Comfortable (default)", "e79e5388f669495f": "Show reasoning effort in the composer as its name, such as High, or as bars.", "7f0365c7e4e8bcbf": "Reset effort display to default", @@ -11828,6 +11839,7 @@ "9cf8308531b4ff31": "transparent transparency solid menus dialogs composer", "d8d6cfd630cff22d": "red green blue orange additions deletions changes counts palette colorblind", "717e49895cfee1c7": "wide full width column layout messages composer monitor", + "9d5c7430a7ff76cf": "wide full width inline page render chart dashboard artifact centered", "88365077fd80787b": "customize show hide panel card environment editor scripts branch pull request git changes servers automations lineage usage limits 5 hour weekly quota tokens context window", "d561f74efa5f3920": "reasoning effort thinking bars graph word label level composer", "6113c17109ee0d57": "latex tex katex equations formulas markdown", @@ -12145,7 +12157,8 @@ "f938bb483eb3d189": "restarts last", "9bca02be2b4d612a": "not connected", "2dcc418b6a13b83c": "needs a manual update", - "5c8ebc36f84dee7a": "needs a newer desktop app", + "f13e08bd3614112e": "update T3 Code on that machine", + "3c3348c36a2695af": "change the update track on that machine", "fa8faa732a2688ef": "on the {channel} channel", "9b961309baafa09d": "no permission", "9bafb2622c22d145": "already updating", @@ -12788,5 +12801,24 @@ "99d51127f573296b": "Another account", "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", "99963c0142e17f00": "For the new {tracker} account.", - "6d8e4ebc889bace9": "Add account" + "6d8e4ebc889bace9": "Add account", + "8a883c4fbc127b68": "Enabling stack auto-merge...", + "5fb2a26ae31e8983": "Could not enable stack auto-merge", + "986d0dcbf4dd0098": "Stack auto-merge enabled", + "f3ed1f63c8a3eef2": "{host} merges the stack through #{number} once its requirements are met.", + "bd536a0a1754f6cb": "Could not cancel stack auto-merge", + "bb90ac3b2f3a72d5": "The host refused to cancel auto-merge. Refresh and try again.", + "9c28753c777c37b7": "{count, plural, one {Auto-merge {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Auto-merge {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + "a86b49982e18784d": "Merge #{number} and its unmerged layers below into {base} using {method} once every one of them meets the requirements on {host}. This may happen immediately.", + "b1afda5c964deee4": [ + "Auto-merge stack (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancel stack auto-merge", + "012c67c7f1a99e33": "Auto-merge stack" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 83fdd0553e4ea..1fe507c25edb4 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminado", "d4d89c139de812a8": "Falló", "c1e03a860c856245": "Detenido", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Cargando plugins de {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP de {provider}", + "fedaa29ff8815a77": "Cargando hooks de {provider}", + "57025ae4de5beb57": "Cargando reglas y skills de {provider}", + "4729a188600f1501": "Conectando con {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Inactivo", "0e8eab930d79d8b4": "Esperando", "54002bf654ddbab1": "Completado", @@ -3232,7 +3237,8 @@ "49e3cf16b3ac3e5f": "Acceso", "9699d255b374e215": "Lo que puede hacer", "86f5769278f5fa4d": "Además de leer, puede iniciar, enviar mensajes a y detener hilos, y ninguno puede ejecutarse con más permisos que el modo que elijas.", - "693a1983e099523a": "Conectando con este backend.", + "4f3982f640dfed5b": "Este enlace añade un backend a este navegador. Continúa solo si confías en él.", + "41b32a424841adb7": "Este enlace de emparejamiento tiene un host de backend no válido.", "ec2a82b05e616aa0": "A este enlace de emparejamiento le falta el host del backend o el token.", "630d4f04309bc19a": "Falló la autenticación.", "63bc32e8544f4de1": "Este entorno espera una credencial de emparejamiento de confianza antes de que la app pueda conectarse.", @@ -3246,11 +3252,13 @@ "55c59743f7fdd7fa": "Pega un token de un solo uso o un secreto de emparejamiento", "ca6a0c94398d763d": "Emparejando...", "989f56b8297dd684": "Este token de emparejamiento de un solo uso ya se envió. Solicita un enlace de emparejamiento nuevo.", + "693a1983e099523a": "Conectando con este backend.", "db3dcafc90d10405": "{environment} está guardado en este navegador.", "47d4ab320c4c394c": "El entorno está guardado en este navegador.", "d235c6bfa25870a4": "{error} Si el backend aceptó este token de un solo uso, solicita un enlace de emparejamiento nuevo antes de reintentarlo.", "00c1dcaef4762f18": "Backend emparejado", "aac4a30e5912c01c": "Falló el emparejamiento", + "c142c3f3bed15f8d": "¿Añadir este backend?", "dbb27f4ee8ecfa8e": "Backend de emparejamiento", "8049e9ba2e8b4867": "Token de emparejamiento", "0528294df7656322": [ @@ -3267,6 +3275,7 @@ } ], "ff5f1c260e87ecde": "Comprueba que se puede acceder al backend desde este navegador, que admite CORS para clientes alojados y que se sirve por HTTPS cuando abres esta página desde HTTPS.", + "984c25ffcae69300": "Añadir backend", "08570ee0982df89d": "Emparejando...", "3bbae7c96b6cbfc3": "Abrir app", "49cc06e79f21f85a": "{seconds} s", @@ -3312,13 +3321,9 @@ "b90e87f4b7125237": "Detalles", "16dc67f5429d8bae": "Trabajo en segundo plano", "2188eee8f81b0f51": "Abrir subagente", - "3b03fc47eba632b4": "{count, plural, one {{formattedCount} archivo cambiado} other {{formattedCount} archivos cambiados}}", "ec9e0be8ec693302": "Contraer todas las carpetas", "b791dd86f7991cc0": "Expandir todas las carpetas", - "afaf1bc8535e0adf": "Abrir diff", - "d31b3c7be099ca82": "{count, plural, one {{formattedCount} archivo más en el diff completo} other {{formattedCount} archivos más en el diff completo}}", "55b936e3014e16c8": "Abrir diff", - "452dc9eaa945693b": "Abrir el diff completo", "28bb7ce40dfd349a": "La salida de la terminal no se puede añadir a la respuesta de una pregunta.", "801cb8edea94b8f6": "Responde o descarta primero la pregunta y luego añádelo al chat.", "aa5507f20d94d5a9": "Actualiza este servidor para enviar archivos con las respuestas a preguntas", @@ -4398,7 +4403,6 @@ "991cc9fb37606c91": "(respuesta vacía)", "36e4b8d2db087296": "Bifurcar desde esta respuesta", "c92a0bab54261695": "Responder a esta respuesta", - "405a3e88ee6e62b3": "No se pueden listar los cambios de este turno en este repositorio.", "f6958f38dc87c712": "Bifurcar desde esta respuesta", "72f8e14b1246d224": "Responder a esta respuesta", "01d7728e893c281d": "Ir al mensaje: {text}", @@ -6835,6 +6839,8 @@ "45674081908ac8aa": "Comando de checkout copiado", "d2970574ef7860d0": "Copiar la rama de la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}", "45c92416a82cf22c": "Nombre de la rama copiado", + "43a18c0bc37988f4": "Se enviaron nuevos commits. Una fusión o revisión sigue aplicándose a {sha}.", + "c930a7ffa49054f0": "Cargar nuevos commits", "63e533a9db74e8dc": "Comprobaciones", "4f7ca990d538a8bc": "Comentarios no disponibles", "95601ce075194611": "{count, plural, one {{formatted} comentario} other {{formatted} comentarios}}", @@ -7554,6 +7560,11 @@ "03338c6aec8edacd": "Define cuánto pueden crecer los mensajes y el cuadro de mensaje en pantallas grandes.", "92785adb251da88c": "Restablecer el ancho del chat al valor predeterminado", "4d457bcce0c0e272": "Ancho del chat", + "7d7f65967cc821e3": "Ancho de la vista previa HTML", + "70ce0af7f78d5957": "Permite que las vistas previas HTML de un chat sean más anchas que sus mensajes, que siguen centrados.", + "f2b119bf02ae2558": "Restablecer el ancho de la vista previa HTML al valor predeterminado", + "6287212fed0deec6": "Igual que el chat", + "dc8e85ea0364649c": "Igual que el chat (predeterminado)", "81f3a196537bbee0": "Cómodo (predeterminado)", "e79e5388f669495f": "Muestra el esfuerzo de razonamiento en el cuadro de mensaje por su nombre, como Alto, o con barras.", "7f0365c7e4e8bcbf": "Restablecer la visualización del esfuerzo al valor predeterminado", @@ -11813,6 +11824,7 @@ "9cf8308531b4ff31": "transparente transparencia sólido menús diálogos cuadro mensaje compositor", "d8d6cfd630cff22d": "rojo verde azul naranja adiciones eliminaciones cambios recuentos paleta daltonismo", "717e49895cfee1c7": "ancho ancho completo columna diseño mensajes cuadro mensaje compositor monitor", + "9d5c7430a7ff76cf": "ancho ancho completo en línea página renderizar gráfico panel artefacto centrado", "88365077fd80787b": "personalizar mostrar ocultar panel tarjeta entorno editor scripts rama pull request git cambios servidores automatizaciones linaje uso límites 5 horas semanal cuota tokens ventana de contexto", "d561f74efa5f3920": "esfuerzo de razonamiento pensamiento barras gráfico palabra etiqueta nivel cuadro mensaje compositor", "6113c17109ee0d57": "latex tex katex ecuaciones fórmulas markdown", @@ -12130,7 +12142,8 @@ "f938bb483eb3d189": "se reinicia el último", "9bca02be2b4d612a": "sin conexión", "2dcc418b6a13b83c": "requiere una actualización manual", - "5c8ebc36f84dee7a": "requiere una app de escritorio más reciente", + "f13e08bd3614112e": "actualiza T3 Code en ese equipo", + "3c3348c36a2695af": "cambia el canal de actualizaciones en ese equipo", "fa8faa732a2688ef": "en el canal {channel}", "9b961309baafa09d": "sin permiso", "9bafb2622c22d145": "ya se está actualizando", @@ -12774,5 +12787,24 @@ "99d51127f573296b": "Otra cuenta", "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", - "6d8e4ebc889bace9": "Añadir cuenta" + "6d8e4ebc889bace9": "Añadir cuenta", + "8a883c4fbc127b68": "Activando la fusión automática de la pila...", + "5fb2a26ae31e8983": "No se pudo activar la fusión automática de la pila", + "986d0dcbf4dd0098": "Fusión automática de la pila activada", + "f3ed1f63c8a3eef2": "{host} fusionará la pila hasta #{number} cuando se cumplan sus requisitos.", + "bd536a0a1754f6cb": "No se pudo cancelar la fusión automática de la pila", + "bb90ac3b2f3a72d5": "El host rechazó cancelar la fusión automática. Actualiza e inténtalo de nuevo.", + "9c28753c777c37b7": "{count, plural, one {¿Fusionar automáticamente {count} {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}?} other {¿Fusionar automáticamente {count} {term, select, mr {merge requests} cr {solicitudes de cambios} other {pull requests}}?}}", + "a86b49982e18784d": "Fusiona #{number} y sus capas sin fusionar de debajo en {base} mediante {method} cuando todas cumplan los requisitos de {host}. Puede ocurrir de inmediato.", + "b1afda5c964deee4": [ + "Fusión automática de la pila (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancelar la fusión automática de la pila", + "012c67c7f1a99e33": "Fusión automática de la pila" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 462e67d2053d3..41abb65fa60b8 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminé", "d4d89c139de812a8": "Échec", "c1e03a860c856245": "Arrêté", - "f1d27d127ab27ac6": "Démarrage", + "7e5abc299ead1d09": "Chargement des plugins de {provider}", + "21872f69ccbc711d": "Démarrage des serveurs MCP de {provider}", + "fedaa29ff8815a77": "Chargement des hooks de {provider}", + "57025ae4de5beb57": "Chargement des règles et des skills de {provider}", + "4729a188600f1501": "Connexion à {provider}", "8c8977097681630f": "Démarrage de {provider}", + "f1d27d127ab27ac6": "Démarrage", "86d60d42f6cb4a40": "Inactif", "0e8eab930d79d8b4": "En attente", "54002bf654ddbab1": "Terminé", @@ -3232,7 +3237,8 @@ "49e3cf16b3ac3e5f": "Accès", "9699d255b374e215": "Ce qu’il peut faire", "86f5769278f5fa4d": "Au-delà de la lecture seule, il peut démarrer, arrêter des fils et leur envoyer des messages, et aucun ne peut s’exécuter avec plus que le mode que vous choisissez.", - "693a1983e099523a": "Connexion à ce backend.", + "4f3982f640dfed5b": "Ce lien ajoute un backend à ce navigateur. Ne continuez que si vous lui faites confiance.", + "41b32a424841adb7": "L’hôte du backend de ce lien d’appairage n’est pas valide.", "ec2a82b05e616aa0": "Il manque l’hôte du backend ou le jeton dans ce lien d’appairage.", "630d4f04309bc19a": "Échec de l’authentification.", "63bc32e8544f4de1": "Cet environnement attend un identifiant d’appairage de confiance avant que l’app puisse se connecter.", @@ -3246,11 +3252,13 @@ "55c59743f7fdd7fa": "Collez un jeton à usage unique ou un secret d’appairage", "ca6a0c94398d763d": "Appairage...", "989f56b8297dd684": "Ce jeton d’appairage à usage unique a déjà été envoyé. Demandez un nouveau lien d’appairage.", + "693a1983e099523a": "Connexion à ce backend.", "db3dcafc90d10405": "{environment} est enregistré dans ce navigateur.", "47d4ab320c4c394c": "L’environnement est enregistré dans ce navigateur.", "d235c6bfa25870a4": "{error} Si le backend a accepté ce jeton à usage unique, demandez un nouveau lien d’appairage avant de réessayer.", "00c1dcaef4762f18": "Backend appairé", "aac4a30e5912c01c": "Échec de l’appairage", + "c142c3f3bed15f8d": "Ajouter ce backend ?", "dbb27f4ee8ecfa8e": "Backend d’appairage", "8049e9ba2e8b4867": "Jeton d’appairage", "0528294df7656322": [ @@ -3267,6 +3275,7 @@ } ], "ff5f1c260e87ecde": "Vérifiez que le backend est joignable depuis ce navigateur, qu’il prend en charge CORS pour les clients hébergés et qu’il est servi en HTTPS si cette page est ouverte en HTTPS.", + "984c25ffcae69300": "Ajouter le backend", "08570ee0982df89d": "Appairage...", "3bbae7c96b6cbfc3": "Ouvrir l’app", "49cc06e79f21f85a": "{seconds} s", @@ -3312,13 +3321,9 @@ "b90e87f4b7125237": "Détails", "16dc67f5429d8bae": "Travail en arrière-plan", "2188eee8f81b0f51": "Ouvrir le sous-agent", - "3b03fc47eba632b4": "{count, plural, one {{formattedCount} fichier modifié} other {{formattedCount} fichiers modifiés}}", "ec9e0be8ec693302": "Réduire tous les dossiers", "b791dd86f7991cc0": "Développer tous les dossiers", - "afaf1bc8535e0adf": "Ouvrir le diff", - "d31b3c7be099ca82": "{count, plural, one {{formattedCount} autre fichier dans le diff complet} other {{formattedCount} autres fichiers dans le diff complet}}", "55b936e3014e16c8": "Ouvrir le diff", - "452dc9eaa945693b": "Ouvrir le diff complet", "28bb7ce40dfd349a": "La sortie du terminal ne peut pas être ajoutée à la réponse à une question.", "801cb8edea94b8f6": "Répondez à la question ou ignorez-la d’abord, puis ajoutez-la à la discussion.", "aa5507f20d94d5a9": "Mettez à jour ce serveur pour envoyer des fichiers avec les réponses aux questions", @@ -4399,7 +4404,6 @@ "991cc9fb37606c91": "(réponse vide)", "36e4b8d2db087296": "Créer un fork depuis cette réponse", "c92a0bab54261695": "Répondre à cette réponse", - "405a3e88ee6e62b3": "Impossible de lister les modifications de ce tour dans ce dépôt.", "f6958f38dc87c712": "Créer un fork depuis cette réponse", "72f8e14b1246d224": "Répondre à cette réponse", "01d7728e893c281d": "Aller au message : {text}", @@ -6836,6 +6840,8 @@ "45674081908ac8aa": "Commande de checkout copiée", "d2970574ef7860d0": "Copier la branche de la {term, select, mr {merge request} cr {demande de modification} other {pull request}}", "45c92416a82cf22c": "Nom de la branche copié", + "43a18c0bc37988f4": "De nouveaux commits ont été poussés. Une fusion ou une revue s’applique toujours à {sha}.", + "c930a7ffa49054f0": "Charger les nouveaux commits", "63e533a9db74e8dc": "Vérifications", "4f7ca990d538a8bc": "Commentaires indisponibles", "95601ce075194611": "{count, plural, one {{formatted} commentaire} other {{formatted} commentaires}}", @@ -7555,6 +7561,11 @@ "03338c6aec8edacd": "Définissez la largeur maximale des messages et de la zone de saisie sur les grands écrans.", "92785adb251da88c": "Réinitialiser la largeur de la discussion à la valeur par défaut", "4d457bcce0c0e272": "Largeur de la discussion", + "7d7f65967cc821e3": "Largeur des aperçus HTML", + "70ce0af7f78d5957": "Permet aux aperçus HTML d’une discussion d’être plus larges que ses messages, qui restent centrés.", + "f2b119bf02ae2558": "Réinitialiser la largeur des aperçus HTML à la valeur par défaut", + "6287212fed0deec6": "Comme la discussion", + "dc8e85ea0364649c": "Comme la discussion (par défaut)", "81f3a196537bbee0": "Confortable (par défaut)", "e79e5388f669495f": "Afficher l’effort de raisonnement dans la zone de saisie par son nom, comme Élevé, ou sous forme de barres.", "7f0365c7e4e8bcbf": "Réinitialiser l’affichage de l’effort à la valeur par défaut", @@ -11818,6 +11829,7 @@ "9cf8308531b4ff31": "transparent transparence opaque menus boîtes de dialogue zone de saisie", "d8d6cfd630cff22d": "rouge vert bleu orange ajouts suppressions modifications compteurs palette daltonien", "717e49895cfee1c7": "large pleine largeur colonne mise en page messages zone de saisie écran", + "9d5c7430a7ff76cf": "large pleine largeur intégré page rendu graphique tableau de bord artefact centré", "88365077fd80787b": "personnaliser afficher masquer panneau carte environnement éditeur scripts branche pull request modifications git serveurs automatisations lignée utilisation limites 5 heures hebdomadaire quota jetons fenêtre de contexte", "d561f74efa5f3920": "effort de raisonnement réflexion barres graphique mot libellé niveau zone de saisie", "6113c17109ee0d57": "latex tex katex équations formules markdown", @@ -12135,7 +12147,8 @@ "f938bb483eb3d189": "redémarre en dernier", "9bca02be2b4d612a": "non connecté", "2dcc418b6a13b83c": "nécessite une mise à jour manuelle", - "5c8ebc36f84dee7a": "nécessite une version plus récente de l’app de bureau", + "f13e08bd3614112e": "mettez à jour T3 Code sur cette machine", + "3c3348c36a2695af": "changez le canal de mise à jour sur cette machine", "fa8faa732a2688ef": "sur le canal {channel}", "9b961309baafa09d": "pas d’autorisation", "9bafb2622c22d145": "déjà en cours de mise à jour", @@ -12779,5 +12792,24 @@ "99d51127f573296b": "Autre compte", "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", "99963c0142e17f00": "Pour le nouveau compte {tracker}.", - "6d8e4ebc889bace9": "Ajouter un compte" + "6d8e4ebc889bace9": "Ajouter un compte", + "8a883c4fbc127b68": "Activation de la fusion automatique de la pile...", + "5fb2a26ae31e8983": "Impossible d’activer la fusion automatique de la pile", + "986d0dcbf4dd0098": "Fusion automatique de la pile activée", + "f3ed1f63c8a3eef2": "{host} fusionnera la pile jusqu’à #{number} dès que ses conditions seront remplies.", + "bd536a0a1754f6cb": "Impossible d’annuler la fusion automatique de la pile", + "bb90ac3b2f3a72d5": "L’hôte a refusé d’annuler la fusion automatique. Actualisez et réessayez.", + "9c28753c777c37b7": "{count, plural, one {Fusionner automatiquement {count} {term, select, mr {merge request} cr {demande de modification} other {pull request}} ?} other {Fusionner automatiquement {count} {term, select, mr {merge requests} cr {demandes de modification} other {pull requests}} ?}}", + "a86b49982e18784d": "Fusionner #{number} et ses couches non fusionnées inférieures dans {base} avec {method} dès que chacune remplit les conditions de {host}. Cela peut se produire immédiatement.", + "b1afda5c964deee4": [ + "Fusion automatique de la pile (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Annuler la fusion automatique de la pile", + "012c67c7f1a99e33": "Fusion automatique de la pile" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 0e6d237df1668..3b380aad685ac 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完了", "d4d89c139de812a8": "失敗", "c1e03a860c856245": "停止", - "f1d27d127ab27ac6": "起動中", + "7e5abc299ead1d09": "{provider} のプラグインを読み込み中", + "21872f69ccbc711d": "{provider} の MCP サーバーを起動中", + "fedaa29ff8815a77": "{provider} のフックを読み込み中", + "57025ae4de5beb57": "{provider} のルールとスキルを読み込み中", + "4729a188600f1501": "{provider} に接続中", "8c8977097681630f": "{provider} を起動中", + "f1d27d127ab27ac6": "起動中", "86d60d42f6cb4a40": "アイドル", "0e8eab930d79d8b4": "待機中", "54002bf654ddbab1": "完了", @@ -3230,7 +3235,8 @@ "49e3cf16b3ac3e5f": "アクセス", "9699d255b374e215": "許可する操作", "86f5769278f5fa4d": "読み取り専用に加えて、スレッドの開始、メッセージ送信、停止ができます。どのスレッドも、選択したモードを超える権限では実行できません。", - "693a1983e099523a": "このバックエンドに接続しています。", + "4f3982f640dfed5b": "このリンクはこのブラウザにバックエンドを追加します。信頼できる場合のみ続行してください。", + "41b32a424841adb7": "このペアリングリンクのバックエンドホストが無効です。", "ec2a82b05e616aa0": "このペアリングリンクにはバックエンドのホストまたはトークンがありません。", "630d4f04309bc19a": "認証に失敗しました。", "63bc32e8544f4de1": "この環境では、アプリが接続する前に信頼されたペアリング資格情報が必要です。", @@ -3244,11 +3250,13 @@ "55c59743f7fdd7fa": "ワンタイムトークンまたはペアリングシークレットを貼り付け", "ca6a0c94398d763d": "ペアリングしています...", "989f56b8297dd684": "このワンタイムペアリングトークンはすでに送信されています。新しいペアリングリンクをリクエストしてください。", + "693a1983e099523a": "このバックエンドに接続しています。", "db3dcafc90d10405": "{environment} はこのブラウザーに保存されています。", "47d4ab320c4c394c": "環境はこのブラウザーに保存されています。", "d235c6bfa25870a4": "{error} バックエンドがこのワンタイムトークンを受け付けた場合は、再試行する前に新しいペアリングリンクをリクエストしてください。", "00c1dcaef4762f18": "バックエンドとペアリングしました", "aac4a30e5912c01c": "ペアリングに失敗しました", + "c142c3f3bed15f8d": "このバックエンドを追加しますか?", "dbb27f4ee8ecfa8e": "ペアリング先のバックエンド", "8049e9ba2e8b4867": "ペアリングトークン", "0528294df7656322": [ @@ -3265,6 +3273,7 @@ } ], "ff5f1c260e87ecde": "バックエンドがこのブラウザーから到達可能で、ホスト型クライアント向けに CORS をサポートしていること、また HTTPS のページから開く場合は HTTPS で提供されていることを確認してください。", + "984c25ffcae69300": "バックエンドを追加", "08570ee0982df89d": "ペアリングしています...", "3bbae7c96b6cbfc3": "アプリを開く", "49cc06e79f21f85a": "{seconds}秒", @@ -3310,13 +3319,9 @@ "b90e87f4b7125237": "詳細", "16dc67f5429d8bae": "バックグラウンドの作業", "2188eee8f81b0f51": "サブエージェントを開く", - "3b03fc47eba632b4": "{count, plural, other {{formattedCount} 個の変更されたファイル}}", "ec9e0be8ec693302": "すべてのフォルダーを折りたたむ", "b791dd86f7991cc0": "すべてのフォルダーを展開", - "afaf1bc8535e0adf": "差分を開く", - "d31b3c7be099ca82": "{count, plural, other {完全な差分には他に {formattedCount} 個のファイルがあります}}", "55b936e3014e16c8": "差分を開く", - "452dc9eaa945693b": "完全な差分を開く", "28bb7ce40dfd349a": "質問への回答にターミナルの出力は追加できません。", "801cb8edea94b8f6": "先に質問に回答するか閉じてから、チャットに追加してください。", "aa5507f20d94d5a9": "質問への回答でファイルを送信するには、このサーバーを更新してください", @@ -4389,7 +4394,6 @@ "991cc9fb37606c91": "(空のレスポンス)", "36e4b8d2db087296": "この応答からフォーク", "c92a0bab54261695": "この応答に返信", - "405a3e88ee6e62b3": "このリポジトリでのこのターンの変更は一覧表示できません。", "f6958f38dc87c712": "この応答からフォーク", "72f8e14b1246d224": "この応答に返信", "01d7728e893c281d": "メッセージに移動: {text}", @@ -6805,6 +6809,8 @@ "45674081908ac8aa": "チェックアウトコマンドをコピーしました", "d2970574ef7860d0": "{term, select, mr {マージリクエストのブランチをコピー} cr {変更リクエストのブランチをコピー} other {プルリクエストのブランチをコピー}}", "45c92416a82cf22c": "ブランチ名をコピーしました", + "43a18c0bc37988f4": "新しいコミットがプッシュされました。マージやレビューは引き続き {sha} に適用されます。", + "c930a7ffa49054f0": "新しいコミットを読み込む", "63e533a9db74e8dc": "チェック", "4f7ca990d538a8bc": "コメントを利用できません", "95601ce075194611": "{count, plural, other {{formatted} 件のコメント}}", @@ -7520,6 +7526,11 @@ "03338c6aec8edacd": "大きな画面でメッセージと入力欄を広げられる幅を設定します。", "92785adb251da88c": "チャットの幅をデフォルトにリセット", "4d457bcce0c0e272": "チャットの幅", + "7d7f65967cc821e3": "HTML プレビューの幅", + "70ce0af7f78d5957": "チャット内の HTML プレビューをメッセージより広く表示します。メッセージは中央のままです。", + "f2b119bf02ae2558": "HTML プレビューの幅をデフォルトにリセット", + "6287212fed0deec6": "チャットに合わせる", + "dc8e85ea0364649c": "チャットに合わせる (デフォルト)", "81f3a196537bbee0": "標準 (デフォルト)", "e79e5388f669495f": "入力欄での推論レベルの表示を、名前 (High など) またはバーから選択します。", "7f0365c7e4e8bcbf": "推論レベルの表示をデフォルトにリセット", @@ -11769,6 +11780,7 @@ "9cf8308531b4ff31": "透明 透過 不透明 メニュー ダイアログ 入力欄 transparency", "d8d6cfd630cff22d": "赤 緑 青 オレンジ 追加 削除 変更 件数 パレット 色覚 colorblind", "717e49895cfee1c7": "幅 全幅 列 レイアウト メッセージ 入力欄 モニター wide width", + "9d5c7430a7ff76cf": "幅 全幅 インライン ページ レンダリング グラフ ダッシュボード アーティファクト 中央 wide width", "88365077fd80787b": "カスタマイズ 表示 非表示 パネル カード 環境 エディター スクリプト ブランチ プルリクエスト Git 変更 サーバー オートメーション 系譜 使用量 上限 5 時間 週間 クォータ トークン コンテキストウィンドウ panel card", "d561f74efa5f3920": "推論レベル 思考 バー グラフ 単語 ラベル レベル 入力欄 reasoning effort", "6113c17109ee0d57": "LaTeX TeX KaTeX 数式 方程式 Markdown latex math", @@ -12086,7 +12098,8 @@ "f938bb483eb3d189": "最後に再起動", "9bca02be2b4d612a": "未接続", "2dcc418b6a13b83c": "手動での更新が必要", - "5c8ebc36f84dee7a": "新しいデスクトップアプリが必要", + "f13e08bd3614112e": "そのマシンで T3 Code を更新してください", + "3c3348c36a2695af": "そのマシンで更新トラックを変更してください", "fa8faa732a2688ef": "{channel} チャネル", "9b961309baafa09d": "権限なし", "9bafb2622c22d145": "すでに更新中", @@ -12720,5 +12733,24 @@ "99d51127f573296b": "別のアカウント", "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", "99963c0142e17f00": "新しい {tracker} アカウント用です。", - "6d8e4ebc889bace9": "アカウントを追加" + "6d8e4ebc889bace9": "アカウントを追加", + "8a883c4fbc127b68": "スタックの自動マージを有効にしています...", + "5fb2a26ae31e8983": "スタックの自動マージを有効にできませんでした", + "986d0dcbf4dd0098": "スタックの自動マージを有効にしました", + "f3ed1f63c8a3eef2": "要件が満たされると、{host} が #{number} までのスタックをマージします。", + "bd536a0a1754f6cb": "スタックの自動マージをキャンセルできませんでした", + "bb90ac3b2f3a72d5": "ホストが自動マージのキャンセルを拒否しました。更新してもう一度お試しください。", + "9c28753c777c37b7": "{count, plural, other {{term, select, mr {マージリクエスト {count} 件を自動マージしますか?} cr {変更リクエスト {count} 件を自動マージしますか?} other {プルリクエスト {count} 件を自動マージしますか?}}}}", + "a86b49982e18784d": "#{number} と、その下の未マージのレイヤーがすべて {host} の要件を満たしたら、{method} で {base} にマージします。すぐにマージされる場合があります。", + "b1afda5c964deee4": [ + "スタックを自動マージ (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "スタックの自動マージをキャンセル", + "012c67c7f1a99e33": "スタックを自動マージ" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 2e98c679624c3..1ba32819b6388 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "완료", "d4d89c139de812a8": "실패", "c1e03a860c856245": "중지됨", - "f1d27d127ab27ac6": "시작 중", + "7e5abc299ead1d09": "{provider} 플러그인 불러오는 중", + "21872f69ccbc711d": "{provider} MCP 서버 시작 중", + "fedaa29ff8815a77": "{provider} 훅 불러오는 중", + "57025ae4de5beb57": "{provider} 규칙 및 스킬 불러오는 중", + "4729a188600f1501": "{provider}에 연결 중", "8c8977097681630f": "{provider} 시작 중", + "f1d27d127ab27ac6": "시작 중", "86d60d42f6cb4a40": "유휴", "0e8eab930d79d8b4": "대기 중", "54002bf654ddbab1": "완료됨", @@ -3231,7 +3236,8 @@ "49e3cf16b3ac3e5f": "액세스", "9699d255b374e215": "허용할 작업", "86f5769278f5fa4d": "읽기 전용 외에 스레드를 시작하고, 메시지를 보내고, 중지할 수 있으며, 어떤 스레드도 선택한 모드보다 높은 권한으로 실행할 수 없습니다.", - "693a1983e099523a": "이 백엔드에 연결하는 중입니다.", + "4f3982f640dfed5b": "이 링크는 이 브라우저에 백엔드를 추가합니다. 신뢰하는 경우에만 계속하세요.", + "41b32a424841adb7": "이 페어링 링크의 백엔드 호스트가 올바르지 않습니다.", "ec2a82b05e616aa0": "이 페어링 링크에 백엔드 호스트 또는 토큰이 없습니다.", "630d4f04309bc19a": "인증에 실패했습니다.", "63bc32e8544f4de1": "앱이 연결하려면 이 환경에 신뢰할 수 있는 페어링 자격 증명이 필요합니다.", @@ -3245,11 +3251,13 @@ "55c59743f7fdd7fa": "일회용 토큰 또는 페어링 시크릿 붙여 넣기", "ca6a0c94398d763d": "페어링하는 중...", "989f56b8297dd684": "이 일회용 페어링 토큰은 이미 제출되었습니다. 새 페어링 링크를 요청하세요.", + "693a1983e099523a": "이 백엔드에 연결하는 중입니다.", "db3dcafc90d10405": "{environment}이(가) 이 브라우저에 저장되었습니다.", "47d4ab320c4c394c": "환경이 이 브라우저에 저장되었습니다.", "d235c6bfa25870a4": "{error} 백엔드가 이 일회용 토큰을 수락했다면 다시 시도하기 전에 새 페어링 링크를 요청하세요.", "00c1dcaef4762f18": "백엔드 페어링됨", "aac4a30e5912c01c": "페어링 실패", + "c142c3f3bed15f8d": "이 백엔드를 추가할까요?", "dbb27f4ee8ecfa8e": "백엔드 페어링 중", "8049e9ba2e8b4867": "페어링 토큰", "0528294df7656322": [ @@ -3266,6 +3274,7 @@ } ], "ff5f1c260e87ecde": "이 브라우저에서 백엔드에 접근할 수 있는지, 호스팅된 클라이언트용 CORS를 지원하는지, HTTPS 페이지에서 열 때 HTTPS로 제공되는지 확인하세요.", + "984c25ffcae69300": "백엔드 추가", "08570ee0982df89d": "페어링하는 중...", "3bbae7c96b6cbfc3": "앱 열기", "49cc06e79f21f85a": "{seconds}초", @@ -3311,13 +3320,9 @@ "b90e87f4b7125237": "세부 정보", "16dc67f5429d8bae": "백그라운드 작업", "2188eee8f81b0f51": "서브에이전트 열기", - "3b03fc47eba632b4": "{count, plural, other {변경된 파일 {formattedCount}개}}", "ec9e0be8ec693302": "모든 폴더 접기", "b791dd86f7991cc0": "모든 폴더 펼치기", - "afaf1bc8535e0adf": "변경 사항 열기", - "d31b3c7be099ca82": "{count, plural, other {전체 변경 사항에 파일 {formattedCount}개 더 있음}}", "55b936e3014e16c8": "변경 사항 열기", - "452dc9eaa945693b": "전체 변경 사항 열기", "28bb7ce40dfd349a": "질문 답변에는 터미널 출력을 추가할 수 없습니다.", "801cb8edea94b8f6": "먼저 질문에 답하거나 닫은 후 채팅에 추가하세요.", "aa5507f20d94d5a9": "질문 답변과 함께 파일을 보내려면 이 서버를 업데이트하세요", @@ -4386,7 +4391,6 @@ "991cc9fb37606c91": "(빈 응답)", "36e4b8d2db087296": "이 응답에서 포크", "c92a0bab54261695": "이 응답에 답장", - "405a3e88ee6e62b3": "이 저장소에서 이 턴의 변경 사항을 나열할 수 없습니다.", "f6958f38dc87c712": "이 응답에서 포크", "72f8e14b1246d224": "이 응답에 답장", "01d7728e893c281d": "메시지로 이동: {text}", @@ -6809,6 +6813,8 @@ "45674081908ac8aa": "체크아웃 명령 복사됨", "d2970574ef7860d0": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} 브랜치 복사", "45c92416a82cf22c": "브랜치 이름 복사됨", + "43a18c0bc37988f4": "새 커밋이 푸시되었습니다. 병합이나 리뷰는 여전히 {sha}에 적용됩니다.", + "c930a7ffa49054f0": "새 커밋 불러오기", "63e533a9db74e8dc": "검사", "4f7ca990d538a8bc": "댓글을 사용할 수 없음", "95601ce075194611": "{count, plural, other {댓글 {formatted}개}}", @@ -7521,6 +7527,11 @@ "03338c6aec8edacd": "큰 화면에서 메시지와 입력창이 넓어질 수 있는 폭을 설정합니다.", "92785adb251da88c": "채팅 너비 기본값으로 재설정", "4d457bcce0c0e272": "채팅 너비", + "7d7f65967cc821e3": "HTML 미리 보기 너비", + "70ce0af7f78d5957": "채팅의 HTML 미리 보기가 메시지보다 넓어질 수 있게 합니다. 메시지는 가운데에 유지됩니다.", + "f2b119bf02ae2558": "HTML 미리 보기 너비 기본값으로 재설정", + "6287212fed0deec6": "채팅에 맞춤", + "dc8e85ea0364649c": "채팅에 맞춤(기본값)", "81f3a196537bbee0": "보통(기본값)", "e79e5388f669495f": "입력창에서 추론 수준을 High 같은 이름 또는 막대로 표시합니다.", "7f0365c7e4e8bcbf": "추론 수준 표시 기본값으로 재설정", @@ -11765,6 +11776,7 @@ "9cf8308531b4ff31": "투명 투명도 불투명 메뉴 대화 상자 입력창", "d8d6cfd630cff22d": "빨간색 녹색 파란색 주황색 추가 삭제 변경 개수 팔레트 색맹", "717e49895cfee1c7": "넓게 전체 너비 열 레이아웃 메시지 입력창 모니터", + "9d5c7430a7ff76cf": "넓게 전체 너비 인라인 페이지 렌더링 차트 대시보드 아티팩트 가운데", "88365077fd80787b": "사용자 지정 표시 숨기기 패널 카드 환경 편집기 스크립트 브랜치 풀 리퀘스트 git 변경 사항 서버 자동화 계보 사용량 한도 5시간 주간 할당량 토큰 컨텍스트 창", "d561f74efa5f3920": "추론 수준 생각 막대 그래프 단어 레이블 수준 입력창", "6113c17109ee0d57": "latex tex katex 수식 공식 마크다운", @@ -12082,7 +12094,8 @@ "f938bb483eb3d189": "마지막에 다시 시작", "9bca02be2b4d612a": "연결되지 않음", "2dcc418b6a13b83c": "수동 업데이트 필요", - "5c8ebc36f84dee7a": "최신 데스크톱 앱 필요", + "f13e08bd3614112e": "해당 기기에서 T3 Code를 업데이트하세요", + "3c3348c36a2695af": "해당 기기에서 업데이트 트랙을 변경하세요", "fa8faa732a2688ef": "{channel} 채널", "9b961309baafa09d": "권한 없음", "9bafb2622c22d145": "이미 업데이트 중", @@ -12716,5 +12729,24 @@ "99d51127f573296b": "다른 계정", "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", "99963c0142e17f00": "새 {tracker} 계정용입니다.", - "6d8e4ebc889bace9": "계정 추가" + "6d8e4ebc889bace9": "계정 추가", + "8a883c4fbc127b68": "스택 자동 병합을 켜는 중...", + "5fb2a26ae31e8983": "스택 자동 병합을 켤 수 없습니다", + "986d0dcbf4dd0098": "스택 자동 병합을 켰습니다", + "f3ed1f63c8a3eef2": "요구 사항이 충족되면 {host}에서 #{number}까지 스택을 병합합니다.", + "bd536a0a1754f6cb": "스택 자동 병합을 취소할 수 없습니다", + "bb90ac3b2f3a72d5": "호스트가 자동 병합 취소를 거부했습니다. 새로 고친 후 다시 시도하세요.", + "9c28753c777c37b7": "{count, plural, other {{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} {count}개를 자동 병합할까요?}}", + "a86b49982e18784d": "#{number}와(과) 그 아래의 병합되지 않은 레이어가 모두 {host}의 요구 사항을 충족하면 {method}(으)로 {base}에 병합합니다. 바로 병합될 수도 있습니다.", + "b1afda5c964deee4": [ + "스택 자동 병합(", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "스택 자동 병합 취소", + "012c67c7f1a99e33": "스택 자동 병합" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index ebcd6d8586978..d2c5b87461830 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Concluído", "d4d89c139de812a8": "Falhou", "c1e03a860c856245": "Parado", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Carregando plugins do {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP do {provider}", + "fedaa29ff8815a77": "Carregando hooks do {provider}", + "57025ae4de5beb57": "Carregando regras e skills do {provider}", + "4729a188600f1501": "Conectando ao {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Ocioso", "0e8eab930d79d8b4": "Aguardando", "54002bf654ddbab1": "Concluído", @@ -3232,7 +3237,8 @@ "49e3cf16b3ac3e5f": "Acesso", "9699d255b374e215": "O que ele pode fazer", "86f5769278f5fa4d": "Além da leitura, ele pode iniciar, enviar mensagens e parar threads, e nenhuma delas pode rodar com mais do que o modo que você escolher.", - "693a1983e099523a": "Conectando a este backend.", + "4f3982f640dfed5b": "Este link adiciona um backend a este navegador. Continue somente se você confia nele.", + "41b32a424841adb7": "Este link de pareamento tem um host de backend inválido.", "ec2a82b05e616aa0": "Falta o host do backend ou o token neste link de pareamento.", "630d4f04309bc19a": "Falha na autenticação.", "63bc32e8544f4de1": "Este ambiente exige uma credencial de pareamento confiável antes que o app possa se conectar.", @@ -3246,11 +3252,13 @@ "55c59743f7fdd7fa": "Cole um token de uso único ou um segredo de pareamento", "ca6a0c94398d763d": "Pareando...", "989f56b8297dd684": "Este token de pareamento de uso único já foi enviado. Solicite um novo link de pareamento.", + "693a1983e099523a": "Conectando a este backend.", "db3dcafc90d10405": "{environment} está salvo neste navegador.", "47d4ab320c4c394c": "O ambiente está salvo neste navegador.", "d235c6bfa25870a4": "{error} Se o backend aceitou este token de uso único, solicite um novo link de pareamento antes de tentar novamente.", "00c1dcaef4762f18": "Backend pareado", "aac4a30e5912c01c": "Falha no pareamento", + "c142c3f3bed15f8d": "Adicionar este backend?", "dbb27f4ee8ecfa8e": "Pareando o backend", "8049e9ba2e8b4867": "Token de pareamento", "0528294df7656322": [ @@ -3267,6 +3275,7 @@ } ], "ff5f1c260e87ecde": "Verifique se o backend está acessível a partir deste navegador, se permite CORS para clientes hospedados e se é servido por HTTPS quando esta página é aberta via HTTPS.", + "984c25ffcae69300": "Adicionar backend", "08570ee0982df89d": "Pareando...", "3bbae7c96b6cbfc3": "Abrir app", "49cc06e79f21f85a": "{seconds}s", @@ -3312,13 +3321,9 @@ "b90e87f4b7125237": "Detalhes", "16dc67f5429d8bae": "Trabalho em segundo plano", "2188eee8f81b0f51": "Abrir subagente", - "3b03fc47eba632b4": "{count, plural, one {{formattedCount} arquivo alterado} other {{formattedCount} arquivos alterados}}", "ec9e0be8ec693302": "Recolher todas as pastas", "b791dd86f7991cc0": "Expandir todas as pastas", - "afaf1bc8535e0adf": "Abrir diff", - "d31b3c7be099ca82": "{count, plural, one {Mais {formattedCount} arquivo no diff completo} other {Mais {formattedCount} arquivos no diff completo}}", "55b936e3014e16c8": "Abrir diff", - "452dc9eaa945693b": "Abrir o diff completo", "28bb7ce40dfd349a": "A saída do terminal não pode ser adicionada à resposta de uma pergunta.", "801cb8edea94b8f6": "Responda ou dispense a pergunta primeiro e depois adicione ao chat.", "aa5507f20d94d5a9": "Atualize este servidor para enviar arquivos com respostas a perguntas", @@ -4398,7 +4403,6 @@ "991cc9fb37606c91": "(resposta vazia)", "36e4b8d2db087296": "Criar fork a partir desta resposta", "c92a0bab54261695": "Responder a esta resposta", - "405a3e88ee6e62b3": "Não é possível listar as alterações deste turno neste repositório.", "f6958f38dc87c712": "Criar fork a partir desta resposta", "72f8e14b1246d224": "Responder a esta resposta", "01d7728e893c281d": "Ir para a mensagem: {text}", @@ -6835,6 +6839,8 @@ "45674081908ac8aa": "Comando de checkout copiado", "d2970574ef7860d0": "Copiar o branch {term, select, mr {do merge request} cr {da solicitação de alteração} other {do pull request}}", "45c92416a82cf22c": "Nome do branch copiado", + "43a18c0bc37988f4": "Novos commits foram enviados. Um merge ou uma revisão ainda se aplica a {sha}.", + "c930a7ffa49054f0": "Carregar novos commits", "63e533a9db74e8dc": "Verificações", "4f7ca990d538a8bc": "Comentários indisponíveis", "95601ce075194611": "{count, plural, one {{formatted} comentário} other {{formatted} comentários}}", @@ -7554,6 +7560,11 @@ "03338c6aec8edacd": "Define até que largura as mensagens e o editor de mensagens podem crescer em telas grandes.", "92785adb251da88c": "Redefinir a largura do chat para o padrão", "4d457bcce0c0e272": "Largura do chat", + "7d7f65967cc821e3": "Largura da pré-visualização HTML", + "70ce0af7f78d5957": "Permite que as pré-visualizações HTML de um chat fiquem mais largas que as mensagens, que continuam centralizadas.", + "f2b119bf02ae2558": "Redefinir a largura da pré-visualização HTML para o padrão", + "6287212fed0deec6": "Igual ao chat", + "dc8e85ea0364649c": "Igual ao chat (padrão)", "81f3a196537bbee0": "Confortável (padrão)", "e79e5388f669495f": "Mostra o esforço de raciocínio no editor de mensagens pelo nome, como Alto, ou como barras.", "7f0365c7e4e8bcbf": "Redefinir a exibição do esforço para o padrão", @@ -11818,6 +11829,7 @@ "9cf8308531b4ff31": "transparente transparência sólido menus caixas de diálogo editor de mensagens", "d8d6cfd630cff22d": "vermelho verde azul laranja adições exclusões alterações contagens paleta daltonismo", "717e49895cfee1c7": "largo largura total coluna layout mensagens editor de mensagens monitor", + "9d5c7430a7ff76cf": "largo largura total em linha página renderizar gráfico painel artefato centralizado", "88365077fd80787b": "personalizar mostrar ocultar painel cartão ambiente editor scripts branch pull request git alterações servidores automações linhagem uso limites 5 horas semanal cota tokens janela de contexto", "d561f74efa5f3920": "esforço de raciocínio pensamento barras gráfico palavra rótulo nível editor de mensagens", "6113c17109ee0d57": "latex tex katex equações fórmulas markdown", @@ -12135,7 +12147,8 @@ "f938bb483eb3d189": "reinicia por último", "9bca02be2b4d612a": "não conectado", "2dcc418b6a13b83c": "precisa de atualização manual", - "5c8ebc36f84dee7a": "precisa de um app desktop mais novo", + "f13e08bd3614112e": "atualize o T3 Code nessa máquina", + "3c3348c36a2695af": "mude o canal de atualização nessa máquina", "fa8faa732a2688ef": "no canal {channel}", "9b961309baafa09d": "sem permissão", "9bafb2622c22d145": "já está atualizando", @@ -12779,5 +12792,24 @@ "99d51127f573296b": "Outra conta", "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", "99963c0142e17f00": "Para a nova conta do {tracker}.", - "6d8e4ebc889bace9": "Adicionar conta" + "6d8e4ebc889bace9": "Adicionar conta", + "8a883c4fbc127b68": "Ativando o merge automático da pilha...", + "5fb2a26ae31e8983": "Não foi possível ativar o merge automático da pilha", + "986d0dcbf4dd0098": "Merge automático da pilha ativado", + "f3ed1f63c8a3eef2": "{host} vai mesclar a pilha até o #{number} quando os requisitos forem atendidos.", + "bd536a0a1754f6cb": "Não foi possível cancelar o merge automático da pilha", + "bb90ac3b2f3a72d5": "O host recusou o cancelamento do merge automático. Atualize e tente novamente.", + "9c28753c777c37b7": "{count, plural, one {Mesclar automaticamente {count} {term, select, mr {merge request} cr {solicitação de alteração} other {pull request}}?} other {Mesclar automaticamente {count} {term, select, mr {merge requests} cr {solicitações de alteração} other {pull requests}}?}}", + "a86b49982e18784d": "Mescla o #{number} e as camadas não mescladas abaixo dele em {base} usando {method} quando todas atenderem aos requisitos de {host}. Isso pode acontecer imediatamente.", + "b1afda5c964deee4": [ + "Merge automático da pilha (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancelar merge automático da pilha", + "012c67c7f1a99e33": "Merge automático da pilha" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 2043881742c8e..5a9f037b671da 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Готово", "d4d89c139de812a8": "Ошибка", "c1e03a860c856245": "Остановлено", - "f1d27d127ab27ac6": "Запуск", + "7e5abc299ead1d09": "Загрузка плагинов {provider}", + "21872f69ccbc711d": "Запуск MCP-серверов {provider}", + "fedaa29ff8815a77": "Загрузка хуков {provider}", + "57025ae4de5beb57": "Загрузка правил и навыков {provider}", + "4729a188600f1501": "Подключение к {provider}", "8c8977097681630f": "Запуск {provider}", + "f1d27d127ab27ac6": "Запуск", "86d60d42f6cb4a40": "Простаивает", "0e8eab930d79d8b4": "Ожидание", "54002bf654ddbab1": "Завершено", @@ -3232,7 +3237,8 @@ "49e3cf16b3ac3e5f": "Доступ", "9699d255b374e215": "Что ему разрешено", "86f5769278f5fa4d": "Помимо чтения, он может запускать треды, отправлять в них сообщения и останавливать их, и ни один не будет работать с режимом выше выбранного.", - "693a1983e099523a": "Подключение к этому бэкенду.", + "4f3982f640dfed5b": "Эта ссылка добавляет бэкенд в этот браузер. Продолжайте, только если доверяете ему.", + "41b32a424841adb7": "В ссылке для сопряжения указан недопустимый хост бэкенда.", "ec2a82b05e616aa0": "В ссылке для сопряжения нет хоста бэкенда или токена.", "630d4f04309bc19a": "Ошибка аутентификации.", "63bc32e8544f4de1": "Этому окружению нужны доверенные учётные данные сопряжения, прежде чем приложение сможет подключиться.", @@ -3246,11 +3252,13 @@ "55c59743f7fdd7fa": "Вставьте одноразовый токен или секрет сопряжения", "ca6a0c94398d763d": "Сопряжение...", "989f56b8297dd684": "Этот одноразовый токен сопряжения уже отправлен. Запросите новую ссылку для сопряжения.", + "693a1983e099523a": "Подключение к этому бэкенду.", "db3dcafc90d10405": "{environment} сохранено в этом браузере.", "47d4ab320c4c394c": "Окружение сохранено в этом браузере.", "d235c6bfa25870a4": "{error} Если бэкенд принял этот одноразовый токен, запросите новую ссылку для сопряжения перед повтором.", "00c1dcaef4762f18": "Сопряжение с бэкендом выполнено", "aac4a30e5912c01c": "Ошибка сопряжения", + "c142c3f3bed15f8d": "Добавить этот бэкенд?", "dbb27f4ee8ecfa8e": "Бэкенд сопряжения", "8049e9ba2e8b4867": "Токен сопряжения", "0528294df7656322": [ @@ -3267,6 +3275,7 @@ } ], "ff5f1c260e87ecde": "Убедитесь, что бэкенд доступен из этого браузера, поддерживает CORS для размещённых клиентов и работает по HTTPS, если эта страница открыта по HTTPS.", + "984c25ffcae69300": "Добавить бэкенд", "08570ee0982df89d": "Сопряжение...", "3bbae7c96b6cbfc3": "Открыть приложение", "49cc06e79f21f85a": "{seconds} с", @@ -3312,13 +3321,9 @@ "b90e87f4b7125237": "Подробности", "16dc67f5429d8bae": "Фоновая работа", "2188eee8f81b0f51": "Открыть субагента", - "3b03fc47eba632b4": "{count, plural, one {{formattedCount} изменённый файл} few {{formattedCount} изменённых файла} many {{formattedCount} изменённых файлов} other {{formattedCount} изменённого файла}}", "ec9e0be8ec693302": "Свернуть все папки", "b791dd86f7991cc0": "Развернуть все папки", - "afaf1bc8535e0adf": "Открыть дифф", - "d31b3c7be099ca82": "{count, plural, one {Ещё {formattedCount} файл в полном диффе} few {Ещё {formattedCount} файла в полном диффе} many {Ещё {formattedCount} файлов в полном диффе} other {Ещё {formattedCount} файла в полном диффе}}", "55b936e3014e16c8": "Открыть дифф", - "452dc9eaa945693b": "Открыть полный дифф", "28bb7ce40dfd349a": "Вывод терминала нельзя добавить к ответу на вопрос.", "801cb8edea94b8f6": "Сначала ответьте на вопрос или закройте его, затем добавьте в чат.", "aa5507f20d94d5a9": "Обновите сервер, чтобы отправлять файлы вместе с ответами на вопросы", @@ -4398,7 +4403,6 @@ "991cc9fb37606c91": "(пустой ответ)", "36e4b8d2db087296": "Ответвить от этого ответа", "c92a0bab54261695": "Ответить на этот ответ", - "405a3e88ee6e62b3": "Не удаётся показать изменения этого хода в этом репозитории.", "f6958f38dc87c712": "Ответвить от этого ответа", "72f8e14b1246d224": "Ответить на этот ответ", "01d7728e893c281d": "Перейти к сообщению: {text}", @@ -6835,6 +6839,8 @@ "45674081908ac8aa": "Команда checkout скопирована", "d2970574ef7860d0": "{term, select, mr {Копировать ветку мерж-реквеста} cr {Копировать ветку запроса на изменение} other {Копировать ветку пул-реквеста}}", "45c92416a82cf22c": "Имя ветки скопировано", + "43a18c0bc37988f4": "Отправлены новые коммиты. Слияние или ревью по-прежнему относится к {sha}.", + "c930a7ffa49054f0": "Загрузить новые коммиты", "63e533a9db74e8dc": "Проверки", "4f7ca990d538a8bc": "Комментарии недоступны", "95601ce075194611": "{count, plural, one {{formatted} комментарий} few {{formatted} комментария} many {{formatted} комментариев} other {{formatted} комментария}}", @@ -7554,6 +7560,11 @@ "03338c6aec8edacd": "Задайте, насколько широкими могут быть сообщения и поле ввода на больших экранах.", "92785adb251da88c": "Сбросить ширину чата к значению по умолчанию", "4d457bcce0c0e272": "Ширина чата", + "7d7f65967cc821e3": "Ширина предпросмотра HTML", + "70ce0af7f78d5957": "Позволяет предпросмотрам HTML в чате быть шире сообщений, которые остаются по центру.", + "f2b119bf02ae2558": "Сбросить ширину предпросмотра HTML к значению по умолчанию", + "6287212fed0deec6": "Как у чата", + "dc8e85ea0364649c": "Как у чата (по умолчанию)", "81f3a196537bbee0": "Удобная (по умолчанию)", "e79e5388f669495f": "Показывать усилие рассуждения в поле ввода названием, например «Высокое», или полосками.", "7f0365c7e4e8bcbf": "Сбросить отображение усилия к значению по умолчанию", @@ -11819,6 +11830,7 @@ "9cf8308531b4ff31": "прозрачный прозрачность сплошной меню диалоги поле ввода", "d8d6cfd630cff22d": "красный зелёный синий оранжевый добавления удаления изменения счётчики палитра дальтонизм", "717e49895cfee1c7": "широкий полная ширина колонка раскладка сообщения поле ввода монитор", + "9d5c7430a7ff76cf": "широкий полная ширина встроенная страница рендер график дашборд артефакт по центру", "88365077fd80787b": "настроить показать скрыть панель карточка окружение редактор скрипты ветка пул-реквест git изменения серверы автоматизации происхождение использование лимиты 5 часов неделя квота токены контекстное окно", "d561f74efa5f3920": "усилие рассуждений размышление полосы график слово метка уровень поле ввода", "6113c17109ee0d57": "latex tex katex уравнения формулы markdown", @@ -12136,7 +12148,8 @@ "f938bb483eb3d189": "перезапуск последним", "9bca02be2b4d612a": "не подключено", "2dcc418b6a13b83c": "нужно обновить вручную", - "5c8ebc36f84dee7a": "нужна более новая версия десктопного приложения", + "f13e08bd3614112e": "обновите T3 Code на этом компьютере", + "3c3348c36a2695af": "смените канал обновлений на этом компьютере", "fa8faa732a2688ef": "на канале {channel}", "9b961309baafa09d": "нет прав", "9bafb2622c22d145": "уже обновляется", @@ -12779,5 +12792,24 @@ "99d51127f573296b": "Другой аккаунт", "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", "99963c0142e17f00": "Для нового аккаунта {tracker}.", - "6d8e4ebc889bace9": "Добавить аккаунт" + "6d8e4ebc889bace9": "Добавить аккаунт", + "8a883c4fbc127b68": "Включение автослияния стека...", + "5fb2a26ae31e8983": "Не удалось включить автослияние стека", + "986d0dcbf4dd0098": "Автослияние стека включено", + "f3ed1f63c8a3eef2": "{host} сольёт стек до #{number}, когда будут выполнены требования.", + "bd536a0a1754f6cb": "Не удалось отменить автослияние стека", + "bb90ac3b2f3a72d5": "Хост отказался отменить автослияние. Обновите и повторите попытку.", + "9c28753c777c37b7": "{count, plural, one {Включить автослияние для {count} {term, select, mr {мерж-реквеста} cr {запроса на изменение} other {пул-реквеста}}?} few {Включить автослияние для {count} {term, select, mr {мерж-реквестов} cr {запросов на изменение} other {пул-реквестов}}?} many {Включить автослияние для {count} {term, select, mr {мерж-реквестов} cr {запросов на изменение} other {пул-реквестов}}?} other {Включить автослияние для {count} {term, select, mr {мерж-реквеста} cr {запроса на изменение} other {пул-реквеста}}?}}", + "a86b49982e18784d": "#{number} и несмёрженные слои под ним будут слиты в {base} методом {method}, когда каждый из них выполнит требования {host}. Это может произойти сразу.", + "b1afda5c964deee4": [ + "Автослияние стека (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Отменить автослияние стека", + "012c67c7f1a99e33": "Автослияние стека" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6229647851dfd..a20cafa099e84 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Klar", "d4d89c139de812a8": "Misslyckades", "c1e03a860c856245": "Stoppad", - "f1d27d127ab27ac6": "Startar", + "7e5abc299ead1d09": "Läser in plugins för {provider}", + "21872f69ccbc711d": "Startar MCP-servrar för {provider}", + "fedaa29ff8815a77": "Läser in hooks för {provider}", + "57025ae4de5beb57": "Läser in regler och färdigheter för {provider}", + "4729a188600f1501": "Ansluter till {provider}", "8c8977097681630f": "Startar {provider}", + "f1d27d127ab27ac6": "Startar", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Väntar", "54002bf654ddbab1": "Slutförd", @@ -3232,7 +3237,8 @@ "49e3cf16b3ac3e5f": "Åtkomst", "9699d255b374e215": "Vad den får göra", "86f5769278f5fa4d": "Utöver endast läsning kan den starta, skicka meddelanden till och stoppa trådar, och ingen av dem kan köras med mer än det läge du väljer.", - "693a1983e099523a": "Ansluter till den här backenden.", + "4f3982f640dfed5b": "Den här länken lägger till en backend i den här webbläsaren. Fortsätt bara om du litar på den.", + "41b32a424841adb7": "Den här parkopplingslänken har en ogiltig backend-värd.", "ec2a82b05e616aa0": "Den här parkopplingslänken saknar backend-värd eller token.", "630d4f04309bc19a": "Autentiseringen misslyckades.", "63bc32e8544f4de1": "Den här miljön kräver en betrodd parkopplingsuppgift innan appen kan ansluta.", @@ -3246,11 +3252,13 @@ "55c59743f7fdd7fa": "Klistra in en engångstoken eller en parkopplingshemlighet", "ca6a0c94398d763d": "Parkopplar...", "989f56b8297dd684": "Den här engångstoken för parkoppling har redan skickats. Begär en ny parkopplingslänk.", + "693a1983e099523a": "Ansluter till den här backenden.", "db3dcafc90d10405": "{environment} är sparad i den här webbläsaren.", "47d4ab320c4c394c": "Miljön är sparad i den här webbläsaren.", "d235c6bfa25870a4": "{error} Om backenden godtog den här engångstoken, begär en ny parkopplingslänk innan du försöker igen.", "00c1dcaef4762f18": "Backenden parkopplades", "aac4a30e5912c01c": "Parkopplingen misslyckades", + "c142c3f3bed15f8d": "Lägga till den här backenden?", "dbb27f4ee8ecfa8e": "Parkopplar backend", "8049e9ba2e8b4867": "Parkopplingstoken", "0528294df7656322": [ @@ -3267,6 +3275,7 @@ } ], "ff5f1c260e87ecde": "Kontrollera att backenden kan nås från den här webbläsaren, stöder CORS för webbaserade klienter och betjänas via HTTPS när den här sidan öppnas via HTTPS.", + "984c25ffcae69300": "Lägg till backend", "08570ee0982df89d": "Parkopplar...", "3bbae7c96b6cbfc3": "Öppna app", "49cc06e79f21f85a": "{seconds} s", @@ -3312,13 +3321,9 @@ "b90e87f4b7125237": "Detaljer", "16dc67f5429d8bae": "Bakgrundsarbete", "2188eee8f81b0f51": "Öppna subagent", - "3b03fc47eba632b4": "{count, plural, one {{formattedCount} ändrad fil} other {{formattedCount} ändrade filer}}", "ec9e0be8ec693302": "Fäll ihop alla mappar", "b791dd86f7991cc0": "Fäll ut alla mappar", - "afaf1bc8535e0adf": "Öppna diff", - "d31b3c7be099ca82": "{count, plural, one {{formattedCount} fil till i hela diffen} other {{formattedCount} filer till i hela diffen}}", "55b936e3014e16c8": "Öppna diff", - "452dc9eaa945693b": "Öppna hela diffen", "28bb7ce40dfd349a": "Terminalutdata kan inte läggas till i ett svar på en fråga.", "801cb8edea94b8f6": "Svara på eller stäng frågan först och lägg sedan till det i chatten.", "aa5507f20d94d5a9": "Uppdatera servern för att skicka filer med svar på frågor", @@ -4399,7 +4404,6 @@ "991cc9fb37606c91": "(tomt svar)", "36e4b8d2db087296": "Forka från det här svaret", "c92a0bab54261695": "Svara på det här svaret", - "405a3e88ee6e62b3": "Den här omgångens ändringar i det här repot kan inte listas.", "f6958f38dc87c712": "Forka från det här svaret", "72f8e14b1246d224": "Svara på det här svaret", "01d7728e893c281d": "Hoppa till meddelande: {text}", @@ -6841,6 +6845,8 @@ "45674081908ac8aa": "Utcheckningskommandot kopierades", "d2970574ef7860d0": "Kopiera grenen för {term, select, mr {merge requesten} cr {ändringsbegäran} other {pull requesten}}", "45c92416a82cf22c": "Grennamnet kopierades", + "43a18c0bc37988f4": "Nya commits har pushats. En merge eller granskning gäller fortfarande {sha}.", + "c930a7ffa49054f0": "Läs in nya commits", "63e533a9db74e8dc": "Kontroller", "4f7ca990d538a8bc": "Kommentarer är inte tillgängliga", "95601ce075194611": "{count, plural, one {{formatted} kommentar} other {{formatted} kommentarer}}", @@ -7560,6 +7566,11 @@ "03338c6aec8edacd": "Ange hur breda meddelanden och inmatningsfältet kan bli på stora skärmar.", "92785adb251da88c": "Återställ chattbredd till standard", "4d457bcce0c0e272": "Chattbredd", + "7d7f65967cc821e3": "Bredd för HTML-förhandsvisning", + "70ce0af7f78d5957": "Låter HTML-förhandsvisningar i en chatt bli bredare än meddelandena, som förblir centrerade.", + "f2b119bf02ae2558": "Återställ bredd för HTML-förhandsvisning till standard", + "6287212fed0deec6": "Samma som chatten", + "dc8e85ea0364649c": "Samma som chatten (standard)", "81f3a196537bbee0": "Bekväm (standard)", "e79e5388f669495f": "Visa resonemangsnivån i inmatningsfältet som sitt namn, till exempel Hög, eller som staplar.", "7f0365c7e4e8bcbf": "Återställ visning av ansträngning till standard", @@ -11826,6 +11837,7 @@ "9cf8308531b4ff31": "transparent genomskinlighet solid menyer dialoger inmatningsfält", "d8d6cfd630cff22d": "röd grön blå orange tillägg borttagningar ändringar antal palett färgblind", "717e49895cfee1c7": "bred full bredd kolumn layout meddelanden inmatningsfält skärm", + "9d5c7430a7ff76cf": "bred full bredd inbäddad sida rendera diagram instrumentpanel artefakt centrerad", "88365077fd80787b": "anpassa visa dölj panel kort miljö redigerare skript gren pull request git ändringar servrar automatiseringar härkomst användning gränser 5 timmar vecka kvot token kontextfönster", "d561f74efa5f3920": "resonemang ansträngning tänkande staplar diagram ord etikett nivå inmatningsfält", "6113c17109ee0d57": "latex tex katex ekvationer formler markdown", @@ -12143,7 +12155,8 @@ "f938bb483eb3d189": "startar om sist", "9bca02be2b4d612a": "inte ansluten", "2dcc418b6a13b83c": "behöver uppdateras manuellt", - "5c8ebc36f84dee7a": "behöver en nyare skrivbordsapp", + "f13e08bd3614112e": "uppdatera T3 Code på den datorn", + "3c3348c36a2695af": "byt uppdateringsspår på den datorn", "fa8faa732a2688ef": "på kanalen {channel}", "9b961309baafa09d": "ingen behörighet", "9bafb2622c22d145": "uppdateras redan", @@ -12786,5 +12799,24 @@ "99d51127f573296b": "Ett konto till", "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", "99963c0142e17f00": "För det nya {tracker}-kontot.", - "6d8e4ebc889bace9": "Lägg till konto" + "6d8e4ebc889bace9": "Lägg till konto", + "8a883c4fbc127b68": "Aktiverar automatisk merge för stacken...", + "5fb2a26ae31e8983": "Kunde inte aktivera automatisk merge för stacken", + "986d0dcbf4dd0098": "Automatisk merge för stacken aktiverad", + "f3ed1f63c8a3eef2": "{host} mergar stacken till och med #{number} när kraven är uppfyllda.", + "bd536a0a1754f6cb": "Kunde inte avbryta automatisk merge för stacken", + "bb90ac3b2f3a72d5": "Värden vägrade avbryta den automatiska mergen. Uppdatera och försök igen.", + "9c28753c777c37b7": "{count, plural, one {Merga {count} {term, select, mr {merge request} cr {ändringsbegäran} other {pull request}} automatiskt?} other {Merga {count} {term, select, mr {merge requests} cr {ändringsbegäranden} other {pull requests}} automatiskt?}}", + "a86b49982e18784d": "Merga #{number} och dess omergade lager under in i {base} med {method} när vart och ett uppfyller kraven på {host}. Det kan ske direkt.", + "b1afda5c964deee4": [ + "Merga stacken automatiskt (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Avbryt automatisk merge för stacken", + "012c67c7f1a99e33": "Merga stacken automatiskt" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index bd4ddf30bd0f8..c2078a0d89243 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完成", "d4d89c139de812a8": "失败", "c1e03a860c856245": "已停止", - "f1d27d127ab27ac6": "正在启动", + "7e5abc299ead1d09": "正在加载 {provider} 插件", + "21872f69ccbc711d": "正在启动 {provider} MCP 服务器", + "fedaa29ff8815a77": "正在加载 {provider} 钩子", + "57025ae4de5beb57": "正在加载 {provider} 规则和技能", + "4729a188600f1501": "正在连接 {provider}", "8c8977097681630f": "正在启动 {provider}", + "f1d27d127ab27ac6": "正在启动", "86d60d42f6cb4a40": "闲置", "0e8eab930d79d8b4": "等待中", "54002bf654ddbab1": "已完成", @@ -3236,7 +3241,8 @@ "49e3cf16b3ac3e5f": "访问权限", "9699d255b374e215": "允许它做什么", "86f5769278f5fa4d": "除只读外,它还可以启动会话、向会话发消息和停止会话,且任何会话的权限都不会超过你选择的模式。", - "693a1983e099523a": "正在连接此后端。", + "4f3982f640dfed5b": "此链接会向此浏览器添加一个后端。仅在你信任它时继续。", + "41b32a424841adb7": "此配对链接中的后端主机无效。", "ec2a82b05e616aa0": "此配对链接缺少后端主机或 token。", "630d4f04309bc19a": "身份验证失败。", "63bc32e8544f4de1": "此环境需要可信的配对凭据,应用才能连接。", @@ -3250,11 +3256,13 @@ "55c59743f7fdd7fa": "粘贴一次性 token 或配对凭据", "ca6a0c94398d763d": "正在配对…", "989f56b8297dd684": "此一次性配对 token 已提交过。请申请新的配对链接。", + "693a1983e099523a": "正在连接此后端。", "db3dcafc90d10405": "{environment} 已保存在此浏览器中。", "47d4ab320c4c394c": "该环境已保存在此浏览器中。", "d235c6bfa25870a4": "{error} 如果后端已接受此一次性 token,请先申请新的配对链接再重试。", "00c1dcaef4762f18": "后端已配对", "aac4a30e5912c01c": "配对失败", + "c142c3f3bed15f8d": "要添加此后端吗?", "dbb27f4ee8ecfa8e": "正在配对后端", "8049e9ba2e8b4867": "配对 token", "0528294df7656322": [ @@ -3271,6 +3279,7 @@ } ], "ff5f1c260e87ecde": "请确认此浏览器能访问该后端、后端为托管客户端启用了 CORS,并且在通过 HTTPS 打开此页面时后端也使用 HTTPS。", + "984c25ffcae69300": "添加后端", "08570ee0982df89d": "正在配对…", "3bbae7c96b6cbfc3": "打开应用", "49cc06e79f21f85a": "{seconds} 秒", @@ -3316,13 +3325,9 @@ "b90e87f4b7125237": "详情", "16dc67f5429d8bae": "后台任务", "2188eee8f81b0f51": "打开子智能体", - "3b03fc47eba632b4": "{count, plural, other {{formattedCount} 个已更改的文件}}", "ec9e0be8ec693302": "折叠全部文件夹", "b791dd86f7991cc0": "展开全部文件夹", - "afaf1bc8535e0adf": "打开差异", - "d31b3c7be099ca82": "{count, plural, other {完整差异中还有 {formattedCount} 个文件}}", "55b936e3014e16c8": "打开差异", - "452dc9eaa945693b": "打开完整差异", "28bb7ce40dfd349a": "终端输出无法添加到问题回答中。", "801cb8edea94b8f6": "先回答或关闭问题,再将其添加到聊天中。", "aa5507f20d94d5a9": "请更新此服务器,才能在回答问题时发送文件", @@ -4405,7 +4410,6 @@ "991cc9fb37606c91": "(空响应)", "36e4b8d2db087296": "从这条回复分叉", "c92a0bab54261695": "回复这条回答", - "405a3e88ee6e62b3": "无法列出此轮次在该仓库中的改动。", "f6958f38dc87c712": "从这条回复分叉", "72f8e14b1246d224": "回复这条回答", "01d7728e893c281d": "跳转到消息:{text}", @@ -6848,6 +6852,8 @@ "45674081908ac8aa": "已复制检出工作副本的命令", "d2970574ef7860d0": "复制 {term, select, mr {MR} cr {change request} other {PR}} 分支", "45c92416a82cf22c": "已复制分支名称", + "43a18c0bc37988f4": "有新的提交被推送。合并或评审仍针对 {sha}。", + "c930a7ffa49054f0": "加载新提交", "63e533a9db74e8dc": "检查", "4f7ca990d538a8bc": "评论不可用", "95601ce075194611": "{count, plural, other {{formatted} 条评论}}", @@ -7569,6 +7575,11 @@ "03338c6aec8edacd": "设置大屏幕上消息和输入框的最大宽度。", "92785adb251da88c": "重置聊天宽度为默认值", "4d457bcce0c0e272": "聊天宽度", + "7d7f65967cc821e3": "HTML 预览宽度", + "70ce0af7f78d5957": "让聊天中的 HTML 预览比消息更宽,消息仍保持居中。", + "f2b119bf02ae2558": "重置 HTML 预览宽度为默认值", + "6287212fed0deec6": "与聊天一致", + "dc8e85ea0364649c": "与聊天一致(默认)", "81f3a196537bbee0": "适中(默认)", "e79e5388f669495f": "在输入框中用名称(如 High)或条形显示推理强度。", "7f0365c7e4e8bcbf": "重置推理强度显示为默认值", @@ -11843,6 +11854,7 @@ "9cf8308531b4ff31": "透明 透明度 实色 菜单 对话框 输入框", "d8d6cfd630cff22d": "红 绿 蓝 橙 新增 删除 更改 计数 调色板 色盲", "717e49895cfee1c7": "宽 全宽 列 布局 消息 输入框 显示器", + "9d5c7430a7ff76cf": "宽 全宽 内嵌 页面 渲染 图表 仪表板 工件 居中", "88365077fd80787b": "自定义 显示 隐藏 面板 卡片 环境 编辑器 脚本 分支 PR git 更改 服务器 自动化 谱系 用量 限制 5 小时 每周 配额 token 上下文窗口", "d561f74efa5f3920": "推理强度 思考 条形 图表 文字 标签 级别 输入框", "6113c17109ee0d57": "latex tex katex 方程 公式 markdown", @@ -12161,7 +12173,8 @@ "f938bb483eb3d189": "最后重启", "9bca02be2b4d612a": "未连接", "2dcc418b6a13b83c": "需要手动更新", - "5c8ebc36f84dee7a": "需要更高版本的桌面应用", + "f13e08bd3614112e": "请在该机器上更新 T3 Code", + "3c3348c36a2695af": "请在该机器上更改更新通道", "fa8faa732a2688ef": "使用 {channel} 通道", "9b961309baafa09d": "没有权限", "9bafb2622c22d145": "正在更新", @@ -12798,5 +12811,24 @@ "99d51127f573296b": "其他账号", "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", "99963c0142e17f00": "用于新的 {tracker} 账号。", - "6d8e4ebc889bace9": "添加账号" + "6d8e4ebc889bace9": "添加账号", + "8a883c4fbc127b68": "正在启用堆叠自动合并…", + "5fb2a26ae31e8983": "无法启用堆叠自动合并", + "986d0dcbf4dd0098": "已启用堆叠自动合并", + "f3ed1f63c8a3eef2": "满足要求后,{host} 会合并截至 #{number} 的堆叠。", + "bd536a0a1754f6cb": "无法取消堆叠自动合并", + "bb90ac3b2f3a72d5": "主机拒绝取消自动合并。请刷新后重试。", + "9c28753c777c37b7": "{count, plural, other {自动合并 {count} 个 {term, select, mr {merge request} cr {change request} other {pull request}}?}}", + "a86b49982e18784d": "当 #{number} 及其下方未合并的各层都满足 {host} 的要求时,使用 {method} 将它们合并到 {base}。这可能会立即发生。", + "b1afda5c964deee4": [ + "自动合并堆叠(", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "取消堆叠自动合并", + "012c67c7f1a99e33": "自动合并堆叠" } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index f864b6f0d4970..07f9a023ad902 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -129,6 +129,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --workspace-titlebar-control-gap: 0.75rem; --workspace-titlebar-scroll-fade-height: 1.5rem; --chat-content-max-width: 46rem; + --html-preview-max-width: var(--chat-content-max-width); --thread-details-panel-width: 17.5rem; /* The prompt on phones: iOS zooms into any input under 16px on focus. */ --font-size-prompt-touch: max(var(--font-size-prompt, 1rem), 16px); @@ -984,6 +985,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil max-width: var(--chat-content-max-width); } + /* ChatCanvas sets these only while HTML previews run wider than the chat column. */ + .html-preview-lane { + width: var(--html-preview-lane-width, auto); + margin-inline-start: var(--html-preview-lane-offset, 0px); + } + .messages-timeline-row-frame { padding-inline: 0; } @@ -1566,23 +1573,14 @@ html[data-theme-id] :is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblo color: color-mix(in srgb, var(--code-foreground) 72%, transparent); } -/* T3 Chat renders inline code and compact chat artifacts with its translucent +/* T3 Chat renders inline code with its translucent secondary surface flattened over the light chat canvas. The raw muted and secondary tokens are substantially darker than those visible pixels. */ html[data-theme-id="t3-chat"] { @variant light { - & .chat-markdown :not(pre) > code, - & [data-changed-files-state], - & [data-changed-files-header] { + & .chat-markdown :not(pre) > code { background-color: var(--message-surface); - } - - & .chat-markdown :not(pre) > code, - & [data-changed-files-state] { border-color: transparent; - } - - & .chat-markdown :not(pre) > code { color: var(--contrast-message-foreground); } } @@ -2072,9 +2070,11 @@ code { } /* Triple-click selection stops at block-level boxes, flex items included, so file chips in - prose stay inline-level down to the icon and label. */ + prose stay inline-level down to the icon and label. Chromium also stops it at + draggable="true" (desktop native file drags) unless user-select is set back to text. */ .chat-markdown-file-link { display: inline-block; + user-select: text; overflow-x: clip; text-overflow: ellipsis; white-space: nowrap; @@ -2375,6 +2375,16 @@ code { --chat-content-max-width: 100%; } +/* HTML preview width setting. ChatCanvas measures this and never lays a + preview out narrower than the chat column. */ +:root[data-html-preview-width="wide"] { + --html-preview-max-width: 72rem; +} + +:root[data-html-preview-width="full"] { + --html-preview-max-width: 100%; +} + :root[data-diff-color-scheme="blue-orange"] { --diff-addition: light-dark(var(--color-blue-600), var(--color-blue-400)); --diff-deletion: light-dark(var(--color-orange-600), var(--color-orange-400)); diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index fb6f719bb2346..84463efc3abfd 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -758,6 +758,77 @@ describe("resolveShortcutCommand", () => { ); }); + it("matches Option symbols against the active Latin layout rather than the US position", () => { + const keybindings = compile([ + { shortcut: modShortcut("a", { altKey: true, shiftKey: true }), command: "appearance.cycle" }, + { shortcut: modShortcut("q", { altKey: true, shiftKey: true }), command: "sidebar.toggle" }, + ]); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "Æ", code: "KeyQ", metaKey: true, altKey: true, shiftKey: true }), + keybindings, + { platform: "MacIntel", keyboardLayoutMap: new Map([["KeyQ", "a"]]) }, + ), + "appearance.cycle", + ); + }); + + it("preserves physical punctuation alongside an Option-modified mapped letter", () => { + for (const key of [";", "m"]) { + const keybindings = compile([ + { shortcut: modShortcut(key, { altKey: true }), command: "diff.toggle" }, + ]); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "µ", code: "Semicolon", metaKey: true, altKey: true }), + keybindings, + { platform: "MacIntel", keyboardLayoutMap: new Map([["Semicolon", "m"]]) }, + ), + "diff.toggle", + ); + } + }); + + it("keeps Latin event keys and unsupported layout fallbacks", () => { + const keybindings = compile([ + { shortcut: modShortcut("a", { altKey: true }), command: "appearance.cycle" }, + { shortcut: modShortcut("q", { altKey: true }), command: "sidebar.toggle" }, + ]); + const options = { platform: "MacIntel", keyboardLayoutMap: new Map([["KeyQ", "a"]]) }; + assert.strictEqual( + resolveShortcutCommand( + event({ key: "q", code: "KeyQ", metaKey: true, altKey: true }), + keybindings, + options, + ), + "sidebar.toggle", + ); + for (const keyboardLayoutMap of [new Map(), new Map([["KeyQ", "й"]])]) { + assert.strictEqual( + resolveShortcutCommand( + event({ key: "Æ", code: "KeyQ", metaKey: true, altKey: true }), + keybindings, + { ...options, keyboardLayoutMap }, + ), + "sidebar.toggle", + ); + } + assert.strictEqual( + resolveShortcutCommand( + event({ + key: "Æ", + code: "KeyQ", + ctrlKey: true, + altKey: true, + getModifierState: () => true, + }), + keybindings, + { ...options, platform: "Win32" }, + ), + null, + ); + }); + it("matches non-Latin layout letters using the physical key code", () => { const keybindings = compile([{ shortcut: modShortcut("d"), command: "diff.toggle" }]); diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index f05067a2e53bc..117847faa95bb 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -17,13 +17,24 @@ import { resolveEventKeys, type ShortcutEventLike as SharedShortcutEventLike, type ShortcutModifierStateLike, + type ShortcutKeyboardLayoutMap, + shortcutKeyFromEvent as sharedShortcutKeyFromEvent, } from "@t3tools/shared/keybindings"; import { isElectron } from "./env"; import { isEditableFocused } from "./lib/editableFocus"; import { projectScriptIdFromCommand } from "./projectScripts"; +import { getKeyboardLayoutMap } from "./keyboardLayout"; export type { ShortcutModifierStateLike } from "@t3tools/shared/keybindings"; -export { shortcutKeyFromEvent } from "@t3tools/shared/keybindings"; +export function shortcutKeyFromEvent( + event: Pick, + platform: string, +) { + return sharedShortcutKeyFromEvent( + event, + isMacPlatform(platform) && event.altKey ? getKeyboardLayoutMap() : undefined, + ); +} export interface ShortcutEventLike extends SharedShortcutEventLike { target?: EventTarget | null; @@ -42,6 +53,7 @@ export interface ShortcutMatchContext { interface ShortcutMatchOptions { platform?: string; + keyboardLayoutMap?: ShortcutKeyboardLayoutMap; context?: Partial; } @@ -194,7 +206,15 @@ export function resolveShortcutCommand( const binding = keybindings[index]; if (!binding) continue; if (!matchesWhenClause(binding.whenAst, context)) continue; - if (!matchesKeybindingShortcut(event, shortcutForContext(binding, context), platform)) continue; + if ( + !matchesKeybindingShortcut( + event, + shortcutForContext(binding, context), + platform, + options?.keyboardLayoutMap ?? getKeyboardLayoutMap(), + ) + ) + continue; return binding.command; } return null; diff --git a/apps/web/src/keyboardLayout.test.ts b/apps/web/src/keyboardLayout.test.ts new file mode 100644 index 0000000000000..b33ef3218041d --- /dev/null +++ b/apps/web/src/keyboardLayout.test.ts @@ -0,0 +1,81 @@ +import { afterEach, assert, it } from "vite-plus/test"; +import { getKeyboardLayoutMap, trackKeyboardLayout } from "./keyboardLayout"; +import { keybindingFromKeyboardEvent } from "./components/settings/KeybindingsSettings.logic"; + +let stop: (() => void) | undefined; +afterEach(() => stop?.()); + +function pendingLayout() { + let resolve!: (layout: Map) => void; + const promise = new Promise>((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +it.each([true, false])( + "records Option symbols and refreshes the current layout (keyboard events: %s)", + async (supportsEvents) => { + let layout = Promise.resolve(new Map([["KeyQ", "a"]])); + const keyboard = Object.assign(supportsEvents ? new EventTarget() : {}, { + getLayoutMap: () => layout, + }); + const focusTarget = new EventTarget(); + stop = trackKeyboardLayout(keyboard, focusTarget); + await keyboard.getLayoutMap(); + const event = { + key: "Æ", + code: "KeyQ", + metaKey: true, + ctrlKey: false, + altKey: true, + shiftKey: true, + }; + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+a"); + assert.strictEqual( + keybindingFromKeyboardEvent(event, "MacIntel", { layoutCharacter: true }), + "mod+alt+shift+a", + ); + const pending = pendingLayout(); + layout = pending.promise; + focusTarget.dispatchEvent(new Event("focus")); + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+a"); + pending.resolve(new Map([["KeyQ", "q"]])); + await layout; + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+q"); + layout = Promise.reject(new Error("Permission denied")); + focusTarget.dispatchEvent(new Event("focus")); + assert.strictEqual(getKeyboardLayoutMap()?.get("KeyQ"), "q"); + await layout.catch(() => undefined); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + layout = Promise.resolve(new Map([["KeyQ", "a"]])); + stop(); + focusTarget.dispatchEvent(new Event("focus")); + await keyboard.getLayoutMap(); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + }, +); + +it("ignores an obsolete layout result", async () => { + const pending = pendingLayout(); + let result = pending.promise; + const keyboard = Object.assign(new EventTarget(), { getLayoutMap: () => result }); + stop = trackKeyboardLayout(keyboard); + result = Promise.resolve(new Map([["KeyQ", "q"]])); + keyboard.dispatchEvent(new Event("layoutchange")); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + await result; + pending.resolve(new Map([["KeyQ", "a"]])); + await pending.promise; + assert.strictEqual(getKeyboardLayoutMap()?.get("KeyQ"), "q"); +}); + +it("does not publish a pending result after disposal", async () => { + const pending = pendingLayout(); + const keyboard = Object.assign(new EventTarget(), { getLayoutMap: () => pending.promise }); + stop = trackKeyboardLayout(keyboard); + stop(); + pending.resolve(new Map([["KeyQ", "a"]])); + await pending.promise; + assert.strictEqual(getKeyboardLayoutMap(), undefined); +}); diff --git a/apps/web/src/keyboardLayout.ts b/apps/web/src/keyboardLayout.ts new file mode 100644 index 0000000000000..61fd6e24a1b57 --- /dev/null +++ b/apps/web/src/keyboardLayout.ts @@ -0,0 +1,44 @@ +import type { ShortcutKeyboardLayoutMap } from "@t3tools/shared/keybindings"; + +interface KeyboardLayoutSource extends Partial< + Pick +> { + getLayoutMap(): Promise; +} + +let keyboardLayoutMap: ShortcutKeyboardLayoutMap | undefined; + +export function getKeyboardLayoutMap() { + return keyboardLayoutMap; +} + +// Option changes event.key to a symbol on macOS; the layout map recovers the +// letter printed on that key without assuming a US physical layout. +export function trackKeyboardLayout( + keyboard = (navigator as Navigator & { keyboard?: KeyboardLayoutSource }).keyboard, + focusTarget: EventTarget | undefined = typeof window === "undefined" ? undefined : window, +) { + let revision = 0; + const refresh = async (clearMap: boolean) => { + const request = ++revision; + if (clearMap) keyboardLayoutMap = undefined; + try { + const layout = await keyboard?.getLayoutMap(); + if (request === revision) keyboardLayoutMap = layout; + } catch { + // Unsupported or permission-blocked browsers keep the existing fallback. + if (request === revision) keyboardLayoutMap = undefined; + } + }; + const onLayoutChange = () => void refresh(true); + const onFocus = () => void refresh(false); + void refresh(true); + keyboard?.addEventListener?.("layoutchange", onLayoutChange); + focusTarget?.addEventListener("focus", onFocus); + return () => { + revision++; + keyboardLayoutMap = undefined; + keyboard?.removeEventListener?.("layoutchange", onLayoutChange); + focusTarget?.removeEventListener("focus", onFocus); + }; +} diff --git a/apps/web/src/lib/preserveReadingPosition.ts b/apps/web/src/lib/preserveReadingPosition.ts new file mode 100644 index 0000000000000..2c6f576519911 --- /dev/null +++ b/apps/web/src/lib/preserveReadingPosition.ts @@ -0,0 +1,115 @@ +import { observeResize } from "./observeResize"; + +/** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */ +export function preserveReadingPosition( + scroller: HTMLElement, + enabled: () => boolean = () => true, +): () => void { + let width = scroller.clientWidth; + let anchor: { range: Range; top: number } | null = null; + let frame: number | null = null; + + const capture = () => { + if (frame !== null || scroller.clientWidth !== width) return; + anchor = null; + if (!enabled() || scroller.scrollTop === 0) return; + const box = scroller.getBoundingClientRect(); + const selection = + scroller.isContentEditable && document.activeElement === scroller + ? document.getSelection() + : null; + if (selection?.isCollapsed && selection.rangeCount > 0) { + const range = selection.getRangeAt(0).cloneRange(); + const rect = range.getBoundingClientRect(); + if ( + scroller.contains(range.startContainer) && + rect.top >= box.top && + rect.bottom <= box.bottom + ) { + anchor = { range, top: rect.top - box.top }; + return; + } + } + // A point near the top captures text rather than the paragraph's bounding box. + const x = box.left + box.width / 2; + // The first point can land in paragraph spacing. Look only within the first few lines. + for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) { + const y = box.top + inset; + const position = document.caretPositionFromPoint?.(x, y); + const range = document.createRange(); + if (position) { + range.setStart(position.offsetNode, position.offset); + } else { + const fallback = document.caretRangeFromPoint?.(x, y); + if (!fallback) continue; + range.setStart(fallback.startContainer, fallback.startOffset); + } + range.collapse(true); + if ( + !scroller.contains(range.startContainer) || + range.startContainer.nodeType !== Node.TEXT_NODE + ) + continue; + const top = range.getBoundingClientRect().top - box.top; + if (top >= 0 && top < scroller.clientHeight) { + anchor = { range, top }; + break; + } + } + }; + const restore = () => { + if ( + !enabled() || + !anchor || + anchor.range.startContainer.nodeType !== Node.TEXT_NODE || + !scroller.contains(anchor.range.startContainer) + ) + return; + const delta = + anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top; + if (Math.abs(delta) > 0.5) scroller.scrollTop += delta; + }; + const stop = observeResize(scroller, () => { + const nextWidth = scroller.clientWidth; + if (nextWidth === width) { + capture(); + return; + } + width = nextWidth; + restore(); + if (frame !== null) cancelAnimationFrame(frame); + // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then. + frame = requestAnimationFrame(() => { + restore(); + frame = null; + capture(); + }); + }); + scroller.addEventListener("scroll", capture, { passive: true }); + scroller.addEventListener("input", capture); + const captureSelection = () => { + if (document.activeElement === scroller) capture(); + }; + if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection); + const interrupt = () => { + if (frame !== null) cancelAnimationFrame(frame); + anchor = null; + // Scrolling wins over a pending resize correction; the next frame captures the reader's new place. + frame = requestAnimationFrame(() => { + frame = null; + width = scroller.clientWidth; + capture(); + }); + }; + scroller.addEventListener("wheel", interrupt, { passive: true }); + scroller.addEventListener("touchmove", interrupt, { passive: true }); + return () => { + stop(); + if (frame !== null) cancelAnimationFrame(frame); + scroller.removeEventListener("scroll", capture); + scroller.removeEventListener("input", capture); + document.removeEventListener("selectionchange", captureSelection); + scroller.removeEventListener("wheel", interrupt); + scroller.removeEventListener("touchmove", interrupt); + }; +} diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts index 0baba982decfb..457c6cea47380 100644 --- a/apps/web/src/localApi.ts +++ b/apps/web/src/localApi.ts @@ -57,7 +57,7 @@ export function createLocalApi(): LocalApi { if (window.desktopBridge) { return window.desktopBridge.showContextMenu(items, position, source) as Promise; } - return showContextMenuFallback(items, position); + return showContextMenuFallback(items, position, source); }, // Unlike native menus, the DOM fallback needs dismissal when underlying state disappears. close: async () => { diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 51aeeade6863d..2640ca1e167d0 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -4,6 +4,7 @@ import ReactDOM from "react-dom/client"; import "@fontsource-variable/inter"; import "./index.css"; +import { trackKeyboardLayout } from "./keyboardLayout"; import { hasCloudPublicConfig } from "./cloud/publicConfig"; import { isElectron } from "./env"; import { startAppServices } from "./appInit"; @@ -11,6 +12,9 @@ import { AppRoot } from "./AppRoot"; import { whenLocaleReady } from "./i18n/runtime"; import { chunkLoadState } from "./lib/chunkReloadGuard"; +const stopTrackingKeyboardLayout = trackKeyboardLayout(); +import.meta.hot?.dispose(stopTrackingKeyboardLayout); + const router = startAppServices(); const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined; diff --git a/apps/web/src/markdown/wordsHast.ts b/apps/web/src/markdown/wordsHast.ts index 6b91c4c45e5d9..3231c2acf3e3b 100644 --- a/apps/web/src/markdown/wordsHast.ts +++ b/apps/web/src/markdown/wordsHast.ts @@ -1,8 +1,10 @@ import type { Element, ElementContent, Root, Text } from "hast"; import { + init as initWords, renderToHtml as wordsRenderToHtml, type RenderOptions as WordsRenderOptions, -} from "@pierre/words"; +} from "@pierre/words/core"; +import wordsWasm from "@pierre/words/wasm"; import { decodeHTML, decodeHTMLAttribute } from "entities"; import { find, html as htmlSchema, svg as svgSchema } from "property-information"; import { resolveCodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates"; @@ -93,6 +95,11 @@ type RenderOptions = Omit; const decoder = new TextDecoder(); const encoder = new TextEncoder(); +// Browsers can disable WebAssembly (JIT off by policy, CSP); renderToHtml then falls back below. +try { + initWords(new WebAssembly.Module(wordsWasm)); +} catch {} + function renderToHtml(markdown: string, options: RenderOptions): Uint8Array { try { return wordsRenderToHtml(markdown, options); diff --git a/apps/web/src/markdown/wordsWasm.d.ts b/apps/web/src/markdown/wordsWasm.d.ts new file mode 100644 index 0000000000000..b718ec11d2be5 --- /dev/null +++ b/apps/web/src/markdown/wordsWasm.d.ts @@ -0,0 +1,4 @@ +declare module "@pierre/words/wasm" { + const bytes: Uint8Array; + export default bytes; +} diff --git a/apps/web/src/remoteOpen.test.ts b/apps/web/src/remoteOpen.test.ts index 12149f98af238..e16e5d0bbe1a3 100644 --- a/apps/web/src/remoteOpen.test.ts +++ b/apps/web/src/remoteOpen.test.ts @@ -1,9 +1,13 @@ import { + BearerConnectionProfile, + BearerConnectionTarget, PrimaryConnectionTarget, RelayConnectionTarget, + SshConnectionProfile, SshConnectionTarget, } from "@t3tools/client-runtime/connection"; import { buildRemoteOpenUrl, EnvironmentId } from "@t3tools/contracts"; +import * as Option from "effect/Option"; import { describe, expect, it } from "vite-plus/test"; import { remoteFallbackEditors, resolveRemoteOpenState } from "./remoteOpen"; @@ -18,6 +22,18 @@ const primaryTarget = (httpBaseUrl: string) => wsBaseUrl: httpBaseUrl.replace("http", "ws"), }); +const sshRoute = (target: { readonly alias: string; readonly username: string | null }) => ({ + target: new SshConnectionTarget({ environmentId, label: "sol", connectionId: "ssh-1" }), + profile: Option.some( + new SshConnectionProfile({ + connectionId: "ssh-1", + environmentId, + label: "sol", + target: { ...target, hostname: "sol.tail1234.ts.net", port: null }, + }), + ), +}); + const TAILSCALE_TARGETS = [ { kind: "tailscale", host: "sol.tail1234.ts.net" }, { kind: "mdns", host: "sol.local" }, @@ -28,7 +44,7 @@ describe("resolveRemoteOpenState", () => { expect( resolveRemoteOpenState({ target: primaryTarget("http://127.0.0.1:8000"), - sshTarget: null, + routes: [], isDesktopRenderer: false, remoteOpenTargets: TAILSCALE_TARGETS, hostEnvironmentId: null, @@ -40,7 +56,7 @@ describe("resolveRemoteOpenState", () => { expect( resolveRemoteOpenState({ target: primaryTarget("https://sol.tail1234.ts.net"), - sshTarget: null, + routes: [], isDesktopRenderer: false, remoteOpenTargets: TAILSCALE_TARGETS, hostEnvironmentId: null, @@ -56,7 +72,7 @@ describe("resolveRemoteOpenState", () => { expect( resolveRemoteOpenState({ target: primaryTarget("http://172.29.112.1:14369"), - sshTarget: null, + routes: [], isDesktopRenderer: true, remoteOpenTargets: TAILSCALE_TARGETS, hostEnvironmentId: null, @@ -70,7 +86,7 @@ describe("resolveRemoteOpenState", () => { expect( resolveRemoteOpenState({ target: new RelayConnectionTarget({ environmentId, label: "sol" }), - sshTarget: null, + routes: [], isDesktopRenderer: true, remoteOpenTargets: TAILSCALE_TARGETS, hostEnvironmentId: environmentId, @@ -82,7 +98,7 @@ describe("resolveRemoteOpenState", () => { expect( resolveRemoteOpenState({ target: new RelayConnectionTarget({ environmentId, label: "sol" }), - sshTarget: null, + routes: [], isDesktopRenderer: true, remoteOpenTargets: TAILSCALE_TARGETS, hostEnvironmentId: EnvironmentId.make("environment-host"), @@ -96,7 +112,7 @@ describe("resolveRemoteOpenState", () => { it("leaves a bare desktop SSH alias for the editor to resolve through SSH config", () => { const state = resolveRemoteOpenState({ target: new SshConnectionTarget({ environmentId, label: "sol", connectionId: "ssh-1" }), - sshTarget: { alias: "sol", username: null }, + routes: [sshRoute({ alias: "sol", username: null })], isDesktopRenderer: true, remoteOpenTargets: [ { kind: "tailscale", host: "sol.tail1234.ts.net", username: "server-user" }, @@ -107,7 +123,7 @@ describe("resolveRemoteOpenState", () => { if (state.mode !== "remote-links") throw new Error("Expected a remote link"); expect( buildRemoteOpenUrl({ editor: "vscode", ...state.host, absolutePath: "/work/project" }), - ).toBe("vscode://vscode-remote/ssh-remote+sol/work/project"); + ).toBe("vscode://vscode-remote/ssh-remote+sol/work/project?windowId=_blank"); expect( buildRemoteOpenUrl({ editor: "zed", ...state.host, absolutePath: "/work/project" }), ).toBe("zed://ssh/sol/work/project"); @@ -127,7 +143,7 @@ describe("resolveRemoteOpenState", () => { ])("keeps one login username in editor links for $alias (username: '$username')", (sshTarget) => { const state = resolveRemoteOpenState({ target: new SshConnectionTarget({ environmentId, label: "server", connectionId: "ssh-1" }), - sshTarget, + routes: [sshRoute(sshTarget)], isDesktopRenderer: true, remoteOpenTargets: TAILSCALE_TARGETS, hostEnvironmentId: null, @@ -136,7 +152,7 @@ describe("resolveRemoteOpenState", () => { if (state.mode !== "remote-links") throw new Error("Expected a remote link"); expect( buildRemoteOpenUrl({ editor: "vscode", ...state.host, absolutePath: "/work/project" }), - ).toBe("vscode://vscode-remote/ssh-remote+admin-user%40server/work/project"); + ).toBe("vscode://vscode-remote/ssh-remote+admin-user%40server/work/project?windowId=_blank"); expect( buildRemoteOpenUrl({ editor: "zed", ...state.host, absolutePath: "/work/project" }), ).toBe("zed://ssh/admin-user@server/work/project"); @@ -150,7 +166,7 @@ describe("resolveRemoteOpenState", () => { it("uses the advertised login username in editor links over a relay", () => { const state = resolveRemoteOpenState({ target: new RelayConnectionTarget({ environmentId, label: "server" }), - sshTarget: null, + routes: [], isDesktopRenderer: false, remoteOpenTargets: [ { kind: "tailscale", host: "server.tail1234.ts.net", username: "admin-user" }, @@ -161,7 +177,9 @@ describe("resolveRemoteOpenState", () => { if (state.mode !== "remote-links") throw new Error("Expected a remote link"); expect( buildRemoteOpenUrl({ editor: "cursor", ...state.host, absolutePath: "/work/project" }), - ).toBe("cursor://vscode-remote/ssh-remote+admin-user%40server.tail1234.ts.net/work/project"); + ).toBe( + "cursor://vscode-remote/ssh-remote+admin-user%40server.tail1234.ts.net/work/project?windowId=_blank", + ); }); it("reports unavailable when a remote environment advertises no hosts", () => { @@ -169,7 +187,7 @@ describe("resolveRemoteOpenState", () => { expect( resolveRemoteOpenState({ target: new RelayConnectionTarget({ environmentId, label: "sol" }), - sshTarget: null, + routes: [], isDesktopRenderer: false, remoteOpenTargets, hostEnvironmentId: null, @@ -177,6 +195,42 @@ describe("resolveRemoteOpenState", () => { ).toEqual({ mode: "remote-unavailable" }); } }); + it("uses a saved SSH route's alias when a Tailscale route is preferred", () => { + const target = new BearerConnectionTarget({ + environmentId, + label: "sol", + connectionId: "ts-1", + }); + const state = resolveRemoteOpenState({ + target, + routes: [ + { + target, + profile: Option.some( + new BearerConnectionProfile({ + connectionId: "ts-1", + environmentId, + label: "sol", + httpBaseUrl: "https://sol.tail1234.ts.net", + wsBaseUrl: "wss://sol.tail1234.ts.net", + network: "tailscale", + }), + ), + }, + sshRoute({ alias: "sol-alias", username: null }), + ], + isDesktopRenderer: false, + remoteOpenTargets: [ + { kind: "tailscale", host: "sol.tail1234.ts.net", username: "server-user" }, + ], + hostEnvironmentId: null, + }); + expect(state).toEqual({ mode: "remote-links", host: { kind: "ssh-alias", host: "sol-alias" } }); + if (state.mode !== "remote-links") throw new Error("Expected a remote link"); + expect( + buildRemoteOpenUrl({ editor: "zed", ...state.host, absolutePath: "/work/project" }), + ).toBe("zed://ssh/sol-alias/work/project"); + }); }); describe("remoteFallbackEditors", () => { @@ -223,7 +277,7 @@ describe("buildRemoteOpenUrl", () => { it("roots Windows paths", () => { expect( buildRemoteOpenUrl({ editor: "vscode", host: "sol", absolutePath: "C:\\Users\\theo" }), - ).toBe("vscode://vscode-remote/ssh-remote+sol/C%3A/Users/theo"); + ).toBe("vscode://vscode-remote/ssh-remote+sol/C%3A/Users/theo?windowId=_blank"); }); it("keeps a plus in the SSH username through Remote-SSH's authority parsing", () => { @@ -250,6 +304,16 @@ describe("buildRemoteOpenUrl", () => { }); }); + it("asks VS Code to open a remote project folder in a new window", () => { + // Without windowId=_blank, VS Code reuses (and replaces) the last active window. + const url = buildRemoteOpenUrl({ + editor: "vscode", + host: "sol", + absolutePath: "/work/project", + }); + expect(new URL(url ?? "").searchParams.get("windowId")).toBe("_blank"); + }); + it("drops the Windows drive letter for Zed", () => { expect( buildRemoteOpenUrl({ editor: "zed", host: "sol", absolutePath: "C:\\Users\\theo" }), @@ -263,8 +327,12 @@ describe("buildRemoteOpenUrl", () => { const targets = [ ["vscode", true, "vscode://vscode-remote/ssh-remote+sol/tmp/my%20file.md:1:1"], ["cursor", true, "cursor://vscode-remote/ssh-remote+sol/tmp/my%20file.md:1:1"], - ["vscode", false, "vscode://vscode-remote/ssh-remote+sol/tmp/my%20file.md"], - ["vscode", undefined, "vscode://vscode-remote/ssh-remote+sol/tmp/my%20file.md"], + ["vscode", false, "vscode://vscode-remote/ssh-remote+sol/tmp/my%20file.md?windowId=_blank"], + [ + "vscode", + undefined, + "vscode://vscode-remote/ssh-remote+sol/tmp/my%20file.md?windowId=_blank", + ], ["zed", true, "zed://ssh/sol/tmp/my%20file.md"], [ "pycharm", diff --git a/apps/web/src/remoteOpen.ts b/apps/web/src/remoteOpen.ts index a62b203663f07..da76b2b595606 100644 --- a/apps/web/src/remoteOpen.ts +++ b/apps/web/src/remoteOpen.ts @@ -1,4 +1,8 @@ -import type { ConnectionTarget } from "@t3tools/client-runtime/connection"; +import { + connectionRoutes, + type ConnectionRoute, + type ConnectionTarget, +} from "@t3tools/client-runtime/connection"; import { REMOTE_CAPABLE_EDITOR_IDS, type EditorId, @@ -50,9 +54,20 @@ function parseHostname(url: string): string | null { } } +function firstSshTarget(routes: ReadonlyArray) { + for (const route of routes) { + const profile = Option.getOrNull(route.profile); + if (profile?._tag === "SshConnectionProfile" && profile.target.alias.length > 0) { + return profile.target; + } + } + return null; +} + export function resolveRemoteOpenState(input: { readonly target: ConnectionTarget | null; - readonly sshTarget: { readonly alias: string; readonly username: string | null } | null; + /** The environment's saved routes, preferred route first. */ + readonly routes: ReadonlyArray; readonly remoteOpenTargets: ReadonlyArray | undefined; readonly isDesktopRenderer: boolean; readonly hostEnvironmentId: string | null; @@ -74,13 +89,13 @@ export function resolveRemoteOpenState(input: { return LOCAL_EXEC; } - if (input.sshTarget !== null && input.sshTarget.alias.length > 0) { - const { alias } = input.sshTarget; + const sshTarget = firstSshTarget(input.routes); + if (sshTarget !== null) { + const { alias } = sshTarget; const userSeparator = alias.lastIndexOf("@"); const host = userSeparator === -1 ? alias : alias.slice(userSeparator + 1); const username = - input.sshTarget.username?.trim() || - (userSeparator === -1 ? null : alias.slice(0, userSeparator)); + sshTarget.username?.trim() || (userSeparator === -1 ? null : alias.slice(0, userSeparator)); return { mode: "remote-links", host: { @@ -115,12 +130,10 @@ const remoteOpenResolutionAtom = Atom.family((environmentId: EnvironmentId) => if (entry === null) { return UNRESOLVED_REMOTE_OPEN; } - const profile = Option.getOrNull(entry.profile); const next: RemoteOpenResolution = { state: resolveRemoteOpenState({ target: entry.target, - sshTarget: - profile !== null && profile._tag === "SshConnectionProfile" ? profile.target : null, + routes: connectionRoutes(entry), remoteOpenTargets: presentation?.serverConfig?.remoteOpenTargets, isDesktopRenderer: window.desktopBridge !== undefined, hostEnvironmentId: get(hostEnvironmentIdAtom), diff --git a/apps/web/src/shortcuts/chatRouteCommands.test.ts b/apps/web/src/shortcuts/chatRouteCommands.test.ts index 3979368ff9032..db332610cd923 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.test.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.test.ts @@ -105,4 +105,21 @@ describe("preview commands", () => { expect(dispatch).toHaveBeenCalledWith(action); }); + + it("preview.find leaves the key unclaimed on non-thread chat routes", () => { + using dispatch = vi.spyOn(previewActions, "dispatchPreviewAction").mockImplementation(() => {}); + using register = vi.spyOn(dispatcher, "registerCommands").mockReturnValue(() => {}); + const router = { + state: { matches: [{ routeId: "/_chat/pull-requests", params: {} }] }, + } as unknown as AnyRouter; + using stack = new DisposableStack(); + stack.defer(installChatRouteCommands(router)); + const event = { preventDefault: vi.fn(), stopPropagation: vi.fn() } as unknown as KeyboardEvent; + + const result = register.mock.calls[0]![0]["preview.find"]!(event); + + expect(result).toBe(false); + expect(event.preventDefault).not.toHaveBeenCalled(); + expect(dispatch).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/shortcuts/chatRouteCommands.ts b/apps/web/src/shortcuts/chatRouteCommands.ts index 7cca45fbd81db..90ccf9fc2023f 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.ts @@ -186,7 +186,13 @@ export function installChatRouteCommands(router: AnyRouter): () => void { "preview.zoomIn": zoomCommand("zoom-in"), "preview.zoomOut": zoomCommand("zoom-out"), "preview.resetZoom": zoomCommand("reset-zoom"), - "preview.find": previewCommand("find"), + // Unclaimed, the browser's own find runs when no thread handles panel find. + "preview.find": (event) => { + const environmentId = readRouteEnvironmentId(); + if (!environmentId || !canOperatePreview(environmentId)) return false; + claim(event); + dispatchPreviewAction("find"); + }, }, { when: () => diff --git a/apps/web/src/speech/useDictationShortcut.browser.test.tsx b/apps/web/src/speech/useDictationShortcut.browser.test.tsx index 8530391cd7f60..7c6ee410cfb03 100644 --- a/apps/web/src/speech/useDictationShortcut.browser.test.tsx +++ b/apps/web/src/speech/useDictationShortcut.browser.test.tsx @@ -179,6 +179,32 @@ it("lets Escape in another editor of the recording editor's dialog reach that ed expect(speech.cancel).not.toHaveBeenCalled(); }); +it("lets Escape close a modal opened over the recording before canceling it", async () => { + const speech = recording(); + const closeImage = vi.fn(); + await using screen = await render( + <> + +
{ + if (event.key === "Escape") closeImage(); + }} + > + +
+ , + ); + const close = screen.getByRole("button", { name: "Close" }).element(); + if (!(close instanceof HTMLElement)) throw new Error("expected the image dialog's button"); + close.focus(); + close.dispatchEvent(escape()); + expect(speech.cancel).not.toHaveBeenCalled(); + expect(closeImage).toHaveBeenCalledTimes(1); +}); + it("cancels the recording on Escape outside other shown dictation editors", async () => { const speech = recording(); const reviewRef = createRef(); diff --git a/apps/web/src/speech/useDictationShortcut.ts b/apps/web/src/speech/useDictationShortcut.ts index 155a6efd68585..72c0fb7bae7f4 100644 --- a/apps/web/src/speech/useDictationShortcut.ts +++ b/apps/web/src/speech/useDictationShortcut.ts @@ -66,7 +66,8 @@ const targetScope = (field: HTMLElement | null | undefined) => // Keys an outside editor (the preview guest) relays arrive on window, so remember their editor. const relayedFrom = new WeakMap(); -// Escape inside another shown dictation editor, or the dialog hosting it, belongs to that editor. +// Escape inside another shown dictation editor, or the dialog hosting it, belongs to that editor; +// Escape inside any other dialog belongs to that dialog, so it closes before dictation cancels. // The editor itself is checked before dialogs, since one dialog can host several editors. function inOtherShortcutTarget(id: symbol, event: Event) { const source = relayedFrom.get(event); @@ -82,7 +83,10 @@ function inOtherShortcutTarget(id: symbol, event: Event) { if (scope(own)?.contains(target)) return false; if (others.some((field) => scope(field)?.contains(target))) return true; } - return false; + const dialog = (target instanceof Element ? target : target.parentElement)?.closest( + '[role="dialog"]', + ); + return !!dialog && !dialog.contains(own ?? null); } export function useDictationShortcut(input: ShortcutInput) { diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index 4194e07834811..ee8e03493b6fd 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -44,7 +44,10 @@ export function useLinkedThreadOpener( const viaEnvironmentId = panelRef.environmentId; const own = useEnvironment(thread?.environmentId ?? null); const connected = own?.connection.phase === "connected"; - const links = useLinkedEnvironments(thread === undefined || connected ? null : viaEnvironmentId); + const links = useLinkedEnvironments( + thread === undefined || connected ? null : viaEnvironmentId, + thread?.environmentId, + ); if (thread === undefined) return null; const resolved = resolveLinkedThreadOpen({ environmentId: thread.environmentId, diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.ts index ab1d30a2791f8..698cb9802dff8 100644 --- a/apps/web/src/state/peerLinks.ts +++ b/apps/web/src/state/peerLinks.ts @@ -1,4 +1,4 @@ -import { useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { linkableMachines, linkedEnvironmentNames, @@ -12,7 +12,7 @@ import { import { AuthAccessReadScope, AuthAccessWriteScope, type EnvironmentId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { Atom } from "effect/reactivity"; -import { useEffect, useEffectEvent } from "react"; +import { useContext, useEffect, useEffectEvent } from "react"; import { useNowMinute } from "../hooks/useNowMinute"; import { connectionAtomRuntime } from "../connection/runtime"; @@ -43,9 +43,11 @@ const offersNoLinksAtom = Atom.make(false).pipe(Atom.withLabel("peer-links:offer /** * The machines `environmentId` links to, by name, while it offers links, and none otherwise. * Its agents can read threads there, and so can a client allowed to read threads on it. + * A `wanted` machine the names lack makes them reread. */ export function useLinkedEnvironments( environmentId: EnvironmentId | null, + wanted?: EnvironmentId, ): ReadonlyMap { const offered = useAtomValue( environmentId === null ? offersNoLinksAtom : offersLinkedEnvironmentsAtom(environmentId), @@ -56,6 +58,13 @@ export function useLinkedEnvironments( ? peerLinkEnvironment.names({ environmentId, input: {} }) : null, ); + const registry = useContext(RegistryContext); + const queried = offered ? environmentId : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links made outside this client are not pushed, so meeting an unknown machine asks the server again + useEffect(() => { + if (queried === null || wanted === undefined) return; + peerLinkEnvironment.refreshNamesLacking(registry, queried, [wanted]); + }, [registry, queried, wanted]); return linkedEnvironmentNames({ links: offered ? (links.data?.links ?? []) : [], environments: identities, diff --git a/apps/web/src/state/portForwards.test.ts b/apps/web/src/state/portForwards.test.ts new file mode 100644 index 0000000000000..f017dfcf47507 --- /dev/null +++ b/apps/web/src/state/portForwards.test.ts @@ -0,0 +1,41 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { Atom, AtomRegistry } from "effect/reactivity"; +import * as AsyncResult from "effect/reactivity/AsyncResult"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +vi.mock("./session", () => ({ + environmentSession: { + transportSessionAtom: () => Atom.make(AsyncResult.success(Option.some({}))), + }, +})); + +const { forwardLocalitiesAtom } = await import("./portForwards"); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe("forward locality", () => { + it("probes again after a failed probe instead of staying unknown", async () => { + vi.useFakeTimers(); + const sharesLoopback = vi + .fn<() => Promise>() + .mockRejectedValueOnce(new Error("tunnel dial refused")) + .mockResolvedValue(false); + vi.stubGlobal("window", { desktopBridge: { preview: { sharesLoopback } } }); + const registry = AtomRegistry.make(); + const environmentId = EnvironmentId.make("env-remote"); + const atom = forwardLocalitiesAtom(JSON.stringify([environmentId])); + const unmount = registry.mount(atom); + + await vi.advanceTimersByTimeAsync(0); + expect(sharesLoopback).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1_000); + + expect(sharesLoopback).toHaveBeenCalledTimes(2); + expect(registry.get(atom)).toEqual(["remote"]); + unmount(); + }); +}); diff --git a/apps/web/src/state/portForwards.ts b/apps/web/src/state/portForwards.ts index 477ad39885adb..5fa3b9db5b2c4 100644 --- a/apps/web/src/state/portForwards.ts +++ b/apps/web/src/state/portForwards.ts @@ -4,9 +4,11 @@ import { type DesktopPortForward, type EnvironmentId, } from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; +import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as AsyncResult from "effect/reactivity/AsyncResult"; @@ -78,6 +80,13 @@ class PortForwardLocalityError extends Schema.TaggedError + Effect.succeed(Duration.min(duration, Duration.seconds(30))), + ), +); + const localityResultAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get) => { // Each established connection probes anew, so a failed probe never outlives a reconnect. @@ -90,7 +99,10 @@ const localityResultAtom = Atom.family((environmentId: EnvironmentId) => return Effect.tryPromise({ try: () => bridge.sharesLoopback(environmentId), catch: (cause) => new PortForwardLocalityError({ environmentId, cause }), - }).pipe(Effect.map((shares): ForwardLocality => (shares ? "local" : "remote"))); + }).pipe( + Effect.retry(LOCALITY_RETRY_SCHEDULE), + Effect.map((shares): ForwardLocality => (shares ? "local" : "remote")), + ); }).pipe( Atom.setIdleTTL(10 * 60_000), Atom.withLabel(`desktop:port-forward-locality-probe:${environmentId}`), diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.ts index 7c8a61dda18e6..650ca55511ff4 100644 --- a/apps/web/src/terminal/ghostty/surface.test.ts +++ b/apps/web/src/terminal/ghostty/surface.test.ts @@ -308,6 +308,26 @@ describe("GhosttyTerminalSurface visibility", () => { expect(harness.onData).not.toHaveBeenCalled(); }); + it("sends nothing for Ctrl+Shift+C or Ctrl+Insert without a selection but keeps Ctrl+C", async () => { + vi.stubGlobal("navigator", { platform: "Linux x86_64" }); + const harness = createHarness(); + const surface = await harness.create({ beforeKey: () => true }); + key(surface, "C", "KeyC", { ctrlKey: true, shiftKey: true }); + key(surface, "Insert", "Insert", { ctrlKey: true }); + expect(harness.onData).not.toHaveBeenCalled(); + key(surface, "c", "KeyC", { ctrlKey: true }); + key(surface, "Insert", "Insert", { ctrlKey: true, altKey: true }); + expect(harness.onData.mock.calls.map(([data]) => data)).toEqual(["\x03", "\x1b[2;7~"]); + }); + + it("sends nothing for Cmd+C on macOS without a selection", async () => { + vi.stubGlobal("navigator", { platform: "MacIntel" }); + const harness = createHarness(); + const surface = await harness.create({ beforeKey: () => true }); + key(surface, "c", "KeyC", { metaKey: true }); + expect(harness.onData).not.toHaveBeenCalled(); + }); + it("skips middle-click selection paste when the desktop turned primary paste off", async () => { vi.stubGlobal("navigator", { platform: "Linux x86_64" }); const harness = createHarness(); diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts index 2e450cff91fb7..27ead0154efea 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -1185,6 +1185,15 @@ export class GhosttyTerminalSurface { } return; } + const copyChord = + primaryModifier && + !event.altKey && + (mac ? !event.shiftKey : event.shiftKey || event.key.toLowerCase() === "insert"); + if (copyChord && isTerminalCopyShortcut(event)) { + event.preventDefault(); + event.stopPropagation(); + return; + } if (isTerminalPasteShortcut(event)) { const gesture = { code: event.code, readText: "" }; this.pasteShortcutGesture = gesture; diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 804757e78307a..5205d37ae3048 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -21,7 +21,6 @@ function makeUiState(overrides: Partial = {}): UiState { projectOrder: [], sidebarProjectScopeKeys: [], threadLastVisitedAtById: {}, - threadChangedFilesExpandedById: {}, defaultAdvertisedEndpointKey: null, pullRequestMergeMethod: "merge", ...overrides, @@ -107,13 +106,6 @@ describe("parsePersistedState", () => { invalid: "not-a-date", }, defaultAdvertisedEndpointKey: "desktop-core:lan:http", - threadChangedFilesExpansionVersion: 2, - threadChangedFilesExpandedById: { - "environment:thread-1": { - "turn-1": false, - "turn-2": true, - }, - }, }); expect(parsed).toEqual({ @@ -127,12 +119,6 @@ describe("parsePersistedState", () => { defaultAdvertisedEndpointKey: "desktop-core:lan:http", sidebarProjectScopeKeys: [], pullRequestMergeMethod: "merge", - threadChangedFilesExpandedById: { - "environment:thread-1": { - "turn-1": false, - "turn-2": true, - }, - }, }); }); @@ -142,19 +128,6 @@ describe("parsePersistedState", () => { ).toBe("fast-forward"); }); - it.each([undefined, 1])("ignores changed-file expansion version %s", (version) => { - const parsed = parsePersistedState({ - ...(version === undefined ? {} : { threadChangedFilesExpansionVersion: version }), - threadChangedFilesExpandedById: { - "environment:thread-1": { - "turn-1": false, - }, - }, - }); - - expect(parsed.threadChangedFilesExpandedById).toEqual({}); - }); - it("migrates legacy CWD project preferences into local alias keys", () => { const parsed = parsePersistedState({ collapsedProjectCwds: ["/repo/b"], @@ -213,12 +186,6 @@ describe("uiStateStore persistence", () => { threadLastVisitedAtById: { "environment:thread-1": "2026-02-25T12:35:00.000Z", }, - threadChangedFilesExpandedById: { - "environment:thread-1": { - "turn-1": false, - "turn-2": true, - }, - }, defaultAdvertisedEndpointKey: "desktop-core:lan:http", }); @@ -238,13 +205,6 @@ describe("uiStateStore persistence", () => { defaultAdvertisedEndpointKey: "desktop-core:lan:http", sidebarProjectScopeKeys: [], sidebarProjectScopeKey: null, - threadChangedFilesExpansionVersion: 2, - threadChangedFilesExpandedById: { - "environment:thread-1": { - "turn-1": false, - "turn-2": true, - }, - }, pullRequestMergeMethod: "merge", }); expect(parsePersistedState(persisted)).toEqual({ diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index b2ac1a508c7a6..38512d0659453 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -5,7 +5,6 @@ import { create } from "zustand"; import { normalizeProjectPathForComparison } from "@t3tools/client-runtime/state/projects"; export const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; -const THREAD_CHANGED_FILES_EXPANSION_VERSION = 2; const LEGACY_PERSISTED_STATE_KEYS = [ "t3code:renderer-state:v8", "t3code:renderer-state:v7", @@ -29,8 +28,6 @@ export interface PersistedUiState { defaultAdvertisedEndpointKey?: string | null; sidebarProjectScopeKey?: string | null; sidebarProjectScopeKeys?: string[]; - threadChangedFilesExpansionVersion?: number; - threadChangedFilesExpandedById?: Record>; pullRequestMergeMethod?: string; } @@ -42,7 +39,6 @@ export interface UiProjectState { export interface UiThreadState { threadLastVisitedAtById: Record; - threadChangedFilesExpandedById: Record>; } export interface UiEndpointState { @@ -61,7 +57,6 @@ const initialState: UiState = { projectOrder: [], sidebarProjectScopeKeys: [], threadLastVisitedAtById: {}, - threadChangedFilesExpandedById: {}, defaultAdvertisedEndpointKey: null, pullRequestMergeMethod: "merge", }; @@ -145,10 +140,6 @@ export function parsePersistedState(parsed: PersistedUiState): UiState { projectExpandedById, projectOrder, threadLastVisitedAtById: sanitizeTimestampRecord(parsed.threadLastVisitedAtById), - threadChangedFilesExpandedById: - parsed.threadChangedFilesExpansionVersion === THREAD_CHANGED_FILES_EXPANSION_VERSION - ? sanitizePersistedThreadChangedFilesExpanded(parsed.threadChangedFilesExpandedById) - : {}, defaultAdvertisedEndpointKey: sanitizeOptionalKey(parsed.defaultAdvertisedEndpointKey), sidebarProjectScopeKeys: sanitizeStringArray( parsed.sidebarProjectScopeKeys ?? [parsed.sidebarProjectScopeKey], @@ -181,34 +172,6 @@ function readPersistedState(): UiState { } } -function sanitizePersistedThreadChangedFilesExpanded( - value: PersistedUiState["threadChangedFilesExpandedById"], -): Record> { - if (!value || typeof value !== "object") { - return {}; - } - - const nextState: Record> = {}; - for (const [threadId, turns] of Object.entries(value)) { - if (!threadId || !turns || typeof turns !== "object") { - continue; - } - - const nextTurns: Record = {}; - for (const [turnId, expanded] of Object.entries(turns)) { - if (turnId && typeof expanded === "boolean") { - nextTurns[turnId] = expanded; - } - } - - if (Object.keys(nextTurns).length > 0) { - nextState[threadId] = nextTurns; - } - } - - return nextState; -} - export function persistState(state: UiState): void { if (typeof window === "undefined") { return; @@ -227,8 +190,6 @@ export function persistState(state: UiState): void { state.sidebarProjectScopeKeys.length === 1 ? (state.sidebarProjectScopeKeys[0] ?? null) : null, - threadChangedFilesExpansionVersion: THREAD_CHANGED_FILES_EXPANSION_VERSION, - threadChangedFilesExpandedById: state.threadChangedFilesExpandedById, pullRequestMergeMethod: state.pullRequestMergeMethod, } satisfies PersistedUiState), ); @@ -291,29 +252,6 @@ export function markThreadUnread( }; } -function setThreadChangedFilesExpanded( - state: UiState, - threadId: string, - turnId: string, - expanded: boolean, -): UiState { - const currentThreadState = state.threadChangedFilesExpandedById[threadId] ?? {}; - if (currentThreadState[turnId] === expanded) { - return state; - } - - return { - ...state, - threadChangedFilesExpandedById: { - ...state.threadChangedFilesExpandedById, - [threadId]: { - ...currentThreadState, - [turnId]: expanded, - }, - }, - }; -} - function setDefaultAdvertisedEndpointKey(state: UiState, key: string | null): UiState { const nextKey = key && key.length > 0 ? key : null; if (state.defaultAdvertisedEndpointKey === nextKey) { @@ -425,7 +363,6 @@ export function reorderProjects( interface UiStateStore extends UiState { markThreadVisited: (threadId: string, visitedAt: string) => void; markThreadUnread: (threadId: string, latestTurnCompletedAt: string | null | undefined) => void; - setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void; setDefaultAdvertisedEndpointKey: (key: string | null) => void; setSidebarProjectScopeKeys: (projectKeys: readonly string[]) => void; setPullRequestMergeMethod: (method: PullRequestMergeMethod) => void; @@ -443,8 +380,6 @@ export const useUiStateStore = create((set) => ({ set((state) => markThreadVisited(state, threadId, visitedAt)), markThreadUnread: (threadId, latestTurnCompletedAt) => set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)), - setThreadChangedFilesExpanded: (threadId, turnId, expanded) => - set((state) => setThreadChangedFilesExpanded(state, threadId, turnId, expanded)), setDefaultAdvertisedEndpointKey: (key) => set((state) => setDefaultAdvertisedEndpointKey(state, key)), setSidebarProjectScopeKeys: (projectKeys) => diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 7c1d17587813e..0930fecde82d0 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -222,6 +222,15 @@ describe("agentWorkingDirectories", () => { ), ).toEqual(["/work/d"]); }); + + it("leaves network shares out of the search roots", () => { + expect( + directories( + "cd //files.example/share", + String.raw`cd '\\files.example\share'; cd C:\work\repo`, + ), + ).toEqual([String.raw`C:\work\repo`]); + }); }); // regression: #35337 a bare file name the agent cited from a subfolder of an unregistered checkout diff --git a/apps/web/test/renderScenarios.renders.tsx b/apps/web/test/renderScenarios.renders.tsx index 8cad678f29f00..535fe44f79a7a 100644 --- a/apps/web/test/renderScenarios.renders.tsx +++ b/apps/web/test/renderScenarios.renders.tsx @@ -94,7 +94,6 @@ function timelineFor() { latestRun: null, turnDiffSummaries: [], runs: [], - onOpenTurnDiff: () => {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 581f9d8e8d8f8..cf697e89b1c32 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -9,7 +9,10 @@ "jsx": "react-jsx", "lib": ["ES2023", "ES2024.Promise", "ESNext.Disposable", "DOM", "DOM.Iterable"], "paths": { - "~/*": ["./src/*"] + "~/*": ["./src/*"], + // Words' entry compiles its WebAssembly on import; these reach its parts without doing so. + "@pierre/words/core": ["./node_modules/@pierre/words/dist/core"], + "@pierre/words/wasm": ["./node_modules/@pierre/words/dist/words.wasm.mjs"] }, "plugins": [ { diff --git a/docs/README.md b/docs/README.md index c59b5f9ae269f..622d31096da05 100644 --- a/docs/README.md +++ b/docs/README.md @@ -35,40 +35,40 @@ ## Working on T3 Code -Start with the [development runbook](./operations/development.md) and +Start with the [development runbook](./operations/00_development.md) and [contribution policy](../CONTRIBUTING.md). -Internal notes preserve architectural decisions, constraints, and implementation traps that the -source alone does not explain. Most code changes do not need an internal documentation update. Follow the -[documentation rules](../AGENTS.md#documentation) before adding one. +Internal docs preserve architectural decisions, trust boundaries, conventions, and cross-cutting +traps that the source alone does not explain. Most code changes do not need an internal +documentation update. Follow the [documentation rules](../AGENTS.md#documentation) before adding +anything. -- [Architecture overview](./internals/overview.md) -- [Glossary](./internals/glossary.md) -- [Connection runtime](./internals/connection-runtime.md) -- [Providers](./internals/providers.md) -- [Adding a provider](./internals/adding-a-provider.md) -- [Pull request file revisions](./internals/pull-request-file-revisions.md) -- [Model classification](./internals/model-manifest.md) -- [Remote environments](./internals/remote.md) -- [Server updates](./internals/server-updates.md) -- [Resource telemetry](./internals/resource-telemetry.md) -- [Product analytics](./internals/product-analytics.md) -- [Environment auth](./internals/environment-auth.md) -- [T3 Connect](./internals/t3-connect.md) -- [Assistant citations](./internals/assistant-citations.md) -- [Mobile layout](./internals/mobile-layout.md) -- [Mobile navigation](./internals/mobile-navigation.md) -- [Mobile development lifecycle](./internals/mobile-development.md) -- [Terminal runtime](./internals/terminal-runtime.md) -- [Devices](./internals/devices.md) -- [Voice input](./internals/voice-input.md) +### Internals (in reading order) + +- [00 · Glossary](./internals/00_glossary.md) +- [01 · Architecture](./internals/01_architecture.md) +- [02 · Effect services](./internals/02_effect-services.md) +- [03 · Providers](./internals/03_providers.md) +- [04 · Environment auth](./internals/04_environment-auth.md) +- [05 · Remote environments](./internals/05_remote.md) +- [06 · T3 Connect](./internals/06_t3-connect.md) +- [07 · Server updates](./internals/07_server-updates.md) +- [08 · Product analytics](./internals/08_product-analytics.md) +- [09 · Connection runtime](./internals/09_connection-runtime.md) +- [10 · Web UI](./internals/10_web-ui.md) +- [11 · Mobile layout](./internals/11_mobile-layout.md) +- [12 · Mobile navigation](./internals/12_mobile-navigation.md) +- [13 · Mobile development lifecycle](./internals/13_mobile-development.md) +- [14 · Translating the UI (i18n)](./internals/14_i18n.md) +- [15 · Testing](./internals/15_testing.md) +- [16 · Performance regression checks](./internals/16_performance-regressions.md) +- [17 · Scripts](./internals/17_scripts.md) ### Runbooks -- [Development and local builds](./operations/development.md) -- [Scenarios: real-app proof for a fix](./operations/scenarios.md) -- [T3 Connect setup](./operations/connect-setup.md) -- [Release](./operations/release.md) -- [Observability](./operations/observability.md) -- [Relay observability](./operations/relay-observability.md) -- [Mobile app store screenshots](./operations/mobile-app-store-screenshots.md) +- [00 · Development and local builds](./operations/00_development.md) +- [01 · Dev container](./operations/01_devcontainer.md) +- [02 · T3 Connect setup](./operations/02_connect-setup.md) +- [03 · Release](./operations/03_release.md) +- [04 · Observability](./operations/04_observability.md) +- [05 · Relay observability](./operations/05_relay-observability.md) diff --git a/docs/internals/00_glossary.md b/docs/internals/00_glossary.md new file mode 100644 index 0000000000000..a313a6eefc934 --- /dev/null +++ b/docs/internals/00_glossary.md @@ -0,0 +1,42 @@ +# Glossary + +Shared vocabulary across T3 Code. Architecture and lifecycle constraints belong in the +[architecture](./01_architecture.md). + +## Workspace and conversation + +| Term | Meaning | +| -------------- | ------------------------------------------------------------------------------------------------- | +| Environment | One running server and the machine, credentials, workspace access, and state it owns. | +| Client | A web, desktop, or mobile UI connected to an environment. The desktop app can also host a server. | +| Project | An environment-local workspace record rooted at a directory. | +| Workspace root | The project's base filesystem directory on the environment. | +| Worktree | A separate Git checkout a thread can use instead of the project's main checkout. | +| Thread | The durable conversation and work history for a project. Survives provider process exits. | +| Turn | One user-to-agent cycle (a run). Provider work can end before checkpoint and diff work settles. | +| T3 home | The base data directory. Runtime state normally lives under its `userdata` directory. | + +## Orchestration + +| Term | Meaning | +| ----------------------- | --------------------------------------------------------------------------------------------------------- | +| Command | A request to change domain state. Accepting it means intent committed, not that side effects finished. | +| Event | A persisted fact produced by a command. | +| Orchestrator | The service that serializes commands and decides their events from current state, without I/O. | +| Projection / read model | A persisted view of current state, committed in the same transaction as the events that change it. | +| Command receipt | A durable record of a command's result, used to make retries idempotent. | +| Outbox effect | Side-effect intent committed with the events, such as starting a provider turn or capturing a checkpoint. | +| Effect worker | The worker that runs outbox effects after commit and feeds their results back as commands. | + +## Providers and checkpoints + +| Term | Meaning | +| ----------------- | ------------------------------------------------------------------------------------------------------------ | +| Provider | The agent runtime T3 Code controls, such as Codex or Claude Code. | +| Driver | The integration for a provider kind. | +| Provider instance | One configured provider, with its own settings and lifecycle. Multiple instances can use the same driver. | +| Adapter | The boundary translating a provider's native protocol into T3 Code operations and events. | +| Session | The provider runtime attached to a thread. A session can be stopped and resumed without deleting the thread. | +| Runtime mode | The thread's permission policy. See [permission modes](../user/permission-modes.md). | +| Interaction mode | How the agent approaches the task, such as planning. Separate from permission policy. | +| Checkpoint | A saved workspace state used for diffs and restore, stored as a hidden Git ref. | diff --git a/docs/internals/01_architecture.md b/docs/internals/01_architecture.md new file mode 100644 index 0000000000000..84cb05a5572d7 --- /dev/null +++ b/docs/internals/01_architecture.md @@ -0,0 +1,74 @@ +# Architecture + +T3 Code keeps execution in the environment that owns the workspace. Web, desktop, and mobile +clients control it over authenticated RPC. A remote client must never substitute its own filesystem, +provider credentials, or machine state for the environment's. The desktop app bundles a server, +but its renderer follows the same boundary. + +## Ownership boundaries + +- **Server (`apps/server`).** Owns provider processes, terminals, Git, checkpoints, durable state, + and project files. +- **Client runtime (`packages/client-runtime`).** Owns shared connection management and domain + state across web, desktop, and mobile so reconnect and multi-environment behavior do not diverge. + Clients supply platform services and UI. See [connection runtime](./09_connection-runtime.md) and + [remote environments](./05_remote.md). +- **Contracts (`packages/contracts`).** The typed wire boundary between independently versioned + clients and servers. Subscriptions send only the state a client needs. Authentication of a socket + does not authorize every method on it; see [environment auth](./04_environment-auth.md). +- **Providers (`packages/provider-*`).** Provider-specific protocols and quirks stay behind an + adapter. Orchestration and clients read capabilities, never provider names. See + [providers](./03_providers.md). + +## Settings ownership + +Client preferences live in the current client; environment defaults and project overrides live on +their owning server. An unavailable settings target must never fall back to another environment. +**All environments** is an explicit bulk edit of currently connected servers, not a durable global +default or sync promise. + +## Durable intent and side effects + +Orchestration state is decided as events, and persisted projections are the source of truth once +applied. The [orchestrator](../../apps/server/src/orchestration-v2/Orchestrator.ts) serializes +commands and decides events without doing I/O. +[EventSink](../../apps/server/src/orchestration-v2/EventSink.ts) commits events, persisted +projections, command receipts, and outbox effects in one database transaction, then notifies +subscribers. + +The [effect worker](../../apps/server/src/orchestration-v2/EffectWorker.ts) runs side effects after +commit and feeds results back as commands. A command acknowledgement therefore means intent +committed, not that provider, checkpoint, or follow-up work finished. Never put external I/O in +command decisions or the database transaction. Effects tied to a lost provider process are retired +on recovery rather than replayed. + +The event log retains only a bounded replay window, so projections cannot be rebuilt from scratch +from the log. Retained events must remain decodable across upgrades: schema changes affect stored +history at startup, not just live RPC traffic. + +## Turn completion and checkpoints + +A provider turn ending and follow-up work settling (checkpoints, diffs, PR sync) are separate +milestones. Late finalization must not keep the client showing provider work as active or extend +recorded provider duration. + +A run is `completed` when its provider turn ends; the turn-end checkpoint is captured afterwards as +an outbox effect on the thread's effect lane. Until that capture commits, readers treat the missing +checkpoint as pending, and command decisions still see the run as `waiting`, so steers, queued +turns, rollback and restore line up behind the capture. + +Checkpoints use hidden Git refs so workspace snapshots never add commits to the user's branch. +Reverting a checkpoint must coordinate workspace state with the provider conversation: if the +provider cannot roll back its conversation, reject the revert before touching the filesystem. + +Thread settlement is server-owned. Clients render persisted settlement state rather than deriving it +from local clocks or PR caches. + +## Desktop process isolation + +Native modules never load on the Electron main process startup path. Native capabilities that can +crash or stall (such as accessibility or window-capture helpers) run in isolated child processes or +workers with deadlines, never as top-level imports in main. + +See the [glossary](./00_glossary.md) for shared terms and the +[development runbook](../operations/00_development.md) for setup and checks. diff --git a/docs/internals/effect-services.md b/docs/internals/02_effect-services.md similarity index 100% rename from docs/internals/effect-services.md rename to docs/internals/02_effect-services.md diff --git a/docs/internals/03_providers.md b/docs/internals/03_providers.md new file mode 100644 index 0000000000000..69206d8458c61 --- /dev/null +++ b/docs/internals/03_providers.md @@ -0,0 +1,87 @@ +# Providers + +Provider protocols, account ownership, permissions, and capabilities belong at the +[adapter boundary](../../packages/provider-core/src/server/ProviderAdapter.ts). Orchestration and +clients read declared capabilities, never provider names. + +## Identity and integration shape + +- **App IDs are primary; provider IDs are refs.** Never match native provider IDs globally without + provider/session/thread scope, and never let child provider turn completions close a parent run. +- **Route by provider instance, not driver kind.** Session state, catalogs, and credentials belong + to a provider instance so two accounts on the same driver cannot share mutable state. Strip + ambient credentials the instance did not configure. +- **Strict ACP compliance for non-first-party agents.** Generic + [ACP Registry](../user/providers-acp.md) and local ACP commands follow the ACP specification + strictly—never deviate from the spec or add agent-id checks, vendor extensions, or + driver-specific workarounds in the shared ACP adapter for non-first-party agents. If an upstream + ACP agent deviates from or lacks part of the spec, let orchestration degrade through capabilities + rather than special-casing it here. Dedicated ACP flavors (over `packages/provider-acp`) are + reserved for first-party drivers that need behavior outside the ACP spec; native + `ProviderAdapterV2` adapters are only for non-ACP protocols. +- **Package boundaries.** Providers live in `packages/provider-` (see + [Pi](../../packages/provider-pi) as reference). Server code imports only + `@t3tools/provider-core/server/*`, contracts, and shared, reaching host capabilities through + `ProviderHost` rather than `apps/server`. Client definitions (`./client`) must stay browser- and + React Native-safe. + +## Honest capabilities and permissions + +- **Declare only what the provider actually supports.** Turn off fork, rollback, steering, or + subagent capabilities the provider lacks so orchestration degrades cleanly (for example, portable + context handoff for forks). A capability left enabled that fails at runtime is a bug. +- **Never emulate missing permission modes.** Expose only modes the provider enforces natively; do + not fake a mode by auto-answering approvals in T3. Unoffered stored modes fall back to Supervised. + Pass native approval and question option IDs through unchanged, and ensure every request can be + declined. +- **Hide plan mode unless it produces proposed-plan cards.** +- **Reject conversation rollback before touching files** when the provider cannot roll back its + conversation (see [checkpoints](./01_architecture.md#turn-completion-and-checkpoints)). + +## Process, setup, and security boundaries + +- **Health checks must stay passive.** Background status and model probes must never open a session + that starts MCP servers, runs hooks, or launches a login flow. Reserve heavier probes for explicit + refresh or setup. +- **Updates run only through a provably owning installer.** Prove ownership from the resolved + executable path (or use a self-updater that checks its own install); leave ambiguous, pinned, or + read-only installs (such as Nix) manual-only. +- **Attachments stay outside the project workspace.** Never copy uploads into the project tree to + bypass a provider's sandbox or approval rules. +- **T3 MCP tools.** Inject the thread's authenticated MCP server so agents can reach T3 tools, and + keep turns working if that server is unreachable. + +## Model manifest + +The bundled [`model-manifest.json`](../../apps/server/src/provider/model-manifest.json) enables +offline startup while remote fetches from `main` update metadata between releases. A bundled +manifest outranks the cached remote copy by `updatedAt`, so **bump `updatedAt` on every edit**. +Declare broken-version minimums in the manifest policy rather than as driver constants. Test catalog +and adapter semantics with synthetic model names so adding a model never requires duplicating config +in tests. + +## Cross-provider traps and testing + +Prove adapter behavior with replay fixtures recorded from the real provider and replayed through the +real orchestrator, adapter, and projections. Hand-written protocol frames guess at wire behavior; use +unit tests for pure logic and failure paths a real provider cannot trigger on demand. + +Traps that have broken multiple adapters: + +- **Lazy config advertisement.** Providers often advertise options only after a session opens or a + model runs. Wait for advertisement before applying settings, and skip unoffered stored options + rather than failing. +- **`"Default"` is a sentinel, not a model ID.** Never send it to a provider; clear or reset the + session's model selection instead. +- **Early Stop.** Cancelling before the provider registers the prompt can be ignored or strand a + session. Gate cancellation on the provider's turn-started signal. +- **Work outliving a turn.** Background tasks, subagents, and provider-initiated continuations can + report after T3's turn settles. Route subagent updates by subagent (not active run), request + continuations when needed, and report pending background work so idle cleanup does not kill the + session. +- **Terminal settlement.** Every terminal path (completion, Stop, provider error, process exit) must + settle open tool calls, subagents, and pending requests. +- **Usage limits.** Classify quota/rate-limit errors as `usage_limit` (with reset time when + available) rather than generic failures. +- **Symlinked workspaces.** Test symlinked paths (such as macOS `/tmp`); providers that compare + canonical paths break if cwd handling disagrees. diff --git a/docs/internals/04_environment-auth.md b/docs/internals/04_environment-auth.md new file mode 100644 index 0000000000000..1b22ab16e4d6d --- /dev/null +++ b/docs/internals/04_environment-auth.md @@ -0,0 +1,82 @@ +# Environment authentication + +The environment issues its own sessions and enforces their capabilities. Cloud identity and relay +credentials belong to a separate trust boundary, described in [T3 Connect](./06_t3-connect.md). A relay +token is never an environment login. See [SECURITY.md](../../SECURITY.md) for the overall threat +model. + +## Scoped sessions and delegation + +- **Narrowing only.** Pairing delegates a set of scopes. Exchanging a bootstrap credential can + narrow a grant, never widen it. Client labels and device metadata have no authorization role. +- **`access:write` hands out what the session holds and revokes anything.** Every route that + returns a credential to the caller requires `access:write` and every scope that credential + carries: a pairing link, an MCP sign-in approval, a link code from a linked environment, and a + guest link (which reads a thread). Revoking is not capped by the caller's scopes. Admitting a + T3 Connect device is not delegation; see [T3 Connect](./06_t3-connect.md). +- **Why the default grant includes management scopes.** `terminal:operate` and + `orchestration:operate` already grant OS-user execution (which can invoke `t3 auth session issue`), + so withholding access or relay management from the default grant would not be a real boundary. + Narrower clients receive explicit scopes. +- **No recoverable secrets in read models.** Only the creation response returns a raw pairing + credential; access listings expose metadata only. +- **DPoP binding.** Browser cookies, bearer tokens, and DPoP tokens share the scoped session model. + DPoP binds tokens to a client proof key; an invalid proof must fail rather than fall back to + bearer auth. Plain paired DPoP sessions renew in place so live sockets and Sharing & access rows + stay stable; T3 Connect, CLI, and desktop sessions never self-renew so revoking/unlinking cuts + them off. +- **WebSocket tickets and per-RPC authorization.** Bearer and DPoP clients mint short-lived tickets + over authenticated HTTP so long-lived tokens never appear in socket URLs. DPoP RPC tickets stay + proof-key bound at upgrade. A successful handshake grants no extra authority: every RPC declares + and checks its required scope in [`RpcAuthorization.ts`](../../apps/server/src/auth/RpcAuthorization.ts). +- **Secret references need `providers:manage`.** A request that names a secret for the server to + read needs `providers:manage` on top of its method's scope, whether the reference is saved in + settings or used once, as in a secret request answered with a reference. Typed values need only + the method's scope. Clients hide the secret provider picker from sessions without it. +- **Backward-compatible scope evolution.** Token exchange intersects requested scopes with the + pairing grant, dropping retired/unknown names and failing before consuming a link if none remain. + Stored grants are never expanded when scopes split. Auth responses preserve legacy `scopes` + alongside exact `permissions` so older clients and servers stay compatible. + +## Non-standard principals + +- **Guest links are not sessions.** [GuestShareService](../../apps/server/src/guest/GuestShareService.ts) + issues HMAC tokens bound to one share in the thread projection—never `SessionStore` rows—so no + RPC, WebSocket, or MCP route can accept one. Closing, replacing, or archiving the share revokes + every token. Guest routes also require T3 Connect to still serve the link's hostname (never rely + on the request `Host` header alone). +- **MCP clients (`mcp-client`) are a separate audience.** Outside agents authenticate on `/mcp` via + PKCE OAuth ([McpOAuth](../../apps/server/src/auth/McpOAuth.ts)), with stateless client + registration so unauthenticated callers cannot grow server state. Users grant read-only access or + a runtime-mode ceiling rather than raw scopes. Every non-`/mcp` HTTP and WebSocket route rejects + `mcp-client` sessions (except the read-only thread relay and client-pairing routes restricted to + [peer links](./05_remote.md#peer-links)). Every MCP tool must statically declare its access level in + [`McpToolAccess.ts`](../../apps/server/src/mcp/McpToolAccess.ts), and thread-only tools must still + refuse outside callers in handlers—hiding from tool listings is only discovery. +- **Peer-link client pairing.** Only a full-access peer link may mint a one-time client pairing on + the linked environment (since full-access agents can already run `t3 auth pairing create`). The + linked side enforces this itself, and the operation stays a human-triggered RPC/HTTP route rather + than an MCP tool. The same route mints a code that links another environment at a chosen access + level, and the linking side's RPC requires the caller to hold that level's scopes. + +### Reusable dev credential + +Web development servers can accept a fixed `T3CODE_DEV_AUTH_TOKEN` across worktrees and ports on one +hostname (see the [development runbook](../operations/00_development.md#reusable-dev-credential)). It +grants administrative access and is ignored by desktop and non-development servers. + +Each environment hashes the value into its own database record and keeps independent SQLite state, +signing keys, and revocation state. Normal credentials always take precedence: a rejected normal +credential never falls back to the reusable dev credential. + +## The environment is the filesystem boundary + +Projects are organizational boundaries, not filesystem sandboxes. `filesystem:read` permits reading +any file the server's OS user can read (for example, artifacts an agent writes in a temp directory); +relative paths and writes remain constrained by +[`WorkspaceFileSystem.ts`](../../apps/server/src/workspace/WorkspaceFileSystem.ts). + +Signed asset URLs are bearer credentials for a single canonical file, rechecked by device/inode +identity on serve ([`AssetAccess.ts`](../../apps/server/src/assets/AssetAccess.ts)). They never +grant access to sibling files, and because `filesystem:read` is checked only at mint time, an issued +URL remains valid until it expires even if the session or grant is revoked. diff --git a/docs/internals/05_remote.md b/docs/internals/05_remote.md new file mode 100644 index 0000000000000..13ef6dffb9374 --- /dev/null +++ b/docs/internals/05_remote.md @@ -0,0 +1,71 @@ +# Remote architecture + +Each connection joins a client to one environment over HTTP and WebSocket. Direct access, Tailscale, +SSH, and T3 Connect change how the client reaches the server; they do not introduce a different +execution model. + +## Identity is independent of the route + +- An environment keeps its ID across restarts and endpoint changes. Repository identity can + correlate clones across environments (preferring `upstream` for PR features, grouping forks by + `origin`), but work never silently crosses environments. +- [Environment ID initialization](../../apps/server/src/environment/ServerEnvironment.ts) publishes + atomically and retains repair state so concurrent initializers choose the same winner; do not + sweep that recovery state as temp cleanup. +- **Routes are untrusted hints.** Only the connecting client can prove reachability. Never fall back + to loopback when a shareable endpoint is unavailable (loopback names the client's own machine). + Verify a direct or learned route answers as the expected environment before sending credentials, + and never let a token paired over HTTPS downgrade to plain HTTP. +- Pull request routing trust covers the saved route set: adding or changing a route revokes trust; + reordering does not. + +## Peer links + +A [peer link](../../apps/server/src/peer/PeerLinks.ts) lets one environment's agents work in another +by signing in to the target's `/mcp` as an ordinary OAuth client (`t3code-peer-link`). The receiving +side lists and revokes it in Sharing & access like any other session, and owns its expiry/renewal. + +- **Mode ceilings always narrow.** Forwarded calls carry the calling agent's modes in + `T3-Mode-Limit`, which the receiving `/mcp` can only intersect downward with the link's approved + access. +- **Non-full-access links are fenced by `linkOrigin`.** Threads launched by a peer link (and their + derived forks, subagents, and spawned threads) carry an immutable `linkOrigin` stamp enforced in + shared access rules ([`mcp/linkOrigin.ts`](../../apps/server/src/mcp/linkOrigin.ts)). Below full + access, linked work can mutate only threads with the same origin, cannot touch projects, settings, + scheduled tasks, or further links, and skips project setup scripts. Full-access links are not + fenced because their agents already run as the receiving OS user. +- **Namespace idempotency keys.** All callers on the linking side share one session on the receiving + side, so idempotency keys must be hashed with the caller's namespace before forwarding. +- **Clients read linked threads as standard thread streams.** + [`PeerThreadRelay`](../../apps/server/src/peer/PeerThreadRelay.ts) proxies the same stream format + read-only so there is no second transcript schema to maintain. + +## Hosted web is a client + +The hosted web app stores its connection catalog in the browser and connects directly to each +environment without proxying traffic. A [hosted pairing URL](../../apps/web/src/hostedPairing.ts) +puts the backend target in the query and the pairing secret in the URL fragment so the secret never +reaches the hosted origin, then strips it from history. + +## Desktop previews tunnel loopback + +A desktop webview for a remote environment keeps `localhost` URLs and tunnels loopback connections +through `/api/preview/tunnel` on the environment's own origin: + +- **Fixed SOCKS5 proxy, not PAC.** Chromium ignores PAC scripts for loopback hosts. Use a fixed + proxy that routes only loopback through the tunnel (excluding link-local addresses) and never + falls back directly—a failed or disabled tunnel must error rather than silently load the + reviewer's own localhost. +- **Media tickets and local-owner check.** Desktop main holds no environment credentials, so the + renderer supplies a media ticket per connection (also tracking route switches). Because Chromium + cannot authenticate to SOCKS5, the local listener restricts access to the current OS user where + the platform allows (Linux `/proc/net/tcp`). + +## Access and process ownership are separate + +- Tailscale supplies an endpoint for normal pairing; auth remains the environment's responsibility. +- [SSH cleanup](../../packages/ssh/src/tunnel.ts) stops a remote server only if the launcher started + it; a server discovered already running must survive client disconnect. +- Remote servers outlive client releases. Clients negotiate features via advertised capabilities + rather than assuming version parity. Process replacement uses the + [update protocol](./07_server-updates.md). diff --git a/docs/internals/06_t3-connect.md b/docs/internals/06_t3-connect.md new file mode 100644 index 0000000000000..dc60a5468b849 --- /dev/null +++ b/docs/internals/06_t3-connect.md @@ -0,0 +1,69 @@ +# T3 Connect + +T3 Connect uses Clerk for cloud identity. The relay manages environment links, bootstrap +credentials, and managed tunnel allocations. Regular HTTP and WebSocket traffic goes directly from +clients to the environment's tunnel hostname—the relay Worker is not in the data path. + +The one forwarded exception is automation webhooks +([`HookForwarder.ts`](../../infra/relay/src/hooks/HookForwarder.ts)), which give senders a stable +URL while leaving token/signature verification to the environment and keeping bodies/tokens out of +traces. Opt-in offline holding stores raw webhook requests in a per-link Durable Object +([`HookInboxObject.ts`](../../infra/relay/src/hooks/HookInboxObject.ts)) rather than Queues or +Postgres because held requests need per-link ordering, retry timing, and larger payload limits. + +Deployment and Clerk configuration live in the [Connect setup runbook](../operations/02_connect-setup.md). + +## The relay is a trusted broker + +- **DPoP-bound bootstrap minting.** For a linked user, the relay asks the environment to mint a + one-time bootstrap credential bound to the client's DPoP key. The client redeems it directly with + the environment for an [environment session](./04_environment-auth.md). The relay never sees session + tokens, and a bootstrap credential is useless without the client's proof key. +- **Mutual authentication.** The environment accepts only bounded, replay-guarded relay proofs for + its own identity, linked user, and operation; the relay verifies signed environment responses + bound to the request nonce and client proof key so nothing behind the tunnel can impersonate the + environment ([`CloudLink.ts`](../../apps/server/src/cloud/CloudLink.ts), + [`EnvironmentConnector.ts`](../../infra/relay/src/environments/EnvironmentConnector.ts)). +- **Explicit trust assumption & device approval.** DPoP protects an honest exchange, not a + compromised relay signing key. Enabling `requireConnectDeviceApproval` shifts trust from the relay + to approved DPoP key thumbprints: untrusted keys mint credentials that cannot be spent until + someone with `access:write` approves the key, and revoking a key revokes all of its sessions and + pending credentials. Approving admits a device already signed in to the owner's cloud account + and returns no credential to the approver, so `access:write` alone is enough, as it is for + turning the setting off. +- **Anti-hijack and anti-SSRF rules.** Managed tunnels expose only the server's own loopback HTTP + origin (ignoring caller-supplied origins). The relay refuses to relink an active environment ID + under a different key until unlinked, resolves endpoints only from its own managed allocations, + and never follows redirects on health or mint requests. + +## Link, allocation, and tunnel lifetimes + +- CLI authorization, desired exposure, and a running connector have separate lifetimes: linking can + record intent while stopped, and logout revokes cloud credentials without uninstalling the + background service. +- Normal CLI shutdown releases its paid tunnel while keeping the hostname reservation and allocation + record (so the environment shows offline rather than unauthorized). Client-installed links and + update handoffs retain the tunnel across shutdown so updates do not pay DNS/routing propagation + delay. +- Every allocation mutation bumps its `generation`. Unlink commits authorization revocation before + external teardown, and release/reclamation lock on the claimed generation so delayed cleanup never + deletes a tunnel reused by a concurrent restart or relink + ([`ManagedEndpointProvider.ts`](../../infra/relay/src/environments/ManagedEndpointProvider.ts)). +- Idle tunnel reclamation deletes only tunnels whose host has registered recovery (and never + unallocated orphans) so hosts that cannot self-heal are left alone. + +## T3 Chat plan cap link + +T3 Chat uses WorkOS rather than Clerk, so accounts link by user consent via a shared secret. T3 Chat +owns the link and plan state; the relay stores no copy and queries T3 Chat only when an account hits +its default cap for a new environment, failing closed to the default cap without disrupting existing +slots. + +## OAuth traps + +- Interactive clients use Clerk session-template JWTs; the headless CLI uses a public PKCE OAuth + client with no secret. The relay must accept both. +- Loopback CLI login starts on the hosted `/connect` page so sign-in finishes before Clerk's + authorize endpoint (going straight to authorize drops parameters across sign-in redirects). +- SSH and headless sessions use Clerk's OAuth device authorization grant directly against Clerk's + token endpoint, which must stay enabled on the CLI OAuth application. diff --git a/docs/internals/07_server-updates.md b/docs/internals/07_server-updates.md new file mode 100644 index 0000000000000..5e181607dd501 --- /dev/null +++ b/docs/internals/07_server-updates.md @@ -0,0 +1,44 @@ +# Server updates + +## Launcher ownership and compatibility + +A [stable launcher](../../apps/server/src/serviceLauncher.ts) owns the runtime selected by systemd, +launchd, or Task Scheduler and is the only runtime writer of durable service state. Server children +request updates over inherited IPC and never rewrite their service definition. Foreground CLI +processes do not self-update. + +Remote updates replace only the server child, not the launcher, so every existing background service +lags behind after a launcher-protocol bump. Keep new server runtimes compatible with the previous +launcher protocol unless impossible, and validate protocol compatibility during preflight. + +Installations use exact versions and stage/preflight before publishing an immutable runtime so +restarts never depend on npm cache eviction or a moving tag. + +## Commit boundary and database rollback + +1. Record the pending update durably (atomic rename + fsync) before stopping the old child. +2. Refuse the update if a database snapshot will not fit on disk. After the old child exits, snapshot + SQLite (main, WAL, SHM) once per update so failed trial migrations are reversible without down + migrations. Never overwrite that snapshot on retry. Files outside SQLite (such as attachments) + are outside this rollback boundary. +3. Start the new runtime as a trial. It must finish migrations, acquire fallible dependencies, bind + HTTP, and hold long-running roots at the activation gate before reporting `prepared`. +4. Only after the launcher commits the new version durably and replies `committed` may the child + release activation gates and accept work. A failed or timed-out trial stops and restores the + snapshot before booting the old version. + +## Client acknowledgement + +An accepted update RPC is only pending. Clients correlate the launcher's update ID with the +reconnected ready state to distinguish commit from rollback. Desktop updates use a two-phase handoff +(prepare token while connected, commit after receiving it) because installing stops the bundled +backend. + +## Recovering interrupted threads + +- On startup, retire effects tied to the lost process before admitting new work. +- Persist restart-continuation intent in the durable outbox and wait for activation before running + it so slow providers never delay readiness or the launcher's commit boundary. +- Cap consecutive crash recoveries per unfinished turn so a crashing turn cannot loop forever. +- Never auto-continue a turn that is archived, settled, snoozed, user-stopped, or waiting on a + blocking user action (approval, question, or secret). diff --git a/docs/internals/08_product-analytics.md b/docs/internals/08_product-analytics.md new file mode 100644 index 0000000000000..375f6be84b857 --- /dev/null +++ b/docs/internals/08_product-analytics.md @@ -0,0 +1,42 @@ +# Product analytics + +The server owns analytics delivery, opt-out, and identity for every connected client. Clients never +load the PostHog browser SDK, PostHog person profiles stay disabled, and visiting hosted web without +an authenticated connection does not count as product use. + +## Identity + +- **Never change `distinct_id`.** It preserves historical continuity in PostHog charts; add fields + instead of changing how it is computed. +- **Count installs with `installId`, resolve owners at query time.** `installId` is a stable hash + persisted in the state directory; `install.owner_observed` links installs to owners (Connect + account, OpenAI `user_id`—not the shared Codex Team `account_id` or per-login `sub`—Claude id, + client device). Two Connect accounts are never merged as one person. +- **Hash everywhere with [one helper](../../packages/shared/src/telemetryId.ts).** Clients and + servers hash with the same SHA-256 helper so IDs correlate; the server accepts only hashes from + clients. + +## Attribution boundaries + +- Client dimensions (`surface`, etc.) belong to the event's WebSocket connection, never a + server-global "current client". Keep client and server dimensions separate, and leave missing + client metadata unknown rather than backfilling from server properties. +- Active-use reports count `client.turn.requested` (deduplicated by command ID), not connections + (T3 Connect sessions renew hourly). + +## Collection boundary and delivery + +- Payloads stay strictly to product metadata, closed contract enums, and normalized measurements: + never attach prompts, file paths, credentials, raw provider payloads, device names, conversation + IDs, or user-named provider instance IDs. Model IDs are reported as the provider used them, + including custom models; known aliases and routed IDs map to one catalog slug, and a model + that is a file path reports only its file name. +- The sole exception is opt-in `agent.feedback`, which + [`FeedbackService`](../../apps/server/src/feedback/FeedbackService.ts) scrubs of paths, private + values, and secret-shaped strings, and only attaches bounded conversation traces when the user + explicitly previews and sends them. +- Delivery ([`AnalyticsService.ts`](../../apps/server/src/telemetry/AnalyticsService.ts)) attaches a + UUID per event, backs off on failure, and drops batches after bounded retries so a stuck batch + cannot loop forever. +- Dev-runner servers and CI smoke tests disable telemetry (and relay tracing) by default so they do + not inflate install counts; set `T3CODE_TELEMETRY_ENABLED=true` to test locally. diff --git a/docs/internals/09_connection-runtime.md b/docs/internals/09_connection-runtime.md new file mode 100644 index 0000000000000..30946168b88f7 --- /dev/null +++ b/docs/internals/09_connection-runtime.md @@ -0,0 +1,51 @@ +# Connection runtime + +Web, desktop, and mobile share one connection owner per environment in `packages/client-runtime`. +Platform code supplies storage, credentials, network signals, and lifecycle events; React views +consume the runtime. Keeping retry and session ownership here prevents competing reconnect loops. + +## One transport retry owner + +- The [supervisor](../../packages/client-runtime/src/connection/supervisor.ts) is the sole owner of + transport retries. Endpoint resolution and opening an RPC session are single attempts. Transient + failures use jittered, capped exponential backoff that resets only after a connection stays up; + offline and auth failures wait for an explicit wakeup. +- Foregrounding, network changes, explicit retries, and offline reports probe the established + session rather than blindly reconnecting (OS offline reports are often wrong, especially for + loopback). Only a failed probe replaces the socket. +- The [registry](../../packages/client-runtime/src/connection/registry.ts) scopes connections by + environment. An involuntary disconnect keeps the registration and cached projections; explicit + removal closes the scope and clears credentials, caches, and drafts. Cloud-account changes apply + only to relay registrations and must never discard directly paired environments. + +## HTTP authorization vs. socket lifetime + +RPC sockets authenticate at upgrade, while HTTP requests pull current credentials from the +[authorization service](../../packages/client-runtime/src/authorization/service.ts). Never tear down +a healthy socket because an HTTP refresh failed—renewal failure belongs to the HTTP operation. Live +sockets whose access token nears expiry renew in place on the same session so open conversations are +not interrupted. Session listings retain unrevoked connected sessions after credential expiry so +active connections stay manageable without extending the credential's lifetime. + +## Transport health and data freshness are separate + +- An open socket does not mean the environment is usable. The RPC session waits for initial server + configuration, and shell and thread subscriptions maintain their own sync state. Never label a + failed subscription "reconnecting" when the transport is healthy. +- Cached projections stay readable offline, but must never imply a live connection or overwrite + newer live data on reconnect. +- **Shell snapshots are intentionally partial.** Servers omit idle subagent children and older + settled threads on demand; left-out rows load via thread-family, shelf, and search queries. A + missing shell row therefore never proves a thread is deleted—code that deletes data or worktrees + on absence must verify with the family or server first. + +## Subscriptions, caching, and mutations + +- [Thread detail](../../packages/client-runtime/src/state/threads.ts) separates subscription + lifetime from cache lifetime: mounted consumers share one live stream (stopping when the last + unmounts), while a short-lived cache retains state and its replay cursor for fast back navigation. +- Commit cached state and replay cursor together only after an update completes. Cancellation must + not advance the cursor past applied data, and an old scope must not overwrite a newer scope's + cache. +- Durable subscriptions follow replacement sessions automatically. Reconnection never auto-replays + mutations—retry and idempotency belong to each operation. diff --git a/docs/internals/web-ui.md b/docs/internals/10_web-ui.md similarity index 91% rename from docs/internals/web-ui.md rename to docs/internals/10_web-ui.md index 1d3b7d7d8c62d..28c2ce1d7856b 100644 --- a/docs/internals/web-ui.md +++ b/docs/internals/10_web-ui.md @@ -2,8 +2,11 @@ ## Primitives -Controls come from [`components/ui`](../../apps/web/src/components/ui). -[AGENTS.md](../../AGENTS.md#taste) says how to use and extend them. +Controls come from [`components/ui`](../../apps/web/src/components/ui), and those exports own +their look. Pick a `variant` or `size`; do not restyle one with `className`. If none fits and the +look is a generic concept, add a variant to the component; a look that belongs to one feature stays +in that feature's own component, not in `components/ui`. Layout classes (width, flex, margin, +position) belong on the parent. `shadcn/no-restyle` fails lint on violations. Don't style a raw `