@lukstei/dsh-session-handoff 0.2.2-rc.5.3 → 0.2.2-rc.5.5

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/README.md CHANGED
@@ -65,13 +65,19 @@ Server-side and client-side entries.
65
65
  | `sessionTitle` | Required | @deepseek-ai/dsh-session-title | Plugin stays pending; never applies. |
66
66
  | `workspaceRegistry` | Required | @deepseek-ai/dsh-workspace | Plugin stays pending; never applies. |
67
67
 
68
- **Client-side** (`inject`: `sessions`, `splitView`; both required):
68
+ **Client-side** (`inject`: `sessions`, `splitView`, `slots`; all required):
69
69
 
70
70
  | Plugin / service | Required? | Provided by | Effect without it |
71
71
  |---|---|---|---|
72
72
  | `sessions` | Required | @deepseek-ai/dsh-api-session-controller | Plugin stays pending; never applies. |
73
73
  | `splitView` | Required | [`@lukstei/dsh-client-split-view`](../dsh-client-split-view/README.md) (also in `dsh.client.inject`) | Plugin stays pending; never applies. The client entry (launch into a pane) does not activate; the host `/handoff` command still works. |
74
74
 
75
+ | `slots` | Required | @deepseek-ai/dsh-client-ui-renderer | Plugin stays pending; never applies. |
76
+
77
+ ### Handoff ring
78
+
79
+ A small ring beside the send button marks a session worth handing off: yellow at 70k prompt tokens, red at 100k. After 5 idle minutes the prompt cache is cold and the bars drop to 40k and 70k. Both bars are also capped at 60% and 80% of the model's context window. For ACP agent sessions, which never report usage to DSH, it reads the agent's context usage from `@zaimokuza/dsh-acp-adapter` once per finished turn. The adapter is an optional peer dependency: without it the ring only covers regular DSH sessions. Display only; run `/handoff` yourself. Thresholds live in `src/client/level.ts`.
80
+
75
81
  Code import (no mount): [`@lukstei/dsh-scratch-dir`](../dsh-scratch-dir/README.md) (`scratchDirectory`).
76
82
 
77
83
  Used by: nothing.
@@ -80,7 +86,7 @@ Used by: nothing.
80
86
 
81
87
  | Input | Brief describes | Brief lands in | Then |
82
88
  |---|---|---|---|
83
- | `/handoff` | this session | scratch directory of a newly created session | New session opens as a split pane. |
89
+ | `/handoff` | this session | scratch directory of a newly created session | New session opens as a split pane; the source is marked done in Kanban and its pane is closed. |
84
90
  | `/handoff <id-or-prefix>` | that session | `<cwd>/.agents/scratch/<current-session-id>/HANDOFF.md` | Current agent is told to read it. |
85
91
 
86
92
  Id resolution: exact id first, then unique prefix over `sessionQuery.listSessions()`. Unknown ids return an error listing the 5 most recent sessions; ambiguous prefixes list candidates. Passing the current session's id is an error. Any non-id text, including `launch`, is treated as an id. A session with no turns returns an error. All I/O failures return `{ kind: "error" }`.
@@ -90,10 +96,11 @@ Id resolution: exact id first, then unique prefix over `sessionQuery.listSession
90
96
  1. Renders this session's brief.
91
97
  2. Creates a session via `sessionController.create()` in the current workspace (falls back to `cwd` when the session has no workspace), same `agentPreset`.
92
98
  3. Replays the current model selection onto the new agent.
93
- 4. Titles it `<source title> - Handoff` (or `Handoff <first 8 id chars>` when untitled). A user title pins it against auto-generated titles.
99
+ 4. Titles it with the full source title (or `Handoff <first 8 id chars>` when untitled) and renames the source to `<title> (Resumed)` unless it already ends with that. A user title pins it against auto-generated titles. Adds a Kanban link `Resumed from <source id>` (`dsh://sessions/<id>`, opens the source session) to record the origin.
94
100
  5. Runs `/kanban {"action":"init","createdAt":…}` against the new agent so it appears on the Kanban board. No `prompt` is sent, since that would seed the composer draft with the follow-up text.
