diff --git a/AGENTS.md b/AGENTS.md index 5ec4b9461..017649c5f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,6 +106,7 @@ app/api/ sessions/[id]/context/route.ts GET ?leafId= — context for a specific leaf sessions/[id]/matches/route.ts GET ?q=&limit= — best `limit` search hits in the active conversation (best match, then newest); Load more asks for a longer prefix sessions/[id]/export/route.ts GET exported HTML for a session + sessions/[id]/move/route.ts POST { hostId?, cwd } move a stopped session into a workspace of any host: `omp session pack` on its host, chunked over the links (`readSessionPack`/`writeSessionPack`), `omp session unpack` on the target, whose arrival marker is reworded to name hosts, workspaces, home and OS; a copy left on another host is marked moved and archived (`finishSessionMove`). 409 `session_busy` while running, `session_has_children` for a parent sessions/[id]/local-file/route.ts GET ?uri=local:// → `{ path, sessionId }`: the absolute path of a file in the session's own local:// directory, resolved on the owning host's daemon, and the canonical session that owns it (a live alias resolves to its current id; the tab must store that, since the alias goes with its wrapper). The open_file host tool then reads it through /api/files with that `sessionId`; 400 `invalid_local_uri` / `not_a_file`, 404 `session_not_found` / `file_not_found`, 403 on a symlink out, 501 `workspace_unsupported` for a host daemon that predates `resolveLocalFile` agent/new/route.ts POST { cwd, message, toolNames?, provider?, modelId? } agent/[id]/route.ts GET state | POST any channel command @@ -159,6 +160,7 @@ lib/ local-bootstrap.ts web server side of the local link: `localLinkUrl`, `ensureLocalHostLink` (the `local` record + `host.json`) host-login.ts `host.json` (`loginHost`, `readHostLogin`) and `isLoopbackHost`, shared by the daemon and local-bootstrap session-ops.ts file-reading half of the session/project routes, run on the owning host's daemon (this machine's too) + session-transfer.ts daemon side of a session move: the `omp session pack|unpack|moved` calls, transfer archives in `/omp-web/transfers/` (swept after 24 h), the reworded arrival marker uploads.ts daemon side of composer uploads: `StagedUploads` (staging dir `/omp-web/uploads/`, offset writes, 24 h sweep, attach into the session's `local/uploads/`), `sanitizeUploadName` upload-retention.ts daemon side of sent-upload retention: `UploadRetention` (op `setUploadRetention`, `/omp-web/upload-retention.json`, sweep at start and every 24 h), `sweepSentUploads`; `upload-retention-sync.ts` is main's side (`startUploadRetentionSync` on every hello, `pushUploadRetention` when the setting changes) link-protocol.ts link messages, codec, binary blob frames, close codes, size limits, `HOST_OP_NAMES`, `SeqWindow`/`Outbox`, `LinkSender`/`PartJoiner` (pieces, fair sending) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec584eb19..745dd290f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **Move sessions by drag and drop.** Drag a session onto another workspace in the sidebar, on the same host or another one. The session is told where it came from: host, working directory, home directory and operating system. A copy left on another host is archived there. + ### Fixed - **Windows updates no longer fail when the update status is read while it is written.** Host update state, the server worker's status and upgrade plans retry their atomic replacement for a moment when a concurrent reader holds the file, as the server's own update state already did. diff --git a/app/api/sessions/[id]/move/route.ts b/app/api/sessions/[id]/move/route.ts new file mode 100644 index 000000000..6579c00bf --- /dev/null +++ b/app/api/sessions/[id]/move/route.ts @@ -0,0 +1,144 @@ +import { hostname } from "os"; +import { apiErrorResponse, hostOfflineResponse, opErrorResponse, resolveHostOrError, resolveSessionHostOr404 } from "@/lib/api-utils"; +import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import { comparableProjectPath } from "@/lib/comparable-path"; +import type { Host } from "@/lib/hosts/host"; +import { HostOpError } from "@/lib/hosts/link-protocol"; +import { customLocalLabel, LOCAL_HOST_ID } from "@/lib/hosts/registry"; +import { invalidateHostSessionList } from "@/lib/hosts/session-index"; +import { clearExitedRpcSession, getRpcSession, getRunningRpcSessionIds } from "@/lib/rpc-manager"; + +/** Session ids with a move in progress in this server process. */ +const sessionsMoving = new Set(); + +/** Characters `cmd.exe` interprets as command syntax when passing an unquoted argument to a `.cmd`/`.bat` launcher. */ +const CMD_META_RE = /[&|<>^%!"\r\n\0]/; + +/** The name the moved session reads: "This machine" says nothing to the model. */ +function sessionHostName(host: Host): string { + return host.id === LOCAL_HOST_ID ? customLocalLabel() || hostname() : host.label; +} + +/** Copies a packed archive from `source` to `target` over the two links, one chunk per round trip. */ +async function copyPack(source: Host, target: Host, transfer: string, bytes: number): Promise { + for (let offset = 0; offset < bytes;) { + const chunk = await source.sessionOps.readSessionPack(transfer, offset); + if (!chunk.ok) throw new HostOpError(chunk.status, chunk.code, chunk.error); + if (chunk.value.byteLength === 0) throw new HostOpError(502, "transfer_truncated", `${source.label} sent a truncated session archive`); + const written = await target.sessionOps.writeSessionPack(transfer, offset, Buffer.from(chunk.value).toString("base64")); + if (!written.ok) throw new HostOpError(written.status, written.code, written.error); + const nextOffset = offset + chunk.value.byteLength; + if (written.value.bytes !== nextOffset) { + throw new HostOpError(502, "host_bad_result", `${target.label} reported an unexpected session archive offset`); + } + offset = nextOffset; + } +} + +/** POST /api/sessions/[id]/move body: { hostId?: string, cwd: string } — move a stopped session into workspace `cwd` + * of host `hostId` (this machine when absent). omp packs it with its artifacts and blobs and unpacks it there, which + * tells the session where it came from; a copy left on another host is marked moved and archived. */ +export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + let reserved = false; + try { + const { hostId, cwd } = await parseJsonWithinLimit<{ hostId?: unknown; cwd?: unknown }>(req, 64 * 1024); + if (typeof cwd !== "string" || !cwd.trim()) { + return Response.json({ error: "cwd is required", code: "cwd_required" }, { status: 400 }); + } + const resolved = await resolveSessionHostOr404(id); + if ("response" in resolved) return resolved.response; + const source = resolved.host; + const offline = hostOfflineResponse(source); + if (offline) return offline; + const targetResolved = resolveHostOrError(hostId); + if ("response" in targetResolved) return targetResolved.response; + const target = targetResolved.host; + + // Check and reserve in one synchronous step, before any await. + if (sessionsMoving.has(id)) { + return Response.json({ error: "This session is already moving", code: "session_busy" }, { status: 409 }); + } + sessionsMoving.add(id); + reserved = true; + + if (getRunningRpcSessionIds().includes(id) || getRpcSession(id)?.isEditingHistory()) { + return Response.json({ error: "Wait for the response to finish before moving this session", code: "session_busy" }, { status: 409 }); + } + // Children may name their parent by path, which the move changes. + const sessions = await source.sessionOps.listSessions(); + if (sessions.some((session) => session.parentSessionId === id)) { + return Response.json({ error: "Move child sessions before moving this session", code: "session_has_children" }, { status: 409 }); + } + const selected = await target.sessionOps.validateCwd(cwd); + if (!selected.ok) return opErrorResponse(selected); + const { cwd: destination, projectRoot } = selected.value; + const sameHost = source.id === target.id; + const destinationLabel = `${sessionHostName(target)}:${destination}`; + if (CMD_META_RE.test(sameHost ? destination : destinationLabel)) { + return Response.json({ error: "The destination path contains characters that cmd.exe reads as syntax", code: "invalid_destination" }, { status: 400 }); + } + const current = sessions.find((session) => session.id === id); + if (sameHost && current && comparableProjectPath(current.cwd) === comparableProjectPath(destination)) { + return Response.json({ ok: true, sessionId: id, hostId: target.id, cwd: destination, projectRoot }); + } + + const live = getRpcSession(id); + if (!live?.hostOwnedLifecycle) await live?.destroyAndWait?.("move", true); + const packed = await source.sessionOps.packSession(id); + if (!packed.ok) return opErrorResponse(packed); + const { transfer, bytes, home, platform } = packed.value; + + let sessionId: string; + let unpackSent = false; + try { + if (!sameHost) await copyPack(source, target, transfer, bytes); + unpackSent = true; + const unpacked = await target.sessionOps.unpackSession(transfer, destination, { + host: sessionHostName(target), + from: sameHost ? null : { host: sessionHostName(source), home, platform }, + }); + if (!unpacked.ok) throw new HostOpError(unpacked.status, unpacked.code, unpacked.error); + sessionId = unpacked.value.sessionId; + } catch (error) { + if (unpackSent && error instanceof HostOpError && error.code === "host_offline") { + // The destination may have already unpacked the session before the reply was lost; keep the destination untouched. + if (!sameHost) await source.sessionOps.discardSessionPack(transfer).catch(() => {}); + return Response.json( + { error: `${target.label} went offline before confirming the move; check ${target.label} before retrying`, code: "move_outcome_unknown", hostOffline: true }, + { status: 503 }, + ); + } + await Promise.allSettled([source.sessionOps.discardSessionPack(transfer), ...(sameHost ? [] : [target.sessionOps.discardSessionPack(transfer)])]); + throw error; + } finally { + invalidateHostSessionList(target.id); + } + + // The session now lives on the target; a copy left behind would be listed twice. + let staleCopy: string | undefined; + if (!sameHost) { + const retired = await source.sessionOps.finishSessionMove(id, transfer, destinationLabel) + .catch((error: unknown) => ({ ok: false as const, error: error instanceof Error ? error.message : String(error) })); + if (!retired.ok) { + staleCopy = retired.error; + console.warn(`[omp-web] session ${id} moved to ${target.label}, but its copy on ${source.label} was not retired: ${retired.error}`); + } + invalidateHostSessionList(source.id); + } + clearExitedRpcSession(id); + return Response.json({ ok: true, sessionId, hostId: target.id, cwd: destination, projectRoot, ...(staleCopy ? { staleCopy } : {}) }); + } catch (error) { + if (error instanceof RequestBodyTooLargeError) { + return Response.json({ error: "Request body is too large", code: "request_too_large" }, { status: 413 }); + } + if (error instanceof SyntaxError) { + return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); + } + if (error instanceof HostOpError) return apiErrorResponse(error); + console.error("[api/sessions/move]", error); + return Response.json({ error: "Session move failed", code: "session_move_failed" }, { status: 500 }); + } finally { + if (reserved) sessionsMoving.delete(id); + } +} diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 85795fb82..f21454e4c 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -1321,7 +1321,8 @@ export function AppShell({ appName }: { appName: string }) { setSidebarOpen(false); requestAnimationFrame(() => chatInputRef.current?.focus()); } - if (!isRestore && selectedSession && sameSessionTarget(session, selectedSession)) return; + // A move within the same host keeps the session ID but still needs to reopen the chat. + if (!isRestore && selectedSession && session.cwd === selectedSession.cwd && sameSessionTarget(session, selectedSession)) return; setNewSessionCwd(null); setNewSessionPoolProject(null); setSelectedSession(session); diff --git a/components/SessionSidebar-rows.tsx b/components/SessionSidebar-rows.tsx index 9ecab4530..9b8890594 100644 --- a/components/SessionSidebar-rows.tsx +++ b/components/SessionSidebar-rows.tsx @@ -27,6 +27,10 @@ import { UnreadSessionIndicator, } from "./SessionSidebar-chrome"; +/** Drag data of a session row; readable only on drop, so a drop target checks the type alone while dragging. */ +const SESSION_DRAG_TYPE = "application/x-ompweb-session"; +type DraggedSession = Pick; + /** * Shared indicator sizing; session rows keep theirs in the right-edge column. * @@ -113,6 +117,8 @@ interface ProjectRowProps { onUpdatePresentation: (project: ManagedProject, updates: { alias?: string | null; sortOrder?: number | null; launchConfig?: ProjectLaunchConfig | null }) => Promise; onDragProjectChange: (project: ManagedProject | null) => void; onDropProject: (project: ManagedProject) => void; + /** Set when a session dragged here can move into this workspace. */ + onDropSession?: (session: DraggedSession, project: ManagedProject) => void; onMoveProject: (project: ManagedProject, delta: -1 | 1) => void; /** A sort is active: show the pin toggle; only pinned rows reorder by hand. */ pinnable: boolean; @@ -153,6 +159,7 @@ function ProjectRow({ onUpdatePresentation, onDragProjectChange, onDropProject, + onDropSession, onMoveProject, pinnable, onTogglePin, @@ -173,6 +180,7 @@ function ProjectRow({ const [actionMenuOpen, setActionMenuOpen] = useState(false); const [confirmRemove, setConfirmRemove] = useState(false); const actionButtonRef = useRef(null); + const [sessionDropActive, setSessionDropActive] = useState(false); const [aliasEditing, setAliasEditing] = useState(false); const [aliasValue, setAliasValue] = useState(""); const aliasInputRef = useRef(null); @@ -205,7 +213,30 @@ function ProjectRow({ : tree; return ( -
+
{ + if (!event.dataTransfer.types.includes(SESSION_DRAG_TYPE)) return; + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + setSessionDropActive(true); + } : undefined} + onDragLeave={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setSessionDropActive(false); }} + onDrop={onDropSession ? (event) => { + const data = event.dataTransfer.getData(SESSION_DRAG_TYPE); + setSessionDropActive(false); + if (!data) return; + event.preventDefault(); + onDropSession(JSON.parse(data) as DraggedSession, project); + } : undefined} + style={{ + marginBottom: 12, + opacity: node?.unavailableReason ? 0.55 : 1, + borderRadius: "var(--radius-control)", + ...(sessionDropActive ? { outline: "1px solid var(--accent)", outlineOffset: -1 } : {}), + }} + > {node?.unavailableReason && {node.unavailableReason}}
{ + const dragged: DraggedSession = { id: session.id, hostId: session.hostId, cwd: session.cwd, projectRoot: session.projectRoot }; + event.dataTransfer.setData(SESSION_DRAG_TYPE, JSON.stringify(dragged)); + event.dataTransfer.effectAllowed = "move"; + }} className="session-item-row" onContextMenu={(event) => { if (renaming || confirmDelete || deleting) return; @@ -975,5 +1012,6 @@ export { ProjectRow, SessionItem, SessionTreeItem, + type DraggedSession, type ProjectRowProps, }; diff --git a/components/SessionSidebar.tsx b/components/SessionSidebar.tsx index bdda72a1c..12e28c6bf 100644 --- a/components/SessionSidebar.tsx +++ b/components/SessionSidebar.tsx @@ -52,7 +52,7 @@ import { hostsCameOnline, } from "./SessionSidebar-helpers"; import { OmpWebTitle, SIDEBAR_BUTTON_TRANSITION, SidebarIconButton, SidebarPortalMenu } from "./SessionSidebar-chrome"; -import { HostGroup, ProjectRow } from "./SessionSidebar-rows"; +import { HostGroup, ProjectRow, type DraggedSession } from "./SessionSidebar-rows"; /** Deadline for one /api/sessions fetch. A wedged-but-listening server never * answers; without this the initial spinner would pend forever. */ @@ -161,6 +161,10 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, }, [hosts, pools]); const selectedWorkspaceRef = useRef(""); selectedWorkspaceRef.current = hostProjectKey(selectedHostId, selectedCwd ?? ""); + const selectedSessionIdRef = useRef(selectedSessionId); + selectedSessionIdRef.current = selectedSessionId; + const allSessionsRef = useRef(allSessions); + allSessionsRef.current = allSessions; // Host group headers only exist once a remote host is linked. const showHostGroups = hostList.some((host) => host.id !== LOCAL_HOST_ID); // The server renders no groups; collapse state is read after mount. @@ -1457,6 +1461,31 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, loadSessions(); }, [allSessions, onSessionDeleted, loadSessions]); + const handleSessionDrop = useCallback(async (dragged: DraggedSession, project: ManagedProject) => { + if (hostOf(dragged) === hostOf(project) && comparableProjectPath(dragged.projectRoot ?? dragged.cwd) === comparableProjectPath(project.path)) return; + const name = project.alias ?? project.name ?? projectLabel(project.path); + try { + const res = await fetch(`/api/sessions/${encodeURIComponent(dragged.id)}/move`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ hostId: hostOf(project), cwd: project.path }), + }); + const data = await res.json().catch(() => ({})) as { sessionId?: string; hostId?: string; cwd?: string; projectRoot?: string; staleCopy?: string; error?: string; code?: string }; + if (!res.ok || !data.sessionId) { + toast.error(t("sessionSidebar.moveFailed"), formatApiError({ ...data, error: data.error ?? `HTTP ${res.status}` })); + return; + } + toast.success(t("sessionSidebar.moved", { name }), data.staleCopy ? t("sessionSidebar.moveStaleCopy", { error: data.staleCopy }) : undefined); + const moved = allSessionsRef.current.find((session) => session.id === dragged.id); + if (moved && selectedSessionIdRef.current === dragged.id) { + handleSelectSessionFromList({ ...moved, id: data.sessionId, hostId: data.hostId, cwd: data.cwd ?? project.path, projectRoot: data.projectRoot, poolId: undefined, projectId: undefined, projectKey: undefined, worktreeBranch: undefined }); + } + loadSessions(); + } catch (error) { + toast.error(t("sessionSidebar.moveFailed"), error instanceof Error ? error.message : String(error)); + } + }, [handleSelectSessionFromList, loadSessions, t]); + useEffect(() => { const selected = allSessions.find((session) => session.id === selectedSessionId); if (selected) setLastOpenSession(hostProjectKey(selected.hostId, workspaceKeyOf(selected)), selected.id); @@ -1843,6 +1872,7 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, pinnable={pinsActive} onTogglePin={handleTogglePin} isDragTarget={draggedProject !== null && projectTargetId(draggedProject, pools) === projectTargetId(project, pools) && projectIdentity(draggedProject) !== projectKey && (!pinsActive || project.pinOrder !== undefined)} + onDropSession={project.poolId || hostUnavailableReason(hostOf(project)) ? undefined : handleSessionDrop} removeBusy={removeProjectKey === projectKey} onSelectSession={handleSelectSessionFromList} searchQuery={trimmedSearchQuery || undefined} diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index 09d0f3939..70ae6d9da 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -651,3 +651,52 @@ test("stderr is dropped once startup settles and never logged on a later exit", h.children[0].exit(); assert.ok(!h.logs.some(line => line.includes("early text") || line.includes("late text")), h.logs.join(" | ")); }); + +test("refuseRunning rejects live turns without stopping the child while stopping idle channels", async (t) => { + const h = harness(); + t.after(() => h.table.stop()); + const opened = await h.table.open(h.a, { sessionId: SAVED, launch }); + h.table.release(h.a, opened.ch); + const child = h.children[0]; + ev(child, { type: "agent_start" }); + let actionRan = false; + await assert.rejects( + h.table.mutateSession(SAVED, async () => { actionRan = true; }, { refuseRunning: true }), + { status: 409, code: "session_busy" }, + ); + assert.equal(actionRan, false); + assert.deepEqual(child.kills, [], "a live running turn must not be killed by a move"); + + // Once settled (idle), refuseRunning stops the idle child cleanly before running action. + ev(child, { type: "agent_end", isTerminal: true }); + ev(child, { type: "session_settled" }); + await h.table.mutateSession(SAVED, async () => { actionRan = true; }, { refuseRunning: true }); + assert.equal(actionRan, true); + assert.deepEqual(child.kills, [false]); +}); + +test("move reservation fences channel open, adopt, and unrelated mutations until released or link drops", async (t) => { + const h = harness(); + t.after(() => h.table.stop()); + const transfer = "11111111-1111-4111-8111-111111111111"; + h.table.reserveMove(h.a, SAVED, transfer); + + await assert.rejects(h.table.open(h.b, { sessionId: SAVED, launch }), { status: 409, code: "session_busy" }); + const adopted = await h.spawn(launch); + await assert.rejects(h.table.adopt(adopted, launch, SAVED), { status: 409, code: "session_busy" }); + await assert.rejects(h.table.mutateSession(SAVED, async () => {}), { status: 409, code: "session_busy" }); + + let finished = false; + await h.table.mutateSession(SAVED, async () => { finished = true; }, { refuseRunning: true, moveTransfer: transfer }); + assert.equal(finished, true); + + h.table.releaseMove(transfer); + const reopened = await h.table.open(h.b, { sessionId: SAVED, launch }); + h.table.release(h.b, reopened.ch); + assert.equal(h.children.length, 2); + + // Link drop also releases an abandoned move reservation. + h.table.reserveMove(h.a, SAVED, transfer); + h.table.linkDown(h.a); + assert.equal(h.table.isMoving(SAVED), false); +}); diff --git a/lib/hosts/daemon-channels.ts b/lib/hosts/daemon-channels.ts index 003735354..a5f877aba 100644 --- a/lib/hosts/daemon-channels.ts +++ b/lib/hosts/daemon-channels.ts @@ -70,6 +70,8 @@ export class ChannelTable { private readonly goneLinks = new Set(); /** Exited channels whose open result is still queued for a paused member. */ private readonly exitedHandoffs = new Map(); + /** Session ids reserved by an in-flight move on this host, until unpack/retirement/discard or link drop. */ + private readonly moving = new Map(); private spawningCount = 0; private commandId = 0; private stopped = false; @@ -104,6 +106,9 @@ export class ChannelTable { if (!isRecord(args) || !(args.sessionId === null || typeof args.sessionId === "string" && isValidSessionId(args.sessionId)) || !isRecord(args.launch) || (args.replaceAdvisor !== undefined && typeof args.replaceAdvisor !== "boolean") || (args.preparing !== undefined && typeof args.preparing !== "boolean") || (args.expectedChannel !== undefined && (typeof args.expectedChannel !== "string" || !args.expectedChannel || args.replaceAdvisor === true))) throw invalid(); + if (args.sessionId !== null && this.moving.has(args.sessionId)) { + throw new HostOpError(409, "session_busy", "This session is currently being moved"); + } let channel: Channel; if (args.expectedChannel !== undefined) { const advertised = this.channels.get(args.expectedChannel); @@ -208,6 +213,9 @@ export class ChannelTable { const identity = id ?? this.identity(launch); const mutation = (identity === null ? undefined : this.mutating.get(identity)) ?? this.mutating.get(file); if (mutation) { await mutation; return this.ensure(id, requested, preparingLinkId); } + if (identity !== null && this.moving.has(identity)) { + throw new HostOpError(409, "session_busy", "This session is currently being moved"); + } const existing = this.find(identity, file); if (existing) { await existing.startup; @@ -249,6 +257,7 @@ export class ChannelTable { const prepared = this.deps.prepareLaunch(launch); const identity = (prepared.sessionFile ? this.identity(prepared) : null) ?? (sessionId && isValidSessionId(sessionId) ? sessionId : null); const key = identity ?? (prepared.sessionFile || null); + if (identity !== null && this.moving.has(identity)) throw new HostOpError(409, "session_busy", "This session is currently being moved"); if (this.find(identity, prepared.sessionFile) || (key !== null && this.spawning.has(key))) throw collision(); const channel = await this.create(prepared, identity, undefined, spawned); channel.opened = true; @@ -503,6 +512,7 @@ export class ChannelTable { for (const owner of channel.commands.values()) if (owner.link?.id === link.id) owner.link = null; } linkDown(link: DaemonLink): void { + this.releaseMovesForLink(link.id); for (const channel of this.channels.values()) { channel.lifecycle?.linkDown(link.id); channel.shared?.linkChanged(); // A restarted server forgets its edit; a dropped holder's edit fails as host_offline anyway. @@ -512,6 +522,7 @@ export class ChannelTable { linkUp(link: DaemonLink): void { for (const channel of this.channels.values()) { channel.lifecycle?.linkUp(link.id); channel.shared?.linkChanged(); } } linkGone(link: DaemonLink): void { this.goneLinks.add(link.id); + this.releaseMovesForLink(link.id); for (const [ch, channel] of this.exitedHandoffs) { channel.members.delete(link.id); if (![...channel.members.values()].some(member => member.paused)) this.exitedHandoffs.delete(ch); @@ -552,9 +563,45 @@ export class ChannelTable { return [entries[index]]; }); } - async mutateSession(id: string, action: (canonicalId: string, liveIds: string[]) => Promise): Promise { + reserveMove(link: DaemonLink, sessionId: string, transfer: string, ttlMs = 10 * 60_000): void { + const existing = this.moving.get(sessionId); + if (existing) clearTimeout(existing.timer); + const timer = setTimeout(() => { + if (this.moving.get(sessionId)?.transfer === transfer) this.moving.delete(sessionId); + }, ttlMs); + timer.unref?.(); + this.moving.set(sessionId, { transfer, linkId: link.id, timer }); + } + releaseMove(transfer: string): void { + for (const [sessionId, entry] of this.moving) { + if (entry.transfer === transfer) { + clearTimeout(entry.timer); + this.moving.delete(sessionId); + } + } + } + isMoving(sessionId: string): boolean { + return this.moving.has(sessionId); + } + private releaseMovesForLink(linkId: string): void { + for (const [sessionId, entry] of this.moving) { + if (entry.linkId === linkId) { + clearTimeout(entry.timer); + this.moving.delete(sessionId); + } + } + } + async mutateSession( + id: string, + action: (canonicalId: string, liveIds: string[]) => Promise, + options?: { refuseRunning?: boolean; moveTransfer?: string }, + ): Promise { if (!isValidSessionId(id)) throw invalid("Invalid session id"); while (this.mutating.has(id)) await this.mutating.get(id); + const moving = this.moving.get(id); + if (moving && moving.transfer !== options?.moveTransfer) { + throw new HostOpError(409, "session_busy", "This session is currently being moved"); + } const { promise, resolve } = Promise.withResolvers(); const keys = new Set([id]); const protect = (channel?: Channel) => { @@ -573,6 +620,9 @@ export class ChannelTable { channel = findTarget(); protect(channel); if (channel && !channel.exited) { + if (options?.refuseRunning && (channel.resuming === true || channel.editor !== undefined || (channel.lifecycle ? !channel.lifecycle.isIdle : channel.pending.activeTurn))) { + throw new HostOpError(409, "session_busy", "Wait for the response to finish before moving this session"); + } const exit = Promise.withResolvers(); channel.transport.onExit(() => exit.resolve()); this.stopChannel(channel); await exit.promise; } @@ -591,6 +641,8 @@ export class ChannelTable { } async stop(): Promise { this.stopped = true; + for (const entry of this.moving.values()) clearTimeout(entry.timer); + this.moving.clear(); const exits = [...this.channels.values()].map(channel => { if (channel.exited) return Promise.resolve(); const { promise, resolve } = Promise.withResolvers(); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index ffd4f67e0..0ecb6bd9a 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -406,7 +406,7 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { try { const result = await runOp(link, op, args); if (op === "open" && isRecord(result) && typeof result.ch === "string") opened = result.ch; - const media = (op === "readMedia" || op === "readFileChunk") && isRecord(result) && result.ok === true && result.value instanceof Uint8Array ? result.value : null; + const media = (op === "readMedia" || op === "readFileChunk" || op === "readSessionPack") && isRecord(result) && result.ok === true && result.value instanceof Uint8Array ? result.value : null; if (media && media.byteLength > LINK_LIMITS.blobBytes) throw new HostOpError(413, "result_too_large", "The result is too large for the host link"); link.result(id, result, { session, key: opened, media }); if (opened) { channelsChanged(opened); channels.release(link, opened); } @@ -457,6 +457,46 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { if (!(isRecord(result) && result.ok === false)) sessionsChanged(); return result; } + // omp writes a live session's file: refuse a running session instead of stopping it; an idle child stops first. + case "packSession": { + if (typeof args.id !== "string") throw new HostOpError(400, "invalid_request", "Invalid session id"); + return channels.mutateSession(args.id, async (id) => { + const packed = await sessionOps.packSession(id); + if (packed.ok) channels.reserveMove(link, id, packed.value.transfer); + return packed; + }, { refuseRunning: true }); + } + case "finishSessionMove": { + if (typeof args.id !== "string") throw new HostOpError(400, "invalid_request", "Invalid session id"); + const transfer = typeof args.transfer === "string" ? args.transfer : ""; + try { + const result = await channels.mutateSession( + args.id, + (id) => sessionOps.finishSessionMove(id, args.transfer as string, args.to as string), + { refuseRunning: true, moveTransfer: transfer }, + ); + if (!(isRecord(result) && result.ok === false)) sessionsChanged(); + return result; + } finally { + channels.releaseMove(transfer); + } + } + case "unpackSession": { + try { + const result = await sessionOps.unpackSession(args.transfer as string, args.cwd as string, args.move as Parameters[2]); + if (!(isRecord(result) && result.ok === false)) sessionsChanged(); + return result; + } finally { + if (typeof args.transfer === "string") channels.releaseMove(args.transfer); + } + } + case "discardSessionPack": { + try { + return await sessionOps.discardSessionPack(args.transfer as string); + } finally { + if (typeof args.transfer === "string") channels.releaseMove(args.transfer); + } + } case "sessionFileExists": return localHost.sessionFileExists(sessionsPath(args.path)); case "invalidateSessionLists": invalidateWorkspaceRoots(); localHost.invalidateSessionLists(args.path === undefined ? undefined : sessionsPath(args.path)); sessionsChanged(); return; case "checkUpdates": { @@ -500,10 +540,13 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { else throw new HostOpError(400, "invalid_request", "Invalid cluster configuration request"); return { state: config.state(), owned: config.holds(link.login.url) }; default: { + if (op === "renameSessionFile" && typeof args.id === "string" && channels.isMoving(args.id)) { + throw new HostOpError(409, "session_busy", "This session is currently being moved"); + } const run = sessionOps[op] as (...params: unknown[]) => Promise; const result = await run.apply(sessionOps, SESSION_OP_PARAMS[op].map(name => args[name])); if (op === "addProject" || op === "updateProject" || op === "hideProject") invalidateWorkspaceRoots(); - if (["renameSessionFile", "deleteSession", "archiveSession", "restoreArchive"].includes(op) && !(isRecord(result) && result.ok === false)) sessionsChanged(); + if (["renameSessionFile", "deleteSession", "archiveSession", "restoreArchive", "unpackSession"].includes(op) && !(isRecord(result) && result.ok === false)) sessionsChanged(); return result; } } diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index cfacf465c..41f63e03c 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -1052,7 +1052,7 @@ function settle(link: Link, message: Res): void { return pending.reject(new HostOpError(502, "host_blob_missing", `${label} did not deliver the ${pending.op} result`)); } const blob = pending.blob.length === 1 ? pending.blob[0] : Buffer.concat(pending.blob); - if (pending.op === "readMedia" || pending.op === "readFileChunk") return pending.resolve({ ok: true, value: blob }); + if (pending.op === "readMedia" || pending.op === "readFileChunk" || pending.op === "readSessionPack") return pending.resolve({ ok: true, value: blob }); try { pending.resolve(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(blob))); } catch { @@ -1100,6 +1100,7 @@ function validResult(op: keyof SessionOps, result: unknown, args: unknown[]): bo switch (op) { // Media bytes only ever arrive through the blob leg. case "readMedia": + case "readSessionPack": return value instanceof Uint8Array; case "searchSessions": return isRecord(value) && Object.entries(value).every(([id, score]) => @@ -1124,6 +1125,13 @@ function validResult(op: keyof SessionOps, result: unknown, args: unknown[]): bo } case "archiveSession": return isRecord(value) && typeof value.archivedPath === "string"; + case "packSession": + return isRecord(value) && typeof value.transfer === "string" && Number.isSafeInteger(value.bytes) + && typeof value.home === "string" && typeof value.platform === "string"; + case "writeSessionPack": + return isRecord(value) && Number.isSafeInteger(value.bytes); + case "unpackSession": + return isRecord(value) && typeof value.sessionId === "string" && isValidSessionId(value.sessionId); // The route reads `projects` and iterates `newRoots`. case "updateProject": return isRecord(value) && Array.isArray(value.projects) && value.projects.every((project) => projectEntry(project) !== null) @@ -1196,11 +1204,19 @@ function archiveEntry(value: unknown): ArchivedSessionInfo | null { const MEDIA_HASH_RE = /^[0-9a-f]{64}$/; /** Ops that rewrite or move a session's file: an exiting orphan of that session may still flush it. */ -const ORPHAN_SENSITIVE_OPS: Partial> = { archiveSession: true, deleteSession: true, renameSessionFile: true }; +const ORPHAN_SENSITIVE_OPS: Partial> = { archiveSession: true, deleteSession: true, renameSessionFile: true, packSession: true, finishSessionMove: true }; /** A clone/fetch may outlast ordinary operations, but preparation still has a bounded deadline. */ const POOL_PREPARE_TIMEOUT_MS = 10 * 60_000; -const SESSION_SEARCH_TIMEOUT_MS = 5_000; +/** The daemon gives `omp session pack|unpack|moved` five minutes. */ +const SESSION_MOVE_TIMEOUT_MS = 6 * 60_000; +const OP_TIMEOUTS: Partial> = { + preparePoolProject: POOL_PREPARE_TIMEOUT_MS, + packSession: SESSION_MOVE_TIMEOUT_MS, + unpackSession: SESSION_MOVE_TIMEOUT_MS, + finishSessionMove: SESSION_MOVE_TIMEOUT_MS, + searchSessions: 5_000, +}; function remoteSessionOps(hostId: string): SessionOps { const ops: Record Promise> = {}; @@ -1210,9 +1226,8 @@ function remoteSessionOps(hostId: string): SessionOps { return { ok: false, status: 400, code: "invalid_hash", error: "Invalid media hash" }; } if (ORPHAN_SENSITIVE_OPS[op]) await orphanExit(hostId, String(args[0])); - const timeout = op === "preparePoolProject" ? POOL_PREPARE_TIMEOUT_MS - : op === "searchSessions" ? SESSION_SEARCH_TIMEOUT_MS : linkTimings.opTimeoutMs; - const result = await request(hostId, op, Object.fromEntries(params.map((name, i) => [name, args[i]])), timeout); + const result = await request(hostId, op, Object.fromEntries(params.map((name, i) => [name, args[i]])), + OP_TIMEOUTS[op] ?? linkTimings.opTimeoutMs); if (op === "listSessionIdsForRestore") { if (Array.isArray(result) && result.every((id) => typeof id === "string" && id.length > 0)) return result; throw new HostOpError(502, "host_bad_result", `${labelOf(hostId)} sent an incomplete active-session inventory`); diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index 49ec8133b..1b2f4032c 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -97,6 +97,12 @@ export const SESSION_OP_PARAMS: { readonly [K in keyof SessionOps]: readonly str renameSessionFile: ["id", "title", "source"], deleteSession: ["id", "liveSessionIds"], archiveSession: ["id"], + packSession: ["id"], + readSessionPack: ["transfer", "offset"], + writeSessionPack: ["transfer", "offset", "data"], + unpackSession: ["transfer", "cwd", "move"], + finishSessionMove: ["id", "transfer", "to"], + discardSessionPack: ["transfer"], listArchives: [], restoreReserve: ["claim"], restoreArchive: ["key", "claim"], diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index faf72495a..605dde8c9 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -30,6 +30,7 @@ import { } from "../omp/session-files"; import { preparePoolProject, type PreparedPoolProject } from "../pooled-projects"; import { projectIdentityKey, sessionPathKey } from "../paths"; +import { discardSessionPack, packSessionFile, readSessionPack, retireMovedSession, unpackSessionPack, writeSessionPack, type SessionMoveOrigin } from "./session-transfer"; import { hideProject, loadProjectRegistry, @@ -111,6 +112,17 @@ export interface SessionOps { /** `liveSessionIds`: sessions main has a live omp process for; their files are never rewritten. */ deleteSession(id: string, liveSessionIds: string[]): Promise }>>; archiveSession(id: string): Promise>; + /** Packs a session for a move (`omp session pack`); `transfer` names the archive on this host until it is unpacked or discarded. */ + packSession(id: string): Promise>; + /** Up to SESSION_PACK_CHUNK_BYTES of a packed archive from `offset`. */ + readSessionPack(transfer: string, offset: number): Promise>; + /** Appends a base64 chunk to an archive arriving from another host; `offset` must be its current size. */ + writeSessionPack(transfer: string, offset: number, data: string): Promise>; + /** Lands archive `transfer` in workspace `cwd` (`omp session unpack`) and tells the session where it came from. */ + unpackSession(transfer: string, cwd: string, move: SessionMoveOrigin): Promise>; + /** After the session arrived on host `to`: marks this copy moved (resuming it forks) and archives it. */ + finishSessionMove(id: string, transfer: string, to: string): Promise>; + discardSessionPack(transfer: string): Promise>; /** This host's archive, newest first (browser entries; no hostId). */ listArchives(): Promise; /** Admit one restore: `restoreArchive` starts only under a claim token reserved here and not fenced since. `instance` @@ -583,6 +595,35 @@ export const sessionOps: SessionOps = { return ok({ archivedPath }); }, + async packSession(id) { + const filePath = await resolveSessionPath(id); + if (!filePath) return sessionNotFound(); + return packSessionFile(filePath); + }, + + readSessionPack, + writeSessionPack, + + async unpackSession(transfer, cwd, move) { + const result = await unpackSessionPack(transfer, cwd, move); + if (result.ok) { + invalidateSessionPathCache(result.value.sessionId); + invalidateSessionListCache(); + } + return result; + }, + + async finishSessionMove(id, transfer, to) { + const filePath = await resolveSessionPath(id); + if (!filePath) return sessionNotFound(); + const result = await retireMovedSession(filePath, transfer, to); + invalidateSessionPathCache(id); + invalidateSessionListCache(); + return result; + }, + + discardSessionPack: async (transfer) => discardSessionPack(transfer), + async listArchives() { return listArchivedSessionInfos(); }, diff --git a/lib/hosts/session-transfer.test.mjs b/lib/hosts/session-transfer.test.mjs new file mode 100644 index 000000000..7e737b451 --- /dev/null +++ b/lib/hosts/session-transfer.test.mjs @@ -0,0 +1,152 @@ +import assert from "node:assert/strict"; +import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import test from "node:test"; + +// The moves run the real `omp session pack|unpack|moved` of ompweb's runner (AGENTS.md: `npm test` needs it installed). +const root = mkdtempSync(join(tmpdir(), "omp-web-session-transfer-")); +const cli = resolve("runner/src/cli.ts"); +const omp = join(root, process.platform === "win32" ? "omp.cmd" : "omp"); +writeFileSync(omp, process.platform === "win32" + ? `@"${process.execPath.replaceAll("%", "%%")}" "${cli.replaceAll("%", "%%")}" %*\r\n` + : `#!/bin/sh\nexec bun ${JSON.stringify(cli)} "$@"\n`); +chmodSync(omp, 0o755); +process.env.OMP_WEB_OMP_BIN = omp; + +const { packSessionFile, readSessionPack, retireMovedSession, unpackSessionPack, writeSessionPack } = await import("./session-transfer.ts"); + +const ID = "11111111-2222-4333-8444-555555555555"; + +/** An agent dir ("a host") holding the fixture session, recorded in workspace `cwd`. */ +function host(name, cwd) { + const agentDir = join(root, name); + const dir = join(agentDir, "sessions", "-fixture"); + mkdirSync(dir, { recursive: true }); + const lines = [ + { type: "session", version: 3, id: ID, cwd, timestamp: "2026-01-01T00:00:00.000Z" }, + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:01.000Z", message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:02.000Z", message: { role: "assistant", provider: "test", model: "m", content: [{ type: "text", text: "hi" }] } }, + ]; + const file = join(dir, `2026-01-01T00-00-00-000Z_${ID}.jsonl`); + writeFileSync(file, `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`); + return { agentDir, file }; +} + +function workspace(name) { + const dir = join(root, name); + mkdirSync(dir, { recursive: true }); + return dir; +} + +function on(agentDir) { + process.env.PI_CODING_AGENT_DIR = agentDir; +} + +function sessionFiles(agentDir) { + return readdirSync(join(agentDir, "sessions"), { recursive: true }).filter((name) => String(name).endsWith(".jsonl")); +} + +function lastEntry(agentDir) { + const [file] = sessionFiles(agentDir); + return JSON.parse(readFileSync(join(agentDir, "sessions", file), "utf8").trim().split("\n").at(-1)); +} + +test.after(() => rmSync(root, { recursive: true, force: true })); + +// Each step starts omp, a few seconds each under a parallel run. +test("a move between workspaces of one host replaces the session and says so", { timeout: 60_000 }, async () => { + const from = workspace("same-from"); + const to = workspace("same-to"); + const { agentDir, file } = host("same", from); + on(agentDir); + + const packed = await packSessionFile(file); + assert.equal(packed.ok, true, JSON.stringify(packed)); + const unpacked = await unpackSessionPack(packed.value.transfer, to, { host: "alpha", from: null }); + assert.deepEqual(unpacked, { ok: true, value: { sessionId: ID } }); + + assert.equal(existsSync(file), false); + assert.equal(sessionFiles(agentDir).length, 1); + const marker = lastEntry(agentDir); + assert.equal(marker.customType, "session-transfer"); + assert.deepEqual(marker.details, { kind: "arrived", fromCwd: from, cwd: to }); + assert.match(marker.content, /moved on host `alpha` from the workspace `.*same-from` to `.*same-to`/); + assert.doesNotMatch(marker.content, /another machine/); + assert.equal(readdirSync(join(agentDir, "omp-web", "transfers")).length, 0); +}); + +test("a move to another host copies the archive in chunks, names both hosts and retires the source", { timeout: 60_000 }, async () => { + const from = workspace("cross-from"); + const to = workspace("cross-to"); + const source = host("source", from); + const target = join(root, "target"); + + on(source.agentDir); + const packed = await packSessionFile(source.file); + assert.equal(packed.ok, true, JSON.stringify(packed)); + const { transfer, bytes } = packed.value; + for (let offset = 0; offset < bytes;) { + on(source.agentDir); + const chunk = await readSessionPack(transfer, offset); + assert.equal(chunk.ok, true); + on(target); + const written = await writeSessionPack(transfer, offset, Buffer.from(chunk.value).toString("base64")); + assert.equal(written.ok, true, JSON.stringify(written)); + offset = written.value.bytes; + } + const repeated = await writeSessionPack(transfer, 0, "AA=="); + assert.equal(repeated.ok, false); + assert.equal(repeated.code, "transfer_offset"); + + const unpacked = await unpackSessionPack(transfer, to, { host: "beta", from: { host: "alpha", home: "/home/alpha", platform: "plan9" } }); + assert.deepEqual(unpacked, { ok: true, value: { sessionId: ID } }); + const marker = lastEntry(target); + assert.match(marker.content, /moved from host `alpha` to host `beta`/); + assert.match(marker.content, /home directory changed from `\/home\/alpha`/); + assert.match(marker.content, /operating system changed from plan9/); + + on(source.agentDir); + assert.deepEqual(await retireMovedSession(source.file, transfer, `beta:${to}`), { ok: true, value: null }); + assert.equal(existsSync(source.file), false); + assert.equal(sessionFiles(source.agentDir).length, 0); + assert.equal(readdirSync(join(source.agentDir, "omp-web", "transfers")).length, 0); +}); + +test("retireMovedSession and unpackSessionPack reject cmd.exe metacharacters", { timeout: 60_000 }, async () => { + const from = workspace("meta-from"); + const source = host("meta-source", from); + on(source.agentDir); + const packed = await packSessionFile(source.file); + assert.equal(packed.ok, true, JSON.stringify(packed)); + + const badRetire = await retireMovedSession(source.file, packed.value.transfer, "beta:C:\\work&whoami"); + assert.equal(badRetire.ok, false); + assert.equal(badRetire.code, "invalid_destination"); + assert.equal(badRetire.status, 400); + assert.equal(existsSync(source.file), true, "rejected retirement must leave the source untouched"); + + const badUnpack = await unpackSessionPack(packed.value.transfer, "C:\\work&whoami", { host: "beta", from: null }); + assert.equal(badUnpack.ok, false); + assert.equal(badUnpack.code, "invalid_destination"); + assert.equal(badUnpack.status, 400); + assert.equal(existsSync(source.file), true); +}); + +test("retireMovedSession refuses retirement when the source session changed after packing", { timeout: 60_000 }, async () => { + const from = workspace("drift-from"); + const to = workspace("drift-to"); + const source = host("drift-source", from); + on(source.agentDir); + const packed = await packSessionFile(source.file); + assert.equal(packed.ok, true, JSON.stringify(packed)); + + appendFileSync(source.file, `${JSON.stringify({ type: "message", id: "u2", parentId: "u1", timestamp: "2026-01-01T00:00:02.000Z", message: { role: "user", content: "late turn" } })}\n`); + const retired = await retireMovedSession(source.file, packed.value.transfer, `beta:${to}`); + assert.equal(retired.ok, false); + assert.equal(retired.code, "session_changed"); + assert.equal(retired.status, 409); + assert.equal(existsSync(source.file), true, "changed source session must stay active"); + assert.equal(sessionFiles(source.agentDir).length, 1); + assert.equal(readdirSync(join(source.agentDir, "omp-web", "transfers")).length, 0); +}); diff --git a/lib/hosts/session-transfer.ts b/lib/hosts/session-transfer.ts new file mode 100644 index 000000000..6fc8523d4 --- /dev/null +++ b/lib/hosts/session-transfer.ts @@ -0,0 +1,275 @@ +// Daemon side of moving a session to another workspace or host, over omp's own `omp session pack|unpack|moved`: the +// archive carries the journal, artifacts and image blobs, and unpacking rewrites the header cwd and appends an `arrived` +// marker the model sees. Main carries the archive between hosts in chunks and names the hosts for that marker. +// No `next/*` or `@/` imports: the daemon loads this through plain jiti. +import { createHash, randomUUID } from "crypto"; +import { execFile } from "child_process"; +import { appendFileSync, closeSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync } from "fs"; +import { homedir, tmpdir } from "os"; +import { join } from "path"; +import { promisify } from "util"; +import { getAgentDir } from "../omp/paths"; +import { OMP_NOT_FOUND, resolveOmpBin, wrapWindowsScript } from "../omp/omp-cli"; +import { archiveSessionFileWithArtifacts, readSessionHeaderSync, writeSessionFileAtomicSync } from "../omp/session-files"; +import { isRecord } from "../type-guards"; +import type { OpResult } from "./session-ops"; + +/** One `readSessionPack`/`writeSessionPack` step; base64 of it stays well under the link's 8 MiB line. */ +export const SESSION_PACK_CHUNK_BYTES = 4 * 1024 * 1024; +/** omp refuses larger session archives. */ +const MAX_PACK_BYTES = 2 * 1024 ** 3; +const TRANSFER_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +/** An archive a failed move left behind. */ +const STALE_TRANSFER_MS = 24 * 60 * 60 * 1000; +const MAX_LABEL_CHARS = 512; +/** Characters `cmd.exe` interprets as command syntax when passing an unquoted argument to a `.cmd`/`.bat` launcher. */ +const CMD_META_RE = /[&|<>^%!"\r\n\0]/; + +/** Source file state captured at pack time so retirement refuses a source that changed while unpacking on another host. */ +const packedSources = new Map(); + +/** Where the session comes from, for the arrival marker: `from` is null for a move between workspaces of one host. */ +export interface SessionMoveOrigin { + host: string; + from: { host: string; home: string; platform: string } | null; +} + +const execFileAsync = promisify(execFile); +const ok = (value: T): OpResult => ({ ok: true, value }); +const fail = (status: number, code: string, error: string): OpResult => ({ ok: false, status, code, error }); +const badTransfer = () => fail(400, "invalid_transfer", "Invalid session transfer"); +const missingTransfer = () => fail(404, "transfer_not_found", "The session archive is gone; start the move again"); + +function fileDigest(filePath: string): string { + return createHash("sha256").update(readFileSync(filePath)).digest("hex"); +} + +function transfersDir(): string { + return join(getAgentDir(), "omp-web", "transfers"); +} + +function transferPath(transfer: unknown): string | null { + return typeof transfer === "string" && TRANSFER_RE.test(transfer) ? join(transfersDir(), `${transfer}.tar`) : null; +} + +function sweepStaleTransfers(): void { + let names: string[]; + try { + names = readdirSync(transfersDir()); + } catch { + return; + } + for (const name of names) { + const file = join(transfersDir(), name); + try { + if (Date.now() - statSync(file).mtimeMs > STALE_TRANSFER_MS) { + rmSync(file, { force: true }); + if (name.endsWith(".tar")) packedSources.delete(name.slice(0, -4)); + } + } catch { /* gone meanwhile */ } + } +} + +function newTransfer(): { transfer: string; file: string } { + sweepStaleTransfers(); + mkdirSync(transfersDir(), { recursive: true, mode: 0o700 }); + const transfer = randomUUID(); + return { transfer, file: transferPath(transfer)! }; +} + +/** `omp session `: its stdout, or the refusal omp printed (`error: …`, exit 1) as a 409. */ +async function runOmpSession(args: string[]): Promise> { + const bin = resolveOmpBin(); + if (!bin) return fail(500, "omp_not_found", OMP_NOT_FOUND); + const target = wrapWindowsScript(bin, ["session", ...args]); + try { + const { stdout } = await execFileAsync(target.file, target.args, { cwd: tmpdir(), timeout: 5 * 60_000, maxBuffer: 1024 * 1024, windowsHide: true }); + return ok(stdout); + } catch (error) { + const stderr = isRecord(error) && typeof error.stderr === "string" ? error.stderr : ""; + // chalk's colours, when omp thinks it writes to a terminal. + const refusal = stderr.replace(/\x1b\[[0-9;]*m/g, "").split("\n").find((line) => line.startsWith("error: ")); + if (refusal) return fail(409, "session_move_refused", refusal.slice("error: ".length)); + return fail(500, "session_move_failed", error instanceof Error ? error.message : String(error)); + } +} + +export async function packSessionFile(sessionFile: string): Promise> { + let digest: string; + try { + digest = fileDigest(sessionFile); + } catch { + return fail(404, "session_not_found", "Session not found"); + } + const { transfer, file } = newTransfer(); + const packed = await runOmpSession(["pack", sessionFile, file]); + if (!packed.ok) { + rmSync(file, { force: true }); + return packed; + } + const bytes = statSync(file).size; + if (bytes > MAX_PACK_BYTES) { + rmSync(file, { force: true }); + return fail(413, "session_too_large", "The session is too large to move"); + } + try { + if (fileDigest(sessionFile) !== digest) { + rmSync(file, { force: true }); + return fail(409, "session_changed", "The session changed while preparing the move; try again"); + } + } catch { + rmSync(file, { force: true }); + return fail(404, "session_not_found", "Session not found"); + } + packedSources.set(transfer, { sessionFile, digest }); + return ok({ transfer, bytes, home: homedir(), platform: process.platform }); +} + +export async function readSessionPack(transfer: string, offset: number): Promise> { + const file = transferPath(transfer); + if (!file || !Number.isSafeInteger(offset) || offset < 0) return badTransfer(); + let fd: number; + try { + fd = openSync(file, "r"); + } catch { + return missingTransfer(); + } + try { + const chunk = Buffer.alloc(SESSION_PACK_CHUNK_BYTES); + return ok(chunk.subarray(0, readSync(fd, chunk, 0, chunk.length, offset))); + } finally { + closeSync(fd); + } +} + +/** Appends `data` (base64) to the archive being received; `offset` must be its current size, so a repeated step fails. */ +export async function writeSessionPack(transfer: string, offset: number, data: string): Promise> { + const file = transferPath(transfer); + if (!file || !Number.isSafeInteger(offset) || offset < 0 || typeof data !== "string") return badTransfer(); + const chunk = Buffer.from(data, "base64"); + if (chunk.byteLength > SESSION_PACK_CHUNK_BYTES || offset + chunk.byteLength > MAX_PACK_BYTES) return fail(413, "session_too_large", "The session is too large to move"); + if (offset === 0) { + sweepStaleTransfers(); + mkdirSync(transfersDir(), { recursive: true, mode: 0o700 }); + } + let size = 0; + try { + size = statSync(file).size; + } catch { + if (offset !== 0) return missingTransfer(); + } + if (size !== offset) return fail(409, "transfer_offset", `The session archive has ${size} bytes, not ${offset}`); + appendFileSync(file, chunk, { mode: 0o600 }); + return ok({ bytes: offset + chunk.byteLength }); +} + +export function discardSessionPack(transfer: string): OpResult { + const file = transferPath(transfer); + if (!file) return badTransfer(); + packedSources.delete(transfer); + rmSync(file, { force: true }); + return ok(null); +} + +function validOrigin(move: unknown): move is SessionMoveOrigin { + const label = (value: unknown) => typeof value === "string" && value.length > 0 && value.length <= MAX_LABEL_CHARS; + if (!isRecord(move) || !label(move.host)) return false; + if (move.from === null) return true; + return isRecord(move.from) && label(move.from.host) && label(move.from.home) && label(move.from.platform); +} + +/** What the session reads where it arrived: omp's own words say "another machine" even for a move on one host. */ +function arrivalNotice(fromCwd: string, cwd: string, move: SessionMoveOrigin): string { + const code = (text: string) => "`" + text + "`"; + if (!move.from) { + return `This session was moved on host ${code(move.host)} from the workspace ${code(fromCwd)} to ${code(cwd)}. Its working directory is now ${code(cwd)}; paths from earlier turns under ${code(fromCwd)} belong to the old workspace. Running processes and shell state did not move with it.`; + } + const lines = [`This session was moved from host ${code(move.from.host)} to host ${code(move.host)}. It ran in ${code(fromCwd)} there; its working directory is now ${code(cwd)}, and paths from earlier turns under ${code(fromCwd)} now live under ${code(cwd)}.`]; + if (move.from.home !== homedir()) lines.push(`The home directory changed from ${code(move.from.home)} to ${code(homedir())}.`); + if (move.from.platform !== process.platform) lines.push(`The operating system changed from ${move.from.platform} to ${process.platform}.`); + lines.push("Running processes, shell state, and files outside the working directory did not move with it."); + return lines.join(" "); +} + +/** Rewords the `arrived` marker omp just appended as the file's last line. */ +function rewordArrival(sessionFile: string, move: SessionMoveOrigin): void { + const body = readFileSync(sessionFile, "utf8"); + const end = body.endsWith("\n") ? body.length - 1 : body.length; + const start = body.lastIndexOf("\n", end - 1) + 1; + let entry: unknown; + try { + entry = JSON.parse(body.slice(start, end)); + } catch { + return; + } + if (!isRecord(entry) || entry.type !== "custom_message" || entry.customType !== "session-transfer") return; + const details = entry.details; + if (!isRecord(details) || details.kind !== "arrived" || typeof details.fromCwd !== "string" || typeof details.cwd !== "string") return; + entry.content = arrivalNotice(details.fromCwd, details.cwd, move); + writeSessionFileAtomicSync(sessionFile, body.slice(0, start) + JSON.stringify(entry) + body.slice(end), "move"); +} + +/** Lands archive `transfer` in `cwd`'s session directory. On the host it was packed on, omp replaces the copy it came + * from, so that is the whole move; a copy that diverged meanwhile makes it a fork with a new id. */ +export async function unpackSessionPack(transfer: string, cwd: string, move: unknown): Promise> { + const file = transferPath(transfer); + if (!file || typeof cwd !== "string" || !cwd) return badTransfer(); + if (CMD_META_RE.test(cwd)) return fail(400, "invalid_destination", "The destination path contains characters that cmd.exe reads as syntax"); + if (!validOrigin(move)) return fail(400, "invalid_request", "Invalid move origin"); + try { + statSync(file); + } catch { + return missingTransfer(); + } + try { + const expected = packedSources.get(transfer); + if (expected) { + let currentDigest: string; + try { + currentDigest = fileDigest(expected.sessionFile); + } catch { + return fail(404, "session_not_found", "Session not found"); + } + if (currentDigest !== expected.digest) { + return fail(409, "session_changed", "The session changed during the move; keeping the source copy"); + } + } + const unpacked = await runOmpSession(["unpack", file, "--cwd", cwd]); + if (!unpacked.ok) return unpacked; + const sessionFile = unpacked.value.trim().split("\n").at(-1) ?? ""; + const sessionId = sessionFile ? readSessionHeaderSync(sessionFile)?.id : undefined; + if (!sessionId) return fail(500, "session_move_failed", "omp did not report the unpacked session"); + rewordArrival(sessionFile, move); + return ok({ sessionId }); + } finally { + packedSources.delete(transfer); + rmSync(file, { force: true }); + } +} + +/** The copy a move to another host left here: marked moved to `to` (resuming it forks), then archived. */ +export async function retireMovedSession(sessionFile: string, transfer: string, to: unknown): Promise> { + if (!transferPath(transfer)) return badTransfer(); + if (typeof to !== "string" || !to.trim() || to.length > MAX_LABEL_CHARS) return fail(400, "invalid_request", "Invalid move label"); + if (CMD_META_RE.test(to)) return fail(400, "invalid_destination", "The destination path contains characters that cmd.exe reads as syntax"); + const expected = packedSources.get(transfer); + if (expected) { + let currentDigest: string; + try { + currentDigest = fileDigest(sessionFile); + } catch { + discardSessionPack(transfer); + return fail(404, "session_not_found", "Session not found"); + } + if (expected.sessionFile !== sessionFile || currentDigest !== expected.digest) { + discardSessionPack(transfer); + return fail(409, "session_changed", "The session changed during the move; keeping the source copy"); + } + } + const discarded = discardSessionPack(transfer); + if (!discarded.ok) return discarded; + const marked = await runOmpSession(["moved", sessionFile, "--to", to]); + if (!marked.ok) return marked; + archiveSessionFileWithArtifacts(sessionFile); + return ok(null); +} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 76a40d343..176bc7e88 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -758,6 +758,8 @@ "errors.invalid_block_index": "A valid block index is required", "errors.invalid_branch_name": "Invalid branch name", "errors.invalid_conflict_strategy": "Invalid conflict strategy", + "errors.invalid_destination": "The destination path contains unsupported characters", + "errors.move_outcome_unknown": "The destination host went offline before confirming the move. Check the destination before retrying.", "errors.invalid_edit_target": "The edit target must be a user message", "errors.invalid_file_names": "Invalid file names", "errors.invalid_git_url": "Enter an https:// or ssh Git repository URL", @@ -1266,6 +1268,9 @@ "sessionSidebar.deleteConfirmBody": "This permanently deletes the session. This cannot be undone.", "sessionSidebar.deleteFailed": "Failed to delete the session", "sessionSidebar.archiveFailed": "Failed to archive the session", + "sessionSidebar.moved": "Session moved to {name}", + "sessionSidebar.moveFailed": "Failed to move the session", + "sessionSidebar.moveStaleCopy": "The copy on the old host was not archived: {error}", "sessionSidebar.expandForks": "Expand forks", "sessionSidebar.explorer": "Explorer", "sessionSidebar.force": "Force", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index e4467fc41..a95373132 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -742,6 +742,8 @@ "errors.invalid_block_index": "有効なブロックインデックスが必要です", "errors.invalid_branch_name": "無効なブランチ名です", "errors.invalid_conflict_strategy": "無効な競合解決方法です", + "errors.invalid_destination": "移動先のパスに使用できない文字が含まれています", + "errors.move_outcome_unknown": "移動の確認前に移動先ホストがオフラインになりました。再試行する前に移動先を確認してください。", "errors.invalid_edit_target": "編集対象はユーザーメッセージである必要があります", "errors.invalid_file_names": "無効なファイル名です", "errors.invalid_git_url": "https:// または ssh の Git リポジトリURLを入力してください", @@ -1227,6 +1229,9 @@ "sessionSidebar.deleteConfirmBody": "このセッションを完全に削除します。この操作は取り消せません。", "sessionSidebar.deleteFailed": "セッションを削除できませんでした", "sessionSidebar.archiveFailed": "セッションをアーカイブできませんでした", + "sessionSidebar.moved": "セッションを {name} に移動しました", + "sessionSidebar.moveFailed": "セッションを移動できませんでした", + "sessionSidebar.moveStaleCopy": "元のホストのコピーはアーカイブされませんでした: {error}", "sessionSidebar.expandForks": "フォークを展開", "sessionSidebar.explorer": "エクスプローラー", "sessionSidebar.force": "強制", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index b98b9dddc..0b3dc8a67 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -742,6 +742,8 @@ "errors.invalid_block_index": "需要提供有效的块索引", "errors.invalid_branch_name": "分支名称无效", "errors.invalid_conflict_strategy": "冲突处理策略无效", + "errors.invalid_destination": "目标路径包含不支持的字符", + "errors.move_outcome_unknown": "目标主机在确认移动前离线。请先检查目标主机,再重试。", "errors.invalid_edit_target": "只能编辑用户消息", "errors.invalid_file_names": "文件名无效", "errors.invalid_git_url": "请输入 https:// 或 ssh 格式的 Git 仓库 URL", @@ -1227,6 +1229,9 @@ "sessionSidebar.deleteConfirmBody": "这将永久删除此会话。此操作无法撤销。", "sessionSidebar.deleteFailed": "删除会话失败", "sessionSidebar.archiveFailed": "归档会话失败", + "sessionSidebar.moved": "会话已移动到 {name}", + "sessionSidebar.moveFailed": "移动会话失败", + "sessionSidebar.moveStaleCopy": "原主机上的副本未归档:{error}", "sessionSidebar.expandForks": "展开分叉", "sessionSidebar.explorer": "资源管理器", "sessionSidebar.force": "强制", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index ca85ab4e1..778637a92 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -757,6 +757,8 @@ "errors.invalid_block_index": "必須提供有效的區塊索引", "errors.invalid_branch_name": "無效的分支名稱", "errors.invalid_conflict_strategy": "無效的衝突處理策略", + "errors.invalid_destination": "目標路徑包含不支援的字元", + "errors.move_outcome_unknown": "目標主機在確認移動前離線。請先檢查目標主機,再重試。", "errors.invalid_edit_target": "編輯目標必須是使用者訊息", "errors.invalid_file_names": "無效的檔案名稱", "errors.invalid_git_url": "請輸入 https:// 或 ssh Git 儲存庫 URL", @@ -1266,6 +1268,9 @@ "sessionSidebar.deleteConfirmBody": "這將永久刪除此對話。此動作無法復原。", "sessionSidebar.deleteFailed": "無法刪除對話", "sessionSidebar.archiveFailed": "無法封存對話", + "sessionSidebar.moved": "對話已移至 {name}", + "sessionSidebar.moveFailed": "無法移動對話", + "sessionSidebar.moveStaleCopy": "原主機上的副本未封存:{error}", "sessionSidebar.expandForks": "展開分支", "sessionSidebar.explorer": "檔案瀏覽器", "sessionSidebar.force": "強制", diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 80e75c16d..824e5dc5f 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -12,6 +12,7 @@ const contextRoute = await import("../app/api/sessions/[id]/context/route.ts"); const importRoute = await import("../app/api/sessions/import/route.ts"); const archiveRoute = await import("../app/api/sessions/archive/route.ts"); const sessionArchiveRoute = await import("../app/api/sessions/[id]/archive/route.ts"); +const moveRoute = await import("../app/api/sessions/[id]/move/route.ts"); const exportRoute = await import("../app/api/sessions/[id]/export/route.ts"); const stateRoute = await import("../app/api/sessions/[id]/state/route.ts"); const autoNameRoute = await import("../app/api/sessions/[id]/auto-name/route.ts"); @@ -1817,3 +1818,180 @@ test("GET /api/sessions?id= returns only the requested session for na assert.deepEqual(dataNone.sessions, []); }); }); + +test("POST /api/sessions/[id]/move reserves a session across concurrent move requests", async () => { + await withAgentDir(async () => { + const id = "0a000000-0000-4000-8000-000000000081"; + const source = await linkHost("Source"); + const target = await linkHost("Target"); + const packStarted = Promise.withResolvers(); + const releasePack = Promise.withResolvers(); + let packs = 0; + try { + source.serve({ + listSessions: () => [listedSession(id, "/srv/from")], + async packSession() { + packs += 1; + packStarted.resolve(); + await releasePack.promise; + return { ok: true, value: { transfer: "11111111-1111-4111-8111-111111111111", bytes: 3, home: "/home/src", platform: "linux" } }; + }, + readSessionPack: () => new Uint8Array([1, 2, 3]), + finishSessionMove: () => ({ ok: true, value: null }), + }); + target.serve({ + listSessions: () => [], + validateCwd: ({ path }) => ({ ok: true, value: { cwd: path, projectRoot: path, projectKey: path } }), + writeSessionPack: ({ offset }) => ({ ok: true, value: { bytes: offset + 3 } }), + unpackSession: () => ({ ok: true, value: { sessionId: id } }), + }); + const req = () => moveRoute.POST( + new Request(`http://localhost/api/sessions/${id}/move`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ hostId: target.id, cwd: "/srv/to" }), + }), + { params: Promise.resolve({ id }) }, + ); + const first = req(); + await packStarted.promise; + const second = await req(); + assert.equal(second.status, 409); + assert.equal((await second.json()).code, "session_busy"); + assert.equal(packs, 1, "concurrent move must be refused before packing a second time"); + releasePack.resolve(); + assert.equal((await first).status, 200); + } finally { + releasePack.resolve(); + closeHostLink(source.id); + closeHostLink(target.id); + revokeHost(source.id); + revokeHost(target.id); + } + }); +}); + +test("POST /api/sessions/[id]/move rejects destination write offset mismatches and discards packs", async () => { + await withAgentDir(async () => { + const id = "0a000000-0000-4000-8000-000000000082"; + const source = await linkHost("Source"); + const target = await linkHost("Target"); + const discarded = []; + let reads = 0; + try { + source.serve({ + listSessions: () => [listedSession(id, "/srv/from")], + packSession: () => ({ ok: true, value: { transfer: "22222222-2222-4222-8222-222222222222", bytes: 4, home: "/home/src", platform: "linux" } }), + readSessionPack: () => { reads += 1; return new Uint8Array([1, 2, 3, 4]); }, + discardSessionPack: ({ transfer }) => { discarded.push(["source", transfer]); return { ok: true, value: null }; }, + }); + target.serve({ + listSessions: () => [], + validateCwd: ({ path }) => ({ ok: true, value: { cwd: path, projectRoot: path, projectKey: path } }), + writeSessionPack: () => ({ ok: true, value: { bytes: 0 } }), + discardSessionPack: ({ transfer }) => { discarded.push(["target", transfer]); return { ok: true, value: null }; }, + }); + const res = await moveRoute.POST( + new Request(`http://localhost/api/sessions/${id}/move`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ hostId: target.id, cwd: "/srv/to" }), + }), + { params: Promise.resolve({ id }) }, + ); + assert.equal(res.status, 502); + assert.equal((await res.json()).code, "host_bad_result"); + assert.equal(reads, 1, "bad write acknowledgement must abort copyPack immediately"); + assert.equal(discarded.length, 2); + } finally { + closeHostLink(source.id); + closeHostLink(target.id); + revokeHost(source.id); + revokeHost(target.id); + } + }); +}); + +test("POST /api/sessions/[id]/move reports move_outcome_unknown when destination drops after unpack is sent", async () => { + await withAgentDir(async () => { + const id = "0a000000-0000-4000-8000-000000000083"; + const source = await linkHost("Source"); + const target = await linkHost("Target"); + const targetDiscards = []; + const sourceDiscards = []; + try { + source.serve({ + listSessions: () => [listedSession(id, "/srv/from")], + packSession: () => ({ ok: true, value: { transfer: "33333333-3333-4333-8333-333333333333", bytes: 2, home: "/home/src", platform: "linux" } }), + readSessionPack: () => new Uint8Array([1, 2]), + discardSessionPack: ({ transfer }) => { sourceDiscards.push(transfer); return { ok: true, value: null }; }, + }); + target.serve({ + listSessions: () => [], + validateCwd: ({ path }) => ({ ok: true, value: { cwd: path, projectRoot: path, projectKey: path } }), + writeSessionPack: ({ offset }) => ({ ok: true, value: { bytes: offset + 2 } }), + unpackSession: () => { + target.drop(); + return new Promise(() => {}); + }, + discardSessionPack: ({ transfer }) => { targetDiscards.push(transfer); return { ok: true, value: null }; }, + }); + const res = await moveRoute.POST( + new Request(`http://localhost/api/sessions/${id}/move`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ hostId: target.id, cwd: "/srv/to" }), + }), + { params: Promise.resolve({ id }) }, + ); + assert.equal(res.status, 503); + assert.deepEqual(await res.json(), { + error: "Target went offline before confirming the move; check Target before retrying", + code: "move_outcome_unknown", + hostOffline: true, + }); + assert.deepEqual(targetDiscards, []); + assert.deepEqual(sourceDiscards, ["33333333-3333-4333-8333-333333333333"]); + } finally { + closeHostLink(source.id); + closeHostLink(target.id); + revokeHost(source.id); + revokeHost(target.id); + } + }); +}); + +test("POST /api/sessions/[id]/move rejects cmd.exe metacharacters in destination before packing", async () => { + await withAgentDir(async () => { + const id = "0a000000-0000-4000-8000-000000000084"; + const source = await linkHost("Source"); + const target = await linkHost("Target"); + let packs = 0; + try { + source.serve({ + listSessions: () => [listedSession(id, "/srv/from")], + packSession: () => { packs += 1; return { ok: true, value: { transfer: "44444444-4444-4444-8444-444444444444", bytes: 0, home: "/home/src", platform: "linux" } }; }, + }); + target.serve({ + listSessions: () => [], + validateCwd: ({ path }) => ({ ok: true, value: { cwd: path, projectRoot: path, projectKey: path } }), + }); + const res = await moveRoute.POST( + new Request(`http://localhost/api/sessions/${id}/move`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ hostId: target.id, cwd: "C:\\work&whoami" }), + }), + { params: Promise.resolve({ id }) }, + ); + assert.equal(res.status, 400); + assert.equal((await res.json()).code, "invalid_destination"); + assert.equal(packs, 0); + } finally { + closeHostLink(source.id); + closeHostLink(target.id); + revokeHost(source.id); + revokeHost(target.id); + } + }); +}); diff --git a/server/routes.ts b/server/routes.ts index d6cfea353..dcf672f27 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -58,6 +58,7 @@ import * as sessionsIdEntriesEntryIdThinking from "@/app/api/sessions/[id]/entri import * as sessionsIdExport from "@/app/api/sessions/[id]/export/route"; import * as sessionsIdLocalFile from "@/app/api/sessions/[id]/local-file/route"; import * as sessionsIdMatches from "@/app/api/sessions/[id]/matches/route"; +import * as sessionsIdMove from "@/app/api/sessions/[id]/move/route"; import * as sessionsId from "@/app/api/sessions/[id]/route"; import * as sessionsIdState from "@/app/api/sessions/[id]/state/route"; import * as sessionsIdSubagentsSubagentId from "@/app/api/sessions/[id]/subagents/[subagentId]/route"; @@ -161,6 +162,7 @@ export const ROUTE_MODULES: Record = { "sessions/[id]/export": sessionsIdExport, "sessions/[id]/local-file": sessionsIdLocalFile, "sessions/[id]/matches": sessionsIdMatches, + "sessions/[id]/move": sessionsIdMove, "sessions/[id]": sessionsId, "sessions/[id]/state": sessionsIdState, "sessions/[id]/subagents/[subagentId]": sessionsIdSubagentsSubagentId,