@lukstei/dsh-session-handoff 0.2.2-rc.5.7 → 0.2.2-rc.5.9

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.
package/dist/index.js CHANGED
@@ -12,10 +12,14 @@ const ASK_HEAD = 500;
12
12
  const ASK_TAIL = 300;
13
13
  const OUTCOME_LIMIT = 240;
14
14
  const FAILURE_LIMIT = 200;
15
- const ARTIFACT_LIMIT = 12;
15
+ const PATH_LIMIT = 300;
16
+ const TOOL_NAME_LIMIT = 80;
16
17
  const RECENT_TURNS = 5;
17
18
  const RECENT_HEAD = 1200;
18
19
  const RECENT_TAIL = 400;
20
+ const FAILURE_MAX = 20;
21
+ const ARTIFACT_MAX = 100;
22
+ const SHORT_ID_LENGTH$1 = 8;
19
23
  /** Tool argument keys that carry a durable file path. */
20
24
  const PATH_KEYS = [
21
25
  "path",
@@ -23,75 +27,120 @@ const PATH_KEYS = [
23
27
  "filePath",
24
28
  "notebook_path"
25
29
  ];
26
- function renderHandoff(snapshot) {
30
+ /** The first line of every handoff follow-up; names the parent session and its brief. */
31
+ const INSTRUCTION_LINE = /^The handoff brief for session (\S+) is at (.+)\.$/;
32
+ /**
33
+ * Id of the session whose brief this session was started from, read from the
34
+ * handoff follow-up it received.
35
+ */
36
+ function parentSessionId(snapshot) {
37
+ for (const event of snapshot.events) {
38
+ if (event.type !== "user/message" || event.data.source.kind !== "user") continue;
39
+ const text = blockText(event.data.content);
40
+ if (text === "") continue;
41
+ const match = INSTRUCTION_LINE.exec(text.split("\n", 1)[0]);
42
+ return match === null ? void 0 : match[1];
43
+ }
44
+ }
45
+ /**
46
+ * Renders one brief for a handoff chain.
47
+ * @param snapshots - Session logs, oldest ancestor first, the handed-off session last.
48
+ */
49
+ function renderHandoff(snapshots) {
27
50
  const turns = [];
28
- const byId = /* @__PURE__ */ new Map();
29
51
  const failures = [];
30
- const artifacts = [];
31
- const callNames = /* @__PURE__ */ new Map();
32
- const seenArtifacts = /* @__PURE__ */ new Set();
33
- let open;
52
+ const artifacts = /* @__PURE__ */ new Map();
53
+ const briefFiles = /* @__PURE__ */ new Set();
34
54
  let goal = "";
35
- for (const event of snapshot.events) switch (event.type) {
36
- case "turn/start": {
37
- const opened = {
38
- turn: event.data.turn,
39
- ask: "",
40
- outcome: "",
41
- reason: void 0
42
- };
43
- turns.push(opened);
44
- byId.set(event.data.turn, opened);
45
- open = opened;
46
- break;
47
- }
48
- case "user/message": {
49
- if (event.data.source.kind !== "user") break;
50
- const text = blockText(event.data.content);
51
- if (text === "") break;
52
- if (goal === "") goal = elide(flatten(text), ASK_HEAD, ASK_TAIL);
53
- if (open !== void 0 && open.ask === "") open.ask = text;
54
- break;
55
- }
56
- case "assistant/message": {
57
- const arc = byId.get(event.data.turn);
58
- if (arc === void 0) break;
59
- arc.outcome = blockText(event.data.message.content);
60
- break;
61
- }
62
- case "turn/end": {
63
- const arc = byId.get(event.data.turn);
64
- if (arc === void 0) break;
65
- arc.reason = event.data.reason;
66
- break;
67
- }
68
- case "tool/call": {
69
- const arc = byId.get(event.data.turn);
70
- callNames.set(event.data.callId, event.data.name);
71
- if (arc === void 0) break;
72
- collectArtifacts(event.data.arguments, artifacts, seenArtifacts);
73
- break;
74
- }
75
- case "tool/result": {
76
- const arc = byId.get(event.data.turn);
77
- if (event.data.message.isError !== true || arc === void 0) break;
78
- const callId = event.data.message.toolCallId;
79
- const name = callNames.get(callId);
80
- failures.push(`- **T${arc.turn}** tool \`${name === void 0 ? callId : name}\`: ${clip(errorReason(event.data.error), FAILURE_LIMIT)}`);
81
- break;
55
+ let eventCount = 0;
56
+ for (const snapshot of snapshots) {
57
+ const sessionId = String(snapshot.session.id);
58
+ const byId = /* @__PURE__ */ new Map();
59
+ const callNames = /* @__PURE__ */ new Map();
60
+ let open;
61
+ let sawUserMessage = false;
62
+ eventCount += snapshot.events.length;
63
+ for (const event of snapshot.events) switch (event.type) {
64
+ case "turn/start": {
65
+ const opened = {
66
+ turn: event.data.turn,
67
+ sessionId,
68
+ index: 0,
69
+ ask: "",
70
+ outcome: "",
71
+ reason: void 0,
72
+ isHandoff: false
73
+ };
74
+ turns.push(opened);
75
+ byId.set(event.data.turn, opened);
76
+ open = opened;
77
+ break;
78
+ }
79
+ case "user/message": {
80
+ if (event.data.source.kind !== "user") break;
81
+ const text = blockText(event.data.content);
82
+ if (text === "") break;
83
+ const instruction = sawUserMessage ? null : INSTRUCTION_LINE.exec(text.split("\n", 1)[0]);
84
+ sawUserMessage = true;
85
+ if (instruction !== null) {
86
+ briefFiles.add(instruction[2]);
87
+ if (open !== void 0) open.isHandoff = true;
88
+ break;
89
+ }
90
+ if (goal === "") goal = elide(flatten(text), ASK_HEAD, ASK_TAIL);
91
+ if (open !== void 0 && open.ask === "") open.ask = text;
92
+ break;
93
+ }
94
+ case "assistant/message": {
95
+ const arc = byId.get(event.data.turn);
96
+ if (arc === void 0) break;
97
+ arc.outcome = blockText(event.data.message.content);
98
+ break;
99
+ }
100
+ case "turn/end": {
101
+ const arc = byId.get(event.data.turn);
102
+ if (arc === void 0) break;
103
+ arc.reason = event.data.reason;
104
+ break;
105
+ }
106
+ case "tool/call": {
107
+ const arc = byId.get(event.data.turn);
108
+ callNames.set(event.data.callId, event.data.name);
109
+ if (arc === void 0 || arc.isHandoff) break;
110
+ collectArtifacts(event.data.arguments, artifacts, briefFiles);
111
+ break;
112
+ }
113
+ case "tool/result": {
114
+ const arc = byId.get(event.data.turn);
115
+ if (event.data.message.isError !== true || arc === void 0) break;
116
+ if (arc.isHandoff) break;
117
+ const callId = event.data.message.toolCallId;
118
+ const name = callNames.get(callId);
119
+ failures.push({
120
+ arc,
121
+ text: `tool \`${clip(name === void 0 ? callId : name, TOOL_NAME_LIMIT)}\`: ${clip(errorReason(event.data.error), FAILURE_LIMIT)}`
122
+ });
123
+ break;
124
+ }
82
125
  }
83
126
  }
84
- const id = String(snapshot.session.id);
85
- const cwd = snapshot.session.cwd;
127
+ const work = turns.filter((turn) => !turn.isHandoff);
128
+ work.forEach((turn, index) => {
129
+ turn.index = index + 1;
130
+ });
131
+ const current = snapshots[snapshots.length - 1];
132
+ const id = String(current.session.id);
133
+ const cwd = current.session.cwd;
86
134
  return {
87
135
  markdown: `${[
88
136
  `# Handoff — ${id}`,
89
137
  "",
90
138
  `- session: \`${id}\``,
139
+ ...snapshots.length > 1 ? [`- chain: ${snapshots.map((snapshot) => `\`${shortId$1(String(snapshot.session.id))}\``).join(" → ")}`] : [],
91
140
  `- cwd: \`${cwd === void 0 ? "unknown" : cwd}\``,
92
- `- created: ${new Date(snapshot.session.createdAt).toISOString()}`,
93
- `- events: ${snapshot.events.length}`,
94
- `- turns: ${turns.length}`,
141
+ `- created: ${new Date(current.session.createdAt).toISOString()}`,
142
+ `- events: ${eventCount}`,
143
+ `- turns: ${work.length}`,
95
144
  "",
96
145
  "## Goal",
97
146
  "",
@@ -99,17 +148,17 @@ function renderHandoff(snapshot) {
99
148
  "",
100
149
  "## Turns",
101
150
  "",
102
- turns.length === 0 ? "none" : turns.map((turn, index) => turnBlock(turn, index >= turns.length - RECENT_TURNS)).join("\n\n"),
151
+ work.length === 0 ? "none" : turnList(work),
103
152
  "",
104
153
  "## Failures",
105
154
  "",
106
- failures.length === 0 ? "none" : failures.join("\n"),
155
+ failures.length === 0 ? "none" : bounded(failures.map(({ arc, text }) => `- **T${arc.index}**${arc.sessionId === id ? "" : ` (${shortId$1(arc.sessionId)})`} ${text}`), FAILURE_MAX, "older failures"),
107
156
  "",
108
157
  "## Artifacts",
109
158
  "",
110
- artifacts.length === 0 ? "none" : artifacts.map((file) => `- \`${file}\``).join("\n")
159
+ artifacts.size === 0 ? "none" : bounded([...artifacts.keys()].map((file) => `- \`${file}\``), ARTIFACT_MAX, "older paths")
111
160
  ].join("\n")}\n`,
112
- turns: turns.length
161
+ turns: work.length
113
162
  };
114
163
  }
115
164
  function handoffInstruction(sessionId, file) {
@@ -124,11 +173,28 @@ function handoffInstruction(sessionId, file) {
124
173
  "Do not start the work until the user confirms the next action."
125
174
  ].join("\n");
126
175
  }
176
+ /** Last RECENT_TURNS turns quoted at length, OLDER_TURNS before them flattened, the rest counted. */
177
+ function turnList(work) {
178
+ const kept = work.slice(-35);
179
+ const dropped = work.length - kept.length;
180
+ const blocks = kept.map((turn, index) => turnBlock(turn, index >= kept.length - RECENT_TURNS));
181
+ if (dropped > 0) blocks.unshift(`… ${dropped} earlier turns omitted`);
182
+ return blocks.join("\n\n");
183
+ }
184
+ /** Keeps the newest `max` lines, naming how many older ones were dropped. */
185
+ function bounded(lines, max, noun) {
186
+ const dropped = lines.length - max;
187
+ if (dropped <= 0) return lines.join("\n");
188
+ return [`- … ${dropped} ${noun} omitted`, ...lines.slice(-max)].join("\n");
189
+ }
190
+ function shortId$1(id) {
191
+ return id.slice(0, SHORT_ID_LENGTH$1);
192
+ }
127
193
  /** Recent turns quote the ask and reply at length; older turns are flattened and short. */
128
194
  function turnBlock(turn, recent) {
129
195
  const kind = turn.reason === void 0 ? "unfinished" : turn.reason.kind;
130
196
  const body = (recent ? [elide(turn.ask, RECENT_HEAD, RECENT_TAIL), elide(turn.outcome, RECENT_HEAD, RECENT_TAIL)] : [elide(flatten(turn.ask), ASK_HEAD, ASK_TAIL), clip(turn.outcome, OUTCOME_LIMIT)]).filter((part) => part !== "").join("\n\n");
131
- return `### T${turn.turn} [${kind}]\n\n${body === "" ? "(no content)" : body}`;
197
+ return `### T${turn.index} [${kind}]\n\n${body === "" ? "(no content)" : body}`;
132
198
  }
133
199
  function blockText(blocks) {
134
200
  const parts = [];
@@ -159,7 +225,7 @@ function errorReason(error) {
159
225
  if (error.reason === void 0) return error.code;
160
226
  return error.reason;
161
227
  }
162
- function collectArtifacts(args, into, seen) {
228
+ function collectArtifacts(args, into, briefFiles) {
163
229
  let parsed;
164
230
  try {
165
231
  parsed = JSON.parse(args);
@@ -170,10 +236,10 @@ function collectArtifacts(args, into, seen) {
170
236
  const record = parsed;
171
237
  for (const key of PATH_KEYS) {
172
238
  const value = record[key];
173
- if (typeof value !== "string" || value === "" || seen.has(value)) continue;
174
- seen.add(value);
175
- into.push(value);
176
- if (into.length >= ARTIFACT_LIMIT) return;
239
+ if (typeof value !== "string" || value === "" || briefFiles.has(value)) continue;
240
+ const path = clip(value, PATH_LIMIT);
241
+ into.delete(path);
242
+ into.set(path, true);
177
243
  }
178
244
  }
179
245
  // src/launch.ts
@@ -194,63 +260,82 @@ const inject = [
194
260
  "workingDirectory",
195
261
  "sessionController",
196
262
  "sessionTitle",
197
- "workspaceRegistry"
263
+ "workspaceRegistry",
264
+ "llm"
198
265
  ];
199
266
  const HANDOFF_FILE = "HANDOFF.md";
200
- const RECENT_LIMIT = 5;
201
267
  const SHORT_ID_LENGTH = 8;
202
268
  const RESUMED_SUFFIX = " (Resumed)";
203
269
  function apply(ctx) {
204
270
  ctx.commands.register({
205
271
  name: "handoff",
206
- description: "Hand this session off to a new one, or write the resume brief for <session-id> into this one",
207
- input: { hint: "[session-id]" },
272
+ description: "Hand this session off to a new one (bare: pick the model from a list)",
273
+ input: { hint: "[provider/model]" },
208
274
  handler: (invocation) => handoff(ctx, invocation)
209
275
  });
210
276
  }
211
- function resolveHandoffTarget(sessions, query) {
212
- const exact = sessions.filter((session) => String(session.header.id) === query);
213
- if (exact.length > 0) return exact;
214
- return sessions.filter((session) => String(session.header.id).startsWith(query));
277
+ /**
278
+ * Split `provider/model` at the first slash: provider ids have none, model ids may.
279
+ * @internal exported for the unit test only.
280
+ */
281
+ function parseModelArg(raw) {
282
+ const text = raw.trim();
283
+ const slash = text.indexOf("/");
284
+ if (slash <= 0 || slash === text.length - 1) return void 0;
285
+ return {
286
+ provider: text.slice(0, slash),
287
+ model: text.slice(slash + 1)
288
+ };
289
+ }
290
+ /**
291
+ * Check the route against the registered providers and the provider's own model
292
+ * resolution, the same check subagent routes get, so a typo fails here and not
293
+ * on the new session's first turn.
294
+ * @returns an error text, or `undefined` when the route resolves.
295
+ */
296
+ async function modelError(ctx, model, signal) {
297
+ try {
298
+ const providers = ctx.llm.listProviders();
299
+ if (!providers.some((provider) => provider.id === model.provider)) {
300
+ const available = providers.map((provider) => provider.id).join(", ");
301
+ return `LLM provider '${model.provider}' is not registered; available providers: ${available || "(none)"}`;
302
+ }
303
+ await ctx.llm.resolveCallConfig({
304
+ provider: model.provider,
305
+ model: model.model
306
+ }, signal);
307
+ return;
308
+ } catch (error) {
309
+ return error instanceof Error ? error.message : String(error);
310
+ }
215
311
  }
216
312
  async function handoff(ctx, invocation) {
217
313
  const raw = invocation.rawInput.trim();
218
- const launch = raw === "";
219
- const agent = invocation.agent;
220
- let targetId;
221
- if (launch) targetId = agent.session.id;
222
- else {
223
- const sessions = await ctx.sessionQuery.listSessions(invocation.signal);
224
- const matches = resolveHandoffTarget(sessions, raw);
225
- if (matches.length === 0) return {
314
+ let model;
315
+ if (raw !== "") {
316
+ model = parseModelArg(raw);
317
+ if (model === void 0) return {
226
318
  kind: "error",
227
- text: `No session matches "${raw}". Most recent sessions:\n${sessions.slice(0, RECENT_LIMIT).map((session) => `- ${String(session.header.id)}`).join("\n")}`
319
+ text: `Expected "<provider>/<model>", got "${raw}"; run bare /handoff to pick one.`
228
320
  };
229
- if (matches.length > 1) return {
321
+ const invalid = await modelError(ctx, model, invocation.signal);
322
+ if (invalid !== void 0) return {
230
323
  kind: "error",
231
- text: `"${raw}" is ambiguous:\n${matches.map((session) => `- ${String(session.header.id)}`).join("\n")}`
232
- };
233
- targetId = matches[0].header.id;
234
- if (targetId === agent.session.id) return {
235
- kind: "error",
236
- text: "That is this session; there is nothing to hand off."
324
+ text: invalid
237
325
  };
238
326
  }
327
+ const agent = invocation.agent;
328
+ const targetId = agent.session.id;
239
329
  try {
240
330
  const snapshot = await ctx.sessionQuery.readSession(targetId);
241
- const rendered = renderHandoff(snapshot);
331
+ const rendered = renderHandoff(await readChain(ctx, snapshot, invocation.signal));
242
332
  if (rendered.turns === 0) return {
243
333
  kind: "error",
244
- text: launch ? "This session has no turns to hand off." : `Session ${shortId(targetId)} has no turns to hand off.`
245
- };
246
- if (launch) return {
247
- kind: "success",
248
- text: formatLaunchResult((await createBeside(ctx, agent, targetId, rendered.markdown, snapshot, invocation.signal)).sessionId)
334
+ text: "This session has no turns to hand off."
249
335
  };
250
- const file = await deliver(ctx, agent, targetId, rendered.markdown);
251
336
  return {
252
337
  kind: "success",
253
- text: `Handoff for ${shortId(targetId)} (${rendered.turns} turns) → ${file}`
338
+ text: formatLaunchResult((await createBeside(ctx, agent, targetId, rendered.markdown, snapshot, invocation.signal, model)).sessionId)
254
339
  };
255
340
  } catch (error) {
256
341
  return {
@@ -260,6 +345,24 @@ async function handoff(ctx, invocation) {
260
345
  }
261
346
  }
262
347
  /**
348
+ * The handed-off session preceded by every ancestor it was itself handed off from,
349
+ * oldest first, so the brief keeps what earlier briefs summarized.
350
+ */
351
+ async function readChain(ctx, snapshot, signal) {
352
+ const chain = [snapshot];
353
+ const seen = /* @__PURE__ */ new Set([String(snapshot.session.id)]);
354
+ let parent = parentSessionId(snapshot);
355
+ if (parent === void 0) return chain;
356
+ const known = new Set((await ctx.sessionQuery.listSessions(signal)).map((session) => String(session.header.id)));
357
+ while (parent !== void 0 && !seen.has(parent) && known.has(parent)) {
358
+ seen.add(parent);
359
+ const ancestor = await ctx.sessionQuery.readSession(parent);
360
+ chain.unshift(ancestor);
361
+ parent = parentSessionId(ancestor);
362
+ }
363
+ return chain;
364
+ }
365
+ /**
263
366
  * Write the brief into the agent's own scratch directory and queue the follow-up
264
367
  * turn that tells it to read that file.
265
368
  * @param ctx - Host context.
@@ -303,8 +406,8 @@ function shortId(id) {
303
406
  return id.slice(0, SHORT_ID_LENGTH);
304
407
  }
305
408
  /**
306
- * Create the resumed session beside this one: same workspace, same preset, same
307
- * model, the brief in its own scratch directory, and one follow-up turn that
409
+ * Create the resumed session beside this one: same workspace, same preset, the
410
+ * source's model or the given one, the brief in its own scratch directory, and one follow-up turn that
308
411
  * tells it to read that brief.
309
412
  * @param ctx - Host context.
310
413
  * @param source - Session the command runs in.
@@ -312,10 +415,11 @@ function shortId(id) {
312
415
  * @param markdown - Rendered brief.
313
416
  * @param snapshot - Source session log, the origin of the kanban links to copy.
314
417
  * @param signal - Cancellation signal of the invoking command.
418
+ * @param model - Model the new session starts on; the source's own when absent.
315
419
  * @returns the created session identity.
316
420
  */
317
- async function createBeside(ctx, source, targetId, markdown, snapshot, signal) {
318
- const selection = source.model.current();
421
+ async function createBeside(ctx, source, targetId, markdown, snapshot, signal, model) {
422
+ const selection = model === void 0 ? source.model.current() : model;
319
423
  const agentPreset = source.session.header.agentPreset;
320
424
  const workspace = workspaceOf(ctx, source.session.id);
321
425
  const created = await ctx.sessionController.create(workspace === void 0 ? {
@@ -347,4 +451,4 @@ async function createBeside(ctx, source, targetId, markdown, snapshot, signal) {
347
451
  await deliver(ctx, agent, targetId, markdown);
348
452
  return created;
349
453
  }
350
- export { apply, inject, name, resolveHandoffTarget };
454
+ export { apply, inject, name, parseModelArg };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lukstei/dsh-session-handoff",
3
- "version": "0.2.2-rc.5.7",
3
+ "version": "0.2.2-rc.5.9",
4
4
  "description": "Session handoff brief command for DSH",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -36,19 +36,23 @@
36
36
  "inject": [
37
37
  "@deepseek-ai/dsh-api-session-controller",
38
38
  "@lukstei/dsh-client-split-view",
39
+ "@deepseek-ai/dsh-client-ui-commands",
39
40
  "@deepseek-ai/dsh-client-ui-conversation",
41
+ "@deepseek-ai/dsh-client-ui-model-selection",
40
42
  "@deepseek-ai/dsh-client-ui-renderer"
41
43
  ]
42
44
  }
43
45
  },
44
46
  "dependencies": {
45
- "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.7"
47
+ "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.9"
46
48
  },
47
49
  "peerDependencies": {
48
50
  "@deepseek-ai/cordis": "*",
49
51
  "@deepseek-ai/dsh-agent": "*",
50
52
  "@deepseek-ai/dsh-api-session-controller": "*",
53
+ "@deepseek-ai/dsh-client-ui-commands": "*",
51
54
  "@deepseek-ai/dsh-client-ui-conversation": "*",
55
+ "@deepseek-ai/dsh-client-ui-model-selection": "*",
52
56
  "@deepseek-ai/dsh-client-ui-primitives": "*",
53
57
  "@deepseek-ai/dsh-client-ui-renderer": "*",
54
58
  "@deepseek-ai/dsh-client-ui-session": "*",
@@ -68,7 +72,9 @@
68
72
  "@deepseek-ai/cordis": "4.1.0",
69
73
  "@deepseek-ai/dsh-agent": "0.2.2-rc.5",
70
74
  "@deepseek-ai/dsh-api-session-controller": "0.2.2-rc.5",
75
+ "@deepseek-ai/dsh-client-ui-commands": "0.2.2-rc.5",
71
76
  "@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.5",
77
+ "@deepseek-ai/dsh-client-ui-model-selection": "0.2.2-rc.5",
72
78
  "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.5",
73
79
  "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.5",
74
80
  "@deepseek-ai/dsh-client-ui-session": "0.2.2-rc.5",
@@ -81,7 +87,7 @@
81
87
  "@deepseek-ai/dsh-token-meter": "0.2.2-rc.5",
82
88
  "@deepseek-ai/dsh-working-directory": "0.2.2-rc.5",
83
89
  "@deepseek-ai/dsh-workspace": "0.2.2-rc.5",
84
- "@lukstei/dsh-client-split-view": "0.2.2-rc.5.7",
90
+ "@lukstei/dsh-client-split-view": "0.2.2-rc.5.9",
85
91
  "@types/node": "^26.0.0",
86
92
  "@types/react": "^19.3.0",
87
93
  "@zaimokuza/dsh-acp-adapter": "0.2.2-rc.5.2",
@@ -1,6 +1,8 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { ISessions } from "@deepseek-ai/dsh-api-session-controller/client";
3
+ import type {} from "@deepseek-ai/dsh-client-ui-commands/client";
3
4
  import type {} from "@deepseek-ai/dsh-client-ui-conversation/client";
5
+ import type {} from "@deepseek-ai/dsh-client-ui-model-selection/client";
4
6
  import type {} from "@deepseek-ai/dsh-client-ui-renderer/client";
5
7
  import type { SessionId } from "@deepseek-ai/dsh-session/types";
6
8
  import type {} from "@lukstei/dsh-client-split-view/client-contract";
@@ -9,7 +11,13 @@ import { launchedSessionId } from "../launch.ts";
9
11
  import { type AcpUsageReader, setAcpUsageReader } from "./acp-usage.ts";
10
12
  import { HandoffRing } from "./ring.ts";
11
13
 
12
- export const inject = ["sessions", "splitView", "slots"];
14
+ export const inject = [
15
+ "sessions",
16
+ "splitView",
17
+ "slots",
18
+ "commandUi",
19
+ "modelDirectories",
20
+ ];
13
21
 
14
22
  /**
15
23
  * Open every session the Host reports as launched as a pane of its own. A slash
@@ -38,11 +46,49 @@ export function apply(ctx: Context): void {
38
46
  };
39
47
 
40
48
  // Same command the user would type; sent directly so the composer draft stays untouched.
41
- const handoff = async (id: SessionId): Promise<void> => {
49
+ const run = async (id: SessionId, line: string): Promise<void> => {
42
50
  await sessions.using(id, { source: "splitView" }, async (reference) => {
43
- await reference.binding.session.command("/handoff");
51
+ const result = await reference.binding.session.command(line);
52
+ if (!result.ok) {
53
+ console.warn(`session-handoff: ${line} failed`, result);
54
+ }
44
55
  });
45
56
  };
57
+ const handoff = (id: SessionId): Promise<void> => run(id, "/handoff");
58
+
59
+ // A bare composer `/handoff` opens the same model list as `/model`; the pick is
60
+ // submitted back as the argued line the Host command parses (the ring sends the bare line straight to the Host, which keeps the source model).
61
+ ctx.effect(
62
+ () =>
63
+ ctx.commandUi.decorate({
64
+ name: "handoff",
65
+ available: () => true,
66
+ ui: {
67
+ kind: "popupSelect",
68
+ searchMode: "fuzzy-label",
69
+ options: async (session) => {
70
+ const state = await ctx.modelDirectories
71
+ .directoryFor(session.sessionId)
72
+ .load();
73
+ return state.groups.flatMap((group) =>
74
+ group.models.map((model) => ({
75
+ id: `${group.id}/${model.id}`,
76
+ label: model.name,
77
+ group: { name: group.id, label: group.name },
78
+ ...(state.current !== null &&
79
+ state.current.provider === group.id &&
80
+ state.current.model === model.id
81
+ ? { active: true }
82
+ : {}),
83
+ })),
84
+ );
85
+ },
86
+ onSelect: (option, session) =>
87
+ run(session.sessionId, `/handoff ${option.id}`),
88
+ },
89
+ }),
90
+ "session-handoff: /handoff picker",
91
+ );
46
92
 
47
93
  const watch = (id: SessionId): void => {
48
94
  const binding = sessions.binding(id);
@@ -34,6 +34,9 @@ export function HandoffRing({
34
34
  const running = useSession((session) => session.running);
35
35
  const [acp, setAcp] = useState<AcpUsage | undefined>(undefined);
36
36
  const [cold, setCold] = useState(false);
37
+ const [pendingSession, setPendingSession] = useState<
38
+ SessionStandardProps["sessionId"] | undefined
39
+ >(undefined);
37
40
 
38
41
  // ACP agents report occupancy to the adapter, never to DSH's `contextPressure`; read it
39
42
  // when a turn settles. The reader is unset (so this is a no-op) without the adapter.
@@ -74,23 +77,47 @@ export function HandoffRing({
74
77
  const level = handoffLevel(tokens, window, cold);
75
78
  if (level === "none" || tokens === undefined) return null;
76
79
  const k = Math.round(tokens / 1000);
80
+ const pending = pendingSession === sessionId;
81
+ const isDisabled = running || pending;
82
+ const startHandoff = async (): Promise<void> => {
83
+ if (isDisabled) return;
84
+ setPendingSession(sessionId);
85
+ try {
86
+ await onHandoff(sessionId);
87
+ } catch (error: unknown) {
88
+ console.error("session-handoff: handoff failed", error);
89
+ } finally {
90
+ setPendingSession((current) =>
91
+ current === sessionId ? undefined : current,
92
+ );
93
+ }
94
+ };
77
95
  const hint = cold
78
96
  ? "cache is cold, a fresh session is cheaper now"
79
97
  : "consider a fresh session";
80
- const label = `Context ${k}k tokens: ${hint}. Click to hand off (/handoff)`;
98
+ const action = pending
99
+ ? "Handing off…"
100
+ : running
101
+ ? "Wait for the current turn to finish to hand off (/handoff)"
102
+ : "Click to hand off (/handoff)";
103
+ const label = `Context ${k}k tokens: ${hint}. ${action}`;
81
104
  return createElement(Tooltip, {
82
105
  label,
83
106
  side: "top",
84
107
  portal: true,
108
+ // Disabled native buttons omit mouseleave, so close Tooltip from state.
109
+ disabled: isDisabled,
85
110
  // biome-ignore lint/correctness/noChildrenProp: Tooltip types `children` as a required prop, which createElement's 3rd argument does not satisfy
86
111
  children: createElement(Button, {
87
112
  variant: "ghost",
88
113
  size: "sm",
114
+ disabled: isDisabled,
115
+ title: isDisabled ? label : undefined,
89
116
  "aria-label": label,
90
117
  // the icon strokes with currentColor; 28px square instead of the text-button padding
91
118
  style: { color: COLOR[level], padding: 0, width: 28 },
92
119
  icon: createElement(IconGaugeOutlineMedium, { size: 16 }),
93
- onClick: () => void onHandoff(sessionId),
120
+ onClick: () => void startHandoff(),
94
121
  }),
95
122
  });
96
123
  }