95
- 6. Writes `HANDOFF.md` into the new session's scratch directory and queues the read-the-brief follow-up.
96
- 7. Returns `Handoff launched: <id>`.
101
+ 6. Copies the source session's kanban links by replaying its `add-link` commands against the new agent.
102
+ 7. Writes `HANDOFF.md` into the new session's scratch directory and queues the read-the-brief follow-up.
103
+ 8. Returns `Handoff launched: <id>`.
97
104
 
98
105
  The client opens the pane. Without the client bundle the session is created but not opened.
99
106
 
@@ -127,7 +134,7 @@ Files:
127
134
  Details:
128
135
 
129
136
  - The command declares `input: { hint: "[session-id]" }`. Without a declared input the client sends the raw line to the model as a prompt and the handler never runs.
130
- - A slash command has no structured return channel to the client, so the Host encodes the new id in the command result text, which is persisted in the `command/done` event. The client subscribes to every open session's event source and calls `ctx.splitView.toggleSession()` when it sees a successful `command/done` starting with `Handoff launched: `.
137
+ - A slash command has no structured return channel to the client, so the Host encodes the new id in the command result text, which is persisted in the `command/done` event. The client subscribes to every open session's event source and calls `ctx.splitView.replaceSession()` when it sees a successful `command/done` starting with `Handoff launched: `, replacing the pane in-place atomically. It then sends `/kanban {"action":"done"}` to the source session, as the Kanban Done button does. A source never initialised in Kanban ignores the done action.
131
138
  - The pane is added through the split store, not `uiWorkspace.openSession()`. The split view patches that method into a read-only overlay without its own composer, so prompts would keep landing in the pane underneath.
132
139
  - The client reacts only to `append` changes. A `replace` replays the whole window on first open and after reconnect gaps and would reopen panes the user closed; the split view restores its panes from local storage.
133
140
  - Kanban membership is a session-log fact: the board lists only sessions whose `kanban` projection is initialized, which happens when `/kanban` runs in that session. Hence the explicit `init`.
