diff --git a/AGENTS.md b/AGENTS.md index 2ce4be8b77640..513ef65bf79db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -214,3 +214,12 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/ - Security is important, but should not be over-indexed on, especially for dev mode/maintainer-only features. - Before a security audit or triaging a vulnerability report, read [SECURITY.md](SECURITY.md) for the trust model and what is intended. + +## This fork + +This checkout is `batchema/t3code`, a personal fork. Its to-do list is the fork's GitHub Issues, not a file in the repo, so every branch sees the same list. + +- When asked to add a to-do, open an issue: `gh issue create --repo batchema/t3code`. Never file it upstream. +- `gh issue list --repo batchema/t3code` shows open work. +- A PR that finishes an issue says `Closes #N`; one that finishes part of it says `Part of #N`. +- The fork runs as Sanu Code beside an installed T3 Code, with its own data in `~/.sanucode`. `scripts/sanucode install` adds the `sanucode` and `sn` commands; `sn help` lists what they do. [Sanu Code](docs/operations/sanu-code.md) covers moving over from T3 Code and connecting devices. diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index e5b23a2627d9c..73969cdc81e57 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -73,6 +73,7 @@ import { threadListEnvironmentsAtom } from "../../state/presentation"; import type { PendingNewTask } from "../../state/use-pending-new-tasks"; import { useQueuedThreadKeys } from "../../state/use-thread-outbox"; import { + ThreadListV2InboxHeader, ThreadListV2PendingRow, ThreadListV2Row, ThreadListV2SettledShelfHeader, @@ -507,6 +508,9 @@ export function HomeScreen(props: HomeScreenProps) { /> ); } + if (item.type === "v2-inbox-header") { + return ; + } if (item.type === "v2-snoozed-shelf") { return ( ); + case "v2-inbox-header": + return ; case "v2-snoozed-shelf": return ( + appAtomRegistry.get(environmentPresentations.presentationsAtom).get(environmentId)?.entry.target + .label; + +/** Other connected machines this thread can move to, each with its projects. */ +export function readThreadMachineMoveTargets( + thread: EnvironmentThreadShell, + projects: ReadonlyArray, +): ReadonlyArray { + return threadMachineMoveTargets({ + sourceEnvironmentId: thread.environmentId, + connectedEnvironmentIds: appAtomRegistry.get(connectedEnvironmentIdsAtom), + serverConfigs: appAtomRegistry.get(environmentServerConfigsAtom), + projects, + labelOf: machineLabel, + canOperate: (environmentId) => + readEnvironmentScope(environmentId, AuthOrchestrationOperateScope), + }); +} + +export async function moveThreadToMachine( + thread: EnvironmentThreadShell, + machine: ThreadMachineMoveTarget, + project: EnvironmentProject, +): Promise { + const fromMachine = machineLabel(thread.environmentId) ?? "this machine"; + if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) { + Dialog.alert(m(msg("Could not move thread")), m(msg("This connection cannot change threads."))); + return; + } + const outcome = await runThreadMachineMove({ + registry: appAtomRegistry, + commands: projectEnvironment, + source: { environmentId: thread.environmentId, threadId: thread.id }, + sourceLabel: fromMachine, + target: { environmentId: machine.environmentId, projectId: project.id }, + targetLabel: `${project.title} on ${machine.label}`, + confirm: ({ leftBehind }) => + new Promise((resolve) => + Dialog.confirm({ + title: m( + msg('Move "{thread}" to {machine}?', { thread: thread.title, machine: machine.label }), + ), + message: threadMachineMoveNotice({ + fromMachine, + toMachine: machine.label, + projectTitle: project.title, + leftBehind, + }), + confirmText: m(msg("Move", { $context: "verb, moves a thread" })), + onCancel: () => resolve(false), + onConfirm: () => { + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); + resolve(true); + }, + }), + ), + resolve: m, + }); + if (outcome._tag === "Failed") Dialog.alert(m(msg("Could not move thread")), outcome.message); + if (outcome._tag === "Moved" && outcome.archiveError !== null) { + Dialog.alert( + m(msg("Moved, but the original is still active on {machine}", { machine: fromMachine })), + m( + msg("{error} The moved copy is on {machine}.", { + error: outcome.archiveError, + machine: machine.label, + }), + ), + ); + } +} diff --git a/apps/mobile/src/features/threads/moveThreadToProject.ts b/apps/mobile/src/features/threads/moveThreadToProject.ts new file mode 100644 index 0000000000000..8785c00c63366 --- /dev/null +++ b/apps/mobile/src/features/threads/moveThreadToProject.ts @@ -0,0 +1,66 @@ +import { threadMoveTargets, type EnvironmentProject } from "@t3tools/client-runtime/state/models"; +import { + isAtomCommandInterrupted, + runAtomCommand, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; +import { threadMoveNotice } from "@t3tools/shared/threadMove"; +import * as Haptics from "expo-haptics"; +import { msg } from "gt-react-native"; + +import * as Dialog from "../../components/ui/Dialog"; +import { m } from "../../i18n/messages"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { projectEnvironment } from "../../state/projects"; +import { environmentServerConfigsAtom } from "../../state/server"; +import { readEnvironmentScope } from "../../state/session"; + +/** Projects this thread can move into, on a server that can move it. */ +export function readThreadMoveTargets( + thread: EnvironmentThreadShell, + projects: ReadonlyArray, +): ReadonlyArray { + const config = appAtomRegistry.get(environmentServerConfigsAtom).get(thread.environmentId); + if (config?.environment.capabilities.threadMoveToProject !== true) return []; + return threadMoveTargets(projects, thread, config.scratchWorkspaceRoot); +} + +export function moveThreadToProject( + thread: EnvironmentThreadShell, + project: EnvironmentProject, +): void { + const failureTitle = m(msg("Could not move thread")); + if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) { + Dialog.alert(failureTitle, m(msg("This connection cannot change threads."))); + return; + } + Dialog.confirm({ + title: m( + msg('Move "{thread}" to {project}?', { thread: thread.title, project: project.title }), + ), + message: threadMoveNotice({ + projectTitle: project.title, + fromWorktree: thread.worktreePath !== null, + }), + confirmText: m(msg("Move", { $context: "verb, moves a thread" })), + onConfirm: () => { + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); + void runAtomCommand( + appAtomRegistry, + projectEnvironment.moveThread, + { + environmentId: thread.environmentId, + input: { threadId: thread.id, projectId: project.id }, + }, + { reportFailure: false }, + ).then((result) => { + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + Dialog.alert(failureTitle, error instanceof Error ? error.message : m(msg("Try again."))); + } + }); + }, + }); +} 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..e5fcfe86a8b14 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -11,6 +11,7 @@ import { import { RowPressable } from "../../components/ui/RowPressable"; import { CustomSnoozeSheet } from "./CustomSnoozeSheet"; import { appAtomRegistry } from "../../state/atom-registry"; +import { useProjects } from "../../state/entities"; import { threadArrangementOpenAtom } from "../../state/thread-order"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -74,6 +75,8 @@ import { useSwipeRowDormant } from "../home/swipe-row-activation"; import { ThreadSwipeable } from "../home/thread-swipe-actions"; import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu"; import { canTurnThreadIntoProject, turnThreadIntoProject } from "./turnThreadIntoProject"; +import { moveThreadToProject, readThreadMoveTargets } from "./moveThreadToProject"; +import { moveThreadToMachine, readThreadMachineMoveTargets } from "./moveThreadToMachine"; import { threadCanArchive } from "../home/threadArchive"; import { useCanShareWithGuest } from "./useCanShareWithGuest"; import { @@ -374,6 +377,18 @@ export const ThreadListV2WorkingShelfHeader = memo(function ThreadListV2WorkingS return ; }); +export const ThreadListV2InboxHeader = memo(function ThreadListV2InboxHeader(props: { + readonly pane?: "screen" | "sidebar"; +}) { + const gt = useGT(); + return ( + + ); +}); + export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader( props: ThreadListV2ShelfHeaderProps, ) { @@ -1060,6 +1075,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { [gt, props.autoSettleOptOutSupported, thread.autoSettleDisabledAt], ); const canTurnIntoProject = canTurnThreadIntoProject(thread); + const projects = useProjects(); + const moveTargets = useMemo(() => readThreadMoveTargets(thread, projects), [thread, projects]); + const machineMoveTargets = useMemo( + () => readThreadMachineMoveTargets(thread, projects), + [thread, projects], + ); const titleMenuItems = useMemo( () => [ { @@ -1085,11 +1106,44 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { } satisfies MenuAction, ] : []), + ...(moveTargets.length > 0 + ? [ + { + id: "move-to-project", + title: gt("Move to project"), + image: "folder", + attributes: { disabled: !threadCanArchive(thread.runtime) }, + subactions: moveTargets.map((project) => ({ + id: `move-to-project:${project.id}`, + title: project.title, + })), + } satisfies MenuAction, + ] + : []), + // One level: Android menus cannot nest a machine's projects inside a submenu. + ...(machineMoveTargets.length > 0 + ? [ + { + id: "move-to-machine", + title: gt("Move to machine"), + image: "server.rack", + attributes: { disabled: !threadCanArchive(thread.runtime) }, + subactions: machineMoveTargets.flatMap((machine, machineIndex) => + machine.projects.map((project, projectIndex) => ({ + id: `move-to-machine:${machineIndex}:${projectIndex}`, + title: `${project.title} · ${machine.label}`, + })), + ), + } satisfies MenuAction, + ] + : []), ], [ canTurnIntoProject, gt, m, + machineMoveTargets, + moveTargets, props.titleRegenerationSupported, thread.runtime, isRegeneratingTitle, @@ -1222,6 +1276,17 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { if (nativeEvent.event === "rename") handleRename(); if (nativeEvent.event === "regenerate-title") handleRegenerateTitle(); if (nativeEvent.event === "turn-into-project") void turnThreadIntoProject(thread); + const machinePick = /^move-to-machine:(\d+):(\d+)$/.exec(nativeEvent.event); + if (machinePick) { + const machine = machineMoveTargets[Number(machinePick[1])]; + const project = machine?.projects[Number(machinePick[2])]; + if (machine && project) void moveThreadToMachine(thread, machine, project); + } + if (nativeEvent.event.startsWith("move-to-project:")) { + const projectId = nativeEvent.event.slice("move-to-project:".length); + const project = moveTargets.find((candidate) => candidate.id === projectId); + if (project) moveThreadToProject(thread, project); + } if (nativeEvent.event === "mark-unread") { void markThreadUnread({ environmentId: thread.environmentId, @@ -1291,6 +1356,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { setCustomSnoozeOpen, snoozePresets, props.snoozePresets, + moveTargets, + machineMoveTargets, ], ); const primaryAction = useMemo(() => { diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 29f6e97b047b4..f4e02771ca919 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -1762,11 +1762,13 @@ describe("Working section beta", () => { "finished-early", ]); expect(layout.workingCount).toBe(1); - expect(layout.workingShelfHeaderIndex).toBe(4); + expect(layout.workingShelfHeaderIndex).toBe(1); + expect(layout.inboxHeaderIndex).toBe(1); const off = build({ workingShelfEnabled: false }); expect(ids(off)).toContain("working"); expect(off.workingCount).toBe(0); + expect(off.inboxHeaderIndex).toBeNull(); }); it("keeps an inactive row in Working during the shared grace and returns it on expiry", () => { @@ -1805,11 +1807,16 @@ describe("Working section beta", () => { expect(ids(layout).slice(1)).toEqual(["finished-early", "finished-late", "asks-approval"]); }); - it("places the shelf after queued tasks and before snoozed and settled threads", () => { + it("places the shelf above the inbox, after queued tasks and pinned threads", () => { const layout = buildThreadListV2Items({ threads: [ makeThread({ id: ThreadId.make("active"), title: "active" }), makeThread({ id: ThreadId.make("working"), title: "working", runtime: running }), + makeThread({ + id: ThreadId.make("pinned"), + title: "pinned", + pinnedAt: "2026-06-01T00:00:00.000Z", + }), makeThread({ id: ThreadId.make("snoozed"), title: "snoozed", @@ -1837,6 +1844,7 @@ describe("Working section beta", () => { workingCount: layout.workingCount, workingShelfExpanded: true, workingShelfHeaderIndex: layout.workingShelfHeaderIndex, + inboxHeaderIndex: layout.inboxHeaderIndex, snoozedCount: layout.snoozedCount, snoozedShelfExpanded: true, snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex, @@ -1853,9 +1861,11 @@ describe("Working section beta", () => { ), ).toEqual([ "queued", - "active", + "pinned", "v2-working-shelf", "working", + "v2-inbox-header", + "active", "v2-snoozed-shelf", "snoozed", "v2-settled-shelf", diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index b8029d3b0b189..a2a6bdd51dfd2 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -424,6 +424,8 @@ export interface ThreadListV2Layout { readonly listedSettledThreads: ReadonlyArray; readonly workingCount: number; readonly workingShelfHeaderIndex: number | null; + /** Only set below the Working shelf, which would otherwise read as owning these rows. */ + readonly inboxHeaderIndex: number | null; readonly snoozedCount: number; readonly snoozedShelfHeaderIndex: number | null; readonly settledCount: number; @@ -464,6 +466,11 @@ export interface ThreadListV2WorkingShelfListItem { readonly disabled: boolean; } +export interface ThreadListV2InboxHeaderListItem { + readonly type: "v2-inbox-header"; + readonly key: "v2-inbox-header"; +} + export interface ThreadListV2SnoozedShelfListItem { readonly type: "v2-snoozed-shelf"; readonly key: "v2-snoozed-shelf"; @@ -485,6 +492,7 @@ export type ThreadListV2ListItem = | ThreadListV2ThreadListItem | ThreadListV2PendingListItem | ThreadListV2WorkingShelfListItem + | ThreadListV2InboxHeaderListItem | ThreadListV2SnoozedShelfListItem | ThreadListV2SettledShelfListItem; @@ -495,6 +503,7 @@ export function isThreadListV2ListItem(value: { value.type === "v2-thread" || value.type === "v2-pending" || value.type === "v2-working-shelf" || + value.type === "v2-inbox-header" || value.type === "v2-snoozed-shelf" || value.type === "v2-settled-shelf" ); @@ -538,6 +547,8 @@ export function threadListV2ListItemsAreEqual( previous.expanded === item.expanded && previous.disabled === item.disabled ); + case "v2-inbox-header": + return previous.type === "v2-inbox-header"; case "v2-snoozed-shelf": return ( previous.type === "v2-snoozed-shelf" && @@ -584,6 +595,7 @@ export function buildThreadListV2ListItems(input: { readonly workingCount?: number; readonly workingShelfExpanded?: boolean; readonly workingShelfHeaderIndex?: number | null; + readonly inboxHeaderIndex?: number | null; readonly snoozedCount?: number; readonly snoozedShelfExpanded?: boolean; readonly snoozedShelfHeaderIndex?: number | null; @@ -639,14 +651,16 @@ export function buildThreadListV2ListItems(input: { })); const workingCount = input.workingCount ?? 0; const workingShelfHeaderIndex = input.workingShelfHeaderIndex ?? null; + const inboxHeaderIndex = input.inboxHeaderIndex ?? null; const snoozedCount = input.snoozedCount ?? 0; const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null; const settledCount = input.settledCount ?? 0; const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null; const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length; - const workingEnd = snoozedShelfHeaderIndex ?? snoozedEnd; - const activeEnd = workingShelfHeaderIndex ?? workingEnd; - const result: ThreadListV2ListItem[] = [...pendingItems, ...threadItems.slice(0, activeEnd)]; + const inboxEnd = snoozedShelfHeaderIndex ?? snoozedEnd; + const workingEnd = inboxHeaderIndex ?? inboxEnd; + const pinnedEnd = workingShelfHeaderIndex ?? workingEnd; + const result: ThreadListV2ListItem[] = [...pendingItems, ...threadItems.slice(0, pinnedEnd)]; const shelfDisabled = input.shelfPreferencesLoading === true; if (workingShelfHeaderIndex !== null && workingCount > 0) { result.push({ @@ -658,6 +672,10 @@ export function buildThreadListV2ListItems(input: { }); result.push(...threadItems.slice(workingShelfHeaderIndex, workingEnd)); } + if (inboxHeaderIndex !== null) { + result.push({ type: "v2-inbox-header", key: "v2-inbox-header" }); + result.push(...threadItems.slice(inboxHeaderIndex, inboxEnd)); + } if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) { result.push({ type: "v2-snoozed-shelf", @@ -852,6 +870,7 @@ export function buildThreadListV2Items(input: { listedSettledThreads: [], workingCount: 0, workingShelfHeaderIndex: null, + inboxHeaderIndex: null, snoozedCount: 0, snoozedShelfHeaderIndex: null, settledCount: 0, @@ -922,7 +941,8 @@ export function buildThreadListV2Items(input: { isLast: false, }); } - for (const thread of orderedActive) { + const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null; + for (const thread of visibleWorking) { items.push({ thread, variant: "card", @@ -932,8 +952,9 @@ export function buildThreadListV2Items(input: { isLast: false, }); } - const workingShelfHeaderIndex = orderedWorking.length > 0 ? items.length : null; - for (const thread of visibleWorking) { + const inboxHeaderIndex = + workingShelfHeaderIndex !== null && orderedActive.length > 0 ? items.length : null; + for (const thread of orderedActive) { items.push({ thread, variant: "card", @@ -975,6 +996,7 @@ export function buildThreadListV2Items(input: { listedSettledThreads: listedSettled, workingCount: orderedWorking.length, workingShelfHeaderIndex, + inboxHeaderIndex, snoozedCount: orderedSnoozed.length, snoozedShelfHeaderIndex, settledCount: settledTotal, diff --git a/apps/mobile/src/features/threads/useThreadListV2.ts b/apps/mobile/src/features/threads/useThreadListV2.ts index 3322dd3bd7ca3..3014e0c527813 100644 --- a/apps/mobile/src/features/threads/useThreadListV2.ts +++ b/apps/mobile/src/features/threads/useThreadListV2.ts @@ -218,6 +218,7 @@ export function useThreadListV2(input: { workingCount: layout.workingCount, workingShelfExpanded: input.workingShelfExpanded, workingShelfHeaderIndex: layout.workingShelfHeaderIndex, + inboxHeaderIndex: layout.inboxHeaderIndex, snoozedCount: layout.snoozedCount, snoozedShelfExpanded: input.snoozedShelfExpanded, snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 039e1ddadd0bf..ab060de1d6b0e 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} an", "77cc5f738cb7d459": "{label} aus", - "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", "aba3bb73ce212f0c": "{names} erfordert {providerName} {version} oder neuer, aber der Homebrew-Cask claude-code hat nur {latestVersion}. Wechsle zum Cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", "d887bea446534de5": "Kein Projekt in dieser Umgebung kann {host}/{repository} lesen.", "4e466d60e2f7736b": "Füge die vollständige Pull-Request-URL ein. Dieser Thread hat kein Repository, in dem die Nummer aufgelöst werden kann.", "302625058bacbe38": "Füge eine vollständige URL ein. Für den Host dieses Projekts ist kein {changeRequest}-URL-Format bekannt.", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Versucht, Designs {count}-mal zu prüfen} other {Versucht, Designs {count}-mal zu prüfen}}", "a16ae702cbb60dde": "{count, plural, one {Design {count}-mal festgelegt} other {Design {count}-mal festgelegt}}", "978b4b05bea775d1": "{count, plural, one {Versucht, das Design {count}-mal festzulegen} other {Versucht, das Design {count}-mal festzulegen}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Verknüpfte Umgebungen {count}-mal aufgelistet} other {Verknüpfte Umgebungen {count}-mal aufgelistet}}", "78d34854295169a7": "{count, plural, one {Versucht, verknüpfte Umgebungen {count}-mal aufzulisten} other {Versucht, verknüpfte Umgebungen {count}-mal aufzulisten}}", "07edf9b32bf1f437": "{count, plural, one {Browser {count}-mal verwendet} other {Browser {count}-mal verwendet}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Feedback an OpenAI gesendet.\n\nThread-ID: `{feedbackId}`", "de62133b5898fab1": "Feedback konnte nicht an OpenAI gesendet werden.\n\n{errorMessage}", "0bed322f6071f4da": "Ein Fehler ist aufgetreten.", + "448735c0084132f5": "Versuche es erneut.", "78f82fef9e0c8661": "Repositorys", "2360ad0503c2a0a8": "Repositorys auswählen", "05b16c85cb1e18bd": "Keine Repositorys", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "Die lokale Datei ist nicht verfügbar. Hänge sie erneut an.", "68883cb3342998e5": "Verbinde dich erneut mit der Umgebung und versuche es noch einmal.", "43f6af4554b019cf": "Anhang konnte nicht geöffnet werden", - "448735c0084132f5": "Versuche es erneut.", "601807baf4e25b94": "Vorschau von {name}", "7d3b922d9826854c": "Anhang wird geöffnet…", "659bc8494984c900": "Anhang öffnen oder teilen", @@ -1948,9 +1952,9 @@ "a5e3ff0d1a60b766": "Relay-Zugriff der Umgebung konnte nicht konfiguriert werden: {detail}", "7d508fe978cb0f3b": "Aus", "3ae222ec888dd171": "Trace-ID:", - "be00d572b18076d8": "Lange drücken, um von diesem Gerät zu entfernen", "46e2a0e828785d97": "{environment} verwalten", "5392155ec0c8b0be": "{environment} von diesem Gerät entfernen", + "be00d572b18076d8": "Lange drücken, um von diesem Gerät zu entfernen", "782a518513f0777a": "{environment} aktivieren", "a35685d9ad9de747": "Verknüpfte Cloud-Umgebungen werden geladen.", "91ca3ba7b2f9d6b6": "Keine weiteren verknüpften Cloud-Umgebungen.", @@ -2757,6 +2761,7 @@ "665abe47a0f4612b": "Checks fehlgeschlagen", "09d74034d376c535": "Checks ausstehend", "91e832d25ff2aba9": "{term, select, mr {Merge Request {number}} cr {Änderungsanfrage {number}} other {Pull Request {number}}}", + "bbb7d40a7ad7ab71": "Privat", "37f84b2c7830febb": "Stack {position} von {size}", "0469747f4bb9caac": "{additions} Hinzufügungen, {deletions} Löschungen", "4e3cdb7e814e8962": "Doppeltippen zum Öffnen. Gedrückt halten für Schnellaktionen.", @@ -2851,7 +2856,6 @@ "f9d3c8aa453829ce": "Tippe auf eine Person, um ein Review anzufordern. Tippe auf einen angefragten Reviewer, um die Anfrage zu entfernen. Änderungen werden beim Schließen dieses Fensters gesendet.", "8d3770f150f0bcb4": "Angefragt", "fff1c3d17603f394": "Dieser Anbieter akzeptiert eine Reviewer-ID, kann aber keine Kandidaten auflisten.", - "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Basis-Branch {branch} kopieren", "06a684782801e8f7": "Head-Branch {branch} kopieren", "8e4f3c862193b8a5": "Bearbeiten", @@ -4782,6 +4786,11 @@ "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.}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "Aktueller Worktree", "731c754897f77b89": "{term, select, mr {Aus MR #{number}} cr {Aus Änderungsanfrage #{number}} other {Aus PR #{number}}}", "3a05fec4b1d0f0a0": "Branch wählen", @@ -4824,6 +4833,7 @@ "905197486607072f": "Verwerfen", "02c0ae493e689f90": "Ziel", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Eingang", "694e089caefce25f": "{count, plural, one {{count} weiteren erledigten Thread anzeigen} other {{count} weitere erledigte Threads anzeigen}}", "ece9e2869077cbb6": "{title} verwerfen", "306a6f95ad9d52f7": "Nicht gesendet", @@ -4842,6 +4852,8 @@ "7171d7551e7cd04e": "Umbenennen", "dffd2e20f7ff5aa1": "Als ungelesen markieren", "1385e2d8bd696370": "In Projekt umwandeln", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "Thread kopieren", "7b24be8e29a2efc5": "Thread-ID kopieren", "4205928193aec525": "Zurückstellen", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 91170171c1621..070d91ce7342e 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} On", "77cc5f738cb7d459": "{label} Off", - "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", "aba3bb73ce212f0c": "Using {names} requires {providerName} {version} or newer, but the claude-code Homebrew cask only has {latestVersion}. Switch to the claude-code@latest cask: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", "d887bea446534de5": "No project in this environment can read {host}/{repository}.", "4e466d60e2f7736b": "Paste the full pull request URL; this thread has no repository to resolve the number against.", "302625058bacbe38": "Paste a full URL; this project's host has no known {changeRequest} URL.", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Tried to check themes {count} time} other {Tried to check themes {count} times}}", "a16ae702cbb60dde": "{count, plural, one {Set the theme {count} time} other {Set the theme {count} times}}", "978b4b05bea775d1": "{count, plural, one {Tried to set the theme {count} time} other {Tried to set the theme {count} times}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Listed linked environments {count} time} other {Listed linked environments {count} times}}", "78d34854295169a7": "{count, plural, one {Tried to list linked environments {count} time} other {Tried to list linked environments {count} times}}", "07edf9b32bf1f437": "{count, plural, one {Used browser {count} time} other {Used browser {count} times}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Feedback sent to OpenAI.\n\nThread ID: `{feedbackId}`", "de62133b5898fab1": "Could not send feedback to OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "An error occurred.", + "448735c0084132f5": "Try again.", "78f82fef9e0c8661": "Repositories", "2360ad0503c2a0a8": "Choose repositories", "05b16c85cb1e18bd": "No repositories", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "The local file is unavailable. Attach it again.", "68883cb3342998e5": "Reconnect to the environment and try again.", "43f6af4554b019cf": "Could not open attachment", - "448735c0084132f5": "Try again.", "601807baf4e25b94": "Preview {name}", "7d3b922d9826854c": "Opening attachment…", "659bc8494984c900": "Open or share attachment", @@ -1948,9 +1952,9 @@ "a5e3ff0d1a60b766": "Could not configure environment relay access: {detail}", "7d508fe978cb0f3b": "Off", "3ae222ec888dd171": "Trace ID:", - "be00d572b18076d8": "Long press to remove from this device", "46e2a0e828785d97": "Manage {environment}", "5392155ec0c8b0be": "Remove {environment} from this device", + "be00d572b18076d8": "Long press to remove from this device", "782a518513f0777a": "Enable {environment}", "a35685d9ad9de747": "Loading linked cloud environments.", "91ca3ba7b2f9d6b6": "No additional linked cloud environments.", @@ -2757,6 +2761,7 @@ "665abe47a0f4612b": "Checks failing", "09d74034d376c535": "Checks pending", "91e832d25ff2aba9": "{term, select, mr {Merge request} cr {Change request} other {Pull request}} {number}", + "bbb7d40a7ad7ab71": "Private", "37f84b2c7830febb": "stack {position} of {size}", "0469747f4bb9caac": "{additions} additions, {deletions} deletions", "4e3cdb7e814e8962": "Double tap to open. Touch and hold for quick actions.", @@ -2851,7 +2856,6 @@ "f9d3c8aa453829ce": "Tap someone to request a review. Tap a requested reviewer to remove the request. Changes are sent when you close this sheet.", "8d3770f150f0bcb4": "Requested", "fff1c3d17603f394": "This provider accepts a reviewer ID but cannot list candidates.", - "bbb7d40a7ad7ab71": "Private", "85ae9979ad3b0c1e": "Copy base branch {branch}", "06a684782801e8f7": "Copy head branch {branch}", "8e4f3c862193b8a5": "Edit", @@ -4784,6 +4788,11 @@ "93ac0c76ae6a2a3b": "The shared content is no longer in the inbox.", "72e35523181b36eb": "Server attachment support is still loading.", "100ddd593ab0b485": "{count, plural, one {{count} shared file was skipped because this draft reached the attachment limit.} other {{count} shared files were skipped because this draft reached the attachment limit.}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "Current worktree", "731c754897f77b89": "{term, select, mr {From MR #{number}} cr {From change request #{number}} other {From PR #{number}}}", "3a05fec4b1d0f0a0": "Choose branch", @@ -4826,6 +4835,7 @@ "905197486607072f": "Discard", "02c0ae493e689f90": "Goal", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Inbox", "694e089caefce25f": "{count, plural, one {Show {count} more settled threads} other {Show {count} more settled threads}}", "ece9e2869077cbb6": "Discard {title}", "306a6f95ad9d52f7": "Unsent", @@ -4844,6 +4854,8 @@ "7171d7551e7cd04e": "Rename", "dffd2e20f7ff5aa1": "Mark unread", "1385e2d8bd696370": "Turn into project", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "Copy thread", "7b24be8e29a2efc5": "Copy thread ID", "4205928193aec525": "Snooze", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 398c20ce17f1f..3d7bd20f07881 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activado", "77cc5f738cb7d459": "{label} desactivado", - "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", "aba3bb73ce212f0c": "Usar {names} requiere {providerName} {version} o posterior, pero el cask de Homebrew claude-code solo tiene {latestVersion}. Cambia al cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", "d887bea446534de5": "Ningún proyecto de este entorno puede leer {host}/{repository}.", "4e466d60e2f7736b": "Pega la URL completa de la pull request; este hilo no tiene ningún repositorio con el que resolver el número.", "302625058bacbe38": "Pega una URL completa; el host de este proyecto no tiene una URL de {changeRequest} conocida.", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Intentó consultar los temas {count} vez} other {Intentó consultar los temas {count} veces}}", "a16ae702cbb60dde": "{count, plural, one {Cambió el tema {count} vez} other {Cambió el tema {count} veces}}", "978b4b05bea775d1": "{count, plural, one {Intentó cambiar el tema {count} vez} other {Intentó cambiar el tema {count} veces}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Listó entornos vinculados {count} vez} other {Listó entornos vinculados {count} veces}}", "78d34854295169a7": "{count, plural, one {Intentó listar entornos vinculados {count} vez} other {Intentó listar entornos vinculados {count} veces}}", "07edf9b32bf1f437": "{count, plural, one {Se usó el navegador {count} vez} other {Se usó el navegador {count} veces}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Comentarios enviados a OpenAI.\n\nID del hilo: `{feedbackId}`", "de62133b5898fab1": "No se pudieron enviar los comentarios a OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Se produjo un error.", + "448735c0084132f5": "Vuelve a intentarlo.", "78f82fef9e0c8661": "Repositorios", "2360ad0503c2a0a8": "Elegir repositorios", "05b16c85cb1e18bd": "Sin repositorios", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "El archivo local no está disponible. Vuelve a adjuntarlo.", "68883cb3342998e5": "Vuelve a conectarte al entorno e inténtalo de nuevo.", "43f6af4554b019cf": "No se pudo abrir el adjunto", - "448735c0084132f5": "Vuelve a intentarlo.", "601807baf4e25b94": "Vista previa de {name}", "7d3b922d9826854c": "Abriendo adjunto…", "659bc8494984c900": "Abrir o compartir adjunto", @@ -1948,9 +1952,9 @@ "a5e3ff0d1a60b766": "No se pudo configurar el acceso del entorno al relay: {detail}", "7d508fe978cb0f3b": "Apagado", "3ae222ec888dd171": "ID de traza:", - "be00d572b18076d8": "Mantén pulsado para quitarlo de este dispositivo", "46e2a0e828785d97": "Gestionar {environment}", "5392155ec0c8b0be": "Quitar {environment} de este dispositivo", + "be00d572b18076d8": "Mantén pulsado para quitarlo de este dispositivo", "782a518513f0777a": "Activar {environment}", "a35685d9ad9de747": "Cargando entornos en la nube vinculados.", "91ca3ba7b2f9d6b6": "No hay más entornos en la nube vinculados.", @@ -2753,6 +2757,7 @@ "665abe47a0f4612b": "Comprobaciones con fallos", "09d74034d376c535": "Comprobaciones pendientes", "91e832d25ff2aba9": "{term, select, mr {Merge request} cr {Solicitud de cambios} other {Pull request}} {number}", + "bbb7d40a7ad7ab71": "Privado", "37f84b2c7830febb": "pila {position} de {size}", "0469747f4bb9caac": "{additions} adiciones, {deletions} eliminaciones", "4e3cdb7e814e8962": "Toca dos veces para abrir. Mantén pulsado para ver acciones rápidas.", @@ -2847,7 +2852,6 @@ "f9d3c8aa453829ce": "Toca a alguien para solicitarle una revisión. Toca a un revisor solicitado para quitar la solicitud. Los cambios se envían al cerrar esta hoja.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este proveedor acepta un ID de revisor, pero no puede listar candidatos.", - "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar la rama base {branch}", "06a684782801e8f7": "Copiar la rama head {branch}", "8e4f3c862193b8a5": "Editar", @@ -4775,6 +4779,11 @@ "93ac0c76ae6a2a3b": "El contenido compartido ya no está en la bandeja de entrada.", "72e35523181b36eb": "La compatibilidad del servidor con adjuntos aún se está cargando.", "100ddd593ab0b485": "{count, plural, one {Se omitió {count} archivo compartido porque este borrador alcanzó el límite de adjuntos.} other {Se omitieron {count} archivos compartidos porque este borrador alcanzó el límite de adjuntos.}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "Worktree actual", "731c754897f77b89": "{term, select, mr {De la MR #{number}} cr {De la solicitud de cambios #{number}} other {De la PR #{number}}}", "3a05fec4b1d0f0a0": "Elegir rama", @@ -4817,6 +4826,7 @@ "905197486607072f": "Descartar", "02c0ae493e689f90": "Objetivo", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Bandeja de entrada", "694e089caefce25f": "{count, plural, one {Mostrar {count} hilo resuelto más} other {Mostrar {count} hilos resueltos más}}", "ece9e2869077cbb6": "Descartar {title}", "306a6f95ad9d52f7": "Sin enviar", @@ -4835,6 +4845,8 @@ "7171d7551e7cd04e": "Renombrar", "dffd2e20f7ff5aa1": "Marcar como no leído", "1385e2d8bd696370": "Convertir en proyecto", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "Copiar hilo", "7b24be8e29a2efc5": "Copiar ID del hilo", "4205928193aec525": "Posponer", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 1734d91934a04..a0343040117ee 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activé", "77cc5f738cb7d459": "{label} désactivé", - "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", "aba3bb73ce212f0c": "{names} nécessite {providerName} {version} ou une version plus récente, mais le cask Homebrew claude-code ne propose que {latestVersion}. Passe au cask claude-code@latest : {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", "d887bea446534de5": "Aucun projet de cet environnement ne peut lire {host}/{repository}.", "4e466d60e2f7736b": "Collez l’URL complète de la pull request ; ce fil n’a pas de dépôt auquel rattacher le numéro.", "302625058bacbe38": "Collez une URL complète ; l’hôte de ce projet n’a pas de format d’URL connu pour {changeRequest}.", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Tentative de vérifier les thèmes {count} fois} other {Tentative de vérifier les thèmes {count} fois}}", "a16ae702cbb60dde": "{count, plural, one {Thème défini {count} fois} other {Thème défini {count} fois}}", "978b4b05bea775d1": "{count, plural, one {Tentative de définir le thème {count} fois} other {Tentative de définir le thème {count} fois}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Environnements associés listés {count} fois} other {Environnements associés listés {count} fois}}", "78d34854295169a7": "{count, plural, one {Tentative de lister les environnements associés {count} fois} other {Tentative de lister les environnements associés {count} fois}}", "07edf9b32bf1f437": "{count, plural, one {Navigateur utilisé {count} fois} other {Navigateur utilisé {count} fois}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Commentaires envoyés à OpenAI.\n\nID du fil : `{feedbackId}`", "de62133b5898fab1": "Impossible d’envoyer les commentaires à OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Une erreur s’est produite.", + "448735c0084132f5": "Réessayez.", "78f82fef9e0c8661": "Dépôts", "2360ad0503c2a0a8": "Choisir les dépôts", "05b16c85cb1e18bd": "Aucun dépôt", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "Le fichier local n’est pas disponible. Joignez-le à nouveau.", "68883cb3342998e5": "Reconnectez-vous à l’environnement et réessayez.", "43f6af4554b019cf": "Impossible d’ouvrir la pièce jointe", - "448735c0084132f5": "Réessayez.", "601807baf4e25b94": "Aperçu de {name}", "7d3b922d9826854c": "Ouverture de la pièce jointe…", "659bc8494984c900": "Ouvrir ou partager la pièce jointe", @@ -1948,9 +1952,9 @@ "a5e3ff0d1a60b766": "Impossible de configurer l’accès au relais de l’environnement : {detail}", "7d508fe978cb0f3b": "Éteint", "3ae222ec888dd171": "ID de trace :", - "be00d572b18076d8": "Appuyez longuement pour retirer de cet appareil", "46e2a0e828785d97": "Gérer {environment}", "5392155ec0c8b0be": "Retirer {environment} de cet appareil", + "be00d572b18076d8": "Appuyez longuement pour retirer de cet appareil", "782a518513f0777a": "Activer {environment}", "a35685d9ad9de747": "Chargement des environnements cloud associés.", "91ca3ba7b2f9d6b6": "Aucun autre environnement cloud associé.", @@ -2753,6 +2757,7 @@ "665abe47a0f4612b": "Vérifications en échec", "09d74034d376c535": "Vérifications en attente", "91e832d25ff2aba9": "{term, select, mr {Merge request} cr {Demande de modification} other {Pull request}} {number}", + "bbb7d40a7ad7ab71": "Privé", "37f84b2c7830febb": "pile {position} sur {size}", "0469747f4bb9caac": "{additions} ajouts, {deletions} suppressions", "4e3cdb7e814e8962": "Touchez deux fois pour ouvrir. Appuyez longuement pour les actions rapides.", @@ -2847,7 +2852,6 @@ "f9d3c8aa453829ce": "Touchez une personne pour lui demander une revue. Touchez un relecteur sollicité pour retirer la demande. Les modifications sont envoyées à la fermeture de ce panneau.", "8d3770f150f0bcb4": "Sollicité", "fff1c3d17603f394": "Ce fournisseur accepte un ID de relecteur mais ne peut pas lister les candidats.", - "bbb7d40a7ad7ab71": "Privé", "85ae9979ad3b0c1e": "Copier la branche de base {branch}", "06a684782801e8f7": "Copier la branche de tête {branch}", "8e4f3c862193b8a5": "Modifier", @@ -4776,6 +4780,11 @@ "93ac0c76ae6a2a3b": "Le contenu partagé n’est plus dans la boîte de réception.", "72e35523181b36eb": "La prise en charge des pièces jointes par le serveur est encore en cours de chargement.", "100ddd593ab0b485": "{count, plural, one {{count} fichier partagé a été ignoré car ce brouillon a atteint la limite de pièces jointes.} other {{count} fichiers partagés ont été ignorés car ce brouillon a atteint la limite de pièces jointes.}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "Worktree actuel", "731c754897f77b89": "{term, select, mr {Depuis la MR #{number}} cr {Depuis la demande de modification #{number}} other {Depuis la PR #{number}}}", "3a05fec4b1d0f0a0": "Choisir une branche", @@ -4818,6 +4827,7 @@ "905197486607072f": "Abandonner", "02c0ae493e689f90": "Objectif", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Réception", "694e089caefce25f": "{count, plural, one {Afficher {count} autre fil clos} other {Afficher {count} autres fils clos}}", "ece9e2869077cbb6": "Supprimer {title}", "306a6f95ad9d52f7": "Non envoyées", @@ -4836,6 +4846,8 @@ "7171d7551e7cd04e": "Renommer", "dffd2e20f7ff5aa1": "Marquer comme non lu", "1385e2d8bd696370": "Transformer en projet", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "Copier le fil", "7b24be8e29a2efc5": "Copier l’ID du fil", "4205928193aec525": "Reporter", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 113ada551f17d..a2ad0b83ff7ee 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "標準", "f42c2a36b3507308": "{label} オン", "77cc5f738cb7d459": "{label} オフ", - "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", "aba3bb73ce212f0c": "{names} を使うには {providerName} {version} 以降が必要ですが、Homebrew の claude-code cask には {latestVersion} までしかありません。claude-code@latest cask に切り替えてください: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", "d887bea446534de5": "この環境には {host}/{repository} を読み取れるプロジェクトがありません。", "4e466d60e2f7736b": "プルリクエストの完全な URL を貼り付けてください。このスレッドには番号を解決するためのリポジトリがありません。", "302625058bacbe38": "完全な URL を貼り付けてください。このプロジェクトのホストには既知の {changeRequest} URL がありません。", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, other {テーマを {count} 回確認しようとしました}}", "a16ae702cbb60dde": "{count, plural, other {テーマを {count} 回設定しました}}", "978b4b05bea775d1": "{count, plural, other {テーマを {count} 回設定しようとしました}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, other {リンク済みの環境を {count} 回一覧表示しました}}", "78d34854295169a7": "{count, plural, other {リンク済みの環境を {count} 回一覧表示しようとしました}}", "07edf9b32bf1f437": "{count, plural, other {ブラウザーを {count} 回使用しました}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "OpenAI にフィードバックを送信しました。\n\nスレッド ID: `{feedbackId}`", "de62133b5898fab1": "OpenAI にフィードバックを送信できませんでした。\n\n{errorMessage}", "0bed322f6071f4da": "エラーが発生しました。", + "448735c0084132f5": "もう一度お試しください。", "78f82fef9e0c8661": "リポジトリ", "2360ad0503c2a0a8": "リポジトリを選択", "05b16c85cb1e18bd": "リポジトリなし", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "ローカルファイルを利用できません。もう一度添付してください。", "68883cb3342998e5": "環境に再接続して、もう一度お試しください。", "43f6af4554b019cf": "添付ファイルを開けませんでした", - "448735c0084132f5": "もう一度お試しください。", "601807baf4e25b94": "{name} をプレビュー", "7d3b922d9826854c": "添付ファイルを開いています…", "659bc8494984c900": "添付ファイルを開くまたは共有", @@ -1948,9 +1952,9 @@ "a5e3ff0d1a60b766": "環境のリレーアクセスを構成できませんでした: {detail}", "7d508fe978cb0f3b": "オフ", "3ae222ec888dd171": "トレース ID:", - "be00d572b18076d8": "長押しでこのデバイスから削除", "46e2a0e828785d97": "{environment} を管理", "5392155ec0c8b0be": "このデバイスから {environment} を削除", + "be00d572b18076d8": "長押しでこのデバイスから削除", "782a518513f0777a": "{environment} を有効にする", "a35685d9ad9de747": "リンクされたクラウド環境を読み込んでいます。", "91ca3ba7b2f9d6b6": "他にリンクされたクラウド環境はありません。", @@ -2750,6 +2754,7 @@ "665abe47a0f4612b": "チェック失敗", "09d74034d376c535": "チェック保留中", "91e832d25ff2aba9": "{term, select, mr {マージリクエスト {number}} cr {変更リクエスト {number}} other {プルリクエスト {number}}}", + "bbb7d40a7ad7ab71": "プライベート", "37f84b2c7830febb": "スタック {size} 件中 {position} 件目", "0469747f4bb9caac": "{additions} 行追加、{deletions} 行削除", "4e3cdb7e814e8962": "ダブルタップで開きます。長押しでクイック操作を表示します。", @@ -2844,7 +2849,6 @@ "f9d3c8aa453829ce": "ユーザーをタップするとレビューをリクエストします。リクエスト済みのレビュアーをタップするとリクエストを削除します。変更はこのシートを閉じたときに送信されます。", "8d3770f150f0bcb4": "リクエスト済み", "fff1c3d17603f394": "このプロバイダーはレビュアー ID を受け付けますが、候補を一覧表示できません。", - "bbb7d40a7ad7ab71": "プライベート", "85ae9979ad3b0c1e": "ベースブランチ {branch} をコピー", "06a684782801e8f7": "ヘッドブランチ {branch} をコピー", "8e4f3c862193b8a5": "編集", @@ -4756,6 +4760,11 @@ "93ac0c76ae6a2a3b": "共有されたコンテンツは受信トレイにありません。", "72e35523181b36eb": "サーバーの添付ファイル対応状況をまだ読み込んでいます。", "100ddd593ab0b485": "{count, plural, other {この下書きが添付ファイルの上限に達したため、共有された {count} 個のファイルをスキップしました。}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "現在のワークツリー", "731c754897f77b89": "{term, select, mr {MR #{number} から} cr {変更リクエスト #{number} から} other {PR #{number} から}}", "3a05fec4b1d0f0a0": "ブランチを選択", @@ -4798,6 +4807,7 @@ "905197486607072f": "破棄", "02c0ae493e689f90": "ゴール", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "受信トレイ", "694e089caefce25f": "{count, plural, other {対応済みのスレッドをさらに {count} 件表示}}", "ece9e2869077cbb6": "{title} を破棄", "306a6f95ad9d52f7": "未送信", @@ -4816,6 +4826,8 @@ "7171d7551e7cd04e": "名前を変更", "dffd2e20f7ff5aa1": "未読にする", "1385e2d8bd696370": "プロジェクトに変換", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "スレッドをコピー", "7b24be8e29a2efc5": "スレッド ID をコピー", "4205928193aec525": "スヌーズ", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 7768bd410d434..6e1567a0c80e6 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "보통", "f42c2a36b3507308": "{label} 켜짐", "77cc5f738cb7d459": "{label} 꺼짐", - "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", "aba3bb73ce212f0c": "{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만 Homebrew claude-code cask에는 {latestVersion}까지만 있습니다. claude-code@latest cask로 전환하세요: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", "d887bea446534de5": "이 환경에는 {host}/{repository}을(를) 읽을 수 있는 프로젝트가 없습니다.", "4e466d60e2f7736b": "전체 풀 리퀘스트 URL을 붙여 넣으세요. 이 스레드에는 번호를 확인할 저장소가 없습니다.", "302625058bacbe38": "전체 URL을 붙여 넣으세요. 이 프로젝트의 호스트에는 알려진 {changeRequest} URL이 없습니다.", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, other {테마 확인 {count}회 시도함}}", "a16ae702cbb60dde": "{count, plural, other {테마 {count}회 설정함}}", "978b4b05bea775d1": "{count, plural, other {테마 설정 {count}회 시도함}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, other {연결된 환경 목록 {count}회 조회함}}", "78d34854295169a7": "{count, plural, other {연결된 환경 목록 조회 {count}회 시도함}}", "07edf9b32bf1f437": "{count, plural, other {브라우저 {count}번 사용함}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "OpenAI에 피드백을 보냈습니다.\n\n스레드 ID: `{feedbackId}`", "de62133b5898fab1": "OpenAI에 피드백을 보낼 수 없습니다.\n\n{errorMessage}", "0bed322f6071f4da": "오류가 발생했습니다.", + "448735c0084132f5": "다시 시도하세요.", "78f82fef9e0c8661": "저장소", "2360ad0503c2a0a8": "저장소 선택", "05b16c85cb1e18bd": "저장소 없음", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "로컬 파일을 사용할 수 없습니다. 다시 첨부하세요.", "68883cb3342998e5": "환경에 다시 연결한 후 다시 시도하세요.", "43f6af4554b019cf": "첨부 파일을 열 수 없습니다", - "448735c0084132f5": "다시 시도하세요.", "601807baf4e25b94": "{name} 미리 보기", "7d3b922d9826854c": "첨부 파일 여는 중…", "659bc8494984c900": "첨부 파일 열기 또는 공유", @@ -1949,9 +1953,9 @@ "a5e3ff0d1a60b766": "환경 릴레이 액세스를 구성할 수 없습니다: {detail}", "7d508fe978cb0f3b": "꺼짐", "3ae222ec888dd171": "추적 ID:", - "be00d572b18076d8": "길게 눌러 이 기기에서 제거", "46e2a0e828785d97": "{environment} 관리", "5392155ec0c8b0be": "이 기기에서 {environment} 제거", + "be00d572b18076d8": "길게 눌러 이 기기에서 제거", "782a518513f0777a": "{environment} 사용", "a35685d9ad9de747": "연결된 클라우드 환경 불러오는 중입니다.", "91ca3ba7b2f9d6b6": "추가로 연결된 클라우드 환경이 없습니다.", @@ -2754,6 +2758,7 @@ "665abe47a0f4612b": "검사 실패", "09d74034d376c535": "검사 대기 중", "91e832d25ff2aba9": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} {number}", + "bbb7d40a7ad7ab71": "비공개", "37f84b2c7830febb": "스택 {size}개 중 {position}번째", "0469747f4bb9caac": "추가 {additions}개, 삭제 {deletions}개", "4e3cdb7e814e8962": "두 번 탭하여 엽니다. 길게 누르면 빠른 작업을 볼 수 있습니다.", @@ -2848,7 +2853,6 @@ "f9d3c8aa453829ce": "검토를 요청하려면 사람을 탭하세요. 요청을 제거하려면 요청된 검토자를 탭하세요. 변경 사항은 이 시트를 닫을 때 전송됩니다.", "8d3770f150f0bcb4": "요청됨", "fff1c3d17603f394": "이 제공자는 검토자 ID를 받지만 후보를 나열할 수 없습니다.", - "bbb7d40a7ad7ab71": "비공개", "85ae9979ad3b0c1e": "기준 브랜치 {branch} 복사", "06a684782801e8f7": "헤드 브랜치 {branch} 복사", "8e4f3c862193b8a5": "편집", @@ -4761,6 +4765,11 @@ "93ac0c76ae6a2a3b": "공유된 콘텐츠가 더 이상 인박스에 없습니다.", "72e35523181b36eb": "서버의 첨부 파일 지원 정보를 아직 불러오는 중입니다.", "100ddd593ab0b485": "{count, plural, other {이 초안이 첨부 파일 한도에 도달해 공유된 파일 {count}개를 건너뛰었습니다.}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "현재 워크트리", "731c754897f77b89": "{term, select, mr {MR #{number}에서} cr {변경 요청 #{number}에서} other {PR #{number}에서}}", "3a05fec4b1d0f0a0": "브랜치 선택", @@ -4803,6 +4812,7 @@ "905197486607072f": "삭제", "02c0ae493e689f90": "목표", "13300e8565fbd665": "{label}({count})", + "8327da16dcfdb504": "수신함", "694e089caefce25f": "{count, plural, other {정리된 스레드 {count}개 더 보기}}", "ece9e2869077cbb6": "{title} 삭제", "306a6f95ad9d52f7": "보내지 않음", @@ -4821,6 +4831,8 @@ "7171d7551e7cd04e": "이름 바꾸기", "dffd2e20f7ff5aa1": "읽지 않음으로 표시", "1385e2d8bd696370": "프로젝트로 전환", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "스레드 복사", "7b24be8e29a2efc5": "스레드 ID 복사", "4205928193aec525": "다시 알림", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 88dbb8da5cd87..c9c048d5ff98d 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} ativado", "77cc5f738cb7d459": "{label} desativado", - "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", "aba3bb73ce212f0c": "Usar {names} requer {providerName} {version} ou mais recente, mas o cask claude-code do Homebrew só tem {latestVersion}. Mude para o cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", "d887bea446534de5": "Nenhum projeto neste ambiente consegue ler {host}/{repository}.", "4e466d60e2f7736b": "Cole a URL completa do pull request; esta thread não tem repositório para resolver o número.", "302625058bacbe38": "Cole uma URL completa; o host deste projeto não tem uma URL de {changeRequest} conhecida.", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Tentou verificar os temas {count} vez} other {Tentou verificar os temas {count} vezes}}", "a16ae702cbb60dde": "{count, plural, one {Definiu o tema {count} vez} other {Definiu o tema {count} vezes}}", "978b4b05bea775d1": "{count, plural, one {Tentou definir o tema {count} vez} other {Tentou definir o tema {count} vezes}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Listou os ambientes vinculados {count} vez} other {Listou os ambientes vinculados {count} vezes}}", "78d34854295169a7": "{count, plural, one {Tentou listar os ambientes vinculados {count} vez} other {Tentou listar os ambientes vinculados {count} vezes}}", "07edf9b32bf1f437": "{count, plural, one {Usou o navegador {count} vez} other {Usou o navegador {count} vezes}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Feedback enviado para a OpenAI.\n\nID da thread: `{feedbackId}`", "de62133b5898fab1": "Não foi possível enviar o feedback para a OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Ocorreu um erro.", + "448735c0084132f5": "Tente novamente.", "78f82fef9e0c8661": "Repositórios", "2360ad0503c2a0a8": "Escolher repositórios", "05b16c85cb1e18bd": "Nenhum repositório", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "O arquivo local não está disponível. Anexe-o novamente.", "68883cb3342998e5": "Reconecte-se ao ambiente e tente novamente.", "43f6af4554b019cf": "Não foi possível abrir o anexo", - "448735c0084132f5": "Tente novamente.", "601807baf4e25b94": "Pré-visualizar {name}", "7d3b922d9826854c": "Abrindo anexo…", "659bc8494984c900": "Abrir ou compartilhar anexo", @@ -1948,9 +1952,9 @@ "a5e3ff0d1a60b766": "Não foi possível configurar o acesso do ambiente ao relay: {detail}", "7d508fe978cb0f3b": "Desligado", "3ae222ec888dd171": "ID do trace:", - "be00d572b18076d8": "Mantenha pressionado para remover deste dispositivo", "46e2a0e828785d97": "Gerenciar {environment}", "5392155ec0c8b0be": "Remover {environment} deste dispositivo", + "be00d572b18076d8": "Mantenha pressionado para remover deste dispositivo", "782a518513f0777a": "Ativar {environment}", "a35685d9ad9de747": "Carregando ambientes na nuvem vinculados.", "91ca3ba7b2f9d6b6": "Nenhum outro ambiente na nuvem vinculado.", @@ -2753,6 +2757,7 @@ "665abe47a0f4612b": "Verificações falhando", "09d74034d376c535": "Verificações pendentes", "91e832d25ff2aba9": "{term, select, mr {Merge request} cr {Solicitação de alteração} other {Pull request}} {number}", + "bbb7d40a7ad7ab71": "Privado", "37f84b2c7830febb": "pilha {position} de {size}", "0469747f4bb9caac": "{additions} adições, {deletions} remoções", "4e3cdb7e814e8962": "Toque duas vezes para abrir. Toque e segure para ver ações rápidas.", @@ -2847,7 +2852,6 @@ "f9d3c8aa453829ce": "Toque em alguém para solicitar uma revisão. Toque em um revisor solicitado para remover a solicitação. As alterações são enviadas quando você fecha esta folha.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este provedor aceita um ID de revisor, mas não consegue listar candidatos.", - "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar branch base {branch}", "06a684782801e8f7": "Copiar branch head {branch}", "8e4f3c862193b8a5": "Editar", @@ -4776,6 +4780,11 @@ "93ac0c76ae6a2a3b": "O conteúdo compartilhado não está mais na caixa de entrada.", "72e35523181b36eb": "O suporte a anexos do servidor ainda está carregando.", "100ddd593ab0b485": "{count, plural, one {{count} arquivo compartilhado foi ignorado porque este rascunho atingiu o limite de anexos.} other {{count} arquivos compartilhados foram ignorados porque este rascunho atingiu o limite de anexos.}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "Worktree atual", "731c754897f77b89": "{term, select, mr {Do MR #{number}} cr {Da solicitação de alteração #{number}} other {Do PR #{number}}}", "3a05fec4b1d0f0a0": "Escolher branch", @@ -4818,6 +4827,7 @@ "905197486607072f": "Descartar", "02c0ae493e689f90": "Meta", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Caixa de entrada", "694e089caefce25f": "{count, plural, one {Mostrar mais {count} thread concluída} other {Mostrar mais {count} threads concluídas}}", "ece9e2869077cbb6": "Descartar {title}", "306a6f95ad9d52f7": "Não enviadas", @@ -4836,6 +4846,8 @@ "7171d7551e7cd04e": "Renomear", "dffd2e20f7ff5aa1": "Marcar como não lida", "1385e2d8bd696370": "Transformar em projeto", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "Copiar thread", "7b24be8e29a2efc5": "Copiar ID da thread", "4205928193aec525": "Adiar", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 2d0fb55302031..785b85c9377ea 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Обычная", "f42c2a36b3507308": "{label}: вкл.", "77cc5f738cb7d459": "{label}: выкл.", - "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", "aba3bb73ce212f0c": "Для {names} нужен {providerName} {version} или новее, но в Homebrew cask claude-code есть только {latestVersion}. Перейдите на cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", "d887bea446534de5": "Ни один проект в этом окружении не может прочитать {host}/{repository}.", "4e466d60e2f7736b": "Вставьте полный URL пул-реквеста: у этого треда нет репозитория, по которому можно найти номер.", "302625058bacbe38": "Вставьте полный URL: для хоста этого проекта неизвестен формат URL {changeRequest}.", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Попытка проверить темы: {count} раз} few {Попытка проверить темы: {count} раза} many {Попытка проверить темы: {count} раз} other {Попытка проверить темы: {count} раза}}", "a16ae702cbb60dde": "{count, plural, one {Тема задана {count} раз} few {Тема задана {count} раза} many {Тема задана {count} раз} other {Тема задана {count} раза}}", "978b4b05bea775d1": "{count, plural, one {Попытка задать тему: {count} раз} few {Попытка задать тему: {count} раза} many {Попытка задать тему: {count} раз} other {Попытка задать тему: {count} раза}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Список привязанных окружений получен {count} раз} few {Список привязанных окружений получен {count} раза} many {Список привязанных окружений получен {count} раз} other {Список привязанных окружений получен {count} раза}}", "78d34854295169a7": "{count, plural, one {Попытка получить список привязанных окружений: {count} раз} few {Попытка получить список привязанных окружений: {count} раза} many {Попытка получить список привязанных окружений: {count} раз} other {Попытка получить список привязанных окружений: {count} раза}}", "07edf9b32bf1f437": "{count, plural, one {Браузер использован {count} раз} few {Браузер использован {count} раза} many {Браузер использован {count} раз} other {Браузер использован {count} раза}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Отзыв отправлен в OpenAI.\n\nID треда: `{feedbackId}`", "de62133b5898fab1": "Не удалось отправить отзыв в OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Произошла ошибка.", + "448735c0084132f5": "Повторите попытку.", "78f82fef9e0c8661": "Репозитории", "2360ad0503c2a0a8": "Выбрать репозитории", "05b16c85cb1e18bd": "Нет репозиториев", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "Локальный файл недоступен. Прикрепите его снова.", "68883cb3342998e5": "Переподключитесь к окружению и повторите попытку.", "43f6af4554b019cf": "Не удалось открыть вложение", - "448735c0084132f5": "Повторите попытку.", "601807baf4e25b94": "Предпросмотр {name}", "7d3b922d9826854c": "Открытие вложения…", "659bc8494984c900": "Открыть вложение или поделиться им", @@ -1972,9 +1976,9 @@ "a5e3ff0d1a60b766": "Не удалось настроить доступ окружения к relay: {detail}", "7d508fe978cb0f3b": "Выкл.", "3ae222ec888dd171": "ID трассировки:", - "be00d572b18076d8": "Нажмите и удерживайте, чтобы удалить с этого устройства", "46e2a0e828785d97": "Управление {environment}", "5392155ec0c8b0be": "Удалить {environment} с этого устройства", + "be00d572b18076d8": "Нажмите и удерживайте, чтобы удалить с этого устройства", "782a518513f0777a": "Включить {environment}", "a35685d9ad9de747": "Загрузка привязанных облачных окружений.", "91ca3ba7b2f9d6b6": "Других привязанных облачных окружений нет.", @@ -2805,6 +2809,7 @@ "665abe47a0f4612b": "Проверки не проходят", "09d74034d376c535": "Проверки выполняются", "91e832d25ff2aba9": "{term, select, mr {Мерж-реквест} cr {Запрос на изменение} other {Пул-реквест}} {number}", + "bbb7d40a7ad7ab71": "Приватный", "37f84b2c7830febb": "стек {position} из {size}", "0469747f4bb9caac": "Добавлено строк: {additions}, удалено: {deletions}", "4e3cdb7e814e8962": "Дважды нажмите, чтобы открыть. Нажмите и удерживайте для быстрых действий.", @@ -2899,7 +2904,6 @@ "f9d3c8aa453829ce": "Нажмите на человека, чтобы запросить ревью. Нажмите на запрошенного ревьюера, чтобы отменить запрос. Изменения отправляются при закрытии этой панели.", "8d3770f150f0bcb4": "Запрошен", "fff1c3d17603f394": "Этот провайдер принимает ID ревьюера, но не может показать список кандидатов.", - "bbb7d40a7ad7ab71": "Приватный", "85ae9979ad3b0c1e": "Копировать базовую ветку {branch}", "06a684782801e8f7": "Копировать head-ветку {branch}", "8e4f3c862193b8a5": "Изменить", @@ -4854,6 +4858,11 @@ "93ac0c76ae6a2a3b": "Общего контента больше нет во входящих.", "72e35523181b36eb": "Поддержка вложений на сервере ещё загружается.", "100ddd593ab0b485": "{count, plural, one {{count} файл пропущен: в черновике достигнут лимит вложений.} few {{count} файла пропущено: в черновике достигнут лимит вложений.} many {{count} файлов пропущено: в черновике достигнут лимит вложений.} other {{count} файла пропущено: в черновике достигнут лимит вложений.}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "Текущее рабочее дерево", "731c754897f77b89": "{term, select, mr {Из MR #{number}} cr {Из запроса на изменение #{number}} other {Из PR #{number}}}", "3a05fec4b1d0f0a0": "Выбрать ветку", @@ -4896,6 +4905,7 @@ "905197486607072f": "Отбросить", "02c0ae493e689f90": "Цель", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Входящие", "694e089caefce25f": "{count, plural, one {Показать ещё {count} разобранный тред} few {Показать ещё {count} разобранных треда} many {Показать ещё {count} разобранных тредов} other {Показать ещё {count} разобранного треда}}", "ece9e2869077cbb6": "Удалить {title}", "306a6f95ad9d52f7": "Неотправленные", @@ -4914,6 +4924,8 @@ "7171d7551e7cd04e": "Переименовать", "dffd2e20f7ff5aa1": "Отметить непрочитанным", "1385e2d8bd696370": "Превратить в проект", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "Копировать тред", "7b24be8e29a2efc5": "Копировать ID треда", "4205928193aec525": "Отложить", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 70617afd183ca..74573dcdebe04 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} på", "77cc5f738cb7d459": "{label} av", - "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", "aba3bb73ce212f0c": "{names} kräver {providerName} {version} eller senare, men Homebrew-casken claude-code har bara {latestVersion}. Byt till casken claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", "d887bea446534de5": "Inget projekt i den här miljön kan läsa {host}/{repository}.", "4e466d60e2f7736b": "Klistra in hela pull request-URL:en; den här tråden har inget repo att slå upp numret i.", "302625058bacbe38": "Klistra in en fullständig URL; det här projektets värd har ingen känd URL för {changeRequest}.", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Försökte kontrollera teman {count} gång} other {Försökte kontrollera teman {count} gånger}}", "a16ae702cbb60dde": "{count, plural, one {Valde tema {count} gång} other {Valde tema {count} gånger}}", "978b4b05bea775d1": "{count, plural, one {Försökte välja tema {count} gång} other {Försökte välja tema {count} gånger}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Listade länkade miljöer {count} gång} other {Listade länkade miljöer {count} gånger}}", "78d34854295169a7": "{count, plural, one {Försökte lista länkade miljöer {count} gång} other {Försökte lista länkade miljöer {count} gånger}}", "07edf9b32bf1f437": "{count, plural, one {Använde webbläsaren {count} gång} other {Använde webbläsaren {count} gånger}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Feedback skickad till OpenAI.\n\nTråd-ID: `{feedbackId}`", "de62133b5898fab1": "Kunde inte skicka feedback till OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Ett fel uppstod.", + "448735c0084132f5": "Försök igen.", "78f82fef9e0c8661": "Repon", "2360ad0503c2a0a8": "Välj repon", "05b16c85cb1e18bd": "Inga repon", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "Den lokala filen är inte tillgänglig. Bifoga den igen.", "68883cb3342998e5": "Återanslut till miljön och försök igen.", "43f6af4554b019cf": "Kunde inte öppna bilagan", - "448735c0084132f5": "Försök igen.", "601807baf4e25b94": "Förhandsvisa {name}", "7d3b922d9826854c": "Öppnar bilagan…", "659bc8494984c900": "Öppna eller dela bilaga", @@ -1948,9 +1952,9 @@ "a5e3ff0d1a60b766": "Kunde inte konfigurera miljöns reläåtkomst: {detail}", "7d508fe978cb0f3b": "Av", "3ae222ec888dd171": "Spårnings-id:", - "be00d572b18076d8": "Tryck länge för att ta bort från den här enheten", "46e2a0e828785d97": "Hantera {environment}", "5392155ec0c8b0be": "Ta bort {environment} från den här enheten", + "be00d572b18076d8": "Tryck länge för att ta bort från den här enheten", "782a518513f0777a": "Aktivera {environment}", "a35685d9ad9de747": "Läser in länkade molnmiljöer.", "91ca3ba7b2f9d6b6": "Inga ytterligare länkade molnmiljöer.", @@ -2757,6 +2761,7 @@ "665abe47a0f4612b": "Kontroller misslyckas", "09d74034d376c535": "Kontroller väntar", "91e832d25ff2aba9": "{term, select, mr {Merge request} cr {Ändringsbegäran} other {Pull request}} {number}", + "bbb7d40a7ad7ab71": "Privat", "37f84b2c7830febb": "stack {position} av {size}", "0469747f4bb9caac": "{additions} tillägg, {deletions} borttagningar", "4e3cdb7e814e8962": "Dubbeltryck för att öppna. Tryck och håll för snabbåtgärder.", @@ -2851,7 +2856,6 @@ "f9d3c8aa453829ce": "Tryck på någon för att begära en granskning. Tryck på en begärd granskare för att ta bort begäran. Ändringarna skickas när du stänger det här bladet.", "8d3770f150f0bcb4": "Begärd", "fff1c3d17603f394": "Leverantören accepterar ett granskar-id men kan inte lista kandidater.", - "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Kopiera basgrenen {branch}", "06a684782801e8f7": "Kopiera huvudgrenen {branch}", "8e4f3c862193b8a5": "Redigera", @@ -4782,6 +4786,11 @@ "93ac0c76ae6a2a3b": "Det delade innehållet finns inte längre i inkorgen.", "72e35523181b36eb": "Serverns stöd för bilagor läses fortfarande in.", "100ddd593ab0b485": "{count, plural, one {{count} delad fil hoppades över eftersom utkastet nådde gränsen för bilagor.} other {{count} delade filer hoppades över eftersom utkastet nådde gränsen för bilagor.}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "Aktuell worktree", "731c754897f77b89": "{term, select, mr {Från MR #{number}} cr {Från ändringsbegäran #{number}} other {Från PR #{number}}}", "3a05fec4b1d0f0a0": "Välj gren", @@ -4824,6 +4833,7 @@ "905197486607072f": "Kasta", "02c0ae493e689f90": "Mål", "13300e8565fbd665": "{label} ({count})", + "8327da16dcfdb504": "Inkorg", "694e089caefce25f": "{count, plural, one {Visa {count} klar tråd till} other {Visa {count} klara trådar till}}", "ece9e2869077cbb6": "Kasta {title}", "306a6f95ad9d52f7": "Ej skickade", @@ -4842,6 +4852,8 @@ "7171d7551e7cd04e": "Byt namn", "dffd2e20f7ff5aa1": "Markera som oläst", "1385e2d8bd696370": "Gör om till projekt", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "Kopiera tråd", "7b24be8e29a2efc5": "Kopiera tråd-id", "4205928193aec525": "Snooza", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 485d4206bf054..5bd4cce90bb7c 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -118,9 +118,9 @@ "c4eb2b21c8c58a54": "普通", "f42c2a36b3507308": "{label} 开启", "77cc5f738cb7d459": "{label} 关闭", - "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", "aba3bb73ce212f0c": "使用 {names} 需要 {providerName} {version} 或更高版本,但 Homebrew 的 claude-code cask 只有 {latestVersion}。请切换到 claude-code@latest cask:{command}", + "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", + "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", "d887bea446534de5": "此环境中没有项目能读取 {host}/{repository}。", "4e466d60e2f7736b": "请粘贴完整的 pull request URL;此会话没有可用于解析编号的仓库。", "302625058bacbe38": "请粘贴完整 URL;此项目的托管平台没有已知的 {changeRequest} URL。", @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, other {尝试检查主题 {count} 次}}", "a16ae702cbb60dde": "{count, plural, other {已设置主题 {count} 次}}", "978b4b05bea775d1": "{count, plural, other {尝试设置主题 {count} 次}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, other {已列出关联的环境 {count} 次}}", "78d34854295169a7": "{count, plural, other {尝试列出关联的环境 {count} 次}}", "07edf9b32bf1f437": "{count, plural, other {已使用浏览器 {count} 次}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "已向 OpenAI 发送反馈。会话 ID:`{feedbackId}`", "de62133b5898fab1": "无法向 OpenAI 发送反馈。\n\n{errorMessage}", "0bed322f6071f4da": "发生错误。", + "448735c0084132f5": "请重试。", "78f82fef9e0c8661": "仓库", "2360ad0503c2a0a8": "选择仓库", "05b16c85cb1e18bd": "无仓库", @@ -1341,7 +1346,6 @@ "c04cd8ec791956cb": "本地文件不可用。请重新附加。", "68883cb3342998e5": "请重新连接环境后重试。", "43f6af4554b019cf": "无法打开附件", - "448735c0084132f5": "请重试。", "601807baf4e25b94": "预览 {name}", "7d3b922d9826854c": "正在打开附件…", "659bc8494984c900": "打开或分享附件", @@ -1950,9 +1954,9 @@ "a5e3ff0d1a60b766": "无法配置环境的中继访问:{detail}", "7d508fe978cb0f3b": "关闭", "3ae222ec888dd171": "追踪 ID:", - "be00d572b18076d8": "长按以从此设备移除", "46e2a0e828785d97": "管理 {environment}", "5392155ec0c8b0be": "从此设备移除 {environment}", + "be00d572b18076d8": "长按以从此设备移除", "782a518513f0777a": "启用 {environment}", "a35685d9ad9de747": "正在加载关联的云环境。", "91ca3ba7b2f9d6b6": "没有其他关联的云环境。", @@ -2754,6 +2758,7 @@ "665abe47a0f4612b": "检查失败", "09d74034d376c535": "检查待定", "91e832d25ff2aba9": "{term, select, mr {MR} cr {change request} other {PR}} {number}", + "bbb7d40a7ad7ab71": "私有", "37f84b2c7830febb": "堆叠第 {position}/{size} 层", "0469747f4bb9caac": "{additions} 处新增,{deletions} 处删除", "4e3cdb7e814e8962": "轻点两下以打开。长按以执行快捷操作。", @@ -2848,7 +2853,6 @@ "f9d3c8aa453829ce": "轻点某人以请求审查。轻点已请求的审查者以移除请求。关闭此面板时会发送更改。", "8d3770f150f0bcb4": "已请求", "fff1c3d17603f394": "此提供方接受审查者 ID,但无法列出候选人。", - "bbb7d40a7ad7ab71": "私有", "85ae9979ad3b0c1e": "复制基础分支 {branch}", "06a684782801e8f7": "复制头部分支 {branch}", "8e4f3c862193b8a5": "编辑", @@ -4765,6 +4769,11 @@ "93ac0c76ae6a2a3b": "共享内容已不在收件箱中。", "72e35523181b36eb": "仍在加载服务器的附件支持信息。", "100ddd593ab0b485": "{count, plural, other {此草稿已达到附件数量上限,已跳过 {count} 个共享文件。}}", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "23c6ae5b54403ea2": "Move", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", "a9d0457b171de12d": "当前工作树", "731c754897f77b89": "{term, select, mr {来自 MR #{number}} cr {来自 change request #{number}} other {来自 PR #{number}}}", "3a05fec4b1d0f0a0": "选择分支", @@ -4807,6 +4816,7 @@ "905197486607072f": "放弃", "02c0ae493e689f90": "目标", "13300e8565fbd665": "{label}({count})", + "8327da16dcfdb504": "收件箱", "694e089caefce25f": "{count, plural, other {再显示 {count} 个已收尾的会话}}", "ece9e2869077cbb6": "丢弃 {title}", "306a6f95ad9d52f7": "未发送", @@ -4825,6 +4835,8 @@ "7171d7551e7cd04e": "重命名", "dffd2e20f7ff5aa1": "标为未读", "1385e2d8bd696370": "转换为项目", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "a1fcc064a5cece14": "复制会话", "7b24be8e29a2efc5": "复制会话 ID", "4205928193aec525": "暂缓", diff --git a/apps/server/src/appControl/AppControl.test.ts b/apps/server/src/appControl/AppControl.test.ts new file mode 100644 index 0000000000000..dd8f863040a7a --- /dev/null +++ b/apps/server/src/appControl/AppControl.test.ts @@ -0,0 +1,62 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { expect, it } from "@effect/vitest"; +import { type AppCommand, AuthSessionId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import * as AppControl from "./AppControl.ts"; + +const commandAction = (command: AppCommand) => ({ _tag: "command", command }) as const; +const makeAppControl = AppControl.make.pipe(Effect.provide(NodeCrypto.layer)); +const desktop = { sessionId: AuthSessionId.make("desktop"), windowId: "socket-a:0" }; +const browser = { sessionId: AuthSessionId.make("browser"), windowId: "socket-b:0" }; +// Another tab of the same browser: same session and RPC client id, its own socket. +const browserTab = { ...browser, windowId: "socket-c:0" }; + +it.effect("runs a command in the window used most recently and returns its answer", () => + Effect.gen(function* () { + const appControl = yield* makeAppControl; + const desktopRequests = yield* appControl.connect(desktop, false); + const browserRequests = yield* appControl.connect(browser, true); + // A tab connecting in the background doesn't take over from the one in use. + yield* appControl.connect(browserTab, false).pipe(Effect.asVoid); + const toBrowser = yield* appControl.run(commandAction("sidebar.toggle")).pipe(Effect.forkChild); + const browserRequest = Option.getOrThrow(yield* Stream.runHead(browserRequests)); + yield* appControl.respond(browser.sessionId, { + requestId: browserRequest.requestId, + result: "ran", + }); + expect(yield* Fiber.join(toBrowser)).toBe("ran"); + yield* appControl.reportFocus(desktop, true); + const run = yield* appControl.run(commandAction("terminal.toggle")).pipe(Effect.forkChild); + const request = Option.getOrThrow(yield* Stream.runHead(desktopRequests)); + expect(request.action).toEqual(commandAction("terminal.toggle")); + // Another session cannot answer for this window. + yield* appControl.respond(browser.sessionId, { requestId: request.requestId, result: "ran" }); + yield* appControl.respond(desktop.sessionId, { + requestId: request.requestId, + result: "not-handled", + }); + expect(yield* Fiber.join(run)).toBe("not-handled"); + }).pipe(Effect.scoped), +); + +it.effect("fails when no window is open or the window does not answer", () => + Effect.gen(function* () { + const appControl = yield* makeAppControl; + yield* Effect.scoped(appControl.connect(desktop, true).pipe(Effect.asVoid)); + expect( + yield* appControl.run(commandAction("terminal.toggle")).pipe(Effect.flip), + ).toBeInstanceOf(AppControl.AppControlNoWindowError); + const requests = yield* appControl.connect(desktop, true); + const run = yield* appControl.run(commandAction("terminal.toggle")).pipe(Effect.forkChild); + yield* Stream.runHead(requests); + yield* TestClock.adjust("5 seconds"); + expect(yield* Fiber.join(run).pipe(Effect.flip)).toBeInstanceOf( + AppControl.AppControlTimeoutError, + ); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/appControl/AppControl.ts b/apps/server/src/appControl/AppControl.ts new file mode 100644 index 0000000000000..86bdb41125a37 --- /dev/null +++ b/apps/server/src/appControl/AppControl.ts @@ -0,0 +1,176 @@ +import type { + AppAction, + AppControlRequest, + AppControlResponseInput, + AppControlResult, + AuthSessionId, +} from "@t3tools/contracts"; +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 Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +/** One window's connection to this server. */ +export interface AppControlClient { + readonly sessionId: AuthSessionId; + /** Unique per socket and RPC client, since tabs share a session. */ + readonly windowId: string; +} + +export class AppControlNoWindowError extends Schema.TaggedError()( + "AppControlNoWindowError", + {}, +) {} + +export class AppControlTimeoutError extends Schema.TaggedError()( + "AppControlTimeoutError", + {}, +) {} + +const RESPONSE_TIMEOUT = "5 seconds"; + +export class AppControl extends Context.Service< + AppControl, + { + /** Registers a window; the commands sent to it arrive until the scope closes. */ + readonly connect: ( + client: AppControlClient, + focused: boolean, + ) => Effect.Effect, never, Scope.Scope>; + readonly reportFocus: (client: AppControlClient, focused: boolean) => Effect.Effect; + readonly respond: ( + sessionId: AuthSessionId, + response: AppControlResponseInput, + ) => Effect.Effect; + /** Runs an action in the window used most recently, returning what the window answered. */ + readonly run: ( + action: AppAction, + ) => Effect.Effect; + } +>()("t3/appControl/AppControl") {} + +interface Window { + readonly sessionId: AuthSessionId; + readonly queue: Queue.Queue; + readonly focusOrder: number; +} + +interface Pending { + readonly sessionId: AuthSessionId; + readonly deferred: Deferred.Deferred; +} + +interface State { + readonly windows: ReadonlyMap; + readonly pending: ReadonlyMap; + readonly focusSequence: number; +} + +const windowKey = (client: AppControlClient) => `${client.sessionId}:${client.windowId}`; + +export const make = Effect.gen(function* () { + const random = yield* SecureRandom.SecureRandom; + const state = yield* Ref.make({ + windows: new Map(), + pending: new Map(), + focusSequence: 0, + }); + + /** Marks a window as the one used most recently. */ + const focusWindow = (current: State, key: string, window: Omit): State => { + const focusSequence = current.focusSequence + 1; + const windows = new Map(current.windows).set(key, { ...window, focusOrder: focusSequence }); + return { ...current, windows, focusSequence }; + }; + + const connect: AppControl["Service"]["connect"] = (client, focused) => + Effect.acquireRelease( + Effect.gen(function* () { + const queue = yield* Queue.unbounded(); + const window = { sessionId: client.sessionId, queue }; + // A window connecting in the background ranks below every window used before. + yield* Ref.update(state, (current) => + focused + ? focusWindow(current, windowKey(client), window) + : { + ...current, + windows: new Map(current.windows).set(windowKey(client), { + ...window, + focusOrder: 0, + }), + }, + ); + return queue; + }), + (queue) => + Ref.update(state, (current) => { + if (current.windows.get(windowKey(client))?.queue !== queue) return current; + const windows = new Map(current.windows); + windows.delete(windowKey(client)); + return { ...current, windows }; + }), + ).pipe(Effect.map((queue) => Stream.fromQueue(queue))); + + const reportFocus: AppControl["Service"]["reportFocus"] = (client, focused) => + Ref.update(state, (current) => { + const window = current.windows.get(windowKey(client)); + return focused && window !== undefined + ? focusWindow(current, windowKey(client), window) + : current; + }); + + const respond: AppControl["Service"]["respond"] = Effect.fn("AppControl.respond")( + function* (sessionId, response) { + const pending = yield* Ref.get(state).pipe( + Effect.map((current) => current.pending.get(response.requestId)), + ); + if (pending?.sessionId !== sessionId) return; + yield* Deferred.succeed(pending.deferred, response.result); + }, + ); + + const run: AppControl["Service"]["run"] = Effect.fn("AppControl.run")(function* (action) { + const requestId = yield* random.uuidV4(); + const deferred = yield* Deferred.make(); + const target = yield* Ref.modify(state, (current) => { + const window = Array.from(current.windows.values()).reduce( + (latest, next) => + latest === undefined || next.focusOrder > latest.focusOrder ? next : latest, + undefined, + ); + if (window === undefined) return [undefined, current] as const; + const pending = new Map(current.pending).set(requestId, { + sessionId: window.sessionId, + deferred, + }); + return [window, { ...current, pending }] as const; + }); + if (target === undefined) return yield* new AppControlNoWindowError(); + const removePending = Ref.update(state, (current) => { + const pending = new Map(current.pending); + pending.delete(requestId); + return { ...current, pending }; + }); + return yield* Queue.offer(target.queue, { requestId, action }).pipe( + Effect.andThen(Deferred.await(deferred).pipe(Effect.timeoutOption(RESPONSE_TIMEOUT))), + Effect.flatMap( + Option.match({ + onNone: () => Effect.fail(new AppControlTimeoutError()), + onSome: Effect.succeed, + }), + ), + Effect.ensuring(removePending), + ); + }); + + return AppControl.of({ connect, reportFocus, respond, run }); +}); + +export const layer = Layer.effect(AppControl, make); diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index df89a0287e127..83834aa09112d 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -83,6 +83,15 @@ describe("RPC authorization scopes", () => { } }); + it("lets thread readers export a conversation but only operators move one in or archive it", () => { + expect(requiredScopeForRpcMethod(WS_METHODS.projectsExportThread)).toBe( + AuthOrchestrationReadScope, + ); + for (const method of [WS_METHODS.projectsImportThread, WS_METHODS.projectsFinishThreadMove]) { + expect(requiredScopeForRpcMethod(method)).toBe(AuthOrchestrationOperateScope); + } + }); + it("lets file readers see a task folder and takes source control to add a repository to it", () => { expect(requiredScopeForRpcMethod(WS_METHODS.workspaceTaskFolder)).toBe(AuthFilesystemReadScope); expect(requiredScopeForRpcMethod(WS_METHODS.workspaceAddTaskFolderRepository)).toBe( diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index ffe84c428a67a..bc06d8cdfbf28 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -179,6 +179,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.projectsWriteFile]: AuthFilesystemWriteScope, [WS_METHODS.projectsEnsureScratch]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateNew]: AuthOrchestrationOperateScope, + [WS_METHODS.projectsExportThread]: AuthOrchestrationReadScope, [WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope, [WS_METHODS.filesystemBrowse]: AuthFilesystemReadScope, [WS_METHODS.workspaceListFolders]: AuthFilesystemReadScope, @@ -226,6 +227,8 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.previewReportStatus]: AuthPreviewOperateScope, [WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope, [WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope, + [WS_METHODS.subscribeAppControl]: AuthOrchestrationReadScope, + [WS_METHODS.appControlRespond]: AuthOrchestrationReadScope, [WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope, [WS_METHODS.deviceConfigure]: AuthSettingsWriteScope, [WS_METHODS.deviceTestHost]: AuthSettingsWriteScope, diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index d3dec1efe59ff..f980e2f5ef033 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -15,7 +15,12 @@ import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts"; import * as CheckpointStore from "./CheckpointStore.ts"; -import { CheckpointRefUnavailableError, CheckpointTurnRangeUnavailableError } from "./Errors.ts"; +import { + CheckpointFolderMissingError, + CheckpointRangeSpansFoldersError, + CheckpointRefUnavailableError, + CheckpointTurnRangeUnavailableError, +} from "./Errors.ts"; const threadId = ThreadId.make("thread:checkpoint-diff-v2"); const firstRunId = RunId.make("run:checkpoint-diff-v2:1"); @@ -51,6 +56,7 @@ function layerFor(input: { readonly projection: Effect.Effect; readonly diffCheckpoints?: CheckpointStore.CheckpointStore["Service"]["diffCheckpoints"]; readonly authoredPaths?: ReadonlySet; + readonly missingFolder?: string; }) { return CheckpointDiffQuery.layer.pipe( Layer.provide( @@ -58,6 +64,7 @@ function layerFor(input: { Layer.mock(ThreadManagement.ThreadManagementService)({ getCheckpointContext: () => input.projection, }), + FileSystem.layerNoop({ exists: (path) => Effect.succeed(path !== input.missingFolder) }), Layer.mock(CheckpointStore.CheckpointStore)({ diffCheckpoints: input.diffCheckpoints ?? (() => Effect.succeed("diff")), listAuthoredPaths: () => Effect.succeed(input.authoredPaths ?? null), @@ -190,6 +197,70 @@ it.effect.each([false, true])( }, ); +it.effect("diffs a moved thread's turns in their own folders and names a missing one", () => { + const checkpoint = ( + scopeId: CheckpointScopeId, + ordinalWithinScope: number, + runId: RunId | null, + appRunOrdinal: number | null, + ): ProjectionCheckpointContext["checkpoints"][number] => ({ + scopeId, + runId, + ordinalWithinScope, + appRunOrdinal, + status: "ready", + ref: CheckpointRef.make(`refs/t3/test/${scopeId}/${ordinalWithinScope}`), + }); + const projection: ProjectionCheckpointContext = { + runs: [ + { id: firstRunId, ordinal: 1, status: "completed" }, + { id: secondRunId, ordinal: 2, status: "completed" }, + ], + checkpointScopes: [ + { id: firstScopeId, runId: firstRunId, kind: "root_run", cwd: "/repo-before-move" }, + { id: secondScopeId, runId: secondRunId, kind: "root_run", cwd: "/repo-after-move" }, + ], + checkpoints: [ + checkpoint(firstScopeId, 0, null, null), + checkpoint(firstScopeId, 1, firstRunId, 1), + checkpoint(secondScopeId, 0, null, null), + checkpoint(secondScopeId, 1, secondRunId, 2), + ], + }; + const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) => + Effect.succeed("diff --git a/file b/file"), + ); + + return Effect.gen(function* () { + const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; + yield* query.getTurnDiff({ threadId, fromTurnCount: 1, toTurnCount: 2 }); + assert.deepEqual( + diffCheckpoints.mock.calls.map(([input]) => [input.cwd, input.fromCheckpointRef]), + [["/repo-after-move", `refs/t3/test/${secondScopeId}/0`]], + ); + assert.instanceOf( + yield* query.getFullThreadDiff({ threadId, toTurnCount: 2 }).pipe(Effect.flip), + CheckpointRangeSpansFoldersError, + ); + const missing = yield* query + .getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 1 }) + .pipe(Effect.flip); + assert.instanceOf(missing, CheckpointFolderMissingError); + assert.equal( + missing.message, + "The folder these changes were made in no longer exists: /repo-before-move", + ); + }).pipe( + Effect.provide( + layerFor({ + projection: Effect.succeed(projection), + diffCheckpoints, + missingFolder: "/repo-before-move", + }), + ), + ); +}); + const layerVcsProcess = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer)); const layerStore = CheckpointStore.layer.pipe( Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcess))), diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index d5344ecaa2fbb..fbc1be1a68bd8 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -26,6 +26,8 @@ import type { ProjectionCheckpointContext } from "../orchestration-v2/Projection import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import { CheckpointDiffResultInvalidError, + CheckpointFolderMissingError, + CheckpointRangeSpansFoldersError, CheckpointRefUnavailableError, CheckpointThreadNotFoundError, CheckpointTurnRangeUnavailableError, @@ -394,6 +396,13 @@ export const make = Effect.gen(function* () { input.fromTurnCount === 0 ? projection.checkpointScopes.find((scope) => scope.kind === "root_run") : undefined; + const fromCheckpoint = + input.fromTurnCount === 0 + ? undefined + : (parentCheckpoint ?? + readyCheckpoints.find( + (checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount, + )); const fromCheckpointRef = input.fromTurnCount === 0 ? firstScope === undefined @@ -402,12 +411,21 @@ export const make = Effect.gen(function* () { scopeId: firstScope.id, ordinalWithinScope: 0, }).pipe(Effect.provideService(Digest.Digest, digest)) - : ( - parentCheckpoint ?? - readyCheckpoints.find( - (checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount, - ) - )?.ref; + : fromCheckpoint?.ref; + // A moved thread's earlier refs live in the repository it left. + const fromScope = + firstScope ?? + projection.checkpointScopes.find((scope) => scope.id === fromCheckpoint?.scopeId); + if (fromScope !== undefined && fromScope.cwd !== toScope.cwd) { + return yield* new CheckpointRangeSpansFoldersError({ operation, threadId: input.threadId }); + } + if (!(yield* fileSystem.exists(toScope.cwd).pipe(Effect.orElseSucceed(() => true)))) { + return yield* new CheckpointFolderMissingError({ + operation, + threadId: input.threadId, + cwd: toScope.cwd, + }); + } if (fromCheckpointRef === undefined) { return yield* new CheckpointRefUnavailableError({ operation, diff --git a/apps/server/src/checkpointing/Errors.ts b/apps/server/src/checkpointing/Errors.ts index b36fe817e9faa..829fb8376534f 100644 --- a/apps/server/src/checkpointing/Errors.ts +++ b/apps/server/src/checkpointing/Errors.ts @@ -79,6 +79,36 @@ export class CheckpointRefUnavailableError extends Schema.TaggedError()( + "CheckpointFolderMissingError", + { + operation: CheckpointDiffOperation, + threadId: ThreadId, + cwd: Schema.String, + }, +) { + override get message(): string { + return `The folder these changes were made in no longer exists: ${this.cwd}`; + } +} + +export class CheckpointRangeSpansFoldersError extends Schema.TaggedError()( + "CheckpointRangeSpansFoldersError", + { + operation: CheckpointDiffOperation, + threadId: ThreadId, + }, +) { + override get message(): string { + return "These turns ran in different folders after the thread moved, so their changes can't be shown together. Pick a single turn."; + } +} + +/** Diff failures caused by a thread's folder, whose messages are meant for the user. */ +export const isCheckpointFolderError = Schema.is( + Schema.Union([CheckpointFolderMissingError, CheckpointRangeSpansFoldersError]), +); + export type CheckpointServiceError = | CheckpointStoreError | ProjectionRepositoryError @@ -86,4 +116,6 @@ export type CheckpointServiceError = | CheckpointThreadNotFoundError | CheckpointWorkspacePathMissingError | CheckpointTurnRangeUnavailableError - | CheckpointRefUnavailableError; + | CheckpointRefUnavailableError + | CheckpointFolderMissingError + | CheckpointRangeSpansFoldersError; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index b29f9c874f123..480395938e04d 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -263,6 +263,8 @@ export const make = Effect.gen(function* () { threadActiveReorder: true, threadAutoSettleOptOut: true, threadProjectFromScratch: true, + threadMoveToProject: true, + threadMoveToMachine: true, threadTitleRegeneration: true, commandOutputStreaming: true, threadVisitedTracking: true, diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 7e846811e1440..eadb4ca344fc6 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -104,6 +104,26 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }), ); + it.effect("writes a rule's condition back with only the parentheses its meaning needs", () => + Effect.sync(() => { + for (const [when, expected] of [ + ["a && b && c", "a && b && c"], + ["a && (b && c)", "a && (b && c)"], + ["a || b && c", "a || b && c"], + ["(a || b) && !c", "(a || b) && !c"], + ["!(a && b) || !!c", "!(a && b) || !!c"], + ["((a))", "a"], + ] as const) { + const rule = { key: "mod+k", command: "terminal.toggle" as const, when }; + const resolved = SharedKeybindings.compileResolvedKeybindingRule(rule); + assert.ok(resolved); + const text = Keybindings.keybindingRuleText(resolved); + assert.equal(text.when, expected); + assert.deepEqual(SharedKeybindings.compileResolvedKeybindingRule(text), resolved); + } + }), + ); + it.effect("rejects invalid rules", () => Effect.sync(() => { assert.isNull( @@ -231,11 +251,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => { const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); const byCommand = new Map(persisted.map((entry) => [entry.command, entry])); - const persistedToggle = byCommand.get("terminal.toggle"); - assert.isNotNull(persistedToggle); - assert.equal(persistedToggle?.key, "mod+shift+y"); - assert.isFalse( - persisted.some((entry) => entry.command === "terminal.toggle" && entry.key === "mod+j"), + assert.deepStrictEqual( + persisted.filter((entry) => entry.command === "terminal.toggle"), + [{ key: "mod+shift+y", command: "terminal.toggle" }], ); for (const defaultRule of SharedKeybindings.DEFAULT_KEYBINDINGS) { @@ -258,21 +276,26 @@ it.layer(NodeServices.layer)("keybindings", (it) => { const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; const keybindings = yield* Keybindings.Keybindings; const when = "composerFocus && draftThreadRoute"; - const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const; - const backgroundRules = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) => - rules.filter((entry) => entry.command === "composer.sendBackground"), + const existing: KeybindingRule[] = [ + { key: "mod+alt+enter", command: "composer.sendBackground", when }, + { key: "mod+j", command: "terminal.toggle" }, + ]; + const lateCommands = new Set(existing.map((entry) => entry.command)); + const lateRules = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) => + rules.filter((entry) => lateCommands.has(entry.command)), ); - yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]); + yield* writeKeybindingsConfig(keybindingsConfigPath, existing); yield* keybindings.syncDefaultKeybindingsOnStartup; - assert.deepStrictEqual(yield* backgroundRules, [ + assert.deepStrictEqual(yield* lateRules, [ { key: "mod+enter", command: "composer.sendBackground", when }, - existing, + { key: "ctrl+`", command: "terminal.toggle" }, + ...existing, ]); - yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]); + yield* writeKeybindingsConfig(keybindingsConfigPath, existing); yield* keybindings.syncDefaultKeybindingsOnStartup; - assert.deepStrictEqual(yield* backgroundRules, [existing]); + assert.deepStrictEqual(yield* lateRules, existing); }).pipe(Effect.provide(layerKeybindings())), ); @@ -340,7 +363,10 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }); const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); - assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle")); + assert.deepStrictEqual( + persisted.filter((entry) => entry.command === "terminal.toggle"), + [{ key: "ctrl+`", command: "terminal.toggle" }], + ); assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run")); assert.isTrue( diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index d9a6a8dbf01d3..d66c6e61e80cb 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -1,4 +1,5 @@ import { + type KeybindingCommand, KeybindingRule, KeybindingsConfigError, KeybindingShortcut, @@ -82,7 +83,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( // Settings sends replace/remove targets in its own normalized spelling, which can differ from a // hand-edited file ("cmd+k" vs "meta+k", "a&&b" vs "a && b"), so compare parsed forms. -function keybindingRuleIdentity(rule: KeybindingRule): string { +function keybindingRuleIdentity(rule: KeybindingRuleText): string { const shortcut = parseKeybindingShortcut(rule.key); const key = (shortcut && encodeShortcut(shortcut)) ?? rule.key; if (rule.when === undefined) return JSON.stringify([rule.command, key, null]); @@ -90,10 +91,28 @@ function keybindingRuleIdentity(rule: KeybindingRule): string { return JSON.stringify([rule.command, key, whenAst ? encodeWhenAst(whenAst) : rule.when]); } -function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean { +interface KeybindingRuleText { + readonly key: string; + readonly command: string; + readonly when?: string | undefined; +} + +export function isSameKeybindingRule(left: KeybindingRuleText, right: KeybindingRuleText): boolean { return keybindingRuleIdentity(left) === keybindingRuleIdentity(right); } +/** Text form of a loaded rule. Unlike the config schema it has no length limit, so any loaded rule renders. */ +export function keybindingRuleText(rule: ResolvedKeybindingRule): { + readonly key: string; + readonly command: KeybindingCommand; + readonly when?: string; +} { + const key = encodeShortcut(rule.shortcut) ?? rule.shortcut.key; + return rule.whenAst === undefined + ? { key, command: rule.command } + : { key, command: rule.command, when: encodeWhenAst(rule.whenAst) }; +} + const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{ readonly id: string; readonly alongside: KeybindingRule; @@ -112,6 +131,11 @@ const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{ when: "composerFocus && draftThreadRoute", }, }, + { + id: "terminal.toggle:ctrl+`", + alongside: { key: "mod+j", command: "terminal.toggle" }, + rule: { key: "ctrl+`", command: "terminal.toggle" }, + }, ]; function keybindingShortcutContext(rule: KeybindingRule): string | null { @@ -155,19 +179,28 @@ function encodeShortcut(shortcut: KeybindingShortcut): string | null { return [...modifiers, key].join("+"); } +// Parenthesizes only where the parser needs it to rebuild the same tree, so a rule read back fits +// the length limit its stored form did: `&&` binds tighter than `||`, and both group left to right. function encodeWhenAst(node: KeybindingWhenNode): string { switch (node.type) { case "identifier": return node.name; case "not": - return `!(${encodeWhenAst(node.node)})`; + return `!${encodeWhenOperand(node.node, ["identifier", "not"])}`; case "and": - return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`; + return `${encodeWhenOperand(node.left, ["identifier", "not", "and"])} && ${encodeWhenOperand(node.right, ["identifier", "not"])}`; case "or": - return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`; + return `${encodeWhenAst(node.left)} || ${encodeWhenOperand(node.right, ["identifier", "not", "and"])}`; } } +function encodeWhenOperand( + node: KeybindingWhenNode, + bare: ReadonlyArray, +): string { + return bare.includes(node.type) ? encodeWhenAst(node) : `(${encodeWhenAst(node)})`; +} + const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown)); const RawKeybindingsEntriesPrettyJson = fromJsonStringPretty(Schema.Array(Schema.Unknown)); const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule); diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts index 928fda0dd72f8..10be29acc24d6 100644 --- a/apps/server/src/mcp/linkOrigin.test.ts +++ b/apps/server/src/mcp/linkOrigin.test.ts @@ -1,4 +1,5 @@ import * as DocumentText from "../provider/DocumentText.ts"; +import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -131,7 +132,12 @@ const layerTools = Layer.mergeAll( list: () => Effect.succeed([]), }), ), - Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide( + Layer.merge( + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), + ), + ), Layer.provide( Layer.mock(ProjectService.ProjectService)({ getById: (id) => diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 1272f367d439d..5bd15b68ee946 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1,4 +1,5 @@ import * as AssetSigner from "../../assets/AssetSigner.ts"; +import * as ThreadProjectMove from "../../project/ThreadProjectMove.ts"; import * as DocumentText from "../../provider/DocumentText.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -89,6 +90,7 @@ const decodeThreadSearchResult = Schema.decodeUnknownEffect( const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe( Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})), Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide(Layer.mock(ThreadProjectMove.ThreadProjectMove)({})), Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), @@ -897,6 +899,7 @@ it.effect("search names the calling thread, so an agent can tell its own match a Effect.provide( McpHttpServer.layerThreadToolkit.pipe( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(Layer.mock(ThreadProjectMove.ThreadProjectMove)({})), Layer.provide(NodeCrypto.layer), Layer.provide(McpToolAccessTestkit.liveThreadsLayer), Layer.provide( @@ -1138,6 +1141,7 @@ it.effect.each([ Effect.provide( McpHttpServer.layerThreadToolkit.pipe( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(Layer.mock(ThreadProjectMove.ThreadProjectMove)({})), Layer.provide(NodeCrypto.layer), Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})), Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})), @@ -1177,6 +1181,7 @@ it.effect("run_scheduled_task_now reports why a started run failed to dispatch", Effect.provide( McpHttpServer.layerThreadToolkit.pipe( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(Layer.mock(ThreadProjectMove.ThreadProjectMove)({})), Layer.provide(NodeCrypto.layer), Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})), Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})), diff --git a/apps/server/src/mcp/toolkits/environment/handlers.test.ts b/apps/server/src/mcp/toolkits/environment/handlers.test.ts index b4d39bd41c17f..eb472ddcf6c38 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.test.ts @@ -1,11 +1,14 @@ import { expect, it } from "@effect/vitest"; import { - DEFAULT_SERVER_SETTINGS, EnvironmentId, + ProjectId, ProviderInstanceId, ThreadId, + type AppControlResult, type OrchestrationV2ThreadShell, + type ServerSettings, } from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -13,7 +16,9 @@ import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; +import * as AppControl from "../../../appControl/AppControl.ts"; import * as Environment from "../../../environment/ServerEnvironment.ts"; +import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; import * as Settings from "../../../serverSettings.ts"; @@ -26,46 +31,98 @@ import { EnvironmentToolkit } from "./tools.ts"; const environmentId = EnvironmentId.make("environment:preferences"); const threadId = ThreadId.make("thread:preferences"); -it.effect("refuses a preferences update when the caller's turn ends while it waits", () => - Effect.gen(function* () { - const caller = yield* Ref.make(liveThreadShell(threadId)); - const updates = yield* Ref.make(0); - const checked = yield* Deferred.make(); - const layerDependencies = Layer.mergeAll( - ThreadCommandExecutor.layer, - Layer.succeed(McpInvocationContext.McpInvocationContext, { - environmentId, - requestNamespace: "provider:preferences", - thread: { - threadId, - providerSessionId: "provider:preferences", - providerInstanceId: ProviderInstanceId.make("codex"), - }, - client: undefined, - capabilities: new Set(["orchestration" as const]), - issuedAt: 0, - }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell: () => - Ref.get(caller).pipe(Effect.tap(() => Deferred.succeed(checked, undefined))), - }), - Layer.mock(Environment.ServerEnvironment)({ - getDescriptor: Effect.succeed({ +const projectId = ProjectId.make("project:preferences"); +// Valid at the 256-character limit; a fully parenthesized re-encoding would exceed it. +const longWhen = Array.from({ length: 15 }, () => "terminalFocus").join(" && "); +const longRule = { key: "mod+alt+k", command: "terminal.toggle" as const, when: longWhen }; + +const makeLayer = Effect.fn(function* ( + options: { + readonly onGetThreadShell?: Effect.Effect; + readonly settings?: Parameters[0]; + readonly appCommand?: Effect.Effect; + } = {}, +) { + const { + onGetThreadShell = Effect.void, + settings = {}, + appCommand = Effect.succeed("ran"), + } = options; + const caller = yield* Ref.make(liveThreadShell(threadId)); + const writes = yield* Ref.make(0); + const write = (value: A) => Ref.update(writes, (count) => count + 1).pipe(Effect.as(value)); + const snapshot = { + keybindings: compileResolvedKeybindingsConfig([...DEFAULT_KEYBINDINGS, longRule]), + issues: [], + }; + const layer = McpToolAccess.HandlersLayer.layer(EnvironmentHandlers.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + ThreadCommandExecutor.layer, + Layer.succeed(McpInvocationContext.McpInvocationContext, { environmentId, - label: "Test", - platform: { os: "linux", arch: "x64" }, - serverVersion: "0.0.0", - capabilities: { repositoryIdentity: false }, + requestNamespace: "provider:preferences", + thread: { + threadId, + providerSessionId: "provider:preferences", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => + id === threadId + ? Ref.get(caller).pipe(Effect.tap(() => onGetThreadShell)) + : Effect.succeed(null), + }), + Layer.mock(Environment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId, + label: "Test", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.0.0", + capabilities: { repositoryIdentity: false }, + }), }), - }), - Layer.mock(Settings.ServerSettingsService)({ - getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS), - updateSettings: () => - Ref.update(updates, (count) => count + 1).pipe(Effect.as(DEFAULT_SERVER_SETTINGS)), - }), - ); + Settings.ServerSettingsService.layerTest(settings), + Layer.mock(Keybindings.Keybindings)({ + getSnapshot: Effect.succeed(snapshot), + upsertKeybindingRule: () => write(snapshot), + removeKeybindingRule: () => write(snapshot), + }), + Layer.mock(AppControl.AppControl)({ + run: () => appCommand.pipe(Effect.tap(() => write(undefined))), + }), + ), + ), + ); + return { caller, writes, layer }; +}); + +const call = (...[name, params]: Parameters["handle"]>) => + EnvironmentToolkit.pipe( + Effect.flatMap((toolkit) => + toolkit.handle(name, params).pipe(Stream.unwrap, Stream.runCollect), + ), + Effect.map((results) => results.at(-1)?.result), + ); + +const unchangedSettings = (expected: ServerSettings) => + Settings.ServerSettingsService.pipe( + Effect.flatMap((settings) => settings.getSettings), + Effect.map((current) => expect(current).toEqual(expected)), + ); + +it.effect("refuses a settings update when the caller's turn ends while it waits", () => + Effect.gen(function* () { + const checked = yield* Deferred.make(); + const { caller, layer } = yield* makeLayer({ + onGetThreadShell: Deferred.succeed(checked, undefined), + }); yield* Effect.gen(function* () { - const toolkit = yield* EnvironmentToolkit; + const before = yield* (yield* Settings.ServerSettingsService).getSettings; const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor; const held = yield* Deferred.make(); const release = yield* Deferred.make(); @@ -76,22 +133,142 @@ it.effect("refuses a preferences update when the caller's turn ends while it wai ) .pipe(Effect.forkChild); yield* Deferred.await(held); - const update = yield* toolkit - .handle("t3_environment_preferences_update", { newWorktreesStartFromOrigin: true }) - .pipe(Stream.unwrap, Stream.runCollect, Effect.forkChild); + const update = yield* call("t3_environment_settings_update", { + patch: { newWorktreesStartFromOrigin: true }, + }).pipe(Effect.forkChild); yield* Deferred.await(checked); yield* Ref.update(caller, (shell) => ({ ...shell, activeRunId: null })); yield* Deferred.succeed(release, undefined); yield* Fiber.join(holder); - const result = yield* Fiber.join(update); - expect(result.at(-1)?.result).toMatchObject({ code: "parent_not_active" }); - expect(yield* Ref.get(updates)).toBe(0); - }).pipe( - Effect.provide( - McpToolAccess.HandlersLayer.layer(EnvironmentHandlers.layer).pipe( - Layer.provideMerge(layerDependencies), - ), - ), - ); + expect(yield* Fiber.join(update)).toMatchObject({ code: "parent_not_active" }); + yield* unchangedSettings(before); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("refuses settings and shortcuts agents may not or cannot write", () => + Effect.gen(function* () { + const { writes, layer } = yield* makeLayer(); + const cases = [ + [ + call("t3_environment_settings_update", { patch: { enableAgentDeviceAccess: true } }), + "capability_denied", + ], + [ + call("t3_environment_settings_update", { + patch: { projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } } }, + }), + "capability_denied", + ], + [call("t3_environment_settings_update", { patch: { notASetting: true } }), "invalid_request"], + [ + call("t3_environment_settings_update", { patch: { defaultTheme: "no-such-theme" } }), + "invalid_request", + ], + [ + call("t3_environment_settings_update", { patch: { linkedEnvironmentsEnabled: "yes" } }), + "invalid_request", + ], + [call("t3_environment_settings_update", { patch: {} }), "invalid_request"], + [call("t3_environment_settings_read", { keys: ["notASetting"] }), "invalid_request"], + [call("t3_keybinding_upsert", { key: "mod+k", command: "not.a.command" }), "invalid_request"], + [ + call("t3_keybinding_upsert", { key: "mod+k+j", command: "terminal.toggle" }), + "invalid_request", + ], + [ + call("t3_keybinding_remove", { key: "mod+k", command: "terminal.toggle" }), + "invalid_request", + ], + [call("t3_app_command", { command: "not.a.command" }), "invalid_request"], + [call("t3_app_command", { command: "composer.sendAlternate" }), "invalid_request"], + [call("t3_app_command", { command: "thread.undo" }), "invalid_request"], + ] as const; + yield* Effect.gen(function* () { + const before = yield* (yield* Settings.ServerSettingsService).getSettings; + for (const [result, code] of cases) expect(yield* result).toMatchObject({ code }); + expect(yield* Ref.get(writes)).toBe(0); + yield* unchangedSettings(before); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("lets agents give up browser and device access but not take back a denial", () => + Effect.gen(function* () { + const { layer } = yield* makeLayer({ + settings: { + enableAgentBrowserAccess: true, + projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } }, + }, + }); + yield* Effect.gen(function* () { + const settings = yield* Settings.ServerSettingsService; + const before = yield* settings.getSettings; + for (const entry of [null, {}]) + expect( + yield* call("t3_environment_settings_update", { + patch: { projectSettingsOverrides: { [projectId]: entry } }, + }), + ).toMatchObject({ code: "capability_denied" }); + yield* unchangedSettings(before); + yield* call("t3_environment_settings_update", { patch: { enableAgentBrowserAccess: false } }); + expect((yield* settings.getSettings).enableAgentBrowserAccess).toBe(false); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("lists every loaded shortcut in a form that writes back", () => + Effect.gen(function* () { + const { writes, layer } = yield* makeLayer(); + yield* Effect.gen(function* () { + const read = yield* call("t3_keybindings_read", {}); + const listed = (read as { keybindings: ReadonlyArray }).keybindings; + expect(listed.find((rule) => rule.key === longRule.key)).toEqual(longRule); + expect( + yield* call("t3_keybinding_upsert", { ...longRule, key: "mod+alt+j", replace: longRule }), + ).toHaveProperty("keybindings"); + expect( + yield* call("t3_keybinding_remove", { + key: "MOD+SHIFT+B", + command: "threadPanel.toggle", + when: "!terminalFocus", + }), + ).toHaveProperty("keybindings"); + expect(yield* Ref.get(writes)).toBe(2); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("says when the user's window cannot run an app command", () => + Effect.gen(function* () { + const cases = [ + [Effect.succeed("ran"), { ran: true }], + [Effect.succeed("not-handled"), { code: "invalid_request" }], + [Effect.succeed("other-environment"), { code: "invalid_request" }], + [Effect.fail(new AppControl.AppControlNoWindowError()), { code: "orchestration_error" }], + ] as const; + for (const [appCommand, expected] of cases) { + const { layer } = yield* makeLayer({ appCommand }); + expect( + yield* call("t3_app_command", { command: "terminal.toggle" }).pipe(Effect.provide(layer)), + ).toMatchObject(expected); + } + }), +); + +it.effect("shows a thread from this environment in the user's window, and no other", () => + Effect.gen(function* () { + const { layer, writes } = yield* makeLayer(); + yield* Effect.gen(function* () { + expect(yield* call("t3_app_navigate", { to: { page: "thread", threadId } })).toEqual({ + ran: true, + }); + expect( + yield* call("t3_app_navigate", { + to: { page: "thread", threadId: ThreadId.make("thread:elsewhere") }, + }), + ).toMatchObject({ code: "thread_not_found" }); + expect(yield* Ref.get(writes)).toBe(1); + }).pipe(Effect.provide(layer)); }), ); diff --git a/apps/server/src/mcp/toolkits/environment/handlers.ts b/apps/server/src/mcp/toolkits/environment/handlers.ts index fb1716885d6e8..0cbdad86dec48 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.ts @@ -1,11 +1,28 @@ -import { OrchestratorMcpFailure, type ServerSettings } from "@t3tools/contracts"; +import { + type AppAction, + AppCommand, + KeybindingRule, + OrchestratorMcpFailure, + ProjectId, + ClientServerSettingsPatch, + ServerSettings, + ServerSettingsPatch, + STATIC_KEYBINDING_COMMANDS, + type ResolvedKeybindingsConfig, +} from "@t3tools/contracts"; +import { compileResolvedKeybindingRule } from "@t3tools/shared/keybindings"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as AppControl from "../../../appControl/AppControl.ts"; import * as Environment from "../../../environment/ServerEnvironment.ts"; +import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; import * as Settings from "../../../serverSettings.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; -import { readCaller, unavailable } from "../../threadAccess.ts"; +import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; +import { readCaller, threadNotFound, unavailable } from "../../threadAccess.ts"; import { EnvironmentToolkit } from "./tools.ts"; export function preferences(settings: ServerSettings) { @@ -29,6 +46,68 @@ export function preferences(settings: ServerSettings) { }, }; } + +const SETTINGS_KEYS = new Set(Object.keys(ServerSettings.fields)); +const PATCH_KEYS = new Set(Object.keys(ClientServerSettingsPatch.fields)); +const THEME_KEYS = new Set( + Object.keys(ServerSettingsPatch.fields).filter((key) => !PATCH_KEYS.has(key)), +); + +const invalid = (message: string) => + new OrchestratorMcpFailure({ code: "invalid_request", message }); +const decodePatch = Schema.decodeUnknownEffect(ClientServerSettingsPatch); +const encodeSettings = Schema.encodeEffect(ServerSettings); +const decodeKeybinding = Schema.decodeUnknownEffect(KeybindingRule); +const decodeAppCommand = Schema.decodeUnknownEffect(AppCommand); + +const settingsView = (settings: ServerSettings, keys: ReadonlyArray | undefined) => + encodeSettings(Settings.redactServerSettingsForClient(settings, { secretReferences: true })).pipe( + Effect.mapError(unavailable), + Effect.map((encoded) => + keys === undefined + ? encoded + : Object.fromEntries(Object.entries(encoded).filter(([key]) => keys.includes(key))), + ), + ); + +/** Whether `next` lets agents use the browser or a device anywhere `current` did not. */ +function grantsAgentAccess(current: ServerSettings, next: ServerSettings): boolean { + const access = (settings: ServerSettings, projectId: ProjectId | null) => { + const resolved = resolveProjectSettings(settings, projectId).settings; + return [resolved.enableAgentBrowserAccess, resolved.enableAgentDeviceAccess]; + }; + const projectIds = new Set([ + ...Object.keys(current.projectSettingsOverrides), + ...Object.keys(next.projectSettingsOverrides), + ]); + return [null, ...[...projectIds].map((id) => ProjectId.make(id))].some((projectId) => { + const before = access(current, projectId); + return access(next, projectId).some((granted, index) => granted && !before[index]); + }); +} + +const keybindingsView = (keybindings: ResolvedKeybindingsConfig) => + keybindings.map(Keybindings.keybindingRuleText); + +/** Rejects a rule the service would store as a broken entry, as the Settings page path does. */ +const validRule = (input: unknown) => + decodeKeybinding(input).pipe( + Effect.mapError((error) => invalid(`Invalid shortcut: ${error.message}`)), + Effect.filterOrFail( + (rule) => compileResolvedKeybindingRule(rule) !== null, + () => invalid("Invalid shortcut: the key or `when` does not parse."), + ), + ); + +/** The listed rule a replace or remove target names, however the agent spelled it. */ +const listedRule = ( + keybindings: ResolvedKeybindingsConfig, + target: { readonly key: string; readonly command: string; readonly when?: string | undefined }, +) => + Effect.fromNullishOr( + keybindingsView(keybindings).find((rule) => Keybindings.isSameKeybindingRule(rule, target)), + ).pipe(Effect.mapError(() => invalid("No such shortcut. `t3_keybindings_read` lists them."))); + const access = Effect.gen(function* () { const context = yield* readCaller(); const environment = yield* Environment.ServerEnvironment; @@ -38,8 +117,51 @@ const access = Effect.gen(function* () { code: "capability_denied", message: "This credential belongs to another environment.", }); - return { ...context, descriptor, settings: yield* Settings.ServerSettingsService }; + return { + ...context, + descriptor, + settings: yield* Settings.ServerSettingsService, + keybindings: yield* Keybindings.Keybindings, + appControl: yield* AppControl.AppControl, + }; +}); + +/** Runs an action in the user's window, failing with `refusals` when the window declines it. */ +const runInWindow = Effect.fn("EnvironmentTools.runInWindow")(function* ( + appControl: AppControl.AppControl["Service"], + action: AppAction, + refusals: Record<"other-environment" | "not-handled", string>, +) { + const failed = (message: string) => + Effect.fail(new OrchestratorMcpFailure({ code: "orchestration_error", message })); + const result = yield* appControl.run(action).pipe( + Effect.catchTags({ + AppControlNoWindowError: () => + failed("No T3 Code window is open on this environment. Mobile apps don't take commands."), + AppControlTimeoutError: () => + failed( + "The user's window didn't answer. It may still act when it wakes, so check before retrying.", + ), + }), + ); + if (result !== "ran") return yield* invalid(refusals[result]); + return { ran: true }; }); + +/** Runs a write under the caller thread's lock, rechecking access once the lock is held. */ +const writeLocked = Effect.fn("EnvironmentTools.writeLocked")(function* ( + check: Effect.Effect, + write: Effect.Effect, +) { + const scope = yield* McpInvocationContext.McpInvocationContext; + const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor; + // The turn may have ended, or the thread's modes changed, while this waited for the lock. + const update = check.pipe(Effect.andThen(write)); + return yield* scope.thread === undefined + ? update + : executor.withLock(scope.thread.threadId, update); +}); + export const layer = McpToolAccess.toLayer(EnvironmentToolkit, { t3_environment_read: McpToolAccess.reads(() => Effect.gen(function* () { @@ -54,21 +176,150 @@ export const layer = McpToolAccess.toLayer(EnvironmentToolkit, { }; }), ), - t3_environment_preferences_update: McpToolAccess.writesEnvironment((patch, check) => + t3_environment_settings_read: McpToolAccess.reads(({ keys }) => Effect.gen(function* () { - const scope = yield* McpInvocationContext.McpInvocationContext; - const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor; - const update = Effect.gen(function* () { - // The turn may have ended, or the thread's modes changed, while this waited for the lock. - yield* check; - const { settings } = yield* access; - return preferences( - yield* settings.updateSettings(patch).pipe(Effect.mapError(unavailable)), + const unknown = (keys ?? []).filter((key) => !SETTINGS_KEYS.has(key)); + if (unknown.length > 0) return yield* invalid(`Unknown settings: ${unknown.join(", ")}.`); + const { settings } = yield* access; + const current = yield* settings.getSettings.pipe(Effect.mapError(unavailable)); + return { settings: yield* settingsView(current, keys) }; + }), + ), + t3_environment_settings_update: McpToolAccess.writesEnvironment(({ patch }, check) => + Effect.gen(function* () { + const keys = Object.keys(patch); + if (keys.length === 0) return yield* invalid("`patch` is empty."); + const unknown = keys.filter((key) => !PATCH_KEYS.has(key)); + if (unknown.length > 0) + return yield* invalid( + `Unknown or read-only settings: ${unknown.join(", ")}.` + + (unknown.some((key) => THEME_KEYS.has(key)) ? " Use `t3_theme_set` for themes." : ""), ); - }); - return yield* scope.thread === undefined - ? update - : executor.withLock(scope.thread.threadId, update); + // Device hosts need the local-host filtering only the RPC path applies. + if (keys.includes("deviceHosts")) + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: "Only the user can change deviceHosts, in Settings.", + }); + const decoded = yield* decodePatch(patch).pipe( + Effect.mapError((error) => invalid(`Invalid settings: ${error.message}`)), + ); + return yield* writeLocked( + check, + Effect.gen(function* () { + const { settings } = yield* access; + const next = yield* settings + .updateSettings(decoded, (current, patched) => + grantsAgentAccess(current, patched) + ? Effect.fail( + new OrchestratorMcpFailure({ + code: "capability_denied", + message: + "Only the user can grant agents browser or device access, in Settings.", + }), + ) + : Effect.void, + ) + .pipe(Effect.catchTags({ ServerSettingsError: () => Effect.fail(unavailable()) })); + return { settings: yield* settingsView(next, keys) }; + }), + ); + }), + ), + t3_keybindings_read: McpToolAccess.reads(() => + Effect.gen(function* () { + const { keybindings } = yield* access; + const snapshot = yield* keybindings.getSnapshot.pipe(Effect.mapError(unavailable)); + return { + keybindings: keybindingsView(snapshot.keybindings), + commands: [...STATIC_KEYBINDING_COMMANDS], + issues: snapshot.issues.map((issue) => issue.message), + }; + }), + ), + t3_keybinding_upsert: McpToolAccess.writesEnvironment(({ replace, ...input }, check) => + Effect.gen(function* () { + const rule = yield* validRule(input); + return yield* writeLocked( + check, + Effect.gen(function* () { + const { keybindings } = yield* access; + const current = yield* keybindings.getSnapshot.pipe(Effect.mapError(unavailable)); + const target = + replace === undefined ? undefined : yield* listedRule(current.keybindings, replace); + const next = yield* keybindings + .upsertKeybindingRule(target ? { ...rule, replace: target } : rule) + .pipe(Effect.mapError(unavailable)); + const commands = new Set([rule.command, target?.command]); + return { + keybindings: keybindingsView( + next.keybindings.filter((binding) => commands.has(binding.command)), + ), + }; + }), + ); + }), + ), + t3_keybinding_remove: McpToolAccess.writesEnvironment((input, check) => + writeLocked( + check, + Effect.gen(function* () { + const { keybindings } = yield* access; + const current = yield* keybindings.getSnapshot.pipe(Effect.mapError(unavailable)); + const target = yield* listedRule(current.keybindings, input); + const next = yield* keybindings + .removeKeybindingRule(target) + .pipe(Effect.mapError(unavailable)); + return { + keybindings: keybindingsView( + next.keybindings.filter((binding) => binding.command === target.command), + ), + }; + }), + ), + ), + t3_app_command: McpToolAccess.writesEnvironment(({ command }) => + Effect.gen(function* () { + const appCommand = yield* decodeAppCommand(command).pipe( + Effect.mapError(() => + invalid( + "Unknown command, or one only the user may run. `t3_keybindings_read` lists them.", + ), + ), + ); + const { appControl } = yield* access; + return yield* runInWindow( + appControl, + { _tag: "command", command: appCommand }, + { + "other-environment": `\`${command}\` runs only while the user's window shows a thread or draft from this environment.`, + "not-handled": `Nothing in the user's window handles \`${command}\` right now, such as a thread command outside a thread.`, + }, + ); + }), + ), + t3_app_navigate: McpToolAccess.writesEnvironment(({ to }) => + Effect.gen(function* () { + const { appControl, scope } = yield* access; + if (to.page === "thread") { + const threads = yield* ThreadManagement.ThreadManagementService; + const shell = yield* threads.getThreadShell(to.threadId).pipe(Effect.mapError(unavailable)); + if (shell === null || shell.deletedAt !== null) + return yield* threadNotFound( + threads, + scope, + to.threadId, + `Thread ${to.threadId} was not found.`, + ); + } + return yield* runInWindow( + appControl, + { _tag: "navigate", to }, + { + "other-environment": "The user's window can't show that page.", + "not-handled": "The user's window can't show that page.", + }, + ); }), ), }); diff --git a/apps/server/src/mcp/toolkits/environment/tools.ts b/apps/server/src/mcp/toolkits/environment/tools.ts index 9e10380295de2..a75cf8172b653 100644 --- a/apps/server/src/mcp/toolkits/environment/tools.ts +++ b/apps/server/src/mcp/toolkits/environment/tools.ts @@ -1,15 +1,16 @@ import { - BackgroundActivityProfile, + AppDestination, BackgroundActivityProfileSelection, ExecutionEnvironmentDescriptor, OrchestratorMcpEnvironmentTarget, OrchestratorMcpFailure, ServerSettings, - ServerSettingsPatch, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import { Tool, Toolkit } from "effect/ai"; +import * as AppControl from "../../../appControl/AppControl.ts"; import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts"; +import * as Keybindings from "../../../keybindings.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; import * as Settings from "../../../serverSettings.ts"; @@ -35,9 +36,26 @@ const shared = { ThreadManagementService.ThreadManagementService, ServerEnvironment.ServerEnvironment, Settings.ServerSettingsService, + Keybindings.Keybindings, + AppControl.AppControl, ThreadCommandExecutor.ThreadCommandExecutor, ], }; +// Settings and keybindings travel as plain JSON; their full schemas would bloat every tool list. +const SettingsObject = Schema.Record(Schema.String, Schema.Unknown); +const KeybindingFields = { + key: Schema.String.annotate({ + description: 'e.g. "mod+shift+k"; mod is cmd on macOS, ctrl elsewhere.', + }), + command: Schema.String.annotate({ description: "From `t3_keybindings_read`." }), + when: Schema.optionalKey(Schema.String.annotate({ description: 'e.g. "!terminalFocus".' })), +}; +const KeybindingRuleView = Schema.Struct({ + key: Schema.String, + command: Schema.String, + when: Schema.optionalKey(Schema.String), +}); + const EnvironmentReadTool = Tool.make("t3_environment_read", { ...shared, description: @@ -53,18 +71,88 @@ const EnvironmentReadTool = Tool.make("t3_environment_read", { }) .annotate(Tool.Readonly, true) .annotate(Tool.Destructive, false); -const EnvironmentPreferencesTool = Tool.make("t3_environment_preferences_update", { +const SettingsReadTool = Tool.make("t3_environment_settings_read", { + ...shared, + description: + "Read this server's settings, as on the Settings page. Secrets come back redacted. Pass `keys` to read only some.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + keys: Schema.optionalKey(Schema.Array(Schema.String)), + }), + success: Schema.Struct({ settings: SettingsObject }), +}) + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false); +const SettingsUpdateTool = Tool.make("t3_environment_settings_update", { ...shared, description: - "Update environment-wide preferences. Live full-access or default caller thread only. Omitted fields are unchanged; `customInstructions: ''` clears it.", + "Change this server's settings. `patch` uses the keys and shapes of `t3_environment_settings_read`; omitted keys are unchanged. Live full-access or default caller thread only. Agent browser and device access stay the user's to grant.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, - defaultThreadEnvMode: ServerSettingsPatch.fields.defaultThreadEnvMode, - newWorktreesStartFromOrigin: ServerSettingsPatch.fields.newWorktreesStartFromOrigin, - enableProviderUpdateChecks: ServerSettingsPatch.fields.enableProviderUpdateChecks, - backgroundActivity: Schema.optionalKey(Schema.Struct({ profile: BackgroundActivityProfile })), - sourceControlWritingStyle: ServerSettingsPatch.fields.sourceControlWritingStyle, + patch: SettingsObject, }), - success: Schema.Struct(PreferenceFields), + success: Schema.Struct({ settings: SettingsObject }), }).annotate(Tool.Destructive, true); -export const EnvironmentToolkit = Toolkit.make(EnvironmentReadTool, EnvironmentPreferencesTool); +const KeybindingsReadTool = Tool.make("t3_keybindings_read", { + ...shared, + description: "List this server's keyboard shortcuts and every command a shortcut can run.", + parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget }), + success: Schema.Struct({ + keybindings: Schema.Array(KeybindingRuleView), + commands: Schema.Array(Schema.String), + issues: Schema.Array(Schema.String), + }), +}) + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false); +const KeybindingUpsertTool = Tool.make("t3_keybinding_upsert", { + ...shared, + description: + "Add a keyboard shortcut, or change one by passing the current binding as `replace`. Live full-access or default caller thread only.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + ...KeybindingFields, + replace: Schema.optionalKey(Schema.Struct(KeybindingFields)), + }), + success: Schema.Struct({ keybindings: Schema.Array(KeybindingRuleView) }), +}).annotate(Tool.Destructive, true); +const KeybindingRemoveTool = Tool.make("t3_keybinding_remove", { + ...shared, + description: + "Remove a keyboard shortcut, matched exactly as `t3_keybindings_read` lists it. Live full-access or default caller thread only.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + ...KeybindingFields, + }), + success: Schema.Struct({ keybindings: Schema.Array(KeybindingRuleView) }), +}).annotate(Tool.Destructive, true); +const AppCommandTool = Tool.make("t3_app_command", { + ...shared, + description: + "Run a command from `t3_keybindings_read` in the user's T3 Code window, the one they used last, as if they pressed its shortcut. Sending or dictating in their composer stays theirs. Live full-access or default caller thread only.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + command: Schema.String.annotate({ description: 'e.g. "terminal.toggle".' }), + }), + success: Schema.Struct({ ran: Schema.Boolean }), +}).annotate(Tool.Destructive, true); +const AppNavigateTool = Tool.make("t3_app_navigate", { + ...shared, + description: + "Show a page in the user's T3 Code window, the one they used last: a thread from this environment, a settings section, usage, or pull requests. Live full-access or default caller thread only.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + to: AppDestination, + }), + success: Schema.Struct({ ran: Schema.Boolean }), +}); +export const EnvironmentToolkit = Toolkit.make( + EnvironmentReadTool, + SettingsReadTool, + SettingsUpdateTool, + KeybindingsReadTool, + KeybindingUpsertTool, + KeybindingRemoveTool, + AppCommandTool, + AppNavigateTool, +); diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 220ed39eb3c81..1cce353eb412d 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -23,6 +23,7 @@ import { import type * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts"; import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; +import * as ThreadProjectMove from "../../../project/ThreadProjectMove.ts"; import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts"; import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts"; import { ThreadToolkit } from "./tools.ts"; @@ -404,6 +405,18 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { Effect.gen(function* () { const { threads, projection, caller } = yield* readThread(input.threadId); const common = { commandId: yield* newCommandId(), threadId: projection.thread.id }; + if (input.action === "move") { + const projectId = yield* required(input.projectId, "projectId"); + const { notice } = yield* (yield* ThreadProjectMove.ThreadProjectMove) + .move({ threadId: projection.thread.id, projectId }) + .pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }), + ), + ); + return { movedToProjectId: projectId, notice }; + } if (input.action === "settle") { return yield* threads .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id }) diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 9803e8b4fa690..322f58c0da61d 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -26,13 +26,14 @@ import * as Schema from "effect/Schema"; import { McpSchema, Tool, Toolkit } from "effect/ai"; import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; +import * as ThreadProjectMove from "../../../project/ThreadProjectMove.ts"; import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts"; import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; const ThreadOrganizeTool = Tool.make("t3_thread_organize", { description: - "Pin, snooze, settle, archive, or mark a thread unread. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active.", + "Pin, snooze, settle, archive, mark unread, or move a thread to another project. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active. `move` needs `projectId` and an idle thread (not this one mid-turn); its history continues in that project's root. Earlier turns' files can't be restored, and a worktree's changes stay behind; `notice` says what changed.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId), @@ -46,18 +47,22 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", { "archive", "unarchive", "mark_unread", + "move", ]), snoozedUntil: Schema.optional(IsoDateTime), + projectId: Schema.optional(ProjectId), }), success: Schema.Union([ OrchestrationV2DispatchCommandResult, Schema.Struct({ settlesWhenTurnEnds: Schema.Literal(true) }), + Schema.Struct({ movedToProjectId: ProjectId, notice: Schema.String }), ]), failure: OrchestratorMcpFailure, failureMode: "return" as const, dependencies: [ McpInvocationContext.McpInvocationContext, ThreadManagementService.ThreadManagementService, + ThreadProjectMove.ThreadProjectMove, SecureRandom.SecureRandom, ], }) diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f02f32d67e764..e7ad79741a9f6 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -188,6 +188,10 @@ const RPC_AGGREGATES = { [WS_METHODS.projectsEnsureScratch]: "orchestration", [WS_METHODS.projectsCreateNew]: "orchestration", [WS_METHODS.projectsCreateFromThread]: "orchestration", + [WS_METHODS.projectsMoveThread]: "orchestration", + [WS_METHODS.projectsExportThread]: "orchestration", + [WS_METHODS.projectsImportThread]: "orchestration", + [WS_METHODS.projectsFinishThreadMove]: "orchestration", [WS_METHODS.shellOpenInEditor]: "workspace", [WS_METHODS.filesystemBrowse]: "workspace", [WS_METHODS.workspaceListFolders]: "workspace", @@ -243,6 +247,8 @@ const RPC_AGGREGATES = { [WS_METHODS.previewReportProfiles]: "preview", [WS_METHODS.previewReportStatus]: "preview", [WS_METHODS.subscribePreviewEvents]: "preview", + [WS_METHODS.subscribeAppControl]: "app-control", + [WS_METHODS.appControlRespond]: "app-control", [WS_METHODS.subscribeDiscoveredLocalServers]: "preview", [WS_METHODS.previewStopLocalServer]: "preview", [WS_METHODS.deviceConfigure]: "device", diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 5b8c5fabd54b7..7760b1efef72e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2613,6 +2613,8 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [ "mcp__t3-code__t3_thread_search", "mcp__t3-code__t3_preview_list", "mcp__t3-code__t3_environment_read", + "mcp__t3-code__t3_environment_settings_read", + "mcp__t3-code__t3_keybindings_read", "mcp__t3-code__t3_environment_links", "mcp__t3-code__t3_theme_read", "mcp__t3-code__html_preview", diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts index 529dea74dec91..224d8a137d0e8 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.taskFolder.test.ts @@ -253,6 +253,7 @@ const taskFolderThread = Effect.fn(function* (state: State, options: Options) { const rootScope = yield* checkpoints.prepareRootRunScope({ threadId, + scopeProjectId: undefined, runId: RunId.make("run:rewind:1"), rootNodeId: NodeId.make("node:rewind:1"), providerThreadId, diff --git a/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts b/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts index c73e1be396187..260fc8293a5e3 100644 --- a/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointScopeOwnership.test.ts @@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import { CheckpointId, @@ -220,6 +221,7 @@ it.effect("resolves the thread baseline after a second root run replaces scope o Layer.mock(ThreadManagement.ThreadManagementService)({ getCheckpointContext: () => Effect.succeed(context), }), + FileSystem.layerNoop({ exists: () => Effect.succeed(true) }), Layer.mock(CheckpointStore.CheckpointStore)({ listAuthoredPaths: () => Effect.succeed(null), diffCheckpoints: (input) => { diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index ec3e872d61c2b..f07802e991ae5 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -167,6 +167,7 @@ export const nestedScopePaths = Effect.fn("CheckpointService.nestedScopePaths")( export interface CheckpointServiceV2Shape { readonly prepareRootRunScope: (input: { readonly threadId: ThreadId; + readonly scopeProjectId: ProjectId | undefined; readonly runId: RunId; readonly rootNodeId: NodeId; readonly providerThreadId: ProviderThreadId; @@ -310,6 +311,7 @@ function checkpointIdForScopeOrdinal( const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: { readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; readonly threadId: ThreadId; + readonly scopeProjectId: ProjectId | undefined; readonly runId: RunId; readonly rootNodeId: NodeId; readonly providerThreadId: ProviderThreadId; @@ -318,7 +320,11 @@ const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(functio }) { const scopeId = yield* input.idAllocator.allocate.checkpointScope({ threadId: input.threadId, - name: ROOT_CHECKPOINT_SCOPE_NAME, + // A moved thread's refs live in another repository, so each project gets its own scope. + name: + input.scopeProjectId === undefined + ? ROOT_CHECKPOINT_SCOPE_NAME + : `${ROOT_CHECKPOINT_SCOPE_NAME}:${input.scopeProjectId}`, }); return { id: scopeId, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5936f57ad5014..3a7042534d81a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -673,6 +673,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.pull-request.sync": case "thread.title.regeneration.complete": case "thread.project.adopt-folder": + case "thread.project.move": case "thread.runtime-mode.set": case "thread.interaction-mode.set": case "thread.model-selection.set": @@ -3005,6 +3006,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.flatMap((resolvedRuntimePolicy) => checkpointService.prepareRootRunScope({ threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId: queuedRun.id, rootNodeId: rootNode.id, providerThreadId: queuedProviderThread.id, @@ -4396,6 +4398,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio | "thread.pull-request-watch.checks-reopen" | "thread.pull-request.sync" | "thread.title.regeneration.complete" + | "thread.project.move" | "thread.runtime-mode.set" | "thread.interaction-mode.set" | "thread.model-selection.set" @@ -4699,6 +4702,43 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } } + let projectMoveChangesCwd = false; + if (command.type === "thread.project.move") { + const reject = (cause: string) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} ${cause}`, + }); + if (thread.projectId === command.projectId) return yield* reject("is already there."); + const records = yield* projectionStore + .getThreadRecords(command.threadId, ["runs", "runtimeRequests"], { turnItemTypes: [] }) + .pipe(mapDispatchError(command)); + if (threadHasUnfinishedWork(records)) { + return yield* reject("still has work in progress. Finish or stop it first."); + } + // Its effect would restore files and the provider thread for the old folder. + const rollbackEffects = + thread.rollbackRequestId === undefined + ? [] + : yield* effectOutbox + .listByCommandId(thread.rollbackRequestId) + .pipe(mapDispatchError(command)); + if ( + rollbackEffects.some((effect) => effect.status === "pending" || effect.status === "running") + ) { + return yield* reject("is still rolling back. Wait for it to finish, then move it."); + } + const current = yield* projects.get(thread.projectId).pipe(mapDispatchError(command)); + const target = yield* projects.get(command.projectId).pipe(mapDispatchError(command)); + if (Option.isNone(target) || target.value.deletedAt !== null) { + return yield* reject(`cannot move to missing project ${command.projectId}.`); + } + projectMoveChangesCwd = + (thread.worktreePath ?? Option.getOrUndefined(current)?.workspaceRoot) !== + target.value.workspaceRoot; + } + const needsProviderState = command.type === "thread.runtime-mode.set" || command.type === "thread.model-selection.set" || @@ -4707,7 +4747,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.type === "thread.settle" || (command.type === "thread.metadata.update" && command.worktreePath !== undefined && - command.worktreePath !== thread.worktreePath); + command.worktreePath !== thread.worktreePath) || + projectMoveChangesCwd; const providerContext = needsProviderState ? yield* projectionStore .getThreadProviderContext( @@ -4757,9 +4798,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const detachSessionIds = new Set( command.type === "thread.archive" || command.type === "thread.settle" ? (providerContext?.providerSessions ?? []).map((session) => session.id) - : command.type === "thread.metadata.update" && - command.worktreePath !== undefined && - command.worktreePath !== thread.worktreePath + : (command.type === "thread.metadata.update" && + command.worktreePath !== undefined && + command.worktreePath !== thread.worktreePath) || + projectMoveChangesCwd ? (providerContext?.providerSessions ?? []).map((session) => session.id) : command.type === "thread.runtime-mode.set" ? (providerContext?.providerSessions ?? []) @@ -5160,6 +5202,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio updatedAt: now, }; } + case "thread.project.move": + return { + ...thread, + projectId: command.projectId, + worktreePath: null, + branch: projectMoveChangesCwd ? command.branch : thread.branch, + ...(projectMoveChangesCwd ? { checkpointScopeProjectId: command.projectId } : {}), + updatedAt: now, + }; case "thread.pull-request.link": case "thread.pull-request.unlink": case "thread.pull-request-link.sync": { @@ -5545,6 +5596,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return "thread.marked-unread" as const; case "thread.metadata.update": case "thread.title.regeneration.complete": + case "thread.project.move": return "thread.metadata-updated" as const; case "thread.pull-request.link": case "thread.pull-request.unlink": @@ -5767,7 +5819,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? "Thread archived." : command.type === "thread.settle" ? "Thread settled." - : command.type === "thread.metadata.update" + : command.type === "thread.metadata.update" || + command.type === "thread.project.move" ? "Workspace changed." : command.type === "thread.runtime-mode.set" ? "Runtime mode changed." @@ -6842,6 +6895,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const checkpointScope = yield* checkpointService .prepareRootRunScope({ threadId: input.command.threadId, + scopeProjectId: input.projection.thread.checkpointScopeProjectId, runId: targetRun.id, rootNodeId: nextRootNodeId, providerThreadId: restartProviderThread.id, @@ -8043,6 +8097,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.flatMap((resolvedRuntimePolicy) => checkpointService.prepareRootRunScope({ threadId: command.threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId, rootNodeId, providerThreadId: queuedProviderThread.id, @@ -8533,6 +8588,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.flatMap((resolvedRuntimePolicy) => checkpointService.prepareRootRunScope({ threadId: command.threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId, rootNodeId, providerThreadId, @@ -9334,6 +9390,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const checkpointScope = yield* checkpointService .prepareRootRunScope({ threadId: command.threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId, rootNodeId, providerThreadId: providerThread.id, @@ -12524,6 +12581,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const checkpointScope = yield* checkpointService .prepareRootRunScope({ threadId: command.threadId, + scopeProjectId: projection.thread.checkpointScopeProjectId, runId: state.run.id, rootNodeId: state.rootNode.id, providerThreadId: state.providerThread.id, @@ -15834,6 +15892,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.pull-request.watch": case "thread.pull-request.sync": case "thread.title.regeneration.complete": + case "thread.project.move": case "thread.runtime-mode.set": case "thread.interaction-mode.set": case "thread.model-selection.set": diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index d5bff642383d3..cc9ed1d914f07 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -27,10 +27,13 @@ import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as EventSink from "./EventSink.ts"; import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectStore from "./ProjectStore.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; @@ -652,6 +655,217 @@ it.live.each(["pooled", "exclusive"] as const)( }), ); +it.live("moving a thread to another project resumes its conversation in the new root", () => + Effect.gen(function* () { + const name = "project-move"; + const sourceRoot = yield* checkpointWorkspace(`${name}-source`); + const targetRoot = yield* checkpointWorkspace(`${name}-target`); + const threadId = ThreadId.make(`thread:${name}`); + const sourceId = ProjectId.make(`project:${name}:source`); + const targetId = ProjectId.make(`project:${name}:target`); + const state = yield* Ref.make({ + activeTurn: null, + opened: [], + started: [], + closedSessionCount: 0, + failedReplacementOpen: true, + }); + const database = SqlitePersistence.layerMemory; + const backgroundWork = yield* Ref.make(false); + const adapter = makeRestartAdapter(state, exclusiveCapabilities); + const rollbackCommandId = CommandId.make(`${name}:rollback`); + + const result = yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const eventSink = yield* EventSink.EventSinkV2; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const projects = yield* ProjectStore.ProjectStoreV2; + for (const [index, [projectId, workspaceRoot]] of ( + [ + [sourceId, sourceRoot], + [targetId, targetRoot], + ] as const + ).entries()) { + yield* projects.apply({ + sequence: index + 1, + eventId: EventId.make(`event:${projectId}`), + aggregateKind: "project", + aggregateId: projectId, + occurredAt: "2026-01-01T00:00:00.000Z", + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "project.created", + payload: { + projectId, + title: projectId, + workspaceRoot, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + }); + } + const send = (step: string) => + Effect.gen(function* () { + const terminal = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "run.updated" && event.payload.status === "completed", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${name}:${step}`), + threadId, + messageId: MessageId.make(`${name}:${step}`), + text: step, + attachments: [], + modelSelection: seedSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* Fiber.join(terminal); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(threadId); + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${name}:create`), + threadId, + projectId: sourceId, + title: name, + modelSelection: seedSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "source-branch", + worktreePath: null, + }); + const first = yield* send("first"); + const move = (projectId: ProjectId, branch: string | null, attempt = "") => + orchestrator.dispatch({ + type: "thread.project.move", + commandId: CommandId.make(`${name}:move:${projectId}${attempt}`), + threadId, + projectId, + branch, + }); + // Detaching would end the session's background agents, as with a worktree handoff. + yield* Ref.set(backgroundWork, true); + const refusedBusy = yield* move(targetId, "target-branch", ":busy").pipe(Effect.flip); + yield* Ref.set(backgroundWork, false); + const moved = yield* move(targetId, "target-branch"); + yield* worker.drain(); + const second = yield* send("second"); + yield* move(sourceId, "source-branch"); + yield* worker.drain(); + const third = yield* send("third"); + const detached = yield* eventSink + .readByCommandId({ commandId: CommandId.make(`${name}:move:${targetId}`) }) + .pipe(Stream.runCollect); + // A rollback whose effect has not run yet would restore the old folder after the move. + const occurredAt = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`event:${name}:rollback`), + type: "thread.metadata-updated", + threadId, + providerInstanceId: third.thread.providerInstanceId, + occurredAt, + payload: { ...third.thread, rollbackRequestId: rollbackCommandId }, + }, + ], + }); + yield* outbox.enqueue([ + { + id: `effect:${rollbackCommandId}`, + commandId: rollbackCommandId, + threadId, + request: { + type: "provider-thread.rollback", + providerThreadId: third.providerThreads[0]!.id, + checkpointId: third.checkpoints[0]!.id, + scopeId: third.checkpoints[0]!.scopeId, + }, + }, + ]); + const refusedRollback = yield* move(targetId, null, ":rollback").pipe(Effect.flip); + return { + first, + moved, + second, + third, + detached: [...detached], + refusedBusy, + refusedRollback, + }; + }).pipe( + Effect.provide( + Layer.merge( + ProviderReplayHarness.layerWithRegistry( + { name }, + ProviderAdapterRegistry.layerSingle({ + ...adapter, + openSession: (input) => + adapter.openSession(input).pipe( + Effect.map((session) => ({ + ...session, + hasPendingBackgroundWork: Ref.get(backgroundWork), + })), + ), + }), + { databaseLayer: database }, + ), + ProjectStore.layer.pipe(Layer.provide(database)), + ), + ), + ); + + assert.include(String(result.refusedBusy.cause), "still running background agents or commands"); + assert.include(String(result.refusedRollback.cause), "still rolling back"); + const firstSession = result.first.providerSessions.find( + (session) => session.status !== "stopped" && session.status !== "error", + ); + assert.isDefined(firstSession); + assert.deepEqual( + result.detached.flatMap(({ event }) => + event.type === "provider-session.detached" ? [event.payload.providerSessionId] : [], + ), + [firstSession.id], + ); + assert.equal(result.second.thread.projectId, targetId); + assert.isNull(result.second.thread.worktreePath); + assert.equal(result.second.thread.branch, "target-branch"); + assert.equal(result.third.thread.projectId, sourceId); + // Each move ends the live session, so every turn opens one in its new root. + assert.lengthOf((yield* Ref.get(state)).opened, 3); + // Each move starts a checkpoint scope of its own, so earlier refs stay in their repository. + assert.lengthOf( + new Set( + result.third.checkpointScopes + .filter((scope) => scope.kind === "root_run") + .map((scope) => scope.id), + ), + 3, + ); + // The provider conversation carries over; only its session moved. + assert.deepEqual( + [...new Set(result.third.providerThreads.map((thread) => thread.nativeThreadRef?.nativeId))], + [`native-thread:${threadId}`], + ); + }), +); + it.live("Stop during a restart interrupts the turn the restart could not stop", () => Effect.gen(function* () { const cwd = yield* checkpointWorkspace("selection-restart-stop"); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 843e51da40423..ad75005d4a3cd 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -94,6 +94,10 @@ import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts"; +import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; @@ -12544,6 +12548,291 @@ it.layer(layerScratchPromotionTest)("turning a No project thread into a project" ); }); +const layerThreadProjectMoveTest = ThreadProjectMove.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + isScratchProject: (projectId) => Effect.succeed(projectId === SCRATCH_PROJECT_ID), + namedProjectsRoot: "/projects", + }), + Layer.mock(GitWorkflow.GitWorkflowService)({ + currentBranch: (cwd) => Effect.succeed(`branch-of:${cwd}`), + }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([modelSelection.instanceId]), + }), + ServerSettings.layerTest( + { defaultModelSelection: modelSelection }, + { organization: "Org", lockedSettings: [], limits: { maxRuntimeMode: "auto" } }, + ), + Layer.mock(ServerEnvironment.ServerEnvironmentIdentity)({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("machine-move-test")), + }), + IdAllocator.layer, + NodeCrypto.layer, + ), + ), + Layer.provideMerge(layerProjectDeletionTest), +); + +it.layer(layerThreadProjectMoveTest)("moving a thread to another project", (it) => { + it.effect( + "moves an idle thread and its bound tasks, and refuses No project or busy threads", + () => + Effect.gen(function* () { + const move = (yield* ThreadProjectMove.ThreadProjectMove).move; + const projects = yield* ProjectService.ProjectService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const tasks = yield* ScheduledTaskService.ScheduledTaskService; + const sourceId = ProjectId.make("thread-move-source"); + const targetId = ProjectId.make("thread-move-target"); + const otherId = ProjectId.make("thread-move-other"); + for (const [projectId, workspaceRoot] of [ + [sourceId, "/tmp/thread-move-source"], + [targetId, "/tmp/thread-move-target"], + [otherId, "/tmp/thread-move-other"], + [SCRATCH_PROJECT_ID, SCRATCH_ROOT], + ] as const) { + if (Option.isNone(yield* projects.getById(projectId))) { + yield* projects.create({ + commandId: CommandId.make(`${projectId}-create`), + projectId, + title: projectId, + workspaceRoot, + }); + } + } + const createThread = (name: string) => + orchestrator + .dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`thread-move-${name}-create`), + threadId: ThreadId.make(`thread-move-${name}`), + projectId: sourceId, + title: name, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "source-branch", + worktreePath: "/tmp/thread-move-source-worktree", + }) + .pipe(Effect.as(ThreadId.make(`thread-move-${name}`))); + const threadId = yield* createThread("idle"); + const busyId = yield* createThread("busy"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("thread-move-busy-message"), + threadId: busyId, + messageId: MessageId.make("thread-move-busy-message"), + text: "Keep this run active.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const { task } = yield* tasks.upsert({ + id: ScheduledTaskId.make("thread-move-bound"), + title: "Bound", + prompt: "Check in", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: sourceId, + threadId, + workspaceStrategy: { type: "root" }, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "user", + creationSource: "web", + }); + const shellOf = (id: ThreadId) => orchestrator.getThreadShell(id); + + const scratch = yield* move({ threadId, projectId: SCRATCH_PROJECT_ID }).pipe(Effect.flip); + assert.equal(scratch.message, "A thread cannot move into No project."); + const busy = yield* move({ threadId: busyId, projectId: targetId }).pipe(Effect.flip); + assert.equal( + busy.message, + `Thread ${busyId} still has work in progress. Finish or stop it first.`, + ); + assert.equal((yield* shellOf(busyId))?.projectId, sourceId); + + const fromWorktree = yield* move({ threadId, projectId: targetId }); + assert.include(fromWorktree.notice, "The worktree and its branch stay on disk"); + const moved = yield* shellOf(threadId); + assert.equal(moved?.projectId, targetId); + // It lands in the project root; the old worktree stays where it was. + assert.isNull(moved?.worktreePath); + assert.equal(moved?.branch, "branch-of:/tmp/thread-move-target"); + const saved = (yield* tasks.list()).tasks.find((candidate) => candidate.id === task.id); + assert.equal(saved?.projectId, targetId); + + yield* move({ threadId, projectId: targetId }); + const fromRoot = yield* move({ threadId, projectId: sourceId }); + assert.notInclude(fromRoot.notice, "worktree"); + assert.include(fromRoot.notice, "files from earlier turns can't be restored"); + assert.equal((yield* shellOf(threadId))?.projectId, sourceId); + + // Another move commits between this move's commit and its task update. + const threads = yield* ThreadManagementService.ThreadManagementService; + const racing = Layer.fresh(ThreadProjectMove.layer).pipe( + Layer.provide( + Layer.succeed(ThreadManagementService.ThreadManagementService, { + ...threads, + dispatch: (command) => + threads.dispatch(command).pipe( + Effect.tap(() => + command.type === "thread.project.move" && command.projectId === targetId + ? threads.dispatch({ + ...command, + commandId: CommandId.make("thread-move-racing"), + projectId: otherId, + }) + : Effect.void, + ), + ), + }), + ), + ); + yield* ThreadProjectMove.ThreadProjectMove.pipe( + Effect.flatMap((service) => service.move({ threadId, projectId: targetId })), + Effect.provide(racing), + ); + assert.equal((yield* shellOf(threadId))?.projectId, otherId); + const raced = (yield* tasks.list()).tasks.find((candidate) => candidate.id === task.id); + assert.equal(raced?.projectId, otherId); + }), + ); + + it.effect("moves a conversation to another machine's project and archives the source after", () => + Effect.gen(function* () { + const service = yield* ThreadProjectMove.ThreadProjectMove; + const projects = yield* ProjectService.ProjectService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const targetId = ProjectId.make("machine-move-target"); + yield* projects.create({ + commandId: CommandId.make("machine-move-target-create"), + projectId: targetId, + title: "Target", + workspaceRoot: "/tmp/machine-move-target", + }); + const bundle = { + title: "Port the parser", + modelSelection: { instanceId: ProviderInstanceId.make("elsewhere-only"), model: "m" }, + runtimeMode: "full-access", + interactionMode: "plan", + createdAt: "2026-01-01T00:00:00.000Z", + messages: [ + { role: "user", text: "Port the parser.", createdAt: "2026-01-01T00:00:01.000Z" }, + { role: "assistant", text: "Ported.", createdAt: "2026-01-01T00:00:02.000Z" }, + ], + } as const; + + const { threadId } = yield* service.importThread({ + projectId: targetId, + bundle, + movedFrom: "Laptop", + leftBehind: { diffs: true, worktree: true, attachments: 0, scheduledTasks: 0 }, + }); + const imported = (yield* orchestrator.getThreadRecords(threadId, [])).thread; + assert.equal(imported.projectId, targetId); + assert.equal(imported.branch, "branch-of:/tmp/machine-move-target"); + assert.isNull(imported.activeProviderThreadId); + // This machine has no such provider instance, and the policy caps the runtime mode. + assert.equal(imported.modelSelection.instanceId, "codex"); + assert.equal(imported.runtimeMode, "auto"); + assert.equal(imported.interactionMode, "plan"); + + // Moving it back carries the same conversation, and names what stays behind. + const exported = yield* service.exportThread(threadId); + assert.deepEqual(exported.bundle.messages, bundle.messages); + assert.equal(exported.bundle.title, bundle.title); + assert.deepEqual(exported.leftBehind, { + diffs: false, + worktree: false, + attachments: 0, + scheduledTasks: 0, + }); + const { projection } = yield* threads.getThreadSnapshot(threadId); + assert.include( + projection.visibleTurnItems.map(({ item }) => + item.type === "system_notice" ? item.message : "", + ), + "Moved from Laptop. Files, diffs and the worktree stayed there.", + ); + + yield* service.finishMove({ threadId, movedTo: "VPS", revision: exported.revision }); + const finished = yield* threads.getThreadSnapshot(threadId); + assert.isNotNull(finished.projection.thread.archivedAt); + assert.include( + finished.projection.visibleTurnItems.map(({ item }) => + item.type === "system_notice" ? item.message : "", + ), + "Moved to VPS. Messages sent here stay separate from that thread.", + ); + + // A turn starts on the source after the export, from another device or a schedule. + const raced = yield* service.importThread({ + projectId: targetId, + bundle, + movedFrom: "Laptop", + leftBehind: { diffs: false, worktree: false, attachments: 0, scheduledTasks: 0 }, + }); + const before = yield* service.exportThread(raced.threadId); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("machine-move-raced-message"), + threadId: raced.threadId, + messageId: MessageId.make("machine-move-raced-message"), + text: "Keep this run active.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const refused = yield* service + .finishMove({ threadId: raced.threadId, movedTo: "VPS", revision: before.revision }) + .pipe(Effect.flip); + assert.equal( + refused.message, + "It changed after the move started, so it was left active here. Its newest messages aren't in the moved copy.", + ); + assert.isNull((yield* orchestrator.getThreadRecords(raced.threadId, [])).thread.archivedAt); + const busy = yield* service.exportThread(raced.threadId).pipe(Effect.flip); + assert.equal(busy.message, "The thread still has work in progress. Finish or stop it first."); + + // Native subagents get messages outside runs, which the revision can't track. + const subagentId = ThreadId.make("machine-move-native-subagent"); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("machine-move-native-subagent-created"), + type: "thread.created", + threadId: subagentId, + occurredAt: yield* DateTime.now, + payload: { + ...imported, + id: subagentId, + creationSource: "provider", + lineage: { + parentThreadId: threadId, + rootThreadId: threadId, + relationshipToParent: "subagent", + }, + }, + }, + ], + }); + const subagent = yield* service.exportThread(subagentId).pipe(Effect.flip); + assert.equal(subagent.message, "Subagent threads stay with the thread that started them."); + }), + ); +}); + it.layer(layerSharedApplicationDataPlaneTest)("snooze projection", (it) => { it.effect("carries snooze, settle and title state through the V2 shell projection", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 18ee960fc9e4d..b59141e69857c 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -20,6 +20,7 @@ import * as ProjectService from "../project/ProjectService.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts"; +import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; import * as CheckpointCaptureService from "./CheckpointCaptureService.ts"; import * as CheckpointService from "./CheckpointService.ts"; import * as CheckpointRollbackService from "./CheckpointRollbackService.ts"; @@ -333,6 +334,18 @@ const layerScratchThreadPromotionProvided = ScratchThreadPromotion.layer.pipe( ).pipe(Layer.provideMerge(layerProjectService)), ), ); +const layerThreadProjectMoveProvided = ThreadProjectMove.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerManagedProjectFoldersProvided, + layerThreadManagementProvided, + layerScheduledTaskProvided, + layerEventSink, + IdAllocator.layer, + ProviderAdapterRegistry.layerFromProviderInstanceRegistry, + ).pipe(Layer.provideMerge(layerProjectService)), + ), +); const layerProviderContinuationWorkerProvided = ProviderContinuationService.layer.pipe( Layer.provide( Layer.mergeAll( @@ -419,6 +432,7 @@ export const layerProduction = Layer.mergeAll( layerThreadLaunchProvided, layerScheduledTaskProvided, layerScratchThreadPromotionProvided, + layerThreadProjectMoveProvided, layerSecretRequestsProvided, GuestShareService.layer.pipe( Layer.provide(Layer.merge(layerOrchestratorProvided, layerCommandOutputHubProvided)), diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index 1d3f563f35b08..9501b5ba30752 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -1,4 +1,5 @@ import * as DocumentText from "../provider/DocumentText.ts"; +import * as ThreadProjectMove from "../project/ThreadProjectMove.ts"; import { NodeHttpServer } from "@effect/platform-node"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -263,7 +264,12 @@ const serveBox = (seen: Ref.Ref, linkSession: Ref.Ref) => Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), ), Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})), - Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide( + Layer.merge( + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), + ), + ), Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})), Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})), Layer.provide(ServerSettings.layerTest()), @@ -344,6 +350,7 @@ const makeLaptop = Effect.gen(function* () { Layer.mock(ProviderRegistry.ProviderRegistry)({}), Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ProjectService.ProjectService)({}), Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}), Layer.mock(SecretRequests.SecretRequests)({}), diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 0f8736986a2df..e033eb586544c 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -109,7 +109,9 @@ type HistoryMessage = Omit - messageEvents({ threadId, index, message }), + messageEvents({ prefix: IMPORT_EVENT_PREFIX, threadId, index, message }), ), { id: EventId.make(`${IMPORT_EVENT_PREFIX}:provider-thread:${providerThreadId}`), @@ -529,7 +529,12 @@ const make = Effect.gen(function* () { yield* eventSink.write({ events: [ ...messages.flatMap((message, index) => - messageEvents({ threadId: input.threadId, index, message }), + messageEvents({ + prefix: IMPORT_EVENT_PREFIX, + threadId: input.threadId, + index, + message, + }), ), { id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${input.threadId}:native-history`), diff --git a/apps/server/src/project/ThreadProjectMove.test.ts b/apps/server/src/project/ThreadProjectMove.test.ts new file mode 100644 index 0000000000000..6975046951f87 --- /dev/null +++ b/apps/server/src/project/ThreadProjectMove.test.ts @@ -0,0 +1,72 @@ +import { type ModelSelection, ProviderInstanceId, type ThreadMoveBundle } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import * as DateTime from "effect/DateTime"; + +import { movedModelSelection, threadMoveBundleFits, threadRevision } from "./ThreadProjectMove.ts"; + +const source = { instanceId: ProviderInstanceId.make("source-only"), model: "s" }; +const fallback = { instanceId: ProviderInstanceId.make("codex"), model: "d" }; + +describe("movedModelSelection", () => { + it.each<{ + readonly case: string; + readonly usable: ReadonlyArray; + readonly projectDefault: ModelSelection | null; + readonly expected: ModelSelection | null; + }>([ + { + case: "the source instance exists here", + usable: ["source-only"], + projectDefault: fallback, + expected: source, + }, + { + case: "only the default is usable", + usable: ["codex"], + projectDefault: fallback, + expected: fallback, + }, + { case: "no default is set", usable: ["codex"], projectDefault: null, expected: null }, + { + case: "the default's instance is missing or disabled", + usable: [], + projectDefault: fallback, + expected: null, + }, + ])("$case", ({ usable, projectDefault, expected }) => { + expect( + movedModelSelection({ + source, + projectDefault, + usable: (instanceId) => usable.includes(instanceId), + }), + ).toEqual(expected); + }); +}); + +describe("threadMoveBundleFits", () => { + const bundle: ThreadMoveBundle = { + title: "Port the parser", + modelSelection: source, + runtimeMode: "full-access", + interactionMode: "default", + createdAt: "2026-01-01T00:00:00.000Z", + messages: [{ role: "user", text: "Port it.", createdAt: "2026-01-01T00:00:00.000Z" }], + }; + const bytes = Buffer.byteLength(JSON.stringify(bundle), "utf8"); + + it("accepts a bundle at the limit and refuses one byte over", () => { + expect(threadMoveBundleFits(bundle, bytes)).toBe(true); + expect(threadMoveBundleFits(bundle, bytes - 1)).toBe(false); + }); +}); + +describe("threadRevision", () => { + it("changes when a retried run completes under the same id", () => { + const run = { id: "run-1", ordinal: 1, completedAt: null }; + expect( + threadRevision([{ ...run, completedAt: DateTime.makeUnsafe("2026-01-01T00:00:00Z") }]), + ).not.toBe(threadRevision([run])); + }); +}); diff --git a/apps/server/src/project/ThreadProjectMove.ts b/apps/server/src/project/ThreadProjectMove.ts new file mode 100644 index 0000000000000..30553ecb7384f --- /dev/null +++ b/apps/server/src/project/ThreadProjectMove.ts @@ -0,0 +1,459 @@ +import { + CommandId, + EventId, + isProviderNativeSubagentThread, + isRuntimeModeAbove, + type ModelSelection, + PROVIDER_SEND_TURN_MAX_FILE_BYTES, + type ProviderInstanceId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type ProjectExportThreadResult, + type ProjectFinishThreadMoveInput, + type ProjectId, + type ProjectImportThreadInput, + type ProjectImportThreadResult, + type ThreadId, + type ThreadMoveBundle, + TurnItemId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { threadMoveLeftBehindList, threadMoveNotice } from "@t3tools/shared/threadMove"; +import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +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 ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as EventSink from "../orchestration-v2/EventSink.ts"; +import { threadHasUnfinishedWork } from "../orchestration-v2/Orchestrator.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; +import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { messageEvents } from "./AgentSessionImporter.ts"; +import * as ManagedProjectFolders from "./ManagedProjectFolders.ts"; +import * as ProjectService from "./ProjectService.ts"; + +const MOVE_EVENT_PREFIX = "thread-machine-move"; +const TOO_LARGE = "This conversation is too large to move."; +const CHANGED = + "It changed after the move started, so it was left active here. Its newest messages aren't in the moved copy."; + +/** The source's own provider when this machine runs it, else the project default when usable. */ +export function movedModelSelection(input: { + readonly source: ModelSelection; + readonly projectDefault: ModelSelection | null; + readonly usable: (instanceId: ProviderInstanceId) => boolean; +}): ModelSelection | null { + if (input.usable(input.source.instanceId)) return input.source; + return input.projectDefault !== null && input.usable(input.projectDefault.instanceId) + ? input.projectDefault + : null; +} + +/** Imports hold bundles to the transcript export's budget, which exports already pass. */ +export function threadMoveBundleFits(bundle: ThreadMoveBundle, maxBytes: number): boolean { + return Buffer.byteLength(JSON.stringify(bundle), "utf8") <= maxBytes; +} + +/** Changes when a run starts or any run, retries included, completes, so finish never archives work export missed. */ +export function threadRevision( + runs: ReadonlyArray<{ + readonly id: string; + readonly ordinal: number; + readonly completedAt: DateTime.Utc | null; + }>, +) { + let newest: (typeof runs)[number] | undefined; + let lastCompletedAt = 0; + for (const run of runs) { + if (newest === undefined || run.ordinal > newest.ordinal) newest = run; + if (run.completedAt !== null) + lastCompletedAt = Math.max(lastCompletedAt, DateTime.toEpochMillis(run.completedAt)); + } + return `${runs.length}:${newest?.id ?? ""}:${lastCompletedAt}`; +} + +export class ThreadProjectMoveError extends Schema.TaggedError()( + "ThreadProjectMoveError", + { + reason: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.reason; + } +} + +export class ThreadProjectMove extends Context.Service< + ThreadProjectMove, + { + /** + * Moves an idle thread, with its scheduled tasks, into another project's root folder. + * Running it again finishes a partial move. + */ + readonly move: (input: { + readonly threadId: ThreadId; + readonly projectId: ProjectId; + }) => Effect.Effect<{ readonly notice: string }, ThreadProjectMoveError>; + /** An idle thread's conversation, for moving it to another environment. Changes nothing. */ + readonly exportThread: ( + threadId: ThreadId, + ) => Effect.Effect; + /** A new thread in `projectId` holding the bundle's history; its first message starts a fresh session. */ + readonly importThread: ( + input: ProjectImportThreadInput, + ) => Effect.Effect; + /** Notes where the conversation went and archives the thread, once the import succeeded. */ + readonly finishMove: ( + input: ProjectFinishThreadMoveInput, + ) => Effect.Effect; + } +>()("t3/project/ThreadProjectMove") {} + +const make = Effect.gen(function* () { + const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; + const projects = yield* ProjectService.ProjectService; + const threads = yield* ThreadManagementService.ThreadManagementService; + const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService; + const git = yield* GitWorkflowService.GitWorkflowService; + const eventSink = yield* EventSink.EventSinkV2; + const ids = yield* IdAllocator.IdAllocatorV2; + const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; + const settingsService = yield* ServerSettings.ServerSettingsService; + const environmentIdentity = yield* ServerEnvironment.ServerEnvironmentIdentity; + const randomId = (yield* SecureRandom.SecureRandom).uuidV4(); + + const fail = (reason: string) => (cause: unknown) => + new ThreadProjectMoveError({ reason, cause }); + + const readTarget = Effect.fn("ThreadProjectMove.readTarget")(function* (projectId: ProjectId) { + const target = yield* projects + .getById(projectId) + .pipe(Effect.mapError(fail("Could not read the project."))); + if (Option.isNone(target) || target.value.deletedAt !== null) { + return yield* new ThreadProjectMoveError({ reason: "Project not found." }); + } + // No project holds one folder per thread, so its root is no place to work. + if (yield* managedFolders.isScratchProject(projectId)) { + return yield* new ThreadProjectMoveError({ + reason: "A thread cannot move into No project.", + }); + } + return target.value; + }); + + const move: ThreadProjectMove["Service"]["move"] = Effect.fn("ThreadProjectMove.move")( + function* (input) { + const target = yield* readTarget(input.projectId); + const thread = yield* threads.getThreadShell(input.threadId).pipe( + Effect.mapError(fail("Could not read the thread.")), + Effect.filterOrFail( + (shell) => shell !== null, + () => new ThreadProjectMoveError({ reason: "Thread not found." }), + ), + ); + if (thread.projectId !== input.projectId) { + const branch = yield* git + .currentBranch(target.workspaceRoot) + .pipe(Effect.orElseSucceed(() => null)); + yield* threads + .dispatch({ + type: "thread.project.move", + commandId: CommandId.make(`thread-project-move:${yield* randomId}`), + threadId: input.threadId, + projectId: input.projectId, + branch, + }) + .pipe( + Effect.mapError( + (cause) => + new ThreadProjectMoveError({ + reason: userFacingDispatchErrorMessage(cause) ?? "Could not move the thread.", + cause, + }), + ), + ); + } + // Another move can commit before these writes, so follow the thread until a read matches. + const currentProject = threads.getThreadShell(input.threadId).pipe( + Effect.map((shell) => shell?.projectId ?? input.projectId), + Effect.mapError(fail("Could not read the thread.")), + ); + let projectId = yield* currentProject; + while (true) { + yield* scheduledTasks + .moveThreadTasks({ threadIds: [input.threadId], projectId }) + .pipe(Effect.mapError(fail("Moved the thread, but not its scheduled tasks. Try again."))); + const now = yield* currentProject; + if (now === projectId) break; + projectId = now; + } + return { + notice: threadMoveNotice({ + projectTitle: target.title, + fromWorktree: thread.worktreePath !== null, + }), + }; + }, + ); + + const exportThread: ThreadProjectMove["Service"]["exportThread"] = Effect.fn( + "ThreadProjectMove.exportThread", + )(function* (threadId) { + const records = yield* threads + .getThreadRecords(threadId, ["runs", "runtimeRequests"]) + .pipe(Effect.mapError(fail("Could not read the thread."))); + // Their messages arrive outside runs, so the move revision can't see them change. + if (isProviderNativeSubagentThread(records.thread)) { + return yield* new ThreadProjectMoveError({ + reason: "Subagent threads stay with the thread that started them.", + }); + } + if (threadHasUnfinishedWork(records)) { + return yield* new ThreadProjectMoveError({ + reason: "The thread still has work in progress. Finish or stop it first.", + }); + } + // The transcript export's size preflight, budget and concurrency limit bound the bundle. + const transcript = yield* threads.getThreadTranscript(threadId).pipe( + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environmentIdentity), + Effect.mapError((cause) => + cause._tag === "ThreadTranscriptTooLargeError" + ? new ThreadProjectMoveError({ reason: TOO_LARGE, cause }) + : new ThreadProjectMoveError({ reason: "Could not read the thread.", cause }), + ), + ); + const thread = records.thread; + let attachments = 0; + const messages = transcript.items.flatMap(({ item }) => { + if (item.type === "user_message") attachments += item.attachments.length; + if (item.type !== "user_message" && item.type !== "assistant_message") return []; + if (item.text.trim() === "") return []; + const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt); + return [ + { role: item.type === "user_message" ? "user" : "assistant", text: item.text, createdAt }, + ] as const; + }); + if (messages.length === 0) { + return yield* new ThreadProjectMoveError({ + reason: "The thread has no conversation to move.", + }); + } + const tasks = yield* scheduledTasks + .list() + .pipe(Effect.mapError(fail("Could not read the thread's scheduled tasks."))); + return { + bundle: { + title: thread.title.trim() === "" ? "Untitled thread" : thread.title, + modelSelection: thread.modelSelection, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + createdAt: DateTime.formatIso(thread.createdAt), + messages, + }, + leftBehind: { + diffs: records.runs.length > 0, + worktree: thread.worktreePath !== null, + attachments, + scheduledTasks: tasks.tasks.filter((task) => task.threadId === threadId).length, + }, + revision: threadRevision(records.runs), + }; + }); + + const importThread: ThreadProjectMove["Service"]["importThread"] = Effect.fn( + "ThreadProjectMove.importThread", + )(function* (input) { + if (!threadMoveBundleFits(input.bundle, PROVIDER_SEND_TURN_MAX_FILE_BYTES)) { + return yield* new ThreadProjectMoveError({ reason: TOO_LARGE }); + } + const project = yield* readTarget(input.projectId); + const settings = yield* settingsService.getSettings.pipe( + Effect.mapError(fail("Could not read this machine's settings.")), + ); + const projectSettings = resolveProjectSettings(settings, project.id, project).settings; + // Provider instances are per machine, so the thread may need this project's default. + const usableIds = yield* Effect.filter(yield* registry.list(), (instanceId) => + threads.isProviderInstanceEnabledForProject({ projectId: project.id, instanceId }), + ); + const modelSelection = movedModelSelection({ + source: input.bundle.modelSelection, + projectDefault: projectSettings.defaultModelSelection, + usable: (instanceId) => usableIds.includes(instanceId), + }); + if (modelSelection === null) { + return yield* new ThreadProjectMoveError({ + reason: `This machine can't run the thread's provider (${input.bundle.modelSelection.instanceId}), and ${project.title} has no usable default model. Set up that provider here, or choose a default model for ${project.title}.`, + }); + } + const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode; + const runtimeMode = + ceiling !== undefined && isRuntimeModeAbove(input.bundle.runtimeMode, ceiling) + ? ceiling + : input.bundle.runtimeMode; + const branch = yield* git + .currentBranch(project.workspaceRoot) + .pipe(Effect.orElseSucceed(() => null)); + const threadId = yield* ids.allocate + .thread({ projectId: project.id }) + .pipe(Effect.mapError(fail("Could not create the thread."))); + const now = yield* DateTime.now; + const createdAt = Option.getOrElse(DateTime.make(input.bundle.createdAt), () => now); + const thread: OrchestrationV2AppThread = { + createdBy: "user", + creationSource: "server", + id: threadId, + projectId: project.id, + title: input.bundle.title, + providerInstanceId: modelSelection.instanceId, + modelSelection, + runtimeMode, + interactionMode: input.bundle.interactionMode, + branch, + worktreePath: null, + linkedPullRequest: null, + branchPullRequest: null, + activeProviderThreadId: null, + // Run-less history, which the first turn hands to a fresh provider session. + historyOrigin: "v1_import", + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + unsettledAt: null, + snoozedUntil: null, + snoozedAt: null, + pinnedAt: null, + pinOrderKey: null, + activeOrderKey: null, + lastVisitedAt: null, + deletedAt: null, + }; + const noticeId = TurnItemId.make(`${MOVE_EVENT_PREFIX}:moved-from:${threadId}`); + const events: ReadonlyArray = [ + { + id: EventId.make(`${MOVE_EVENT_PREFIX}:thread:${threadId}:created`), + type: "thread.created", + threadId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: thread, + }, + ...input.bundle.messages.flatMap((message, index) => + messageEvents({ prefix: MOVE_EVENT_PREFIX, threadId, index, message }), + ), + { + id: EventId.make(noticeId), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + ...movedNoticeFields(noticeId, threadId, now), + runId: null, + nodeId: null, + providerThreadId: null, + ordinal: input.bundle.messages.length + 1, + message: `Moved from ${input.movedFrom}. ${threadMoveLeftBehindList(input.leftBehind)} stayed there.`, + }, + }, + ]; + yield* eventSink.write({ events }).pipe(Effect.mapError(fail("Could not create the thread."))); + return { threadId }; + }); + + const finishMove: ThreadProjectMove["Service"]["finishMove"] = Effect.fn( + "ThreadProjectMove.finishMove", + )(function* (input) { + const records = yield* threads + .getThreadRecords(input.threadId, ["runs", "runtimeRequests"]) + .pipe(Effect.mapError(fail("Could not read the thread."))); + const { thread, runs } = records; + // A run can start between this check and the archive below; that window is a few + // milliseconds, while the one this closes spans the whole confirmation and import. + if (threadRevision(runs) !== input.revision || threadHasUnfinishedWork(records)) { + return yield* new ThreadProjectMoveError({ reason: CHANGED }); + } + const lastRun = runs.reduce<(typeof runs)[number] | undefined>( + (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), + undefined, + ); + const now = yield* DateTime.now; + const noticeId = + lastRun === undefined + ? TurnItemId.make(`${MOVE_EVENT_PREFIX}:moved-to:${input.threadId}`) + : ids.derive.runSignalTurnItem({ runId: lastRun.id, signal: "moved-to-machine" }); + yield* eventSink + .write({ + events: [ + { + id: yield* ids.allocate + .event({ threadId: input.threadId }) + .pipe(Effect.mapError(fail("Could not note the move."))), + type: "turn-item.updated", + threadId: input.threadId, + ...(lastRun === undefined ? {} : { runId: lastRun.id }), + occurredAt: now, + payload: { + ...movedNoticeFields(noticeId, input.threadId, now), + runId: lastRun?.id ?? null, + nodeId: lastRun?.rootNodeId ?? null, + providerThreadId: lastRun?.providerThreadId ?? null, + // EventSink allocates the real position, after the run's existing items. + ordinal: 0, + message: `Moved to ${input.movedTo}. Messages sent here stay separate from that thread.`, + }, + }, + ], + }) + .pipe(Effect.mapError(fail("Could not note the move."))); + if (thread.archivedAt !== null) return; + yield* threads + .dispatch({ + type: "thread.archive", + commandId: CommandId.make(`thread-machine-move:${yield* randomId}`), + threadId: input.threadId, + }) + .pipe( + Effect.mapError( + (cause) => + new ThreadProjectMoveError({ + reason: userFacingDispatchErrorMessage(cause) ?? "Could not archive the thread.", + cause, + }), + ), + ); + }); + + return ThreadProjectMove.of({ move, exportThread, importThread, finishMove }); +}); + +function movedNoticeFields(id: TurnItemId, threadId: ThreadId, now: DateTime.Utc) { + return { + id, + threadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "system_notice", + level: "info", + } as const; +} + +export const layer = Layer.effect(ThreadProjectMove, make); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 3b3f1459cb9dd..aa9f9f54a1d5b 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -15,6 +15,8 @@ import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; import { GitManager } from "../git/GitManager.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; import { TaskFolders } from "../workspace/TaskFolders.ts"; +import { AppControl } from "../appControl/AppControl.ts"; +import { Keybindings } from "../keybindings.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import { PreviewAutomationBroker } from "../mcp/PreviewAutomationBroker.ts"; import { @@ -41,6 +43,7 @@ import { IssueService } from "../issue/IssueService.ts"; import { PullRequestReviewGuideService } from "../pullRequest/PullRequestReviewGuideService.ts"; import { PullRequestService } from "../pullRequest/PullRequestService.ts"; import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts"; +import { ThreadProjectMove } from "../project/ThreadProjectMove.ts"; import { SecretRequests } from "../secrets/SecretRequests.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { SourceControlRepositoryService } from "../sourceControl/SourceControlRepositoryService.ts"; @@ -62,6 +65,8 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(GitWorkflowService)({}), Layer.mock(TaskFolders)({}), Layer.mock(IssueService)({}), + Layer.mock(Keybindings)({}), + Layer.mock(AppControl)({}), Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "" }), Layer.mock(McpProviderSessions)({}), Layer.mock(OrchestratorV2)({}), @@ -81,6 +86,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(GitManager)({}), Layer.mock(RemoteDelegation)({}), Layer.mock(ScheduledTaskService)({}), + Layer.mock(ThreadProjectMove)({}), Layer.mock(SecretRequests)({}), ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-context-budget-" }), Layer.mock(ServerEnvironment)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 222f23b6b02d9..1593cfd0760e1 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59170 + "mcpToolListJsonBytes": 62321 } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d06186beb1988..e8f4a4008baa4 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -29,6 +29,7 @@ import * as Stream from "effect/Stream"; import { FetchHttpClient, HttpRouter, HttpServer } from "effect/http"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; +import * as AppControl from "./appControl/AppControl.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; @@ -773,7 +774,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provideMerge(layerVcs), Layer.provideMerge(Layer.mergeAll(layerTerminal, layerPreview, layerDevice)), Layer.provideMerge(layerPersistence), - Layer.provideMerge(Layer.mergeAll(Keybindings.layer, UsageLimitSources.layer)), + Layer.provideMerge(Layer.mergeAll(Keybindings.layer, UsageLimitSources.layer, AppControl.layer)), Layer.provideMerge(ProviderRegistry.layer), Layer.provideMerge( ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(SqlitePersistence.layerConfig)), diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index f837fd8ca9722..ff1383781e0d7 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -489,6 +489,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" ); assert.equal(afterProviderSave.responseStreamingMode, "paragraph"); assert.equal(afterProviderSave.providerInstances[instanceId]?.displayName, "Kilo"); + + // A write's check judges the edit it would overwrite, and its failure leaves the file alone. + yield* writeFileStringAtomically({ + filePath: config.settingsPath, + contents: `{ "responseStreamingMode": "turn" }`, + }); + const refused = yield* serverSettings + .updateSettings({ responseStreamingMode: "paragraph" }, (current, next) => + current.responseStreamingMode === "turn" && next.responseStreamingMode === "paragraph" + ? Effect.fail("refused" as const) + : Effect.void, + ) + .pipe(Effect.flip); + assert.equal(refused, "refused"); + const afterRefusal = yield* decodeServerSettingsJson( + yield* fs.readFileString(config.settingsPath), + ); + assert.equal(afterRefusal.responseStreamingMode, "turn"); }).pipe(Effect.provide(layerServerSettings())), ); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index d4ddfd8b5c0c1..91e9c991dd14e 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -264,9 +264,11 @@ export class ServerSettingsService extends Context.Service< readonly getSettings: Effect.Effect; - readonly updateSettings: ( + /** `check` runs in the write lock on the settings the patch applies to; failing it aborts the write. */ + readonly updateSettings: ( patch: ServerSettingsPatch, - ) => Effect.Effect; + check?: (current: ServerSettings, next: ServerSettings) => Effect.Effect, + ) => Effect.Effect>; readonly updateProviderInstance: ( mutation: ProviderInstanceMutation, @@ -309,9 +311,9 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( const writeSemaphore = yield* Semaphore.make(1); const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)); - const updateTestSettings = ( - update: (current: ServerSettings) => Effect.Effect, - ): Effect.Effect => + const updateTestSettings = ( + update: (current: ServerSettings) => Effect.Effect, + ): Effect.Effect => writeSemaphore.withPermits(1)( Ref.get(currentSettingsRef).pipe( Effect.flatMap(update), @@ -326,10 +328,11 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( start: Effect.void, ready: Effect.void, getSettings, - updateSettings: (patch) => - updateTestSettings((currentSettings) => - Effect.succeed(applyServerSettingsPatch(currentSettings, patch)), - ), + updateSettings: (patch, check) => + updateTestSettings((currentSettings) => { + const next = applyServerSettingsPatch(currentSettings, patch); + return (check?.(currentSettings, next) ?? Effect.void).pipe(Effect.as(next)); + }), updateProviderInstance: (mutation, patch = {}) => updateTestSettings((currentSettings) => Effect.gen(function* () { @@ -1189,10 +1192,10 @@ const make = Effect.gen(function* () { ); }; - const updateAndPersistSettings = ( + const updateAndPersistSettings = ( patch: ServerSettingsPatch, - update: (current: ServerSettings) => Effect.Effect, - ): Effect.Effect => + update: (current: ServerSettings) => Effect.Effect, + ): Effect.Effect => writeSemaphore.withPermits(1)( Effect.gen(function* () { const { settings: current, parseFailure } = yield* reloadSettings; @@ -1414,12 +1417,14 @@ const make = Effect.gen(function* () { start, ready: Deferred.await(startedDeferred), getSettings: getMaterializedSettings, - updateSettings: (patch) => - updateAndPersistSettings(patch, (current) => - ensureSecretProviderWritesAllowed(patch, settingsPath).pipe( - Effect.as(applyServerSettingsPatch(current, patch)), - ), - ), + updateSettings: (patch, check) => + updateAndPersistSettings(patch, (current) => { + const next = applyServerSettingsPatch(current, patch); + return ensureSecretProviderWritesAllowed(patch, settingsPath).pipe( + Effect.andThen(check?.(current, next) ?? Effect.void), + Effect.as(next), + ); + }), updateProviderInstance: (mutation, patch = {}) => updateAndPersistSettings(patch, (current) => Effect.gen(function* () { diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 02ca5170d7ffd..9bfe8e1e64ef4 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -79,6 +79,7 @@ import * as AgentSessionScanner from "./project/AgentSessionScanner.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts"; import * as ProviderInstallation from "./provider/providerInstallation.ts"; +import * as AppControl from "./appControl/AppControl.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts"; @@ -94,6 +95,7 @@ import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as HostResources from "./resourceTelemetry/HostResources.ts"; import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts"; +import * as ThreadProjectMove from "./project/ThreadProjectMove.ts"; import * as McpAppRequests from "./mcpApps/McpAppRequests.ts"; import * as McpSignIn from "./mcpApps/McpSignIn.ts"; import * as ModelManifest from "./provider/ModelManifest.ts"; @@ -837,6 +839,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(AnalyticsService.AnalyticsService)({}), Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused" }), Layer.mock(BackgroundPolicy.BackgroundPolicy)({}), + Layer.mock(AppControl.AppControl)({}), Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}), Layer.mock(NativeChildWorkQuery.NativeChildWorkQuery)({}), Layer.mock(CommandOutputHub.CommandOutputHub)({}), @@ -962,6 +965,7 @@ it.live.each([ namedProjectsRoot: process.cwd(), }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ProviderRegistry.ProviderRegistry)({}), Layer.mock(UsageLimitSources.UsageLimitSources)({}), Layer.mock(ExternalLauncher.ExternalLauncher)({}), @@ -1105,6 +1109,7 @@ it.effect.each([ namedProjectsRoot: process.cwd(), }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({ getDescriptor: Effect.succeed({ environmentId: EnvironmentId.make("config-test"), @@ -1329,6 +1334,7 @@ it.effect("access changes made while the snapshot loads reach the client after i namedProjectsRoot: "/unused", }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({ listPairingLinks: () => Effect.succeed([]), @@ -1486,6 +1492,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", ( namedProjectsRoot: process.cwd(), }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({ getDescriptor: Effect.succeed({ environmentId: EnvironmentId.make("config-test"), @@ -1865,6 +1872,7 @@ it.effect("a missing thread worktree gets its project's skills in the cwd snapsh namedProjectsRoot: process.cwd(), }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), ); @@ -1951,6 +1959,7 @@ it.effect("a git action that fails partway still refreshes the repository status Layer.mock(DirectEndpoints.DirectEndpoints)({}), Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), ); @@ -2031,6 +2040,7 @@ it.effect("a publish whose push fails still refreshes the new remote", () => Layer.mock(DirectEndpoints.DirectEndpoints)({}), Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), ); @@ -2531,6 +2541,7 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i Layer.mock(DirectEndpoints.DirectEndpoints)({}), Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ThreadProjectMove.ThreadProjectMove)({}), Layer.mock(ServerEnvironment.ServerEnvironment)({}), Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), Layer.mock(ProjectService.ProjectService)({ diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ddd07fcfad656..aaf047c27eeab 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -233,6 +233,8 @@ import * as ProjectService from "./project/ProjectService.ts"; import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts"; import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts"; +import * as ThreadProjectMove from "./project/ThreadProjectMove.ts"; +import { isCheckpointFolderError } from "./checkpointing/Errors.ts"; import { mutateProjectWithClone } from "./project/ProjectMutation.ts"; import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts"; import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; @@ -242,6 +244,7 @@ import * as DirectEndpoints from "./environment/DirectEndpoints.ts"; import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import * as DefectReporter from "./observability/DefectReporter.ts"; import * as EventLoopMonitor from "./observability/EventLoopMonitor.ts"; +import * as AppControl from "./appControl/AppControl.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import { requiredScopeForDeviceList, rpcAuthorizationError } from "./auth/RpcAuthorization.ts"; @@ -1462,6 +1465,9 @@ export const layerWsRpc = ( const projectService = yield* ProjectService.ProjectService; const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; const scratchThreadPromotion = yield* ScratchThreadPromotion.ScratchThreadPromotion; + const threadProjectMove = yield* ThreadProjectMove.ThreadProjectMove; + const threadMoveError = (cause: ThreadProjectMove.ThreadProjectMoveError) => + new OrchestrationDispatchCommandError({ message: cause.message, cause }); const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor; const threadSearch = yield* ThreadSearch.ThreadSearch; @@ -1505,10 +1511,10 @@ export const layerWsRpc = ( yield* Effect.context>>(); const orchestrationEngine = yield* Orchestrator.OrchestratorV2; const random = yield* SecureRandom.SecureRandom; - // RPC client ids are only unique within one socket; terminals share viewers across sockets. - const terminalViewerPrefix = yield* random.uuidV4(); - const terminalViewerId = (metadata: { readonly client: { readonly id: number } }) => - `${terminalViewerPrefix}:${metadata.client.id}`; + // RPC client ids are only unique within one socket; terminals and app windows span sockets. + const socketPrefix = yield* random.uuidV4(); + const socketClientId = (metadata: { readonly client: { readonly id: number } }) => + `${socketPrefix}:${metadata.client.id}`; const serverCommandId = (tag: string) => random.uuidV4().pipe( Effect.orDie, @@ -1549,6 +1555,7 @@ export const layerWsRpc = ( threadManagement.getThreadShell, ); const previewManager = yield* PreviewManager.PreviewManager; + const appControl = yield* AppControl.AppControl; const portDiscovery = yield* PortScanner.PortDiscovery; const providerRegistry = yield* ProviderRegistry.ProviderRegistry; const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; @@ -2087,7 +2094,9 @@ export const layerWsRpc = ( Effect.mapError( (cause) => new OrchestrationGetTurnDiffError({ - message: "Failed to load turn diff", + message: isCheckpointFolderError(cause) + ? cause.message + : "Failed to load turn diff", cause, }), ), @@ -2097,7 +2106,9 @@ export const layerWsRpc = ( Effect.mapError( (cause) => new OrchestrationGetFullThreadDiffError({ - message: "Failed to load full thread diff", + message: isCheckpointFolderError(cause) + ? cause.message + : "Failed to load full thread diff", cause, }), ), @@ -2803,6 +2814,12 @@ export const layerWsRpc = ( input, ), ), + Effect.andThen( + appControl.reportFocus( + { sessionId: currentSessionId, windowId: socketClientId(metadata) }, + input.focused && input.visible, + ), + ), ), [WS_METHODS.cloudGetRelayClientStatus]: (_input) => relayClient.resolve, [WS_METHODS.cloudInstallRelayClient]: (_input) => @@ -2991,6 +3008,14 @@ export const layerWsRpc = ( (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }), ), ), + [WS_METHODS.projectsMoveThread]: (input) => + threadProjectMove.move(input).pipe(Effect.asVoid, Effect.mapError(threadMoveError)), + [WS_METHODS.projectsExportThread]: (input) => + threadProjectMove.exportThread(input.threadId).pipe(Effect.mapError(threadMoveError)), + [WS_METHODS.projectsImportThread]: (input) => + threadProjectMove.importThread(input).pipe(Effect.mapError(threadMoveError)), + [WS_METHODS.projectsFinishThreadMove]: (input) => + threadProjectMove.finishMove(input).pipe(Effect.mapError(threadMoveError)), [WS_METHODS.projectCloneCancel]: (input) => projectCloneTracker.cancel(input.projectId).pipe(Effect.map((applied) => ({ applied }))), [WS_METHODS.projectCloneRetry]: (input) => @@ -3350,15 +3375,15 @@ export const layerWsRpc = ( prepareTerminalLaunch(input).pipe( Effect.map((launch) => terminalManager - .attachOutputStream(launch.input, terminalViewerId(metadata)) + .attachOutputStream(launch.input, socketClientId(metadata)) .pipe(Stream.provideService(TerminalManager.TerminalCwdRecovery, launch.recover)), ), ), ), [WS_METHODS.terminalWrite]: (input, metadata) => - terminalManager.write(input, terminalViewerId(metadata)), + terminalManager.write(input, socketClientId(metadata)), [WS_METHODS.terminalResize]: (input, metadata) => - terminalManager.resize(input, terminalViewerId(metadata)), + terminalManager.resize(input, socketClientId(metadata)), [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input), [WS_METHODS.terminalClose]: (input) => terminalManager.close(input), [WS_METHODS.terminalObserve]: (input) => @@ -3384,6 +3409,14 @@ export const layerWsRpc = ( [WS_METHODS.previewReportProfiles]: (input) => reportProfiles(input), [WS_METHODS.previewReportStatus]: (input) => previewManager.reportStatus(input), [WS_METHODS.subscribePreviewEvents]: (_input) => previewManager.events, + [WS_METHODS.subscribeAppControl]: (input, metadata) => + Stream.unwrap( + appControl.connect( + { sessionId: currentSessionId, windowId: socketClientId(metadata) }, + input.focused, + ), + ), + [WS_METHODS.appControlRespond]: (input) => appControl.respond(currentSessionId, input), [WS_METHODS.deviceConfigure]: (input) => deviceService.configure(input), [WS_METHODS.deviceTestHost]: (input) => deviceService.testHost(input), [WS_METHODS.deviceEasAccount]: (input) => deviceService.easAccount(input), diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index ae8e685c5c9ec..2268180482bbb 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -59,6 +59,7 @@ import { environmentProjects } from "./state/projects"; import { primaryServerConfigAtom } from "./state/server"; import { environmentShell } from "./state/shell"; import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; +import { startAppControl } from "./lib/appControl"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; import { m } from "./i18n/messages"; import { startI18n, subscribeI18n } from "./i18n/runtime"; @@ -282,6 +283,7 @@ export function startAppServices(): AppRouter { startPreviewTitleRecording(); startBrowserProfileReporting(); installChatRouteCommands(router); + startAppControl(router); installCommandPaletteCommands(router); registerOpenFavoriteEditorCommand(); startThreadOverlayRetention(router); diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index c7515485662ac..fd6dc7516d992 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -65,7 +65,11 @@ import { } from "./ui/sidebar"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { registerCommands, registerMenuAction } from "../shortcuts/dispatcher"; +import { + registerCommandRunner, + registerCommands, + registerMenuAction, +} from "../shortcuts/dispatcher"; import { resolveThreadRouteRef } from "../threadRoutes"; const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)"; @@ -370,9 +374,15 @@ function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { const unsubscribe = window.desktopBridge?.onMenuAction((action) => { if (action === "sidebar.toggle") toggleSidebar(); }); + const unregisterRunner = registerCommandRunner((command) => { + if (command !== "sidebar.toggle") return false; + toggleSidebar(); + return true; + }); return () => { window.removeEventListener("keydown", onKeyDown, true); unsubscribe?.(); + unregisterRunner(); }; }, [keybindings, router, showSidebar, toggleSidebar, usagePageOpen]); diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 60c3c24ce5c2d..11db65b3ca3ad 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -218,6 +218,7 @@ it("opens a linked Linear issue from an inactive thread's sidebar badge", async __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + threadDetailsOpenByDefault: true, }); await page.viewport(1400, 900); const router = getRouter( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d17af4f620755..4dbf66624db08 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -64,7 +64,7 @@ import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./cha import { cancelHeldComposerSend, useComposerSendHeld } from "./chat/preparingComposerImages"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; -import { useChatShortcuts } from "./chat/useChatShortcuts"; +import { type ChatShortcutCommands, useChatShortcuts } from "./chat/useChatShortcuts"; import { ChatBannerLane } from "./chat/ChatBannerLane"; import * as Schema from "effect/Schema"; import { @@ -202,7 +202,14 @@ import { usePreviewMiniPlayerStore, } from "../previewMiniPlayerStore"; import { threadPullRequestPanelTarget } from "./pullRequest/pullRequestDetail.logic"; -import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog"; +import { + LinkPullRequestDialogHost, + openLinkPullRequestDialog, +} from "./pullRequest/LinkPullRequestDialog"; +import { canShareWithGuestAtom } from "./chat/guestShareAvailability"; +import { openGuestShareDialog } from "./chat/guestShareDialogState"; +import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; +import { useRestartAgentSession } from "../hooks/useRestartAgentSession"; import { GuestPendingMessages } from "./chat/GuestShareControls"; import { useDeviceState } from "~/state/device"; import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar"; @@ -2047,8 +2054,16 @@ export default function ChatView(props: ChatViewProps) { ? activePreviewMiniPlayer : null; const canvasPreview = useThreadPreviewCanvasSource(activeThreadRef, shownPreviewMiniPlayer); + const threadDetailsOpenByDefault = useClientSettings( + (settings) => settings.threadDetailsOpenByDefault, + ); const threadPanelInlineOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, activeThreadRef, "inline"), + selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + activeThreadRef, + "inline", + threadDetailsOpenByDefault, + ), ); // Selects only the mode, so canvas resizes rerender the chat view only when the // card switches presentation. @@ -2068,6 +2083,7 @@ export default function ChatView(props: ChatViewProps) { state.threadPanelVisibilityByThreadKey, activeThreadRef, threadPanelPresentation, + threadDetailsOpenByDefault, ), ); const supportsThreadPullRequests = serverConfig !== null; @@ -2875,6 +2891,33 @@ export default function ChatView(props: ChatViewProps) { } }); + const restartAgentSession = useRestartAgentSession(); + const canShareWithGuest = useAtomValue(canShareWithGuestAtom(environmentId)); + // The palette offers these too, through the same shortcuts. + const serverThreadShortcuts: ChatShortcutCommands = { + "thread.restartSession": ({ event }) => { + if (serverThread === null) return false; + if (!event.repeat) void restartAgentSession(serverThread, activeProjectCwd); + }, + "thread.showPullRequests": () => { + if (!pullRequestsSurfaceAvailable || activeThreadRef === null) return false; + useRightPanelStore.getState().open(activeThreadRef, "pull-requests"); + }, + "thread.linkPullRequest": () => { + if ( + !isServerThread || + activeThreadRef === null || + threadPullRequestLinkMode(serverConfig?.environment.capabilities) === "unsupported" + ) + return false; + openLinkPullRequestDialog(activeThreadRef); + }, + "thread.shareWithGuest": () => { + if (!isServerThread || activeThreadRef === null || !canShareWithGuest) return false; + openGuestShareDialog(activeThreadRef); + }, + }; + useChatShortcuts({ enabled: activeThreadId !== null && !backgroundThread, embedded, @@ -2893,6 +2936,7 @@ export default function ChatView(props: ChatViewProps) { ...terminalShortcuts, ...rightPanelShortcuts, ...threadLifecycleShortcuts, + ...serverThreadShortcuts, "thread.copyReference": ({ event }) => { if (!event.repeat) copyActiveThreadReference(); }, diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index cc839c6d92c3c..8230a6f53515e 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -53,6 +53,7 @@ import { AuthFilesystemReadScope, type DesktopWslState, type EnvironmentId, + type KeybindingCommand, type FilesystemBrowseResult, SourceControlProviderKind, PRIMARY_LOCAL_ENVIRONMENT_ID, @@ -69,7 +70,10 @@ import { FileSearchIcon, FolderGit2Icon, FolderIcon, + FolderInputIcon, + ServerIcon, FolderPlusIcon, + KeyboardIcon, MessageSquareDashedIcon, LinkIcon, MessageSquareIcon, @@ -85,6 +89,7 @@ import { UserPlusIcon, } from "lucide-react"; import { openThreadFind } from "./chat/threadFindStore"; +import { toggleComposerVimMode } from "./chat/composerVimMode"; import { dispatchPreviewAction } from "./preview/previewActionBus"; import { previewBridge } from "./preview/previewBridge"; import { @@ -123,10 +128,15 @@ import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesys import { projectEnvironment } from "../state/projects"; import { useEnvironmentQuery } from "../state/query"; import { serverEnvironment } from "../state/server"; -import { threadEnvironment } from "../state/threads"; import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { sourceControlEnvironment } from "../state/sourceControl"; import { useAtomCommand } from "../state/use-atom-command"; +import { useRestartAgentSession } from "../hooks/useRestartAgentSession"; +import { + confirmThreadMove, + moveThreadToMachineAndOpen, + readThreadMachineMoveTargets, +} from "../hooks/useThreadActions"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; import { useScratchProject } from "../hooks/useScratchProject"; @@ -151,6 +161,7 @@ import { waitForProject, } from "../state/entities"; import { isShownUnderParent, visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; +import { threadMoveTargets, threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; import { resolveThreadActionProjectRef, startNewThreadFromContext, @@ -326,6 +337,16 @@ function openIntentView( const NEW_THREAD_NO_PROJECT_VALUE = "new-thread-in:no-project"; +const PALETTE_ITEM_COMMANDS = new Set([ + "chat.new", + "chat.newLocal", + "chat.newWithoutProject", + "thread.restartSession", + "thread.showPullRequests", + "thread.linkPullRequest", + "thread.shareWithGuest", +]); + export function CommandPalette({ children }: { children: ReactNode }) { useCommandPaletteMount(); const state = useCommandPaletteStore(); @@ -490,12 +511,8 @@ function OpenCommandPaletteDialog(props: { const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, { reportFailure: false, }); - const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, { - reportFailure: false, - }); - const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { - reportFailure: false, - }); + const restartAgentSession = useRestartAgentSession(); + const moveThread = useAtomCommand(projectEnvironment.moveThread, { reportFailure: false }); const { environments } = useEnvironments(); const desktopLocalBootstraps = useDesktopLocalBootstraps(); const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -1515,6 +1532,7 @@ function OpenCommandPaletteDialog(props: { searchTerms: ["link", "pull request", "pr", "attach", "stack"], title: gt("Link pull request to thread"), icon: , + shortcutCommand: "thread.linkPullRequest", run: async () => { openLinkPullRequestDialog(threadRef); }, @@ -1528,6 +1546,7 @@ function OpenCommandPaletteDialog(props: { visibleThreadPullRequests(activeThread.pullRequests).length === 0 && !activeThread.issues?.length, icon: , + shortcutCommand: "thread.showPullRequests", run: async () => { useRightPanelStore.getState().open(threadRef, "pull-requests"); }, @@ -1542,12 +1561,100 @@ function OpenCommandPaletteDialog(props: { searchTerms: ["share", "guest", "invite", "link", "teammate"], title: gt("Share with guest"), icon: , + shortcutCommand: "thread.shareWithGuest", run: async () => { openGuestShareDialog(threadRef); }, }); } + const moveTargets = + activeThread !== null && + activeThreadServerConfig?.environment.capabilities.threadMoveToProject === true + ? threadMoveTargets(projects, activeThread, activeThreadServerConfig.scratchWorkspaceRoot) + : []; + if (activeThread !== null && moveTargets.length > 0) { + const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); + actionItems.push({ + kind: "submenu", + value: "action:move-thread-to-project", + searchTerms: ["move", "project", "folder", "relocate", "wrong project"], + title: gt("Move thread to..."), + icon: , + addonIcon: , + disabled: !threadRuntimeCanArchive(activeThread.runtime), + groups: [ + { + value: "move-thread-to-project", + label: gt("Projects"), + items: moveTargets.map((project) => ({ + kind: "action" as const, + value: `move-thread-to:${project.environmentId}:${project.id}`, + searchTerms: [project.title, project.workspaceRoot], + title: project.title, + description: project.workspaceRoot, + icon: , + run: async () => { + if (!(await confirmThreadMove(threadRef, project.id))) return; + const result = await moveThread({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, projectId: project.id }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Could not move thread"), + description: thrownErrorMessage(error, m) ?? gt("An error occurred."), + }), + ); + } + }, + })), + }, + ], + }); + } + + const machineMoveTargets = activeThread + ? readThreadMachineMoveTargets(scopeThreadRef(activeThread.environmentId, activeThread.id)) + : []; + if (activeThread !== null && machineMoveTargets.length > 0) { + const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); + actionItems.push({ + kind: "submenu", + value: "action:move-thread-to-machine", + searchTerms: ["move", "machine", "environment", "server", "remote", "computer"], + title: gt("Move thread to machine..."), + icon: , + addonIcon: , + disabled: !threadRuntimeCanArchive(activeThread.runtime), + groups: machineMoveTargets.map((machine) => ({ + value: `move-thread-to-machine:${machine.environmentId}`, + label: machine.label, + items: machine.projects.map((project) => ({ + kind: "action" as const, + value: `move-thread-to-machine:${machine.environmentId}:${project.id}`, + searchTerms: [machine.label, project.title, project.workspaceRoot], + title: project.title, + description: project.workspaceRoot, + icon: , + run: () => + moveThreadToMachineAndOpen( + threadRef, + { environmentId: machine.environmentId, projectId: project.id }, + (target) => + navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(target), + }), + ), + })), + })), + }); + } + if (activeThread !== null) { const thread = activeThread; actionItems.push({ @@ -1556,32 +1663,12 @@ function OpenCommandPaletteDialog(props: { searchTerms: ["restart", "reset", "reload", "agent", "session", "skills", "plugins", "mcp"], title: gt("Restart agent session"), icon: , - run: async () => { - const { environmentId } = thread; - if (thread.runtime !== null) { - const stopped = await stopThreadSession({ - environmentId, - input: { threadId: thread.id }, - }); - if (stopped._tag === "Failure") throw squashAtomCommandFailure(stopped); - } - toastManager.add({ - type: "success", - title: gt("Agent session will restart"), - description: gt("Your next message starts a fresh session."), - }); - const project = projectByKey.get(`${environmentId}:${thread.projectId}`); - if (!project) return; - const refreshed = await refreshProviders({ - environmentId, - input: { - instanceId: thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId, - cwd: thread.worktreePath ?? project.workspaceRoot, - fresh: true, - }, - }); - if (refreshed._tag === "Failure") throw squashAtomCommandFailure(refreshed); - }, + shortcutCommand: "thread.restartSession", + run: () => + restartAgentSession( + thread, + projectByKey.get(`${thread.environmentId}:${thread.projectId}`)?.workspaceRoot ?? null, + ), }); } @@ -1777,6 +1864,18 @@ function OpenCommandPaletteDialog(props: { }); } + actionItems.push({ + kind: "action", + value: "action:toggle-vim-mode", + searchTerms: ["vim", "vi", "normal mode", "insert mode", "composer", "keyboard"], + title: clientSettings.composerVimMode ? gt("Turn off vim mode") : gt("Turn on vim mode"), + icon: , + shortcutCommand: "composer.toggleVimMode", + run: async () => { + toggleComposerVimMode(); + }, + }); + actionItems.push({ kind: "action", value: "action:settings", @@ -2689,16 +2788,15 @@ function OpenCommandPaletteDialog(props: { return; } } - // Global new-thread handlers ignore shortcuts while the palette is open. + // Global new-thread and thread handlers ignore shortcuts while the palette is open. const isJump = threadJumpIndexFromCommand(command ?? "") !== null; - const isNewThread = + const isItemCommand = !event.nativeEvent.isComposing && event.keyCode !== 229 && - (command === "chat.new" || - command === "chat.newLocal" || - command === "chat.newWithoutProject"); + command !== null && + PALETTE_ITEM_COMMANDS.has(command); const matchingItem = - isJump || isNewThread + isJump || isItemCommand ? displayedGroups .flatMap((group) => group.items) .find((item) => item.shortcutCommand === command) diff --git a/apps/web/src/components/CommandPaletteLookups.ts b/apps/web/src/components/CommandPaletteLookups.ts index 75e94a33e0573..dae6b1ada8a79 100644 --- a/apps/web/src/components/CommandPaletteLookups.ts +++ b/apps/web/src/components/CommandPaletteLookups.ts @@ -57,6 +57,7 @@ export const selectCommandPaletteClientSettings = (settings: ClientSettings) => sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides, sidebarProjectSortOrder: settings.sidebarProjectSortOrder, sidebarThreadSortOrder: settings.sidebarThreadSortOrder, + composerVimMode: settings.composerVimMode, }); export function useSortedProjectGroups(environmentLabelById: ReadonlyMap) { diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 402156b001286..f0e62be9290c0 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -116,6 +116,14 @@ import { markAsClipboardEdit, markAsCompositionReplace, } from "~/composer-undo-grouping"; +import { INITIAL_VIM_STATE, type VimMode, type VimState } from "~/composer-vim"; +import { + ComposerVimExtension, + type ComposerVimContext, + composerVimMode, + handleComposerVimKeyDown, + showComposerVimMode, +} from "~/composer-vim-editor"; import { collectInlineContextIds } from "~/lib/composerContextReferences"; import { resolveDiffThemeName } from "~/lib/diffRendering"; import { isRichTextFormattingShortcut } from "~/keybindings"; @@ -176,6 +184,9 @@ export interface ComposerPromptEditorProps { cursor: number; richTextEnabled?: boolean; literalText?: boolean; + vimEnabled?: boolean; + /** The vim mode after each change, or null while vim mode is off. */ + onVimModeChange?: (mode: VimMode | null) => void; contextRecords: ComposerDraftContextRecords; buildContextClipboardFragment?: | ((contextIds: ReadonlyArray) => string | null) @@ -808,6 +819,8 @@ function replaceSkillChips( export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) { const restoreFocusRef = useRef(false); + // Outlives the keyed editor so the mode and register survive switching drafts. + const vimStateRef = useRef(INITIAL_VIM_STATE); const { onChange: onPromptChange } = props; const [selection, setSelection] = useState<{ value: string; @@ -830,6 +843,7 @@ export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) { key={`${props.draftKey ?? ""}:${props.literalText ? "literal" : props.richTextEnabled ? "rich" : "plain"}`} {...props} restoreFocusRef={restoreFocusRef} + vimStateRef={vimStateRef} initialExpandedCursor={ selection?.value === props.value && selection.cursor === props.cursor ? selection.expandedCursor @@ -889,6 +903,7 @@ function createComposerExtensions(richText: boolean) { ComposerCitationExtension, ComposerContextReferenceExtension, ComposerChipSelectionExtension, + ComposerVimExtension, ...(richText ? [ ComposerMarkdownSourceExtension, @@ -972,6 +987,7 @@ function ComposerPromptEditorTiptapInner( props: ComposerPromptEditorProps & { initialExpandedCursor: number; restoreFocusRef: RefObject; + vimStateRef: RefObject; }, ) { const { @@ -1004,6 +1020,9 @@ function ComposerPromptEditorTiptapInner( onPaste, editorRef, restoreFocusRef, + vimEnabled = false, + onVimModeChange, + vimStateRef, } = props; const richText = !literalText && (richTextEnabled ?? false); const clampEditorCursor = (text: string, position: number) => @@ -1024,6 +1043,8 @@ function ComposerPromptEditorTiptapInner( onCommandKeyDown, isPathQueryActive, importContextFragment, + vimEnabled, + onVimModeChange, })); const { environmentId } = use(ComposerContextActionsContext); @@ -1117,6 +1138,7 @@ function ComposerPromptEditorTiptapInner( const suppressTrigger = literalText || inCodeBlock || + composerVimMode(updated.state) === "normal" || [updated.state.selection.$from.nodeBefore, updated.state.selection.$from.nodeAfter].some( (node) => node?.isInline && node.isAtom && !node.isText && node.type.name !== "hardBreak", ); @@ -1130,6 +1152,33 @@ function ComposerPromptEditorTiptapInner( ); }; + const vimContext: ComposerVimContext = { + state: vimStateRef, + onModeChange: (mode) => readCallbacks().onVimModeChange?.(mode), + commandKey: (key, event) => readCallbacks().onCommandKeyDown?.(key, event) ?? false, + insertNewline: (view) => { + const dispatch = (tr: Transaction) => view.dispatch(tr.scrollIntoView()); + if (!selectionInOneCodeBlock(view.state) || !newlineInCode(view.state, dispatch)) { + insertComposerNewline(view, richText); + } + }, + insertMarkdown: (view, markdown) => { + const instance = (view.dom as TiptapEditorHTMLElement).editor; + if (!instance) return; + const nested = ["listItem", "taskItem", "blockquote"].some((name) => + hasAncestor(view.state.selection.$from, name), + ); + insertMarkdownParagraphs( + markdown, + skillLabelFor, + { styling: richText, blocks: !nested, literalText, isKnownModel }, + (content) => { + instance.chain().command(collapseShownMarkdownSource).insertContent(content).run(); + }, + ); + }, + }; + const editorAttributes = { class: cn( "composer-tiptap -m-1 block max-h-52 min-h-[calc(2lh+--spacing(2))] overflow-y-auto p-1 whitespace-pre-wrap wrap-break-word bg-transparent leading-relaxed text-foreground focus:outline-none", @@ -1181,6 +1230,9 @@ function ComposerPromptEditorTiptapInner( }, }, handleKeyDown: (view, event) => { + if (readCallbacks().vimEnabled && handleComposerVimKeyDown(view, event, vimContext)) { + return true; + } // In a right-to-left line the start is on the right. const backArrow = caretLineDirection(view.state) === "rtl" ? "ArrowRight" : "ArrowLeft"; const boundary = event.metaKey @@ -1365,34 +1417,7 @@ function ComposerPromptEditorTiptapInner( return true; } event.preventDefault(); - if ( - (isTaskItem || isListItem) && - instance && - splitOrLiftListItem(instance, collapseShownMarkdownSource) - ) { - return true; - } - if ( - richText && - instance && - hasAncestor(view.state.selection.$from, "blockquote") && - view.state.selection.$from.parent.content.size === 0 && - instance.commands.lift("blockquote") - ) { - return true; - } - // Parse shown Markdown first, or the split leaves each half with one delimiter. - if (instance) { - return instance - .chain() - .command(collapseShownMarkdownSource) - .command(({ state, dispatch }) => splitBlockKeepMarks(state, dispatch)) - .scrollIntoView() - .run(); - } - return splitBlockKeepMarks(view.state, (tr) => { - view.dispatch(tr.scrollIntoView()); - }); + return insertComposerNewline(view, richText); } if (!handler) return false; const handled = handler(event.key, event); @@ -1403,6 +1428,7 @@ function ComposerPromptEditorTiptapInner( return handled; }, handleTextInput: (view, from, to, text) => { + if (composerVimMode(view.state) === "normal") return true; if (literalText || view.composing || text.length !== 1) return false; const closer = SURROUND_CLOSE[text]; const { selection } = view.state; @@ -1598,6 +1624,15 @@ function ComposerPromptEditorTiptapInner( } }, [disabled, editor]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the vim setting into the editor's plugin state and reports the mode to the indicator + useLayoutEffect(() => { + if (!editor) return; + if (!vimEnabled) vimStateRef.current = INITIAL_VIM_STATE; + const mode = vimEnabled ? vimStateRef.current.mode : null; + showComposerVimMode(editor.view, mode); + readCallbacks().onVimModeChange?.(mode); + }, [editor, readCallbacks, vimEnabled, vimStateRef]); + // Push attributes before layout measurements; Tiptap updates them later in a passive effect. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes DOM attributes into the ProseMirror view before layout measurements read them useLayoutEffect(() => { @@ -1990,6 +2025,36 @@ function ComposerPromptEditorTiptapInner( ); } +/** Starts a new line at the selection, continuing or leaving a list or quote like Enter. */ +function insertComposerNewline(view: EditorView, richText: boolean): boolean { + const instance = (view.dom as TiptapEditorHTMLElement).editor; + const inList = richText && (instance?.isActive("taskItem") || instance?.isActive("listItem")); + if (inList && instance && splitOrLiftListItem(instance, collapseShownMarkdownSource)) { + return true; + } + if ( + richText && + instance && + hasAncestor(view.state.selection.$from, "blockquote") && + view.state.selection.$from.parent.content.size === 0 && + instance.commands.lift("blockquote") + ) { + return true; + } + // Parse shown Markdown first, or the split leaves each half with one delimiter. + if (instance) { + return instance + .chain() + .command(collapseShownMarkdownSource) + .command(({ state, dispatch }) => splitBlockKeepMarks(state, dispatch)) + .scrollIntoView() + .run(); + } + return splitBlockKeepMarks(view.state, (tr) => { + view.dispatch(tr.scrollIntoView()); + }); +} + /** Split newlines into paragraphs; trailing hard breaks render no visible line. */ function insertMarkdownParagraphs( value: string, diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.vim.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.vim.browser.test.tsx new file mode 100644 index 0000000000000..66b0babaff85c --- /dev/null +++ b/apps/web/src/components/ComposerPromptEditorTiptap.vim.browser.test.tsx @@ -0,0 +1,114 @@ +import type { Editor } from "@tiptap/core"; +import { createRef, useState } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { render } from "../../test/render"; + +import { serializeEditorDoc } from "~/composer-rich-text-doc"; +import { + ComposerPromptEditorTiptap as ComposerPromptEditor, + type ComposerPromptEditorHandle, + type ComposerPromptEditorProps, +} from "./ComposerPromptEditorTiptap"; + +type VimProps = Pick; + +function VimComposer({ value, ...props }: VimProps & { value: string }) { + const [prompt, setPrompt] = useState({ value, cursor: value.length }); + return ( + ()} + value={prompt.value} + cursor={prompt.cursor} + richTextEnabled + vimEnabled + contextRecords={new Map()} + skills={[]} + disabled={false} + placeholder="" + onChange={(...args) => setPrompt({ value: args[0], cursor: args[1] })} + onPaste={() => {}} + {...props} + /> + ); +} + +async function mountVim(value: string, props: VimProps = {}) { + await using stack = new AsyncDisposableStack(); + const screen = stack.use(await render()); + const element = screen.container.querySelector(".tiptap"); + if (!element) throw new Error("Composer did not mount"); + const { editor } = element; + editor.view.focus(); + const environment = stack.move(); + return Object.assign(screen, { + [Symbol.asyncDispose]: () => environment.disposeAsync(), + editor, + text: () => serializeEditorDoc(editor.state.doc).value, + }); +} + +describe("composer vim mode", () => { + it("edits from normal mode and undoes one command at a time", async () => { + await using screen = await mountVim("foo bar baz"); + await userEvent.keyboard("{Escape}"); + expect(screen.editor.view.dom.dataset.vimMode).toBe("normal"); + await userEvent.keyboard("0dwxq"); + expect(screen.text()).toBe("ar baz"); + await userEvent.keyboard("u"); + expect(screen.text()).toBe("bar baz"); + await userEvent.keyboard("u"); + expect(screen.text()).toBe("foo bar baz"); + }); + + it("keeps chips when putting a yanked line", async () => { + await using screen = await mountVim("see @a.md now\nnext"); + await userEvent.keyboard("{Escape}ggyyp"); + expect(screen.text()).toBe("see @a.md now\nsee @a.md now\nnext"); + let chips = 0; + screen.editor.state.doc.descendants((node) => { + if (node.type.name === "composer-mention") chips += 1; + }); + expect(chips).toBe(2); + }); + + it("deletes, puts and joins lines across paragraphs", async () => { + await using screen = await mountVim("a\nb\nc"); + await userEvent.keyboard("{Escape}ggjdd"); + expect(screen.text()).toBe("a\nc"); + await userEvent.keyboard("P"); + expect(screen.text()).toBe("a\nb\nc"); + await userEvent.keyboard("ggJ"); + expect(screen.text()).toBe("a b\nc"); + await userEvent.keyboard("0cwx{Escape}w."); + expect(screen.text()).toBe("x x\nc"); + expect(screen.editor.view.dom.querySelector(".composer-vim-cursor")?.textContent).toBe("x"); + }); + + it("continues a list when opening a line below an item", async () => { + await using screen = await mountVim("- a\n- b"); + await userEvent.keyboard("{Escape}ggoc{Escape}"); + expect(screen.text()).toBe("- a\n- c\n- b"); + }); + + it("sends with Enter from normal mode without adding a line", async () => { + const onCommandKeyDown = vi.fn((key: string) => key === "Enter"); + await using screen = await mountVim("hello", { onCommandKeyDown }); + await userEvent.keyboard("{Escape}{Enter}"); + expect(onCommandKeyDown).toHaveBeenCalledWith("Enter", expect.anything()); + expect(screen.text()).toBe("hello"); + }); + + it("lets an open menu take Escape before leaving insert mode", async () => { + const onCommandKeyDown = vi.fn((key: string) => key === "Escape"); + const onVimModeChange = vi.fn(); + await using screen = await mountVim("@a", { onCommandKeyDown, onVimModeChange }); + await userEvent.keyboard("{Escape}"); + expect(onVimModeChange).not.toHaveBeenCalledWith("normal"); + onCommandKeyDown.mockReturnValue(false); + await userEvent.keyboard("{Escape}"); + expect(onVimModeChange).toHaveBeenLastCalledWith("normal"); + expect(screen.editor.view.dom.dataset.vimMode).toBe("normal"); + }); +}); diff --git a/apps/web/src/components/DiffPanel.browser.test.tsx b/apps/web/src/components/DiffPanel.browser.test.tsx index 685cac0fc7f62..f7bea2cec52ef 100644 --- a/apps/web/src/components/DiffPanel.browser.test.tsx +++ b/apps/web/src/components/DiffPanel.browser.test.tsx @@ -322,22 +322,37 @@ it.each([false, true])( }, ); -it("says a turn diff cut off at the server's size limit is incomplete", async () => { +function setNotARepo() { + state.status = Atom.make( + AsyncResult.success({ + isRepo: false, + hasPrimaryRemote: false, + isDefaultRef: false, + refName: null, + hasWorkingTreeChanges: false, + workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 }, + hasUpstream: false, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ); +} + +it("explains a turn without a checkpoint in a folder outside git", async () => { using context = setup("origin/orphan"); + setNotARepo(); state.checkpoints = [ { runId: "run", checkpointTurnCount: 1, checkpointRef: "ref", - status: "ready", + status: "missing", files: [], assistantMessageId: null, completedAt: "2026-01-01T00:00:00Z", }, ]; - state.checkpointDiff = { - diff: "diff --git a/first.txt b/first.txt\n--- a/first.txt\n+++ b/first.txt\n@@ -0,0 +1 @@\n+visible\n\n[truncated]", - }; useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run")); await using screen = await render( @@ -346,12 +361,50 @@ it("says a turn diff cut off at the server's size limit is incomplete", async () , ); - await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible(); await expect - .element(screen.getByText("This preview exceeds the size limit. Changes shown are incomplete.")) + .element( + screen.getByText("Turn diffs are unavailable because this project is not a git repository."), + ) .toBeVisible(); }); +// A moved thread's turns diff in the folder they ran in, whatever the current project is. +it.each([true, false])( + "says a turn diff cut off at the server's size limit is incomplete (current folder is git: %s)", + async (isRepo) => { + using context = setup("origin/orphan"); + if (!isRepo) setNotARepo(); + state.checkpoints = [ + { + runId: "run", + checkpointTurnCount: 1, + checkpointRef: "ref", + status: "ready", + files: [], + assistantMessageId: null, + completedAt: "2026-01-01T00:00:00Z", + }, + ]; + state.checkpointDiff = { + diff: "diff --git a/first.txt b/first.txt\n--- a/first.txt\n+++ b/first.txt\n@@ -0,0 +1 @@\n+visible\n\n[truncated]", + }; + useDiffPanelStore.getState().selectTurn(context.threadRef, RunId.make("run")); + await using screen = await render( + +
+ +
+
, + ); + await expect.element(screen.getByText("first.txt", { exact: true }).first()).toBeVisible(); + await expect + .element( + screen.getByText("This preview exceeds the size limit. Changes shown are incomplete."), + ) + .toBeVisible(); + }, +); + it("shows a turn's repositories in a folder that is not a Git repository", async () => { using context = setup("origin/orphan"); state.status = Atom.make( diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 561bcd2b3e040..1224bfd0d1076 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -409,6 +409,8 @@ export default function DiffPanel({ : (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ?? orderedTurnDiffSummaries[0]); const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount; + // A moved thread's turns diff in the folder they ran in, which may be git when the current one isn't. + const canDiffSelectedTurn = isGitRepo || hasRepositoryChanges || selectedTurn?.status === "ready"; const reviewSectionId = toolCallSelection ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}` : selectedTurn @@ -436,7 +438,7 @@ export default function DiffPanel({ ignoreWhitespace: diffIgnoreWhitespace, cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null, }, - { enabled: (isGitRepo || hasRepositoryChanges) && selectedTurn !== undefined }, + { enabled: canDiffSelectedTurn && selectedTurn !== undefined }, ); const branchDiffPreviewInput = canReadFiles && isGitSelection && activeThread && gitCwd @@ -1580,7 +1582,7 @@ export default function DiffPanel({
Select a thread to inspect turn diffs.
- ) : !isGitRepo && !hasRepositoryChanges && !toolCallSelection ? ( + ) : !canDiffSelectedTurn && !toolCallSelection ? (
Turn diffs are unavailable because this project is not a git repository.
diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 57ed98c49dfca..89960ca9bc4ea 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -115,6 +115,7 @@ import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey"; +import { registerCommandRunner } from "../shortcuts/dispatcher"; export interface RightPanelTabsProps { mode: PreviewPanelMode; @@ -1140,6 +1141,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) { if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false); + const openAddSurfaceMenu = useEffectEvent(() => { + addSurfaceTriggerRef.current?.focus(); + setAddSurfaceMenuOpen(true); + }); const addSurfaceMenuBlocked = () => !addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS) !== null; const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => { @@ -1153,24 +1158,28 @@ export function RightPanelTabs(props: RightPanelTabsProps) { if (addSurfaceMenuBlocked()) return; event.preventDefault(); event.stopPropagation(); - if (!event.repeat) { - addSurfaceTriggerRef.current?.focus(); - setAddSurfaceMenuOpen(true); - } + if (!event.repeat) openAddSurfaceMenu(); }); // Forwarded from a focused browser page. Focusing the trigger here would let ChatView's // window-focus handler see a plain button and refocus the composer, closing the menu. const onMenuAction = useEffectEvent((action: string) => { if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true); }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown, the desktop menu action (forwarded from a focused browser page), and the app command runner for the new surface shortcut while the panel is open useEffect(() => { if (props.open === false) return; document.addEventListener("keydown", onNewSurfaceKeyDown, true); const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction); + const unregisterRunner = registerCommandRunner((command) => { + if (command !== "rightPanel.new" || document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) + return false; + openAddSurfaceMenu(); + return true; + }); return () => { document.removeEventListener("keydown", onNewSurfaceKeyDown, true); unsubscribe?.(); + unregisterRunner(); }; }, [props.open]); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index f8527d0d75a1f..21f5c58b6e4a7 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -104,6 +104,7 @@ import { threadTraversalDirectionFromCommand, } from "../keybindings"; import { isModelPickerOpen } from "../modelPickerVisibility"; +import { registerCommandRunner } from "../shortcuts/dispatcher"; import { isMacPlatform } from "~/lib/utils"; import { readLocalApi } from "../localApi"; import { configuredHostedAppUrl } from "../hostedPairing"; @@ -126,6 +127,9 @@ import { } from "../threadSelectionStore"; import { canTurnThreadIntoProject, + confirmThreadMove, + readThreadMachineMoveTargets, + readThreadMoveTargets, useAcknowledgeThreadWoke, useThreadActions, } from "../hooks/useThreadActions"; @@ -177,6 +181,7 @@ import { ProjectRowActions } from "./ProjectComboboxRow"; import { buildDraftActionMenuItems, buildThreadActionMenuItems, + parseMachineMovePick, threadActionRequiresOperate, } from "./threadActionMenu.logic"; import { @@ -947,6 +952,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve confirmAndUnpinThread, setThreadAutoSettle, turnThreadIntoProject, + moveThreadToProject, + moveThreadToMachine, reorderPinnedThread, reorderActiveThread, markThreadUnread, @@ -2672,6 +2679,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve serverConfigs.get(thread.environmentId)?.environment.capabilities .threadAutoSettleOptOut === true; const isRegeneratingTitle = thread.titleRegeneration != null; + const machineMoveTargets = readThreadMachineMoveTargets(threadRef); const isSettled = settledThreadKeysRef.current.has(threadKey); const isSnoozed = snoozedThreadKeysRef.current.has(threadKey); const isPinned = thread.pinnedAt != null; @@ -2715,6 +2723,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve canShareWithGuestAtom(threadRef.environmentId), ), canTurnIntoProject: canTurnThreadIntoProject(threadRef), + moveTargets: readThreadMoveTargets(threadRef), + machineMoveTargets, canRename: !fromSearch, supports: { settlement: configLoaded, @@ -2744,6 +2754,30 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (preset) attemptSnooze(threadRef, preset); return; } + const machinePick = parseMachineMovePick(clicked.value, machineMoveTargets); + if (machinePick) { + await moveThreadToMachine(threadRef, { + environmentId: machinePick.machine.environmentId, + projectId: machinePick.project.id, + }); + return; + } + if (clicked.value.startsWith("move-to-project:")) { + const projectId = ProjectId.make(clicked.value.slice("move-to-project:".length)); + if (!(await confirmThreadMove(threadRef, projectId))) return; + const result = await moveThreadToProject(threadRef, projectId); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Could not move thread"), + description: thrownErrorMessage(error, m) ?? gt("An error occurred."), + }), + ); + } + return; + } switch (clicked.value) { case "filter-by-project": if (threadProjectGroup) { @@ -2949,43 +2983,50 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown for thread navigation shortcuts using the current thread list useEffect(() => { - const onWindowKeyDown = (event: KeyboardEvent) => { - if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) { - return; - } - const command = resolveShortcutCommand(event, keybindings, { - platform: navigator.platform, - context: threadShortcutContext(routeThreadRef), - }); - const navigateToRowKey = (targetRowKey: string | null) => { - if (!targetRowKey) return false; - const targetDraftId = draftIdByRowKey.get(targetRowKey); - const targetThread = threadByKey.get(targetRowKey); - if (targetDraftId === undefined && !targetThread) return false; - event.preventDefault(); - event.stopPropagation(); - if (targetDraftId !== undefined) navigateToDraft(targetDraftId); - else if (targetThread) - navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); - return true; - }; + const navigateToRowKey = (targetRowKey: string | null) => { + if (!targetRowKey) return false; + const targetDraftId = draftIdByRowKey.get(targetRowKey); + const targetThread = threadByKey.get(targetRowKey); + if (targetDraftId !== undefined) navigateToDraft(targetDraftId); + else if (targetThread) + navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); + else return false; + return true; + }; + const runThreadCommand = (command: string | null) => { const traversalDirection = threadTraversalDirectionFromCommand(command); if (traversalDirection !== null) { - navigateToRowKey( + return navigateToRowKey( resolveAdjacentThreadId({ threadIds: orderedRowKeys, currentThreadId: routeRowKey, direction: traversalDirection, }), ); - return; } const jumpIndex = threadJumpIndexFromCommand(command ?? ""); - if (jumpIndex === null) return; - navigateToRowKey(orderedRowKeys[jumpIndex] ?? null); + return jumpIndex !== null && navigateToRowKey(orderedRowKeys[jumpIndex] ?? null); + }; + const onWindowKeyDown = (event: KeyboardEvent) => { + if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) { + return; + } + const command = resolveShortcutCommand(event, keybindings, { + platform: navigator.platform, + context: threadShortcutContext(routeThreadRef), + }); + if (!runThreadCommand(command)) return; + event.preventDefault(); + event.stopPropagation(); }; window.addEventListener("keydown", onWindowKeyDown); - return () => window.removeEventListener("keydown", onWindowKeyDown); + const unregisterRunner = registerCommandRunner( + (command) => !isCommandPaletteOpen() && runThreadCommand(command), + ); + return () => { + window.removeEventListener("keydown", onWindowKeyDown); + unregisterRunner(); + }; }, [ draftIdByRowKey, keybindings, diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index 7848009308750..5c3ddc93f03a7 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -4,6 +4,7 @@ import { ChatCanvasContext } from "./ChatCanvasContext"; import type { ChatCanvasPreview } from "./chatCanvasLayout"; import { resolveChatCanvasModel, type ChatCanvasStore } from "./canvasStore"; import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore"; +import { useClientSettings } from "../../hooks/useSettings"; import { observeResize } from "../../lib/observeResize"; import type { ScopedThreadRef } from "@t3tools/contracts"; @@ -134,10 +135,18 @@ export function ChatCanvas({ stopObserving(); }; }, [store, composerOverlayElement, timelineElement, detailsCardTopInset]); + const threadDetailsOpenByDefault = useClientSettings( + (settings) => settings.threadDetailsOpenByDefault, + ); const detailsCardInlineOpen = useRightPanelStore((state) => threadRef === null ? false - : selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), + : selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + threadRef, + "inline", + threadDetailsOpenByDefault, + ), ); const model = resolveChatCanvasModel({ measurements, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6fb651c3471f6..76ccc7a84d6a4 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -115,6 +115,8 @@ import { } from "../../composerDraftStore"; import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../../threadRoutes"; import { ComposerStashBadge } from "./ComposerStashBadge"; +import { Badge } from "../ui/badge"; +import type { VimMode } from "../../composer-vim"; import { ComposerStashMenu } from "./ComposerStashMenu"; import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; @@ -1061,6 +1063,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const isMobileViewport = useMediaQuery("max-sm"); const isSoftwareKeyboardOpen = useSoftwareKeyboardOpen(); const [isComposerFocused, setIsComposerFocused] = useState(false); + const [vimMode, setVimMode] = useState(null); const [composerSubmissionError, setComposerSubmissionError] = useState(null); const [providerInputSubmissionError, setProviderInputSubmissionError] = useState( null, @@ -3851,6 +3854,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } editorRef={composerEditorRef} richTextEnabled={settings.composerRichTextEnabled} + vimEnabled={settings.composerVimMode} + onVimModeChange={setVimMode} literalText={isLiteralPendingAnswer} isPathQueryActive={isPathQueryActiveStable} value={activePendingProgress ? activePendingProgress.customAnswer : prompt} @@ -3972,6 +3977,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) {composerAttachButton && !dictationTakesFooter ? (
{composerAttachButton}
) : null} + {vimMode && !dictationTakesFooter ? ( +
+ + {vimMode === "normal" ? "NORMAL" : "INSERT"} + +
+ ) : null}
useRightPanelStore.getState().threadPanelVisibilityByThreadKey, threadRef, "popover", + false, ); function Card({ diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index 9959dbe2dc41c..799eda5e910b0 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -12,6 +12,7 @@ import { ScrollArea } from "../ui/scroll-area"; import { cn } from "../../lib/utils"; import { Popover, PopoverPopup, PopoverCreateHandle } from "../ui/popover"; import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore"; +import { useClientSettings } from "../../hooks/useSettings"; import { useChatCanvas } from "./ChatCanvasContext"; import { THREAD_DETAILS_CARD_GAP, @@ -43,11 +44,24 @@ export function ThreadDetailsCard({ const placement = canvas?.detailsCardPlacement ?? null; const mode = placement ? "inline" : "popover"; const topInset = canvas?.detailsCardTopInset ?? 0; + const threadDetailsOpenByDefault = useClientSettings( + (settings) => settings.threadDetailsOpenByDefault, + ); const inlineOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), + selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + threadRef, + "inline", + threadDetailsOpenByDefault, + ), ); const popoverOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "popover"), + selectThreadPanelOpen( + state.threadPanelVisibilityByThreadKey, + threadRef, + "popover", + threadDetailsOpenByDefault, + ), ); const measurementKey = `${threadRef.environmentId}:${threadRef.threadId}:${preferredPlacement?.width ?? "popup"}:${contentKey}`; const [measurements, setMeasurements] = useState({ diff --git a/apps/web/src/components/chat/composerShortcuts.ts b/apps/web/src/components/chat/composerShortcuts.ts index 30beb9771968f..d3f030d532d58 100644 --- a/apps/web/src/components/chat/composerShortcuts.ts +++ b/apps/web/src/components/chat/composerShortcuts.ts @@ -1,6 +1,7 @@ import type { ComposerHandleRef } from "../../composerHandleContext"; import type { BranchToolbarHandle } from "../BranchToolbar"; import type { ChatComposerHandle } from "./ChatComposer"; +import { toggleComposerVimMode } from "./composerVimMode"; import type { ChatShortcutCommands } from "./useChatShortcuts"; const openControl = @@ -9,7 +10,7 @@ const openControl = if (!event.repeat) composerRef.current?.openControl(control); }; -/** Chords that open or step the composer's controls and its branch toolbar. Held keys do not repeat them. */ +/** Chords for the composer's controls, vim mode and branch toolbar. Held keys do not repeat them. */ export function composerShortcutCommands( composerRef: ComposerHandleRef, branchToolbarRef: { readonly current: BranchToolbarHandle | null }, @@ -34,5 +35,8 @@ export function composerShortcutCommands( "composer.previousWorktree": ({ event }) => { if (!event.repeat) branchToolbarRef.current?.usePreviousWorktree(); }, + "composer.toggleVimMode": ({ event }) => { + if (!event.repeat) toggleComposerVimMode(); + }, } satisfies ChatShortcutCommands; } diff --git a/apps/web/src/components/chat/composerVimMode.ts b/apps/web/src/components/chat/composerVimMode.ts new file mode 100644 index 0000000000000..09b78408c7074 --- /dev/null +++ b/apps/web/src/components/chat/composerVimMode.ts @@ -0,0 +1,15 @@ +import { msg } from "gt-react"; + +import { getClientSettings, updateClientSettings } from "../../hooks/useSettings"; +import { m } from "../../i18n/messages"; +import { toastManager } from "../ui/toast"; + +export function toggleComposerVimMode(): void { + const enabled = !getClientSettings().composerVimMode; + void updateClientSettings({ composerVimMode: enabled }); + toastManager.add({ + id: "composer-vim-mode", + title: m(enabled ? msg("Vim mode on") : msg("Vim mode off")), + timeout: 1500, + }); +} diff --git a/apps/web/src/components/chat/useChatShortcuts.ts b/apps/web/src/components/chat/useChatShortcuts.ts index 6400aa137ca1e..c8af635d6b942 100644 --- a/apps/web/src/components/chat/useChatShortcuts.ts +++ b/apps/web/src/components/chat/useChatShortcuts.ts @@ -1,6 +1,7 @@ import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts"; import { useEffect, useEffectEvent } from "react"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; +import { registerCommandRunner } from "../../shortcuts/dispatcher"; import { resolveChatShortcutCommand, type ShortcutMatchContext } from "../../keybindings"; import { isTerminalCloseConfirmPending } from "../../lib/terminalCloseConfirm"; import { @@ -101,6 +102,17 @@ export function useChatShortcuts(input: ChatShortcutsInput) { event.preventDefault(); event.stopPropagation(); }); + const runWithoutKey = useEffectEvent((command: KeybindingCommand) => { + if (!input.enabled || isCommandPaletteOpen()) return false; + const run = + input.commands[command] ?? + composerShortcutCommands(input.composerRef, input.branchToolbarRef)[command] ?? + input.fallback(command); + const event = new KeyboardEvent("keydown", { cancelable: true }); + return ( + run !== undefined && run({ event, terminalFocusOwner: getTerminalFocusOwner() }) !== false + ); + }); const dismissFind = useEffectEvent((event: KeyboardEvent) => { if ( event.key !== "Escape" || @@ -141,9 +153,11 @@ export function useChatShortcuts(input: ChatShortcutsInput) { const onKeyDown = (event: KeyboardEvent) => dismissFind(event); window.addEventListener("keydown", onKeyDownCapture, true); window.addEventListener("keydown", onKeyDown); + const unregisterRunner = registerCommandRunner((command) => runWithoutKey(command)); return () => { window.removeEventListener("keydown", onKeyDownCapture, true); window.removeEventListener("keydown", onKeyDown); + unregisterRunner(); }; }, [composerElement, embedded]); } diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index 9a5e4c24e7a0c..d1347eb9a0b13 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -18,6 +18,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { useDiffPanelStore } from "../../diffPanelStore"; +import { getClientSettings } from "../../hooks/useSettings"; import { type ThreadPanelPresentation } from "../../rightPanelLayout"; import { selectThreadPanelOpen, @@ -250,17 +251,18 @@ export function useRightPanelActions(input: RightPanelActionsInput) { const toggleThreadPanel = () => { if (!activeThreadRef) return; const store = useRightPanelStore.getState(); + const open = selectThreadPanelOpen( + store.threadPanelVisibilityByThreadKey, + activeThreadRef, + threadPanelPresentation, + getClientSettings().threadDetailsOpenByDefault, + ); if (threadPanelPresentation === "inline") { - const open = selectThreadPanelOpen( - store.threadPanelVisibilityByThreadKey, - activeThreadRef, - "inline", - ); if (!open) requestWorkspaceFocus({ area: "details" }); else if (document.activeElement?.closest('[data-workspace-area="details"]')) requestWorkspaceContentFocus(); } - store.toggleThreadPanel(activeThreadRef, threadPanelPresentation); + store.setThreadPanelOpen(activeThreadRef, threadPanelPresentation, !open); }; const toggleThreadPanelStable = useStableCallback(toggleThreadPanel); const toggleRightPanelMaximized = () => { diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1e14ab19d9012..b3aa286e7142b 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -168,6 +168,7 @@ import { resolveFilterOptions } from "./pullRequestListOptions"; import { PullRequestGuideTab } from "./PullRequestGuideTab"; import { guideRunKey, useGuideRunStore } from "./guide/guideRunStore"; import { useReviewGuideWriter } from "./guide/useReviewGuideWriter"; +import { registerCommandRunner } from "~/shortcuts/dispatcher"; import { changeRequestTermKind, type ChangeRequestTermKind } from "./changeRequestTerm"; @@ -617,6 +618,22 @@ export function PullRequestDetailPanel({ description: error.message, }), }); + const copyNumber = useEffectEvent(() => + copyReference( + `#${reference.number}`, + m( + msg("Failed to copy {term, select, mr {MR} cr {change request} other {PR}} number", { + term: changeRequestTermKind(terminology), + }), + ), + ), + ); + const runCopyNumber = useEffectEvent((command: string) => { + if (command !== "pullRequest.copyNumber" || !shortcutsEnabled || isCommandPaletteOpen()) + return false; + copyNumber(); + return true; + }); const copyFromShortcut = useEffectEvent((event: KeyboardEvent) => { if (!shortcutsEnabled || event.defaultPrevented || isCommandPaletteOpen()) return; const command = resolveShortcutCommand(event, keybindings, { @@ -625,21 +642,17 @@ export function PullRequestDetailPanel({ if (command !== "pullRequest.copyNumber") return; event.preventDefault(); event.stopPropagation(); - if (!event.repeat) - copyReference( - `#${reference.number}`, - m( - msg("Failed to copy {term, select, mr {MR} cr {change request} other {PR}} number", { - term: changeRequestTermKind(terminology), - }), - ), - ); + if (!event.repeat) copyNumber(); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown capture listener for the copy-number shortcut useEffect(() => { const onKeyDown = (event: KeyboardEvent) => copyFromShortcut(event); window.addEventListener("keydown", onKeyDown, true); - return () => window.removeEventListener("keydown", onKeyDown, true); + const unregisterRunner = registerCommandRunner((command) => runCopyNumber(command)); + return () => { + window.removeEventListener("keydown", onKeyDown, true); + unregisterRunner(); + }; }, []); const autoMergeKey = `${pullRequestKey}:${detail?.autoMergeMethod ?? ""}`; const [seenAutoMergeKey, setSeenAutoMergeKey] = useState(null); diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index 72fda9150a7b2..b310e1d027be1 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -295,6 +295,34 @@ export function AppearanceSettingsPanel() { } /> + + updateSettings({ + threadDetailsOpenByDefault: DEFAULT_UNIFIED_SETTINGS.threadDetailsOpenByDefault, + }) + } + /> + ) : null + } + control={ + + updateSettings({ threadDetailsOpenByDefault: Boolean(checked) }) + } + aria-label={gt("Open thread details by default")} + /> + } + /> { ); }); + it("resets a customized shortcut to the default its command no longer has", () => { + const rows = buildKeybindingRows( + compileResolvedKeybindingsConfig([ + { command: "terminal.toggle", key: "ctrl+`" }, + { command: "terminal.toggle", key: "mod+shift+y" }, + ]), + ); + expect(rows.find((row) => row.key === "mod+shift+y")?.defaultKey).toBe("mod+j"); + }); + it("marks only bindings shadowed by later unconditional or matching conditions", () => { const bindings = compileResolvedKeybindingsConfig([ { command: "sidebar.toggle", key: "mod+b" }, diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 55d4278b0fe16..b5e2928dbded8 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -173,29 +173,27 @@ function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource { function defaultBindingForBinding( binding: ResolvedKeybindingRule, + boundIds: ReadonlySet, ): ResolvedKeybindingRule | undefined { + const id = bindingRowId(binding); const bindingKey = shortcutToKeybindingInput(binding.shortcut); const bindingWhen = whenAstToExpression(binding.whenAst); + const defaults = DEFAULT_RESOLVED_KEYBINDINGS.filter( + (entry) => entry.command === binding.command, + ); + // Reset restores a default the command lost before one it still has. + const candidates = [ + ...defaults.filter((entry) => !boundIds.has(bindingRowId(entry))), + ...defaults.filter((entry) => boundIds.has(bindingRowId(entry))), + ]; return ( - DEFAULT_RESOLVED_KEYBINDINGS.find( - (entry) => - entry.command === binding.command && - shortcutToKeybindingInput(entry.shortcut) === bindingKey && - whenAstToExpression(entry.whenAst) === bindingWhen, - ) ?? + defaults.find((entry) => bindingRowId(entry) === id) ?? (bindingWhen === "false" - ? DEFAULT_RESOLVED_KEYBINDINGS.find( - (entry) => - entry.command === binding.command && - shortcutToKeybindingInput(entry.shortcut) === bindingKey, - ) + ? defaults.find((entry) => shortcutToKeybindingInput(entry.shortcut) === bindingKey) : undefined) ?? - DEFAULT_RESOLVED_KEYBINDINGS.find( - (entry) => - entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen, - ) ?? - DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command) + candidates.find((entry) => whenAstToExpression(entry.whenAst) === bindingWhen) ?? + candidates[0] ); } @@ -203,6 +201,14 @@ function keybindingRowId(command: KeybindingCommand, key: string, when: string): return `${command}\u0000${key}\u0000${when}`; } +function bindingRowId(binding: ResolvedKeybindingRule): string { + return keybindingRowId( + binding.command, + shortcutToKeybindingInput(binding.shortcut), + whenAstToExpression(binding.whenAst), + ); +} + function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean { if (leftWhen === "false" || rightWhen === "false") return false; return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen; @@ -311,8 +317,9 @@ export function buildKeybindingRows( } } const rowsById = new Map(); + const boundIds = new Set(keybindings.map(bindingRowId)); for (const [index, binding] of keybindings.entries()) { - const defaultBinding = defaultBindingForBinding(binding); + const defaultBinding = defaultBindingForBinding(binding, boundIds); const key = shortcutToKeybindingInput(binding.shortcut); const when = whenAstToExpression(binding.whenAst); const id = keybindingRowId(binding.command, key, when); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 493d8a1e79565..b54550b709207 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -500,6 +500,9 @@ export function useSettingsRestore(onRestored?: () => void) { ? [gt("Diff colors")] : []), ...(settings.chatWidth !== DEFAULT_UNIFIED_SETTINGS.chatWidth ? [gt("Chat width")] : []), + ...(settings.threadDetailsOpenByDefault !== DEFAULT_UNIFIED_SETTINGS.threadDetailsOpenByDefault + ? [gt("Open thread details by default")] + : []), ...(settings.effortDisplay !== DEFAULT_UNIFIED_SETTINGS.effortDisplay ? [gt("Effort display")] : []), @@ -576,6 +579,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.sendShortcut !== DEFAULT_UNIFIED_SETTINGS.sendShortcut ? [gt("Send shortcut")] : []), + ...(settings.composerVimMode !== DEFAULT_UNIFIED_SETTINGS.composerVimMode + ? [gt("Vim mode")] + : []), ...(settings.followUpBehavior !== DEFAULT_UNIFIED_SETTINGS.followUpBehavior ? [gt("Follow-up behavior")] : []), @@ -697,6 +703,7 @@ export function useSettingsRestore(onRestored?: () => void) { appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast, diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme, chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, + threadDetailsOpenByDefault: DEFAULT_UNIFIED_SETTINGS.threadDetailsOpenByDefault, effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay, mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, language: DEFAULT_UNIFIED_SETTINGS.language, @@ -711,6 +718,7 @@ export function useSettingsRestore(onRestored?: () => void) { proactivePanelsEnabled: DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled, showSkillsInSlashMenu: DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu, composerRichTextEnabled: DEFAULT_UNIFIED_SETTINGS.composerRichTextEnabled, + composerVimMode: DEFAULT_UNIFIED_SETTINGS.composerVimMode, sendShortcut: DEFAULT_UNIFIED_SETTINGS.sendShortcut, followUpBehavior: DEFAULT_UNIFIED_SETTINGS.followUpBehavior, sideThreadOpenTarget: DEFAULT_UNIFIED_SETTINGS.sideThreadOpenTarget, @@ -1258,6 +1266,27 @@ export function ChatSettingsPanel() { /> } /> + + updateSettings({ composerVimMode: DEFAULT_UNIFIED_SETTINGS.composerVimMode }) + } + /> + ) : null + } + control={ + updateSettings({ composerVimMode: Boolean(checked) })} + aria-label={gt("Vim mode")} + /> + } + /> ; + /** Picked by `move-to-machine::`. */ + readonly machineMoveTargets?: ReadonlyArray<{ + readonly label: string; + readonly projects: ReadonlyArray<{ readonly title: string }>; + }>; } /** Local navigation, read markers, and copying remain available to read-only clients. */ @@ -141,6 +151,17 @@ export function threadActionRequiresOperate(action: ThreadActionMenuId): boolean ].includes(action); } +/** The machine and project a `move-to-machine::` pick names, by position. */ +export function parseMachineMovePick }>( + id: string, + targets: ReadonlyArray, +): { readonly machine: M; readonly project: M["projects"][number] } | null { + const match = /^move-to-machine:(\d+):(\d+)$/.exec(id); + const machine = match ? targets[Number(match[1])] : undefined; + const project = match ? machine?.projects[Number(match[2])] : undefined; + return machine && project !== undefined ? { machine, project } : null; +} + export function buildThreadActionMenuItems( state: ThreadActionMenuState, resolve: MessageResolver = m, @@ -244,6 +265,38 @@ export function buildThreadActionMenuItems( }, ] : []), + ...(state.moveTargets && state.moveTargets.length > 0 + ? [ + { + id: "move-to-project" as const, + label: resolve(msg("Move to project")), + icon: "folder-input", + disabled: state.isRunning, + children: state.moveTargets.map((project) => ({ + id: `move-to-project:${project.id}` as const, + label: project.title, + })), + }, + ] + : []), + ...(state.machineMoveTargets && state.machineMoveTargets.length > 0 + ? [ + { + id: "move-to-machine" as const, + label: resolve(msg("Move to machine")), + icon: "server", + disabled: state.isRunning, + children: state.machineMoveTargets.map((machine, machineIndex) => ({ + id: `move-to-machine:${machineIndex}` as const, + label: machine.label, + children: machine.projects.map((project, projectIndex) => ({ + id: `move-to-machine:${machineIndex}:${projectIndex}` as const, + label: project.title, + })), + })), + }, + ] + : []), ...(state.supports.autoSettleOptOut ? [ { diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index 326b592e823db..2dd7500d4666f 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -106,6 +106,7 @@ import { saveUsagePagePreferences, type UsagePagePreferences, } from "./usagePagePreferences"; +import { registerCommandRunner } from "../../shortcuts/dispatcher"; function isUsageMetric(value: string | null | undefined): value is UsageMetric { return METRIC_OPTIONS.some((option) => option.value === value); @@ -271,6 +272,14 @@ export function UsagePage() { setLimitsNow(Date.now()); if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause); }); + const runUsageCommand = useEffectEvent((command: string | null) => { + const metricOption = METRIC_OPTIONS.find((option) => option.command === command); + const periodOption = WINDOW_OPTIONS.find((option) => option.command === command); + if (!metricOption && !periodOption) return false; + if (metricOption) selectMetric(metricOption.value); + if (periodOption && !showingLimits) selectWindow(periodOption.days); + return true; + }); const onUsageKeyDown = useEffectEvent((event: KeyboardEvent) => { if ( event.defaultPrevented || @@ -281,21 +290,21 @@ export function UsagePage() { ) return; - const command = resolveUsageShortcut(event, keybindings); - const metricOption = METRIC_OPTIONS.find((option) => option.command === command); - const periodOption = WINDOW_OPTIONS.find((option) => option.command === command); - if (!metricOption && !periodOption) return; - + if (!runUsageCommand(resolveUsageShortcut(event, keybindings))) return; event.preventDefault(); event.stopPropagation(); - if (metricOption) selectMetric(metricOption.value); - if (periodOption && !showingLimits) selectWindow(periodOption.days); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window capture keydown listener for usage metric and period shortcuts useEffect(() => { globalThis.window.addEventListener("keydown", onUsageKeyDown, true); - return () => globalThis.window.removeEventListener("keydown", onUsageKeyDown, true); + const unregisterRunner = registerCommandRunner( + (command) => !isCommandPaletteOpen() && runUsageCommand(command), + ); + return () => { + globalThis.window.removeEventListener("keydown", onUsageKeyDown, true); + unregisterRunner(); + }; }, []); const refreshWindow = () => { diff --git a/apps/web/src/composer-vim-editor.ts b/apps/web/src/composer-vim-editor.ts new file mode 100644 index 0000000000000..bc2a24cff7ff7 --- /dev/null +++ b/apps/web/src/composer-vim-editor.ts @@ -0,0 +1,244 @@ +import { Extension } from "@tiptap/core"; +import { closeHistory, redo, undo } from "@tiptap/pm/history"; +import { type EditorState, Plugin, PluginKey, Selection } from "@tiptap/pm/state"; +import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view"; + +import { + flatToPm, + pmToFlat, + type RichDocMap, + serializeEditorDoc, + serializeSelection, +} from "~/composer-rich-text-doc"; +import { + clampNormalCursor, + registerText, + VIM_CHIP, + type VimMode, + type VimOutcome, + type VimState, + vimEscape, + vimNormalKey, +} from "~/composer-vim"; + +const vimPluginKey = new PluginKey("composer-vim"); +const CURSOR_CLASS = "composer-vim-cursor"; + +/** The vim mode the editor shows, or null when vim mode is off. */ +export function composerVimMode(state: EditorState): VimMode | null { + return vimPluginKey.getState(state) ?? null; +} + +export function showComposerVimMode(view: EditorView, mode: VimMode | null): void { + if (composerVimMode(view.state) !== mode) + view.dispatch(view.state.tr.setMeta(vimPluginKey, mode)); +} + +function emptyLineCursor(): HTMLElement { + const cursor = document.createElement("span"); + cursor.className = `${CURSOR_CLASS} composer-vim-cursor-empty`; + cursor.textContent = "\u00a0"; + return cursor; +} + +/** Normal mode covers the character after the caret, or a placeholder cell at a line end. */ +function blockCursor(state: EditorState): DecorationSet | null { + const { selection } = state; + if (!selection.empty) return null; + const { $head } = selection; + const next = $head.nodeAfter; + const decoration = + next?.isText && next.text?.[0] !== "\n" + ? Decoration.inline($head.pos, $head.pos + 1, { class: CURSOR_CLASS }) + : next?.isInline && !next.isText && next.type.name !== "hardBreak" + ? Decoration.node($head.pos, $head.pos + next.nodeSize, { class: CURSOR_CLASS }) + : Decoration.widget($head.pos, emptyLineCursor, { key: CURSOR_CLASS, side: 1 }); + return DecorationSet.create(state.doc, [decoration]); +} + +export const ComposerVimExtension = Extension.create({ + name: "composer-vim", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: vimPluginKey, + state: { + init: () => null, + apply: (tr, mode) => { + const next = tr.getMeta(vimPluginKey) as VimMode | null | undefined; + return next === undefined ? mode : next; + }, + }, + props: { + attributes: (state): Record => { + const mode = vimPluginKey.getState(state); + return mode ? { "data-vim-mode": mode } : {}; + }, + decorations: (state) => + vimPluginKey.getState(state) === "normal" ? blockCursor(state) : null, + }, + }), + ]; + }, +}); + +// The engine's text: one character per document position, so offsets are flat offsets. +const flatTexts = new WeakMap(); + +function flatText(map: RichDocMap): string { + let text = flatTexts.get(map); + if (text === undefined) { + text = map.runs + .map((run) => { + if (run.kind === "token") return VIM_CHIP; + if (run.kind === "break") return "\n"; + if (run.kind === "prefix") return ""; + const start = run.mdStart + run.openLen; + return map.value.slice(start, start + run.docLen); + }) + .join(""); + flatTexts.set(map, text); + } + return text; +} + +export interface ComposerVimContext { + readonly state: { current: VimState }; + readonly onModeChange: (mode: VimMode) => void; + /** The composer's own Enter and Escape handling: sending, menus and suggestions. */ + readonly commandKey: (key: "Enter" | "Escape", event: KeyboardEvent) => boolean; + /** Starts a new line at the selection the way a non-sending Enter does. */ + readonly insertNewline: (view: EditorView) => void; + /** Inserts Markdown at the selection the way a paste does. */ + readonly insertMarkdown: (view: EditorView, markdown: string) => void; +} + +function consume(event: KeyboardEvent): void { + event.preventDefault(); + event.stopPropagation(); +} + +function engineKey(event: KeyboardEvent): string | null { + if (event.metaKey) return null; + if (event.ctrlKey) return !event.altKey && event.key.toLowerCase() === "r" ? "" : null; + if (event.key === "Backspace") return ""; + if (event.key === "Delete") return ""; + return event.key.length === 1 ? event.key : null; +} + +function selectFlat(view: EditorView, offset: number) { + const map = serializeEditorDoc(view.state.doc); + return view.state.tr.setSelection(Selection.near(view.state.doc.resolve(flatToPm(map, offset)))); +} + +function placeCursor(view: EditorView, offset: number, mode: VimMode): void { + const target = + mode === "normal" + ? clampNormalCursor(flatText(serializeEditorDoc(view.state.doc)), offset) + : offset; + const tr = selectFlat(view, target); + // Same transaction as the move, so change handlers already see the new mode. + if (composerVimMode(view.state) !== mode) tr.setMeta(vimPluginKey, mode); + view.dispatch(tr.scrollIntoView()); +} + +function applyOutcome(view: EditorView, outcome: VimOutcome, context: ComposerVimContext): void { + let state = outcome.state; + if (outcome.yank && state.register) { + const map = serializeEditorDoc(view.state.doc); + const source = serializeSelection( + view.state.doc, + flatToPm(map, outcome.yank.from), + flatToPm(map, outcome.yank.to), + ); + state = { ...state, register: { ...state.register, source } }; + } + context.state.current = state; + if (state.pending.length > 0) return; + if (outcome.history) { + (outcome.history === "undo" ? undo : redo)(view.state, (tr) => view.dispatch(tr)); + const map = serializeEditorDoc(view.state.doc); + placeCursor(view, pmToFlat(map, view.state.selection.head), "normal"); + return; + } + // Each command is its own undo step, even when typed within the grouping delay. + if (outcome.steps.length > 0) view.dispatch(closeHistory(view.state.tr)); + for (const step of outcome.steps) { + if (step.type === "replace") { + const map = serializeEditorDoc(view.state.doc); + const from = flatToPm(map, step.from); + const to = flatToPm(map, step.to); + view.dispatch( + step.text ? view.state.tr.insertText(step.text, from, to) : view.state.tr.delete(from, to), + ); + continue; + } + view.dispatch(selectFlat(view, step.at)); + if (step.type === "newline") { + context.insertNewline(view); + } else if (state.register) { + const { register } = state; + context.insertMarkdown( + view, + registerText(register, register.source ?? register.text, step.count), + ); + } + } + placeCursor(view, outcome.cursor, state.mode); + if (state.mode === "insert") context.onModeChange("insert"); +} + +/** Returns true when vim handled the key. Normal mode swallows every key that would type text. */ +export function handleComposerVimKeyDown( + view: EditorView, + event: KeyboardEvent, + context: ComposerVimContext, +): boolean { + if (event.isComposing || event.keyCode === 229 || event.target !== view.dom) return false; + const vim = context.state; + if (vim.current.mode === "insert") { + if ( + event.key !== "Escape" || + event.shiftKey || + event.altKey || + event.metaKey || + event.ctrlKey + ) { + return false; + } + consume(event); + // An open menu or suggestion closes first, like it does without vim. + if (context.commandKey("Escape", event)) return true; + const map = serializeEditorDoc(view.state.doc); + const next = vimEscape(vim.current, flatText(map), pmToFlat(map, view.state.selection.head)); + vim.current = next.state; + placeCursor(view, next.cursor, "normal"); + context.onModeChange("normal"); + return true; + } + if (event.key === "Escape") { + // Without a pending command, Escape keeps its usual meaning. + if (vim.current.pending.length === 0) return false; + vim.current = { ...vim.current, pending: [] }; + consume(event); + return true; + } + if (event.key === "Enter") { + vim.current = { ...vim.current, pending: [] }; + context.commandKey("Enter", event); + consume(event); + return true; + } + const key = engineKey(event); + if (key === null) return false; + consume(event); + const map = serializeEditorDoc(view.state.doc); + const outcome = vimNormalKey( + vim.current, + key, + flatText(map), + pmToFlat(map, view.state.selection.head), + ); + applyOutcome(view, outcome, context); + return true; +} diff --git a/apps/web/src/composer-vim.test.ts b/apps/web/src/composer-vim.test.ts new file mode 100644 index 0000000000000..c8ec24772185b --- /dev/null +++ b/apps/web/src/composer-vim.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + applyVimSteps, + INITIAL_VIM_STATE, + type VimState, + vimEscape, + vimNormalKey, +} from "./composer-vim"; + +/** Runs keys from normal mode on `start`, where `|` marks the cursor; insert mode types text. */ +function vim(start: string, keys: string, initial: Partial = {}) { + let text = start.replace("|", ""); + let cursor = start.indexOf("|"); + let state: VimState = { ...INITIAL_VIM_STATE, mode: "normal", ...initial }; + for (const key of keys.match(/<[^>]+>|[\s\S]/gu) ?? []) { + if (state.mode === "insert") { + if (key === "") { + ({ state, cursor } = vimEscape(state, text, cursor)); + continue; + } + const typed = key === "" ? "\n" : key; + text = text.slice(0, cursor) + typed + text.slice(cursor); + cursor += typed.length; + continue; + } + const outcome = vimNormalKey(state, key, text, cursor); + text = applyVimSteps(text, outcome.steps, outcome.state.register); + state = outcome.state; + cursor = outcome.cursor; + } + return `${text.slice(0, cursor)}|${text.slice(cursor)}`; +} + +describe("vim motions", () => { + it.each([ + ["|foo bar baz", "w", "foo |bar baz"], + ["|foo bar baz", "2w", "foo bar |baz"], + ["|foo.bar baz", "w", "foo|.bar baz"], + ["|foo.bar baz", "W", "foo.bar |baz"], + ["|foo\n\nbar", "w", "foo\n|\nbar"], + ["|a  b", "w", "a | b"], + ["|a  b", "ww", "a  |b"], + ["|a  b", "ww", "a | b"], + ["foo bar |baz", "b", "foo |bar baz"], + ["foo.bar |baz", "B", "|foo.bar baz"], + ["foo\n|bar", "b", "|foo\nbar"], + ["|foo bar", "e", "fo|o bar"], + ["fo|o bar", "e", "foo ba|r"], + ["|foo.bar", "E", "foo.ba|r"], + ["foo b|ar", "0", "|foo bar"], + [" fo|o", "^", " |foo"], + ["|foo bar", "$", "foo ba|r"], + ["a|b", "l", "a|b"], + ["a\n|b", "h", "a\n|b"], + ["|ab", " ", "a|b"], + ["a|b", "", "|ab"], + ["|abc\nde", "j", "abc\n|de"], + ["ab|c\nde", "j", "abc\nd|e"], + ["ab|c\nd\nxyz", "jj", "abc\nd\nxy|z"], + ["|ab\nwxyz", "$j", "ab\nwxy|z"], + ["ab\n|c", "k", "|ab\nc"], + ["|ab", "j", "|ab"], + ["a\nb\n|c", "gg", "|a\nb\nc"], + ["|a\n b\nc", "2G", "a\n |b\nc"], + ["|a\nb\nc", "G", "a\nb\n|c"], + ["|a-b-c", "f-", "a|-b-c"], + ["|a-b-c", "2f-", "a-b|-c"], + ["|a-b-c", "f-;", "a-b|-c"], + ["|a-b-c", "f-;,", "a|-b-c"], + ["|a-b-c", "t-;", "a-|b-c"], + ["a-b-|c", "F-", "a-b|-c"], + ["a-b-|c", "T-", "a-b-|c"], + ["|a\n-", "f-", "|a\n-"], + ])("%j %j -> %j", (start, keys, expected) => { + expect(vim(start, keys)).toBe(expected); + }); +}); + +describe("vim edits", () => { + it.each([ + ["|foo bar", "x", "|oo bar"], + ["fo|o", "x", "f|o"], + ["|foo", "3x", "|"], + ["foo |bar", "X", "foo|bar"], + ["|foo bar baz", "dw", "|bar baz"], + ["|foo bar baz", "d2w", "|baz"], + ["|foo bar baz", "2dw", "|baz"], + ["foo |bar\nbaz", "dw", "foo| \nbaz"], + ["foo |bar baz", "db", "|bar baz"], + ["| b", "dw", "| b"], + ["|foo bar", "de", "| bar"], + ["|foo bar", "cwxy", "x|y bar"], + ["foo |bar", "D", "foo| "], + ["foo |bar", "Cqux", "foo qu|x"], + ["|abc", "sx", "|xbc"], + ["a\n|b\nc", "dd", "a\n|c"], + ["a\nb\n|c", "dd", "a\n|b"], + ["|a\nb\nc", "2dd", "|c"], + [" a\n|b", "dd", " |a"], + ["a\n|b\nc", "dj", "|a"], + ["a\n|b\nc", "ccx", "a\n|x\nc"], + ["a\n|b\nc", "Sx", "a\n|x\nc"], + ["a b|c d", "f d0", "| d"], + ["a\n|b\nc", "yyp", "a\nb\n|b\nc"], + ["a\n|b\nc", "yyP", "a\n|b\nb\nc"], + ["a\n|b", "Yp", "a\nb\n|b"], + ["|a", "ddp", "\n|a"], + ["|ab", "ylp", "a|ab"], + ["|ab", "yl2p", "aa|ab"], + ["|ab", "xp", "b|a"], + ["|foo bar", "dwP", "foo| bar"], + ["|foo bar", "yiwP", "fo|ofoo bar"], + ["a|b\ncd", "J", "ab| cd"], + ["a\n b", "J", "a| b"], + ["a \nb", "J", "a |b"], + ["|a\nb\nc", "3J", "a b| c"], + ["|abc", "rx", "|xbc"], + ["|abc", "2rx", "x|xc"], + ["|abc", "5rx", "|abc"], + ["|ab", "ix", "|xab"], + ["|ab", "ax", "a|xb"], + [" a|b", "Ix", " |xab"], + ["|ab", "Ax", "ab|x"], + ["|a\nb", "ox", "a\n|x\nb"], + ["a\n|b", "Ox", "a\n|x\nb"], + ])("%j %j -> %j", (start, keys, expected) => { + expect(vim(start, keys)).toBe(expected); + }); +}); + +describe("vim text objects", () => { + it.each([ + ["foo |bar baz", "diw", "foo | baz"], + ["foo |bar baz", "daw", "foo |baz"], + ["foo |baz", "daw", "fo|o"], + ["foo.b|ar baz", "diW", "| baz"], + ["a | b", "diw", "a | b"], + ['say "hi |there" ok', 'di"', 'say "|" ok'], + ['say "hi |there" ok', 'da"', "say |ok"], + ['|say "hi"', 'ci"x', 'say "|x"'], + ["it's 'a|b'", "di'", "it's 'a|b'"], + ["x 'a|b' y", "di'", "x '|' y"], + ["foo(|a, (b))", "di(", "foo(|)"], + ["foo(a, (|b))", "di(", "foo(a, (|))"], + ["foo(a, (b)|)", "dib", "foo(|)"], + ["foo(|a)", "da(", "fo|o"], + ["foo(|a)", "ci)x", "foo(|x)"], + ["[a, |b]", "di[", "[|]"], + ["{\n |a\n}", "di{", "{\n|\n}"], + ["{|a}", "daB", "|"], + ["|none", "di(", "|none"], + ])("%j %j -> %j", (start, keys, expected) => { + expect(vim(start, keys)).toBe(expected); + }); +}); + +describe("vim repeat", () => { + it.each([ + ["|a b c", "dw.", "|c"], + ["|abcdef", "2x.", "|ef"], + ["|foo foo", "cwbarw.", "bar ba|r"], + ["|a\nb", "ocj.", "a\nc\nb\n|c"], + ["|a\nb", "Axyj.", "ax\ny\nbx\n|y"], + ["|abc", ".", "|abc"], + ["|ab cd", "yw.", "|ab cd"], + ])("%j %j -> %j", (start, keys, expected) => { + expect(vim(start, keys)).toBe(expected); + }); +}); + +describe("vim state", () => { + it("waits for the rest of a command", () => { + const outcome = vimNormalKey({ ...INITIAL_VIM_STATE, mode: "normal" }, "d", "abc", 0); + expect(outcome.state.pending).toEqual(["d"]); + expect(outcome.steps).toEqual([]); + }); + + it("reports the yanked range so the editor can keep its Markdown", () => { + const outcome = vimNormalKey( + { ...INITIAL_VIM_STATE, mode: "normal", pending: ["d"] }, + "d", + "a\n b\nc", + 2, + ); + expect(outcome.yank).toEqual({ from: 2, to: 5 }); + expect(outcome.state.register).toEqual({ text: " b", linewise: true }); + }); + + it("steps back onto the last typed character when leaving insert mode", () => { + expect(vimEscape(INITIAL_VIM_STATE, "ab\ncd", 3)).toMatchObject({ + state: { mode: "normal" }, + cursor: 3, + }); + expect(vimEscape(INITIAL_VIM_STATE, "ab", 2).cursor).toBe(1); + }); + + it("swallows unknown keys", () => { + const outcome = vimNormalKey({ ...INITIAL_VIM_STATE, mode: "normal" }, "Q", "abc", 1); + expect(outcome).toMatchObject({ steps: [], cursor: 1, state: { pending: [] } }); + }); +}); diff --git a/apps/web/src/composer-vim.ts b/apps/web/src/composer-vim.ts new file mode 100644 index 0000000000000..fd12b09e2bc5c --- /dev/null +++ b/apps/web/src/composer-vim.ts @@ -0,0 +1,881 @@ +/** + * Vim keys for the composer over plain text: lines end with "\n" and a chip is + * one character. Pure; the editor applies the returned steps to its document. + */ + +export type VimMode = "insert" | "normal"; + +export const VIM_CHIP = "\uFFFC"; + +type Operator = "d" | "c" | "y"; +type FindKind = "f" | "F" | "t" | "T"; + +export interface VimRegister { + readonly text: string; + readonly linewise: boolean; + /** Markdown for `text`, so a put restores chips and formatting. */ + readonly source?: string; +} + +export interface VimState { + readonly mode: VimMode; + readonly pending: ReadonlyArray; + readonly register: VimRegister | null; + readonly lastFind: { readonly kind: FindKind; readonly char: string } | null; + readonly lastChange: { readonly keys: ReadonlyArray; readonly inserted: string } | null; + /** The command that entered insert mode and the text it left, completed into `lastChange` on Escape. */ + readonly insert: { readonly keys: ReadonlyArray; readonly baseline: string } | null; + /** Column kept across `j` and `k`; Infinity after `$`. */ + readonly column: number | null; +} + +export const INITIAL_VIM_STATE: VimState = { + mode: "insert", + pending: [], + register: null, + lastFind: null, + lastChange: null, + insert: null, + column: null, +}; + +/** Offsets refer to the text left by the previous step. Replace text never contains "\n". */ +export type VimStep = + | { readonly type: "replace"; readonly from: number; readonly to: number; readonly text: string } + | { readonly type: "newline"; readonly at: number } + | { readonly type: "put"; readonly at: number; readonly count: number }; + +export interface VimOutcome { + readonly state: VimState; + readonly steps: ReadonlyArray; + /** Cursor in the text after the steps. */ + readonly cursor: number; + /** Range of the text before the steps that the register now holds. */ + readonly yank?: { readonly from: number; readonly to: number }; + readonly history?: "undo" | "redo"; +} + +type Motion = { readonly key: string; readonly char?: string }; +type Target = Motion | { readonly object: string } | "line"; +type Command = + | { + readonly kind: "motion"; + readonly motion: Motion; + readonly count: number; + readonly counted: boolean; + } + | { + readonly kind: "operator"; + readonly op: Operator; + readonly target: Target; + readonly count: number; + readonly counted: boolean; + } + | { + readonly kind: "action"; + readonly key: string; + readonly char?: string; + readonly count: number; + }; + +const MOTION_KEYS = new Set([ + "h", + "j", + "k", + "l", + "w", + "W", + "b", + "B", + "e", + "E", + "0", + "^", + "$", + "G", + ";", + ",", +]); +const MOTION_ALIASES: Record = { " ": "l", "": "h" }; +const FIND_KEYS = new Set(["f", "F", "t", "T"]); +const OBJECT_KEYS: Record = { + w: "w", + W: "W", + '"': '"', + "'": "'", + "`": "`", + "(": "(", + ")": "(", + b: "(", + "[": "[", + "]": "[", + "{": "{", + "}": "{", + B: "{", +}; +// Shorthands for an operator and a target. +const SHORTHANDS: Record = { + x: { op: "d", target: { key: "l" } }, + "": { op: "d", target: { key: "l" } }, + X: { op: "d", target: { key: "h" } }, + s: { op: "c", target: { key: "l" } }, + S: { op: "c", target: "line" }, + D: { op: "d", target: { key: "$" } }, + C: { op: "c", target: { key: "$" } }, + Y: { op: "y", target: "line" }, +}; +const ACTION_KEYS = new Set(["i", "a", "I", "A", "o", "O", "p", "P", "J", "u", "", "."]); + +function isSingleChar(key: string | undefined): key is string { + return key !== undefined && key.length === 1; +} + +function parseCommand(keys: ReadonlyArray): Command | "incomplete" | "invalid" { + let index = 0; + const readCount = () => { + let digits = ""; + while (index < keys.length && /^[0-9]$/.test(keys[index]!) && (digits || keys[index] !== "0")) { + digits += keys[index++]; + } + return digits ? Number(digits) : null; + }; + // A motion, or "incomplete" while it waits for its character. + const readMotion = (): Motion | "incomplete" | "invalid" => { + if (index >= keys.length) return "incomplete"; + const raw = keys[index++]!; + const key = MOTION_ALIASES[raw] ?? raw; + if (MOTION_KEYS.has(key)) return { key }; + if (FIND_KEYS.has(key)) { + if (index >= keys.length) return "incomplete"; + const char = keys[index++]; + return isSingleChar(char) ? { key, char } : "invalid"; + } + if (key === "g") { + if (index >= keys.length) return "incomplete"; + return keys[index++] === "g" ? { key: "gg" } : "invalid"; + } + return "invalid"; + }; + + const firstCount = readCount(); + if (index >= keys.length) return "incomplete"; + const key = keys[index]!; + const shorthand = SHORTHANDS[key]; + if (shorthand) { + return { + kind: "operator", + ...shorthand, + count: firstCount ?? 1, + counted: firstCount !== null, + }; + } + if (key === "d" || key === "c" || key === "y") { + index += 1; + const secondCount = readCount(); + const count = (firstCount ?? 1) * (secondCount ?? 1); + const counted = firstCount !== null || secondCount !== null; + if (index >= keys.length) return "incomplete"; + const next = keys[index]!; + if (next === key) return { kind: "operator", op: key, target: "line", count, counted }; + if (next === "i" || next === "a") { + index += 1; + if (index >= keys.length) return "incomplete"; + const object = OBJECT_KEYS[keys[index]!]; + return object + ? { kind: "operator", op: key, target: { object: next + object }, count, counted } + : "invalid"; + } + const motion = readMotion(); + if (typeof motion === "string") return motion; + return { kind: "operator", op: key, target: motion, count, counted }; + } + if (key === "r") { + if (index + 1 >= keys.length) return "incomplete"; + const char = keys[index + 1]; + return isSingleChar(char) ? { kind: "action", key, char, count: firstCount ?? 1 } : "invalid"; + } + if (ACTION_KEYS.has(key)) return { kind: "action", key, count: firstCount ?? 1 }; + const motion = readMotion(); + if (typeof motion === "string") return motion; + return { kind: "motion", motion, count: firstCount ?? 1, counted: firstCount !== null }; +} + +function lineStart(text: string, position: number): number { + return position <= 0 ? 0 : text.lastIndexOf("\n", position - 1) + 1; +} + +function lineEnd(text: string, position: number): number { + const end = text.indexOf("\n", position); + return end === -1 ? text.length : end; +} + +function isBlank(char: string | undefined): boolean { + return char !== undefined && /\s/.test(char); +} + +function firstNonBlank(text: string, position: number): number { + const end = lineEnd(text, position); + let index = lineStart(text, position); + while (index < end && isBlank(text[index])) index += 1; + return index; +} + +/** Normal mode rests on a character, never after the last one in a line. */ +export function clampNormalCursor(text: string, position: number): number { + const bounded = Math.max(0, Math.min(position, text.length)); + const start = lineStart(text, bounded); + const end = lineEnd(text, bounded); + return end > start && bounded >= end ? end - 1 : bounded; +} + +/** 0 blank, 1 word, 2 punctuation, 3 chip. A WORD is any run of non-blanks. */ +function charClass(char: string | undefined, big: boolean): number { + if (char === undefined || isBlank(char)) return 0; + if (big) return 1; + if (char === VIM_CHIP) return 3; + return /[\p{L}\p{N}_]/u.test(char) ? 1 : 2; +} + +/** Whether `char` continues a run of `kind`; every chip is a word of its own. */ +function joins(kind: number, char: string | undefined, big: boolean): boolean { + return kind !== 3 && charClass(char, big) === kind; +} + +function nextWordStart(text: string, position: number, big: boolean): number { + let index = position; + const kind = charClass(text[index], big); + if (kind !== 0) { + index += 1; + while (index < text.length && joins(kind, text[index], big)) index += 1; + } + while (index < text.length && isBlank(text[index])) { + index += 1; + // An empty line counts as a word. + if (text[index] === "\n" && text[index - 1] === "\n") return index; + } + return index; +} + +function previousWordStart(text: string, position: number, big: boolean): number { + if (position <= 0) return 0; + let index = position - 1; + while (index > 0 && isBlank(text[index])) { + if (text[index] === "\n" && text[index - 1] === "\n") return index; + index -= 1; + } + const kind = charClass(text[index], big); + if (kind !== 0) while (index > 0 && joins(kind, text[index - 1], big)) index -= 1; + return index; +} + +function wordEnd(text: string, position: number, big: boolean): number { + let index = position + 1; + while (index < text.length && isBlank(text[index])) index += 1; + if (index >= text.length) return Math.max(position, text.length - 1); + const kind = charClass(text[index], big); + while (index + 1 < text.length && joins(kind, text[index + 1], big)) index += 1; + return index; +} + +function findInLine( + text: string, + cursor: number, + kind: FindKind, + char: string, + count: number, + repeat: boolean, +): number | null { + if (kind === "f" || kind === "t") { + const end = lineEnd(text, cursor); + // Repeating `t` from just before a match would find that match again. + let index = cursor + (kind === "t" && repeat ? 1 : 0); + for (let step = 0; step < count; step += 1) { + index = text.indexOf(char, index + 1); + if (index === -1 || index >= end) return null; + } + return kind === "f" ? index : index - 1; + } + const start = lineStart(text, cursor); + let index = cursor - (kind === "T" && repeat ? 1 : 0); + for (let step = 0; step < count; step += 1) { + if (index - 1 < start) return null; + index = text.lastIndexOf(char, index - 1); + if (index < start) return null; + } + return kind === "F" ? index : index + 1; +} + +const REVERSED_FIND: Record = { f: "F", F: "f", t: "T", T: "t" }; + +type MotionResult = { + position: number; + type: "exclusive" | "inclusive" | "linewise"; + column?: number; + lastFind?: VimState["lastFind"]; +}; + +function lineIndexStart(text: string, line: number): number { + let start = 0; + for (let index = 0; index < line; index += 1) { + const end = text.indexOf("\n", start); + if (end === -1) return start; + start = end + 1; + } + return start; +} + +function motionTarget( + state: VimState, + text: string, + cursor: number, + motion: Motion, + count: number, + counted: boolean, +): MotionResult | null { + const start = lineStart(text, cursor); + const end = lineEnd(text, cursor); + const repeatWord = (step: (position: number) => number) => { + let position = cursor; + for (let index = 0; index < count; index += 1) position = step(position); + return position; + }; + switch (motion.key) { + case "h": + return { position: Math.max(start, cursor - count), type: "exclusive" }; + case "l": + return { position: Math.min(end, cursor + count), type: "exclusive" }; + case "0": + return { position: start, type: "exclusive" }; + case "^": + return { position: firstNonBlank(text, cursor), type: "exclusive" }; + case "$": { + let lineEndPosition = end; + for (let index = 1; index < count && lineEndPosition < text.length; index += 1) { + lineEndPosition = lineEnd(text, lineEndPosition + 1); + } + return { position: lineEndPosition, type: "exclusive", column: Infinity }; + } + case "w": + case "W": + return { + position: repeatWord((position) => nextWordStart(text, position, motion.key === "W")), + type: "exclusive", + }; + case "b": + case "B": + return { + position: repeatWord((position) => previousWordStart(text, position, motion.key === "B")), + type: "exclusive", + }; + case "e": + case "E": + return { + position: repeatWord((position) => wordEnd(text, position, motion.key === "E")), + type: "inclusive", + }; + case "j": + case "k": { + const column = state.column ?? cursor - start; + let targetStart = start; + let moved = 0; + for (; moved < count; moved += 1) { + if (motion.key === "j") { + const targetEnd = lineEnd(text, targetStart); + if (targetEnd >= text.length) break; + targetStart = targetEnd + 1; + } else { + if (targetStart === 0) break; + targetStart = lineStart(text, targetStart - 1); + } + } + if (moved === 0) return null; + const targetEnd = lineEnd(text, targetStart); + return { + position: Math.min(targetStart + column, Math.max(targetStart, targetEnd - 1)), + type: "linewise", + column, + }; + } + case "G": + case "gg": { + const lines = text.split("\n").length; + const line = counted ? Math.min(count, lines) - 1 : motion.key === "G" ? lines - 1 : 0; + return { position: firstNonBlank(text, lineIndexStart(text, line)), type: "linewise" }; + } + case ";": + case ",": { + const last = state.lastFind; + if (!last) return null; + const kind = motion.key === ";" ? last.kind : REVERSED_FIND[last.kind]; + const position = findInLine(text, cursor, kind, last.char, count, true); + if (position === null) return null; + return { position, type: kind === "f" || kind === "t" ? "inclusive" : "exclusive" }; + } + default: { + const kind = motion.key as FindKind; + const char = motion.char!; + const position = findInLine(text, cursor, kind, char, count, false); + if (position === null) return null; + return { + position, + type: kind === "f" || kind === "t" ? "inclusive" : "exclusive", + lastFind: { kind, char }, + }; + } + } +} + +function wordObject(text: string, cursor: number, around: boolean, big: boolean) { + const start = lineStart(text, cursor); + const end = lineEnd(text, cursor); + if (start === end) return null; + const position = Math.min(cursor, end - 1); + const kind = charClass(text[position], big); + let from = position; + let to = position + 1; + while (from > start && joins(kind, text[from - 1], big)) from -= 1; + while (to < end && joins(kind, text[to], big)) to += 1; + if (!around) return { from, to }; + if (kind === 0) { + const next = charClass(text[to], big); + if (to < end && next !== 0) { + to += 1; + while (to < end && joins(next, text[to], big)) to += 1; + } + } else if (to < end && isBlank(text[to])) { + while (to < end && isBlank(text[to])) to += 1; + } else { + while (from > start && isBlank(text[from - 1])) from -= 1; + } + return { from, to }; +} + +function quoteObject(text: string, cursor: number, quote: string, around: boolean) { + const start = lineStart(text, cursor); + const end = lineEnd(text, cursor); + const quotes: number[] = []; + for (let index = start; index < end; index += 1) { + if (text[index] === quote && text[index - 1] !== "\\") quotes.push(index); + } + // Quotes pair up from the start of the line. + for (let index = 0; index + 1 < quotes.length; index += 2) { + const open = quotes[index]!; + const close = quotes[index + 1]!; + if (cursor > close) continue; + if (!around) return { from: open + 1, to: close }; + let from = open; + let to = close + 1; + if (to < end && isBlank(text[to])) { + while (to < end && isBlank(text[to])) to += 1; + } else { + while (from > start && isBlank(text[from - 1])) from -= 1; + } + return { from, to }; + } + return null; +} + +const BRACKET_CLOSE: Record = { "(": ")", "[": "]", "{": "}" }; + +function bracketObject(text: string, cursor: number, open: string, around: boolean) { + const close = BRACKET_CLOSE[open]!; + let from = -1; + let depth = 0; + for (let index = text[cursor] === close ? cursor - 1 : cursor; index >= 0; index -= 1) { + const char = text[index]; + if (char === close) depth += 1; + else if (char === open) { + if (depth === 0) { + from = index; + break; + } + depth -= 1; + } + } + if (from === -1) return null; + let to = -1; + depth = 0; + for (let index = from + 1; index < text.length; index += 1) { + const char = text[index]; + if (char === open) depth += 1; + else if (char === close) { + if (depth === 0) { + to = index; + break; + } + depth -= 1; + } + } + if (to === -1) return null; + if (around) return { from, to: to + 1 }; + let innerFrom = from + 1; + let innerTo = to; + // A block that opens and closes on its own lines keeps those lines. + if (text[innerFrom] === "\n") innerFrom += 1; + const lastBreak = text.lastIndexOf("\n", innerTo - 1); + if (lastBreak >= innerFrom && /^\s*$/.test(text.slice(lastBreak, innerTo))) innerTo = lastBreak; + return { from: innerFrom, to: Math.max(innerFrom, innerTo) }; +} + +function textObject(text: string, cursor: number, object: string) { + const around = object[0] === "a"; + const kind = object.slice(1); + if (kind === "w" || kind === "W") return wordObject(text, cursor, around, kind === "W"); + if (kind === '"' || kind === "'" || kind === "`") return quoteObject(text, cursor, kind, around); + return bracketObject(text, cursor, kind, around); +} + +/** End (inclusive) of `cw`, which changes to the end of the word under the cursor. */ +function changeWordEnd(text: string, cursor: number, count: number, big: boolean): number { + const kind = charClass(text[cursor], big); + let end = cursor; + while (end + 1 < text.length && joins(kind, text[end + 1], big)) end += 1; + for (let index = 1; index < count; index += 1) end = wordEnd(text, end, big); + return end; +} + +export function registerText(register: Pick, text: string, count: number) { + return Array.from({ length: count }, () => text).join(register.linewise ? "\n" : ""); +} + +export function applyVimSteps( + text: string, + steps: ReadonlyArray, + register: VimRegister | null, +): string { + let next = text; + for (const step of steps) { + if (step.type === "replace") { + next = next.slice(0, step.from) + step.text + next.slice(step.to); + } else if (step.type === "newline") { + next = `${next.slice(0, step.at)}\n${next.slice(step.at)}`; + } else if (register) { + next = + next.slice(0, step.at) + + registerText(register, register.text, step.count) + + next.slice(step.at); + } + } + return next; +} + +/** The text typed into `baseline` to produce `text`, or null when it was not a plain insertion. */ +function insertedText(baseline: string, text: string): string | null { + const shortest = Math.min(baseline.length, text.length); + let prefix = 0; + while (prefix < shortest && baseline[prefix] === text[prefix]) prefix += 1; + let suffix = 0; + while ( + suffix < shortest - prefix && + baseline[baseline.length - 1 - suffix] === text[text.length - 1 - suffix] + ) { + suffix += 1; + } + if (prefix + suffix !== baseline.length) return null; + const inserted = text.slice(prefix, text.length - suffix); + return inserted.includes(VIM_CHIP) ? null : inserted; +} + +/** Steps that type `text` at `at`, splitting lines the way Enter would. */ +function typingSteps(at: number, text: string): VimStep[] { + const steps: VimStep[] = []; + let position = at; + text.split("\n").forEach((line, index) => { + if (index > 0) { + steps.push({ type: "newline", at: position }); + position += 1; + } + if (line) steps.push({ type: "replace", from: position, to: position, text: line }); + position += line.length; + }); + return steps; +} + +function escapeCursor(text: string, cursor: number): number { + return Math.max(lineStart(text, cursor), cursor - 1); +} + +/** Leaves insert mode: the cursor steps back onto the last typed character. */ +export function vimEscape( + state: VimState, + text: string, + cursor: number, +): { state: VimState; cursor: number } { + const lastChange = state.insert + ? { keys: state.insert.keys, inserted: insertedText(state.insert.baseline, text) ?? "" } + : state.lastChange; + return { + state: { ...state, mode: "normal", pending: [], insert: null, column: null, lastChange }, + cursor: escapeCursor(text, cursor), + }; +} + +function operate( + state: VimState, + keys: ReadonlyArray, + text: string, + cursor: number, + op: Operator, + target: Target, + count: number, + counted: boolean, +): VimOutcome | null { + let from: number; + let to: number; + let linewise = false; + let lastFind = state.lastFind; + if (target === "line") { + from = lineStart(text, cursor); + to = lineEnd(text, cursor); + for (let index = 1; index < count && to < text.length; index += 1) to = lineEnd(text, to + 1); + linewise = true; + } else if ("object" in target) { + const range = textObject(text, cursor, target.object); + if (!range) return null; + ({ from, to } = range); + } else if ( + op === "c" && + (target.key === "w" || target.key === "W") && + !isBlank(text[cursor]) && + cursor < text.length + ) { + from = cursor; + to = changeWordEnd(text, cursor, count, target.key === "W") + 1; + } else { + const motion = motionTarget(state, text, cursor, target, count, counted); + if (!motion) return null; + lastFind = motion.lastFind ?? lastFind; + from = Math.min(cursor, motion.position); + to = Math.max(cursor, motion.position); + if (motion.type === "linewise") { + from = lineStart(text, from); + to = lineEnd(text, to); + linewise = true; + } else if (motion.type === "inclusive") { + to = Math.min(text.length, to + 1); + } else if (target.key === "w" || target.key === "W") { + // A word motion that crosses into the next line stops at the end of this one. + const lastBreak = text.lastIndexOf("\n", to - 1); + if (lastBreak >= from) to = lastBreak; + } + } + + if (from === to && !linewise && op !== "c") return null; + const register: VimRegister = { text: text.slice(from, to), linewise }; + const yank = { from, to }; + const base: VimState = { ...state, register, lastFind, column: null }; + if (op === "y") { + const position = linewise && lineStart(text, cursor) === from ? cursor : from; + return { state: base, steps: [], cursor: clampNormalCursor(text, position), yank }; + } + if (op === "c") { + const steps: VimStep[] = from === to ? [] : [{ type: "replace", from, to, text: "" }]; + return { + state: { + ...base, + mode: "insert", + insert: { keys, baseline: applyVimSteps(text, steps, register) }, + }, + steps, + cursor: from, + yank, + }; + } + let deleteFrom = from; + let deleteTo = to; + if (linewise) { + if (to < text.length) deleteTo = to + 1; + else if (from > 0) deleteFrom = from - 1; + } + const steps: VimStep[] = [{ type: "replace", from: deleteFrom, to: deleteTo, text: "" }]; + const next = applyVimSteps(text, steps, register); + return { + state: { ...base, lastChange: { keys, inserted: "" } }, + steps, + cursor: linewise + ? firstNonBlank(next, Math.min(deleteFrom, next.length)) + : clampNormalCursor(next, from), + yank, + }; +} + +function act( + state: VimState, + keys: ReadonlyArray, + text: string, + cursor: number, + key: string, + count: number, + char: string | undefined, +): VimOutcome | null { + const start = lineStart(text, cursor); + const end = lineEnd(text, cursor); + const enterInsert = (position: number, steps: VimStep[] = []): VimOutcome => ({ + state: { + ...state, + mode: "insert", + column: null, + insert: { keys, baseline: applyVimSteps(text, steps, state.register) }, + }, + steps, + cursor: position, + }); + const change = (steps: VimStep[], position: number): VimOutcome => ({ + state: { ...state, column: null, lastChange: { keys, inserted: "" } }, + steps, + cursor: clampNormalCursor(applyVimSteps(text, steps, state.register), position), + }); + switch (key) { + case "i": + return enterInsert(cursor); + case "a": + return enterInsert(Math.min(cursor + 1, end)); + case "I": + return enterInsert(firstNonBlank(text, cursor)); + case "A": + return enterInsert(end); + case "o": + return enterInsert(end + 1, [{ type: "newline", at: end }]); + case "O": + return enterInsert(start, [{ type: "newline", at: start }]); + case "u": + return { state, steps: [], cursor, history: "undo" }; + case "": + return { state, steps: [], cursor, history: "redo" }; + case "p": + case "P": { + const register = state.register; + if (!register) return null; + if (register.linewise) { + const at = key === "p" ? end : start; + const lineAt = key === "p" ? end + 1 : start; + const steps: VimStep[] = [ + { type: "newline", at }, + { type: "put", at: lineAt, count }, + ]; + return change(steps, firstNonBlank(applyVimSteps(text, steps, register), lineAt)); + } + const at = key === "p" ? Math.min(cursor + 1, end) : cursor; + return change([{ type: "put", at, count }], at + register.text.length * count - 1); + } + case "J": { + let next = text; + let position = cursor; + const steps: VimStep[] = []; + for (let join = 0; join < Math.max(1, count - 1); join += 1) { + const joinAt = lineEnd(next, position); + if (joinAt >= next.length) break; + let contentStart = joinAt + 1; + while ( + contentStart < next.length && + next[contentStart] !== "\n" && + isBlank(next[contentStart]) + ) { + contentStart += 1; + } + const separator = + joinAt === lineStart(next, joinAt) || + isBlank(next[joinAt - 1]) || + contentStart >= next.length || + next[contentStart] === "\n" || + next[contentStart] === ")" + ? "" + : " "; + const step: VimStep = { type: "replace", from: joinAt, to: contentStart, text: separator }; + steps.push(step); + next = applyVimSteps(next, [step], null); + position = joinAt; + } + if (steps.length === 0) return null; + return change(steps, position); + } + case "r": { + if (cursor + count > end || !char) return null; + return change( + [{ type: "replace", from: cursor, to: cursor + count, text: char.repeat(count) }], + cursor + count - 1, + ); + } + case ".": { + const last = state.lastChange; + if (!last) return null; + const replay = run({ ...state, pending: [] }, last.keys, text, cursor); + if (!replay) return null; + if (replay.state.mode !== "insert") + return { ...replay, state: { ...replay.state, lastChange: last } }; + const steps = [...replay.steps]; + const typed = typingSteps(replay.cursor, last.inserted); + const previous = steps.at(-1); + const first = typed[0]; + // Merge the deletion and the typing so one undo reverts the repeat. + if ( + previous?.type === "replace" && + first?.type === "replace" && + previous.from + previous.text.length === first.from + ) { + steps[steps.length - 1] = { ...previous, text: previous.text + first.text }; + typed.shift(); + } + steps.push(...typed); + const next = applyVimSteps(text, steps, replay.state.register); + return { + ...replay, + state: { ...replay.state, mode: "normal", insert: null, lastChange: last }, + steps, + cursor: escapeCursor(next, replay.cursor + last.inserted.length), + }; + } + default: + return null; + } +} + +function run( + state: VimState, + keys: ReadonlyArray, + text: string, + cursor: number, +): VimOutcome | null { + const command = parseCommand(keys); + if (typeof command === "string") return null; + if (command.kind === "operator") { + return operate( + state, + keys, + text, + cursor, + command.op, + command.target, + command.count, + command.counted, + ); + } + if (command.kind === "action") { + return act(state, keys, text, cursor, command.key, command.count, command.char); + } + const motion = motionTarget(state, text, cursor, command.motion, command.count, command.counted); + if (!motion) return null; + return { + state: { ...state, column: motion.column ?? null, lastFind: motion.lastFind ?? state.lastFind }, + steps: [], + cursor: clampNormalCursor(text, motion.position), + }; +} + +/** + * Handles one key in normal mode. `key` is a single character, or ``, `` or ``. + * Unknown or failed commands are swallowed without changes, like Vim's beep. + */ +export function vimNormalKey( + state: VimState, + key: string, + text: string, + cursor: number, +): VimOutcome { + const keys = [...state.pending, key]; + const parsed = parseCommand(keys); + if (parsed === "incomplete") return { state: { ...state, pending: keys }, steps: [], cursor }; + const idle = { ...state, pending: [] }; + if (parsed === "invalid") return { state: idle, steps: [], cursor }; + return run(idle, keys, text, cursor) ?? { state: idle, steps: [], cursor }; +} diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index f4abe911aa72a..f6ce263fd872c 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -127,6 +127,22 @@ const ICON_PATHS: Record, + workspaceRoot: string | null, + ) => { + const { environmentId } = thread; + if (thread.runtime !== null) { + const stopped = await stopThreadSession({ environmentId, input: { threadId: thread.id } }); + if (stopped._tag === "Failure") throw squashAtomCommandFailure(stopped); + } + toastManager.add({ + type: "success", + title: gt("Agent session will restart"), + description: gt("Your next message starts a fresh session."), + }); + if (workspaceRoot === null) return; + const refreshed = await refreshProviders({ + environmentId, + input: { + instanceId: thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId, + cwd: thread.worktreePath ?? workspaceRoot, + fresh: true, + }, + }); + if (refreshed._tag === "Failure") throw squashAtomCommandFailure(refreshed); + }; + return (...args: Parameters) => + restart(...args).catch((error: unknown) => { + toastManager.add({ + type: "error", + title: gt("Unable to restart agent session"), + description: thrownErrorMessage(error, m) ?? gt("An unexpected error occurred."), + }); + }); +} diff --git a/apps/web/src/hooks/useThreadActionMenu.test.ts b/apps/web/src/hooks/useThreadActionMenu.test.ts index 3c8255b04c088..1ffea067eff75 100644 --- a/apps/web/src/hooks/useThreadActionMenu.test.ts +++ b/apps/web/src/hooks/useThreadActionMenu.test.ts @@ -120,6 +120,9 @@ vi.mock("./useSettings", () => ({ })); vi.mock("./useThreadActions", () => ({ canTurnThreadIntoProject: () => false, + confirmThreadMove: async () => false, + readThreadMoveTargets: () => [], + readThreadMachineMoveTargets: () => [], useThreadActions: () => Object.fromEntries( [ diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index 4e5914d078c57..1162dcbc2bc6b 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -11,6 +11,7 @@ import { import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { AuthOrchestrationOperateScope, + ProjectId, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; @@ -20,6 +21,7 @@ import { msg } from "gt-react"; import { pickSnoozePreset, resolveSnoozePresets } from "../components/Sidebar.snooze"; import { buildThreadActionMenuItems, + parseMachineMovePick, threadActionRequiresOperate, type ThreadActionMenuId, } from "../components/threadActionMenu.logic"; @@ -50,7 +52,13 @@ import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; import { useCopyToClipboard } from "./useCopyToClipboard"; import { useNewThreadHandler } from "./useHandleNewThread"; import { useClientSettings } from "./useSettings"; -import { canTurnThreadIntoProject, useThreadActions } from "./useThreadActions"; +import { + canTurnThreadIntoProject, + confirmThreadMove, + readThreadMachineMoveTargets, + readThreadMoveTargets, + useThreadActions, +} from "./useThreadActions"; function failureToast(title: string, error: unknown) { toastManager.add( @@ -91,6 +99,8 @@ export function useThreadActionMenu(input: { deleteThread, markThreadUnread, turnThreadIntoProject, + moveThreadToProject, + moveThreadToMachine, } = useThreadActions(); const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, { reportFailure: false, @@ -138,6 +148,7 @@ export function useThreadActionMenu(input: { }; const isRegeneratingTitle = thread.titleRegeneration != null; const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId); + const machineMoveTargets = readThreadMachineMoveTargets(threadRef); const items = buildThreadActionMenuItems({ canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), canFind: onFind !== undefined, @@ -154,6 +165,8 @@ export function useThreadActionMenu(input: { snoozePresets, canShareWithGuest, canTurnIntoProject: canTurnThreadIntoProject(threadRef), + moveTargets: readThreadMoveTargets(threadRef), + machineMoveTargets, }); const clicked = await settlePromise(() => api.contextMenu.show(items, position)); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -194,6 +207,22 @@ export function useThreadActionMenu(input: { failureToast(title, squashAtomCommandFailure(result)); } }; + const machinePick = parseMachineMovePick(action, machineMoveTargets); + if (machinePick) { + await moveThreadToMachine(threadRef, { + environmentId: machinePick.machine.environmentId, + projectId: machinePick.project.id, + }); + return; + } + if (action.startsWith("move-to-project:")) { + const projectId = ProjectId.make(action.slice("move-to-project:".length)); + if (!(await confirmThreadMove(threadRef, projectId))) return; + await reportFailure(m(msg("Could not move thread")), () => + moveThreadToProject(threadRef, projectId), + ); + return; + } switch (action) { case "find": onFind?.(threadRef); diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 2a591127044d1..e9e85ba962f01 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -7,17 +7,23 @@ import { } from "@t3tools/client-runtime/environment"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled"; -import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; +import { threadMoveTargets, threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; +import { + moveThreadToMachine, + threadMachineMoveTargets, +} from "@t3tools/client-runtime/state/threadMachineMove"; import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope, EnvironmentAuthorizationError, EnvironmentId, + type ProjectId, type ScopedThreadRef, ThreadId, sessionGrantsScope, } from "@t3tools/contracts"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; +import { threadMachineMoveNotice, threadMoveNotice } from "@t3tools/shared/threadMove"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; @@ -29,6 +35,8 @@ import { useComposerDraftStore } from "../composerDraftStore"; import { environmentSession, readEnvironmentScope } from "../state/session"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentServerConfigsAtom } from "../state/server"; +import { readEnvironment } from "../state/environments"; +import { environmentSummaries } from "../state/presentation"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { orchestrationEnvironment } from "../state/orchestration"; import { projectEnvironment } from "../state/projects"; @@ -46,6 +54,7 @@ import { readEnvironmentSupportsAutoSettleOptOut, readEnvironmentThreadRefs, readProject, + readProjects, readThreadShell, readThreadShells, } from "../state/entities"; @@ -287,6 +296,120 @@ export function canTurnThreadIntoProject(threadRef: ScopedThreadRef): boolean { return project !== null && isScratchProject(project, config.scratchWorkspaceRoot); } +/** Projects this thread can move into, on a server that can move it. */ +export function readThreadMoveTargets(threadRef: ScopedThreadRef) { + const thread = readThreadShell(threadRef); + const config = appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId); + if (!thread || config?.environment.capabilities.threadMoveToProject !== true) return []; + return threadMoveTargets(readProjects(), thread, config.scratchWorkspaceRoot); +} + +/** Says what the move changes for this thread before it happens. */ +export async function confirmThreadMove( + threadRef: ScopedThreadRef, + projectId: ProjectId, +): Promise { + const thread = readThreadShell(threadRef); + const project = readProject({ environmentId: threadRef.environmentId, projectId }); + const api = readLocalApi(); + if (!thread || !project || !api) return false; + const notice = threadMoveNotice({ + projectTitle: project.title, + fromWorktree: thread.worktreePath !== null, + }); + const confirmed = await settlePromise(() => + api.dialogs.confirm( + `${m(msg('Move "{thread}" to {project}?', { thread: thread.title, project: project.title }))}\n${notice}`, + { + initialFocus: "confirm", + }, + ), + ); + return confirmed._tag === "Success" && confirmed.value; +} + +/** Other connected machines this thread can move to, each with its projects. */ +export function readThreadMachineMoveTargets(threadRef: ScopedThreadRef) { + return threadMachineMoveTargets({ + sourceEnvironmentId: threadRef.environmentId, + connectedEnvironmentIds: appAtomRegistry.get(environmentSummaries.connectedEnvironmentIdsAtom), + serverConfigs: appAtomRegistry.get(environmentServerConfigsAtom), + projects: readProjects(), + labelOf: (environmentId) => readEnvironment(environmentId)?.label, + canOperate: (environmentId) => + readEnvironmentScope(environmentId, AuthOrchestrationOperateScope), + }); +} + +/** Confirms, moves the thread to a project on another machine, then opens it there. */ +export async function moveThreadToMachineAndOpen( + source: ScopedThreadRef, + target: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + open: (threadRef: ScopedThreadRef) => Promise, +): Promise { + const thread = readThreadShell(source); + const project = readProject(target); + const fromMachine = readEnvironment(source.environmentId)?.label; + const toMachine = readEnvironment(target.environmentId)?.label; + const api = readLocalApi(); + if (!thread || !project || !fromMachine || !toMachine || !api) return; + const outcome = await moveThreadToMachine({ + registry: appAtomRegistry, + commands: projectEnvironment, + source, + sourceLabel: fromMachine, + target, + targetLabel: `${project.title} on ${toMachine}`, + confirm: async ({ leftBehind }) => { + const notice = threadMachineMoveNotice({ + fromMachine, + toMachine, + projectTitle: project.title, + leftBehind, + }); + const confirmed = await settlePromise(() => + api.dialogs.confirm( + `${m(msg('Move "{thread}" to {machine}?', { thread: thread.title, machine: toMachine }))}\n${notice}`, + { + initialFocus: "confirm", + }, + ), + ); + return confirmed._tag === "Success" && confirmed.value; + }, + resolve: m, + }); + if (outcome._tag === "Cancelled") return; + if (outcome._tag === "Failed") { + toastManager.add( + stackedThreadToast({ + type: "error", + title: m(msg("Could not move thread")), + description: outcome.message, + }), + ); + return; + } + refreshArchivedThreadsForEnvironment(source.environmentId); + if (outcome.archiveError !== null) { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: m( + msg("Moved, but the original is still active on {machine}", { machine: fromMachine }), + ), + description: m( + msg("{error} The moved copy is on {machine}.", { + error: outcome.archiveError, + machine: toMachine, + }), + ), + }), + ); + } + await settlePromise(() => open(outcome.threadRef)); +} + function threadOperationFailure(target: ScopedThreadRef) { return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope) ? null @@ -341,6 +464,7 @@ export function useThreadActions() { const createProjectFromThread = useAtomCommand(projectEnvironment.createFromThread, { reportFailure: false, }); + const moveThread = useAtomCommand(projectEnvironment.moveThread, { reportFailure: false }); const stopThreadSession = useOrchestrationCommand(threadEnvironment.stopSession); const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, { reportFailure: false, @@ -1066,5 +1190,20 @@ export function useThreadActions() { environmentId: target.environmentId, input: { threadId: target.threadId }, }), + moveThreadToProject: (target: ScopedThreadRef, projectId: ProjectId) => + moveThread({ + environmentId: target.environmentId, + input: { threadId: target.threadId, projectId }, + }), + moveThreadToMachine: ( + source: ScopedThreadRef, + target: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + ) => + moveThreadToMachineAndOpen(source, target, (threadRef) => + router.navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }), + ), }; } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 3a71e92063446..a4c34d8e9de58 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Versucht, Designs {count}-mal zu prüfen} other {Versucht, Designs {count}-mal zu prüfen}}", "a16ae702cbb60dde": "{count, plural, one {Design {count}-mal festgelegt} other {Design {count}-mal festgelegt}}", "978b4b05bea775d1": "{count, plural, one {Versucht, das Design {count}-mal festzulegen} other {Versucht, das Design {count}-mal festzulegen}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Verknüpfte Umgebungen {count}-mal aufgelistet} other {Verknüpfte Umgebungen {count}-mal aufgelistet}}", "78d34854295169a7": "{count, plural, one {Versucht, verknüpfte Umgebungen {count}-mal aufzulisten} other {Versucht, verknüpfte Umgebungen {count}-mal aufzulisten}}", "07edf9b32bf1f437": "{count, plural, one {Browser {count}-mal verwendet} other {Browser {count}-mal verwendet}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Feedback an OpenAI gesendet.\n\nThread-ID: `{feedbackId}`", "de62133b5898fab1": "Feedback konnte nicht an OpenAI gesendet werden.\n\n{errorMessage}", "0bed322f6071f4da": "Ein Fehler ist aufgetreten.", + "448735c0084132f5": "Versuche es erneut.", "78f82fef9e0c8661": "Repositorys", "2360ad0503c2a0a8": "Repositorys auswählen", "05b16c85cb1e18bd": "Keine Repositorys", @@ -1796,9 +1801,10 @@ "2eb493c9e7a5fe9a": "Pull Request mit Thread verknüpfen", "abbbacfec60327d7": "Verknüpfte Elemente anzeigen", "67f5b13c3c7bcd40": "Mit Gast teilen", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "Agentensitzung neu starten", - "963d099509eabcd6": "Die Agentensitzung wird neu gestartet", - "1d384d4fe7888a09": "Deine nächste Nachricht startet eine neue Sitzung.", "e4b61c891fed297e": "Gehe zu Datei", "d2ccdb8cd3297212": "Projekt hinzufügen", "594bcbef04093f72": "WSL-Ordner öffnen", @@ -1808,6 +1814,8 @@ "a0cc19e60dd99851": "Nutzung öffnen", "46694969044eee98": "Nächsten Arbeitsbereich fokussieren", "0a1011328ba42eef": "Vorherigen Arbeitsbereich fokussieren", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "Einstellungen öffnen", "1d17dc60c59e0524": "Projekt loslösen", "5cfaaa20c460c328": "Projekt anheften", @@ -1907,7 +1915,6 @@ "8bf65a425f50d140": "Hell", "d604bc5cf3386f00": "Dunkel", "4758dde317babc14": "Design-Auswahl konnte nicht gespeichert werden", - "448735c0084132f5": "Versuche es erneut.", "e1ef4197dc810bab": "Für den hellen Modus", "002fa063deda988d": "Für den dunklen Modus", "9c6962c66efa5668": "Darstellung ändern", @@ -2767,6 +2774,8 @@ "3364346f40934e88": "Alle Projekte anzeigen", "666f3ac177c116b6": "Nach {project} filtern", "1385e2d8bd696370": "In Projekt umwandeln", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "Verhalten beim automatischen Erledigen", "39eb35d54cacd314": "Einstellungen folgen", "65e3725b1c46b314": "Nie", @@ -2867,6 +2876,9 @@ "c7d7f42240dac324": "Diese Umgebung unterstützt das Verknüpfen dieses Pull Requests nicht.", "6096ad21ed076d33": "Aktualisierung der Verknüpfung unterbrochen.", "c80f181fe72924a9": "Projekt konnte nicht entfernt werden", + "963d099509eabcd6": "Die Agentensitzung wird neu gestartet", + "1d384d4fe7888a09": "Deine nächste Nachricht startet eine neue Sitzung.", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "Konnte nicht ohne Projekt starten", "8d51135cc55089f9": "Modelleinstellungen nicht gespeichert", "c7193961d383be05": "Gespeicherte Modelleinstellungen konnten nicht geladen werden. Versuche es erneut.", @@ -2901,6 +2913,10 @@ "08f5b642746eebbe": "Thread „{title}“ loslösen?", "bc574b901d06687c": "Dadurch wird der Thread aus deinem Bereich „Angeheftet“ entfernt.", "b4f6775203e9d0bc": "Thread gelöscht, aber die Navigation ist fehlgeschlagen", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "Archivieren konnte nicht rückgängig gemacht werden", "241a9d368c292ddb": "Dieser Thread ist der einzige, der mit diesem Worktree verknüpft ist:", "4cce2f30bd1d0d0f": "Den Worktree auch löschen?", @@ -4713,6 +4729,8 @@ "16aa57835b1ee840": "Eine Genehmigung wird bereits beantwortet, daher wurde deine Nachricht nicht gesendet.", "cdfced17f0576311": "Eine weitere Genehmigung ist eingegangen, daher wurde deine Nachricht nicht gesendet.", "08a5b53649784fe8": "{count, plural, one {Der Prompt liegt {excess} Zeichen über dem Limit von {limit} Zeichen. Kürze oder teile ihn vor dem Senden.} other {Der Prompt liegt {excess} Zeichen über dem Limit von {limit} Zeichen. Kürze oder teile ihn vor dem Senden.}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "Das Kopieren von Snapshots erfordert eine sichere Browserverbindung.", "4bd2f44a35e591ca": "Im Systembrowser öffnen", "202e13f15a3dcd30": "Link kopieren", @@ -7501,6 +7519,9 @@ "92785adb251da88c": "Chatbreite auf Standard zurücksetzen", "4d457bcce0c0e272": "Chatbreite", "81f3a196537bbee0": "Komfortabel (Standard)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "e79e5388f669495f": "Den Denkaufwand im Eingabefeld als Namen, etwa Hoch, oder als Balken anzeigen.", "7f0365c7e4e8bcbf": "Anzeige des Aufwands auf Standard zurücksetzen", "14bf40f765172a50": "Aufwandsanzeige", @@ -10039,6 +10060,7 @@ "4b46043fd3700c17": "Skills im Slash-Menü anzeigen", "2407d5d61e7f7206": "Rich-Text-Eingabefeld", "64b8fd2c284c3137": "Tastenkürzel zum Senden", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "Verhalten bei Folgenachrichten", "425021487583cf8a": "Subagenten und Nebenchats öffnen in", "856812e7e1fc445e": "Tool-Aufrufe im Chat", @@ -10087,6 +10109,8 @@ "761ac81a418bd87d": "Immer {modifierLabel} + Enter", "3a6fb236cd3f521b": "Formatiertes Markdown beim Tippen anzeigen.", "f9251f92691626cd": "Rich-Text-Eingabefeld auf Standard zurücksetzen", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Lege fest, wann Enter einen Prompt sendet oder eine neue Zeile einfügt", "147e9953f6fc550d": "Tastenkürzel zum Senden auf Standard zurücksetzen", "4a1201bd18283940": "Skills auch im /-Befehlsmenü anzeigen. Skills erscheinen immer, wenn du $ tippst.", @@ -11760,6 +11784,7 @@ "d8d6cfd630cff22d": "rot grün blau orange hinzufügungen löschungen änderungen anzahl palette farbenblind", "717e49895cfee1c7": "breit volle breite spalte layout nachrichten eingabefeld monitor", "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", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "reasoning aufwand denken balken grafik wort bezeichnung stufe eingabefeld", "6113c17109ee0d57": "latex tex katex gleichungen formeln markdown", "8c8364d44fa28d22": "dev nightly latest kanal artwork badge bezeichnung ausblenden keine", @@ -11821,6 +11846,7 @@ "7d0ab4cf50686d31": "proaktiv automatisch öffnen diff pull request pr rechter bereich agent abschluss", "5256dd2ed3a24332": "befehlsmenü dollar $ slash /", "ade91c8927c48175": "eingabefeld rich text tiptap fett kursiv markdown formatiert wysiwyg", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "enter return befehl strg ctrl mehrzeilig prompt neue zeile eingabefeld", "9d1013084c46ecce": "warteschlange einreihen umlenken laufende runde senden standardverhalten eingabefeld", "e5e7f5e1fb1f2e4c": "subagent nebenchat verknüpfter thread klick rechte leiste seitenleiste hauptansicht befehl strg mittelklick", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 65ed2a4db1b89..59bc060d276df 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Tried to check themes {count} time} other {Tried to check themes {count} times}}", "a16ae702cbb60dde": "{count, plural, one {Set the theme {count} time} other {Set the theme {count} times}}", "978b4b05bea775d1": "{count, plural, one {Tried to set the theme {count} time} other {Tried to set the theme {count} times}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Listed linked environments {count} time} other {Listed linked environments {count} times}}", "78d34854295169a7": "{count, plural, one {Tried to list linked environments {count} time} other {Tried to list linked environments {count} times}}", "07edf9b32bf1f437": "{count, plural, one {Used browser {count} time} other {Used browser {count} times}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Feedback sent to OpenAI.\n\nThread ID: `{feedbackId}`", "de62133b5898fab1": "Could not send feedback to OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "An error occurred.", + "448735c0084132f5": "Try again.", "78f82fef9e0c8661": "Repositories", "2360ad0503c2a0a8": "Choose repositories", "05b16c85cb1e18bd": "No repositories", @@ -1797,9 +1802,10 @@ "2eb493c9e7a5fe9a": "Link pull request to thread", "abbbacfec60327d7": "Show linked items", "67f5b13c3c7bcd40": "Share with guest", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "Restart agent session", - "963d099509eabcd6": "Agent session will restart", - "1d384d4fe7888a09": "Your next message starts a fresh session.", "e4b61c891fed297e": "Go to file", "d2ccdb8cd3297212": "Add project", "594bcbef04093f72": "Open WSL folder", @@ -1809,6 +1815,8 @@ "a0cc19e60dd99851": "Open usage", "46694969044eee98": "Focus Next Workspace Area", "0a1011328ba42eef": "Focus Previous Workspace Area", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "Open settings", "1d17dc60c59e0524": "Unpin project", "5cfaaa20c460c328": "Pin project", @@ -1908,7 +1916,6 @@ "8bf65a425f50d140": "Light", "d604bc5cf3386f00": "Dark", "4758dde317babc14": "Couldn't save theme selection", - "448735c0084132f5": "Try again.", "e1ef4197dc810bab": "For light mode", "002fa063deda988d": "For dark mode", "9c6962c66efa5668": "Change appearance", @@ -2766,6 +2773,8 @@ "3364346f40934e88": "Show all projects", "666f3ac177c116b6": "Filter by {project}", "1385e2d8bd696370": "Turn into project", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "Auto-settle behavior", "39eb35d54cacd314": "Follow settings", "65e3725b1c46b314": "Never", @@ -2866,6 +2875,9 @@ "c7d7f42240dac324": "This environment does not support linking this pull request.", "6096ad21ed076d33": "Link update interrupted.", "c80f181fe72924a9": "Failed to remove project", + "963d099509eabcd6": "Agent session will restart", + "1d384d4fe7888a09": "Your next message starts a fresh session.", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "Could not start without a project", "8d51135cc55089f9": "Model preferences not saved", "c7193961d383be05": "Could not load saved model preferences. Try again.", @@ -2900,6 +2912,10 @@ "08f5b642746eebbe": "Unpin thread \"{title}\"?", "bc574b901d06687c": "This will move the thread out of your pinned section.", "b4f6775203e9d0bc": "Thread deleted, but navigation failed", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "Failed to undo archive", "241a9d368c292ddb": "This thread is the only one linked to this worktree:", "4cce2f30bd1d0d0f": "Delete the worktree too?", @@ -4712,6 +4728,8 @@ "16aa57835b1ee840": "An approval is already being answered, so your message wasn't sent.", "cdfced17f0576311": "Another approval arrived, so your message wasn't sent.", "08a5b53649784fe8": "{count, plural, one {Prompt is {excess} character over the {limit}-character limit. Shorten or split it before sending.} other {Prompt is {excess} characters over the {limit}-character limit. Shorten or split it before sending.}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "Snapshot copying requires a secure browser connection.", "4bd2f44a35e591ca": "Open in system browser", "202e13f15a3dcd30": "Copy Link", @@ -7509,6 +7527,9 @@ "92785adb251da88c": "Reset chat width to default", "4d457bcce0c0e272": "Chat width", "81f3a196537bbee0": "Comfortable (default)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "e79e5388f669495f": "Show reasoning effort in the composer as its name, such as High, or as bars.", "7f0365c7e4e8bcbf": "Reset effort display to default", "14bf40f765172a50": "Effort display", @@ -10048,6 +10069,7 @@ "4b46043fd3700c17": "Show skills in slash menu", "2407d5d61e7f7206": "Rich text composer", "64b8fd2c284c3137": "Send shortcut", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "Follow-up behavior", "425021487583cf8a": "Open subagents and side chats in", "856812e7e1fc445e": "Tool calls in chat", @@ -10096,6 +10118,8 @@ "761ac81a418bd87d": "{modifierLabel} + Enter always", "3a6fb236cd3f521b": "Show formatted Markdown as you type.", "f9251f92691626cd": "Reset rich text composer to default", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Choose when Enter sends a prompt or inserts a new line", "147e9953f6fc550d": "Reset send shortcut to default", "4a1201bd18283940": "Also include skills in the / command menu. Skills always appear when you type $.", @@ -11768,6 +11792,7 @@ "d8d6cfd630cff22d": "red green blue orange additions deletions changes counts palette colorblind", "717e49895cfee1c7": "wide full width column layout messages composer monitor", "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", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "reasoning effort thinking bars graph word label level composer", "6113c17109ee0d57": "latex tex katex equations formulas markdown", "8c8364d44fa28d22": "dev nightly latest channel artwork pill label hide none", @@ -11829,6 +11854,7 @@ "7d0ab4cf50686d31": "proactive automatically open diff pull request pr right panel agent completion", "5256dd2ed3a24332": "command menu dollar $ slash /", "ade91c8927c48175": "composer rich text tiptap bold italic markdown styled wysiwyg", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "enter return command ctrl multiline prompt new line composer", "9d1013084c46ecce": "queue steer running turn send default behavior composer", "e5e7f5e1fb1f2e4c": "subagent side chat linked thread click right panel side panel main view command ctrl middle click", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index dae05eda74dd9..7a8b08ff50842 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Intentó consultar los temas {count} vez} other {Intentó consultar los temas {count} veces}}", "a16ae702cbb60dde": "{count, plural, one {Cambió el tema {count} vez} other {Cambió el tema {count} veces}}", "978b4b05bea775d1": "{count, plural, one {Intentó cambiar el tema {count} vez} other {Intentó cambiar el tema {count} veces}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Listó entornos vinculados {count} vez} other {Listó entornos vinculados {count} veces}}", "78d34854295169a7": "{count, plural, one {Intentó listar entornos vinculados {count} vez} other {Intentó listar entornos vinculados {count} veces}}", "07edf9b32bf1f437": "{count, plural, one {Se usó el navegador {count} vez} other {Se usó el navegador {count} veces}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Comentarios enviados a OpenAI.\n\nID del hilo: `{feedbackId}`", "de62133b5898fab1": "No se pudieron enviar los comentarios a OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Se produjo un error.", + "448735c0084132f5": "Vuelve a intentarlo.", "78f82fef9e0c8661": "Repositorios", "2360ad0503c2a0a8": "Elegir repositorios", "05b16c85cb1e18bd": "Sin repositorios", @@ -1797,9 +1802,10 @@ "2eb493c9e7a5fe9a": "Vincular una pull request al hilo", "abbbacfec60327d7": "Mostrar elementos vinculados", "67f5b13c3c7bcd40": "Compartir con un invitado", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "Reiniciar sesión del agente", - "963d099509eabcd6": "La sesión del agente se reiniciará", - "1d384d4fe7888a09": "Tu próximo mensaje inicia una sesión nueva.", "e4b61c891fed297e": "Ir al archivo", "d2ccdb8cd3297212": "Añadir proyecto", "594bcbef04093f72": "Abrir carpeta de WSL", @@ -1809,6 +1815,8 @@ "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Enfocar la siguiente área de trabajo", "0a1011328ba42eef": "Enfocar el área de trabajo anterior", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "Abrir ajustes", "1d17dc60c59e0524": "Desfijar proyecto", "5cfaaa20c460c328": "Fijar proyecto", @@ -1908,7 +1916,6 @@ "8bf65a425f50d140": "Claro", "d604bc5cf3386f00": "Oscuro", "4758dde317babc14": "No se pudo guardar el tema seleccionado", - "448735c0084132f5": "Vuelve a intentarlo.", "e1ef4197dc810bab": "Para el modo claro", "002fa063deda988d": "Para el modo oscuro", "9c6962c66efa5668": "Cambiar apariencia", @@ -2766,6 +2773,8 @@ "3364346f40934e88": "Mostrar todos los proyectos", "666f3ac177c116b6": "Filtrar por {project}", "1385e2d8bd696370": "Convertir en proyecto", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "Resolución automática", "39eb35d54cacd314": "Según los ajustes", "65e3725b1c46b314": "Nunca", @@ -2866,6 +2875,9 @@ "c7d7f42240dac324": "Este entorno no permite vincular esta pull request.", "6096ad21ed076d33": "Se interrumpió la actualización del vínculo.", "c80f181fe72924a9": "No se pudo quitar el proyecto", + "963d099509eabcd6": "La sesión del agente se reiniciará", + "1d384d4fe7888a09": "Tu próximo mensaje inicia una sesión nueva.", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "No se pudo empezar sin proyecto", "8d51135cc55089f9": "Preferencias de modelos no guardadas", "c7193961d383be05": "No se pudieron cargar las preferencias de modelos guardadas. Vuelve a intentarlo.", @@ -2900,6 +2912,10 @@ "08f5b642746eebbe": "¿Desfijar el hilo \"{title}\"?", "bc574b901d06687c": "Esto sacará el hilo de tu sección de fijados.", "b4f6775203e9d0bc": "Hilo eliminado, pero falló la navegación", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "No se pudo deshacer el archivado", "241a9d368c292ddb": "Este hilo es el único vinculado a este worktree:", "4cce2f30bd1d0d0f": "¿Eliminar también el worktree?", @@ -4710,6 +4726,8 @@ "16aa57835b1ee840": "Ya se está respondiendo a una aprobación, así que tu mensaje no se envió.", "cdfced17f0576311": "Llegó otra aprobación, así que tu mensaje no se envió.", "08a5b53649784fe8": "{count, plural, one {El prompt supera en {excess} carácter el límite de {limit} caracteres. Acórtalo o divídelo antes de enviarlo.} other {El prompt supera en {excess} caracteres el límite de {limit} caracteres. Acórtalo o divídelo antes de enviarlo.}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "Copiar instantáneas requiere una conexión segura del navegador.", "4bd2f44a35e591ca": "Abrir en el navegador del sistema", "202e13f15a3dcd30": "Copiar enlace", @@ -7502,6 +7520,9 @@ "92785adb251da88c": "Restablecer el ancho del chat al valor predeterminado", "4d457bcce0c0e272": "Ancho del chat", "81f3a196537bbee0": "Cómodo (predeterminado)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "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", "14bf40f765172a50": "Visualización del esfuerzo", @@ -10036,6 +10057,7 @@ "4b46043fd3700c17": "Mostrar skills en el menú de barra", "2407d5d61e7f7206": "Cuadro de mensaje con texto enriquecido", "64b8fd2c284c3137": "Atajo de envío", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "Comportamiento de los seguimientos", "425021487583cf8a": "Abrir subagentes y chats laterales en", "856812e7e1fc445e": "Llamadas a herramientas en el chat", @@ -10084,6 +10106,8 @@ "761ac81a418bd87d": "{modifierLabel} + Enter siempre", "3a6fb236cd3f521b": "Muestra el Markdown con formato mientras escribes.", "f9251f92691626cd": "Restablecer el cuadro de mensaje con texto enriquecido al valor predeterminado", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Elige cuándo Enter envía un prompt o inserta una línea nueva", "147e9953f6fc550d": "Restablecer el atajo de envío al valor predeterminado", "4a1201bd18283940": "Incluye también las skills en el menú de comandos /. Las skills siempre aparecen al escribir $.", @@ -11753,6 +11777,7 @@ "d8d6cfd630cff22d": "rojo verde azul naranja adiciones eliminaciones cambios recuentos paleta daltonismo", "717e49895cfee1c7": "ancho ancho completo columna diseño mensajes cuadro mensaje compositor monitor", "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", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "esfuerzo de razonamiento pensamiento barras gráfico palabra etiqueta nivel cuadro mensaje compositor", "6113c17109ee0d57": "latex tex katex ecuaciones fórmulas markdown", "8c8364d44fa28d22": "dev nightly latest canal ilustración píldora etiqueta ocultar ninguno", @@ -11814,6 +11839,7 @@ "7d0ab4cf50686d31": "proactivo abrir automáticamente diff pull request pr panel derecho agente finalización", "5256dd2ed3a24332": "menú de comandos dólar $ barra /", "ade91c8927c48175": "cuadro mensaje compositor texto enriquecido tiptap negrita cursiva markdown con estilo wysiwyg", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "enter intro comando ctrl multilínea prompt nueva línea cuadro mensaje compositor", "9d1013084c46ecce": "cola redirigir turno en ejecución enviar comportamiento predeterminado cuadro mensaje compositor", "e5e7f5e1fb1f2e4c": "subagente chat lateral hilo vinculado clic panel derecho panel lateral vista principal comando ctrl clic central", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 6054810c0c23d..77e0564bf9c6e 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Tentative de vérifier les thèmes {count} fois} other {Tentative de vérifier les thèmes {count} fois}}", "a16ae702cbb60dde": "{count, plural, one {Thème défini {count} fois} other {Thème défini {count} fois}}", "978b4b05bea775d1": "{count, plural, one {Tentative de définir le thème {count} fois} other {Tentative de définir le thème {count} fois}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Environnements associés listés {count} fois} other {Environnements associés listés {count} fois}}", "78d34854295169a7": "{count, plural, one {Tentative de lister les environnements associés {count} fois} other {Tentative de lister les environnements associés {count} fois}}", "07edf9b32bf1f437": "{count, plural, one {Navigateur utilisé {count} fois} other {Navigateur utilisé {count} fois}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Commentaires envoyés à OpenAI.\n\nID du fil : `{feedbackId}`", "de62133b5898fab1": "Impossible d’envoyer les commentaires à OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Une erreur s’est produite.", + "448735c0084132f5": "Réessayez.", "78f82fef9e0c8661": "Dépôts", "2360ad0503c2a0a8": "Choisir les dépôts", "05b16c85cb1e18bd": "Aucun dépôt", @@ -1797,9 +1802,10 @@ "2eb493c9e7a5fe9a": "Associer une pull request au fil", "abbbacfec60327d7": "Afficher les éléments associés", "67f5b13c3c7bcd40": "Partager avec un invité", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "Redémarrer la session de l’agent", - "963d099509eabcd6": "La session de l’agent va redémarrer", - "1d384d4fe7888a09": "Votre prochain message démarre une nouvelle session.", "e4b61c891fed297e": "Aller au fichier", "d2ccdb8cd3297212": "Ajouter un projet", "594bcbef04093f72": "Ouvrir un dossier WSL", @@ -1809,6 +1815,8 @@ "a0cc19e60dd99851": "Ouvrir l’utilisation", "46694969044eee98": "Activer la zone de travail suivante", "0a1011328ba42eef": "Activer la zone de travail précédente", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "Ouvrir les paramètres", "1d17dc60c59e0524": "Désépingler le projet", "5cfaaa20c460c328": "Épingler le projet", @@ -1908,7 +1916,6 @@ "8bf65a425f50d140": "Clair", "d604bc5cf3386f00": "Sombre", "4758dde317babc14": "Impossible d’enregistrer le choix du thème", - "448735c0084132f5": "Réessayez.", "e1ef4197dc810bab": "Pour le mode clair", "002fa063deda988d": "Pour le mode sombre", "9c6962c66efa5668": "Changer l’apparence", @@ -2766,6 +2773,8 @@ "3364346f40934e88": "Afficher tous les projets", "666f3ac177c116b6": "Filtrer par {project}", "1385e2d8bd696370": "Transformer en projet", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "Comportement de la clôture automatique", "39eb35d54cacd314": "Suivre les paramètres", "65e3725b1c46b314": "Jamais", @@ -2866,6 +2875,9 @@ "c7d7f42240dac324": "Cet environnement ne permet pas d’associer cette pull request.", "6096ad21ed076d33": "Mise à jour de l’association interrompue.", "c80f181fe72924a9": "Échec du retrait du projet", + "963d099509eabcd6": "La session de l’agent va redémarrer", + "1d384d4fe7888a09": "Votre prochain message démarre une nouvelle session.", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "Impossible de démarrer sans projet", "8d51135cc55089f9": "Préférences de modèle non enregistrées", "c7193961d383be05": "Impossible de charger les préférences de modèle enregistrées. Réessayez.", @@ -2900,6 +2912,10 @@ "08f5b642746eebbe": "Désépingler le fil « {title} » ?", "bc574b901d06687c": "Le fil sera retiré de votre section des épinglés.", "b4f6775203e9d0bc": "Fil supprimé, mais la navigation a échoué", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "Échec de l’annulation de l’archivage", "241a9d368c292ddb": "Ce fil est le seul associé à ce worktree :", "4cce2f30bd1d0d0f": "Supprimer aussi le worktree ?", @@ -4711,6 +4727,8 @@ "16aa57835b1ee840": "Une réponse à une approbation est déjà en cours, votre message n’a donc pas été envoyé.", "cdfced17f0576311": "Une autre approbation est arrivée, votre message n’a donc pas été envoyé.", "08a5b53649784fe8": "{count, plural, one {Le prompt dépasse de {excess} caractère la limite de {limit} caractères. Raccourcissez-le ou divisez-le avant l’envoi.} other {Le prompt dépasse de {excess} caractères la limite de {limit} caractères. Raccourcissez-le ou divisez-le avant l’envoi.}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "La copie de l’instantané nécessite une connexion sécurisée du navigateur.", "4bd2f44a35e591ca": "Ouvrir dans le navigateur du système", "202e13f15a3dcd30": "Copier le lien", @@ -7503,6 +7521,9 @@ "92785adb251da88c": "Réinitialiser la largeur de la discussion à la valeur par défaut", "4d457bcce0c0e272": "Largeur de la discussion", "81f3a196537bbee0": "Confortable (par défaut)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "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", "14bf40f765172a50": "Affichage de l’effort", @@ -10038,6 +10059,7 @@ "4b46043fd3700c17": "Afficher les skills dans le menu slash", "2407d5d61e7f7206": "Zone de saisie en texte enrichi", "64b8fd2c284c3137": "Raccourci d’envoi", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "Comportement des relances", "425021487583cf8a": "Ouvrir les sous-agents et discussions annexes dans", "856812e7e1fc445e": "Appels d’outils dans la discussion", @@ -10086,6 +10108,8 @@ "761ac81a418bd87d": "{modifierLabel} + Enter toujours", "3a6fb236cd3f521b": "Affiche le Markdown mis en forme pendant la saisie.", "f9251f92691626cd": "Réinitialiser la zone de saisie en texte enrichi à la valeur par défaut", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Choisissez quand Enter envoie un prompt ou insère une nouvelle ligne", "147e9953f6fc550d": "Réinitialiser le raccourci d’envoi à la valeur par défaut", "4a1201bd18283940": "Inclut aussi les skills dans le menu de commandes /. Les skills apparaissent toujours quand vous tapez $.", @@ -11758,6 +11782,7 @@ "d8d6cfd630cff22d": "rouge vert bleu orange ajouts suppressions modifications compteurs palette daltonien", "717e49895cfee1c7": "large pleine largeur colonne mise en page messages zone de saisie écran", "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", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "effort de raisonnement réflexion barres graphique mot libellé niveau zone de saisie", "6113c17109ee0d57": "latex tex katex équations formules markdown", "8c8364d44fa28d22": "dev nightly dernière canal illustration pastille libellé masquer aucun", @@ -11819,6 +11844,7 @@ "7d0ab4cf50686d31": "proactif ouvrir automatiquement diff pull request pr panneau de droite agent fin", "5256dd2ed3a24332": "commande menu dollar $ slash /", "ade91c8927c48175": "zone de saisie texte enrichi tiptap gras italique markdown stylé wysiwyg", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "entrée retour commande ctrl multiligne prompt nouvelle ligne zone de saisie", "9d1013084c46ecce": "file d’attente réorienter tour en cours envoyer comportement par défaut zone de saisie", "e5e7f5e1fb1f2e4c": "sous-agent discussion annexe fil associé clic panneau droit panneau latéral vue principale commande ctrl clic du milieu", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 188d63866545c..be79ceafc6b90 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, other {テーマを {count} 回確認しようとしました}}", "a16ae702cbb60dde": "{count, plural, other {テーマを {count} 回設定しました}}", "978b4b05bea775d1": "{count, plural, other {テーマを {count} 回設定しようとしました}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, other {リンク済みの環境を {count} 回一覧表示しました}}", "78d34854295169a7": "{count, plural, other {リンク済みの環境を {count} 回一覧表示しようとしました}}", "07edf9b32bf1f437": "{count, plural, other {ブラウザーを {count} 回使用しました}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "OpenAI にフィードバックを送信しました。\n\nスレッド ID: `{feedbackId}`", "de62133b5898fab1": "OpenAI にフィードバックを送信できませんでした。\n\n{errorMessage}", "0bed322f6071f4da": "エラーが発生しました。", + "448735c0084132f5": "もう一度お試しください。", "78f82fef9e0c8661": "リポジトリ", "2360ad0503c2a0a8": "リポジトリを選択", "05b16c85cb1e18bd": "リポジトリなし", @@ -1796,9 +1801,10 @@ "2eb493c9e7a5fe9a": "プルリクエストをスレッドにリンク", "abbbacfec60327d7": "リンクされた項目を表示", "67f5b13c3c7bcd40": "ゲストと共有", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "エージェントのセッションを再起動", - "963d099509eabcd6": "エージェントのセッションが再起動されます", - "1d384d4fe7888a09": "次のメッセージで新しいセッションが始まります。", "e4b61c891fed297e": "ファイルに移動", "d2ccdb8cd3297212": "プロジェクトを追加", "594bcbef04093f72": "WSL のフォルダーを開く", @@ -1808,6 +1814,8 @@ "a0cc19e60dd99851": "使用量を開く", "46694969044eee98": "次のワークスペース領域にフォーカス", "0a1011328ba42eef": "前のワークスペース領域にフォーカス", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "設定を開く", "1d17dc60c59e0524": "プロジェクトのピン留めを解除", "5cfaaa20c460c328": "プロジェクトをピン留め", @@ -1906,7 +1914,6 @@ "8bf65a425f50d140": "ライト", "d604bc5cf3386f00": "ダーク", "4758dde317babc14": "テーマの選択を保存できませんでした", - "448735c0084132f5": "もう一度お試しください。", "e1ef4197dc810bab": "ライトモード用", "002fa063deda988d": "ダークモード用", "9c6962c66efa5668": "外観を変更", @@ -2764,6 +2771,8 @@ "3364346f40934e88": "すべてのプロジェクトを表示", "666f3ac177c116b6": "{project} で絞り込み", "1385e2d8bd696370": "プロジェクトに変換", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "自動対応済みの動作", "39eb35d54cacd314": "設定に従う", "65e3725b1c46b314": "しない", @@ -2864,6 +2873,9 @@ "c7d7f42240dac324": "この環境はこのプルリクエストのリンクをサポートしていません。", "6096ad21ed076d33": "リンクの更新が中断されました。", "c80f181fe72924a9": "プロジェクトを削除できませんでした", + "963d099509eabcd6": "エージェントのセッションが再起動されます", + "1d384d4fe7888a09": "次のメッセージで新しいセッションが始まります。", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "プロジェクトなしで開始できませんでした", "8d51135cc55089f9": "モデルの設定は保存されませんでした", "c7193961d383be05": "保存されたモデルの設定を読み込めませんでした。もう一度お試しください。", @@ -2898,6 +2910,10 @@ "08f5b642746eebbe": "スレッド「{title}」のピン留めを解除しますか?", "bc574b901d06687c": "スレッドがピン留めセクションから移動します。", "b4f6775203e9d0bc": "スレッドは削除されましたが、移動に失敗しました", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "アーカイブを元に戻せませんでした", "241a9d368c292ddb": "このワークツリーにリンクされているのは、このスレッドだけです:", "4cce2f30bd1d0d0f": "ワークツリーも削除しますか?", @@ -4700,6 +4716,8 @@ "16aa57835b1ee840": "承認への応答がすでに進行中のため、メッセージは送信されませんでした。", "cdfced17f0576311": "別の承認が届いたため、メッセージは送信されませんでした。", "08a5b53649784fe8": "{count, plural, other {プロンプトが {limit} 文字の上限を {excess} 文字超えています。送信する前に短くするか分割してください。}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "スナップショットのコピーには安全なブラウザー接続が必要です。", "4bd2f44a35e591ca": "システムのブラウザーで開く", "202e13f15a3dcd30": "リンクをコピー", @@ -7468,6 +7486,9 @@ "92785adb251da88c": "チャットの幅をデフォルトにリセット", "4d457bcce0c0e272": "チャットの幅", "81f3a196537bbee0": "標準 (デフォルト)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "e79e5388f669495f": "入力欄での推論レベルの表示を、名前 (High など) またはバーから選択します。", "7f0365c7e4e8bcbf": "推論レベルの表示をデフォルトにリセット", "14bf40f765172a50": "推論レベルの表示", @@ -9991,6 +10012,7 @@ "4b46043fd3700c17": "スラッシュメニューにスキルを表示", "2407d5d61e7f7206": "リッチテキスト入力欄", "64b8fd2c284c3137": "送信ショートカット", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "フォローアップの動作", "425021487583cf8a": "サブエージェントとサイドチャットを開く場所", "856812e7e1fc445e": "チャット内のツール呼び出し", @@ -10039,6 +10061,8 @@ "761ac81a418bd87d": "常に {modifierLabel} + Enter", "3a6fb236cd3f521b": "入力中に Markdown を整形して表示します。", "f9251f92691626cd": "リッチテキスト入力欄をデフォルトにリセット", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Enter でプロンプトを送信するか改行するかを選択します", "147e9953f6fc550d": "送信ショートカットをデフォルトにリセット", "4a1201bd18283940": "/ コマンドメニューにもスキルを表示します。$ を入力したときは常にスキルが表示されます。", @@ -11709,6 +11733,7 @@ "d8d6cfd630cff22d": "赤 緑 青 オレンジ 追加 削除 変更 件数 パレット 色覚 colorblind", "717e49895cfee1c7": "幅 全幅 列 レイアウト メッセージ 入力欄 モニター wide width", "88365077fd80787b": "カスタマイズ 表示 非表示 パネル カード 環境 エディター スクリプト ブランチ プルリクエスト Git 変更 サーバー オートメーション 系譜 使用量 上限 5 時間 週間 クォータ トークン コンテキストウィンドウ panel card", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "推論レベル 思考 バー グラフ 単語 ラベル レベル 入力欄 reasoning effort", "6113c17109ee0d57": "LaTeX TeX KaTeX 数式 方程式 Markdown latex math", "8c8364d44fa28d22": "dev nightly latest チャンネル アートワーク ピル ラベル 非表示 なし channel", @@ -11770,6 +11795,7 @@ "7d0ab4cf50686d31": "自動 開く 差分 プルリクエスト PR 右パネル エージェント 完了 proactive", "5256dd2ed3a24332": "コマンドメニュー ドル $ スラッシュ / command menu", "ade91c8927c48175": "入力欄 リッチテキスト Tiptap 太字 斜体 Markdown スタイル WYSIWYG rich text", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "Enter Return Command Ctrl 複数行 プロンプト 改行 入力欄 shortcut", "9d1013084c46ecce": "キュー 軌道修正 実行中 ターン 送信 デフォルト 動作 入力欄 queue steer", "e5e7f5e1fb1f2e4c": "サブエージェント サイドチャット リンクされたスレッド クリック 右パネル サイドパネル メインビュー コマンド ctrl 中クリック", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fd4f1a5af2fc8..a216645f0298b 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, other {테마 확인 {count}회 시도함}}", "a16ae702cbb60dde": "{count, plural, other {테마 {count}회 설정함}}", "978b4b05bea775d1": "{count, plural, other {테마 설정 {count}회 시도함}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, other {연결된 환경 목록 {count}회 조회함}}", "78d34854295169a7": "{count, plural, other {연결된 환경 목록 조회 {count}회 시도함}}", "07edf9b32bf1f437": "{count, plural, other {브라우저 {count}번 사용함}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "OpenAI에 피드백을 보냈습니다.\n\n스레드 ID: `{feedbackId}`", "de62133b5898fab1": "OpenAI에 피드백을 보낼 수 없습니다.\n\n{errorMessage}", "0bed322f6071f4da": "오류가 발생했습니다.", + "448735c0084132f5": "다시 시도하세요.", "78f82fef9e0c8661": "저장소", "2360ad0503c2a0a8": "저장소 선택", "05b16c85cb1e18bd": "저장소 없음", @@ -1796,9 +1801,10 @@ "2eb493c9e7a5fe9a": "스레드에 풀 리퀘스트 연결", "abbbacfec60327d7": "연결된 항목 표시", "67f5b13c3c7bcd40": "게스트와 공유", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "에이전트 세션 다시 시작", - "963d099509eabcd6": "에이전트 세션이 다시 시작됩니다", - "1d384d4fe7888a09": "다음 메시지부터 새 세션이 시작됩니다.", "e4b61c891fed297e": "파일로 이동", "d2ccdb8cd3297212": "프로젝트 추가", "594bcbef04093f72": "WSL 폴더 열기", @@ -1808,6 +1814,8 @@ "a0cc19e60dd99851": "사용량 열기", "46694969044eee98": "다음 작업 영역으로 포커스 이동", "0a1011328ba42eef": "이전 작업 영역으로 포커스 이동", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "설정 열기", "1d17dc60c59e0524": "프로젝트 고정 해제", "5cfaaa20c460c328": "프로젝트 고정", @@ -1908,7 +1916,6 @@ "8bf65a425f50d140": "라이트", "d604bc5cf3386f00": "다크", "4758dde317babc14": "테마 선택을 저장할 수 없습니다", - "448735c0084132f5": "다시 시도하세요.", "e1ef4197dc810bab": "라이트 모드용", "002fa063deda988d": "다크 모드용", "9c6962c66efa5668": "모양 변경", @@ -2765,6 +2772,8 @@ "3364346f40934e88": "모든 프로젝트 표시", "666f3ac177c116b6": "{project}(으)로 필터", "1385e2d8bd696370": "프로젝트로 전환", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "자동 정리 동작", "39eb35d54cacd314": "설정 따르기", "65e3725b1c46b314": "안 함", @@ -2865,6 +2874,9 @@ "c7d7f42240dac324": "이 환경은 이 풀 리퀘스트 연결을 지원하지 않습니다.", "6096ad21ed076d33": "연결 업데이트가 중단되었습니다.", "c80f181fe72924a9": "프로젝트를 제거하지 못했습니다", + "963d099509eabcd6": "에이전트 세션이 다시 시작됩니다", + "1d384d4fe7888a09": "다음 메시지부터 새 세션이 시작됩니다.", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "프로젝트 없이 시작할 수 없습니다", "8d51135cc55089f9": "모델 환경설정이 저장되지 않음", "c7193961d383be05": "저장된 모델 환경설정을 불러올 수 없습니다. 다시 시도하세요.", @@ -2899,6 +2911,10 @@ "08f5b642746eebbe": "스레드 \"{title}\"의 고정을 해제할까요?", "bc574b901d06687c": "스레드가 고정 섹션에서 빠집니다.", "b4f6775203e9d0bc": "스레드를 삭제했지만 이동하지 못했습니다", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "보관을 실행 취소하지 못했습니다", "241a9d368c292ddb": "이 워크트리에 연결된 스레드는 이것뿐입니다:", "4cce2f30bd1d0d0f": "워크트리도 삭제할까요?", @@ -4697,6 +4713,8 @@ "16aa57835b1ee840": "이미 승인에 응답하는 중이어서 메시지를 보내지 않았습니다.", "cdfced17f0576311": "다른 승인 요청이 도착해 메시지를 보내지 않았습니다.", "08a5b53649784fe8": "{count, plural, other {프롬프트가 {limit}자 제한을 {excess}자 초과합니다. 보내기 전에 줄이거나 나누세요.}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "스냅샷을 복사하려면 보안 브라우저 연결이 필요합니다.", "4bd2f44a35e591ca": "시스템 브라우저에서 열기", "202e13f15a3dcd30": "링크 복사", @@ -7469,6 +7487,9 @@ "92785adb251da88c": "채팅 너비 기본값으로 재설정", "4d457bcce0c0e272": "채팅 너비", "81f3a196537bbee0": "보통(기본값)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "e79e5388f669495f": "입력창에서 추론 수준을 High 같은 이름 또는 막대로 표시합니다.", "7f0365c7e4e8bcbf": "추론 수준 표시 기본값으로 재설정", "14bf40f765172a50": "추론 수준 표시", @@ -9993,6 +10014,7 @@ "4b46043fd3700c17": "슬래시 메뉴에 스킬 표시", "2407d5d61e7f7206": "서식 있는 텍스트 입력창", "64b8fd2c284c3137": "보내기 단축키", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "후속 메시지 동작", "425021487583cf8a": "서브에이전트와 사이드 채팅을 여는 위치", "856812e7e1fc445e": "채팅의 도구 호출", @@ -10041,6 +10063,8 @@ "761ac81a418bd87d": "항상 {modifierLabel} + Enter", "3a6fb236cd3f521b": "입력하는 동안 서식이 적용된 Markdown을 표시합니다.", "f9251f92691626cd": "서식 있는 텍스트 입력창 기본값으로 재설정", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Enter 키로 프롬프트를 보낼지 새 줄을 넣을지 선택합니다", "147e9953f6fc550d": "보내기 단축키 기본값으로 재설정", "4a1201bd18283940": "/ 명령 메뉴에도 스킬을 포함합니다. $를 입력하면 스킬이 항상 표시됩니다.", @@ -11705,6 +11729,7 @@ "d8d6cfd630cff22d": "빨간색 녹색 파란색 주황색 추가 삭제 변경 개수 팔레트 색맹", "717e49895cfee1c7": "넓게 전체 너비 열 레이아웃 메시지 입력창 모니터", "88365077fd80787b": "사용자 지정 표시 숨기기 패널 카드 환경 편집기 스크립트 브랜치 풀 리퀘스트 git 변경 사항 서버 자동화 계보 사용량 한도 5시간 주간 할당량 토큰 컨텍스트 창", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "추론 수준 생각 막대 그래프 단어 레이블 수준 입력창", "6113c17109ee0d57": "latex tex katex 수식 공식 마크다운", "8c8364d44fa28d22": "dev nightly latest 채널 아트워크 알약 레이블 숨기기 없음", @@ -11766,6 +11791,7 @@ "7d0ab4cf50686d31": "자동 열기 변경 사항 풀 리퀘스트 PR 오른쪽 패널 에이전트 완료", "5256dd2ed3a24332": "명령 메뉴 달러 $ 슬래시 /", "ade91c8927c48175": "입력창 서식 있는 텍스트 tiptap 굵게 기울임 마크다운 스타일 wysiwyg", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "enter return command ctrl 여러 줄 프롬프트 새 줄 입력창", "9d1013084c46ecce": "대기열 방향 조정 실행 중 턴 보내기 기본 동작 입력창", "e5e7f5e1fb1f2e4c": "서브에이전트 사이드 채팅 연결된 스레드 클릭 오른쪽 패널 사이드 패널 메인 보기 커맨드 ctrl 가운데 클릭", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f8450e8032e5f..c2ca3ff2c45d9 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Tentou verificar os temas {count} vez} other {Tentou verificar os temas {count} vezes}}", "a16ae702cbb60dde": "{count, plural, one {Definiu o tema {count} vez} other {Definiu o tema {count} vezes}}", "978b4b05bea775d1": "{count, plural, one {Tentou definir o tema {count} vez} other {Tentou definir o tema {count} vezes}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Listou os ambientes vinculados {count} vez} other {Listou os ambientes vinculados {count} vezes}}", "78d34854295169a7": "{count, plural, one {Tentou listar os ambientes vinculados {count} vez} other {Tentou listar os ambientes vinculados {count} vezes}}", "07edf9b32bf1f437": "{count, plural, one {Usou o navegador {count} vez} other {Usou o navegador {count} vezes}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Feedback enviado para a OpenAI.\n\nID da thread: `{feedbackId}`", "de62133b5898fab1": "Não foi possível enviar o feedback para a OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Ocorreu um erro.", + "448735c0084132f5": "Tente novamente.", "78f82fef9e0c8661": "Repositórios", "2360ad0503c2a0a8": "Escolher repositórios", "05b16c85cb1e18bd": "Nenhum repositório", @@ -1797,9 +1802,10 @@ "2eb493c9e7a5fe9a": "Vincular pull request à thread", "abbbacfec60327d7": "Mostrar itens vinculados", "67f5b13c3c7bcd40": "Compartilhar com convidado", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "Reiniciar a sessão do agente", - "963d099509eabcd6": "A sessão do agente será reiniciada", - "1d384d4fe7888a09": "Sua próxima mensagem inicia uma nova sessão.", "e4b61c891fed297e": "Ir para arquivo", "d2ccdb8cd3297212": "Adicionar projeto", "594bcbef04093f72": "Abrir pasta do WSL", @@ -1809,6 +1815,8 @@ "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Focar a próxima área do workspace", "0a1011328ba42eef": "Focar a área anterior do workspace", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "Abrir configurações", "1d17dc60c59e0524": "Desafixar projeto", "5cfaaa20c460c328": "Fixar projeto", @@ -1908,7 +1916,6 @@ "8bf65a425f50d140": "Claro", "d604bc5cf3386f00": "Escuro", "4758dde317babc14": "Não foi possível salvar a seleção de tema", - "448735c0084132f5": "Tente novamente.", "e1ef4197dc810bab": "Para o modo claro", "002fa063deda988d": "Para o modo escuro", "9c6962c66efa5668": "Mudar aparência", @@ -2766,6 +2773,8 @@ "3364346f40934e88": "Mostrar todos os projetos", "666f3ac177c116b6": "Filtrar por {project}", "1385e2d8bd696370": "Transformar em projeto", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "Comportamento da conclusão automática", "39eb35d54cacd314": "Seguir as configurações", "65e3725b1c46b314": "Nunca", @@ -2866,6 +2875,9 @@ "c7d7f42240dac324": "Este ambiente não permite vincular este pull request.", "6096ad21ed076d33": "Atualização do vínculo interrompida.", "c80f181fe72924a9": "Falha ao remover o projeto", + "963d099509eabcd6": "A sessão do agente será reiniciada", + "1d384d4fe7888a09": "Sua próxima mensagem inicia uma nova sessão.", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "Não foi possível começar sem projeto", "8d51135cc55089f9": "Preferências de modelo não salvas", "c7193961d383be05": "Não foi possível carregar as preferências de modelo salvas. Tente novamente.", @@ -2900,6 +2912,10 @@ "08f5b642746eebbe": "Desafixar a thread \"{title}\"?", "bc574b901d06687c": "A thread sairá da seção de fixadas.", "b4f6775203e9d0bc": "Thread excluída, mas a navegação falhou", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "Falha ao desfazer o arquivamento", "241a9d368c292ddb": "Esta é a única thread vinculada a este worktree:", "4cce2f30bd1d0d0f": "Excluir o worktree também?", @@ -4710,6 +4726,8 @@ "16aa57835b1ee840": "Uma aprovação já está sendo respondida, então sua mensagem não foi enviada.", "cdfced17f0576311": "Chegou outra aprovação, então sua mensagem não foi enviada.", "08a5b53649784fe8": "{count, plural, one {O prompt tem {excess} caractere acima do limite de {limit}. Encurte ou divida antes de enviar.} other {O prompt tem {excess} caracteres acima do limite de {limit}. Encurte ou divida antes de enviar.}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "Copiar o snapshot exige uma conexão segura no navegador.", "4bd2f44a35e591ca": "Abrir no navegador do sistema", "202e13f15a3dcd30": "Copiar link", @@ -7502,6 +7520,9 @@ "92785adb251da88c": "Redefinir a largura do chat para o padrão", "4d457bcce0c0e272": "Largura do chat", "81f3a196537bbee0": "Confortável (padrão)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "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", "14bf40f765172a50": "Exibição do esforço", @@ -10038,6 +10059,7 @@ "4b46043fd3700c17": "Mostrar skills no menu de barra", "2407d5d61e7f7206": "Editor de texto formatado", "64b8fd2c284c3137": "Atalho de envio", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "Comportamento de mensagens de acompanhamento", "425021487583cf8a": "Abrir subagentes e chats paralelos em", "856812e7e1fc445e": "Chamadas de ferramentas no chat", @@ -10086,6 +10108,8 @@ "761ac81a418bd87d": "{modifierLabel} + Enter sempre", "3a6fb236cd3f521b": "Mostra o Markdown formatado enquanto você digita.", "f9251f92691626cd": "Redefinir o editor de mensagens com rich text para o padrão", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Escolha quando Enter envia um prompt ou insere uma nova linha", "147e9953f6fc550d": "Redefinir o atalho de envio para o padrão", "4a1201bd18283940": "Inclui também as skills no menu de comandos /. As skills sempre aparecem quando você digita $.", @@ -11758,6 +11782,7 @@ "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", "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", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "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", "8c8364d44fa28d22": "dev nightly latest canal arte pílula rótulo ocultar nenhum", @@ -11819,6 +11844,7 @@ "7d0ab4cf50686d31": "proativo abrir automaticamente diff pull request pr painel direito agente conclusão", "5256dd2ed3a24332": "menu de comandos cifrão $ barra /", "ade91c8927c48175": "editor de mensagens rich text tiptap negrito itálico markdown estilizado wysiwyg", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "enter return command ctrl várias linhas prompt nova linha editor de mensagens", "9d1013084c46ecce": "fila enfileirar direcionar turno em execução enviar comportamento padrão editor de mensagens", "e5e7f5e1fb1f2e4c": "subagente chat paralelo thread vinculada clique painel direito painel lateral visualização principal comando ctrl clique do meio", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 75b7db757cf04..260eef3a8ffcc 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Попытка проверить темы: {count} раз} few {Попытка проверить темы: {count} раза} many {Попытка проверить темы: {count} раз} other {Попытка проверить темы: {count} раза}}", "a16ae702cbb60dde": "{count, plural, one {Тема задана {count} раз} few {Тема задана {count} раза} many {Тема задана {count} раз} other {Тема задана {count} раза}}", "978b4b05bea775d1": "{count, plural, one {Попытка задать тему: {count} раз} few {Попытка задать тему: {count} раза} many {Попытка задать тему: {count} раз} other {Попытка задать тему: {count} раза}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Список привязанных окружений получен {count} раз} few {Список привязанных окружений получен {count} раза} many {Список привязанных окружений получен {count} раз} other {Список привязанных окружений получен {count} раза}}", "78d34854295169a7": "{count, plural, one {Попытка получить список привязанных окружений: {count} раз} few {Попытка получить список привязанных окружений: {count} раза} many {Попытка получить список привязанных окружений: {count} раз} other {Попытка получить список привязанных окружений: {count} раза}}", "07edf9b32bf1f437": "{count, plural, one {Браузер использован {count} раз} few {Браузер использован {count} раза} many {Браузер использован {count} раз} other {Браузер использован {count} раза}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Отзыв отправлен в OpenAI.\n\nID треда: `{feedbackId}`", "de62133b5898fab1": "Не удалось отправить отзыв в OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Произошла ошибка.", + "448735c0084132f5": "Повторите попытку.", "78f82fef9e0c8661": "Репозитории", "2360ad0503c2a0a8": "Выбрать репозитории", "05b16c85cb1e18bd": "Нет репозиториев", @@ -1797,9 +1802,10 @@ "2eb493c9e7a5fe9a": "Привязать пул-реквест к треду", "abbbacfec60327d7": "Показать привязанные элементы", "67f5b13c3c7bcd40": "Поделиться с гостем", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "Перезапустить сеанс агента", - "963d099509eabcd6": "Сеанс агента будет перезапущен", - "1d384d4fe7888a09": "Следующее сообщение начнёт новый сеанс.", "e4b61c891fed297e": "Перейти к файлу", "d2ccdb8cd3297212": "Добавить проект", "594bcbef04093f72": "Открыть папку WSL", @@ -1809,6 +1815,8 @@ "a0cc19e60dd99851": "Открыть использование", "46694969044eee98": "Фокус на следующую панель рабочей области", "0a1011328ba42eef": "Фокус на предыдущую панель рабочей области", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "Открыть настройки", "1d17dc60c59e0524": "Открепить проект", "5cfaaa20c460c328": "Закрепить проект", @@ -1908,7 +1916,6 @@ "8bf65a425f50d140": "Светлая", "d604bc5cf3386f00": "Тёмная", "4758dde317babc14": "Не удалось сохранить выбор темы", - "448735c0084132f5": "Повторите попытку.", "e1ef4197dc810bab": "Для светлого режима", "002fa063deda988d": "Для тёмного режима", "9c6962c66efa5668": "Изменить оформление", @@ -2766,6 +2773,8 @@ "3364346f40934e88": "Показать все проекты", "666f3ac177c116b6": "Фильтр: {project}", "1385e2d8bd696370": "Превратить в проект", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "Авторазбор", "39eb35d54cacd314": "Как в настройках", "65e3725b1c46b314": "Никогда", @@ -2866,6 +2875,9 @@ "c7d7f42240dac324": "Это окружение не поддерживает привязку этого пул-реквеста.", "6096ad21ed076d33": "Обновление привязки прервано.", "c80f181fe72924a9": "Не удалось удалить проект", + "963d099509eabcd6": "Сеанс агента будет перезапущен", + "1d384d4fe7888a09": "Следующее сообщение начнёт новый сеанс.", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "Не удалось начать без проекта", "8d51135cc55089f9": "Настройки моделей не сохранены", "c7193961d383be05": "Не удалось загрузить сохранённые настройки моделей. Повторите попытку.", @@ -2900,6 +2912,10 @@ "08f5b642746eebbe": "Открепить тред «{title}»?", "bc574b901d06687c": "Тред будет убран из раздела закреплённых.", "b4f6775203e9d0bc": "Тред удалён, но переход не удался", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "Не удалось отменить архивацию", "241a9d368c292ddb": "Только этот тред связан с этим рабочим деревом:", "4cce2f30bd1d0d0f": "Удалить и рабочее дерево?", @@ -4710,6 +4726,8 @@ "16aa57835b1ee840": "На подтверждение уже отвечают, поэтому ваше сообщение не отправлено.", "cdfced17f0576311": "Пришло другое подтверждение, поэтому ваше сообщение не отправлено.", "08a5b53649784fe8": "{count, plural, one {Промпт превышает лимит в {limit} символов на {excess} символ. Сократите или разделите его перед отправкой.} few {Промпт превышает лимит в {limit} символов на {excess} символа. Сократите или разделите его перед отправкой.} many {Промпт превышает лимит в {limit} символов на {excess} символов. Сократите или разделите его перед отправкой.} other {Промпт превышает лимит в {limit} символов на {excess} символа. Сократите или разделите его перед отправкой.}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "Для копирования снимка нужно защищённое подключение браузера.", "4bd2f44a35e591ca": "Открыть в системном браузере", "202e13f15a3dcd30": "Копировать ссылку", @@ -7502,6 +7520,9 @@ "92785adb251da88c": "Сбросить ширину чата к значению по умолчанию", "4d457bcce0c0e272": "Ширина чата", "81f3a196537bbee0": "Удобная (по умолчанию)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "e79e5388f669495f": "Показывать усилие рассуждения в поле ввода названием, например «Высокое», или полосками.", "7f0365c7e4e8bcbf": "Сбросить отображение усилия к значению по умолчанию", "14bf40f765172a50": "Отображение усилия", @@ -10041,6 +10062,7 @@ "4b46043fd3700c17": "Показывать навыки в меню /", "2407d5d61e7f7206": "Поле ввода с форматированием", "64b8fd2c284c3137": "Сочетание для отправки", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "Поведение дополнительных сообщений", "425021487583cf8a": "Открывать субагентов и боковые чаты в", "856812e7e1fc445e": "Вызовы инструментов в чате", @@ -10089,6 +10111,8 @@ "761ac81a418bd87d": "Всегда {modifierLabel} + Enter", "3a6fb236cd3f521b": "Показывать форматированный Markdown при вводе.", "f9251f92691626cd": "Сбросить поле ввода с форматированием к значению по умолчанию", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Когда Enter отправляет промпт, а когда вставляет новую строку", "147e9953f6fc550d": "Сбросить сочетание для отправки к значению по умолчанию", "4a1201bd18283940": "Также показывать навыки в меню команд /. Навыки всегда появляются при вводе $.", @@ -11759,6 +11783,7 @@ "d8d6cfd630cff22d": "красный зелёный синий оранжевый добавления удаления изменения счётчики палитра дальтонизм", "717e49895cfee1c7": "широкий полная ширина колонка раскладка сообщения поле ввода монитор", "88365077fd80787b": "настроить показать скрыть панель карточка окружение редактор скрипты ветка пул-реквест git изменения серверы автоматизации происхождение использование лимиты 5 часов неделя квота токены контекстное окно", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "усилие рассуждений размышление полосы график слово метка уровень поле ввода", "6113c17109ee0d57": "latex tex katex уравнения формулы markdown", "8c8364d44fa28d22": "dev nightly latest канал оформление метка скрыть нет", @@ -11820,6 +11845,7 @@ "7d0ab4cf50686d31": "заблаговременно автоматически открывать дифф пул-реквест pr правая панель агент завершение", "5256dd2ed3a24332": "меню команд доллар $ слеш /", "ade91c8927c48175": "поле ввода форматирование tiptap жирный курсив markdown стили wysiwyg", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "enter return command ctrl многострочный промпт новая строка поле ввода", "9d1013084c46ecce": "очередь корректировка выполняющийся ход отправить поведение по умолчанию поле ввода", "e5e7f5e1fb1f2e4c": "субагент боковой чат привязанный тред щелчок правая панель боковая панель основное окно command ctrl средняя кнопка", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6a3525acc8636..03ce8bb145691 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, one {Försökte kontrollera teman {count} gång} other {Försökte kontrollera teman {count} gånger}}", "a16ae702cbb60dde": "{count, plural, one {Valde tema {count} gång} other {Valde tema {count} gånger}}", "978b4b05bea775d1": "{count, plural, one {Försökte välja tema {count} gång} other {Försökte välja tema {count} gånger}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, one {Listade länkade miljöer {count} gång} other {Listade länkade miljöer {count} gånger}}", "78d34854295169a7": "{count, plural, one {Försökte lista länkade miljöer {count} gång} other {Försökte lista länkade miljöer {count} gånger}}", "07edf9b32bf1f437": "{count, plural, one {Använde webbläsaren {count} gång} other {Använde webbläsaren {count} gånger}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "Feedback skickad till OpenAI.\n\nTråd-ID: `{feedbackId}`", "de62133b5898fab1": "Kunde inte skicka feedback till OpenAI.\n\n{errorMessage}", "0bed322f6071f4da": "Ett fel uppstod.", + "448735c0084132f5": "Försök igen.", "78f82fef9e0c8661": "Repon", "2360ad0503c2a0a8": "Välj repon", "05b16c85cb1e18bd": "Inga repon", @@ -1797,9 +1802,10 @@ "2eb493c9e7a5fe9a": "Länka pull request till tråd", "abbbacfec60327d7": "Visa länkade objekt", "67f5b13c3c7bcd40": "Dela med gäst", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "Starta om agentsessionen", - "963d099509eabcd6": "Agentsessionen startas om", - "1d384d4fe7888a09": "Ditt nästa meddelande startar en ny session.", "e4b61c891fed297e": "Gå till fil", "d2ccdb8cd3297212": "Lägg till projekt", "594bcbef04093f72": "Öppna WSL-mapp", @@ -1809,6 +1815,8 @@ "a0cc19e60dd99851": "Öppna användning", "46694969044eee98": "Fokusera nästa område i arbetsytan", "0a1011328ba42eef": "Fokusera föregående område i arbetsytan", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "Öppna inställningar", "1d17dc60c59e0524": "Lossa projekt", "5cfaaa20c460c328": "Fäst projekt", @@ -1908,7 +1916,6 @@ "8bf65a425f50d140": "Ljust", "d604bc5cf3386f00": "Mörkt", "4758dde317babc14": "Kunde inte spara temavalet", - "448735c0084132f5": "Försök igen.", "e1ef4197dc810bab": "För ljust läge", "002fa063deda988d": "För mörkt läge", "9c6962c66efa5668": "Ändra utseende", @@ -2766,6 +2773,8 @@ "3364346f40934e88": "Visa alla projekt", "666f3ac177c116b6": "Filtrera efter {project}", "1385e2d8bd696370": "Gör om till projekt", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "Beteende för automatisk markering som klar", "39eb35d54cacd314": "Följ inställningarna", "65e3725b1c46b314": "Aldrig", @@ -2866,6 +2875,9 @@ "c7d7f42240dac324": "Den här miljön stöder inte länkning av den här pull requesten.", "6096ad21ed076d33": "Uppdateringen av länken avbröts.", "c80f181fe72924a9": "Det gick inte att ta bort projektet", + "963d099509eabcd6": "Agentsessionen startas om", + "1d384d4fe7888a09": "Ditt nästa meddelande startar en ny session.", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "Kunde inte starta utan ett projekt", "8d51135cc55089f9": "Modellinställningarna sparades inte", "c7193961d383be05": "Kunde inte läsa in sparade modellinställningar. Försök igen.", @@ -2900,6 +2912,10 @@ "08f5b642746eebbe": "Lossa tråden ”{title}”?", "bc574b901d06687c": "Det här flyttar tråden från dina fästa trådar.", "b4f6775203e9d0bc": "Tråden togs bort, men navigeringen misslyckades", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "Det gick inte att ångra arkiveringen", "241a9d368c292ddb": "Den här tråden är den enda som är länkad till den här worktree:n:", "4cce2f30bd1d0d0f": "Ta bort worktree:n också?", @@ -4711,6 +4727,8 @@ "16aa57835b1ee840": "Ett godkännande håller redan på att besvaras, så ditt meddelande skickades inte.", "cdfced17f0576311": "Ett annat godkännande kom in, så ditt meddelande skickades inte.", "08a5b53649784fe8": "{count, plural, one {Prompten är {excess} tecken över gränsen på {limit} tecken. Korta ned eller dela upp den innan du skickar.} other {Prompten är {excess} tecken över gränsen på {limit} tecken. Korta ned eller dela upp den innan du skickar.}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "Kopiering av ögonblicksbilder kräver en säker webbläsaranslutning.", "4bd2f44a35e591ca": "Öppna i systemets webbläsare", "202e13f15a3dcd30": "Kopiera länk", @@ -7508,6 +7526,9 @@ "92785adb251da88c": "Återställ chattbredd till standard", "4d457bcce0c0e272": "Chattbredd", "81f3a196537bbee0": "Bekväm (standard)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "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", "14bf40f765172a50": "Visning av ansträngning", @@ -10046,6 +10067,7 @@ "4b46043fd3700c17": "Visa färdigheter i snedstrecksmenyn", "2407d5d61e7f7206": "Inmatningsfält med formaterad text", "64b8fd2c284c3137": "Kortkommando för att skicka", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "Beteende för uppföljningar", "425021487583cf8a": "Öppna subagenter och sidochattar i", "856812e7e1fc445e": "Verktygsanrop i chatten", @@ -10094,6 +10116,8 @@ "761ac81a418bd87d": "Alltid {modifierLabel} + Enter", "3a6fb236cd3f521b": "Visa formaterad Markdown medan du skriver.", "f9251f92691626cd": "Återställ inmatningsfält med formaterad text till standard", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "Välj när Enter skickar en prompt eller infogar en ny rad", "147e9953f6fc550d": "Återställ kortkommando för att skicka till standard", "4a1201bd18283940": "Ta även med färdigheter i kommandomenyn /. Färdigheter visas alltid när du skriver $.", @@ -11766,6 +11790,7 @@ "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", "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", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "resonemang ansträngning tänkande staplar diagram ord etikett nivå inmatningsfält", "6113c17109ee0d57": "latex tex katex ekvationer formler markdown", "8c8364d44fa28d22": "dev nightly latest kanal grafik pill etikett dölj ingen", @@ -11827,6 +11852,7 @@ "7d0ab4cf50686d31": "proaktiv öppna automatiskt diff pull request pr högerpanel agent slutförd", "5256dd2ed3a24332": "kommandomeny dollar $ snedstreck /", "ade91c8927c48175": "inmatningsfält formaterad text tiptap fet kursiv markdown formaterad wysiwyg", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "enter retur command ctrl flera rader prompt ny rad inmatningsfält", "9d1013084c46ecce": "kö styr om pågående omgång skicka standardbeteende inmatningsfält", "e5e7f5e1fb1f2e4c": "subagent sidochatt länkad tråd klick högerpanel sidopanel huvudvy kommando ctrl mittenklick", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index af1ca50a064b3..3a5a1f20d2eec 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -288,6 +288,10 @@ "227120bfdd990e37": "{count, plural, other {尝试检查主题 {count} 次}}", "a16ae702cbb60dde": "{count, plural, other {已设置主题 {count} 次}}", "978b4b05bea775d1": "{count, plural, other {尝试设置主题 {count} 次}}", + "bce8bd2a6d0cf027": "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + "66e57246ed44f3a7": "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + "7828d4bbf0c9e95b": "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + "34747255bb7f542c": "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", "d533fcae02ad5016": "{count, plural, other {已列出关联的环境 {count} 次}}", "78d34854295169a7": "{count, plural, other {尝试列出关联的环境 {count} 次}}", "07edf9b32bf1f437": "{count, plural, other {已使用浏览器 {count} 次}}", @@ -813,6 +817,7 @@ "9aba95a61cc1b6e3": "已向 OpenAI 发送反馈。会话 ID:`{feedbackId}`", "de62133b5898fab1": "无法向 OpenAI 发送反馈。\n\n{errorMessage}", "0bed322f6071f4da": "发生错误。", + "448735c0084132f5": "请重试。", "78f82fef9e0c8661": "仓库", "2360ad0503c2a0a8": "选择仓库", "05b16c85cb1e18bd": "无仓库", @@ -1797,9 +1802,10 @@ "2eb493c9e7a5fe9a": "为会话关联 PR", "abbbacfec60327d7": "显示已关联项", "67f5b13c3c7bcd40": "与访客共享", + "9e335da3914219ef": "Move thread to...", + "0c271911b4353bd1": "Could not move thread", + "c61c29a8e3e4bb7e": "Move thread to machine...", "82da5b8b340217ac": "重启智能体会话", - "963d099509eabcd6": "智能体会话将重启", - "1d384d4fe7888a09": "你的下一条消息将以全新上下文开始。", "e4b61c891fed297e": "转到文件", "d2ccdb8cd3297212": "添加项目", "594bcbef04093f72": "打开 WSL 文件夹", @@ -1809,6 +1815,8 @@ "a0cc19e60dd99851": "打开用量", "46694969044eee98": "聚焦下一个工作区区域", "0a1011328ba42eef": "聚焦上一个工作区区域", + "9cc23815f968fc60": "Turn off vim mode", + "84bce7eeb6d810d2": "Turn on vim mode", "90896a7348c4e7ce": "打开设置", "1d17dc60c59e0524": "取消置顶项目", "5cfaaa20c460c328": "置顶项目", @@ -1909,7 +1917,6 @@ "8bf65a425f50d140": "浅色", "d604bc5cf3386f00": "深色", "4758dde317babc14": "无法保存主题选择", - "448735c0084132f5": "请重试。", "e1ef4197dc810bab": "用于浅色模式", "002fa063deda988d": "用于深色模式", "9c6962c66efa5668": "切换外观", @@ -2770,6 +2777,8 @@ "3364346f40934e88": "显示所有项目", "666f3ac177c116b6": "按 {project} 筛选", "1385e2d8bd696370": "转换为项目", + "f83a8e1234105a07": "Move to project", + "4fa3e627c850327e": "Move to machine", "fcf482cda9bf739f": "自动收尾行为", "39eb35d54cacd314": "跟随设置", "65e3725b1c46b314": "从不", @@ -2870,6 +2879,9 @@ "c7d7f42240dac324": "此环境不支持关联该 pull request。", "6096ad21ed076d33": "关联更新被中断。", "c80f181fe72924a9": "无法移除项目", + "963d099509eabcd6": "智能体会话将重启", + "1d384d4fe7888a09": "你的下一条消息将以全新上下文开始。", + "185ebb3287e9a1b0": "Unable to restart agent session", "e5765017baf14aae": "无法在没有项目的情况下开始", "8d51135cc55089f9": "模型偏好未保存", "c7193961d383be05": "无法加载已保存的模型偏好,请重试。", @@ -2904,6 +2916,10 @@ "08f5b642746eebbe": "取消置顶会话“{title}”?", "bc574b901d06687c": "这会将会话移出置顶区域。", "b4f6775203e9d0bc": "会话已删除,但跳转失败", + "50b4da8d06300c78": "Move \"{thread}\" to {project}?", + "38063dee3d39f749": "Move \"{thread}\" to {machine}?", + "be3d2e52c9310262": "Moved, but the original is still active on {machine}", + "f20e60f77223c2c3": "{error} The moved copy is on {machine}.", "2e48bc42b04612ab": "无法撤销归档", "241a9d368c292ddb": "此会话是唯一关联到该工作树的会话:", "4cce2f30bd1d0d0f": "同时删除工作树?", @@ -4717,6 +4733,8 @@ "16aa57835b1ee840": "正在回应另一个审批,所以你的消息没有发送。", "cdfced17f0576311": "又来了一个审批,所以你的消息没有发送。", "08a5b53649784fe8": "{count, plural, other {提示词超出 {limit} 个字符的限制 {excess} 个字符。请在发送前缩短或拆分。}}", + "b66426523869d0c2": "Vim mode on", + "9df3f34033216cac": "Vim mode off", "507265b36dfc57fd": "复制快照需要安全的浏览器连接。", "4bd2f44a35e591ca": "在系统浏览器中打开", "202e13f15a3dcd30": "复制链接", @@ -7517,6 +7535,9 @@ "92785adb251da88c": "重置聊天宽度为默认值", "4d457bcce0c0e272": "聊天宽度", "81f3a196537bbee0": "适中(默认)", + "2c846ef87869e62d": "Show the thread details card in threads where you haven't opened or closed it.", + "8db9a1093c4a9ed5": "Reset open thread details by default", + "92729a403d37c575": "Open thread details by default", "e79e5388f669495f": "在输入框中用名称(如 High)或条形显示推理强度。", "7f0365c7e4e8bcbf": "重置推理强度显示为默认值", "14bf40f765172a50": "推理强度显示", @@ -10054,6 +10075,7 @@ "4b46043fd3700c17": "在斜杠菜单中显示技能", "2407d5d61e7f7206": "富文本输入框", "64b8fd2c284c3137": "发送快捷键", + "5ebcecf2239612d1": "Vim mode", "6163f91bddf474ae": "追加消息行为", "425021487583cf8a": "子智能体和侧聊的打开位置", "856812e7e1fc445e": "聊天中的工具调用", @@ -10102,6 +10124,8 @@ "761ac81a418bd87d": "始终 {modifierLabel} + Enter", "3a6fb236cd3f521b": "输入时显示 Markdown 格式效果。", "f9251f92691626cd": "重置富文本输入框为默认值", + "297c247a9e06dbc5": "Edit prompts with Vim keys. Escape switches to normal mode.", + "27cab6f283ab2e53": "Reset vim mode to default", "b59ca5c465dbe742": "选择 Enter 是发送提示词还是插入换行", "147e9953f6fc550d": "重置发送快捷键为默认值", "4a1201bd18283940": "在 / 命令菜单中也显示技能。输入 $ 时始终会显示技能。", @@ -11783,6 +11807,7 @@ "d8d6cfd630cff22d": "红 绿 蓝 橙 新增 删除 更改 计数 调色板 色盲", "717e49895cfee1c7": "宽 全宽 列 布局 消息 输入框 显示器", "88365077fd80787b": "自定义 显示 隐藏 面板 卡片 环境 编辑器 脚本 分支 PR git 更改 服务器 自动化 谱系 用量 限制 5 小时 每周 配额 token 上下文窗口", + "250961f0478379a4": "show hide panel card new threads collapsed closed", "d561f74efa5f3920": "推理强度 思考 条形 图表 文字 标签 级别 输入框", "6113c17109ee0d57": "latex tex katex 方程 公式 markdown", "8c8364d44fa28d22": "dev nightly latest 渠道 插图 胶囊 标签 隐藏 无", @@ -11844,6 +11869,7 @@ "7d0ab4cf50686d31": "主动 自动打开 差异 PR pr 右侧面板 智能体 完成", "5256dd2ed3a24332": "命令 菜单 美元 $ 斜杠 /", "ade91c8927c48175": "输入框 富文本 tiptap 粗体 斜体 markdown 样式 所见即所得", + "43a479f9d9ddff18": "vim vi neovim modal normal insert keys keyboard composer editor", "34d74827c2a8b009": "enter 回车 command ctrl 多行 提示词 换行 输入框", "9d1013084c46ecce": "排队 引导 运行中 轮次 发送 默认行为 输入框", "e5e7f5e1fb1f2e4c": "子智能体 侧聊 关联会话 单击 右侧面板 侧边面板 主视图 command ctrl 中键单击", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 2b19b90cc28e3..bba920f4f40ac 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1876,6 +1876,25 @@ code { margin-bottom: 0; } +/* Vim normal mode draws a block over the character under the hidden caret. */ +.composer-tiptap[data-vim-mode="normal"] { + caret-color: transparent; +} + +.composer-tiptap[data-vim-mode="normal"]:focus .composer-vim-cursor { + background-color: var(--color-foreground); + color: var(--color-background); +} + +.composer-vim-cursor-empty { + display: inline-block; + min-width: 1ch; +} + +.composer-tiptap:not(:focus) .composer-vim-cursor-empty { + display: none; +} + .chat-markdown p, .chat-markdown ul, .chat-markdown ol, diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index fb6f719bb2346..cb1dc51670f16 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -18,6 +18,7 @@ import { isSidebarToggleShortcut, isTerminalNewShortcut, isTerminalSplitShortcut, + isTerminalToggleShortcut, resolveChatShortcutCommand, resolveShortcutCommand, shouldShowThreadJumpHintsForModifiers, @@ -300,6 +301,36 @@ describe("split/new/close terminal shortcuts", () => { }), ); }); + + it("toggles with Ctrl+` on every platform, even from the terminal, labelled by mod+j", () => { + const backtick = { key: "`", code: "Backquote" }; + // German layouts put a dead circumflex on the same physical key. + const germanBacktick = { key: "Dead", code: "Backquote" }; + for (const platform of ["MacIntel", "Win32", "Linux"]) { + for (const terminalFocus of [false, true]) { + for (const keys of [backtick, germanBacktick]) { + assert.isTrue( + isTerminalToggleShortcut( + event({ ...keys, ctrlKey: true }), + DEFAULT_RESOLVED_KEYBINDINGS, + { platform, context: { terminalFocus } }, + ), + ); + } + } + } + assert.isFalse( + isTerminalToggleShortcut( + event({ ...backtick, metaKey: true }), + DEFAULT_RESOLVED_KEYBINDINGS, + { platform: "MacIntel" }, + ), + ); + assert.strictEqual( + shortcutLabelForCommand(DEFAULT_RESOLVED_KEYBINDINGS, "terminal.toggle", "MacIntel"), + "⌘J", + ); + }); }); describe("shortcutLabelForCommand", () => { diff --git a/apps/web/src/lib/appControl.ts b/apps/web/src/lib/appControl.ts new file mode 100644 index 0000000000000..5befbd12c554b --- /dev/null +++ b/apps/web/src/lib/appControl.ts @@ -0,0 +1,122 @@ +import { EnvironmentRegistry } from "@t3tools/client-runtime/connection"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { request, subscribeDynamic } from "@t3tools/client-runtime/rpc"; +import { + type AppAction, + type AppCommand, + type AppControlResult, + type AppDestination, + EnvironmentId, + VIEW_ONLY_APP_COMMANDS, + WS_METHODS, +} from "@t3tools/contracts"; +import type { AnyRouter, NavigateOptions } from "@tanstack/react-router"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import { useComposerDraftStore } from "../composerDraftStore"; +import { readPullRequestListPreferences } from "../components/pullRequest/pullRequestListPreferences"; +import type { SettingsPath } from "../components/settings/settingsSearch"; +import { connectionAtomRuntime } from "../connection/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { runCommand } from "../shortcuts/dispatcher"; +import { waitForThreadShell } from "../state/entities"; +import { navigateSettled } from "./navigateSettled"; +import { resolveThreadRouteTarget } from "../threadRoutes"; + +// The server stops waiting for an answer after this long. +const RESPONSE_DEADLINE = "5 seconds"; + +/** Runs the commands agents send this window, from every environment it is connected to. */ +export function startAppControl(router: AnyRouter): () => void { + // Outside view-only commands, a command runs only on its own environment's thread or draft, + // so an agent can't act through this window on an environment it has no access to. + const shownEnvironmentIds = () => { + const params: Record = router.state.matches.at(-1)?.params ?? {}; + const target = resolveThreadRouteTarget(params); + const draft = + target?.kind === "draft" + ? useComposerDraftStore.getState().getDraftSession(target.draftId) + : null; + return [params.environmentId, draft?.environmentId, draft?.loadBalancedEnvironmentId]; + }; + const run = (environmentId: string, command: AppCommand): AppControlResult => { + if (!VIEW_ONLY_APP_COMMANDS.has(command)) { + const shown = shownEnvironmentIds().filter((id) => id != null); + if (shown.length === 0 || shown.some((id) => id !== environmentId)) + return "other-environment"; + } + return runCommand(command) ? "ran" : "not-handled"; + }; + const destination = (environmentId: string, to: AppDestination): NavigateOptions => { + switch (to.page) { + case "thread": + return { + to: "/$environmentId/$threadId", + params: { environmentId, threadId: to.threadId }, + } as const; + case "settings": { + // Straight to a section: `/settings` redirects, which would look like a blocked move. + const path: SettingsPath = `/settings/${to.section ?? "general"}`; + return { to: path }; + } + case "usage": + return { to: "/usage" } as const; + case "pull-requests": + return { to: "/pull-requests", search: readPullRequestListPreferences() } as const; + } + }; + const act = async (environmentId: string, action: AppAction): Promise => { + if (action._tag === "command") return run(environmentId, action.command); + const { to } = action; + if (!(await navigateSettled(router, destination(environmentId, to)))) return "not-handled"; + // An older thread mounts its chat only once its row loads, after the route has settled. + if ( + to.page === "thread" && + !(await waitForThreadShell(scopeThreadRef(EnvironmentId.make(environmentId), to.threadId))) + ) + return "not-handled"; + return "ran"; + }; + const focused = Effect.sync(() => ({ + focused: document.hasFocus() && document.visibilityState === "visible", + })); + const atom = connectionAtomRuntime.atom( + Effect.gen(function* () { + const registry = yield* EnvironmentRegistry.EnvironmentRegistry; + yield* Stream.concat( + Stream.fromEffect(SubscriptionRef.get(registry.entries)), + SubscriptionRef.changes(registry.entries), + ).pipe( + Stream.map((entries) => [...entries.keys()]), + Stream.changesWith((previous, current) => previous.join() === current.join()), + Stream.switchMap((environmentIds) => + Stream.mergeAll( + environmentIds.map((environmentId) => + registry.followStream( + environmentId, + subscribeDynamic(WS_METHODS.subscribeAppControl, () => focused).pipe( + Stream.mapEffect(({ requestId, action }) => + // Requests run in order, so one that never settles must not hold the rest. + Effect.promise(() => act(environmentId, action)).pipe( + Effect.timeout(RESPONSE_DEADLINE), + Effect.flatMap((result) => + request(WS_METHODS.appControlRespond, { requestId, result }), + ), + Effect.ignoreCause, + ), + ), + Stream.ignoreCause, + ), + ), + ), + { concurrency: "unbounded" }, + ), + ), + Stream.runDrain, + ); + }), + ); + return appAtomRegistry.mount(atom); +} diff --git a/apps/web/src/lib/navigateSettled.browser.test.tsx b/apps/web/src/lib/navigateSettled.browser.test.tsx new file mode 100644 index 0000000000000..791bd30916fd2 --- /dev/null +++ b/apps/web/src/lib/navigateSettled.browser.test.tsx @@ -0,0 +1,87 @@ +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + redirect, + RouterProvider, +} from "@tanstack/react-router"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { navigateSettled } from "./navigateSettled"; + +function makeRouter(input: { nextLoader: () => Promise; redirect: boolean }) { + const root = createRootRoute({ component: Outlet }); + const home = createRoute({ getParentRoute: () => root, path: "/", component: () =>

home

}); + const next = createRoute({ + getParentRoute: () => root, + path: "/usage", + beforeLoad: () => { + if (input.redirect) throw redirect({ to: "/settings/general" }); + }, + loader: input.nextLoader, + component: () =>

usage

, + }); + const settings = createRoute({ + getParentRoute: () => root, + path: "/settings/general", + component: () =>

settings

, + }); + const thread = createRoute({ + getParentRoute: () => root, + path: "/$environmentId/$threadId", + component: () =>

thread

, + }); + return createRouter({ + routeTree: root.addChildren([home, next, settings, thread]), + history: createMemoryHistory({ initialEntries: ["/"] }), + }); +} + +describe("navigateSettled", () => { + it("resolves once the destination is on screen, not when navigation starts", async () => { + let openGate = () => {}; + const gate = new Promise((resolve) => { + openGate = resolve; + }); + const router = makeRouter({ nextLoader: () => gate, redirect: false }); + // The test needs its own route tree, with a loader that holds navigation pending. + // Its paths reuse app routes so the registered route types accept them. + await using screen = await render(, { router: false }); + await expect.element(screen.getByText("home")).toBeInTheDocument(); + + let settled = false; + const navigated = navigateSettled(router, { to: "/usage" }).finally(() => { + settled = true; + }); + await vi.waitFor(() => expect(router.state.status).toBe("pending")); + expect(settled).toBe(false); + + openGate(); + expect(await navigated).toBe(true); + expect(screen.container.textContent).toBe("usage"); + }); + + it("resolves false when the window ends up somewhere else", async () => { + const router = makeRouter({ nextLoader: async () => {}, redirect: true }); + // The test needs its own route tree, with a route that redirects elsewhere. + await using screen = await render(, { router: false }); + await expect.element(screen.getByText("home")).toBeInTheDocument(); + + expect(await navigateSettled(router, { to: "/usage" })).toBe(false); + await expect.element(screen.getByText("settings")).toBeInTheDocument(); + }); + + it("arrives at a thread whose id needs encoding in the URL", async () => { + const router = makeRouter({ nextLoader: async () => {}, redirect: false }); + // The test needs its own route tree; this one mirrors the app's thread route. + await using screen = await render(, { router: false }); + await expect.element(screen.getByText("home")).toBeInTheDocument(); + + const params = { environmentId: "environment", threadId: "mcp:thread" }; + expect(await navigateSettled(router, { to: "/$environmentId/$threadId", params })).toBe(true); + expect(screen.container.textContent).toBe("thread"); + }); +}); diff --git a/apps/web/src/lib/navigateSettled.ts b/apps/web/src/lib/navigateSettled.ts new file mode 100644 index 0000000000000..b02997f5dfea1 --- /dev/null +++ b/apps/web/src/lib/navigateSettled.ts @@ -0,0 +1,15 @@ +import type { AnyRouter, NavigateOptions } from "@tanstack/react-router"; + +/** + * Navigates and resolves once the destination is on screen, so a command sent next reaches it. + * Resolves false when the window ends up elsewhere, such as after a redirect. A blocked navigation + * never settles (TanStack leaves it pending), so callers bound the wait. + */ +export async function navigateSettled( + router: AnyRouter, + options: NavigateOptions, +): Promise { + const target = router.buildLocation(options).pathname; + if (router.state.location.pathname !== target) await router.navigate(options); + return router.state.location.pathname === target; +} diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts index 32dd581430cb2..f3fc75cc94f26 100644 --- a/apps/web/src/rightPanelStore.test.ts +++ b/apps/web/src/rightPanelStore.test.ts @@ -12,6 +12,7 @@ import { pullRequestSurfaceId, selectActiveRightPanel, selectActiveRightPanelSurface, + selectThreadPanelOpen, selectThreadPanelVisibility, selectThreadRightPanelState, useRightPanelStore, @@ -811,16 +812,33 @@ describe("rightPanelStore", () => { threadPanelVisibilityByThreadKey: { "env-1:thread-A": { inlineOpen: false, popoverOpen: true }, "env-1:thread-B": { inlineOpen: true, popoverOpen: true }, + "env-1:thread-C": { popoverOpen: true }, }, }), ).toEqual({ byThreadKey: {}, threadPanelVisibilityByThreadKey: { "env-1:thread-A": { inlineOpen: false, popoverOpen: false }, + "env-1:thread-B": { inlineOpen: true, popoverOpen: false }, }, }); }); + it("opens the inline card from the setting until the thread has its own choice", async () => { + const visibility = () => useRightPanelStore.getState().threadPanelVisibilityByThreadKey; + expect(selectThreadPanelOpen(visibility(), refA, "inline", false)).toBe(false); + expect(selectThreadPanelOpen(visibility(), refA, "inline", true)).toBe(true); + + useRightPanelStore.getState().setThreadPanelOpen(refA, "inline", true); + useRightPanelStore.getState().setThreadPanelOpen(refB, "inline", false); + await reloadRightPanelStore(); + + for (const openByDefault of [false, true]) { + expect(selectThreadPanelOpen(visibility(), refA, "inline", openByDefault)).toBe(true); + expect(selectThreadPanelOpen(visibility(), refB, "inline", openByDefault)).toBe(false); + } + }); + it("closes the popover atomically when the real right panel opens", () => { useRightPanelStore.getState().setThreadPanelOpen(refA, "popover", true); useRightPanelStore.getState().open(refA, "diff"); @@ -830,7 +848,7 @@ describe("rightPanelStore", () => { useRightPanelStore.getState().threadPanelVisibilityByThreadKey, refA, ), - ).toEqual({ inlineOpen: true, popoverOpen: false }); + ).toEqual({ popoverOpen: false }); }); it("keeps an open popover visible by promoting it to inline when the real panel closes", () => { @@ -839,13 +857,19 @@ describe("rightPanelStore", () => { store.setThreadPanelOpen(refA, "inline", false); store.setThreadPanelOpen(refA, "popover", true); store.close(refA); + store.open(refB, "diff"); + store.setThreadPanelOpen(refB, "popover", true); + store.close(refB); - expect( - selectThreadPanelVisibility( - useRightPanelStore.getState().threadPanelVisibilityByThreadKey, - refA, - ), - ).toEqual({ inlineOpen: true, popoverOpen: true }); + const { threadPanelVisibilityByThreadKey } = useRightPanelStore.getState(); + expect(selectThreadPanelVisibility(threadPanelVisibilityByThreadKey, refA)).toEqual({ + inlineOpen: true, + popoverOpen: true, + }); + expect(selectThreadPanelVisibility(threadPanelVisibilityByThreadKey, refB)).toEqual({ + inlineOpen: true, + popoverOpen: true, + }); }); it("opens workspace-root links as the singleton files explorer", () => { diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 19d08158e23e9..f334a2f345c1d 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -160,7 +160,8 @@ export interface ThreadRightPanelState { } export interface ThreadPanelVisibility { - inlineOpen: boolean; + /** The user's choice for this thread. Absent, the threadDetailsOpenByDefault setting applies. */ + inlineOpen?: boolean; popoverOpen: boolean; } @@ -269,7 +270,6 @@ interface RightPanelStoreState { presentation: ThreadPanelPresentation, open: boolean, ) => void; - toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void; removeThread: (ref: ScopedThreadRef) => void; } @@ -279,10 +279,7 @@ const EMPTY_THREAD_STATE: ThreadRightPanelState = { surfaces: [], }; -const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { - inlineOpen: true, - popoverOpen: false, -}; +const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = { popoverOpen: false }; const singletonSurface = ( kind: Exclude< @@ -455,7 +452,7 @@ const updateThreadPanelVisibilityMap = ( ): Record => { const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY; const next = updater(current); - if (next.inlineOpen && !next.popoverOpen) { + if (next.inlineOpen === undefined && !next.popoverOpen) { if (!(threadKey in byThreadKey)) return byThreadKey; const { [threadKey]: _removed, ...rest } = byThreadKey; return rest; @@ -486,11 +483,12 @@ const updateThread = ( (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility), ); } else if (current.isOpen && !next.isOpen) { + // The store can't see the default setting, so an open popover becomes an explicit inline choice. threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap( threadPanelVisibilityByThreadKey, threadKey, (visibility) => - visibility.popoverOpen && !visibility.inlineOpen + visibility.popoverOpen && visibility.inlineOpen !== true ? { ...visibility, inlineOpen: true } : visibility, ); @@ -764,8 +762,8 @@ export function migratePersistedRightPanelState(persistedState: unknown): { persistedState.threadPanelVisibilityByThreadKey as Record, ).flatMap(([threadKey, value]) => { if (!value || typeof value !== "object" || !("inlineOpen" in value)) return []; - return value.inlineOpen === false - ? [[threadKey, { inlineOpen: false, popoverOpen: false }]] + return typeof value.inlineOpen === "boolean" + ? [[threadKey, { inlineOpen: value.inlineOpen, popoverOpen: false }]] : []; }), ) @@ -1341,17 +1339,6 @@ export const useRightPanelStore = create()( }, ), })), - toggleThreadPanel: (ref, presentation) => - set((state) => ({ - threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap( - state.threadPanelVisibilityByThreadKey, - scopedThreadKey(ref), - (visibility) => - presentation === "inline" - ? { ...visibility, inlineOpen: !visibility.inlineOpen } - : { ...visibility, popoverOpen: !visibility.popoverOpen }, - ), - })), removeThread: (ref) => set((state) => { const threadKey = scopedThreadKey(ref); @@ -1399,8 +1386,8 @@ export const useRightPanelStore = create()( ), threadPanelVisibilityByThreadKey: Object.fromEntries( Object.entries(state.threadPanelVisibilityByThreadKey).flatMap( - ([threadKey, visibility]) => - visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]], + ([threadKey, { inlineOpen }]) => + inlineOpen === undefined ? [] : [[threadKey, { inlineOpen, popoverOpen: false }]], ), ), }), @@ -1455,9 +1442,12 @@ export function selectThreadPanelOpen( byThreadKey: Record, ref: ScopedThreadRef | null | undefined, presentation: ThreadPanelPresentation, + inlineOpenByDefault: boolean, ): boolean { const visibility = selectThreadPanelVisibility(byThreadKey, ref); - return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen; + return presentation === "inline" + ? (visibility.inlineOpen ?? inlineOpenByDefault) + : visibility.popoverOpen; } export function selectActiveRightPanel( diff --git a/apps/web/src/shortcuts/dispatcher.browser.test.ts b/apps/web/src/shortcuts/dispatcher.browser.test.ts index b9bf6c4e4b7d3..1e4c1dacbd29a 100644 --- a/apps/web/src/shortcuts/dispatcher.browser.test.ts +++ b/apps/web/src/shortcuts/dispatcher.browser.test.ts @@ -1,7 +1,7 @@ import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { dispatchMenuAction, registerCommands, registerMenuAction } from "./dispatcher"; +import { dispatchMenuAction, registerCommands, registerMenuAction, runCommand } from "./dispatcher"; function bindings(entries: ReadonlyArray<[string, KeybindingCommand]>): ResolvedKeybindingsConfig { return entries.map(([key, command]) => ({ @@ -46,22 +46,29 @@ describe("command dispatcher", () => { expect(global).not.toHaveBeenCalled(); }); - it("falls through scopes that return false, skip the command, or fail their guard", () => { - const global = vi.fn(); - const declined = vi.fn(() => false); - const guarded = vi.fn(); - using stack = new DisposableStack(); - stack.defer(registerCommands({ "chat.new": global }, { keybindings })); - stack.defer(registerCommands({ "chat.new": declined }, { keybindings })); - stack.defer(registerCommands({ "chat.newLocal": vi.fn() }, { keybindings })); - stack.defer(registerCommands({ "chat.new": guarded }, { keybindings, when: () => false })); - - press("k"); - - expect(guarded).not.toHaveBeenCalled(); - expect(declined).toHaveBeenCalledOnce(); - expect(global).toHaveBeenCalledOnce(); - }); + it.each([ + ["key press", () => press("k")], + ["agent", () => expect(runCommand("chat.new")).toBe(true)], + ])( + "falls through scopes that return false, skip the command, or fail their guard (%s)", + (_, run) => { + const global = vi.fn(); + const declined = vi.fn(() => false); + const guarded = vi.fn(); + using stack = new DisposableStack(); + stack.defer(registerCommands({ "chat.new": global }, { keybindings })); + stack.defer(registerCommands({ "chat.new": declined }, { keybindings })); + stack.defer(registerCommands({ "chat.newLocal": vi.fn() }, { keybindings })); + stack.defer(registerCommands({ "chat.new": guarded }, { keybindings, when: () => false })); + + run(); + + expect(guarded).not.toHaveBeenCalled(); + expect(declined).toHaveBeenCalledOnce(); + expect(global).toHaveBeenCalledOnce(); + expect(runCommand("chat.find")).toBe(false); + }, + ); it("stops once a handler prevents default, and unregisters on cleanup", () => { const lower = vi.fn(); diff --git a/apps/web/src/shortcuts/dispatcher.ts b/apps/web/src/shortcuts/dispatcher.ts index 9e361e825db7f..680671c9d872f 100644 --- a/apps/web/src/shortcuts/dispatcher.ts +++ b/apps/web/src/shortcuts/dispatcher.ts @@ -127,6 +127,41 @@ function pushScope(list: CommandScope[], scope: CommandScope): () => void { }; } +type CommandRunner = (command: KeybindingCommand) => boolean; +const commandRunners: CommandRunner[] = []; + +/** + * For views that match their own shortcuts (the chat, the sidebar), so `runCommand` reaches + * them too. A runner returns whether it ran the command. + */ +export function registerCommandRunner(runner: CommandRunner): () => void { + commandRunners.push(runner); + return () => { + const index = commandRunners.lastIndexOf(runner); + if (index !== -1) commandRunners.splice(index, 1); + }; +} + +/** + * Runs a command as its shortcut would, without a key press. Returns false when nothing + * on screen handles it right now, such as a thread command outside a thread. + */ +export function runCommand(command: KeybindingCommand): boolean { + for (let index = commandRunners.length - 1; index >= 0; index -= 1) { + if (commandRunners[index]?.(command)) return true; + } + const event = new KeyboardEvent("keydown", { cancelable: true }); + for (const scopes of [captureScopes, globalScopes]) { + for (let index = scopes.length - 1; index >= 0; index -= 1) { + const scope = scopes[index]; + const handler = scope?.commands[command]; + if (handler === undefined || scope?.options.when?.(event) === false) continue; + if (handler(event) !== false) return true; + } + } + return false; +} + /** App-global commands, registered once at module level or bootstrap. */ export function registerCommands( commands: CommandHandlers, diff --git a/docs/operations/sanu-code.md b/docs/operations/sanu-code.md new file mode 100644 index 0000000000000..94789b4b91769 --- /dev/null +++ b/docs/operations/sanu-code.md @@ -0,0 +1,76 @@ +# Sanu Code + +Sanu Code is this fork run from source beside an installed T3 Code. It keeps its own data in +`~/.sanucode`, so the installed app, its database, and its connections stay untouched. + +## Set up + +Install `vp` ([Install vp](../../README.md#install-vp)), clone the fork, and run in the checkout: + +```sh +vp i +./scripts/sanucode install +``` + +This links `sanucode` and its alias `sn` in `~/.local/bin` to that checkout, so `git pull` also +updates the command. `sn help` lists every command. Sanu Code runs on the Node version pinned in +`package.json`, even when a Node version manager such as nvm selects another one. + +| Command | Opens | +| -------- | ---------------------------------------------------------------------------------------- | +| `sn app` | The desktop app | +| `sn` | The web app at `http://localhost:5733`. Open the `pairingUrl` it prints once per browser | + +Both use the same data and ports, so run one at a time. Sanu Code runs only while that command +does; keep its terminal open while you need it, including from your phone. + +## Move over from T3 Code + +`sn import` replaces Sanu Code's data with a copy of the installed T3 Code's projects, threads, +settings, keybindings, and display preferences. It saves the previous Sanu Code data in +`~/.sanucode/backup` and refuses to run while Sanu Code is open. + +1. Let running threads in T3 Code finish. +2. Quit and reopen T3 Code once. It closes inactive agent sessions on start, and the import skips + any thread whose session is still open. +3. Quit Sanu Code, then run `sn import`. It prints the threads each project received. Skipped + threads stay readable in T3 Code. + +Treat the import as a one-time move: running it again later replaces everything you did in Sanu +Code. It does not bring sign-ins, paired phones and machines, scheduled tasks, or secrets. +Reconnect devices as described below. + +## Connect your phone + +Sanu Code has no T3 Connect, because official builds carry the relay configuration and a build +from source does not. Phones and other machines reach it over your local network or Tailscale. + +1. Start `sn app`, open **Settings → Sharing & access**, and turn on **Network access**. The app + restarts. +2. Create a pairing link with an address your phone can reach, such as your computer's Tailscale + address. +3. In the mobile app, open **Settings → Environments → Add environment** and scan the QR code. + +Pair from `sn app`, which lists your computer's network addresses. The paired phone also reaches +`sn`, whose server listens on every interface at the same port. Plain HTTP works over Tailscale. +For HTTPS, enable HTTPS certificates for your tailnet, then use `sn --share --built`. + +## Connect other machines + +For each machine running T3 Code that you want to control from Sanu Code: + +1. Let it accept network connections: run `t3 up --lan` on a command-line host, or turn on + **Network access** in its desktop app. +2. Run `t3 pair` on that machine. +3. In Sanu Code, open **Settings → Environments → Add environment** and paste the link. If its + address is not reachable from your computer, replace the host with the machine's Tailscale + name or address and keep the port. + +This adds a new sign-in on that machine, and T3 Code's existing connection keeps working. Features +unique to this fork only work on machines that run Sanu Code. + +## Day to day + +- Update with `git pull` in the checkout, then restart Sanu Code. +- Keep T3 Code installed as a fallback, but never run agents in the same worktree from both apps. +- Once you stop using T3 Code, remove its environment from your phone and other clients. diff --git a/docs/user/composer.md b/docs/user/composer.md index 53017052a2a01..a254d11c4b34d 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -37,6 +37,30 @@ at the end, leave the block. **Backspace** at the start of a code block turns it back into plain lines. Choose the language in a code block's corner to change it. Very large code blocks are shown without syntax highlighting. +## Vim mode + +On web and desktop, vim mode is on by default, so you can edit prompts with Vim +keys. Turn it off in **Settings → Chat → Vim mode**. You can also toggle it from +the command palette, or assign a shortcut to `composer.toggleVimMode` in +**Settings → Keybindings**. The composer starts in insert mode; **Escape** +switches to normal mode, and the composer footer shows the current mode. When a +menu or prompt suggestion is open, Escape closes it first. In normal mode, Escape +does what it does without vim mode. + +Normal mode supports: + +- Motions `h j k l`, `w b e`, `W B E`, `0 ^ $`, `gg G`, and `f F t T` with `;` + and `,`, with counts such as `3w`. +- `i I a A o O` to insert. +- `x X s S r`, `d c y` with a motion or text object, `dd cc yy`, `D C Y`, `p P`, + `J`, `.` to repeat, `u` to undo and `Ctrl+R` to redo. +- Text objects `iw aw iW aW`, `i" a"`, `i' a'`, `i( a(`, `i[ a[` and `i{ a{`. + +Enter sends from normal mode when your **Send shortcut** would send. A file, +skill or other chip counts as one character. Yanked and deleted text stays in +the composer rather than the clipboard. Lines follow the composer's paragraphs, +not wrapped lines. + ## Attach files Attach up to 100 files per message. Each image can be up to 10 MiB, with at most diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md index eab9e88ec98f0..9f5b1fd6410bc 100644 --- a/docs/user/keybindings.md +++ b/docs/user/keybindings.md @@ -54,6 +54,13 @@ on macOS and Ctrl on Windows and Linux, including GNOME, KDE Plasma, Niri, and Hyprland. If a custom desktop shortcut takes the same keys, choose another binding in Settings. +## Toggle the terminal + +`mod+j` and ``ctrl+` `` open and close the terminal drawer, even while the terminal +has focus. Like VS Code, ``ctrl+` `` uses Control on every platform, including macOS. +If you changed the terminal shortcut earlier, T3 Code leaves it alone and does not +add ``ctrl+` ``; add it under **Terminal: Toggle** in Keybindings. + ## Copy pull request references With a PR open in the right panel or on the Pull requests page, use `mod+shift+c` @@ -179,6 +186,9 @@ shortcut; assign one in **Settings → Keybindings**. `thread.regenerateTitle` generates a new title for the focused thread, like **Regenerate title** in the thread menu. It has no default shortcut. +`composer.toggleVimMode` turns [vim mode](./composer.md#vim-mode) on or off. It +has no default shortcut. + `thread.undo` (`mod+z` by default) reverses the actions shown in the notice at the bottom of the sidebar, such as unpin, settle, snooze, archive, or discarding a draft. Consecutive diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 9bbf3194a9d59..06f2e405bd283 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -49,6 +49,36 @@ moves and the agent keeps working in the same place. Other threads in that folde move with it. Rename the project in its settings, and use **Initialize Git** to get branch and diff controls. +### Move a thread to another project + +Started in the wrong place? Pick **Move to project** from the thread's menu, or +**Move thread to...** in the command palette, and choose a project on the same +machine. The thread keeps its history and continues in that project's root folder +from your next message. Stop a running thread before moving it. + +Earlier turns keep their diffs for as long as the folder they ran in exists, but +their files can't be restored. A thread that had its own worktree leaves it behind: +the worktree and branch stay on disk, but the agent no longer sees changes left +there. The old worktree shows as unused in +[Storage cleanup](./project-settings.md#storage-cleanup). To keep working in a fresh +worktree, hand the moved thread off to one. + +### Move a thread to another machine + +To continue a conversation on another connected machine, pick **Move to machine** +from the thread's menu, or **Move thread to machine...** in the command palette, +and choose a project there. Both machines need this version of T3 Code, and your +connection must be allowed to change threads on both. + +The new thread gets the conversation, and your next message starts a fresh agent +session there with that history. Files, diffs, the worktree, attachments and +scheduled tasks stay on the first machine, where the old thread is archived. To go +back, unarchive it there, or move the new thread back the same way. + +The other machine must be able to run the thread's provider, or its project needs a +default model. If the thread gets a new message while it moves, the original stays +active, because the copy doesn't have that message. + ### Start in the background In a desktop browser or the desktop app, press `Cmd+Enter` on macOS or `Ctrl+Enter` @@ -137,10 +167,11 @@ open. ### Fold working threads (beta) Threads that are working or waiting on work they will resume from move into a collapsed -**Working** section below the active list. +**Working** section. That includes subagents, watched pull requests with checks still running, Claude monitors, and background commands or other monitors the agent says it is waiting on. A dev server or other process an agent leaves running does not keep a thread -there. A thread returns to the top of the active list when it finishes, fails, or needs an approval or +there. On web and desktop the section sits below the active list. On iOS and Android it sits above +it, under pinned threads, and the active list below it is labeled **Inbox**. A thread returns to the top of the active list when it finishes, fails, or needs an approval or answer. The Working section lists the thread you last sent work to first. Pinned threads stay in the pinned section. @@ -298,6 +329,11 @@ Select a server to open it in the browser panel. **Stop** ends the server's job and keeps the agent, the terminal, and T3 Code running. Stop needs terminal access to the environment and is not available on Windows. +The thread details card starts closed in each thread. Show or hide it with +`mod+shift+b`, and the thread remembers your choice. To show it in every thread you +haven't opened or closed it in, turn on **Settings → Appearance → Open thread +details by default**. + To choose what the thread details card shows, right-click the card or open **Settings → Appearance → Thread details**. Hidden rows keep their keyboard shortcuts, such as Open in editor and project scripts. **Reset to default** brings diff --git a/evals/mcp-tool-use/cases/projects.ndjson b/evals/mcp-tool-use/cases/projects.ndjson index b52ee4eff30bc..8048dc129ad0b 100644 --- a/evals/mcp-tool-use/cases/projects.ndjson +++ b/evals/mcp-tool-use/cases/projects.ndjson @@ -1 +1,2 @@ {"id": "archive-project-not-delete", "area": "projects", "kind": "guard", "pattern": "archive a project by deleting it", "experience": "Projects gained an archive flag. Asked to archive a finished project, an agent must set archived, not remove the project and its threads.", "rule": "t3_project_update archived: Threads and files are kept.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_project_list": {"projects": [{"id": "project-app", "title": "app", "workspaceRoot": "/home/dev/code/app", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}, {"id": "project-old-site", "title": "old-site", "workspaceRoot": "/home/dev/code/old-site", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-03-01T00:00:00.000Z", "updatedAt": "2026-04-02T00:00:00.000Z", "deletedAt": null}], "nextCursor": null}}}, "prompt": "I'm done with the old-site project. Archive it in T3 Code so it stops showing up in my project pickers.", "expect": {"calls": [{"tool": "t3_project_update", "args": {"projectId": "project-old-site", "archived": true}}], "callsMustNot": [{"tool": "t3_project_delete"}, {"tool": "t3_project_update", "args": {"projectId": "project-app"}}]}, "maxSteps": 6} +{"id": "move-thread-to-another-project", "area": "projects", "kind": "bad", "pattern": "move a thread by copying it", "experience": "Asked to move a started thread into the right project, an agent had no move action, so it could only fork the thread or start a new one, which leaves the conversation behind (batchema/t3code#6).", "rule": "t3_thread_organize move: the thread keeps its history and continues in the target project's root.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_project_list": {"projects": [{"id": "project-web", "title": "web", "workspaceRoot": "/home/user/code/web", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}, {"id": "project-api", "title": "api", "workspaceRoot": "/home/user/code/api", "defaultModelSelection": null, "scripts": [], "pinnedAt": null, "archivedAt": null, "createdAt": "2026-09-01T00:00:00.000Z", "updatedAt": "2026-10-20T00:00:00.000Z", "deletedAt": null}], "nextCursor": null}, "t3_thread_organize": {"movedToProjectId": "project-api", "notice": "The conversation moves with it, and the agent works in api's folder from the next message. Earlier diffs open while their original folder exists, and files from earlier turns can't be restored."}}}, "prompt": "I started thread thread-auth-retry in the web project by mistake; the bug is in api. Move that thread over to the api project so it keeps going there.", "expect": {"calls": [{"tool": "t3_thread_organize", "args": {"action": "move", "threadId": "thread-auth-retry", "projectId": "project-api"}}], "callsMustNot": [{"tool": "t3_thread_launch"}, {"tool": "create_threads"}, {"tool": "t3_thread_transfer"}]}, "maxSteps": 6} diff --git a/evals/mcp-tool-use/cases/settings.ndjson b/evals/mcp-tool-use/cases/settings.ndjson new file mode 100644 index 0000000000000..ab730a715531f --- /dev/null +++ b/evals/mcp-tool-use/cases/settings.ndjson @@ -0,0 +1,3 @@ +{"id": "labs-setting-uses-settings-update", "area": "settings", "kind": "bad", "pattern": "edit settings.json by hand", "experience": "Asked to turn on the Linked environments Labs switch on a headless box, an agent had no tool for it and told the user to write the server's settings.json by hand.", "rule": "t3_environment_settings_update: Change this server's settings.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_environment_settings_read": {"settings": {"linkedEnvironmentsEnabled": false, "guestSharingEnabled": false, "promptSuggestionsEnabled": false}}, "t3_environment_settings_update": {"settings": {"linkedEnvironmentsEnabled": true}}}}, "prompt": "Turn on the linked environments beta on this machine. There's no T3 Code window open on it.", "expect": {"calls": [{"tool": "t3_environment_settings_update", "args": {"patch.linkedEnvironmentsEnabled": true}}], "shellMustNot": ["settings\\.json"]}, "maxSteps": 6} +{"id": "open-panel-uses-app-command", "area": "settings", "kind": "bad", "pattern": "tell the user to press the shortcut", "experience": "Asked to open the terminal in the user's T3 Code window, an agent had no way to act on the window and told the user which shortcut to press.", "rule": "t3_app_command: Run a command from `t3_keybindings_read` in the user's T3 Code window.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_keybindings_read": {"keybindings": [{"key": "mod+j", "command": "terminal.toggle"}], "commands": ["terminal.toggle", "sidebar.toggle", "chat.new"], "issues": []}, "t3_app_command": {"ran": true}}}, "prompt": "Open the terminal in my T3 Code window.", "expect": {"calls": [{"tool": "t3_app_command", "args": {"command": "terminal.toggle"}}]}, "maxSteps": 6} +{"id": "open-settings-section-uses-app-navigate", "area": "settings", "kind": "bad", "pattern": "tell the user where to click", "experience": "Asked to show the keybindings settings in the user's T3 Code window, an agent had no way to move the window and described where to click.", "rule": "t3_app_navigate: Show a page in the user's T3 Code window, the one they used last: a thread from this environment, a settings section, usage, or pull requests.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_app_navigate": {"ran": true}}}, "prompt": "Take my T3 Code window to the keybindings settings.", "expect": {"calls": [{"tool": "t3_app_navigate", "args": {"to": {"page": "settings", "section": "keybindings"}}}]}, "maxSteps": 6} diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 92fad6b57ac9d..4fdd9b8c135ca 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -267,6 +267,10 @@ "types": "./src/state/models.ts", "default": "./src/state/models.ts" }, + "./state/threadMachineMove": { + "types": "./src/state/threadMachineMove.ts", + "default": "./src/state/threadMachineMove.ts" + }, "./state/orchestration": { "types": "./src/state/orchestration.ts", "default": "./src/state/orchestration.ts" diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 0947b1c046085..18c68cc648d68 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -75,6 +75,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.serverGetDatabaseStorage | typeof WS_METHODS.subscribeTerminalMetadata | typeof WS_METHODS.subscribePreviewEvents + | typeof WS_METHODS.subscribeAppControl | typeof WS_METHODS.subscribeDiscoveredLocalServers | typeof WS_METHODS.subscribeDeviceState | typeof WS_METHODS.subscribeResourceTelemetry diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 4401f90e898c3..ba2771130f288 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -20,6 +20,7 @@ import * as DateTime from "effect/DateTime"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import { isScratchProject } from "./projects.ts"; import { formatSubagentDisplayTitle } from "./subagentDisplay.ts"; export interface EnvironmentProject extends OrchestrationProjectShell { @@ -27,6 +28,35 @@ export interface EnvironmentProject extends OrchestrationProjectShell { readonly isScratch?: true; } +/** The live projects on `environmentId` a thread can move into: all but No project. */ +export function threadMoveProjects< + P extends Pick & { + readonly archivedAt?: EnvironmentProject["archivedAt"]; + }, +>( + projects: ReadonlyArray

, + environmentId: EnvironmentId, + scratchWorkspaceRoot: string | null | undefined, +): ReadonlyArray

{ + return projects.filter( + (project) => + project.environmentId === environmentId && + project.archivedAt == null && + !isScratchProject(project, scratchWorkspaceRoot), + ); +} + +/** Where a thread can move: the other live projects on its environment, except No project. */ +export function threadMoveTargets( + projects: ReadonlyArray, + thread: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + scratchWorkspaceRoot: string | null | undefined, +): ReadonlyArray { + return threadMoveProjects(projects, thread.environmentId, scratchWorkspaceRoot).filter( + (project) => project.id !== thread.projectId, + ); +} + /** * The projection stays nested so the server projection and all structurally * shared collections retain their identities. diff --git a/packages/client-runtime/src/state/projectCommands.ts b/packages/client-runtime/src/state/projectCommands.ts index b2930759d5cb8..50a1c214151c9 100644 --- a/packages/client-runtime/src/state/projectCommands.ts +++ b/packages/client-runtime/src/state/projectCommands.ts @@ -231,6 +231,30 @@ export function createProjectEnvironmentAtoms( scheduler: projectScheduler, concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, }), + moveThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:projects:move-thread", + tag: WS_METHODS.projectsMoveThread, + scheduler: projectScheduler, + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, + }), + exportThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:projects:export-thread", + tag: WS_METHODS.projectsExportThread, + scheduler: projectScheduler, + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, + }), + importThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:projects:import-thread", + tag: WS_METHODS.projectsImportThread, + scheduler: projectScheduler, + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, + }), + finishThreadMove: createEnvironmentRpcCommand(runtime, { + label: "environment-data:projects:finish-thread-move", + tag: WS_METHODS.projectsFinishThreadMove, + scheduler: projectScheduler, + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, + }), writeFile: createEnvironmentRpcCommand(runtime, { label: "environment-data:projects:write-file", tag: WS_METHODS.projectsWriteFile, diff --git a/packages/client-runtime/src/state/threadMachineMove.test.ts b/packages/client-runtime/src/state/threadMachineMove.test.ts new file mode 100644 index 0000000000000..2f2d936e709b4 --- /dev/null +++ b/packages/client-runtime/src/state/threadMachineMove.test.ts @@ -0,0 +1,150 @@ +import { + EnvironmentId, + ProjectId, + ProviderInstanceId, + ThreadId, + type ProjectExportThreadResult, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { AtomRegistry } from "effect/reactivity"; +import { describe, expect, it } from "vite-plus/test"; + +import type { AtomCommand } from "./runtime.ts"; +import { + moveThreadToMachine, + threadMachineMoveTargets, + type ThreadMachineMoveCommands, +} from "./threadMachineMove.ts"; + +const source = { environmentId: EnvironmentId.make("laptop"), threadId: ThreadId.make("old") }; +const target = { environmentId: EnvironmentId.make("vps"), projectId: ProjectId.make("api") }; +const exported: ProjectExportThreadResult = { + bundle: { + title: "Port the parser", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "m" }, + runtimeMode: "full-access", + interactionMode: "default", + createdAt: "2026-01-01T00:00:00.000Z", + messages: [{ role: "user", text: "Port it.", createdAt: "2026-01-01T00:00:00.000Z" }], + }, + leftBehind: { diffs: true, worktree: false, attachments: 0, scheduledTasks: 0 }, + revision: "1:run", +}; + +type Step = "export" | "import" | "finish"; + +class StepFailed extends Schema.TaggedError()("StepFailed", { + message: Schema.String, +}) {} + +function setup(failing: ReadonlySet, exportGate: Promise = Promise.resolve()) { + const calls: Array<{ readonly step: Step; readonly environmentId: string }> = []; + const command = ( + step: Step, + value: A, + ): AtomCommand< + { readonly environmentId: EnvironmentId; readonly input: unknown }, + A, + unknown + > => ({ + label: step, + run: (_registry, { environmentId }) => + Effect.gen(function* () { + calls.push({ step, environmentId }); + if (step === "export") yield* Effect.promise(() => exportGate); + if (failing.has(step)) return yield* new StepFailed({ message: `${step} failed` }); + return value; + }), + }); + const commands: ThreadMachineMoveCommands = { + exportThread: command("export", exported), + importThread: command("import", { threadId: ThreadId.make("new") }), + finishThreadMove: command("finish", undefined), + }; + const move = (confirm = true) => + moveThreadToMachine({ + registry: AtomRegistry.make(), + commands, + source, + sourceLabel: "Laptop", + target, + targetLabel: "api on VPS", + confirm: async () => confirm, + }); + return { calls, move }; +} + +describe("moveThreadToMachine", () => { + it("imports on the target before archiving on the source", async () => { + const { calls, move } = setup(new Set()); + expect(await move()).toEqual({ + _tag: "Moved", + threadRef: { environmentId: "vps", threadId: "new" }, + archiveError: null, + }); + expect(calls).toEqual([ + { step: "export", environmentId: "laptop" }, + { step: "import", environmentId: "vps" }, + { step: "finish", environmentId: "laptop" }, + ]); + }); + + it.each([ + { failing: "export" as const, reached: ["export"] }, + { failing: "import" as const, reached: ["export", "import"] }, + ])("archives nothing when $failing fails", async ({ failing, reached }) => { + const { calls, move } = setup(new Set([failing])); + expect(await move()).toEqual({ _tag: "Failed", message: `${failing} failed` }); + expect(calls.map((call) => call.step)).toEqual(reached); + }); + + it("changes nothing when the move is not confirmed", async () => { + const { calls, move } = setup(new Set()); + expect(await move(false)).toEqual({ _tag: "Cancelled" }); + expect(calls.map((call) => call.step)).toEqual(["export"]); + }); + + it("reports the new thread and the archive failure, so the user knows both copies exist", async () => { + const { move } = setup(new Set(["finish"])); + expect(await move()).toEqual({ + _tag: "Moved", + threadRef: { environmentId: "vps", threadId: "new" }, + archiveError: "finish failed", + }); + }); + + it("ignores a second move of the same thread while one is in flight", async () => { + let release = () => {}; + const { calls, move } = setup(new Set(), new Promise((resolve) => (release = resolve))); + const first = move(); + expect(await move()).toEqual({ _tag: "Cancelled" }); + release(); + expect((await first)._tag).toBe("Moved"); + expect(calls.filter((call) => call.step === "import")).toHaveLength(1); + }); +}); + +describe("threadMachineMoveTargets", () => { + const laptop = EnvironmentId.make("laptop"); + const vps = EnvironmentId.make("vps"); + const supported = { environment: { capabilities: { threadMoveToMachine: true } } }; + const targets = (canOperate: ReadonlySet) => + threadMachineMoveTargets({ + sourceEnvironmentId: laptop, + connectedEnvironmentIds: [laptop, vps], + serverConfigs: new Map([ + [laptop, supported], + [vps, supported], + ]), + projects: [{ id: ProjectId.make("api"), environmentId: vps, workspaceRoot: "/api" }], + labelOf: (environmentId) => environmentId, + canOperate: (environmentId) => canOperate.has(environmentId), + }).map((machine) => machine.environmentId); + + it("lists machines only when this connection can change threads on both ends", () => { + expect(targets(new Set(["laptop", "vps"]))).toEqual(["vps"]); + expect(targets(new Set(["vps"]))).toEqual([]); + expect(targets(new Set(["laptop"]))).toEqual([]); + }); +}); diff --git a/packages/client-runtime/src/state/threadMachineMove.ts b/packages/client-runtime/src/state/threadMachineMove.ts new file mode 100644 index 0000000000000..c422bded14b9f --- /dev/null +++ b/packages/client-runtime/src/state/threadMachineMove.ts @@ -0,0 +1,196 @@ +import type { + EnvironmentId, + ProjectExportThreadResult, + ProjectFinishThreadMoveInput, + ProjectId, + ProjectImportThreadInput, + ProjectImportThreadResult, + ScopedThreadRef, + ThreadId, +} from "@t3tools/contracts"; +import type { AtomRegistry } from "effect/reactivity"; +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; + +import { scopedThreadKey } from "../environment/scoped.ts"; +import { type EnvironmentProject, threadMoveProjects } from "./models.ts"; +import { + type AtomCommand, + type AtomCommandResult, + isAtomCommandInterrupted, + runAtomCommand, + squashAtomCommandFailure, +} from "./runtime.ts"; + +type EnvironmentCommand = AtomCommand< + { readonly environmentId: EnvironmentId; readonly input: I }, + A, + unknown +>; + +export interface ThreadMachineMoveCommands { + readonly exportThread: EnvironmentCommand< + { readonly threadId: ThreadId }, + ProjectExportThreadResult + >; + readonly importThread: EnvironmentCommand; + readonly finishThreadMove: EnvironmentCommand; +} + +export type ThreadMachineMoveOutcome = + | { readonly _tag: "Cancelled" } + /** Nothing changed on either machine. */ + | { readonly _tag: "Failed"; readonly message: string } + /** The new thread exists; `archiveError` says the old one is still active beside it. */ + | { + readonly _tag: "Moved"; + readonly threadRef: ScopedThreadRef; + readonly archiveError: string | null; + }; + +export interface ThreadMachineMoveTarget

{ + readonly environmentId: EnvironmentId; + readonly label: string; + readonly projects: ReadonlyArray

; +} + +interface MoveServerConfig { + readonly scratchWorkspaceRoot?: string | undefined; + readonly environment: { readonly capabilities: { readonly threadMoveToMachine?: boolean } }; +} + +/** + * The other connected machines a thread can move to, each with its projects. Both ends must + * support it, and this connection must be able to change threads on both. + */ +export function threadMachineMoveTargets< + P extends Parameters[0][number], +>(input: { + readonly sourceEnvironmentId: EnvironmentId; + readonly connectedEnvironmentIds: ReadonlyArray; + readonly serverConfigs: ReadonlyMap; + readonly projects: ReadonlyArray

; + readonly labelOf: (environmentId: EnvironmentId) => string | undefined; + readonly canOperate: (environmentId: EnvironmentId) => boolean; +}): ReadonlyArray> { + const supports = (environmentId: EnvironmentId) => + input.serverConfigs.get(environmentId)?.environment.capabilities.threadMoveToMachine === true; + if (!supports(input.sourceEnvironmentId) || !input.canOperate(input.sourceEnvironmentId)) { + return []; + } + return input.connectedEnvironmentIds.flatMap((environmentId) => { + const label = input.labelOf(environmentId); + if ( + environmentId === input.sourceEnvironmentId || + label === undefined || + !supports(environmentId) || + !input.canOperate(environmentId) + ) { + return []; + } + const projects = threadMoveProjects( + input.projects, + environmentId, + input.serverConfigs.get(environmentId)?.scratchWorkspaceRoot, + ); + return projects.length === 0 ? [] : [{ environmentId, label, projects }]; + }); +} + +function failureMessage( + result: AtomCommandResult, + resolve: MFunctionType, +): string { + const error = result._tag === "Failure" ? squashAtomCommandFailure(result) : undefined; + return error instanceof Error && error.message !== "" + ? error.message + : resolve(msg("Try again.")); +} + +const movesInFlight = new Set(); +const quiet = { reportFailure: false }; + +/** + * Copies the thread's conversation to a project on another machine, then archives it here. The + * client carries the bundle over connections it already has, so the servers never trust each + * other. Archiving waits for the import, so a failed import changes nothing. + */ +export async function moveThreadToMachine(input: { + readonly registry: AtomRegistry.AtomRegistry; + readonly commands: ThreadMachineMoveCommands; + readonly source: ScopedThreadRef; + readonly sourceLabel: string; + readonly target: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }; + /** "api on VPS": where the archived thread says it went. */ + readonly targetLabel: string; + readonly confirm: (exported: ProjectExportThreadResult) => Promise; + readonly resolve?: MFunctionType; +}): Promise { + // A second pick while one runs would import the conversation twice. + const key = scopedThreadKey(input.source); + if (movesInFlight.has(key)) return { _tag: "Cancelled" }; + movesInFlight.add(key); + try { + return await moveOnce(input); + } finally { + movesInFlight.delete(key); + } +} + +async function moveOnce( + input: Parameters[0], +): Promise { + const { registry, commands, source, target, resolve = mFallback } = input; + const settled = (result: AtomCommandResult): ThreadMachineMoveOutcome => + isAtomCommandInterrupted(result) + ? { _tag: "Cancelled" } + : { _tag: "Failed", message: failureMessage(result, resolve) }; + + const exported = await runAtomCommand( + registry, + commands.exportThread, + { + environmentId: source.environmentId, + input: { threadId: source.threadId }, + }, + quiet, + ); + if (exported._tag !== "Success") return settled(exported); + if (!(await input.confirm(exported.value))) return { _tag: "Cancelled" }; + + const imported = await runAtomCommand( + registry, + commands.importThread, + { + environmentId: target.environmentId, + input: { + projectId: target.projectId, + bundle: exported.value.bundle, + movedFrom: input.sourceLabel, + leftBehind: exported.value.leftBehind, + }, + }, + quiet, + ); + if (imported._tag !== "Success") return settled(imported); + const threadRef = { environmentId: target.environmentId, threadId: imported.value.threadId }; + + const finished = await runAtomCommand( + registry, + commands.finishThreadMove, + { + environmentId: source.environmentId, + input: { + threadId: source.threadId, + movedTo: input.targetLabel, + revision: exported.value.revision, + }, + }, + quiet, + ); + return { + _tag: "Moved", + threadRef, + archiveError: finished._tag === "Success" ? null : failureMessage(finished, resolve), + }; +} diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index d7e0a24d0284f..b985afee1d8f4 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -1156,6 +1156,40 @@ export function summarizeT3ToolCalls( ); break; } + case "app-command": { + const count = selected.length; + label = done + ? resolve( + msg( + "{count, plural, one {Ran app commands {count} time} other {Ran app commands {count} times}}", + { count }, + ), + ) + : resolve( + msg( + "{count, plural, one {Tried to run app commands {count} time} other {Tried to run app commands {count} times}}", + { count }, + ), + ); + break; + } + case "app-navigate": { + const count = selected.length; + label = done + ? resolve( + msg( + "{count, plural, one {Opened pages in the app {count} time} other {Opened pages in the app {count} times}}", + { count }, + ), + ) + : resolve( + msg( + "{count, plural, one {Tried to open pages in the app {count} time} other {Tried to open pages in the app {count} times}}", + { count }, + ), + ); + break; + } case "environment-links": { const count = selected.length; label = done diff --git a/packages/contracts/src/appControl.ts b/packages/contracts/src/appControl.ts new file mode 100644 index 0000000000000..4430a5f36e9b8 --- /dev/null +++ b/packages/contracts/src/appControl.ts @@ -0,0 +1,125 @@ +import { Schema } from "effect"; + +import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { STATIC_KEYBINDING_COMMANDS } from "./keybindings.ts"; + +/** + * Only the user may trigger these: they send what the user wrote, listen to them, or pick + * work that may belong to another environment (undo and reopen history, new threads, hosts). + * Agents start threads with `t3_thread_launch` instead. + */ +const USER_ONLY_COMMANDS = new Set([ + "composer.sendAlternate", + "composer.sendBackground", + "composer.sendAndNewThread", + "composer.dictation", + "composer.cycleHost", + "thread.steerQueuedMessage", + "thread.undo", + "view.reopenClosed", + "chat.new", + "chat.newLocal", + "chat.newWithoutProject", +]); + +/** + * These change only the window's own view, so they run on any screen. The rest act on the + * thread or draft on screen, so they run only while it belongs to the agent's environment. + */ +export const VIEW_ONLY_APP_COMMANDS: ReadonlySet = new Set([ + "sidebar.toggle", + "navigation.back", + "navigation.forward", + "workspace.focusNext", + "workspace.focusPrevious", + "commandPalette.toggle", + "theme.select", + "appearance.cycle", + "themeEditor.toggle", + "thread.previous", + "thread.next", + "usage.open", + "usage.cost", + "usage.tokens", + "usage.limits", + "usage.period.day", + "usage.period.week", + "usage.period.month", + "usage.period.quarter", +]); + +/** Shortcut commands an agent may run in the user's window. */ +const APP_COMMANDS = STATIC_KEYBINDING_COMMANDS.filter( + (command) => !USER_ONLY_COMMANDS.has(command), +); +export const AppCommand = Schema.Literals(APP_COMMANDS); +export type AppCommand = typeof AppCommand.Type; + +const APP_SETTINGS_SECTIONS = [ + "general", + "appearance", + "chat", + "diffs", + "keybindings", + "voice", + "snap-shot", + "providers", + "threads", + "projects", + "browser", + "devices", + "scheduled-tasks", + "source-control", + "worktrees", + "connections", + "access", + "secrets", + "maintenance", + "diagnostics", + "labs", + "about", + "archived", +] as const; +export const AppSettingsSection = Schema.Literals(APP_SETTINGS_SECTIONS); +export type AppSettingsSection = typeof AppSettingsSection.Type; + +/** A page of the user's window. A thread is always one from the agent's environment. */ +export const AppDestination = Schema.Union([ + Schema.Struct({ page: Schema.Literal("thread"), threadId: ThreadId }), + Schema.Struct({ page: Schema.Literal("settings"), section: Schema.optional(AppSettingsSection) }), + Schema.Struct({ page: Schema.Literals(["usage", "pull-requests"]) }), +]); +export type AppDestination = typeof AppDestination.Type; + +export const AppAction = Schema.Union([ + Schema.TaggedStruct("command", { command: AppCommand }), + Schema.TaggedStruct("navigate", { to: AppDestination }), +]); +export type AppAction = typeof AppAction.Type; + +export const AppControlRequest = Schema.Struct({ + requestId: TrimmedNonEmptyString, + action: AppAction, +}); +export type AppControlRequest = typeof AppControlRequest.Type; + +export const AppControlSubscribeInput = Schema.Struct({ + /** Whether the window is in use as it subscribes, so a background reconnect is not. */ + focused: Schema.Boolean, +}); +export type AppControlSubscribeInput = typeof AppControlSubscribeInput.Type; + +export const AppControlResult = Schema.Literals([ + "ran", + /** Nothing on screen handles the command right now, or the window has no such page. */ + "not-handled", + /** The window isn't showing a thread or draft from the agent's environment. */ + "other-environment", +]); +export type AppControlResult = typeof AppControlResult.Type; + +export const AppControlResponseInput = Schema.Struct({ + requestId: TrimmedNonEmptyString, + result: AppControlResult, +}); +export type AppControlResponseInput = typeof AppControlResponseInput.Type; diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index b211332c1c8b8..0d22a4e750880 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -54,6 +54,9 @@ export const CLIENT_GUARDED_RPC_SCOPES = { // Writing a guide runs a model on this environment's providers, which reading one does not. [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope, + [WS_METHODS.projectsMoveThread]: AuthOrchestrationOperateScope, + [WS_METHODS.projectsImportThread]: AuthOrchestrationOperateScope, + [WS_METHODS.projectsFinishThreadMove]: AuthOrchestrationOperateScope, [WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlStar]: AuthSourceControlWriteScope, diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 34c8688316ae2..ef9402702d26b 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -139,6 +139,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ threadActiveReorder: Schema.optionalKey(Schema.Boolean), threadAutoSettleOptOut: Schema.optionalKey(Schema.Boolean), threadProjectFromScratch: Schema.optionalKey(Schema.Boolean), + threadMoveToProject: Schema.optionalKey(Schema.Boolean), + threadMoveToMachine: Schema.optionalKey(Schema.Boolean), threadTitleRegeneration: Schema.optionalKey(Schema.Boolean), threadVisitedTracking: Schema.optionalKey(Schema.Boolean), threadPullRequestLinking: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index d7af43291a061..255f5fe7d805a 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -2,6 +2,7 @@ export * from "./baseSchemas.ts"; export * from "./assistantCitations.ts"; export * from "./composerContext.ts"; export * from "./composerContextClipboard.ts"; +export * from "./appControl.ts"; export * from "./background.ts"; export * from "./acpRegistry.ts"; export * from "./auth.ts"; diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index eda5138b760b9..ea0db35f612c5 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -45,6 +45,10 @@ const THREAD_KEYBINDING_COMMANDS = [ "thread.pin", "thread.regenerateTitle", "thread.undo", + "thread.restartSession", + "thread.showPullRequests", + "thread.linkPullRequest", + "thread.shareWithGuest", ...THREAD_JUMP_KEYBINDING_COMMANDS, ] as const; @@ -93,6 +97,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "composer.sendBackground", "composer.sendAndNewThread", "composer.dictation", + "composer.toggleVimMode", "composer.host", "composer.cycleHost", "composer.effort", diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8b05c12e17871..ce749b4ae6aa0 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -483,6 +483,8 @@ export const OrchestrationV2AppThread = Schema.Struct({ interactionMode: ProviderInteractionMode, branch: Schema.NullOr(TrimmedNonEmptyString), worktreePath: Schema.NullOr(TrimmedNonEmptyString), + /** Set when a move changed the thread's folder, so later checkpoints keep their own repository. */ + checkpointScopeProjectId: Schema.optional(ProjectId), linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)), branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), @@ -3800,6 +3802,18 @@ const OrchestrationV2InternalCommand = Schema.Union([ text: Schema.String, attachments: Schema.optional(Schema.Array(ChatAttachment)), }), + /** + * Moves an idle thread into another project's root folder. A changed folder ends its provider + * sessions, so the next turn resumes or hands off the conversation there. + */ + Schema.Struct({ + type: Schema.Literal("thread.project.move"), + commandId: CommandId, + threadId: ThreadId, + projectId: ProjectId, + /** The target root's current branch, read by the caller. */ + branch: Schema.NullOr(TrimmedNonEmptyString), + }), /** Moves a thread to a project rooted at the folder it already works in, so its cwd never changes. */ Schema.Struct({ type: Schema.Literal("thread.project.adopt-folder"), diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 0077ef78020d8..72c5de50a1b8d 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -3,6 +3,7 @@ import * as SchemaTransformation from "effect/SchemaTransformation"; import * as Struct from "effect/Struct"; import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts"; import { ModelSelection } from "./modelSelection.ts"; +import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts"; import { CommandId, ForwardCompatibleUnion, @@ -591,6 +592,72 @@ export const ProjectCreateFromThreadResult = Schema.Struct({ }); export type ProjectCreateFromThreadResult = typeof ProjectCreateFromThreadResult.Type; +export const ProjectMoveThreadInput = Schema.Struct({ + threadId: ThreadId, + projectId: ProjectId, +}); +export type ProjectMoveThreadInput = typeof ProjectMoveThreadInput.Type; + +/** + * A thread's conversation as another environment can import it. Checkpoints, runs, provider + * sessions and attachments belong to the machine that made them, so they stay behind. + */ +export const ThreadMoveBundle = Schema.Struct({ + title: TrimmedNonEmptyString, + modelSelection: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: ProviderInteractionMode, + createdAt: IsoDateTime, + messages: Schema.Array( + Schema.Struct({ + role: Schema.Literals(["user", "assistant"]), + text: Schema.String, + createdAt: IsoDateTime, + }), + ), +}); +export type ThreadMoveBundle = typeof ThreadMoveBundle.Type; + +export const ProjectExportThreadInput = Schema.Struct({ threadId: ThreadId }); +export type ProjectExportThreadInput = typeof ProjectExportThreadInput.Type; + +/** What a move leaves on the source environment, so messages name only what applies. */ +export const ThreadMoveLeftBehind = Schema.Struct({ + diffs: Schema.Boolean, + worktree: Schema.Boolean, + attachments: NonNegativeInt, + scheduledTasks: NonNegativeInt, +}); + +export const ProjectExportThreadResult = Schema.Struct({ + bundle: ThreadMoveBundle, + leftBehind: ThreadMoveLeftBehind, + /** The thread's runs at export; finishing the move refuses once a new one has started. */ + revision: Schema.String, +}); +export type ProjectExportThreadResult = typeof ProjectExportThreadResult.Type; + +export const ProjectImportThreadInput = Schema.Struct({ + projectId: ProjectId, + bundle: ThreadMoveBundle, + /** The source machine as the user knows it, for the new thread's notice. */ + movedFrom: TrimmedNonEmptyString, + leftBehind: ThreadMoveLeftBehind, +}); +export type ProjectImportThreadInput = typeof ProjectImportThreadInput.Type; + +export const ProjectImportThreadResult = Schema.Struct({ threadId: ThreadId }); +export type ProjectImportThreadResult = typeof ProjectImportThreadResult.Type; + +export const ProjectFinishThreadMoveInput = Schema.Struct({ + threadId: ThreadId, + /** Where the conversation went, as the user knows it, for the archived thread's notice. */ + movedTo: TrimmedNonEmptyString, + /** From the export the target imported, so newer work is never archived unseen. */ + revision: Schema.String, +}); +export type ProjectFinishThreadMoveInput = typeof ProjectFinishThreadMoveInput.Type; + export class ProjectWriteFileError extends Schema.TaggedError()( "ProjectWriteFileError", { diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index e30bf9af2937c..b079a6fd31155 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -92,6 +92,11 @@ import { AuthAccessStreamEvent, EnvironmentAuthorizationError, } from "./auth.ts"; +import { + AppControlRequest, + AppControlResponseInput, + AppControlSubscribeInput, +} from "./appControl.ts"; import { ClientActivityReportInput } from "./background.ts"; import { FilesystemGetMetadataInput, @@ -293,6 +298,12 @@ import { ProjectCreateNewResult, ProjectCreateFromThreadInput, ProjectCreateFromThreadResult, + ProjectMoveThreadInput, + ProjectExportThreadInput, + ProjectExportThreadResult, + ProjectImportThreadInput, + ProjectImportThreadResult, + ProjectFinishThreadMoveInput, ProjectEnsureScratchResult, ProjectListEntriesError, ProjectListEntriesInput, @@ -477,6 +488,10 @@ export const WS_METHODS = { projectsEnsureScratch: "projects.ensureScratch", projectsCreateNew: "projects.createNew", projectsCreateFromThread: "projects.createFromThread", + projectsMoveThread: "projects.moveThread", + projectsExportThread: "projects.exportThread", + projectsImportThread: "projects.importThread", + projectsFinishThreadMove: "projects.finishThreadMove", shellOpenInEditor: "shell.openInEditor", @@ -703,6 +718,8 @@ export const WS_METHODS = { worktreeSetupCancel: "worktreeSetup.cancel", subscribeTerminalMetadata: "subscribeTerminalMetadata", subscribePreviewEvents: "subscribePreviewEvents", + subscribeAppControl: "subscribeAppControl", + appControlRespond: "appControl.respond", subscribeDiscoveredLocalServers: "subscribeDiscoveredLocalServers", subscribeDeviceState: "subscribeDeviceState", subscribeServerConfig: "subscribeServerConfig", @@ -1653,6 +1670,28 @@ const WsProjectsCreateFromThreadRpc = Rpc.make(WS_METHODS.projectsCreateFromThre error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), }); +const WsProjectsMoveThreadRpc = Rpc.make(WS_METHODS.projectsMoveThread, { + payload: ProjectMoveThreadInput, + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), +}); + +const WsProjectsExportThreadRpc = Rpc.make(WS_METHODS.projectsExportThread, { + payload: ProjectExportThreadInput, + success: ProjectExportThreadResult, + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), +}); + +const WsProjectsImportThreadRpc = Rpc.make(WS_METHODS.projectsImportThread, { + payload: ProjectImportThreadInput, + success: ProjectImportThreadResult, + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), +}); + +const WsProjectsFinishThreadMoveRpc = Rpc.make(WS_METHODS.projectsFinishThreadMove, { + payload: ProjectFinishThreadMoveInput, + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]), +}); + const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, { payload: LaunchEditorInput, error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]), @@ -1989,6 +2028,18 @@ const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewEvents, stream: true, }); +const WsSubscribeAppControlRpc = Rpc.make(WS_METHODS.subscribeAppControl, { + payload: AppControlSubscribeInput, + success: AppControlRequest, + error: EnvironmentAuthorizationError, + stream: true, +}); + +const WsAppControlRespondRpc = Rpc.make(WS_METHODS.appControlRespond, { + payload: AppControlResponseInput, + error: EnvironmentAuthorizationError, +}); + const WsPreviewStopLocalServerRpc = Rpc.make(WS_METHODS.previewStopLocalServer, { payload: PreviewStopLocalServerInput, error: Schema.Union([PreviewStopLocalServerError, EnvironmentAuthorizationError]), @@ -2520,6 +2571,10 @@ export const WsRpcGroup = RpcGroup.make( WsProjectsEnsureScratchRpc, WsProjectsCreateNewRpc, WsProjectsCreateFromThreadRpc, + WsProjectsMoveThreadRpc, + WsProjectsExportThreadRpc, + WsProjectsImportThreadRpc, + WsProjectsFinishThreadMoveRpc, WsProjectsWriteFileRpc, WsProjectsMutateRpc, WsShellOpenInEditorRpc, @@ -2578,6 +2633,8 @@ export const WsRpcGroup = RpcGroup.make( WsPreviewReportProfilesRpc, WsPreviewReportStatusRpc, WsSubscribePreviewEventsRpc, + WsSubscribeAppControlRpc, + WsAppControlRespondRpc, WsPreviewStopLocalServerRpc, WsSubscribeDiscoveredLocalServersRpc, WsDeviceConfigureRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b0726b07174c9..54520af163e85 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -526,6 +526,7 @@ export const ClientSettingsSchema = Schema.Struct({ pullRequestLinksOpenInApp: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), composerRichTextEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + composerVimMode: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), sendShortcut: Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"]).pipe( Schema.withDecodingDefault(Effect.succeed("enter")), ), @@ -555,6 +556,9 @@ export const ClientSettingsSchema = Schema.Struct({ threadDetailsItems: Schema.Record(Schema.String, Schema.Boolean).pipe( Schema.withDecodingDefault(Effect.succeed({})), ), + threadDetailsOpenByDefault: Schema.Boolean.pipe( + Schema.withDecodingDefault(Effect.succeed(false)), + ), sidebarWorkingShelfEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)), @@ -2109,6 +2113,7 @@ export const ClientSettingsPatch = Schema.Struct({ ), pullRequestLinksOpenInApp: Schema.optionalKey(Schema.Boolean), composerRichTextEnabled: Schema.optionalKey(Schema.Boolean), + composerVimMode: Schema.optionalKey(Schema.Boolean), sendShortcut: Schema.optionalKey(Schema.Literals(["enter", "mod-enter-multiline", "mod-enter"])), followUpBehavior: Schema.optionalKey(Schema.Literals(["queue", "steer"])), sideThreadOpenTarget: Schema.optionalKey(SideThreadOpenTarget), @@ -2121,6 +2126,7 @@ export const ClientSettingsPatch = Schema.Struct({ screenReaderWindowTitle: Schema.optionalKey(Schema.Boolean), threadDetailsUsageEnabled: Schema.optionalKey(Schema.Boolean), threadDetailsItems: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)), + threadDetailsOpenByDefault: Schema.optionalKey(Schema.Boolean), sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean), sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode), sidebarProjectGroupingOverrides: Schema.optionalKey( diff --git a/packages/shared/package.json b/packages/shared/package.json index b1ffa038030ef..8a704e709446f 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -3,6 +3,10 @@ "private": true, "type": "module", "exports": { + "./threadMove": { + "types": "./src/threadMove.ts", + "import": "./src/threadMove.ts" + }, "./png": { "types": "./src/png.ts", "import": "./src/png.ts" diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 9a67264d8bd1f..ca79492e7086b 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -63,6 +63,8 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+f6", command: "workspace.focusPrevious" }, { key: "mod+[", command: "navigation.back", when: "!terminalFocus" }, { key: "mod+]", command: "navigation.forward", when: "!terminalFocus" }, + // VS Code's chord uses Ctrl on every platform. Listed before mod+j so labels show mod+j. + { key: "ctrl+`", command: "terminal.toggle" }, { key: "mod+j", command: "terminal.toggle" }, { key: "mod+alt+b", command: "rightPanel.toggle" }, { key: "mod+shift+b", command: "threadPanel.toggle", when: "!terminalFocus" }, diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index fc2af2e05cc37..6c60c9b169ceb 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -55,6 +55,8 @@ export type T3McpToolSummaryAction = | "environment-link" | "environment-unlink" | "environment-update" + | "app-command" + | "app-navigate" | "theme-read" | "theme-set" | "attachment-prepare" @@ -415,10 +417,28 @@ const T3_MCP_TOOLS: Readonly> = { ["Forget", "Forgetting", "Forgot", "a linked environment"], "environment-unlink", ), - t3_environment_preferences_update: tool( - ["Update", "Updating", "Updated", "environment preferences"], + t3_environment_settings_read: tool( + ["Read", "Reading", "Read", "environment settings"], + "environment-read", + ), + t3_environment_settings_update: tool( + ["Update", "Updating", "Updated", "environment settings"], + "environment-update", + ), + t3_keybindings_read: tool( + ["List", "Listing", "Listed", "keyboard shortcuts"], + "environment-read", + ), + t3_keybinding_upsert: tool( + ["Set", "Setting", "Set", "a keyboard shortcut"], + "environment-update", + ), + t3_keybinding_remove: tool( + ["Remove", "Removing", "Removed", "a keyboard shortcut"], "environment-update", ), + t3_app_command: tool(["Run", "Running", "Ran", "an app command"], "app-command"), + t3_app_navigate: tool(["Open", "Opening", "Opened", "a page in the app"], "app-navigate"), t3_theme_read: tool(["Read", "Reading", "Read", "themes"], "theme-read"), t3_theme_set: tool(["Set", "Setting", "Set", "the theme"], "theme-set"), t3_thread_launch: tool(["Launch", "Launching", "Launched", "a project thread"], "thread-create"), diff --git a/packages/shared/src/threadMove.ts b/packages/shared/src/threadMove.ts new file mode 100644 index 0000000000000..3da835d59091e --- /dev/null +++ b/packages/shared/src/threadMove.ts @@ -0,0 +1,39 @@ +/** What moving a thread to another project changes, worded the same for people and agents. */ +export function threadMoveNotice(input: { + readonly projectTitle: string; + readonly fromWorktree: boolean; +}): string { + return input.fromWorktree + ? `The agent will work in ${input.projectTitle}'s root folder. The worktree and its branch stay on disk, but the agent won't see changes left there. Earlier diffs open while the worktree exists, and files from earlier turns can't be restored.` + : `The conversation moves with it, and the agent works in ${input.projectTitle}'s folder from the next message. Earlier diffs open while their original folder exists, and files from earlier turns can't be restored.`; +} + +interface ThreadMoveLeftBehind { + readonly diffs: boolean; + readonly worktree: boolean; + readonly attachments: number; + readonly scheduledTasks: number; +} + +/** "Files, diffs and 2 attachments": what a machine move leaves on the source, naming only what applies. */ +export function threadMoveLeftBehindList(leftBehind: ThreadMoveLeftBehind): string { + const count = (n: number, noun: string) => `${n} ${noun}${n === 1 ? "" : "s"}`; + const stays = [ + "Files", + ...(leftBehind.diffs ? ["diffs"] : []), + ...(leftBehind.worktree ? ["the worktree"] : []), + ...(leftBehind.attachments > 0 ? [count(leftBehind.attachments, "attachment")] : []), + ...(leftBehind.scheduledTasks > 0 ? [count(leftBehind.scheduledTasks, "scheduled task")] : []), + ]; + return stays.length === 1 ? "Files" : `${stays.slice(0, -1).join(", ")} and ${stays.at(-1)}`; +} + +/** What moving a thread to another machine carries and leaves behind. */ +export function threadMachineMoveNotice(input: { + readonly fromMachine: string; + readonly toMachine: string; + readonly projectTitle: string; + readonly leftBehind: ThreadMoveLeftBehind; +}): string { + return `The conversation moves to ${input.projectTitle} on ${input.toMachine} and continues in a new session there. ${threadMoveLeftBehindList(input.leftBehind)} stay on ${input.fromMachine}, where this thread is archived. Unarchive it to come back.`; +} diff --git a/scripts/sanucode b/scripts/sanucode new file mode 100755 index 0000000000000..9077d6bd8944c --- /dev/null +++ b/scripts/sanucode @@ -0,0 +1,79 @@ +#!/bin/sh +# Sanu Code: runs this fork from source beside an installed T3 Code, with its own data in ~/.sanucode. +# sanucode serve the web app (extra flags pass through, e.g. --share --built) +# sanucode app open the desktop app (shares data with the web app; run one at a time) +# sanucode import replace Sanu Code's threads and preferences with a fresh copy of T3 Code's +# sanucode install link `sanucode` and `sn` in ~/.local/bin to this checkout +set -eu + +repo=$(cd "$(dirname "$(realpath "$0")")/.." && pwd) +home="$HOME/.sanucode" + +case "${1:-}" in + help | -h | --help) + sed -n '2,6s/^# //p' "$repo/scripts/sanucode" + exit 0 + ;; + install) + bin="$HOME/.local/bin" + mkdir -p "$bin" + ln -sfn "$repo/scripts/sanucode" "$bin/sanucode" + ln -sfn sanucode "$bin/sn" + echo "Linked sanucode and sn in $bin to $repo." + case ":$PATH:" in + *":$bin:"*) ;; + *) echo "Add $bin to your PATH to use them." ;; + esac + exit 0 + ;; +esac + +if ! command -v vp >/dev/null 2>&1; then + echo "sanucode: vp is not installed. See \"Install vp\" in $repo/README.md." >&2 + exit 1 +fi + +# An explicit version keeps the pinned Node even when vp defers to a system Node such as nvm's. +node_version=$(sed -n 's/^ *"node": "\([0-9.]*\)".*/\1/p' "$repo/package.json" | head -n 1) +cd "$repo" + +case "${1:-}" in + app) + shift + set -- dev:desktop --home-dir "$home" "$@" + ;; + import) + t3_data="$HOME/.t3/userdata" + data="$home/userdata" + backup="$home/backup" + prefs="settings.json keybindings.json keybindings-migrations client-settings.json" + + # SQLite removes the -wal file on a clean shutdown, so its presence means Sanu Code is open. + if [ -e "$data/statev2.sqlite-wal" ]; then + echo "sanucode: Sanu Code is running. Quit it, then import again." >&2 + exit 1 + fi + + mkdir -p "$data" "$backup" + for file in statev2.sqlite $prefs; do + if [ -f "$data/$file" ]; then cp "$data/$file" "$backup/"; fi + done + + vp env exec --node "$node_version" vp run migrate-dev-db \ + --base-dir "$home" --projects 1000 --threads-per-project 1000 + + for file in $prefs; do + if [ -f "$t3_data/$file" ]; then cp "$t3_data/$file" "$data/"; fi + done + + echo + echo "Imported T3 Code. Threads still running there were skipped." + echo "Previous Sanu Code data is in $backup." + exit 0 + ;; + *) + set -- dev --home-dir "$home" --host 0.0.0.0 --no-auto-bootstrap-project-from-cwd "$@" + ;; +esac + +exec vp env exec --node "$node_version" vp run "$@"