opencode-work-context 0.2.1 → 0.4.1
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 +44 -0
- package/commands/wc.md +6 -0
- package/package.json +1 -1
- package/plugin/attention.js +364 -0
- package/plugin/notifier.js +83 -0
- package/plugin/session-switcher.js +14 -7
- package/plugin/stage-switcher.js +27 -26
- package/plugin/stages-tui.js +22 -15
- package/plugin/tui-state.js +31 -0
- package/plugin/tui.js +2 -0
- package/plugin/work-context-modal.js +74 -31
- package/plugin/workspace-switcher.js +16 -7
- package/src/core.js +65 -12
- package/src/storage.js +25 -5
- package/src/tool-definitions.js +3 -1
- package/tools/work_context_reopen_workspace.js +3 -0
- package/tools/work_context_restore_stage.js +3 -0
package/README.md
CHANGED
|
@@ -73,6 +73,13 @@ To correct a completed stage without discarding its result or session history,
|
|
|
73
73
|
use `/wc stage reopen <workspace> <stage> "reason"`. Reopening leaves
|
|
74
74
|
downstream stages unchanged and requires a separate-session explicit resume.
|
|
75
75
|
|
|
76
|
+
To recover an archived stage, use `/wc stage restore <workspace> <stage>
|
|
77
|
+
"reason"`. It restores the status saved during archiving and preserves the
|
|
78
|
+
stage body, result, and recovery history. Archives written by older versions
|
|
79
|
+
did not save their source status and restore to `in_progress`. To reopen an
|
|
80
|
+
accidentally completed workspace, use `/wc workspace reopen <workspace>
|
|
81
|
+
"reason"`; it only accepts `completed` workspaces, never cancelled ones.
|
|
82
|
+
|
|
76
83
|
When you return later, continue from the active stage. A stage must have a
|
|
77
84
|
non-empty prompt before implementation begins; if the prompt is missing or
|
|
78
85
|
ambiguous, `/wc resume` instructs the agent to ask focused questions first.
|
|
@@ -215,6 +222,41 @@ The shortcut is registered with the public keymap layer. If another plugin or
|
|
|
215
222
|
terminal reserves `Ctrl+X`, remove or change the conflicting binding, or
|
|
216
223
|
disable this TUI loader; the package does not use an internal keymap fallback.
|
|
217
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
|
+
To verify an installed project manually, install the distribution package that
|
|
252
|
+
provides `notify-send` (commonly `libnotify-bin`), ensure `notify-send "Test"`
|
|
253
|
+
appears in the current desktop session, restart OpenCode, start work in a linked
|
|
254
|
+
session, and switch to another native session before the first one finishes or
|
|
255
|
+
asks a question. Expect one desktop notification and a persistent `[ATTN]`
|
|
256
|
+
marker. Open the affected native session to clear the marker. Set
|
|
257
|
+
`notifications.desktop` to `false`, restart OpenCode, and repeat to verify that
|
|
258
|
+
only the marker remains.
|
|
259
|
+
|
|
218
260
|
Tools are registered by the installed server export and are not copied into the
|
|
219
261
|
project. Core and storage remain in the installed package; projects should not
|
|
220
262
|
copy `src/` or `tools/`. `.work-context` Markdown, JSONL, `INDEX.md`, and
|
|
@@ -243,6 +285,8 @@ accepted only after every stage is `completed`. Use `/wc workspace list <workspa
|
|
|
243
285
|
to list stages with their descriptions. Workspace titles can be changed with
|
|
244
286
|
`/wc workspace rename <workspace> "title"`, and existing stage descriptions can
|
|
245
287
|
be changed with `/wc stage update <workspace> <stage> "description"`.
|
|
288
|
+
`/wc workspace reopen <workspace> "reason"` records a recovery entry and returns
|
|
289
|
+
only a completed workspace to `in_progress`.
|
|
246
290
|
|
|
247
291
|
If the host `opencode.json` restricts `experimental.primary_tools`, add the
|
|
248
292
|
registered `work_context_*` tool names to that allowlist; the installer does not
|
package/commands/wc.md
CHANGED
|
@@ -19,10 +19,12 @@ Use these exact tool mappings; do not invent shortened tool names:
|
|
|
19
19
|
- `workspace list <workspace>` or `<workspace> list` -> `work_context_workspace_list`
|
|
20
20
|
- `workspace rename <workspace> "title"` -> `work_context_rename_workspace`
|
|
21
21
|
- `workspace finish <workspace>` -> `work_context_workspace_finish`
|
|
22
|
+
- `workspace reopen <workspace> "reason"` -> `work_context_reopen_workspace`
|
|
22
23
|
- `resume <workspace> <stage>` -> `work_context_start_session`
|
|
23
24
|
- `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE` -> `work_context_force_close_session`
|
|
24
25
|
- `stage add [<workspace>] ...` -> `work_context_add_stage` (optional `prompt`; a detailed local prompt is expected for stages created from planning, while shared context belongs in workspace knowledge)
|
|
25
26
|
- `stage reopen <workspace> <stage> "reason"` -> `work_context_reopen_stage`
|
|
27
|
+
- `stage restore <workspace> <stage> "reason"` -> `work_context_restore_stage`
|
|
26
28
|
- `stage rename [<workspace>] [<stage>] "title"` -> `work_context_rename_stage`
|
|
27
29
|
- `stage update [<workspace>] [<stage>] "description"` -> `work_context_update_stage`
|
|
28
30
|
- `stage update-prompt [<workspace>] [<stage>] "prompt"` -> `work_context_update_stage_prompt`
|
|
@@ -40,10 +42,12 @@ Supported syntax:
|
|
|
40
42
|
- `workspace list <workspace>`
|
|
41
43
|
- `workspace rename <workspace> "title"`
|
|
42
44
|
- `workspace finish <workspace>`
|
|
45
|
+
- `workspace reopen <workspace> "reason"`
|
|
43
46
|
- `resume <workspace> <stage>`
|
|
44
47
|
- `stage force-close <workspace> <stage> <sessionId> "reason" FORCE_CLOSE`
|
|
45
48
|
- `stage add [<workspace>] "title" ["prompt"]`
|
|
46
49
|
- `stage reopen <workspace> <stage> "reason"`
|
|
50
|
+
- `stage restore <workspace> <stage> "reason"`
|
|
47
51
|
- `stage rename [<workspace>] [<stage>] "title"`
|
|
48
52
|
- `stage update [<workspace>] [<stage>] "description"`
|
|
49
53
|
- `stage update-prompt [<workspace>] [<stage>] "prompt"`
|
|
@@ -76,6 +80,8 @@ Supported syntax:
|
|
|
76
80
|
- `stage finish` closes and completes only the current stage session; it never starts, resumes, or binds the same OpenCode session to a downstream stage
|
|
77
81
|
- `stage finish` always validates the Knowledge Base and returns total and active entry counts plus downstream unfinished stages for informational prompt review; do not begin a downstream stage until the user explicitly resumes it in a separate OpenCode session
|
|
78
82
|
- `stage reopen <workspace> <stage> "reason"` applies only to a completed stage, preserves its result and completion history, records the reason, changes it to `in_progress`, and does not start a session or affect downstream stages; use an explicit separate-session `resume` to work on it again
|
|
83
|
+
- `stage restore <workspace> <stage> "reason"` applies only to an archived stage and restores its saved pre-archive status. New archives preserve that status; legacy archives restore to `in_progress`. It records the reason, preserves stage content and results, does not start a session, and requires explicit separate-session `resume` when restored to `planned` or `in_progress`.
|
|
84
|
+
- `workspace reopen <workspace> "reason"` applies only to a completed workspace, changes it to `in_progress`, and records durable recovery history. Cancelled workspaces cannot be reopened.
|
|
79
85
|
- `knowledge list|add|update|supersede <workspace> ...`
|
|
80
86
|
|
|
81
87
|
Arguments: $ARGUMENTS
|
package/package.json
CHANGED
|
@@ -0,0 +1,364 @@
|
|
|
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 { readTuiState, updateTuiState } from "./tui-state.js";
|
|
6
|
+
|
|
7
|
+
const ATTENTION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
8
|
+
const MAX_SEEN_EVENTS = 500;
|
|
9
|
+
const MAX_SESSIONS = 100;
|
|
10
|
+
const ACTIVE_ATTENTION_KEY = Symbol.for("opencode-work-context.attention");
|
|
11
|
+
const activeControllers = new WeakMap();
|
|
12
|
+
const PRIORITY = { idle: 1, question: 2, permission: 3, error: 4 };
|
|
13
|
+
const REASON_TEXT = { idle: "response complete", question: "question", permission: "permission", error: "error" };
|
|
14
|
+
const EVENT_TYPES = [
|
|
15
|
+
"session.status",
|
|
16
|
+
"session.idle",
|
|
17
|
+
"question.asked",
|
|
18
|
+
"question.v2.asked",
|
|
19
|
+
"permission.asked",
|
|
20
|
+
"permission.v2.asked",
|
|
21
|
+
"session.error",
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
const stableHash = (parts) => createHash("sha256").update(parts.map((part) => String(part ?? "")).join("\0")).digest("hex").slice(0, 24);
|
|
25
|
+
const eventBody = (event) => event?.properties || event?.data || {};
|
|
26
|
+
const eventSessionId = (event) => {
|
|
27
|
+
const body = eventBody(event);
|
|
28
|
+
return body.sessionID || body.sessionId || body.session_id || event?.sessionID || event?.sessionId || event?.session_id;
|
|
29
|
+
};
|
|
30
|
+
const eventKey = (event, kind, cycle) => {
|
|
31
|
+
const body = eventBody(event);
|
|
32
|
+
const hostId = body.id || body.requestID || event?.id;
|
|
33
|
+
if (hostId) return `${event.type}:${hostId}`;
|
|
34
|
+
const tool = body.tool || {};
|
|
35
|
+
const error = body.error || {};
|
|
36
|
+
return `${event.type}:fallback:${stableHash([
|
|
37
|
+
eventSessionId(event),
|
|
38
|
+
kind,
|
|
39
|
+
cycle,
|
|
40
|
+
event?.durable?.aggregateID,
|
|
41
|
+
event?.durable?.seq,
|
|
42
|
+
tool.messageID,
|
|
43
|
+
tool.callID,
|
|
44
|
+
error.name,
|
|
45
|
+
error.code,
|
|
46
|
+
])}`;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export const normalizeAttentionEvent = (event, cycle = 0) => {
|
|
50
|
+
const sessionId = eventSessionId(event);
|
|
51
|
+
if (!sessionId || !EVENT_TYPES.includes(event?.type)) return null;
|
|
52
|
+
const body = eventBody(event);
|
|
53
|
+
if (event.type === "session.status") {
|
|
54
|
+
const status = typeof body.status === "string" ? body.status : body.status?.type;
|
|
55
|
+
if (!status || !["busy", "retry", "idle"].includes(status)) return null;
|
|
56
|
+
return { sessionId, kind: "status", status, key: eventKey(event, `status:${status}`, cycle) };
|
|
57
|
+
}
|
|
58
|
+
const kind = event.type === "session.idle"
|
|
59
|
+
? "idle"
|
|
60
|
+
: event.type.startsWith("question.")
|
|
61
|
+
? "question"
|
|
62
|
+
: event.type.startsWith("permission.")
|
|
63
|
+
? "permission"
|
|
64
|
+
: "error";
|
|
65
|
+
return { sessionId, kind, key: eventKey(event, kind, cycle) };
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export const attentionReasonText = (reason) => REASON_TEXT[reason] || "attention";
|
|
69
|
+
export const attentionForSession = (api, sessionId) => api?.workContextAttention?.attentionFor?.(sessionId) || null;
|
|
70
|
+
export const acknowledgeNavigation = (api, sessionId, observedEventKey) => {
|
|
71
|
+
if (!sessionId || !observedEventKey) return false;
|
|
72
|
+
return api?.workContextAttention?.acknowledge?.(sessionId, observedEventKey) === true;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const validAttention = (value) => value
|
|
76
|
+
&& typeof value === "object"
|
|
77
|
+
&& typeof value.eventKey === "string"
|
|
78
|
+
&& Object.hasOwn(PRIORITY, value.reason)
|
|
79
|
+
&& Number.isFinite(value.revision)
|
|
80
|
+
&& typeof value.createdAt === "string"
|
|
81
|
+
&& typeof value.updatedAt === "string";
|
|
82
|
+
|
|
83
|
+
export const createAttentionEngine = ({ persisted, now = () => Date.now(), onChange } = {}) => {
|
|
84
|
+
const sessions = new Map();
|
|
85
|
+
const seen = new Map();
|
|
86
|
+
const listeners = new Set();
|
|
87
|
+
let revision = 0;
|
|
88
|
+
|
|
89
|
+
const notify = (change) => {
|
|
90
|
+
onChange?.(serialize());
|
|
91
|
+
for (const listener of listeners) listener(change);
|
|
92
|
+
};
|
|
93
|
+
const prune = () => {
|
|
94
|
+
const cutoff = now() - ATTENTION_TTL_MS;
|
|
95
|
+
for (const [key, timestamp] of seen) if (!Number.isFinite(timestamp) || timestamp < cutoff) seen.delete(key);
|
|
96
|
+
for (const [id, state] of sessions) if (!Number.isFinite(state.updatedAt) || state.updatedAt < cutoff) sessions.delete(id);
|
|
97
|
+
while (seen.size > MAX_SEEN_EVENTS) seen.delete(seen.keys().next().value);
|
|
98
|
+
const ordered = [...sessions.entries()].sort((left, right) => (right[1].updatedAt || 0) - (left[1].updatedAt || 0));
|
|
99
|
+
sessions.clear();
|
|
100
|
+
for (const [id, state] of ordered.slice(0, MAX_SESSIONS)) sessions.set(id, state);
|
|
101
|
+
};
|
|
102
|
+
const restore = () => {
|
|
103
|
+
if (!persisted || persisted.schema !== 1) return;
|
|
104
|
+
if (Array.isArray(persisted.seen)) {
|
|
105
|
+
for (const item of persisted.seen) {
|
|
106
|
+
if (Array.isArray(item) && typeof item[0] === "string" && Number.isFinite(item[1])) seen.set(item[0], item[1]);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (persisted.sessions && typeof persisted.sessions === "object" && !Array.isArray(persisted.sessions)) {
|
|
110
|
+
for (const [id, value] of Object.entries(persisted.sessions)) {
|
|
111
|
+
if (!id || !value || typeof value !== "object") continue;
|
|
112
|
+
const attention = validAttention(value.attention) ? { ...value.attention } : null;
|
|
113
|
+
revision = Math.max(revision, attention?.revision || 0);
|
|
114
|
+
sessions.set(id, {
|
|
115
|
+
busy: value.busy === true,
|
|
116
|
+
cycle: Number.isInteger(value.cycle) && value.cycle >= 0 ? value.cycle : 0,
|
|
117
|
+
attention,
|
|
118
|
+
updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : now(),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
prune();
|
|
123
|
+
};
|
|
124
|
+
const serialize = () => {
|
|
125
|
+
prune();
|
|
126
|
+
return {
|
|
127
|
+
schema: 1,
|
|
128
|
+
sessions: Object.fromEntries([...sessions].map(([id, state]) => [id, state])),
|
|
129
|
+
seen: [...seen],
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
const stateFor = (sessionId) => {
|
|
133
|
+
let state = sessions.get(sessionId);
|
|
134
|
+
if (!state) {
|
|
135
|
+
state = { busy: false, cycle: 0, attention: null, updatedAt: now() };
|
|
136
|
+
sessions.set(sessionId, state);
|
|
137
|
+
}
|
|
138
|
+
return state;
|
|
139
|
+
};
|
|
140
|
+
const applyAttention = (state, normalized, foreground) => {
|
|
141
|
+
if (foreground === normalized.sessionId) return { changed: false, suppressed: true };
|
|
142
|
+
const current = state.attention;
|
|
143
|
+
if (current && PRIORITY[normalized.kind] < PRIORITY[current.reason]) return { changed: false, suppressed: false };
|
|
144
|
+
const timestamp = new Date(now()).toISOString();
|
|
145
|
+
revision += 1;
|
|
146
|
+
state.attention = {
|
|
147
|
+
eventKey: normalized.key,
|
|
148
|
+
reason: normalized.kind,
|
|
149
|
+
revision,
|
|
150
|
+
createdAt: current?.createdAt || timestamp,
|
|
151
|
+
updatedAt: timestamp,
|
|
152
|
+
};
|
|
153
|
+
return { changed: true, suppressed: false, attention: { ...state.attention }, created: !current, upgraded: Boolean(current && PRIORITY[normalized.kind] > PRIORITY[current.reason]) };
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
restore();
|
|
157
|
+
return {
|
|
158
|
+
apply(event, { foreground } = {}) {
|
|
159
|
+
const initial = normalizeAttentionEvent(event);
|
|
160
|
+
if (!initial) return { changed: false, ignored: true };
|
|
161
|
+
const state = stateFor(initial.sessionId);
|
|
162
|
+
const normalized = normalizeAttentionEvent(event, state.cycle);
|
|
163
|
+
if (seen.has(normalized.key)) return { changed: false, duplicate: true };
|
|
164
|
+
seen.set(normalized.key, now());
|
|
165
|
+
state.updatedAt = now();
|
|
166
|
+
let result = { changed: false };
|
|
167
|
+
if (normalized.kind === "status") {
|
|
168
|
+
if (normalized.status === "busy" || normalized.status === "retry") {
|
|
169
|
+
if (!state.busy) state.cycle += 1;
|
|
170
|
+
state.busy = true;
|
|
171
|
+
} else if (state.busy) {
|
|
172
|
+
state.busy = false;
|
|
173
|
+
result = applyAttention(state, { ...normalized, kind: "idle" }, foreground);
|
|
174
|
+
}
|
|
175
|
+
} else if (normalized.kind === "idle") {
|
|
176
|
+
if (state.busy) {
|
|
177
|
+
state.busy = false;
|
|
178
|
+
result = applyAttention(state, normalized, foreground);
|
|
179
|
+
}
|
|
180
|
+
} else {
|
|
181
|
+
result = applyAttention(state, normalized, foreground);
|
|
182
|
+
}
|
|
183
|
+
prune();
|
|
184
|
+
notify({ sessionId: normalized.sessionId, ...result });
|
|
185
|
+
return { sessionId: normalized.sessionId, ...result };
|
|
186
|
+
},
|
|
187
|
+
acknowledge(sessionId, observedEventKey) {
|
|
188
|
+
const state = sessions.get(sessionId);
|
|
189
|
+
if (!state?.attention) return false;
|
|
190
|
+
if (observedEventKey && state.attention.eventKey !== observedEventKey) return false;
|
|
191
|
+
const acknowledged = { ...state.attention };
|
|
192
|
+
state.attention = null;
|
|
193
|
+
state.updatedAt = now();
|
|
194
|
+
notify({ sessionId, acknowledged });
|
|
195
|
+
return true;
|
|
196
|
+
},
|
|
197
|
+
attentionFor(sessionId) {
|
|
198
|
+
const attention = sessions.get(sessionId)?.attention;
|
|
199
|
+
return attention ? { ...attention } : null;
|
|
200
|
+
},
|
|
201
|
+
list() {
|
|
202
|
+
return [...sessions.entries()].flatMap(([sessionId, state]) => state.attention ? [{ sessionId, ...state.attention }] : []);
|
|
203
|
+
},
|
|
204
|
+
subscribe(listener) {
|
|
205
|
+
listeners.add(listener);
|
|
206
|
+
return () => listeners.delete(listener);
|
|
207
|
+
},
|
|
208
|
+
serialize,
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const currentSessionId = (api) => api?.route?.current?.name === "session"
|
|
213
|
+
? api.route.current.params?.sessionID || api.route.current.params?.sessionId || api.route.current.params?.session_id
|
|
214
|
+
: undefined;
|
|
215
|
+
const linkedSessionIds = (snapshot) => new Set((snapshot?.data?.workspaces || []).flatMap((workspace) =>
|
|
216
|
+
(workspace.sessions || []).map((session) => session.opencode_session_id).filter(Boolean)));
|
|
217
|
+
const notificationContexts = (snapshot, sessionId, reason) => {
|
|
218
|
+
const contexts = [];
|
|
219
|
+
const seen = new Set();
|
|
220
|
+
for (const workspace of snapshot?.workspaces || []) {
|
|
221
|
+
for (const session of workspace.sessions || []) {
|
|
222
|
+
if (session.opencode_session_id !== sessionId || !session.stage) continue;
|
|
223
|
+
const key = `${workspace.id}:${session.stage}`;
|
|
224
|
+
if (seen.has(key)) continue;
|
|
225
|
+
const stage = (workspace.stages || []).find((item) => item.id === session.stage);
|
|
226
|
+
if (!stage) continue;
|
|
227
|
+
seen.add(key);
|
|
228
|
+
contexts.push({
|
|
229
|
+
workspaceId: workspace.id,
|
|
230
|
+
workspaceTitle: workspace.title,
|
|
231
|
+
stageId: stage.id,
|
|
232
|
+
stageTitle: stage.title,
|
|
233
|
+
reason,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return contexts;
|
|
238
|
+
};
|
|
239
|
+
const disposeRegistration = (registration) => {
|
|
240
|
+
if (typeof registration === "function") registration();
|
|
241
|
+
else registration?.dispose?.();
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
export const desktopNotificationsEnabled = (projectRoot) => {
|
|
245
|
+
try { return loadConfig(projectRoot).notifications?.desktop !== false; } catch { return false; }
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
export const createAttentionTuiController = ({ api, projectRoot, read = readWorkContextSnapshot, onAttention, now } = {}) => {
|
|
249
|
+
const persisted = readTuiState(projectRoot).attention;
|
|
250
|
+
const engine = createAttentionEngine({
|
|
251
|
+
persisted,
|
|
252
|
+
now,
|
|
253
|
+
onChange: (attention) => updateTuiState(projectRoot, (state) => ({ ...state, attention })),
|
|
254
|
+
});
|
|
255
|
+
let linked = new Set();
|
|
256
|
+
let snapshot = null;
|
|
257
|
+
let disposed = false;
|
|
258
|
+
let pending = Promise.resolve();
|
|
259
|
+
const refresh = async () => {
|
|
260
|
+
try {
|
|
261
|
+
const result = await read({ projectRoot, sessionId: currentSessionId(api) });
|
|
262
|
+
if (result?.ok) {
|
|
263
|
+
linked = linkedSessionIds(result);
|
|
264
|
+
snapshot = result.data;
|
|
265
|
+
const current = currentSessionId(api);
|
|
266
|
+
if (current && linked.has(current)) engine.acknowledge(current);
|
|
267
|
+
}
|
|
268
|
+
} catch {}
|
|
269
|
+
return linked;
|
|
270
|
+
};
|
|
271
|
+
const process = async (event) => {
|
|
272
|
+
if (disposed) return { changed: false, ignored: true };
|
|
273
|
+
const sessionId = eventSessionId(event);
|
|
274
|
+
if (!sessionId) return { changed: false, ignored: true };
|
|
275
|
+
await refresh();
|
|
276
|
+
if (!linked.has(sessionId)) return { changed: false, unlinked: true };
|
|
277
|
+
const foreground = currentSessionId(api);
|
|
278
|
+
if (foreground === sessionId) engine.acknowledge(sessionId);
|
|
279
|
+
const result = engine.apply(event, { foreground });
|
|
280
|
+
if (result.changed) onAttention?.({
|
|
281
|
+
sessionId,
|
|
282
|
+
attention: result.attention,
|
|
283
|
+
created: result.created,
|
|
284
|
+
upgraded: result.upgraded,
|
|
285
|
+
contexts: notificationContexts(snapshot, sessionId, result.attention.reason),
|
|
286
|
+
});
|
|
287
|
+
return result;
|
|
288
|
+
};
|
|
289
|
+
const handle = (event) => {
|
|
290
|
+
const result = pending.then(() => process(event));
|
|
291
|
+
pending = result.catch(() => {});
|
|
292
|
+
return result;
|
|
293
|
+
};
|
|
294
|
+
const acknowledge = (sessionId, observedEventKey) => engine.acknowledge(sessionId, observedEventKey);
|
|
295
|
+
const aggregate = (matches) => {
|
|
296
|
+
const bySession = new Map();
|
|
297
|
+
for (const attention of engine.list()) {
|
|
298
|
+
const records = (snapshot?.workspaces || []).flatMap((workspace) => (workspace.sessions || [])
|
|
299
|
+
.filter((session) => session.opencode_session_id === attention.sessionId)
|
|
300
|
+
.map((session) => ({ workspace, session })));
|
|
301
|
+
if (records.some(matches)) bySession.set(attention.sessionId, attention);
|
|
302
|
+
}
|
|
303
|
+
const items = [...bySession.values()];
|
|
304
|
+
if (!items.length) return null;
|
|
305
|
+
const mostImportant = items.reduce((best, item) => PRIORITY[item.reason] > PRIORITY[best.reason] ? item : best);
|
|
306
|
+
return { count: items.length, reason: mostImportant.reason, items };
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
return {
|
|
310
|
+
refresh,
|
|
311
|
+
handle,
|
|
312
|
+
acknowledge,
|
|
313
|
+
attentionFor: engine.attentionFor,
|
|
314
|
+
attentionForStage: (workspace, stage) => aggregate((record) => record.workspace.id === workspace && record.session.stage === stage),
|
|
315
|
+
attentionForWorkspace: (workspace) => aggregate((record) => record.workspace.id === workspace),
|
|
316
|
+
list: engine.list,
|
|
317
|
+
subscribe: engine.subscribe,
|
|
318
|
+
dispose: () => { disposed = true; },
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
export const tui = async (api, options = {}) => {
|
|
323
|
+
if (!api?.event?.on) return;
|
|
324
|
+
if (activeControllers.has(api) || api[ACTIVE_ATTENTION_KEY]) return activeControllers.get(api) || api[ACTIVE_ATTENTION_KEY];
|
|
325
|
+
const projectRoot = api.state?.path?.worktree || api.state?.path?.directory;
|
|
326
|
+
if (!projectRoot) return;
|
|
327
|
+
const desktopNotifier = options.desktopNotifier || createDesktopNotifier({ enabled: desktopNotificationsEnabled(projectRoot), ...options.notifierOptions });
|
|
328
|
+
const controller = createAttentionTuiController({
|
|
329
|
+
api,
|
|
330
|
+
projectRoot,
|
|
331
|
+
read: api.attentionSnapshotProvider || readWorkContextSnapshot,
|
|
332
|
+
onAttention: (change) => {
|
|
333
|
+
try { options.onAttention?.(change); } catch {}
|
|
334
|
+
const context = change.contexts?.[0];
|
|
335
|
+
if (context) void Promise.resolve(desktopNotifier.notify(context)).catch(() => {});
|
|
336
|
+
},
|
|
337
|
+
now: options.now,
|
|
338
|
+
});
|
|
339
|
+
await controller.refresh();
|
|
340
|
+
const registrations = EVENT_TYPES.map((type) => api.event.on(type, (event) => { void controller.handle(event); }));
|
|
341
|
+
registrations.push(api.event.on("tui.session.select", (event) => {
|
|
342
|
+
queueMicrotask(() => {
|
|
343
|
+
const sessionId = currentSessionId(api);
|
|
344
|
+
if (sessionId) controller.acknowledge(sessionId);
|
|
345
|
+
});
|
|
346
|
+
}));
|
|
347
|
+
let cleaned = false;
|
|
348
|
+
const cleanup = () => {
|
|
349
|
+
if (cleaned) return;
|
|
350
|
+
cleaned = true;
|
|
351
|
+
controller.dispose();
|
|
352
|
+
for (const registration of registrations) disposeRegistration(registration);
|
|
353
|
+
if (activeControllers.get(api) === cleanup) activeControllers.delete(api);
|
|
354
|
+
if (api[ACTIVE_ATTENTION_KEY] === cleanup) delete api[ACTIVE_ATTENTION_KEY];
|
|
355
|
+
if (api.workContextAttention === controller) delete api.workContextAttention;
|
|
356
|
+
};
|
|
357
|
+
api.workContextAttention = controller;
|
|
358
|
+
api[ACTIVE_ATTENTION_KEY] = cleanup;
|
|
359
|
+
activeControllers.set(api, cleanup);
|
|
360
|
+
api.lifecycle?.onDispose?.(cleanup);
|
|
361
|
+
return cleanup;
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
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, "&")
|
|
22
|
+
.replace(/</g, "<")
|
|
23
|
+
.replace(/>/g, ">");
|
|
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
|
|
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,
|