package/dist/client.js CHANGED
@@ -4,6 +4,8 @@ window.__ModuleLoader__.load({
4
4
  var module = { exports: {} };
5
5
  var exports = module.exports;
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
8
+ let react = require("react");
7
9
  /**
8
10
  * The launched Session id carried by one durable event, or `undefined` when the
9
11
  * event is not a successful handoff launch.
@@ -15,8 +17,104 @@ window.__ModuleLoader__.load({
15
17
  if (typeof text !== "string" || !text.startsWith("Handoff launched: ")) return;
16
18
  return text.slice(18);
17
19
  }
20
+ // src/client/acp-usage.ts
21
+ let reader;
22
+ const listeners = /* @__PURE__ */ new Set();
23
+ function setAcpUsageReader(next) {
24
+ reader = next;
25
+ for (const listener of listeners) listener();
26
+ }
27
+ /** `useSyncExternalStore` seat, so a ring mounted before the adapter re-reads once it arrives. */
28
+ function subscribeAcpUsageReader(listener) {
29
+ listeners.add(listener);
30
+ return () => {
31
+ listeners.delete(listener);
32
+ };
33
+ }
34
+ function currentAcpUsageReader() {
35
+ return reader;
36
+ }
37
+ // src/client/level.ts
38
+ /** Anthropic prompt-cache TTL: past this idle gap the next turn re-writes the whole context. */
39
+ const CACHE_TTL_MS = 3e5;
40
+ const WARM = {
41
+ soft: 1e5,
42
+ strong: 15e4
43
+ };
44
+ const COLD = {
45
+ soft: 7e4,
46
+ strong: 1e5
47
+ };
48
+ const SOFT_WINDOW_SHARE = .6;
49
+ const STRONG_WINDOW_SHARE = .8;
50
+ function handoffLevel(pressureTokens, contextWindow, cold) {
51
+ if (pressureTokens === void 0) return "none";
52
+ const bar = cold ? COLD : WARM;
53
+ const soft = contextWindow === void 0 ? bar.soft : Math.min(bar.soft, SOFT_WINDOW_SHARE * contextWindow);
54
+ if (pressureTokens >= (contextWindow === void 0 ? bar.strong : Math.min(bar.strong, STRONG_WINDOW_SHARE * contextWindow))) return "strong";
55
+ return pressureTokens >= soft ? "soft" : "none";
56
+ }
57
+ // src/client/ring.ts
58
+ const COLOR = {
59
+ soft: "#d9a400",
60
+ strong: "#d62839"
61
+ };
62
+ /** Gauge icon beside the send button once the session is big enough that `/handoff` pays off. */
63
+ function HandoffRing({ sessionId, useProjection, useSession, onHandoff }) {
64
+ const pressure = useProjection("contextPressure");
65
+ const running = useSession((session) => session.running);
66
+ const [acp, setAcp] = (0, react.useState)(void 0);
67
+ const [cold, setCold] = (0, react.useState)(false);
68
+ const readUsage = (0, react.useSyncExternalStore)(subscribeAcpUsageReader, currentAcpUsageReader);
69
+ (0, react.useEffect)(() => {
70
+ if (running || readUsage === void 0) return;
71
+ let live = true;
72
+ readUsage(sessionId).then((usage) => {
73
+ if (live) setAcp(usage);
74
+ });
75
+ return () => {
76
+ live = false;
77
+ };
78
+ }, [
79
+ sessionId,
80
+ running,
81
+ readUsage
82
+ ]);
83
+ const tokens = pressure !== void 0 && pressure.pressureTokens !== void 0 ? pressure.pressureTokens : acp?.used;
84
+ const window = pressure !== void 0 && pressure.contextWindow !== void 0 ? pressure.contextWindow : acp?.size;
85
+ (0, react.useEffect)(() => {
86
+ setCold(false);
87
+ if (running) return;
88
+ const timer = setTimeout(() => setCold(true), CACHE_TTL_MS);
89
+ return () => clearTimeout(timer);
90
+ }, [tokens, running]);
91
+ const level = handoffLevel(tokens, window, cold);
92
+ if (level === "none" || tokens === void 0) return null;
93
+ const label = `Context ${Math.round(tokens / 1e3)}k tokens: ${cold ? "cache is cold, a fresh session is cheaper now" : "consider a fresh session"}. Click to hand off (/handoff)`;
94
+ return (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
95
+ label,
96
+ side: "top",
97
+ portal: true,
98
+ children: (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Button, {
99
+ variant: "ghost",
100
+ size: "sm",
101
+ "aria-label": label,
102
+ style: {
103
+ color: COLOR[level],
104
+ padding: 0,
105
+ width: 28
106
+ },
107
+ icon: (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.IconGaugeOutlineMedium, { size: 16 }),
108
+ onClick: () => void onHandoff(sessionId)
109
+ })
110
+ });
111
+ }
18
112
  // src/client/index.ts
19
- const inject = ["sessions", "splitView"];
113
+ const inject = [
114
+ "sessions",
115
+ "splitView",
116
+ "slots"
117
+ ];
20
118
  /**
21
119
  * Open every session the Host reports as launched as a pane of its own. A slash
22
120
  * command cannot reach the client, so the Host publishes the new id in the
@@ -31,6 +129,19 @@ window.__ModuleLoader__.load({
31
129
  function apply(ctx) {
32
130
  const sessions = ctx.sessions;
33
131
  const off = /* @__PURE__ */ new Map();
132
+ const markDone = async (id) => {
133
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
134
+ await reference.binding.session.command(`/kanban ${JSON.stringify({
135
+ action: "done",
136
+ doneAt: Date.now()
137
+ })}`);
138
+ });
139
+ };
140
+ const handoff = async (id) => {
141
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
142
+ await reference.binding.session.command("/handoff");
143
+ });
144
+ };
34
145
  const watch = (id) => {
35
146
  const binding = sessions.binding(id);
36
147
  if (binding === void 0) return;
@@ -41,7 +152,8 @@ window.__ModuleLoader__.load({
41
152
  if (entry.type !== "event") continue;
42
153
  const launched = launchedSessionId(entry.event);
43
154
  if (launched === void 0) continue;
44
- ctx.splitView.toggleSession(launched);
155
+ ctx.splitView.replaceSession(id, launched);
156
+ markDone(id);
45
157
  return;
46
158
  }
47
159
  });
@@ -58,6 +170,26 @@ window.__ModuleLoader__.load({
58
170
  off.delete(id);
59
171
  }
60
172
  };
