opencode-work-context 0.3.0 → 0.4.2

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
@@ -222,6 +222,51 @@ The shortcut is registered with the public keymap layer. If another plugin or
222
222
  terminal reserves `Ctrl+X`, remove or change the conflicting binding, or
223
223
  disable this TUI loader; the package does not use an internal keymap fallback.
224
224
 
225
+ ### Background Attention Notifications
226
+
227
+ The optional TUI loader tracks linked OpenCode sessions that need attention.
228
+ Questions, permission requests, errors, and a background session becoming idle
229
+ after observed work remain marked with `[ATTN]` until that native session is
230
+ opened. Attention does not change workspace or stage lifecycle state.
231
+
232
+ On Linux, the loader also sends one best-effort desktop notification for newly
233
+ created background attention when `notify-send` is installed and a desktop DBus
234
+ session is available. Desktop delivery is enabled by default. Disable it while
235
+ retaining in-app attention indicators with:
236
+
237
+ ```yaml
238
+ notifications:
239
+ desktop: false
240
+ ```
241
+
242
+ The package invokes the fixed `notify-send` executable directly without a shell
243
+ or configurable command. Notification text contains only bounded, sanitized
244
+ workspace and stage IDs/titles plus a controlled reason. It never includes
245
+ prompts, messages, tool output, paths, secrets, or raw provider errors. Missing
246
+ commands, unsupported platforms, unavailable desktop sessions, timeouts, and
247
+ delivery errors are ignored so they cannot interrupt TUI startup or event
248
+ processing. Notifications are not replayed after restart, and clicking one does
249
+ not navigate to its session in this release.
250
+
251
+ Background includes a linked native session that is not selected and a current
252
+ session in an OpenCode process whose terminal has emitted a standard blur event.
253
+ The latter allows notifications when switching between independent OpenCode
254
+ processes in different terminal windows, tabs, or focus-aware multiplexer panes.
255
+ Focus is tracked through OpenTUI's public renderer events rather than by querying
256
+ the operating system or a specific terminal multiplexer. Until the terminal
257
+ reports focus or blur, the process is conservatively treated as focused. A
258
+ terminal or multiplexer that does not forward focus events retains session-only
259
+ background detection.
260
+
261
+ To verify an installed project manually, install the distribution package that
262
+ provides `notify-send` (commonly `libnotify-bin`), ensure `notify-send "Test"`
263
+ appears in the current desktop session, restart OpenCode, start work in a linked
264
+ session, and switch to another native session before the first one finishes or
265
+ asks a question. Expect one desktop notification and a persistent `[ATTN]`
266
+ marker. Open the affected native session to clear the marker. Set
267
+ `notifications.desktop` to `false`, restart OpenCode, and repeat to verify that
268
+ only the marker remains.
269
+
225
270
  Tools are registered by the installed server export and are not copied into the
226
271
  project. Core and storage remain in the installed package; projects should not
