@k-electron/k-bench 0.4.0 → 0.5.0

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  Persistent terminal Sessions on your Mac, organised into Workspaces, reachable from any browser on your tailnet. It launches Claude Code, and resumes it when you restart.
4
4
 
5
- ![Claude Code running in a k-bench Session, with the Workspaces and Sessions in the sidebar](docs/images/hero.png)
5
+ ![Claude Code running in a Workspace's Prime, with the sidebar listing the Workspaces and the Open Workspace's Sessions](docs/images/hero.png)
6
6
 
7
7
  k-bench is macOS-only, and Tailscale is the only way in. It runs on your Mac as a background service and shows your terminals in a web page that only your own tailnet login can open.
8
8
 
@@ -19,43 +19,32 @@ It is not only for Claude Code. **New shell** gives you a plain shell Session, s
19
19
 
20
20
  ## What you get
21
21
 
22
- - **Sessions that keep running** when you close the tab, lock your phone or lose your connection. Come back from any device and pick up where you left off.
23
- - **Claude Sessions.** Pick **New Claude…** from a Workspace's **+**, choose the model, effort, advisor and Focus view (a condensed view that suits a phone), and k-bench launches Claude Code for you. Restart a Stopped Claude Session, even after a reboot, and the conversation you were last in resumes, even after a `/clear`.
24
- - **Workspaces per project.** A Workspace points at a project folder on your Mac, and its Sessions start there.
25
- - **Two Panes** side by side for the Workspace you're in: its Prime on the left, and its Worker, or a dev server, on the right.
26
- - **Bells.** When a Session rings the terminal bell, its row in the sidebar shows a Bell until you look at it.
27
- - **A phone layout** with a drawer for your Workspaces and a row of extra keys (Esc, Tab, Shift-Tab, Ctrl, the arrows and Enter) for the keys a phone keyboard lacks.
22
+ - **Sessions that keep running** when you close the browser tab, lock your phone or lose your connection. Come back from any Device and pick up where you left off.
23
+ - **A Workspace per project.** A Workspace points at a project folder on your Mac, and its Sessions start there.
24
+ - **A Prime and a Worker in every Workspace.** Two Claude Sessions that k-bench launches with fixed Launch options: the Prime plans in the left Pane, and the Worker builds in the right one. Opening the Workspace starts them, and a restart resumes each one's Claude conversation, even after a reboot or a `/clear`.
25
+ - **The Open Workspace follows you between Devices.** Open a Workspace on your laptop, and your phone shows it too.
26
+ - **Other Sessions in the right Pane's Tabs.** **New shell** for a dev server or a test watcher, or **New Claude…** to launch Claude Code with the model, effort, advisor and Focus view you choose.
27
+ - **Room when you need it.** Drag the divider to an edge to shut a Pane, and give the other one the whole width.
28
+ - **Bells.** When a Session rings the terminal bell, the sidebar marks it until you look at it.
29
+ - **A Phone layout** with a drawer for your Workspaces and Extra keys (Esc, Tab, Shift-Tab, Ctrl, the arrows and Enter) for the keys a phone keyboard lacks.
28
30
  - **Access only for your tailnet login.** k-bench listens on localhost only and is published with `tailscale serve`. It admits only requests that carry your own tailnet login.
29
31
 
30
- ![Two Panes side by side on a desktop: a shell and a dev server](docs/images/desktop.png)
32
+ ![The Prime in the left Pane, and a dev server in the right Pane, whose Tabs show the Worker and the dev server](docs/images/desktop.png)
31
33
 
32
34
  ## Quick start
33
35
 