173
+ ctx.effect(() => ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
174
+ name: "conversation.input.right",
175
+ id: "session-handoff.ring",
176
+ order: 1e3,
177
+ inject: () => ({ onHandoff: handoff })
178
+ }, HandoffRing)), "session-handoff: handoff ring");
179
+ ctx.inject(["remote", "remote.dshAcp"], (acpCtx) => {
180
+ const remote = acpCtx.remote.dshAcp;
181
+ const reader = async (id) => {
182
+ const result = await remote.agentSessionSnapshot(id);
183
+ if (!result.ok) {
184
+ console.warn("session-handoff: ACP usage unavailable", result);
185
+ return;
186
+ }
187
+ const usage = result.value.contextUsage;
188
+ return usage === null ? void 0 : usage;
189
+ };
190
+ setAcpUsageReader(reader);
191
+ return () => setAcpUsageReader(void 0);
192
+ });
61
193
  const dispose = sessions.list.subscribe(sync);
62
194
  sync();
63
195
  ctx.effect(() => () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lukstei/dsh-session-handoff",
3
- "version": "0.2.2-rc.5.3",
3
+ "version": "0.2.2-rc.5.5",
4
4
  "description": "Session handoff brief command for DSH",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -32,41 +32,65 @@
32
32
  "immediately": true,
33
33
  "inject": [
34
34
  "@deepseek-ai/dsh-api-session-controller",
35
- "@lukstei/dsh-client-split-view"
35
+ "@lukstei/dsh-client-split-view",
36
+ "@deepseek-ai/dsh-client-ui-conversation",
37
+ "@deepseek-ai/dsh-client-ui-renderer"
36
38
  ]
37
39
  }
38
40
  },
39
41
  "dependencies": {
40
- "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.3"
42
+ "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.5"
41
43
  },
42
44
  "peerDependencies": {
43
45
  "@deepseek-ai/cordis": "*",
44
46
  "@deepseek-ai/dsh-agent": "*",
45
47
  "@deepseek-ai/dsh-api-session-controller": "*",
48
+ "@deepseek-ai/dsh-client-ui-conversation": "*",
49
+ "@deepseek-ai/dsh-client-ui-primitives": "*",
50
+ "@deepseek-ai/dsh-client-ui-renderer": "*",
51
+ "@deepseek-ai/dsh-client-ui-session": "*",
52
+ "@deepseek-ai/dsh-client-ui-slots": "*",
46
53
  "@deepseek-ai/dsh-commands": "*",
47
54
  "@deepseek-ai/dsh-llm": "*",
48
55
  "@deepseek-ai/dsh-session": "*",
49
56
  "@deepseek-ai/dsh-session-query": "*",
50
57
  "@deepseek-ai/dsh-session-title": "*",
58
+ "@deepseek-ai/dsh-token-meter": "*",
51
59
  "@deepseek-ai/dsh-working-directory": "*",
52
- "@deepseek-ai/dsh-workspace": "*"
60
+ "@deepseek-ai/dsh-workspace": "*",
61
+ "@zaimokuza/dsh-acp-adapter": "*",
62
+ "react": "*"
53
63
  },
54
64
  "devDependencies": {
55
65
  "@deepseek-ai/cordis": "4.1.0",
56
66
  "@deepseek-ai/dsh-agent": "0.2.2-rc.5",
57
67
  "@deepseek-ai/dsh-api-session-controller": "0.2.2-rc.5",
68
+ "@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.5",
69
+ "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.5",
70
+ "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.5",
71
+ "@deepseek-ai/dsh-client-ui-session": "0.2.2-rc.5",
72
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.5",
58
73
  "@deepseek-ai/dsh-commands": "0.2.2-rc.5",
59
74
  "@deepseek-ai/dsh-llm": "0.2.2-rc.5",
60
75
  "@deepseek-ai/dsh-session": "0.2.2-rc.5",
61
76
  "@deepseek-ai/dsh-session-query": "0.2.2-rc.5",
62
77
  "@deepseek-ai/dsh-session-title": "0.2.2-rc.5",
78
+ "@deepseek-ai/dsh-token-meter": "0.2.2-rc.5",
63
79
  "@deepseek-ai/dsh-working-directory": "0.2.2-rc.5",
64
80
  "@deepseek-ai/dsh-workspace": "0.2.2-rc.5",
65
- "@lukstei/dsh-client-split-view": "0.2.2-rc.5.3",
81
+ "@lukstei/dsh-client-split-view": "0.2.2-rc.5.5",
66
82
  "@types/node": "^26.0.0",
83
+ "@types/react": "^19.3.0",
84
+ "@zaimokuza/dsh-acp-adapter": "0.2.2-rc.5.2",
85
+ "react": "^19.3.1",
67
86
  "tsdown": "^0.23.0",
68
87
  "typescript": "^7.0.2"
69
88
  },