227
272
  copy `src/` or `tools/`. `.work-context` Markdown, JSONL, `INDEX.md`, and
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.3.0",
4
+ "version": "0.4.2",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -0,0 +1,372 @@
1
+ import { createHash } from "node:crypto";
2
+ import { loadConfig } from "../src/storage.js";
3
+ import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
4
+ import { createDesktopNotifier } from "./notifier.js";
5
+ import { createTuiFocusTracker } from "./tui-focus.js";
6
+ import { readTuiState, updateTuiState } from "./tui-state.js";
7
+
8
+ const ATTENTION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
9
+ const MAX_SEEN_EVENTS = 500;
10
+ const MAX_SESSIONS = 100;
11
+ const ACTIVE_ATTENTION_KEY = Symbol.for("opencode-work-context.attention");
12
+ const activeControllers = new WeakMap();
13
+ const PRIORITY = { idle: 1, question: 2, permission: 3, error: 4 };
14
+ const REASON_TEXT = { idle: "response complete", question: "question", permission: "permission", error: "error" };
15
+ const EVENT_TYPES = [
16
+ "session.status",
17
+ "session.idle",
18
+ "question.asked",
19
+ "question.v2.asked",
20
+ "permission.asked",
21
+ "permission.v2.asked",
22
+ "session.error",
23
+ ];
24
+
25
+ const stableHash = (parts) => createHash("sha256").update(parts.map((part) => String(part ?? "")).join("\0")).digest("hex").slice(0, 24);
26
+ const eventBody = (event) => event?.properties || event?.data || {};
27
+ const eventSessionId = (event) => {
28
+ const body = eventBody(event);
29
+ return body.sessionID || body.sessionId || body.session_id || event?.sessionID || event?.sessionId || event?.session_id;
30
+ };
31
+ const eventKey = (event, kind, cycle) => {
32
+ const body = eventBody(event);
33
+ const hostId = body.id || body.requestID || event?.id;
34
+ if (hostId) return `${event.type}:${hostId}`;
35
+ const tool = body.tool || {};
36
+ const error = body.error || {};
37
+ return `${event.type}:fallback:${stableHash([
38
+ eventSessionId(event),
39
+ kind,
40
+ cycle,
41
+ event?.durable?.aggregateID,
42
+ event?.durable?.seq,
43
+ tool.messageID,
44
+ tool.callID,
45
+ error.name,
46
+ error.code,
47
+ ])}`;
48
+ };
49
+
50
+ export const normalizeAttentionEvent = (event, cycle = 0) => {
51
+ const sessionId = eventSessionId(event);
52
+ if (!sessionId || !EVENT_TYPES.includes(event?.type)) return null;
53
+ const body = eventBody(event);
54
+ if (event.type === "session.status") {
55
+ const status = typeof body.status === "string" ? body.status : body.status?.type;
56
+ if (!status || !["busy", "retry", "idle"].includes(status)) return null;
57
+ return { sessionId, kind: "status", status, key: eventKey(event, `status:${status}`, cycle) };
58
+ }
59
+ const kind = event.type === "session.idle"
60
+ ? "idle"
61
+ : event.type.startsWith("question.")
62
+ ? "question"
63
+ : event.type.startsWith("permission.")
64
+ ? "permission"
65
+ : "error";
66
+ return { sessionId, kind, key: eventKey(event, kind, cycle) };
67
+ };
68
+
69
+ export const attentionReasonText = (reason) => REASON_TEXT[reason] || "attention";
70
+ export const attentionForSession = (api, sessionId) => api?.workContextAttention?.attentionFor?.(sessionId) || null;
71
+ export const acknowledgeNavigation = (api, sessionId, observedEventKey) => {
72
+ if (!sessionId || !observedEventKey) return false;
73
+ return api?.workContextAttention?.acknowledge?.(sessionId, observedEventKey) === true;
74
+ };
75
+
76
+ const validAttention = (value) => value
77
+ && typeof value === "object"
78
+ && typeof value.eventKey === "string"
79
+ && Object.hasOwn(PRIORITY, value.reason)
80
+ && Number.isFinite(value.revision)
81
+ && typeof value.createdAt === "string"
82
+ && typeof value.updatedAt === "string";
83
+
84
+ export const createAttentionEngine = ({ persisted, now = () => Date.now(), onChange } = {}) => {
85
+ const sessions = new Map();
86
+ const seen = new Map();
87
+ const listeners = new Set();
88
+ let revision = 0;
89
+
90
+ const notify = (change) => {
91
+ onChange?.(serialize());
92
+ for (const listener of listeners) listener(change);
93
+ };
94
+ const prune = () => {
95
+ const cutoff = now() - ATTENTION_TTL_MS;
96
+ for (const [key, timestamp] of seen) if (!Number.isFinite(timestamp) || timestamp < cutoff) seen.delete(key);
97
+ for (const [id, state] of sessions) if (!Number.isFinite(state.updatedAt) || state.updatedAt < cutoff) sessions.delete(id);
98
+ while (seen.size > MAX_SEEN_EVENTS) seen.delete(seen.keys().next().value);
99
+ const ordered = [...sessions.entries()].sort((left, right) => (right[1].updatedAt || 0) - (left[1].updatedAt || 0));
100
+ sessions.clear();
101
+ for (const [id, state] of ordered.slice(0, MAX_SESSIONS)) sessions.set(id, state);
102
+ };
103
+ const restore = () => {
104
+ if (!persisted || persisted.schema !== 1) return;
105
+ if (Array.isArray(persisted.seen)) {
106
+ for (const item of persisted.seen) {
107
+ if (Array.isArray(item) && typeof item[0] === "string" && Number.isFinite(item[1])) seen.set(item[0], item[1]);
108
+ }
109
+ }
110
+ if (persisted.sessions && typeof persisted.sessions === "object" && !Array.isArray(persisted.sessions)) {
111
+ for (const [id, value] of Object.entries(persisted.sessions)) {
112
+ if (!id || !value || typeof value !== "object") continue;
113
+ const attention = validAttention(value.attention) ? { ...value.attention } : null;
114
+ revision = Math.max(revision, attention?.revision || 0);
115
+ sessions.set(id, {
116
+ busy: value.busy === true,
117
+ cycle: Number.isInteger(value.cycle) && value.cycle >= 0 ? value.cycle : 0,
118
+ attention,
119
+ updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : now(),
120
+ });
121
+ }
122
+ }
123
+ prune();
124
+ };
125
+ const serialize = () => {
126
+ prune();
127
+ return {
128
+ schema: 1,
129
+ sessions: Object.fromEntries([...sessions].map(([id, state]) => [id, state])),
130
+ seen: [...seen],
131
+ };
132
+ };
133
+ const stateFor = (sessionId) => {
134
+ let state = sessions.get(sessionId);
135
+ if (!state) {
136
+ state = { busy: false, cycle: 0, attention: null, updatedAt: now() };
137
+ sessions.set(sessionId, state);
138
+ }
139
+ return state;
140
+ };
141
+ const applyAttention = (state, normalized, foreground) => {
142
+ if (foreground === normalized.sessionId) return { changed: false, suppressed: true };
143
+ const current = state.attention;
144
+ if (current && PRIORITY[normalized.kind] < PRIORITY[current.reason]) return { changed: false, suppressed: false };
145
+ const timestamp = new Date(now()).toISOString();
146
+ revision += 1;
147
+ state.attention = {
148
+ eventKey: normalized.key,
149
+ reason: normalized.kind,
150
+ revision,
151
+ createdAt: current?.createdAt || timestamp,
152
+ updatedAt: timestamp,
153
+ };
154
+ return { changed: true, suppressed: false, attention: { ...state.attention }, created: !current, upgraded: Boolean(current && PRIORITY[normalized.kind] > PRIORITY[current.reason]) };
155
+ };
156
+
157
+ restore();
158
+ return {
159
+ apply(event, { foreground } = {}) {
160
+ const initial = normalizeAttentionEvent(event);
161
+ if (!initial) return { changed: false, ignored: true };
162
+ const state = stateFor(initial.sessionId);
163
+ const normalized = normalizeAttentionEvent(event, state.cycle);
164
+ if (seen.has(normalized.key)) return { changed: false, duplicate: true };
165
+ seen.set(normalized.key, now());
166
+ state.updatedAt = now();
167
+ let result = { changed: false };
168
+ if (normalized.kind === "status") {
169
+ if (normalized.status === "busy" || normalized.status === "retry") {
170
+ if (!state.busy) state.cycle += 1;
171
+ state.busy = true;
172
+ } else if (state.busy) {
173
+ state.busy = false;
174
+ result = applyAttention(state, { ...normalized, kind: "idle" }, foreground);
175
+ }
176
+ } else if (normalized.kind === "idle") {
177
+ if (state.busy) {
178
+ state.busy = false;
179
+ result = applyAttention(state, normalized, foreground);
180
+ }
181
+ } else {
182
+ result = applyAttention(state, normalized, foreground);
183
+ }
184
+ prune();
185
+ notify({ sessionId: normalized.sessionId, ...result });
186
+ return { sessionId: normalized.sessionId, ...result };
187
+ },
188
+ acknowledge(sessionId, observedEventKey) {
189
+ const state = sessions.get(sessionId);
190
+ if (!state?.attention) return false;
191
+ if (observedEventKey && state.attention.eventKey !== observedEventKey) return false;
192
+ const acknowledged = { ...state.attention };
193
+ state.attention = null;
194
+ state.updatedAt = now();
195
+ notify({ sessionId, acknowledged });
196
+ return true;
197
+ },
198
+ attentionFor(sessionId) {
199
+ const attention = sessions.get(sessionId)?.attention;
200
+ return attention ? { ...attention } : null;
201
+ },
202
+ list() {
203
+ return [...sessions.entries()].flatMap(([sessionId, state]) => state.attention ? [{ sessionId, ...state.attention }] : []);
204
+ },
205
+ subscribe(listener) {
206
+ listeners.add(listener);
207
+ return () => listeners.delete(listener);
208
+ },
209
+ serialize,
210
+ };
211
+ };
212
+
213
+ const currentSessionId = (api) => api?.route?.current?.name === "session"
214
+ ? api.route.current.params?.sessionID || api.route.current.params?.sessionId || api.route.current.params?.session_id
215
+ : undefined;
216
+ const linkedSessionIds = (snapshot) => new Set((snapshot?.data?.workspaces || []).flatMap((workspace) =>
217
+ (workspace.sessions || []).map((session) => session.opencode_session_id).filter(Boolean)));
218
+ const notificationContexts = (snapshot, sessionId, reason) => {
219
+ const contexts = [];
220
+ const seen = new Set();
221
+ for (const workspace of snapshot?.workspaces || []) {
222
+ for (const session of workspace.sessions || []) {
223
+ if (session.opencode_session_id !== sessionId || !session.stage) continue;
224
+ const key = `${workspace.id}:${session.stage}`;
225
+ if (seen.has(key)) continue;
226
+ const stage = (workspace.stages || []).find((item) => item.id === session.stage);
227
+ if (!stage) continue;
228
+ seen.add(key);
229
+ contexts.push({
230
+ workspaceId: workspace.id,
231
+ workspaceTitle: workspace.title,
232
+ stageId: stage.id,
233
+ stageTitle: stage.title,
234
+ reason,
235
+ });
236
+ }
237
+ }
238
+ return contexts;
239
+ };
240
+ const disposeRegistration = (registration) => {
241
+ if (typeof registration === "function") registration();
242
+ else registration?.dispose?.();
243
+ };
244
+
245
+ export const desktopNotificationsEnabled = (projectRoot) => {
246
+ try { return loadConfig(projectRoot).notifications?.desktop !== false; } catch { return false; }
247
+ };
248
+
249
+ export const createAttentionTuiController = ({ api, projectRoot, read = readWorkContextSnapshot, onAttention, isFocused = () => true, now } = {}) => {
250
+ const persisted = readTuiState(projectRoot).attention;
251
+ const engine = createAttentionEngine({
252
+ persisted,
253
+ now,
254
+ onChange: (attention) => updateTuiState(projectRoot, (state) => ({ ...state, attention })),
255
+ });
256
+ let linked = new Set();
257
+ let snapshot = null;
258
+ let disposed = false;
259
+ let pending = Promise.resolve();
260
+ const refresh = async () => {
261
+ try {
262
+ const result = await read({ projectRoot, sessionId: currentSessionId(api) });
263
+ if (result?.ok) {
264
+ linked = linkedSessionIds(result);
265
+ snapshot = result.data;
266
+ const current = currentSessionId(api);
267
+ if (isFocused() !== false && current && linked.has(current)) engine.acknowledge(current);
268
+ }
269
+ } catch {}
270
+ return linked;
271
+ };
272
+ const process = async (event) => {
273
+ if (disposed) return { changed: false, ignored: true };
274
+ const sessionId = eventSessionId(event);
275
+ if (!sessionId) return { changed: false, ignored: true };
276
+ await refresh();
277
+ if (!linked.has(sessionId)) return { changed: false, unlinked: true };
278
+ const foreground = isFocused() !== false ? currentSessionId(api) : undefined;
279
+ if (foreground === sessionId) engine.acknowledge(sessionId);
280
+ const result = engine.apply(event, { foreground });
281
+ if (result.changed) onAttention?.({
282
+ sessionId,
283
+ attention: result.attention,
284
+ created: result.created,
285
+ upgraded: result.upgraded,
286
+ contexts: notificationContexts(snapshot, sessionId, result.attention.reason),
287
+ });
288
+ return result;
289
+ };
290
+ const handle = (event) => {
291
+ const result = pending.then(() => process(event));
292
+ pending = result.catch(() => {});
293
+ return result;
294
+ };
295
+ const acknowledge = (sessionId, observedEventKey) => engine.acknowledge(sessionId, observedEventKey);
296
+ const aggregate = (matches) => {
297
+ const bySession = new Map();
298
+ for (const attention of engine.list()) {
299
+ const records = (snapshot?.workspaces || []).flatMap((workspace) => (workspace.sessions || [])
300
+ .filter((session) => session.opencode_session_id === attention.sessionId)
301
+ .map((session) => ({ workspace, session })));
302
+ if (records.some(matches)) bySession.set(attention.sessionId, attention);
303
+ }
304
+ const items = [...bySession.values()];
305
+ if (!items.length) return null;
306
+ const mostImportant = items.reduce((best, item) => PRIORITY[item.reason] > PRIORITY[best.reason] ? item : best);
307
+ return { count: items.length, reason: mostImportant.reason, items };
308
+ };
309
+
310
+ return {
311
+ refresh,
312
+ handle,
313
+ acknowledge,
314
+ attentionFor: engine.attentionFor,
315
+ attentionForStage: (workspace, stage) => aggregate((record) => record.workspace.id === workspace && record.session.stage === stage),
316
+ attentionForWorkspace: (workspace) => aggregate((record) => record.workspace.id === workspace),
317
+ list: engine.list,
318
+ subscribe: engine.subscribe,
319
+ dispose: () => { disposed = true; },
320
+ };
321
+ };
322
+
323
+ export const tui = async (api, options = {}) => {
324
+ if (!api?.event?.on) return;
325
+ if (activeControllers.has(api) || api[ACTIVE_ATTENTION_KEY]) return activeControllers.get(api) || api[ACTIVE_ATTENTION_KEY];
326
+ const projectRoot = api.state?.path?.worktree || api.state?.path?.directory;
327
+ if (!projectRoot) return;
328
+ const desktopNotifier = options.desktopNotifier || createDesktopNotifier({ enabled: desktopNotificationsEnabled(projectRoot), ...options.notifierOptions });
329
+ let controller;
330
+ const focus = options.tuiFocus || createTuiFocusTracker({
331
+ renderer: api.renderer,
332
+ onFocus: () => { void controller?.refresh(); },
333
+ });
334
+ controller = createAttentionTuiController({
335
+ api,
336
+ projectRoot,
337
+ read: api.attentionSnapshotProvider || readWorkContextSnapshot,
338
+ isFocused: options.isTuiFocused || (() => focus.isFocused()),
339
+ onAttention: (change) => {
340
+ try { options.onAttention?.(change); } catch {}
341
+ const context = change.contexts?.[0];
342
+ if (context) void Promise.resolve(desktopNotifier.notify(context)).catch(() => {});
343
+ },
344
+ now: options.now,
345
+ });
346
+ await controller.refresh();
347
+ const registrations = EVENT_TYPES.map((type) => api.event.on(type, (event) => { void controller.handle(event); }));
348
+ registrations.push(api.event.on("tui.session.select", (event) => {
349
+ queueMicrotask(() => {
350
+ const sessionId = currentSessionId(api);
351
+ if (sessionId) controller.acknowledge(sessionId);
352
+ });
353
+ }));
354
+ let cleaned = false;
355
+ const cleanup = () => {
356
+ if (cleaned) return;
357
+ cleaned = true;
358
+ controller.dispose();
359
+ focus.dispose?.();
360
+ for (const registration of registrations) disposeRegistration(registration);
361
+ if (activeControllers.get(api) === cleanup) activeControllers.delete(api);
362
+ if (api[ACTIVE_ATTENTION_KEY] === cleanup) delete api[ACTIVE_ATTENTION_KEY];
363
+ if (api.workContextAttention === controller) delete api.workContextAttention;
364
+ };
365
+ api.workContextAttention = controller;
366
+ api[ACTIVE_ATTENTION_KEY] = cleanup;
367
+ activeControllers.set(api, cleanup);
368
+ api.lifecycle?.onDispose?.(cleanup);
369
+ return cleanup;
370
+ };
371
+
372
+ export default { id: "work-context-attention", tui };
@@ -0,0 +1,83 @@
1
+ import { spawn as nodeSpawn } from "node:child_process";
2
+
3
+ const TITLE_LIMIT = 120;
4
+ const BODY_LIMIT = 240;
5
+ const REASONS = {
6
+ idle: "Response complete",
7
+ question: "Question requires attention",
8
+ permission: "Permission requires attention",
9
+ error: "Error requires attention",
10
+ };
11
+
12
+ const truncate = (text, limit) => text.length <= limit
13
+ ? text
14
+ : `${text.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
15
+
16
+ export const sanitizeNotificationText = (value, limit) => {
17
+ const text = String(value ?? "")
18
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")
19
+ .replace(/\s+/g, " ")
20
+ .trim()
21
+ .replace(/&/g, "&amp;")
22
+ .replace(/</g, "&lt;")
23
+ .replace(/>/g, "&gt;");
24
+ return truncate(text, limit);
25
+ };
26
+
27
+ export const buildNotification = ({ workspaceId, workspaceTitle, stageId, stageTitle, reason } = {}) => {
28
+ if (!/^\d{6}$/.test(workspaceId) || !/^\d{2}$/.test(stageId) || !REASONS[reason]) return null;
29
+ const safeWorkspace = sanitizeNotificationText(workspaceTitle, 80);
30
+ const safeStage = sanitizeNotificationText(stageTitle, 100);
31
+ if (!safeWorkspace || !safeStage) return null;
32
+ return {
33
+ title: truncate(`Work Context ${workspaceId}: ${safeWorkspace}`, TITLE_LIMIT),
34
+ body: truncate(`Stage ${stageId}: ${safeStage}. ${REASONS[reason]}.`, BODY_LIMIT),
35
+ };
36
+ };
37
+
38
+ export const notifySendArguments = (notification) => [
39
+ "--app-name=OpenCode Work Context",
40
+ "--urgency=normal",
41
+ "--",
42
+ notification.title,
43
+ notification.body,
44
+ ];
45
+
46
+ export const createDesktopNotifier = ({
47
+ enabled = true,
48
+ platform = process.platform,
49
+ spawn = nodeSpawn,
50
+ timeoutMs = 3000,
51
+ } = {}) => ({
52
+ async notify(context) {
53
+ const notification = buildNotification(context);
54
+ if (!enabled || platform !== "linux" || !notification) return false;
55
+ return new Promise((resolve) => {
56
+ let child;
57
+ let timer;
58
+ let settled = false;
59
+ const finish = (delivered) => {
60
+ if (settled) return;
61
+ settled = true;
62
+ if (timer) clearTimeout(timer);
63
+ resolve(delivered);
64
+ };
65
+ try {
66
+ child = spawn("notify-send", notifySendArguments(notification), {
67
+ shell: false,
68
+ stdio: "ignore",
69
+ windowsHide: true,
70
+ });
71
+ child.once("error", () => finish(false));
72
+ child.once("exit", (code) => finish(code === 0));
73
+ timer = setTimeout(() => {
74
+ try { child.kill(); } catch {}
75
+ finish(false);
76
+ }, timeoutMs);
77
+ timer.unref?.();
78
+ } catch {
79
+ finish(false);
80
+ }
81
+ });
82
+ },
83
+ });
@@ -1,4 +1,5 @@
1
1
  import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
2
+ import { acknowledgeNavigation, attentionForSession, attentionReasonText } from "./attention.js";
2
3
 
3
4
  const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
4
5
 
@@ -7,10 +8,13 @@ const currentSessionId = (api) => api?.route?.current?.params?.sessionID || api?
7
8
  const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.directory;
8
9
  const sessionTime = (session) => String(session.updated_at || session.started_at || "");
9
10
 
10
- const compareSessions = (left, right, currentId) => {
11
+ const compareSessions = (left, right, currentId, attention) => {
11
12
  const leftCurrent = left.opencode_session_id === currentId;
12
13
  const rightCurrent = right.opencode_session_id === currentId;
13
14
  if (leftCurrent !== rightCurrent) return leftCurrent ? -1 : 1;
15
+ const leftAttention = Boolean(attention?.(left.opencode_session_id));
16
+ const rightAttention = Boolean(attention?.(right.opencode_session_id));
17
+ if (leftAttention !== rightAttention) return leftAttention ? -1 : 1;
14
18
  return (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
15
19
  || sessionTime(right).localeCompare(sessionTime(left))
16
20
  || Number(right.ordinal || 0) - Number(left.ordinal || 0)
@@ -19,14 +23,14 @@ const compareSessions = (left, right, currentId) => {
19
23
  };
20
24
 
21
25
  /** Return one deterministic work-context record for each native OpenCode session. */
22
- export const sortSessionSwitcherEntries = (entries = [], currentId = null) => {
26
+ export const sortSessionSwitcherEntries = (entries = [], currentId = null, attention) => {
23
27
  const selected = new Map();
24
28
  for (const entry of entries) {
25
29
  const id = entry.session?.opencode_session_id;
26
- if (!id || selected.has(id) && compareSessions(selected.get(id).session, entry.session, currentId) <= 0) continue;
30
+ if (!id || selected.has(id) && compareSessions(selected.get(id).session, entry.session, currentId, attention) <= 0) continue;
27
31
  selected.set(id, entry);
28
32
  }
29
- return [...selected.values()].sort((left, right) => compareSessions(left.session, right.session, currentId));
33
+ return [...selected.values()].sort((left, right) => compareSessions(left.session, right.session, currentId, attention));
30
34
  };
31
35
 
32
36
  export const selectSession = (entries = [], currentId = null) => sortSessionSwitcherEntries(entries, currentId)[0]?.session || null;
@@ -36,8 +40,10 @@ export const switchToSession = (api, session) => {
36
40
  if (!sessionID) return errorResult("SESSION_OPENCODE_ID_MISSING", "This work-context session has no OpenCode session ID", { session_id: session?.session_id });
37
41
  if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
38
42
  try {
43
+ const observed = attentionForSession(api, sessionID)?.eventKey;
39
44
  api.ui?.dialog?.clear?.();
40
45
  api.route.navigate("session", { sessionID });
46
+ acknowledgeNavigation(api, sessionID, observed);
41
47
  return { ok: true, data: { opencode_session_id: sessionID, created: false, navigated: true } };
42
48
  } catch (error) {
43
49
  return errorResult(error.code || "SESSION_SWITCH_ERROR", error.message || "OpenCode could not open the selected session", { opencode_session_id: sessionID });
@@ -58,7 +64,8 @@ export const createSessionSwitcherFlow = (api, { read = readWorkContextSnapshot
58
64
  const entries = (data.workspaces || []).flatMap((workspace) => (workspace.sessions || []).map((session) => ({ workspace, session })));
59
65
  if (!entries.length) { toast("No sessions found"); return result; }
60
66
  const currentId = currentSessionId(api);
61
- const available = sortSessionSwitcherEntries(entries, currentId);
67
+ const attention = (id) => attentionForSession(api, id);
68
+ const available = sortSessionSwitcherEntries(entries, currentId, attention);
62
69
  const unavailable = entries.filter(({ session }) => !session.opencode_session_id);
63
70
  const labels = { active: "Active", handed_off: "Handed off", abandoned: "Abandoned", closed: "Closed" };
64
71
  api.ui.dialog.setSize?.("medium");
@@ -67,8 +74,8 @@ export const createSessionSwitcherFlow = (api, { read = readWorkContextSnapshot
67
74
  placeholder: "Search sessions",
68
75
  options: [
69
76
  ...available.map(({ workspace, session }) => ({
70
- title: `${workspace.id} ${session.stage || "-"}/${String(session.ordinal || 0).padStart(2, "0")} ${session.summary || "Work session"} · ${workspace.title}`,
71
- description: `${session.state || "unknown"} · ${session.session_id || "unknown"}`,
77
+ title: `${attention(session.opencode_session_id) ? "[ATTN] " : ""}${workspace.id} ${session.stage || "-"}/${String(session.ordinal || 0).padStart(2, "0")} ${session.summary || "Work session"} · ${workspace.title}`,
78
+ description: `${attention(session.opencode_session_id) ? `needs attention: ${attentionReasonText(attention(session.opencode_session_id).reason)} · ` : ""}${session.state || "unknown"} · ${session.session_id || "unknown"}`,
72
79
  footer: session.opencode_session_id,
73
80
  category: session.opencode_session_id === currentId ? "Current" : labels[session.state] || session.state || "Unknown",
74
81
  value: session,
@@ -1,13 +1,11 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
1
  import { contextFor } from "../src/opencode-adapter.js";
4
- import { atomicWrite } from "../src/storage.js";
5
2
  import { isDependencySatisfied } from "../src/stage-status.js";
3
+ import { readTuiState, updateTuiState } from "./tui-state.js";
4
+ import { acknowledgeNavigation, attentionForSession, attentionReasonText } from "./attention.js";
6
5
 
7
6
  const TERMINAL_STATUSES = new Set(["completed", "cancelled", "archived"]);
8
7
  const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
9
8
  const RECENT_STAGE_LIMIT = 5;
10
- const RECENT_STATE_FILE = path.join(".work-context", "local", "tui-state.json");
11
9
  const recentStagesByApi = new WeakMap();
12
10
 
13
11
  const errorResult = (code, message, details = {}) => ({ ok: false, error: { code, message, details } });
@@ -15,24 +13,16 @@ const currentSessionId = (api) => api?.route?.current?.params?.sessionID || api?
15
13
  const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.directory;
16
14
 
17
15
  const readRecentState = (root) => {
18
- if (!root) return {};
19
- try {
20
- const file = path.join(root, RECENT_STATE_FILE);
21
- if (!fs.lstatSync(file).isFile()) return {};
22
- const state = JSON.parse(fs.readFileSync(file, "utf8"));
23
- if (!state || state.schema !== 1 || !state.recent_stages || typeof state.recent_stages !== "object") return {};
24
- return Object.fromEntries(Object.entries(state.recent_stages).map(([workspace, stages]) => [
25
- workspace,
26
- Array.isArray(stages) ? stages.filter((stage) => /^\d{2}$/.test(stage)).slice(0, RECENT_STAGE_LIMIT) : [],
27
- ]));
28
- } catch { return {}; }
16
+ const recent = readTuiState(root).recent_stages;
17
+ if (!recent || typeof recent !== "object" || Array.isArray(recent)) return {};
18
+ return Object.fromEntries(Object.entries(recent).map(([workspace, stages]) => [
19
+ workspace,
20
+ Array.isArray(stages) ? stages.filter((stage) => /^\d{2}$/.test(stage)).slice(0, RECENT_STAGE_LIMIT) : [],
21
+ ]));
29
22
  };
30
23
 
31
24
  const persistRecentState = (root, store) => {
32
- if (!root) return;
33
- try {
34
- atomicWrite(path.join(root, RECENT_STATE_FILE), `${JSON.stringify({ schema: 1, recent_stages: Object.fromEntries(store) }, null, 2)}\n`);
35
- } catch {}
25
+ updateTuiState(root, (state) => ({ ...state, recent_stages: Object.fromEntries(store) }));
36
26
  };
37
27
 
38
28
  const recentStageStore = (api) => {
@@ -55,9 +45,10 @@ export const rememberRecentStage = (api, workspace, stage) => {
55
45
 
56
46
  export const recentStageIds = (api, workspace) => [...(recentStageStore(api).get(workspace) || [])];
57
47
 
58
- export const selectStageSession = (sessions = []) => sessions
48
+ export const selectStageSession = (sessions = [], attention) => sessions
59
49
  .filter((session) => session.opencode_session_id)
60
- .sort((left, right) => (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
50
+ .sort((left, right) => Number(Boolean(attention?.(right.opencode_session_id))) - Number(Boolean(attention?.(left.opencode_session_id)))
51
+ || (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
61
52
  || String(right.updated_at || right.started_at || "").localeCompare(String(left.updated_at || left.started_at || ""))
62
53
  || Number(right.ordinal || 0) - Number(left.ordinal || 0))[0] || null;
63
54
 
@@ -100,8 +91,10 @@ export const readStageSwitcherSnapshot = ({ projectRoot: root, sessionId } = {})
100
91
  const navigateToSession = (api, sessionID) => {
101
92
  if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
102
93
  try {
94
+ const observed = attentionForSession(api, sessionID)?.eventKey;
103
95
  api.ui?.dialog?.clear?.();
104
96
  api.route.navigate("session", { sessionID });
97
+ acknowledgeNavigation(api, sessionID, observed);
105
98
  return { ok: true, data: { opencode_session_id: sessionID, created: false } };
106
99
  } catch (error) {
107
100
  return errorResult(error.code || "SESSION_SWITCH_ERROR", error.message || "OpenCode could not open the selected session");
@@ -176,16 +169,22 @@ export const createStageSwitcherFlow = (api, { read = readStageSwitcherSnapshot,
176
169
  catch (error) { result = errorResult(error.code || "STORAGE_ERROR", error.message || "Cannot read work-context storage"); }
177
170
  if (!result?.ok) { toast(`${result?.error?.code || "STORAGE_ERROR"}: ${result?.error?.message || "Cannot read work-context storage"}`, "error"); return result; }
178
171
  const { workspace, stages } = result.data;
172
+ const sessionAttention = (id) => attentionForSession(api, id);
173
+ const stageAttention = (id) => api.workContextAttention?.attentionForStage?.(workspace.id, id);
174
+ const decorated = stages.map((stage) => ({ ...stage, attention: stageAttention(stage.id), selectedSession: selectStageSession(stage.sessions, sessionAttention) }));
179
175
  rememberRecentStage(api, workspace.id, result.data.currentStage);
180
176
  const recent = recentStageIds(api, workspace.id)
181
- .map((id) => stages.find((stage) => stage.id === id))
177
+ .map((id) => decorated.find((stage) => stage.id === id))
182
178
  .filter((stage) => stage && !stage.current);
179
+ const current = decorated.filter((stage) => stage.current);
180
+ const needsAttention = decorated.filter((stage) => !stage.current && stage.attention);
181
+ const ordinary = decorated.filter((stage) => !stage.current && !stage.attention);
183
182
  const optionFor = (stage, category) => {
184
183
  const available = (stage.sessions || []).filter((session) => session.opencode_session_id).length;
185
184
  const state = stage.blocked ? `blocked by ${stage.blockers.join(", ")}` : stage.status;
186
185
  return {
187
- title: `${stage.current ? ">" : " "} ${stage.id}. ${stage.title}`,
188
- description: `${state} · ${available ? `${available} session${available === 1 ? "" : "s"}` : TERMINAL_STATUSES.has(stage.status) || stage.blocked ? "no session available" : "new session"}`,
186
+ title: `${stage.current ? ">" : " "} ${stage.attention ? "[ATTN] " : ""}${stage.id}. ${stage.title}`,
187
+ description: `${stage.attention ? `needs attention: ${attentionReasonText(stage.attention.reason)} (${stage.attention.count}) · ` : ""}${state} · ${available ? `${available} session${available === 1 ? "" : "s"}` : TERMINAL_STATUSES.has(stage.status) || stage.blocked ? "no session available" : "new session"}`,
189
188
  category,
190
189
  disabled: (TERMINAL_STATUSES.has(stage.status) || stage.blocked) && !available,
191
190
  value: stage,
@@ -196,8 +195,10 @@ export const createStageSwitcherFlow = (api, { read = readStageSwitcherSnapshot,
196
195
  title: `Switch stage · ${workspace.id} ${workspace.title}`,
197
196
  placeholder: "Search stages",
198
197
  options: [
199
- ...recent.map((stage) => optionFor(stage, "Recent")),
200
- ...stages.map((stage) => optionFor(stage, stage.current ? "Current" : stage.status)),
198
+ ...current.map((stage) => optionFor(stage, "Current")),
199
+ ...needsAttention.map((stage) => optionFor(stage, "Needs attention")),
200
+ ...recent.filter((stage) => !stage.attention).map((stage) => optionFor(stage, "Recent")),
201
+ ...ordinary.map((stage) => optionFor(stage, stage.status)),
201
202
  ],
202
203
  onSelect: (option) => void (async () => {
203
204
  const switched = await switchToStage(api, option.value, { workspace: workspace.id, currentStage: result.data.currentStage, start });
@@ -4,6 +4,7 @@ import { readStagesSnapshot } from "../src/stages-snapshot.js";
4
4
  import { renderStagesPanel } from "../src/stages-renderer.js";
5
5
  import { jsx } from "@opentui/solid/jsx-runtime";
6
6
  import { createSignal } from "solid-js";
7
+ import { attentionReasonText } from "./attention.js";
7
8
 
8
9
  const DEBOUNCE_MS = 150;
9
10
  const POLL_MS = 1000;
@@ -24,7 +25,7 @@ export { readStagesSnapshot, renderStagesPanel };
24
25
 
25
26
  const defaultRuntime = { jsx };
26
27
 
27
- const renderStagesContent = (result, theme, runtime = defaultRuntime) => !result?.ok || !result.data?.workspace
28
+ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention) => !result?.ok || !result.data?.workspace
28
29
  ? [
29
30
  runtime.jsx("text", { children: runtime.jsx("b", { children: "Stages" }) }),
30
31
  ...renderStagesPanel(result).split("\n").slice(1).map((line) => runtime.jsx("text", { children: line })),
@@ -32,7 +33,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime) => !result
32
33
  : [
33
34
  runtime.jsx("box", {
34
35
  marginBottom: 1,
35
- children: runtime.jsx("text", { wrapMode: "word", children: runtime.jsx("b", { children: result.data.workspace.title }) }),
36
+ children: runtime.jsx("text", { wrapMode: "word", children: runtime.jsx("b", { children: `${attention?.attentionForWorkspace?.(result.data.workspace.id) ? "[ATTN] " : ""}${result.data.workspace.title}` }) }),
36
37
  }),
37
38
  runtime.jsx("box", {
38
39
  flexDirection: "row",
@@ -41,19 +42,22 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime) => !result
41
42
  runtime.jsx("text", { fg: theme?.current?.textMuted, children: ` · ${result.data.workspace.status}` }),
42
43
  ],
43
44
  }),
44
- ...result.data.stages.map((stage) => runtime.jsx("box", {
45
- flexDirection: "row",
46
- children: [
47
- runtime.jsx("text", { flexShrink: 0, marginRight: 1, fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: statusMarker(stage.status) }),
48
- runtime.jsx("text", { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: `${stage.id}. ${stage.title}` }),
49
- ],
50
- })),
45
+ ...result.data.stages.map((stage) => {
46
+ const unread = attention?.attentionForStage?.(result.data.workspace.id, stage.id);
47
+ return runtime.jsx("box", {
48
+ flexDirection: "row",
49
+ children: [
50
+ runtime.jsx("text", { flexShrink: 0, marginRight: 1, fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: statusMarker(stage.status) }),
51
+ runtime.jsx("text", { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: `${stage.id}. ${stage.title}${unread ? ` [ATTN: ${attentionReasonText(unread.reason)}${unread.count > 1 ? ` x${unread.count}` : ""}]` : ""}` }),
52
+ ],
53
+ });
54
+ }),
51
55
  ];
52
56
 
53
- export const renderStagesElement = (result, theme, runtime = defaultRuntime) => {
57
+ export const renderStagesElement = (result, theme, runtime = defaultRuntime, attention) => {
54
58
  return runtime.jsx("box", {
55
59
  flexDirection: "column",
56
- children: () => renderStagesContent(typeof result === "function" ? result() : result, theme, runtime),
60
+ children: () => renderStagesContent(typeof result === "function" ? result() : result, theme, runtime, attention),
57
61
  });
58
62
  };
59
63
 
@@ -89,13 +93,14 @@ const disposeRegistration = (registration) => {
89
93
  else registration?.dispose?.();
90
94
  };
91
95
 
92
- export const createStagesTuiController = ({ projectRoot, read = readStagesSnapshot, debounceMs = DEBOUNCE_MS, pollMs = POLL_MS, createSignal: makeSignal = createSignal } = {}) => {
96
+ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapshot, debounceMs = DEBOUNCE_MS, pollMs = POLL_MS, createSignal: makeSignal = createSignal, attention } = {}) => {
93
97
  const snapshots = new Map();
94
98
  const generations = new Map();
95
99
  const timers = new Map();
96
100
  const pollers = new Map();
97
101
  const [version, setVersion] = makeSignal(0);
98
102
  let disposed = false;
103
+ const unsubscribeAttention = attention?.subscribe?.(() => setVersion((value) => value + 1));
99
104
 
100
105
  const readSnapshot = async (sessionId) => {
101
106
  if (disposed || !sessionId) return;
@@ -164,6 +169,7 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
164
169
  for (const poller of pollers.values()) clearInterval(poller);
165
170
  pollers.clear();
166
171
  snapshots.clear();
172
+ unsubscribeAttention?.();
167
173
  },
168
174
  };
169
175
  };
@@ -191,9 +197,9 @@ export const resolveProjectRoot = async (api, { timeoutMs = PATH_TIMEOUT_MS, pol
191
197
  return null;
192
198
  };
193
199
 
194
- const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime) => runtime.jsx("box", {
200
+ const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime, attention) => runtime.jsx("box", {
195
201
  flexDirection: "column",
196
- children: renderStagesElement(() => controller.resultFor(sessionId), theme, runtime),
202
+ children: renderStagesElement(() => controller.resultFor(sessionId), theme, runtime, attention),
197
203
  });
198
204
 
199
205
  const ACTIVE_WORKSPACE_SESSION = "__active_" + "work" + "_context_workspace__";
@@ -215,6 +221,7 @@ export const tui = async (api, options = {}) => {
215
221
  debounceMs: options.debounceMs,
216
222
  pollMs: options.pollMs,
217
223
  createSignal: options.runtime?.createSignal,
224
+ attention: api.workContextAttention,
218
225
  });
219
226
  await controller.load(initialSessionId);
220
227
  let currentSessionId = initialSessionId;
@@ -234,7 +241,7 @@ export const tui = async (api, options = {}) => {
234
241
  sidebar_content: (slotContext = {}, slotState = {}) => {
235
242
  const sessionId = sessionIdForSlot(api, initialSessionId, slotContext, slotState) || ACTIVE_WORKSPACE_SESSION;
236
243
  currentSessionId = sessionId;
237
- return renderStagesSlot(controller, api.theme, sessionId, options.runtime);
244
+ return renderStagesSlot(controller, api.theme, sessionId, options.runtime, api.workContextAttention);
238
245
  },
239
246
  },
240
247
  });
@@ -0,0 +1,18 @@
1
+ export const createTuiFocusTracker = ({ renderer, onFocus } = {}) => {
2
+ let state = "unknown";
3
+ const handleFocus = () => {
4
+ state = "focused";
5
+ try { onFocus?.(); } catch {}
6
+ };
7
+ const handleBlur = () => { state = "blurred"; };
8
+ renderer?.on?.("focus", handleFocus);
9
+ renderer?.on?.("blur", handleBlur);
10
+ return {
11
+ state: () => state,
12
+ isFocused: () => state !== "blurred",
13
+ dispose: () => {
14
+ renderer?.off?.("focus", handleFocus);
15
+ renderer?.off?.("blur", handleBlur);
16
+ },
17
+ };
18
+ };
@@ -0,0 +1,31 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { atomicWrite } from "../src/storage.js";
4
+
5
+ export const TUI_STATE_FILE = path.join(".work-context", "local", "tui-state.json");
6
+
7
+ export const readTuiState = (root) => {
8
+ if (!root) return { schema: 1 };
9
+ try {
10
+ const file = path.join(root, TUI_STATE_FILE);
11
+ if (!fs.lstatSync(file).isFile()) return { schema: 1 };
12
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
13
+ return value && value.schema === 1 && typeof value === "object" && !Array.isArray(value)
14
+ ? value
15
+ : { schema: 1 };
16
+ } catch {
17
+ return { schema: 1 };
18
+ }
19
+ };
20
+
21
+ export const updateTuiState = (root, update) => {
22
+ if (!root) return false;
23
+ try {
24
+ const current = readTuiState(root);
25
+ const next = update(current);
26
+ atomicWrite(path.join(root, TUI_STATE_FILE), `${JSON.stringify({ ...next, schema: 1 }, null, 2)}\n`);
27
+ return true;
28
+ } catch {
29
+ return false;
30
+ }
31
+ };
package/plugin/tui.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import stages from "./stages-tui.js";
2
2
  import modal from "./work-context-modal.js";
3
+ import attention from "./attention.js";
3
4
 
4
5
  // Keep the sidebar and modal adapters composed under one optional TUI entry.
5
6
  // The server plugin remains a separate runtime contract.
6
7
  export const tui = async (api, options = {}) => {
8
+ await attention.tui(api, options);
7
9
  await stages.tui(api, options);
8
10
  await modal.tui(api, options);
9
11
  };
@@ -7,6 +7,7 @@ import { createSignal } from "solid-js";
7
7
  import { openStageSwitcher } from "./stage-switcher.js";
8
8
  import { openWorkspaceSwitcher } from "./workspace-switcher.js";
9
9
  import { openSessionSwitcher } from "./session-switcher.js";
10
+ import { attentionForSession, attentionReasonText } from "./attention.js";
10
11
 
11
12
  const COMMAND_NAME = "work_context.open";
12
13
  const ACTIONS_COMMAND_NAME = "work_context.actions";
@@ -115,6 +116,7 @@ export const createWorkContextModalController = ({
115
116
  createSignal: makeSignal = createSignal,
116
117
  onClose = () => {},
117
118
  onCommand = () => {},
119
+ attention,
118
120
  } = {}) => {
119
121
  const [version, setVersion] = makeSignal(0);
120
122
  const [query, setQuery] = makeSignal("");
@@ -127,6 +129,7 @@ export const createWorkContextModalController = ({
127
129
  let poller;
128
130
  let disposed = false;
129
131
  let onSelectionChange = () => {};
132
+ const unsubscribeAttention = attention?.subscribe?.(() => setVersion((value) => value + 1));
130
133
 
131
134
  const refresh = async () => {
132
135
  if (disposed) return;
@@ -149,7 +152,17 @@ export const createWorkContextModalController = ({
149
152
  timer = setTimeout(() => { timer = undefined; void refresh(); }, debounceMs);
150
153
  };
151
154
  const snapshot = () => { version(); return result; };
152
- const workspaces = () => filterWorkspaces(snapshot()?.data?.workspaces || [], query());
155
+ const workspaces = () => {
156
+ const data = snapshot()?.data || {};
157
+ return filterWorkspaces(data.workspaces || [], query())
158
+ .map((workspace) => ({
159
+ ...workspace,
160
+ stages: [...(workspace.stages || [])].sort((left, right) => Number(Boolean(right.current)) - Number(Boolean(left.current))
161
+ || Number(Boolean(attention?.attentionForStage?.(workspace.id, right.id))) - Number(Boolean(attention?.attentionForStage?.(workspace.id, left.id)))),
162
+ }))
163
+ .sort((left, right) => Number(right.id === data.currentWorkspace) - Number(left.id === data.currentWorkspace)
164
+ || Number(Boolean(attention?.attentionForWorkspace?.(right.id))) - Number(Boolean(attention?.attentionForWorkspace?.(left.id))));
165
+ };
153
166
  const selectedWorkspace = () => workspaces()[Math.min(workspaceIndex(), Math.max(0, workspaces().length - 1))] || null;
154
167
  const selectedStage = () => selectedWorkspace()?.stages?.[Math.min(stageIndex(), Math.max(0, (selectedWorkspace()?.stages || []).length - 1))] || null;
155
168
  const [preparedCommand, setPreparedCommand] = makeSignal(null);
@@ -200,9 +213,9 @@ export const createWorkContextModalController = ({
200
213
  void refresh();
201
214
  if (pollMs) poller = setInterval(scheduleRefresh, pollMs);
202
215
  return {
203
- snapshot, query, setQuery, workspaces, selectedWorkspace, selectedStage, details, preparedCommand, prepareCommand, insertCommand, handleKey, scheduleRefresh,
216
+ snapshot, query, setQuery, workspaces, selectedWorkspace, selectedStage, details, preparedCommand, prepareCommand, insertCommand, handleKey, scheduleRefresh, attention,
204
217
  onSelectionChange: (handler) => { onSelectionChange = typeof handler === "function" ? handler : () => {}; },
205
- dispose: () => { disposed = true; clearTimeout(timer); clearInterval(poller); },
218
+ dispose: () => { disposed = true; clearTimeout(timer); clearInterval(poller); unsubscribeAttention?.(); },
206
219
  };
207
220
  };
208
221
 
@@ -228,19 +241,25 @@ export const renderWorkContextModal = (controller, theme, runtime = { jsx }, { m
228
241
  const muted = theme?.current?.textMuted;
229
242
  const selectedWorkspaceIndex = selected ? workspaces.indexOf(selected) : -1;
230
243
  const selectedStageIndex = stage && selected ? (selected.stages || []).indexOf(stage) : -1;
231
- const workspaceItems = workspaces.map((workspace, index) => runtime.jsx("box", {
232
- id: `workspace-${workspace.id}`, flexDirection: "row", gap: 1, children: [
233
- line(runtime, index === selectedWorkspaceIndex ? ">" : " ", { flexShrink: 0, marginRight: 1, fg: index === selectedWorkspaceIndex ? theme?.current?.text : muted }),
234
- line(runtime, `${workspace.id} ${workspace.title}`, { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: workspace.id === data?.currentWorkspace ? theme?.current?.warning : theme?.current?.text }),
235
- line(runtime, workspace.status, { flexShrink: 0, fg: muted }),
236
- ],
237
- }));
238
- const stageItems = selected ? (selected.stages || []).map((item, index) => runtime.jsx("box", {
239
- id: `stage-${item.id}`, flexDirection: "row", children: [
240
- line(runtime, index === selectedStageIndex ? ">" : " ", { flexShrink: 0, marginRight: 1, fg: index === selectedStageIndex ? theme?.current?.text : muted }),
241
- line(runtime, `${marker(item.status)} ${item.id}. ${item.title}${item.current ? " · current" : ""}`, { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: item.current ? theme?.current?.warning : theme?.current?.text }),
242
- ],
243
- })) : [];
244
+ const workspaceItems = workspaces.map((workspace, index) => {
245
+ const unread = controller.attention?.attentionForWorkspace?.(workspace.id);
246
+ return runtime.jsx("box", {
247
+ id: `workspace-${workspace.id}`, flexDirection: "row", gap: 1, children: [
248
+ line(runtime, index === selectedWorkspaceIndex ? ">" : " ", { flexShrink: 0, marginRight: 1, fg: index === selectedWorkspaceIndex ? theme?.current?.text : muted }),
249
+ line(runtime, `${unread ? "[ATTN] " : ""}${workspace.id} ${workspace.title}`, { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: workspace.id === data?.currentWorkspace ? theme?.current?.warning : theme?.current?.text }),
250
+ line(runtime, workspace.status, { flexShrink: 0, fg: muted }),
251
+ ],
252
+ });
253
+ });
254
+ const stageItems = selected ? (selected.stages || []).map((item, index) => {
255
+ const unread = controller.attention?.attentionForStage?.(selected.id, item.id);
256
+ return runtime.jsx("box", {
257
+ id: `stage-${item.id}`, flexDirection: "row", children: [
258
+ line(runtime, index === selectedStageIndex ? ">" : " ", { flexShrink: 0, marginRight: 1, fg: index === selectedStageIndex ? theme?.current?.text : muted }),
259
+ line(runtime, `${marker(item.status)} ${item.id}. ${item.title}${item.current ? " · current" : ""}${unread ? ` [ATTN: ${attentionReasonText(unread.reason)}${unread.count > 1 ? ` x${unread.count}` : ""}]` : ""}`, { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: item.current ? theme?.current?.warning : theme?.current?.text }),
260
+ ],
261
+ });
262
+ }) : [];
244
263
  const children = [runtime.jsx("box", {
245
264
  flexDirection: "row", justifyContent: "space-between", paddingLeft: 2, paddingRight: 2,
246
265
  children: [
@@ -270,7 +289,10 @@ export const renderWorkContextModal = (controller, theme, runtime = { jsx }, { m
270
289
  line(runtime, "Details", { marginTop: 1, fg: muted }),
271
290
  line(runtime, stage.description || "No description.", { wrapMode: "word", fg: theme?.current?.text }),
272
291
  line(runtime, `Sessions ${(selected.sessions || []).length}`, { fg: muted }),
273
- ...(selected.sessions || []).map((session) => line(runtime, `${session.state || "unknown"} ${session.session_id || "unknown"} stage ${session.stage || "-"}`, { wrapMode: "word", fg: muted })),
292
+ ...(selected.sessions || []).map((session) => {
293
+ const unread = controller.attention?.attentionFor?.(session.opencode_session_id);
294
+ return line(runtime, `${unread ? `[ATTN: ${attentionReasonText(unread.reason)}] ` : ""}${session.state || "unknown"} ${session.session_id || "unknown"} stage ${session.stage || "-"}`, { wrapMode: "word", fg: muted });
295
+ }),
274
296
  ] : []),
275
297
  ] }),
276
298
  ],
@@ -409,10 +431,14 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
409
431
  const workspaces = [...loaded.workspaces].sort((left, right) => {
410
432
  if (left.id === loaded.currentWorkspace) return -1;
411
433
  if (right.id === loaded.currentWorkspace) return 1;
434
+ const leftAttention = api.workContextAttention?.attentionForWorkspace?.(left.id);
435
+ const rightAttention = api.workContextAttention?.attentionForWorkspace?.(right.id);
436
+ if (Boolean(leftAttention) !== Boolean(rightAttention)) return leftAttention ? -1 : 1;
412
437
  return (rank[left.status] ?? 9) - (rank[right.status] ?? 9) || left.id.localeCompare(right.id);
413
438
  });
414
439
  const options = workspaces.flatMap((workspace) => {
415
- const category = `${workspace.id} · ${workspace.title} · ${workspace.status}`;
440
+ const unread = api.workContextAttention?.attentionForWorkspace?.(workspace.id);
441
+ const category = `${unread ? "[ATTN] " : ""}${workspace.id} · ${workspace.title} · ${workspace.status}`;
416
442
  return [
417
443
  { title: "Overview", description: workspace.status, footer: progress(workspace), category, value: { type: "workspace", workspace } },
418
444
  ...(workspace.stages || []).map((stage) => ({
@@ -437,17 +463,23 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
437
463
  entries.sort((left, right) => {
438
464
  if (left.stage.current) return -1;
439
465
  if (right.stage.current) return 1;
466
+ const leftAttention = api.workContextAttention?.attentionForStage?.(left.workspace.id, left.stage.id);
467
+ const rightAttention = api.workContextAttention?.attentionForStage?.(right.workspace.id, right.stage.id);
468
+ if (Boolean(leftAttention) !== Boolean(rightAttention)) return leftAttention ? -1 : 1;
440
469
  return (rank[left.stage.status] ?? 9) - (rank[right.stage.status] ?? 9)
441
470
  || left.workspace.id.localeCompare(right.workspace.id)
442
471
  || Number(left.stage.id) - Number(right.stage.id);
443
472
  });
444
473
  const labels = { in_progress: "In progress", planned: "Planned", completed: "Completed", cancelled: "Cancelled" };
445
- showSelect("Stages", entries.map(({ workspace, stage }) => ({
446
- title: `${marker(stage.status)} ${workspace.id}/${stage.id} ${stage.title} · ${workspace.title}`,
447
- description: stage.description || stage.status,
448
- category: stage.current ? "Current" : labels[stage.status] || stage.status,
449
- value: { workspace, stage },
450
- })), (option) => showStageActions(option.value.workspace, option.value.stage, { backTitle: "Back to stages", onBack: () => void browseStages() }));
474
+ showSelect("Stages", entries.map(({ workspace, stage }) => {
475
+ const unread = api.workContextAttention?.attentionForStage?.(workspace.id, stage.id);
476
+ return {
477
+ title: `${marker(stage.status)} ${unread ? "[ATTN] " : ""}${workspace.id}/${stage.id} ${stage.title} · ${workspace.title}`,
478
+ description: unread ? `Needs attention: ${attentionReasonText(unread.reason)} (${unread.count}) · ${stage.description || stage.status}` : stage.description || stage.status,
479
+ category: stage.current ? "Current" : labels[stage.status] || stage.status,
480
+ value: { workspace, stage },
481
+ };
482
+ }), (option) => showStageActions(option.value.workspace, option.value.stage, { backTitle: "Back to stages", onBack: () => void browseStages() }));
451
483
  };
452
484
  const sessionOrdinal = (session) => String(session.ordinal).includes("/")
453
485
  ? String(session.ordinal)
@@ -482,15 +514,19 @@ export const createWorkContextActionFlow = (api, { projectRoot, sessionId, read
482
514
  const rightCurrent = right.session.opencode_session_id === sessionId || right.session.session_id === sessionId;
483
515
  if (leftCurrent) return -1;
484
516
  if (rightCurrent) return 1;
517
+ const leftAttention = attentionForSession(api, left.session.opencode_session_id);
518
+ const rightAttention = attentionForSession(api, right.session.opencode_session_id);
519
+ if (Boolean(leftAttention) !== Boolean(rightAttention)) return leftAttention ? -1 : 1;
485
520
  return (rank[left.session.state] ?? 9) - (rank[right.session.state] ?? 9)
486
521
  || String(right.session.updated_at || "").localeCompare(String(left.session.updated_at || ""));
487
522
  });
488
523
  const labels = { active: "Active", handed_off: "Handed off", abandoned: "Abandoned", closed: "Closed" };
489
524
  showSelect("Sessions", entries.map(({ workspace, session }) => {
490
525
  const current = session.opencode_session_id === sessionId || session.session_id === sessionId;
526
+ const unread = attentionForSession(api, session.opencode_session_id);
491
527
  return {
492
- title: `${workspace.id} ${sessionOrdinal(session)} ${session.summary || "Work session"} · ${workspace.title}`,
493
- description: `${session.state || "unknown"} · ${session.session_id}`,
528
+ title: `${unread ? "[ATTN] " : ""}${workspace.id} ${sessionOrdinal(session)} ${session.summary || "Work session"} · ${workspace.title}`,
529
+ description: `${unread ? `needs attention: ${attentionReasonText(unread.reason)} · ` : ""}${session.state || "unknown"} · ${session.session_id}`,
494
530
  footer: session.updated_at || session.started_at,
495
531
  category: current ? "Current" : labels[session.state] || session.state || "Unknown",
496
532
  value: { workspace, session },
@@ -541,7 +577,7 @@ export const openCompatibilityDialog = (api, runtime = {}, options = {}) => {
541
577
  watcher?.close();
542
578
  closeDialog(api);
543
579
  };
544
- const controller = createWorkContextModalController({ projectRoot, sessionId, read: options.read || readWorkContextSnapshot, createSignal: runtime.createSignal, onClose: close, onCommand: (command) => insertPromptCommand(api, command) });
580
+ const controller = createWorkContextModalController({ projectRoot, sessionId, read: options.read || readWorkContextSnapshot, createSignal: runtime.createSignal, attention: api.workContextAttention, onClose: close, onCommand: (command) => insertPromptCommand(api, command) });
545
581
  try { watcher = projectRoot && fs.watch(path.join(projectRoot, ".work-context"), { recursive: true }, () => controller.scheduleRefresh?.()); } catch {}
546
582
  const maxListHeight = Math.max(8, Math.floor((api.renderer?.height || 60) / 2) - 6);
547
583
  const render = () => renderWorkContextModal(controller, api.theme, runtime, { maxListHeight });
@@ -1,4 +1,5 @@
1
1
  import { readWorkContextSnapshot } from "../src/work-context-snapshot.js";
2
+ import { acknowledgeNavigation, attentionForSession, attentionReasonText } from "./attention.js";
2
3
 
3
4
  const SESSION_STATE_RANK = { active: 0, handed_off: 1, abandoned: 2, closed: 3 };
4
5
  const WORKSPACE_STATUS_RANK = { in_progress: 0, planned: 1, completed: 2, cancelled: 3 };
@@ -8,15 +9,19 @@ const currentSessionId = (api) => api?.route?.current?.params?.sessionID || api?
8
9
  const projectRoot = (api) => api?.state?.path?.worktree || api?.state?.path?.directory;
9
10
 
10
11
  /** Select the best existing OpenCode session without changing work-context state. */
11
- export const selectWorkspaceSession = (sessions = []) => sessions
12
+ export const selectWorkspaceSession = (sessions = [], attention) => sessions
12
13
  .filter((session) => session.opencode_session_id)
13
- .sort((left, right) => (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
14
+ .sort((left, right) => Number(Boolean(attention?.(right.opencode_session_id))) - Number(Boolean(attention?.(left.opencode_session_id)))
15
+ || (SESSION_STATE_RANK[left.state] ?? 9) - (SESSION_STATE_RANK[right.state] ?? 9)
14
16
  || String(right.updated_at || right.started_at || "").localeCompare(String(left.updated_at || left.started_at || ""))
15
17
  || Number(right.ordinal || 0) - Number(left.ordinal || 0))[0] || null;
16
18
 
17
- export const sortWorkspaceSwitcherEntries = (workspaces = [], currentWorkspace = null) => [...workspaces].sort((left, right) => {
19
+ export const sortWorkspaceSwitcherEntries = (workspaces = [], currentWorkspace = null, attention) => [...workspaces].sort((left, right) => {
18
20
  if (left.id === currentWorkspace) return -1;
19
21
  if (right.id === currentWorkspace) return 1;
22
+ const leftAttention = Boolean(attention?.(left.id));
23
+ const rightAttention = Boolean(attention?.(right.id));
24
+ if (leftAttention !== rightAttention) return leftAttention ? -1 : 1;
20
25
  return (WORKSPACE_STATUS_RANK[left.status] ?? 9) - (WORKSPACE_STATUS_RANK[right.status] ?? 9)
21
26
  || left.id.localeCompare(right.id);
22
27
  });
@@ -24,8 +29,10 @@ export const sortWorkspaceSwitcherEntries = (workspaces = [], currentWorkspace =
24
29
  const navigateToSession = (api, sessionID) => {
25
30
  if (typeof api?.route?.navigate !== "function") return errorResult("SESSION_SWITCH_UNAVAILABLE", "This OpenCode host cannot switch sessions from a TUI plugin");
26
31
  try {
32
+ const observed = attentionForSession(api, sessionID)?.eventKey;
27
33
  api.ui?.dialog?.clear?.();
28
34
  api.route.navigate("session", { sessionID });
35
+ acknowledgeNavigation(api, sessionID, observed);
29
36
  return { ok: true, data: { opencode_session_id: sessionID, created: false } };
30
37
  } catch (error) {
31
38
  return errorResult(error.code || "SESSION_SWITCH_ERROR", error.message || "OpenCode could not open the selected session");
@@ -49,8 +56,10 @@ export const createWorkspaceSwitcherFlow = (api, { read = readWorkContextSnapsho
49
56
  return result;
50
57
  }
51
58
  const data = result.data || {};
52
- const workspaces = sortWorkspaceSwitcherEntries(data.workspaces || [], data.currentWorkspace)
53
- .map((workspace) => ({ ...workspace, selectedSession: selectWorkspaceSession(workspace.sessions) }));
59
+ const workspaceAttention = (id) => api.workContextAttention?.attentionForWorkspace?.(id);
60
+ const sessionAttention = (id) => attentionForSession(api, id);
61
+ const workspaces = sortWorkspaceSwitcherEntries(data.workspaces || [], data.currentWorkspace, workspaceAttention)
62
+ .map((workspace) => ({ ...workspace, attention: workspaceAttention(workspace.id), selectedSession: selectWorkspaceSession(workspace.sessions, sessionAttention) }));
54
63
  if (!workspaces.length) {
55
64
  toast("No workspaces found");
56
65
  return result;
@@ -60,9 +69,9 @@ export const createWorkspaceSwitcherFlow = (api, { read = readWorkContextSnapsho
60
69
  title: "Switch workspace",
61
70
  placeholder: "Search workspaces",
62
71
  options: workspaces.map((workspace) => ({
63
- title: `${workspace.id} ${workspace.title}${workspace.id === data.currentWorkspace ? " · current" : ""}`,
72
+ title: `${workspace.attention ? "[ATTN] " : ""}${workspace.id} ${workspace.title}${workspace.id === data.currentWorkspace ? " · current" : ""}`,
64
73
  description: workspace.selectedSession
65
- ? `${workspace.status} · ${workspace.selectedSession.state || "unknown"} session`
74
+ ? `${workspace.attention ? `needs attention: ${attentionReasonText(workspace.attention.reason)} (${workspace.attention.count}) · ` : ""}${workspace.status} · ${workspace.selectedSession.state || "unknown"} session`
66
75
  : `${workspace.status} · no OpenCode session available`,
67
76
  category: workspace.id === data.currentWorkspace ? "Current" : workspace.status,
68
77
  disabled: !workspace.selectedSession,
package/src/storage.js CHANGED
@@ -288,7 +288,7 @@ export class FileStorage {
288
288
 
289
289
  export function loadConfig(projectRoot, configFile = path.resolve(projectRoot, ".work-context", "config.yaml")) {
290
290
  if (!fs.existsSync(configFile)) return {};
291
- const data = Object.assign(Object.create(null), { storage: Object.create(null), title: Object.create(null), tracker: Object.create(null) });
291
+ const data = Object.assign(Object.create(null), { storage: Object.create(null), title: Object.create(null), tracker: Object.create(null), notifications: Object.create(null) });
292
292
  let section = null;
293
293
  for (const line of fs.readFileSync(configFile, "utf8").split("\n")) {
294
294
  if (!line.trim() || line.trim().startsWith("#")) continue;
@@ -296,8 +296,8 @@ export function loadConfig(projectRoot, configFile = path.resolve(projectRoot, "
296
296
  if (!match[1]) { section = match[3] ? null : match[2]; if (match[3]) data[match[2]] = scalarConfig(match[3]); else if (!data[match[2]] || typeof data[match[2]] !== "object") data[match[2]] = Object.create(null); continue; }
297
297
  if (section && data[section] && typeof data[section] === "object") data[section][match[2]] = scalarConfig(match[3]);
298
298
  }
299
- if (Object.keys(data).some((key) => !["schema", "storage", "title", "tracker"].includes(key)) || Object.keys(data.storage).some((key) => !["mode", "root", "personal_root"].includes(key)) || Object.keys(data.title).some((key) => key !== "issue_prefix") || Object.keys(data.tracker).some((key) => key !== "provider") || data.schema !== 1 || !data.storage || !["personal", "shared-git", "hybrid"].includes(data.storage.mode) || typeof data.storage.root !== "string" || typeof data.storage.personal_root !== "string" || !data.title || !["none", "short", "full"].includes(data.title.issue_prefix) || !data.tracker || (data.tracker.provider !== null && typeof data.tracker.provider !== "string")) fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
299
+ if (Object.keys(data).some((key) => !["schema", "storage", "title", "tracker", "notifications"].includes(key)) || Object.keys(data.storage).some((key) => !["mode", "root", "personal_root"].includes(key)) || Object.keys(data.title).some((key) => key !== "issue_prefix") || Object.keys(data.tracker).some((key) => key !== "provider") || !data.notifications || typeof data.notifications !== "object" || Array.isArray(data.notifications) || Object.keys(data.notifications).some((key) => key !== "desktop") || data.schema !== 1 || !data.storage || !["personal", "shared-git", "hybrid"].includes(data.storage.mode) || typeof data.storage.root !== "string" || typeof data.storage.personal_root !== "string" || !data.title || !["none", "short", "full"].includes(data.title.issue_prefix) || !data.tracker || (data.tracker.provider !== null && typeof data.tracker.provider !== "string") || (data.notifications.desktop !== undefined && typeof data.notifications.desktop !== "boolean")) fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
300
300
  return data;
301
301
  }
302
302
  const scalarConfig = (value) => value === "null" ? null : value === "[]" ? [] : value === "{}" ? {} : /^(true|false)$/.test(value) ? value === "true" : /^-?\d+(\.\d+)?$/.test(value) ? Number(value) : value;
303
- export const defaultConfig = () => `schema: 1\nstorage:\n mode: hybrid\n root: .work-context\n personal_root: .work-context/local\ntitle:\n issue_prefix: short\ntracker:\n provider: null\n`;
303
+ export const defaultConfig = () => `schema: 1\nstorage:\n mode: hybrid\n root: .work-context\n personal_root: .work-context/local\ntitle:\n issue_prefix: short\ntracker:\n provider: null\nnotifications:\n desktop: true\n`;