34
- **You need:**
35
-
36
- - A Mac (k-bench is macOS-only).
37
- - [Node](https://nodejs.org/) 26 or later.
38
- - tmux (`brew install tmux`).
39
- - [Tailscale](https://tailscale.com/download), signed in, with HTTPS certificates turned on for your tailnet. [Setup](docs/guide/setup.md#1-set-up-tailscale) has the steps.
40
-
41
- **Then:**
36
+ First get what [Setup](docs/guide/setup.md) says you need, and [set up Tailscale](docs/guide/setup.md#1-set-up-tailscale). Then:
42
37
 
43
38
  ```sh
44
39
  npm i -g @k-electron/k-bench
45
40
  k-bench install
46
41
  ```
47
42
 
48
- `k-bench install` finds your tailnet login by itself, starts k-bench as a background service that starts when you log in, publishes it with `tailscale serve`, and prints the URL it is now reachable at. Open that URL from any device signed in to your tailnet with the same login. To see what the install would do first, run `k-bench install --dry-run`: it changes nothing.
49
-
50
- Something not working? Run `k-bench status`: it checks each part and says how to fix what fails.
43
+ `k-bench install` publishes k-bench on your tailnet and prints its URL. Open that URL from any device signed in to your tailnet with the same login. [Setup](docs/guide/setup.md) covers the install, updating and uninstalling. If something isn't working, run `k-bench status`.
51
44
 
52
45
  ## Guide
53
46
 
54
- - [The guide](docs/guide/README.md), with
55
- - [Setup](docs/guide/setup.md): Tailscale, installing, updating, uninstalling.
56
- - [Using k-bench](docs/guide/using-k-bench.md): Workspaces, Sessions, Claude Sessions, Panes, Bells, scrolling and copying, the phone layout.
57
- - [Using k-bench with Claude Code](docs/guide/claude-code.md): Claude Sessions and the New Claude dialog, Focus view, resuming on restart, making Claude Code ring the Bell, and working with several conversations.
58
- - [Troubleshooting](docs/guide/troubleshooting.md): start from `k-bench status`.
47
+ - [The guide](docs/guide/README.md): setup, using k-bench, using it with Claude Code, and troubleshooting.
59
48
  - [CHANGELOG](CHANGELOG.md): what changed in each version.
60
49
 
61
50
  ## Security
@@ -20,10 +20,34 @@ export class Attachments {
20
20
  constructor(tmux, sessions) {
21
21
  /** Per Session, the terminal the window was last sized for (see `writeSizedToTyper`). */
22
22
  const lastTyper = new Map();
23
+ /**
24
+ * Per Session with an `endWaiting` under way, whether another key came meanwhile. A run
25
+ * of keys asks tmux one at a time, and once more after the last, so no key is dropped.
26
+ */
27
+ const endingWaiting = new Map();
28
+ const endWaiting = (sessionId) => {
29
+ endingWaiting.set(sessionId, false);
30
+ // A Session that went away has no state to end; its tmux client's exit reports it.
31
+ void tmux
32
+ .endWaiting(sessionId)
33
+ .catch(() => { })
34
+ .finally(() => {
35
+ const again = endingWaiting.get(sessionId);
36
+ endingWaiting.delete(sessionId);
37
+ if (again)
38
+ endWaiting(sessionId);
39
+ });
40
+ };
23
41
  this.context = {
24
42
  tmux,
25
43
  sessions,
26
44
  lastTyper,
45
+ ownerTyped: (sessionId) => {
46
+ if (endingWaiting.has(sessionId))
47
+ endingWaiting.set(sessionId, true);
48
+ else
49
+ endWaiting(sessionId);
50
+ },
27
51
  forget: (terminal) => {
28
52
  this.terminals.delete(terminal);
29
53
  if (lastTyper.get(terminal.sessionId) === terminal) {
@@ -145,6 +169,8 @@ class Terminal {
145
169
  if (this.phase === "looking-up")
146
170
  this.pendingInput.push({ data, automatic });
147
171
  else if (this.phase === "attached") {
172
+ if (!automatic && !isOnlyMouseReports(data))
173
+ this.context.ownerTyped(this.sessionId);
148
174
  const write = automatic
149
175
  ? () => this.write(data)
150
176
  : () => this.writeSizedToTyper(data);
@@ -258,6 +284,18 @@ class Terminal {
258
284
  }
259
285
  }
260
286
  }
287
+ /**
288
+ * Whether `data` is nothing but mouse reports: what xterm.js sends for a click, a drag or the
289
+ * wheel once tmux asks for the mouse, as SGR (`ESC[<b;x;yM`) or legacy (`ESC[M` and three
290
+ * bytes, none of them ESC). Scrolling or clicking is not the owner answering a Session, so
291
+ * it doesn't end Waiting.
292
+ */
293
+ function isOnlyMouseReports(data) {
294
+ const [before, ...reports] = data.split("\x1b");
295
+ return (before === "" &&
296
+ reports.length > 0 &&
297
+ reports.every((report) => /^\[<\d+;\d+;\d+[Mm]$/.test(report) || /^\[M.{3}$/su.test(report)));
298
+ }
261
299
  /** Whether `promise` settles within `ms`. */
262
300
  async function settlesWithin(promise, ms) {
263
301
  let timer;
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Launching Claude Code for a Claude Session (ADR-0005). k-bench starts it through its
3
- * documented command-line flags and learns which conversation it is on through a silent
4
- * `SessionStart` hook, so everything k-bench knows about Claude Code is in this file: the
5
- * flags it passes, the hook, and the launcher script that runs it.
3
+ * documented command-line flags and learns which conversation it is on, and whether it is
4
+ * Working, Waiting or Idle, through silent hooks, so everything k-bench knows about Claude Code is in
5
+ * this file: the flags it passes, the hooks, and the launcher script that runs it.
6
6
  */
7
7
  import { DEFAULT_LAUNCH_OPTIONS, LAUNCH_CHOICES, } from "../shared/launch-options.js";
8
8
  /**
@@ -63,16 +63,121 @@ const CONVERSATION_HOOK = [
63
63
  "} >/dev/null 2>&1; exit 0",
64
64
  ].join(" ");
65
65
  /**
66
- * The `--settings` every launch passes: the conversation hook and, with Focus view on, its
67
- * keys. Focus view needs both keys: it does nothing without the fullscreen renderer, and
66
+ * The tmux pane user option the activity hooks write a Claude Session's state to (a
67
+ * `SessionActivity`), on the pane Claude Code runs in, and the tmux `wait-for` channel they
68
+ * signal after, so the state feed re-reads at once (see `TmuxDriver`). It is empty until a
69
+ * hook has run, which reads as Idle.
70
+ */
71
+ export const ACTIVITY_OPTION = "@kb-activity";
72
+ export const ACTIVITY_CHANNEL = "kb-activity-changed";
73
+ /**
74
+ * The pane option every write of `ACTIVITY_OPTION` stamps with the time, in epoch seconds, so
75
+ * a state written moments ago is never taken for a quiet one (see `TmuxDriver.decayWorking`).
76
+ */
77
+ export const ACTIVITY_AT_OPTION = "@kb-activity-at";
78
+ /**
79
+ * Matches the stdin of an event fired inside a subagent (or a teammate), which carries an
80
+ * `agent_id` key. It can't match inside a value, such as a prompt, since JSON escapes a `"`
81
+ * there. A subagent's turn, its tools and its finish say nothing about the Session's own
82
+ * turn, so most activity hooks ignore such events (see `ACTIVITY_EVENTS`). The hooks
83
+ * reference documents `agent_id` as the subagent's or teammate's ID; the main agent started
84
+ * with `--agent` carries only `agent_type`, so that is never tested.
85
+ */
86
+ const FROM_AN_AGENT = '"agent_id"[[:space:]]*:';
87
+ /**
88
+ * The hook that records `activity`, and the time, on its own tmux pane in one tmux call, and
89
+ * signals the channel, unless its stdin matches one of `ignore` (extended regexes). It is
90
+ * built like the conversation hook, for the same reasons: it prints nothing, exits 0
91
+ * whatever happens, and is one line of plain `sh` with no `jq`. The state it writes is
92
+ * k-bench's own word, never taken from stdin.
93
+ */
94
+ function activityHook(activity, ignore) {
95
+ // With nothing to ignore there is no test at all: an empty pattern would match anything.
96
+ const skip = ignore.length
97
+ ? `printf '%s' "$input" | grep -Eq '${ignore.join("|")}'`
98
+ : "false";
99
+ return [
100
+ "{",
101
+ // Read whole either way, so Claude Code never writes to a hook that has gone.
102
+ "input=$(tr -d '\\n');",
103
+ `if ${skip}; then :;`,
104
+ 'elif [ -n "$TMUX_PANE" ]; then',
105
+ // Stamped first, so a decay never sees the new state with the old time.
106
+ `tmux set-option -p -t "$TMUX_PANE" ${ACTIVITY_AT_OPTION} "$(date +%s)"`,
107
+ `\\; set-option -p -t "$TMUX_PANE" ${ACTIVITY_OPTION} ${activity} &&`,
108
+ `tmux wait-for -S ${ACTIVITY_CHANNEL};`,
109
+ "fi;",
110
+ "} >/dev/null 2>&1; exit 0",
111
+ ].join(" ");
112
+ }
113
+ /**
114
+ * Which Claude Code hook events set which state (see Working, Waiting and Idle in the
115
+ * glossary):
116
+ * - `SessionStart`: a new or restarted Claude Session, or a new conversation in one, starts
117
+ * Idle. Not on compaction, which can happen mid-turn and keeps the turn going.
118
+ * - `UserPromptSubmit`: a turn starts, so Working.
119
+ * - `PermissionRequest` (a permission prompt), `PreToolUse` for `AskUserQuestion` (a
120
+ * question) and `ExitPlanMode` (a plan to approve), and `Elicitation` (an MCP server's
121
+ * question): Claude Code stops mid-turn for the owner, so Waiting. `PermissionRequest` fires
122
+ * as the prompt shows; the `Notification` for it waits about six seconds, so it isn't used.
123
+ * The hooks reference doesn't say whether approving a plan is a permission prompt, so
124
+ * `ExitPlanMode` is matched as well; if it is, the two agree.
125
+ * - `PostToolUse`, `PostToolUseFailure` and `ElicitationResult`: the owner answered, or a
126
+ * tool finished, so Working. No hook fires when the owner denies a tool, so the owner's
127
+ * own key ends Waiting too (see `TmuxDriver.endWaiting`).
128
+ * - `Stop`, and `StopFailure` (fired instead when an API error ends the turn): the turn is
129
+ * over, so Idle. Neither fires for a subagent.
130
+ * `matcher` is the hook group's tool name matcher, for a tool event. Each hook ignores an
131
+ * event from a subagent (`FROM_AN_AGENT`), except a `PermissionRequest` or `Elicitation`
132
+ * (`anyAgent`): a prompt needs the owner whoever asked. A subagent's Waiting then ends as any
133
+ * other does, by the owner's key or the main agent's next event.
134
+ */
135
+ const ACTIVITY_EVENTS = [
136
+ {
137
+ event: "SessionStart",
138
+ activity: "idle",
139
+ ignore: '"source"[[:space:]]*:[[:space:]]*"compact"',
140
+ },
141
+ { event: "UserPromptSubmit", activity: "working" },
142
+ { event: "PermissionRequest", activity: "waiting", anyAgent: true },
143
+ { event: "PreToolUse", activity: "waiting", matcher: "AskUserQuestion|ExitPlanMode" },
144
+ { event: "Elicitation", activity: "waiting", anyAgent: true },
145
+ { event: "PostToolUse", activity: "working" },
146
+ { event: "PostToolUseFailure", activity: "working" },
147
+ { event: "ElicitationResult", activity: "working" },
148
+ { event: "Stop", activity: "idle" },
149
+ { event: "StopFailure", activity: "idle" },
150
+ ];
151
+ /** Every hook k-bench passes, by Claude Code hook event: the conversation's, then the states'. */
152
+ function launchHooks() {
153
+ const hooks = {
154
+ SessionStart: [{ hooks: [{ type: "command", command: CONVERSATION_HOOK }] }],
155
+ };
156
+ for (const { event, activity, matcher, ignore, anyAgent } of ACTIVITY_EVENTS) {
157
+ const ignored = [...(anyAgent ? [] : [FROM_AN_AGENT]), ...(ignore ? [ignore] : [])];
158
+ hooks[event] = [
159
+ ...(hooks[event] ?? []),
160
+ {
161
+ ...(matcher ? { matcher } : {}),
162
+ hooks: [{ type: "command", command: activityHook(activity, ignored) }],
163
+ },
164
+ ];
165
+ }
166
+ return hooks;
167
+ }
168
+ /**
169
+ * The `--settings` every launch passes: k-bench's hooks, Claude Code's `dark` theme and, with
170
+ * Focus view on, its keys. The theme is fixed, not a Launch option: the owner's own theme may
171
+ * be `light`, which colours some text near-black, unreadable on k-bench's dark terminal.
172
+ * Focus view needs both keys: it does nothing without the fullscreen renderer, and
68
173
  * fullscreen is not the default on every machine. `--settings` applies to that launch only
69
- * and adds to the owner's own settings and hooks, leaving their files unchanged.
174
+ * and adds to the owner's own settings and hooks, or outranks them, leaving their files
175
+ * unchanged.
70
176
  */
71
177
  function launchSettings(focusView) {
72
178
  return JSON.stringify({
73
- hooks: {
74
- SessionStart: [{ hooks: [{ type: "command", command: CONVERSATION_HOOK }] }],
75
- },
179
+ hooks: launchHooks(),
180
+ theme: "dark",
76
181
  ...(focusView ? { viewMode: "focus", tui: "fullscreen" } : {}),
77
182
  });
78
183
  }
@@ -80,7 +185,7 @@ function launchSettings(focusView) {
80
185
  * The flags that follow the one naming the conversation. This is where Launch options become
81
186
  * flags: a Default option adds nothing. Advisor Off is not a flag (there is none): the
82
187
  * launcher sets `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1` for it. `--settings` is always passed,
83
- * for the conversation hook.
188
+ * for k-bench's hooks and the dark theme.
84
189
  */
85
190
  function launchOptionArguments(options) {
86
191
  const { model, effort, advisor, focusView } = options;
@@ -39,5 +39,6 @@ export function resolveConfig(env = process.env) {
39
39
  allowedLogin: env.K_BENCH_ALLOWED_LOGIN ?? "",
40
40
  pickerRoot: resolve(env.K_BENCH_PICKER_ROOT ?? homedir()),
41
41
  claudeProgram: "claude",
42
+ workingQuietMs: 15_000,
42
43
  };
43
44
  }
@@ -12,7 +12,7 @@ import { TmuxDriver } from "./tmux.js";
12
12
  export async function startServer(config, options = {}) {
13
13
  const store = new Store(config.dataDir);
14
14
  const tmux = new TmuxDriver(config.tmuxSocket, config.claudeProgram);
15
- const service = new Service(store, tmux);
15
+ const service = new Service(store, tmux, { workingQuietMs: config.workingQuietMs });
16
16
  // Anything on the socket that the store does not know is left over: clean it up first.
17
17
  await service.reconcile();
18
18
  // A tmux server that outlived the previous k-bench gets this version's hooks.
@@ -24,6 +24,7 @@ export async function startServer(config, options = {}) {
24
24
  });
25
25
  const events = new EventSockets(feed);
26
26
  const bells = tmux.watchBells(() => feed.notify());
27
+ const activity = tmux.watchActivity(() => feed.notify());
27
28
  // A Claude Session's new conversation is stored at once, whether or not anyone is viewing
28
29
  // it. One reconcile at a time; stopping waits for the last before the database closes.
29
30
  let following = Promise.resolve();
@@ -75,6 +76,7 @@ export async function startServer(config, options = {}) {
75
76
  const stop = () => {
76
77
  stopping ??= (async () => {
77
78
  await bells.stop();
79
+ await activity.stop();
78
80
  await conversations.stop();
79
81
  await following;
80
82
  events.closeAll();
@@ -5,6 +5,7 @@ import { DEFAULT_LAUNCH_OPTIONS, ROLE_LAUNCH_OPTIONS, } from "../shared/launch-o
5
5
  import { sessionsByRole } from "../shared/session-roles.js";
6
6
  import { availableName } from "./naming.js";
7
7
  import { Reconciler } from "./reconciler.js";
8
+ import { nowInSeconds } from "./tmux.js";
8
9
  /**
9
10
  * A failure the HTTP layer maps to a status code. `details` go into the response body
10
11
  * next to the message, for a client that acts on the refusal.
@@ -31,6 +32,13 @@ function assertNoRole(session, change) {
31
32
  throw new ServiceError("conflict", `The ${ROLE_NAMES[session.role]} can't be ${change}`);
32
33
  }
33
34
  }
35
+ /**
36
+ * A Session's state: none for a shell or a Stopped Session. A running Claude Session is in the
37
+ * state its hooks last wrote, and Idle until one has run (see `LiveSession.activity`).
38
+ */
39
+ function activityOf(session, live) {
40
+ return session.kind === "claude" && live ? live.activity : null;
41
+ }
34
42
  function isDirectory(path) {
35
43
  try {
36
44
  return statSync(path).isDirectory();
@@ -80,10 +88,13 @@ export class Service {
80
88
  sessionCreations = Promise.resolve();
81
89
  reconciler;
82
90
  restarts = new Map();
83
- constructor(store, tmux) {
91
+ /** How long a Working Session prints nothing before it decays to Idle. */
92
+ workingQuietMs;
93
+ constructor(store, tmux, options) {
84
94
  this.store = store;
85
95
  this.tmux = tmux;
86
96
  this.reconciler = new Reconciler(store, tmux);
97
+ this.workingQuietMs = options.workingQuietMs;
87
98
  }
88
99
  /**
89
100
  * Kills tmux sessions that have no store record and stores the conversation each Claude
@@ -396,8 +407,14 @@ export class Service {
396
407
  this.store.setRightPane(session.workspaceId, this.rightPane(session.workspaceId));
397
408
  });
398
409
  }
410
+ /**
411
+ * The state, read fresh. Reading it is not free of effects: like `reconcile`, it changes
412
+ * tmux, writing Idle back to each quiet Working Session (`decayQuietWork`), so the decay
413
+ * latches.
414
+ */
399
415
  async getState() {
400
416
  const live = await this.reconciler.reconcile();
417
+ await this.decayQuietWork(live);
401
418
  return {
402
419
  openWorkspaceId: this.openWorkspaceId(),
403
420
  workspaces: this.store.listWorkspaces().map((workspace) => ({
@@ -410,11 +427,29 @@ export class Service {
410
427
  role: session.role,
411
428
  status: live.has(session.id) ? "running" : "stopped",
412
429
  bell: live.get(session.id)?.bell ?? false,
430
+ activity: activityOf(session, live.get(session.id)),
413
431
  })),
414
432
  rightPane: this.rightPane(workspace.id),
415
433
  })),
416
434
  };
417
435
  }
436
+ /**
437
+ * Makes Idle each Working Session that has printed nothing for the quiet time: Claude Code
438
+ * fires no hook when a turn is interrupted, and a wrong Idle is better than a wrong Working.
439
+ * The Idle is written back to tmux, so it latches: the redraws an idle Claude Code makes
440
+ * now and then don't bring Working back, and only a hook or the owner's key moves it on.
441
+ * Waiting never decays, since a permission prompt doesn't redraw.
442
+ */
443
+ async decayQuietWork(live) {
444
+ const quietSince = nowInSeconds() - Math.ceil(this.workingQuietMs / 1000);
445
+ await Promise.all([...live.values()]
446
+ .filter((session) => session.activity === "working" && session.lastChange <= quietSince)
447
+ .map(async (session) => {
448
+ const activity = await this.tmux.decayWorking(session.id, quietSince);
449
+ if (activity !== undefined)
450
+ session.activity = activity;
451
+ }));
452
+ }
418
453
  /**
419
454
  * Gives a Stopped Session a fresh program in its Workspace folder, keeping its id and name:
420
455
  * a shell, or Claude Code for a Claude Session.
@@ -2,7 +2,7 @@ import { execFile, spawn } from "node:child_process";
2
2
  import { userInfo } from "node:os";
3
3
  import { promisify } from "node:util";
4
4
  import * as pty from "node-pty";
5
- import { CONVERSATION_CHANNEL, CONVERSATION_OPTION, claudeCommand, } from "./claude.js";
5
+ import { ACTIVITY_AT_OPTION, ACTIVITY_CHANNEL, ACTIVITY_OPTION, CONVERSATION_CHANNEL, CONVERSATION_OPTION, claudeCommand, } from "./claude.js";
6
6
  const execFileAsync = promisify(execFile);
7
7
  /** Every Session is a tmux session named `kb-<session id>` on the instance's socket. */
8
8
  const PREFIX = "kb-";
@@ -12,6 +12,42 @@ const BELL_OPTION = "@kb-bell";
12
12
  const BELL_CHANNEL = "kb-bell-changed";
13
13
  /** How long a channel watch waits before trying again after tmux failed it unexpectedly. */
14
14
  const WATCH_RETRY_MS = 1_000;
15
+ const ACTIVITIES = ["working", "waiting", "idle"];
16
+ /**
17
+ * A Session's state from what the activity hooks wrote: Idle while it is empty, before any
18
+ * hook has run, or when it isn't a state at all.
19
+ */
20
+ function activityOf(written) {
21
+ return ACTIVITIES.find((activity) => activity === written) ?? "idle";
22
+ }
23
+ /** The tmux format for a Session's state, as the activity hooks wrote it. */
24
+ const ACTIVITY_NOW = `#{${ACTIVITY_OPTION}}`;
25
+ /** A tmux format that is true while a Session's state is `activity`. */
26
+ function activityIs(activity) {
27
+ return `#{==:${ACTIVITY_NOW},${activity}}`;
28
+ }
29
+ /**
30
+ * The tmux target for the Session's one pane. The trailing colon names the Session's current
31
+ * window: without it tmux 3.8 finds no window for a format and prints an empty value, without
32
+ * failing.
33
+ */
34
+ function paneOf(id) {
35
+ return `=${PREFIX}${id}:`;
36
+ }
37
+ /**
38
+ * The `set-option` arguments that set the pane option `option` on `pane` to the tmux format
39
+ * `format`, expanded as it is set.
40
+ */
41
+ function setPaneOption(pane, option, format) {
42
+ return ["set-option", "-p", "-F", "-t", pane, option, format];
43
+ }
44
+ /**
45
+ * The `set-option` arguments that make the state on `pane` `activity` while the tmux format
46
+ * `test` is true, and leave it alone otherwise.
47
+ */
48
+ function setActivityIf(pane, test, activity) {
49
+ return setPaneOption(pane, ACTIVITY_OPTION, `#{?${test},${activity},${ACTIVITY_NOW}}`);
50
+ }
15
51
  /** The owner's login shell. */
16
52
  function ownerShell() {
17
53
  return userInfo().shell || "/bin/zsh";
@@ -181,6 +217,14 @@ export class TmuxDriver {
181
217
  watchConversations(onChange) {
182
218
  return this.watchChannel(CONVERSATION_CHANNEL, onChange);
183
219
  }
220
+ /**
221
+ * Calls `onChange` soon after Claude Code in any Claude Session reports a new state (and
222
+ * now and then when none did), until stopped; `listSessions` then has it. Like the Bells,
223
+ * reports are missed only while no tmux server runs.
224
+ */
225
+ watchActivity(onChange) {
226
+ return this.watchChannel(ACTIVITY_CHANNEL, onChange);
227
+ }
184
228
  watchChannel(channel, onChange) {
185
229
  const watch = new ChannelWatcher([...this.baseArgs(), "wait-for", channel], this.env(), {
186
230
  onChange,
@@ -200,9 +244,9 @@ export class TmuxDriver {
200
244
  }
201
245
  }
202
246
  /**
203
- * The Sessions whose shell is currently alive on this socket, with their Bells and
204
- * conversations. The conversation is a pane option; a session's format reads it from the
205
- * session's one pane.
247
+ * The Sessions whose shell is currently alive on this socket, with their Bells, states and
248
+ * conversations. The state and conversation are pane options; a session's format reads them,
249
+ * and its last output, from the session's one window and pane.
206
250
  */
207
251
  async listSessions() {
208
252
  let stdout;
@@ -210,7 +254,8 @@ export class TmuxDriver {
210
254
  stdout = await this.run([
211
255
  "list-sessions",
212
256
  "-F",
213
- `#{session_name}\t#{${BELL_OPTION}}\t#{${CONVERSATION_OPTION}}`,
257
+ // The conversation goes last: it is read as the rest of the line.
258
+ `#{session_name}\t#{${BELL_OPTION}}\t#{${ACTIVITY_OPTION}}\t#{${ACTIVITY_AT_OPTION}}\t#{window_activity}\t#{${CONVERSATION_OPTION}}`,
214
259
  ]);
215
260
  }
216
261
  catch (error) {
@@ -222,29 +267,66 @@ export class TmuxDriver {
222
267
  .split("\n")
223
268
  .filter((line) => line.startsWith(PREFIX))
224
269
  .map((line) => {
225
- const [name = "", bell = "", ...conversation] = line.split("\t");
270
+ const [name = "", bell = "", activity = "", at = "", output = "", ...conversation] = line.split("\t");
226
271
  return {
227
272
  id: name.slice(PREFIX.length),
228
273
  bell: bell !== "",
274
+ activity: activityOf(activity),
275
+ lastChange: Math.max(Number(at) || 0, Number(output) || 0),
229
276
  conversation: conversation.join("\t"),
230
277
  };
231
278
  });
232
279
  }
280
+ /**
281
+ * Makes a Waiting Claude Session Working, for a key the owner sent it, which is how they
282
+ * answer or deny what it asked (see Waiting in the glossary). Any other state is left
283
+ * alone. It is one tmux call, sent as the key arrives, so it reads the state the key
284
+ * answered: a Waiting that a hook writes after it, for the next prompt, stays. It signals
285
+ * the activity channel only when the Session was Waiting.
286
+ */
287
+ async endWaiting(id) {
288
+ const pane = paneOf(id);
289
+ const isWaiting = activityIs("waiting");
290
+ await this.run(["if-shell", "-F", "-t", pane, isWaiting, `wait-for -S ${ACTIVITY_CHANNEL}`],
291
+ // Stamped before the state is written, while it still says Waiting.
292
+ setPaneOption(pane, ACTIVITY_AT_OPTION, `#{?${isWaiting},${nowInSeconds()},#{${ACTIVITY_AT_OPTION}}}`), setActivityIf(pane, isWaiting, "working"));
293
+ }
294
+ /**
295
+ * Makes a Working Claude Session Idle if it has printed nothing, and had no state written,
296
+ * since `quietSince` (epoch seconds), and returns the state it is in after. Any other state
297
+ * is left alone. It is one tmux call, so a hook or the owner's key that writes the state
298
+ * after it was last read is never overwritten. Returns undefined when the Session has gone.
299
+ */
300
+ async decayWorking(id, quietSince) {
301
+ const pane = paneOf(id);
302
+ const quiet = [
303
+ activityIs("working"),
304
+ `#{e|<=:#{window_activity},${quietSince}}`,
305
+ `#{e|<=:#{${ACTIVITY_AT_OPTION}},${quietSince}}`,
306
+ ].reduce((all, test) => `#{&&:${all},${test}}`);
307
+ try {
308
+ const stdout = await this.run(setActivityIf(pane, quiet, "idle"), [
309
+ "display-message",
310
+ "-p",
311
+ "-t",
312
+ pane,
313
+ ACTIVITY_NOW,
314
+ ]);
315
+ return activityOf(stdout.trim());
316
+ }
317
+ catch (error) {
318
+ if (isNoSuchSession(error))
319
+ return undefined;
320
+ throw error;
321
+ }
322
+ }
233
323
  /**
234
324
  * The size the Session's shell sees: that of its tmux pane's terminal. tmux resizes that
235
325
  * terminal some time after the window (at most once every 250ms per tmux pane), so the
236
326
  * window's size can be ahead of it. tmux names the terminal; `stty` reads its size.
237
327
  */
238
328
  async shellSize(id) {
239
- const tmuxPaneTty = (await this.run([
240
- "display-message",
241
- "-p",
242
- "-t",
243
- // The trailing colon names the Session's current window. Without it tmux 3.8
244
- // finds no window and prints an empty value, without failing.
245
- `=${PREFIX}${id}:`,
246
- "#{pane_tty}",
247
- ])).trim();
329
+ const tmuxPaneTty = (await this.run(["display-message", "-p", "-t", paneOf(id), "#{pane_tty}"])).trim();
248
330
  // `-f` is the macOS spelling (the Host is a Mac); it prints "<rows> <cols>".
249
331
  const { stdout } = await execFileAsync("stty", ["-f", tmuxPaneTty, "size"]);
250
332
  const [rows, cols] = stdout.trim().split(" ").map(Number);
@@ -359,6 +441,10 @@ class ChannelWatcher {
359
441
  return this.stopping;
360
442
  }
361
443
  }
444
+ /** The time now in epoch seconds, as tmux keeps it. */
445
+ export function nowInSeconds() {
446
+ return Math.floor(Date.now() / 1000);
447
+ }
362
448
  function stderrOf(error) {
363
449
  return String(error.stderr ?? "");
364
450
  }