@phren/cli 0.3.47 → 0.3.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -593,14 +593,20 @@ export async function panes(server, workspace, tab) {
593
593
  if (!objects(s.tabs).some(t => t.tab_id === tab && t.workspace_id === workspace))
594
594
  throw new BridgeError(409, "This terminal tab has changed. Refresh the computer.");
595
595
  const mux = (await terminal()).terminalMux(server);
596
+ // Loaded lazily: session-move imports this module, and a static import back makes a cycle.
597
+ const { listMoves, moveSessionFields } = await import("./session-move.js");
598
+ const moves = await listMoves();
596
599
  return { kind: mux.kind, mux, groupId: workspace, childId: tab, panes: await Promise.all(objects(s.panes)
597
600
  .filter(p => p.workspace_id === workspace && p.tab_id === tab).map(async (p) => {
598
601
  const chat = await paneChatState(server, p);
599
602
  const record = await paneRecord(server, p, typeof chat.sessionId === "string" ? chat.sessionId : undefined);
600
603
  const t = objects(s.tabs).find(candidate => candidate.tab_id === tab && candidate.workspace_id === workspace);
601
604
  const w = objects(s.workspaces).find(candidate => candidate.workspace_id === workspace);
605
+ const title = await recordTitle(record, { paneLabel: p.label, harnessTitle: p.title || p.terminal_title_stripped, tabLabel: t?.label, workspaceLabel: w?.label, fallbackLabel: p.label || p.pane_id });
606
+ const moveFields = typeof chat.sessionId === "string" && provider.safeParse(p.agent).success
607
+ ? moveSessionFields(moves, { server, workspace, tab, pane: String(p.pane_id), source: p.agent, session: chat.sessionId }, title) : {};
602
608
  return { id: p.pane_id, label: p.label || p.pane_id, agent: p.agent, agentStatus: p.agent_status,
603
- title: await recordTitle(record, { paneLabel: p.label, harnessTitle: p.title || p.terminal_title_stripped, tabLabel: t?.label, workspaceLabel: w?.label, fallbackLabel: p.label || p.pane_id }),
609
+ title, ...moveFields,
604
610
  cwd: p.foreground_cwd || p.cwd, ...chat, ...paneAccountField(server, p) };
605
611
  })) };
606
612
  }
@@ -134,6 +134,7 @@ export declare const capabilities: {
134
134
  agentFolder: boolean;
135
135
  launchPermissionMode: boolean;
136
136
  sessionMove: boolean;
137
+ moveNewChat: boolean;
137
138
  projectMemory: boolean;
138
139
  fileWrite: boolean;
139
140
  fileSearch: boolean;
@@ -1,4 +1,4 @@
1
- import { listMoves, readMove } from "./session-move.js";
1
+ import { listMoves, moveSessionFields, readMove } from "./session-move.js";
2
2
  import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
3
3
  import { ownerInboxView } from "./owner-inbox-view.js";
4
4
  import { closeFinishedWorker, closeOwnPane } from "./worker-close.js";
@@ -81,7 +81,7 @@ async function childActivity(source, session) {
81
81
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
82
82
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
83
83
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
84
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
84
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true };
85
85
  export function capabilitiesForModules(snapshot) {
86
86
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
87
87
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -166,6 +166,8 @@ export function workspacesReader(ctx) {
166
166
  agents.push(pane);
167
167
  agentsByTab.set(key, agents);
168
168
  }
169
+ // Move records are decoration: read alongside the rest, inside the budget.
170
+ const movesRead = listMoves().catch(() => []);
169
171
  const tabs = objects(workspaces.groups).flatMap(group => objects(group.children).map(tab => ({ group, tab })));
170
172
  // What a chat needs to open (the exact conversation) comes straight from the
171
173
  // chat states; everything below it is decoration.
@@ -214,6 +216,12 @@ export function workspacesReader(ctx) {
214
216
  return;
215
217
  Object.assign(tab, stall);
216
218
  tab.title = title;
219
+ if (target.success) {
220
+ const moves = await movesRead;
221
+ if (expired)
222
+ return;
223
+ Object.assign(tab, moveSessionFields(moves, target.data, title));
224
+ }
217
225
  // What a finished turn said last; a row still working (background work) has no last word yet.
218
226
  const reply = tab.agentStatus === "working" ? undefined : replyExcerpt(record);
219
227
  if (reply)
@@ -38,6 +38,10 @@ export declare const moveRequestSchema: z.ZodObject<{
38
38
  xhigh: "xhigh";
39
39
  }>>;
40
40
  }, z.core.$strict>;
41
+ mode: z.ZodDefault<z.ZodEnum<{
42
+ "new-chat": "new-chat";
43
+ replace: "replace";
44
+ }>>;
41
45
  id: z.ZodOptional<z.ZodString>;
42
46
  handoffTimeoutMs: z.ZodOptional<z.ZodNumber>;
43
47
  }, z.core.$strict>;
@@ -48,6 +52,7 @@ declare const moveRecordSchema: z.ZodObject<{
48
52
  failed: "failed";
49
53
  "handing-off": "handing-off";
50
54
  launching: "launching";
55
+ linking: "linking";
51
56
  moved: "moved";
52
57
  }>;
53
58
  createdAt: z.ZodString;
@@ -88,6 +93,57 @@ declare const moveRecordSchema: z.ZodObject<{
88
93
  xhigh: "xhigh";
89
94
  }>>;
90
95
  }, z.core.$strict>;
