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/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index c6fa629d18b43..ba759225ea7f6 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -32,7 +32,7 @@ import { import { useEffect, useRef, useState } from "react"; import { Platform, Pressable, View } from "react-native"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; -import { KeyboardController } from "react-native-keyboard-controller"; +import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller"; import { AuthOrchestrationOperateScope, @@ -1014,30 +1014,32 @@ export function NewTaskDraftScreen(props: { if (!flow.selectedModel) { return ( }> - - {environmentControl} - - {environmentConnected && selectedEnvironmentServerConfig ? ( - - Your draft is saved on this device. {selectedEnvironmentLabel} has no - model available. Install or sign in to a provider there to choose one. - - ) : ( - - Your draft is saved on this device. Connect to an environment to choose its first - model. - - )} - - - + + + {environmentControl} + + {environmentConnected && selectedEnvironmentServerConfig ? ( + + Your draft is saved on this device. {selectedEnvironmentLabel} has no + model available. Install or sign in to a provider there to choose one. + + ) : ( + + Your draft is saved on this device. Connect to an environment to choose its first + model. + + )} + + + + ); } 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/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 920d14bbcc4ef..0a9ee8b3056bf 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -461,6 +461,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps readDraftMessage: () => getComposerDraftSnapshot(composerDraftKey).text, subscribeToDraftChanges: (onChange) => appAtomRegistry.subscribe(composerDraftsAtom, onChange), selection: composerMenu.selection, + hidden: props.hidden, onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text), onChangeSelection: composerMenu.onSelectionChange, }); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 364c5ed2ec822..03803dc893d76 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -65,9 +65,6 @@ import { resolveUserMessagePresentation, } from "@t3tools/client-runtime/user-message"; 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, @@ -87,7 +84,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, @@ -211,8 +213,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"; @@ -344,6 +344,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", @@ -1316,7 +1321,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; @@ -1984,7 +1992,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; @@ -2079,12 +2086,6 @@ function renderFeedEntry( onOpenDetails={props.onOpenSetupDetails} /> ) : null} - {entry.checkpointSummary ? ( - - ) : null} ); } @@ -2176,14 +2177,6 @@ function renderFeedEntry( hasFailure={entry.hasFailure} shimmer={entry.shimmer} thought={entry.thought} - trailing={ - entry.checkpointSummary ? ( - - ) : null - } onToggle={() => props.onToggleWorkGroup(entry.groupId, entry.id)} /> ); @@ -2695,12 +2688,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; @@ -2826,7 +2759,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) => { @@ -3169,19 +3105,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); @@ -4199,7 +4122,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) { @@ -4309,7 +4232,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 e38625d565885..916d613c0ff21 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 00caad7e8d504..d1e5299bf713c 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -1080,7 +1080,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 ? [ { @@ -1097,6 +1099,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-provider-instance.test.ts b/apps/mobile/src/features/threads/thread-provider-instance.test.ts index 56ddec3ab1542..a8f8c7723356e 100644 --- a/apps/mobile/src/features/threads/thread-provider-instance.test.ts +++ b/apps/mobile/src/features/threads/thread-provider-instance.test.ts @@ -208,13 +208,22 @@ describe("thread list reorder availability", () => { : current.activeReorderEnvironmentIds, }; }; - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2); + // Active rows sort by an implied key, so moving past an unarranged row writes only the mover. + const expectMoveDown = (neighborWritable: boolean) => { + const movable = section === "active" || neighborWritable; + expect(createThreadMovePlanner(plannerInput())(movedId, "down")?.length).toBe( + movable ? (section === "active" ? 1 : 2) : undefined, + ); + expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe( + movable, + ); + }; + expectMoveDown(true); const before = registry.get(environments); registry.set(connected, [onlineId]); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false); + expectMoveDown(false); expect(registry.get(environments).pinningEnvironmentIds.has(offlineId)).toBe(true); expect(registry.get(environments).settlementEnvironmentIds.has(offlineId)).toBe(true); expect(registry.get(environments).providersByEnvironmentId.get(offlineId)).toBe( @@ -260,7 +269,7 @@ describe("thread list reorder availability", () => { ); expect(updated.pinReorderEnvironmentIds.has(offlineId)).toBe(false); expect(updated.activeReorderEnvironmentIds.has(offlineId)).toBe(false); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); + expectMoveDown(false); registry.set( configs, @@ -284,16 +293,14 @@ describe("thread list reorder availability", () => { registry.set(connected, [onlineId, offlineId]); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(true); + expectMoveDown(true); expect(registry.get(environments).snoozePresetsByEnvironmentId.get(offlineId)).toBe( updated.snoozePresetsByEnvironmentId.get(offlineId), ); registry.set(configs, new Map([[onlineId, config]])); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false); + expectMoveDown(false); } finally { registry.dispose(); } diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index bf4213e6d4fe4..d495b5df3c40e 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -288,7 +288,7 @@ export function ShimmeringWorkContent(props: { // Uses a native Animated value instead of Reanimated, whose per-frame commits // starve React's while commit pausing is disabled (package.json). See - // docs/internals/performance-regressions.md. + // docs/internals/16_performance-regressions.md. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- steps the native shimmer value on timers while visible and active, and stops them on cleanup useEffect(() => { progress.setValue(0); @@ -1418,7 +1418,6 @@ export function ThreadWorkGroupToggle(props: { readonly hasFailure: boolean; readonly shimmer: boolean; readonly thought?: string | undefined; - readonly trailing?: ReactNode; readonly onToggle: () => void; }) { const gt = useGT(); @@ -1508,7 +1507,6 @@ export function ThreadWorkGroupToggle(props: { /> - {props.trailing} ); 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/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 949ff2f60b951..5166fef9d9216 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -1420,11 +1420,12 @@ describe("thread drag destinations", () => { assignments, }); expect(pending.orderedIds).toEqual([ids[3], ids[0], ids[1], ids[2]]); + const field = section === "pinned" ? "pinOrderKey" : "activeOrderKey"; const confirmed = ordered.map((row) => ({ ...row, - [section === "pinned" ? "pinOrderKey" : "activeOrderKey"]: assignments.find( - (a) => a.id === `${row.environmentId}:${row.id}`, - )!.orderKey, + [field]: + assignments.find((a) => a.id === `${row.environmentId}:${row.id}`)?.orderKey ?? + row[field], })); expect( getThreadListV2OrderedSection({ threads: confirmed, section, now: NOW }).map( @@ -1437,7 +1438,7 @@ describe("thread drag destinations", () => { }, ); - it("refuses a drop that would need to rewrite an old server's keyless row", () => { + it("moves past an old server's keyless row by writing only the moved row", () => { const old = EnvironmentId.make("old-server"); const ordered = [environmentId, old, environmentId].map((env, index) => makeThread({ @@ -1452,11 +1453,11 @@ describe("thread drag destinations", () => { section: "active", reorderableEnvironmentIds: new Set([environmentId]), })(`${environmentId}:2`, { targetId: `${environmentId}:0`, placement: "before" }), - ).toBeNull(); + ).toEqual([{ id: `${environmentId}:2`, orderKey: expect.any(String) }]); }); }); -it("allows a long drop past an old server even when both adjacent moves fail", () => { +it("moves past an old server one step or in a long drop", () => { const old = EnvironmentId.make("old-server"); const ordered = [ makeThread({ id: ThreadId.make("a"), title: "a" }), @@ -1471,7 +1472,7 @@ it("allows a long drop past an old server even when both adjacent moves fail", ( }); const movedId = `${environmentId}:a`; expect(planner(movedId, "up")).toBeNull(); - expect(planner(movedId, "down")).toBeNull(); + expect(planner(movedId, "down")?.map(({ id }) => id)).toEqual([movedId]); const assignments = planner(movedId, { targetId: `${environmentId}:d`, placement: "after" }); expect(assignments).toHaveLength(1); expect(assignments![0]!.id).toBe(movedId); diff --git a/apps/mobile/src/features/threads/threadOrder.ts b/apps/mobile/src/features/threads/threadOrder.ts index 11e9482efcfd9..48a2e695b6bd2 100644 --- a/apps/mobile/src/features/threads/threadOrder.ts +++ b/apps/mobile/src/features/threads/threadOrder.ts @@ -1,5 +1,6 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { + activeThreadSortKey, generateSpreadPinOrderKeys, pinOrderKeyBetween, planPinnedReorder, @@ -72,9 +73,13 @@ function rowId(row: OrderRow): string { return `${row.environmentId}:${row.id}`; } +function storedKey(row: OrderRow, section: PendingThreadOrder["section"]) { + return (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null; +} + function rowOrder(row: OrderRow, section: PendingThreadOrder["section"]) { return { - key: (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null, + key: section === "pinned" ? storedKey(row, section) : activeThreadSortKey(row), anchor: section === "pinned" ? (row.pinnedAt ?? "") : (row.unsettledAt ?? row.createdAt), }; } @@ -88,12 +93,13 @@ export function createThreadMovePlanner(input: { }) { const orderedIds = input.ordered.map(rowId); const orderedIdSet = new Set(orderedIds); - const keysById = new Map( - (input.allThreads ?? input.ordered).map((row) => [ - rowId(row), - rowOrder(row, input.section).key, - ]), - ); + // Hidden rows keep their stored key: only stored keys can collide with a write. + const keysById = new Map([ + ...(input.allThreads ?? input.ordered).map( + (row) => [rowId(row), storedKey(row, input.section)] as const, + ), + ...input.ordered.map((row) => [rowId(row), rowOrder(row, input.section).key] as const), + ]); const writableIds = new Set( (input.allThreads ?? input.ordered) .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId)) @@ -144,9 +150,10 @@ export function computeThreadMoveAvailability(input: { const writableIds = new Set(); for (const row of input.allThreads ?? input.ordered) { const id = rowId(row); - keysById.set(id, rowOrder(row, input.section).key); + keysById.set(id, storedKey(row, input.section)); if (input.reorderableEnvironmentIds.has(row.environmentId)) writableIds.add(id); } + for (const row of rows) keysById.set(rowId(row), rowOrder(row, input.section).key); const reservedKeys = new Set(); keysById.forEach((key, id) => { if (key != null && !indexById.has(id)) reservedKeys.add(key); diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 50a987787b4e4..9942754660b8e 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -195,7 +195,7 @@ function PoolWindowCard({ const inlineLabels = wide && segmentWidth >= 96; const inlineReset = wide && segmentWidth >= 150; const inlineName = wide && segmentWidth >= 220; - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0); const openAccount = (account: LimitAccount) => navigation.navigate("SettingsUsageAccount", { accountKey: account.key, diff --git a/apps/mobile/src/features/voice-input/useVoiceInputController.test.tsx b/apps/mobile/src/features/voice-input/useVoiceInputController.test.tsx new file mode 100644 index 0000000000000..f6e5ae62836c3 --- /dev/null +++ b/apps/mobile/src/features/voice-input/useVoiceInputController.test.tsx @@ -0,0 +1,80 @@ +import { act, useEffect, useSyncExternalStore } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +const harness = vi.hoisted(() => ({ + session: null as import("./voiceInputSession").VoiceInputSession | null, +})); + +vi.mock("@react-navigation/native", () => ({ + useFocusEffect: (callback: () => void | (() => void)) => useEffect(callback, [callback]), +})); +vi.mock("./VoiceInputProvider", () => ({ + useGlobalVoiceInput: () => { + const session = harness.session!; + const snapshot = useSyncExternalStore(session.subscribe, session.getSnapshot); + return { ...snapshot, isAvailable: true, isBusy: false, session }; + }, +})); + +import { useVoiceInputController } from "./useVoiceInputController"; +import { VoiceInputSession } from "./voiceInputSession"; + +function Composer(props: { readonly hidden: boolean }) { + useVoiceInputController({ + ownerKey: "thread-1", + label: "Thread", + readDraftMessage: () => "", + selection: { start: 0, end: 0 }, + hidden: props.hidden, + onChangeDraftMessage: () => {}, + onChangeSelection: () => {}, + }); + return null; +} + +function setup() { + const session = new VoiceInputSession({ + recorder: { + uri: "file:///voice.m4a", + prepareToRecordAsync: async () => {}, + record: () => {}, + stop: async () => {}, + }, + getTranscriber: () => ({ + prepare: async () => ({ locale: "en-US", transcribe: async () => "" }), + }), + requestPermission: async () => ({ granted: true, canAskAgain: true }), + configureRecording: async () => {}, + releaseRecording: async () => {}, + deleteRecording: () => {}, + sampleRecording: () => null, + publishAudioLevels: () => {}, + keepAwake: () => () => {}, + }); + harness.session = session; + const root = createRoot(document.createElement("div")); + return { + isFocused: () => session.getSnapshot().focusedOwners.has("thread-1"), + render: (hidden: boolean) => act(() => root.render(