89
+ "peerDependenciesMeta": {
90
+ "@zaimokuza/dsh-acp-adapter": {
91
+ "optional": true
92
+ }
93
+ },
70
94
  "license": "MIT",
71
95
  "repository": {
72
96
  "type": "git",
@@ -0,0 +1,31 @@
1
+ /** Context occupancy an ACP agent reported, as the adapter exposes it. */
2
+ export interface AcpUsage {
3
+ readonly used: number;
4
+ readonly size: number;
5
+ }
6
+
7
+ export type AcpUsageReader = (
8
+ sessionId: string,
9
+ ) => Promise<AcpUsage | undefined>;
10
+
11
+ // smell: module-level seat; the optional ACP scope in `index.ts` fills it, so the ring needs no
12
+ // hard dependency on the adapter.
13
+ let reader: AcpUsageReader | undefined;
14
+ const listeners = new Set<() => void>();
15
+
16
+ export function setAcpUsageReader(next: AcpUsageReader | undefined): void {
17
+ reader = next;
18
+ for (const listener of listeners) listener();
19
+ }
20
+
21
+ /** `useSyncExternalStore` seat, so a ring mounted before the adapter re-reads once it arrives. */
22
+ export function subscribeAcpUsageReader(listener: () => void): () => void {
23
+ listeners.add(listener);
24
+ return () => {
25
+ listeners.delete(listener);
26
+ };
27
+ }
28
+
29
+ export function currentAcpUsageReader(): AcpUsageReader | undefined {
30
+ return reader;
31
+ }
@@ -1,10 +1,15 @@
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-conversation/client";
4
+ import type {} from "@deepseek-ai/dsh-client-ui-renderer/client";
3
5
  import type { SessionId } from "@deepseek-ai/dsh-session/types";
4
6
  import type {} from "@lukstei/dsh-client-split-view/client-contract";
7
+ import type {} from "@zaimokuza/dsh-acp-adapter/remote";
5
8
  import { launchedSessionId } from "../launch.ts";
9
+ import { type AcpUsageReader, setAcpUsageReader } from "./acp-usage.ts";
10
+ import { HandoffRing } from "./ring.ts";
6
11
 
7
- export const inject = ["sessions", "splitView"];
12
+ export const inject = ["sessions", "splitView", "slots"];
8
13
 
9
14
  /**
10
15
  * Open every session the Host reports as launched as a pane of its own. A slash
@@ -23,6 +28,22 @@ export function apply(ctx: Context): void {
23
28
  const sessions = ctx.sessions as unknown as ISessions;
24
29
  const off = new Map<SessionId, () => void>();
25
30
 
31
+ // Same effect as the Kanban Done button: record done.
32
+ const markDone = async (id: SessionId): Promise<void> => {
33
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
34
+ await reference.binding.session.command(
35
+ `/kanban ${JSON.stringify({ action: "done", doneAt: Date.now() })}`,
36
+ );
37
+ });
38
+ };
39
+
40
+ // Same command the user would type; sent directly so the composer draft stays untouched.
41
+ const handoff = async (id: SessionId): Promise<void> => {
42
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
43
+ await reference.binding.session.command("/handoff");
44
+ });
45
+ };
46
+
26
47
  const watch = (id: SessionId): void => {
27
48
  const binding = sessions.binding(id);
28
49
  if (binding === undefined) return;
@@ -36,7 +57,8 @@ export function apply(ctx: Context): void {
36
57
  if (entry.type !== "event") continue;
37
58
  const launched = launchedSessionId(entry.event);
38
59
  if (launched === undefined) continue;
39
- ctx.splitView.toggleSession(launched);
60
+ ctx.splitView.replaceSession(id, launched);
61
+ void markDone(id);
40
62
  return;
41
63
  }
42
64
  });
@@ -55,6 +77,40 @@ export function apply(ctx: Context): void {
55
77
  }
56
78
  };
57
79
 
80
+ ctx.effect(
81
+ () =>
82
+ ctx.slots.inject("conversation.input.right", () =>
83
+ ctx.slots.register(
84
+ {
85
+ name: "conversation.input.right",
86
+ id: "session-handoff.ring",
87
+ order: 1000,
88
+ inject: () => ({ onHandoff: handoff }),
89
+ },
90
+ HandoffRing,
91
+ ),
92
+ ),
93
+ "session-handoff: handoff ring",
94
+ );
95
+
96
+ // Optional: the ACP adapter's remote exists only while that plugin is mounted. Outside this
97
+ // scope the reader stays unset and the ring falls back to the DSH `contextPressure`.
98
+ // `remote` is requested alongside, as the adapter's own client does for its namespace.
99
+ ctx.inject(["remote", "remote.dshAcp"], (acpCtx) => {
100
+ const remote = acpCtx.remote.dshAcp;
101
+ const reader: AcpUsageReader = async (id) => {
102
+ const result = await remote.agentSessionSnapshot(id);
103
+ if (!result.ok) {
104
+ console.warn("session-handoff: ACP usage unavailable", result);
105
+ return undefined;
106
+ }
107
+ const usage = result.value.contextUsage;
108
+ return usage === null ? undefined : usage;
109
+ };
110
+ setAcpUsageReader(reader);
111
+ return () => setAcpUsageReader(undefined);
112
+ });
113
+
58
114
  const dispose = sessions.list.subscribe(sync);
59
115
  sync();
60
116
  ctx.effect(
@@ -0,0 +1,31 @@
1
+ export type HandoffLevel = "none" | "soft" | "strong";
2
+
3
+ /** Anthropic prompt-cache TTL: past this idle gap the next turn re-writes the whole context. */
4
+ export const CACHE_TTL_MS = 5 * 60_000;
5
+
6
+ // Absolute prompt sizes, tuned by cost: a fresh session starts near 18k tokens, so a handoff
7
+ // pays back sooner the more context a turn re-sends. A cold cache lowers both bars.
8
+ const WARM = { soft: 100_000, strong: 150_000 };
9
+ const COLD = { soft: 70_000, strong: 100_000 };
10
+ // The window still caps the bars, so small-window models warn before compaction does.
11
+ const SOFT_WINDOW_SHARE = 0.6;
12
+ const STRONG_WINDOW_SHARE = 0.8;
13
+
14
+ export function handoffLevel(
15
+ pressureTokens: number | undefined,
16
+ contextWindow: number | undefined,
17
+ cold: boolean,
18
+ ): HandoffLevel {
19
+ if (pressureTokens === undefined) return "none";
20
+ const bar = cold ? COLD : WARM;
21
+ const soft =
22
+ contextWindow === undefined
23
+ ? bar.soft
24
+ : Math.min(bar.soft, SOFT_WINDOW_SHARE * contextWindow);
25
+ const strong =
26
+ contextWindow === undefined
27
+ ? bar.strong
28
+ : Math.min(bar.strong, STRONG_WINDOW_SHARE * contextWindow);
29
+ if (pressureTokens >= strong) return "strong";
30
+ return pressureTokens >= soft ? "soft" : "none";
31
+ }
@@ -0,0 +1,96 @@
1
+ import {
2
+ Button,
3
+ IconGaugeOutlineMedium,
4
+ Tooltip,
5
+ } from "@deepseek-ai/dsh-client-ui-primitives";
6
+ import type {} from "@deepseek-ai/dsh-client-ui-session/client";
7
+ import type { SessionStandardProps } from "@deepseek-ai/dsh-client-ui-slots";
8
+ import type {} from "@deepseek-ai/dsh-token-meter/client";
9
+ import {
10
+ createElement,
11
+ useEffect,
12
+ useState,
13
+ useSyncExternalStore,
14
+ } from "react";
15
+ import {
16
+ type AcpUsage,
17
+ currentAcpUsageReader,
18
+ subscribeAcpUsageReader,
19
+ } from "./acp-usage.ts";
20
+ import { CACHE_TTL_MS, handoffLevel } from "./level.ts";
21
+
22
+ const COLOR = { soft: "#d9a400", strong: "#d62839" } as const;
23
+
24
+ /** Gauge icon beside the send button once the session is big enough that `/handoff` pays off. */
25
+ export function HandoffRing({
26
+ sessionId,
27
+ useProjection,
28
+ useSession,
29
+ onHandoff,
30
+ }: Pick<SessionStandardProps, "sessionId" | "useProjection" | "useSession"> & {
31
+ onHandoff: (sessionId: SessionStandardProps["sessionId"]) => Promise<void>;
32
+ }) {
33
+ const pressure = useProjection("contextPressure");
34
+ const running = useSession((session) => session.running);
35
+ const [acp, setAcp] = useState<AcpUsage | undefined>(undefined);
36
+ const [cold, setCold] = useState(false);
37
+
38
+ // ACP agents report occupancy to the adapter, never to DSH's `contextPressure`; read it
39
+ // when a turn settles. The reader is unset (so this is a no-op) without the adapter.
40
+ const readUsage = useSyncExternalStore(
41
+ subscribeAcpUsageReader,
42
+ currentAcpUsageReader,
43
+ );
44
+ useEffect(() => {
45
+ if (running || readUsage === undefined) return;
46
+ let live = true;
47
+ void readUsage(sessionId).then((usage) => {
48
+ if (live) setAcp(usage);
49
+ });
50
+ return () => {
51
+ live = false;
52
+ };
53
+ }, [sessionId, running, readUsage]);
54
+
55
+ const tokens =
56
+ pressure !== undefined && pressure.pressureTokens !== undefined
57
+ ? pressure.pressureTokens
58
+ : acp?.used;
59
+ const window =
60
+ pressure !== undefined && pressure.contextWindow !== undefined
61
+ ? pressure.contextWindow
62
+ : acp?.size;
63
+
64
+ // A new usage sample or a running turn means the cache was just touched; once idle for
65
+ // the TTL it is cold. Mount counts as warm because the last request time is unknown.
66
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `tokens` is the restart trigger
67
+ useEffect(() => {
68
+ setCold(false);
69
+ if (running) return;
70
+ const timer = setTimeout(() => setCold(true), CACHE_TTL_MS);
71
+ return () => clearTimeout(timer);
72
+ }, [tokens, running]);
73
+
74
+ const level = handoffLevel(tokens, window, cold);
75
+ if (level === "none" || tokens === undefined) return null;
76
+ const k = Math.round(tokens / 1000);
77
+ const hint = cold
78
+ ? "cache is cold, a fresh session is cheaper now"
79
+ : "consider a fresh session";
80
+ const label = `Context ${k}k tokens: ${hint}. Click to hand off (/handoff)`;
81
+ return createElement(Tooltip, {
82
+ label,
83
+ side: "top",
84
+ portal: true,
85
+ // biome-ignore lint/correctness/noChildrenProp: Tooltip types `children` as a required prop, which createElement's 3rd argument does not satisfy
86
+ children: createElement(Button, {
87
+ variant: "ghost",
88
+ size: "sm",
89
+ "aria-label": label,
90
+ // the icon strokes with currentColor; 28px square instead of the text-button padding
91
+ style: { color: COLOR[level], padding: 0, width: 28 },
92
+ icon: createElement(IconGaugeOutlineMedium, { size: 16 }),
93
+ onClick: () => void onHandoff(sessionId),
94
+ }),
95
+ });
96
+ }
package/src/index.ts CHANGED
@@ -10,7 +10,10 @@ import type {
10
10
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
11
11
  import type {} from "@deepseek-ai/dsh-session";
12
12
  import type { SessionId } from "@deepseek-ai/dsh-session/types";
13
- import type { SessionRecord } from "@deepseek-ai/dsh-session-query";
13
+ import type {
14
+ SessionLogSnapshot,
15
+ SessionRecord,
16
+ } from "@deepseek-ai/dsh-session-query";
14
17
  import type {} from "@deepseek-ai/dsh-session-title";
15
18
  import type {} from "@deepseek-ai/dsh-working-directory";
16
19
  import type { Workspace } from "@deepseek-ai/dsh-workspace";
@@ -31,6 +34,7 @@ export const inject = [
31
34
  const HANDOFF_FILE = "HANDOFF.md";
32
35
  const RECENT_LIMIT = 5;
33
36
  const SHORT_ID_LENGTH = 8;
37
+ const RESUMED_SUFFIX = " (Resumed)";
34
38
 
35
39
  export function apply(ctx: Context): void {
36
40
  ctx.commands.register({
@@ -116,6 +120,7 @@ async function handoff(
116
120
  agent,
117
121
  targetId,
118
122
  rendered.markdown,
123
+ snapshot,
119
124
  invocation.signal,
120
125
  );
121
126
  return {
@@ -188,6 +193,28 @@ function workspaceOf(
188
193
  return undefined;
189
194
  }
190
195
 
196
+ function kanbanLinkArgs(snapshot: SessionLogSnapshot): string[] {
197
+ const all: string[] = [];
198
+ for (const event of snapshot.events) {
199
+ if (event.type !== "command/run" || event.data.name !== "kanban") continue;
200
+ const args = event.data.args;
201
+ if (args === undefined) continue;
202
+ try {
203
+ const parsed: unknown = JSON.parse(args);
204
+ if (
205
+ typeof parsed === "object" &&
206
+ parsed !== null &&
207
+ "action" in parsed &&
208
+ parsed.action === "add-link"
209
+ )
210
+ all.push(args);
211
+ } catch {
212
+ // edge case: non-JSON kanban args carry no link
213
+ }
214
+ }
215
+ return all;
216
+ }
217
+
191
218
  function shortId(id: string): string {
192
219
  return id.slice(0, SHORT_ID_LENGTH);
193
220
  }
@@ -200,6 +227,7 @@ function shortId(id: string): string {
200
227
  * @param source - Session the command runs in.
201
228
  * @param targetId - Durable id of the handed-off session.
202
229
  * @param markdown - Rendered brief.
230
+ * @param snapshot - Source session log, the origin of the kanban links to copy.
203
231
  * @param signal - Cancellation signal of the invoking command.
204
232
  * @returns the created session identity.
205
233
  */
@@ -208,6 +236,7 @@ async function createBeside(
208
236
  source: Agent,
209
237
  targetId: string,
210
238
  markdown: string,
239
+ snapshot: SessionLogSnapshot,
211
240
  signal: AbortSignal,
212
241
  ): Promise<SessionCreateValue> {
213
242
  const selection = source.model.current();
@@ -236,8 +265,17 @@ async function createBeside(
236
265
  agent.session,
237
266
  sourceTitle === undefined
238
267
  ? `Handoff ${shortId(targetId)}`
239
- : `${sourceTitle.title} - Handoff`,
268
+ : sourceTitle.title,
240
269
  );
270
+ if (
271
+ sourceTitle !== undefined &&
272
+ !sourceTitle.title.endsWith(RESUMED_SUFFIX)
273
+ ) {
274
+ ctx.sessionTitle.rename(
275
+ source.session,
276
+ `${sourceTitle.title}${RESUMED_SUFFIX}`,
277
+ );
278
+ }
241
279
 
242
280
  // edge case: a session the controller creates carries no kanban marker, so the
243
281
  // board would never list it; this is the init kanban's own client sends.
@@ -248,6 +286,25 @@ async function createBeside(
248
286
  signal,
249
287
  );
250
288
 
289
+ // Replaying the source's add-link commands in order reproduces its link set,
290
+ // since the kanban fold dedupes by url.
291
+ for (const args of kanbanLinkArgs(snapshot)) {
292
+ await ctx.commands.execute(agent, `/kanban ${args}`, [], signal);
293
+ }
294
+
295
+ const sourceLink = {
296
+ action: "add-link",
297
+ label: `Resumed from ${targetId}`,
298
+ url: `dsh://sessions/${targetId}`,
299
+ priority: 0,
300
+ };
301
+ await ctx.commands.execute(
302
+ agent,
303
+ `/kanban ${JSON.stringify(sourceLink)}`,
304
+ [],
305
+ signal,
306
+ );
307
+
251
308
  await deliver(ctx, agent, targetId, markdown);
252
309
  return created;
253
310
  }