96
+ mode: z.ZodOptional<z.ZodEnum<{
97
+ "new-chat": "new-chat";
98
+ replace: "replace";
99
+ }>>;
100
+ handedOffTo: z.ZodOptional<z.ZodObject<{
101
+ target: z.ZodUnion<readonly [z.ZodObject<{
102
+ server: z.ZodString;
103
+ workspace: z.ZodString;
104
+ tab: z.ZodString;
105
+ pane: z.ZodString;
106
+ source: z.ZodEnum<{
107
+ claude: "claude";
108
+ codex: "codex";
109
+ copilot: "copilot";
110
+ opencode: "opencode";
111
+ phren: "phren";
112
+ }>;
113
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
114
+ }, z.core.$strip>, z.ZodObject<{
115
+ server: z.ZodString;
116
+ workspace: z.ZodString;
117
+ tab: z.ZodString;
118
+ pane: z.ZodString;
119
+ source: z.ZodEnum<{
120
+ claude: "claude";
121
+ codex: "codex";
122
+ copilot: "copilot";
123
+ opencode: "opencode";
124
+ phren: "phren";
125
+ }>;
126
+ starting: z.ZodLiteral<true>;
127
+ startingToken: z.ZodString;
128
+ }, z.core.$strip>]>;
129
+ }, z.core.$strict>>;
130
+ handedOffFrom: z.ZodOptional<z.ZodObject<{
131
+ target: z.ZodObject<{
132
+ server: z.ZodString;
133
+ workspace: z.ZodString;
134
+ tab: z.ZodString;
135
+ pane: z.ZodString;
136
+ source: z.ZodEnum<{
137
+ claude: "claude";
138
+ codex: "codex";
139
+ copilot: "copilot";
140
+ opencode: "opencode";
141
+ phren: "phren";
142
+ }>;
143
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
144
+ }, z.core.$strip>;
145
+ title: z.ZodString;
146
+ }, z.core.$strict>>;
91
147
  cwd: z.ZodString;
92
148
  dispatch: z.ZodOptional<z.ZodString>;
93
149
  handoff: z.ZodOptional<z.ZodObject<{
@@ -136,6 +192,21 @@ declare const moveRecordSchema: z.ZodObject<{
136
192
  starting: z.ZodLiteral<true>;
137
193
  startingToken: z.ZodString;
138
194
  }, z.core.$strip>]>>;
195
+ paneTarget: z.ZodOptional<z.ZodObject<{
196
+ server: z.ZodString;
197
+ workspace: z.ZodString;
198
+ tab: z.ZodString;
199
+ pane: z.ZodString;
200
+ source: z.ZodEnum<{
201
+ claude: "claude";
202
+ codex: "codex";
203
+ copilot: "copilot";
204
+ opencode: "opencode";
205
+ phren: "phren";
206
+ }>;
207
+ }, z.core.$strip>>;
208
+ linkPending: z.ZodOptional<z.ZodBoolean>;
209
+ notice: z.ZodOptional<z.ZodString>;
139
210
  movedAt: z.ZodOptional<z.ZodString>;
140
211
  error: z.ZodOptional<z.ZodString>;
141
212
  }, z.core.$strict>;
@@ -166,6 +237,8 @@ export declare function moveFrom(records: readonly MoveRecord[], target: {
166
237
  source: string;
167
238
  session?: string;
168
239
  }): MoveRecord | undefined;
240
+ /** Conversation-bound annotations shared by tab and pane overview rows. */
241
+ export declare function moveSessionFields(records: readonly MoveRecord[], target: Target, title?: string): Json;
169
242
  /** The receipt fields for a finished move. */
170
243
  export declare function movedWorker(record: MoveRecord): MovedWorker | undefined;
171
244
  /** A harness as people name it, with its account and model: "Claude (work, opus)". */
@@ -176,7 +249,7 @@ export declare function harnessName(to: {
176
249
  effort?: string;
177
250
  }): string;
178
251
  /** What the moving agent is asked to write. */
179
- export declare function handoffRequest(id: string, to: MoveTo): string;
252
+ export declare function handoffRequest(id: string, to: MoveTo, mode?: "replace" | "new-chat"): string;
180
253
  /** The hand-off between the markers in the agent's replies after the request,
181
254
  * or undefined while its end marker has not arrived. Code fences around the
182
255
  * block are dropped. */
@@ -281,7 +354,7 @@ export declare class SessionMover {
281
354
  private exit;
282
355
  /** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
283
356
  private relaunch;
284
- /** The new agent's full target, waiting a little for its conversation id when the launch did not have it yet. */
357
+ /** New chats remain open as linking while the harness establishes its conversation. */
285
358
  private newTarget;
286
359
  }
287
360
  /** The last `bytes` of a transcript as lines, the first (cut) one dropped. */
@@ -1,6 +1,6 @@
1
1
  // Moving a live session to another agent: the agent in the pane writes a
2
2
  // hand-off, exits the way it normally does, and the target harness starts in
3
- // the same pane, in the same folder, with that hand-off as its first prompt.
3
+ // the same pane by default, or a new chat that keeps the old agent running.
4
4
  //
5
5
  // The hand-off is asked for through the same durable prompt path `hand_off`
6
6
  // uses, as a reply between two marker lines; the Hook reads it from the
@@ -35,12 +35,13 @@ export { moveToSchema };
35
35
  export const moveRequestSchema = z.object({
36
36
  target: targetSchema,
37
37
  to: moveToSchema,
38
+ mode: z.enum(["replace", "new-chat"]).default("replace"),
38
39
  /** Kept on a retry: the same id returns the move already under way. */
39
40
  id: z.string().uuid().optional(),
40
41
  /** How long the agent gets to write its hand-off before Phren builds one. */
41
42
  handoffTimeoutMs: z.number().int().min(5_000).max(900_000).optional(),
42
43
  }).strict();
43
- const MOVE_STATES = ["handing-off", "exiting", "launching", "moved", "failed"];
44
+ const MOVE_STATES = ["handing-off", "exiting", "launching", "linking", "moved", "failed"];
44
45
  const timestamp = z.string().datetime();
45
46
  const moveRecordSchema = z.object({
46
47
  id: z.string().uuid(),
@@ -48,6 +49,9 @@ const moveRecordSchema = z.object({
48
49
  createdAt: timestamp, updatedAt: timestamp,
49
50
  from: z.object({ target: targetSchema, account: z.string().max(64).optional(), label: z.string().max(200).optional() }).strict(),
50
51
  to: moveToSchema,
52
+ mode: z.enum(["replace", "new-chat"]).optional(),
53
+ handedOffTo: z.object({ target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
54
+ handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
51
55
  cwd: z.string().max(4096),
52
56
  /** The dispatch the moved worker was launched for, as its turn record names it. */
53
57
  dispatch: briefId.optional(),
@@ -56,6 +60,9 @@ const moveRecordSchema = z.object({
56
60
  exit: z.enum(["clean", "interrupted", "killed"]).optional(),
57
61
  placement: z.enum(["same-pane", "adjacent-pane"]).optional(),
58
62
  target: z.union([targetSchema, startingTargetSchema]).optional(),
63
+ paneTarget: targetSchema.omit({ session: true }).optional(),
64
+ linkPending: z.boolean().optional(),
65
+ notice: z.string().max(500).optional(),
59
66
  movedAt: timestamp.optional(),
60
67
  error: z.string().max(500).optional(),
61
68
  }).strict();
@@ -111,6 +118,18 @@ export function moveFrom(records, target) {
111
118
  && (target.session === undefined || from.session === target.session);
112
119
  });
113
120
  }
121
+ /** Conversation-bound annotations shared by tab and pane overview rows. */
122
+ export function moveSessionFields(records, target, title) {
123
+ const matches = (other) => other.server === target.server && other.workspace === target.workspace
124
+ && other.tab === target.tab && other.pane === target.pane && other.source === target.source
125
+ && "session" in other && other.session === target.session;
126
+ const outgoing = records.find(record => record.state === "moved" && record.mode === "new-chat" && matches(record.from.target));
127
+ const incoming = records.find(record => record.state === "moved" && record.mode === "new-chat" && record.target && matches(record.target));
128
+ const suffix = outgoing ? ` (handed off to ${outgoing.to.harness})` : "";
129
+ return { ...(outgoing?.handedOffTo ? { handedOffTo: outgoing.handedOffTo,
130
+ title: `${(title ?? outgoing.from.label ?? outgoing.from.target.source).replace(/ \(handed off to [^)]+\)$/, "")}${suffix}` } : {}),
131
+ ...(incoming?.handedOffFrom ? { handedOffFrom: incoming.handedOffFrom } : {}) };
132
+ }
114
133
  /** The receipt fields for a finished move. */
115
134
  export function movedWorker(record) {
116
135
  if (record.state !== "moved" || !record.target)
@@ -128,7 +147,7 @@ const markers = (id) => {
128
147
  return { begin: `=== PHREN HANDOFF ${short} BEGIN ===`, end: `=== PHREN HANDOFF ${short} END ===` };
129
148
  };
130
149
  /** What the moving agent is asked to write. */
131
- export function handoffRequest(id, to) {
150
+ export function handoffRequest(id, to, mode = "replace") {
132
151
  const { begin, end } = markers(id);
133
152
  return [
134
153
  `Phren is moving this session to ${harnessName(to)}, which continues the work in this same folder. Write a hand-off for it now.`,
@@ -146,7 +165,8 @@ export function handoffRequest(id, to) {
146
165
  "## Decisions: what you chose and why, including approaches you ruled out",
147
166
  "## Next steps: in order",
148
167
  "## Open questions: for the owner, or still undecided",
149
- "## Key files: paths, a few words each",
168
+ "## Key files: paths, a few words each, including files you had open or changed",
169
+ ...(mode === "new-chat" ? ["The target starts in a new chat. Keep this agent running; do not exit after the hand-off."] : []),
150
170
  "",
151
171
  "Write it in full; do not shorten it. Use no tools once you start it. Phren saves it to a file and starts the next agent with it.",
152
172
  ].join("\n");
@@ -322,6 +342,9 @@ export function handoffDocument(record, body, observed, at) {
322
342
  "",
323
343
  `Moved by Phren at ${at} (move ${record.id}) in ${record.cwd}.${record.dispatch ? ` Dispatch ${record.dispatch}.` : ""}`,
324
344
  "",
345
+ ...(record.mode === "new-chat" ? ["## Previous chat", "",
346
+ `Title: ${record.from.label ?? record.from.target.source}`,
347
+ "Target (JSON, for opening the old chat):", "```json", JSON.stringify(record.from.target), "```", ""] : []),
325
348
  body.trim(),
326
349
  "",
327
350
  observed,
@@ -397,10 +420,10 @@ export class SessionMover {
397
420
  if (!path.isAbsolute(cwd))
398
421
  throw new BridgeError(409, "The pane's folder is unknown, so the new agent could not start there.");
399
422
  const dispatch = await this.deps.paneDispatch?.(target.server, pane).catch(() => undefined);
400
- const label = [pane.label, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
423
+ const label = [pane.label, pane.title, pane.terminal_title_stripped, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
401
424
  const at = new Date(this.now).toISOString();
402
425
  const record = { id: data.id ?? randomUUID(), state: "handing-off", createdAt: at, updatedAt: at,
403
- from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd,
426
+ mode: data.mode, from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd,
404
427
  ...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}) };
405
428
  await saveMove(record);
406
429
  const key = `${target.server}\0${target.pane}`;
@@ -423,25 +446,34 @@ export class SessionMover {
423
446
  const [git, processes] = await Promise.all([(this.deps.git ?? readGitState)(record.cwd).catch(() => undefined),
424
447
  (this.deps.processesBelow ?? processesBelow)(pids).catch(() => [])]);
425
448
  const written = await this.askForHandoff(record, handoffMs);
426
- const body = "text" in written ? written.text : await this.fallback(record, written.reason);
449
+ const fallback = "text" in written ? undefined : await this.fallback(record, written.reason);
450
+ const body = "text" in written ? written.text : record.mode === "new-chat"
451
+ ? `## Goal and current state\n\n${fallback}\n\n## Next steps\n\nContinue the owner's goal above after checking the checkout and the latest agent reply.\n\n## Key files\n\nOpen or changed files are named in the conversation above and the checked Git state below; open editor tabs are not available to the Hook.`
452
+ : fallback;
427
453
  const document = handoffDocument(record, body, observedState(git, processes), new Date(this.now).toISOString());
428
454
  const file = handoffPath(record.id);
429
455
  const prompt = briefText(continuePrompt(document, file));
430
456
  // The folder is the new agent's brief folder; the hand-off is written into it, whole.
431
457
  await writeLaunchBrief({ id: record.id, text: prompt }, this.now, record.from.label);
432
458
  await atomic(file, document);
433
- await this.update(record, { state: "exiting", handoff: { path: file, source: "text" in written ? "agent" : "fallback",
459
+ await this.update(record, { state: record.mode === "new-chat" ? "launching" : "exiting", handoff: { path: file, source: "text" in written ? "agent" : "fallback",
434
460
  ...("reason" in written ? { reason: written.reason.slice(0, 300) } : {}), chars: document.length } });
435
- const exit = await this.exit(record);
436
- await this.update(record, { state: "launching", exit });
437
- await this.deps.afterExit?.(from.server, from.pane).catch(() => undefined);
461
+ if (record.mode !== "new-chat") {
462
+ const exit = await this.exit(record);
463
+ await this.update(record, { state: "launching", exit });
464
+ await this.deps.afterExit?.(from.server, from.pane).catch(() => undefined);
465
+ }
438
466
  const launched = await this.relaunch(record, prompt);
439
- await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched });
467
+ await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched,
468
+ ...(record.mode === "new-chat" ? {
469
+ ...(launched.target ? { handedOffTo: { target: launched.target } } : {}),
470
+ handedOffFrom: { target: from, title: record.from.label ?? from.source },
471
+ } : {}) });
440
472
  logger.info("move", `Moved ${from.source} in pane ${from.pane} to ${harnessName(record.to)} (${launched.placement}); hand-off ${record.handoff?.source}.`);
441
473
  }
442
474
  catch (error) {
443
475
  const message = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, " ");
444
- const stopped = record.state === "launching";
476
+ const stopped = record.exit !== undefined;
445
477
  const hint = stopped && record.handoff ? ` The old agent has exited; start ${HARNESS_NAMES[record.to.harness]} in the pane with the hand-off at ${record.handoff.path}.` : "";
446
478
  await this.update(record, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => undefined);
447
479
  logger.warn("move", `Moving pane ${from.pane} to ${record.to.harness} failed: ${message}`);
@@ -452,7 +484,7 @@ export class SessionMover {
452
484
  const from = record.from.target;
453
485
  const deadline = this.now + handoffMs;
454
486
  try {
455
- const sent = await this.deps.deliver(from, handoffRequest(record.id, record.to), `move-${record.id}`);
487
+ const sent = await this.deps.deliver(from, handoffRequest(record.id, record.to, record.mode), `move-${record.id}`);
456
488
  if (sent.ok !== true && sent.queued !== true)
457
489
  return { reason: `the request could not be delivered (${String(sent.error ?? sent.state ?? "not confirmed")}).` };
458
490
  }
@@ -547,33 +579,54 @@ export class SessionMover {
547
579
  // A Claude target with no account keeps the pane's own, so its shell's CLAUDE_CONFIG_DIR is right.
548
580
  const shellAccount = record.from.account ?? DEFAULT_ACCOUNT;
549
581
  const account = record.to.harness === "claude" ? record.to.account ?? shellAccount : undefined;
550
- const samePane = (this.deps.envAtStart?.(from.server) ?? false) || record.to.harness !== "claude" || account === shellAccount;
582
+ const samePane = record.mode !== "new-chat" && ((this.deps.envAtStart?.(from.server) ?? false) || record.to.harness !== "claude" || account === shellAccount);
551
583
  const data = { kind: record.to.harness, label: record.from.label ?? HARNESS_NAMES[record.to.harness], cwd: record.cwd,
552
584
  ...(record.to.model ? { model: record.to.model } : {}), ...(record.to.effort ? { effort: record.to.effort } : {}), ...(account ? { account } : {}),
553
585
  brief: { id: record.id, text: prompt }, ...(samePane ? {} : { workspaceId: from.workspace }) };
554
586
  const into = samePane ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : undefined;
555
587
  const launched = await this.deps.launch(from.server, data, { ...(into ? { into } : {}), ...(record.dispatch ? { dispatchId: record.dispatch } : {}) });
588
+ // Keep the launched location even if delivering its first prompt fails.
589
+ const paneTarget = targetSchema.omit({ session: true }).parse({ server: from.server,
590
+ workspace: launched.workspaceId, tab: launched.tabId, pane: launched.paneId, source: record.to.harness });
591
+ const launchedTarget = z.union([targetSchema, startingTargetSchema]).safeParse(launched.target);
592
+ await this.update(record, { paneTarget, placement: samePane ? "same-pane" : "adjacent-pane",
593
+ ...(launchedTarget.success ? { target: launchedTarget.data } : {}) });
556
594
  // The target that takes no brief at launch (Copilot) gets it typed, as dispatch does.
557
595
  if (launched.briefLaunched === false) {
558
- const typedTo = targetSchema.safeParse(launched.target);
559
- if (typedTo.success)
560
- await this.deps.deliver(typedTo.data, prompt, `move-${record.id}-brief`).catch(() => undefined);
561
- else
562
- await this.deps.terminal.prompt(from.server, String(launched.paneId), prompt).catch(() => undefined);
596
+ try {
597
+ const typedTo = targetSchema.safeParse(launched.target);
598
+ if (typedTo.success) {
599
+ const sent = await this.deps.deliver(typedTo.data, prompt, `move-${record.id}-brief`);
600
+ if (sent.state === "failed" || (sent.ok !== true && sent.queued !== true)
601
+ || (sent.delivered === false && sent.queued !== true)) {
602
+ throw new Error(String(sent.error ?? sent.state ?? "delivery was not confirmed"));
603
+ }
604
+ }
605
+ else
606
+ await this.deps.terminal.prompt(from.server, paneTarget.pane, prompt);
607
+ }
608
+ catch (error) {
609
+ const reason = error instanceof Error ? error.message : String(error);
610
+ throw new Error(`${record.mode === "new-chat" ? "New chat" : "Target"} started but did not receive the hand-off. The launched pane was left open. ${reason}`);
611
+ }
563
612
  }
564
- if (!samePane)
613
+ if (!samePane && record.mode !== "new-chat")
565
614
  await this.deps.terminal.closePane(from.server, from.pane).catch(() => undefined);
566
615
  // The account the new agent runs under, also when the move named none.
567
616
  const to = account ? { ...record.to, account } : record.to;
568
- return { to, placement: samePane ? "same-pane" : "adjacent-pane", ...await this.newTarget(from.server, launched, record.to.harness) };
617
+ return { to, placement: samePane ? "same-pane" : "adjacent-pane", ...await this.newTarget(record, launched, record.to.harness) };
569
618
  }
570
- /** The new agent's full target, waiting a little for its conversation id when the launch did not have it yet. */
571
- async newTarget(server, launched, source) {
619
+ /** New chats remain open as linking while the harness establishes its conversation. */
620
+ async newTarget(record, launched, source) {
621
+ const server = record.from.target.server;
572
622
  const full = targetSchema.safeParse(launched.target);
573
623
  if (full.success)
574
624
  return { target: full.data };
575
625
  const place = { server, workspace: String(launched.workspaceId), tab: String(launched.tabId), pane: String(launched.paneId), source };
576
- for (const until = this.now + 30_000; this.now < until; await this.sleep(this.poll)) {
626
+ const newChat = record.mode === "new-chat";
627
+ if (newChat)
628
+ await this.update(record, { state: "linking" });
629
+ for (const until = this.now + (newChat ? 180_000 : 30_000); this.now < until; await this.sleep(this.poll)) {
577
630
  const pane = findPane(await this.deps.snapshot(server).catch(() => ({})), place);
578
631
  const session = pane && pane.agent === source ? await this.deps.identity(server, pane).catch(() => undefined) : undefined;
579
632
  const target = targetSchema.safeParse({ ...place, session });
@@ -581,7 +634,8 @@ export class SessionMover {
581
634
  return { target: target.data };
582
635
  }
583
636
  const starting = startingTargetSchema.safeParse(launched.target);
584
- return starting.success ? { target: starting.data } : {};
637
+ return { ...(starting.success ? { target: starting.data } : {}),
638
+ ...(newChat ? { linkPending: true, notice: "New chat started; the conversation link is pending after three minutes. Use the pane target to open it." } : {}) };
585
639
  }
586
640
  }
587
641
  /** The last `bytes` of a transcript as lines, the first (cut) one dropped. */