opencode-work-context 0.4.9 → 0.4.11

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.4.9",
4
+ "version": "0.4.11",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -163,6 +163,30 @@ export const switchToStage = async (api, stage, options = {}) => {
163
163
 
164
164
  export const createStageSwitcherFlow = (api, { read = readStageSwitcherSnapshot, start = startStageSession } = {}) => {
165
165
  const toast = (message, variant = "warning") => api?.ui?.toast?.({ message, variant });
166
+ const select = async (stageId) => {
167
+ let result;
168
+ try { result = await read({ projectRoot: projectRoot(api), sessionId: currentSessionId(api) }); }
169
+ catch (error) { result = errorResult(error.code || "STORAGE_ERROR", error.message || "Cannot read work-context storage"); }
170
+ if (!result?.ok) {
171
+ toast(`${result?.error?.code || "STORAGE_ERROR"}: ${result?.error?.message || "Cannot read work-context storage"}`, "error");
172
+ return result;
173
+ }
174
+ const stage = result.data.stages.find((item) => item.id === stageId);
175
+ if (!stage) {
176
+ const missing = errorResult("NOT_FOUND", "The selected work-context stage no longer exists");
177
+ toast(`${missing.error.code}: ${missing.error.message}`, "error");
178
+ return missing;
179
+ }
180
+ const selected = {
181
+ ...stage,
182
+ attention: api.workContextAttention?.attentionForStage?.(result.data.workspace.id, stage.id),
183
+ selectedSession: selectStageSession(stage.sessions, (id) => attentionForSession(api, id)),
184
+ };
185
+ const switched = await switchToStage(api, selected, { workspace: result.data.workspace.id, currentStage: result.data.currentStage, start });
186
+ if (!switched.ok) toast(`${switched.error.code}: ${switched.error.message}`, "error");
187
+ else toast(switched.data.created ? "Stage session created" : "Stage session opened", "success");
188
+ return switched;
189
+ };
166
190
  const open = async () => {
167
191
  let result;
168
192
  try { result = await read({ projectRoot: projectRoot(api), sessionId: currentSessionId(api) }); }
@@ -201,14 +225,12 @@ export const createStageSwitcherFlow = (api, { read = readStageSwitcherSnapshot,
201
225
  ...ordinary.map((stage) => optionFor(stage, stage.status)),
202
226
  ],
203
227
  onSelect: (option) => void (async () => {
204
- const switched = await switchToStage(api, option.value, { workspace: workspace.id, currentStage: result.data.currentStage, start });
205
- if (!switched.ok) toast(`${switched.error.code}: ${switched.error.message}`, "error");
206
- else toast(switched.data.created ? "Stage session created" : "Stage session opened", "success");
228
+ await select(option.value.id);
207
229
  })(),
208
230
  }));
209
231
  return result;
210
232
  };
211
- return { open };
233
+ return { open, select };
212
234
  };
213
235
 
214
236
  export const openStageSwitcher = (api, options = {}) => {
@@ -1,10 +1,12 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { readStagesSnapshot } from "../src/stages-snapshot.js";
4
- import { renderStagesPanel } from "../src/stages-renderer.js";
4
+ import { renderDependencyTree, renderStagesPanel } from "../src/stages-renderer.js";
5
5
  import { jsx } from "@opentui/solid/jsx-runtime";
6
6
  import { createSignal } from "solid-js";
7
7
  import { attentionReasonText } from "./attention.js";
8
+ import { createStageSwitcherFlow } from "./stage-switcher.js";
9
+ import { readTuiState, updateTuiState } from "./tui-state.js";
8
10
 
9
11
  const DEBOUNCE_MS = 150;
10
12
  const POLL_MS = 1000;
@@ -13,6 +15,10 @@ const PATH_POLL_MS = 25;
13
15
  const WORK_CONTEXT_PREFIX = "work" + "_" + "context_";
14
16
  const activeTuiInstances = new WeakMap();
15
17
  const ACTIVE_TUI_KEY = Symbol.for("opencode-work-context.stages-tui");
18
+ const DEPENDENCIES_COMMAND = "work_context.toggle_dependencies";
19
+ const DEPENDENCIES_SHORTCUT = "<leader>d";
20
+ const TREE_COMMAND = "work_context.show_dependency_tree";
21
+ const TREE_SHORTCUT = "<leader>t";
16
22
  const statusMarker = (status) => ({
17
23
  planned: "[ ]",
18
24
  in_progress: "[•]",
@@ -25,7 +31,7 @@ export { readStagesSnapshot, renderStagesPanel };
25
31
 
26
32
  const defaultRuntime = { jsx };
27
33
 
28
- const renderStagesContent = (result, theme, runtime = defaultRuntime, attention) => !result?.ok || !result.data?.workspace
34
+ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention, showDependencies = true, onStageSelect) => !result?.ok || !result.data?.workspace
29
35
  ? [
30
36
  runtime.jsx("text", { children: runtime.jsx("b", { children: "Stages" }) }),
31
37
  ...renderStagesPanel(result).split("\n").slice(1).map((line) => runtime.jsx("text", { children: line })),
@@ -46,18 +52,22 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention)
46
52
  const unread = attention?.attentionForStage?.(result.data.workspace.id, stage.id);
47
53
  return runtime.jsx("box", {
48
54
  flexDirection: "row",
55
+ onMouseDown: (event) => {
56
+ if (event?.button != null && event.button !== 0) return;
57
+ return onStageSelect?.(stage);
58
+ },
49
59
  children: [
50
60
  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}` : ""}]` : ""}` }),
61
+ 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}${showDependencies && stage.depends_on?.length ? `\nDeps: ${stage.depends_on.join(", ")}` : ""}${unread ? ` [ATTN: ${attentionReasonText(unread.reason)}${unread.count > 1 ? ` x${unread.count}` : ""}]` : ""}` }),
52
62
  ],
53
63
  });
54
64
  }),
55
65
  ];
56
66
 
57
- export const renderStagesElement = (result, theme, runtime = defaultRuntime, attention) => {
67
+ export const renderStagesElement = (result, theme, runtime = defaultRuntime, attention, showDependencies = true, onStageSelect) => {
58
68
  return runtime.jsx("box", {
59
- flexDirection: "column",
60
- children: () => renderStagesContent(typeof result === "function" ? result() : result, theme, runtime, attention),
69
+ flexDirection: "column",
70
+ children: () => renderStagesContent(typeof result === "function" ? result() : result, theme, runtime, attention, typeof showDependencies === "function" ? showDependencies() : showDependencies, onStageSelect),
61
71
  });
62
72
  };
63
73
 
@@ -99,6 +109,7 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
99
109
  const timers = new Map();
100
110
  const pollers = new Map();
101
111
  const [version, setVersion] = makeSignal(0);
112
+ const [showDependencies, setShowDependencies] = makeSignal(readTuiState(projectRoot).sidebar_dependencies === true);
102
113
  let disposed = false;
103
114
  const unsubscribeAttention = attention?.subscribe?.(() => setVersion((value) => value + 1));
104
115
 
@@ -160,6 +171,13 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
160
171
  load: readSnapshot,
161
172
  scheduleRefresh,
162
173
  resultFor,
174
+ showDependencies,
175
+ toggleDependencies: () => {
176
+ const visible = !showDependencies();
177
+ setShowDependencies(visible);
178
+ updateTuiState(projectRoot, (state) => ({ ...state, sidebar_dependencies: visible }));
179
+ return visible;
180
+ },
163
181
  dispose: () => {
164
182
  if (disposed) return;
165
183
  disposed = true;
@@ -197,11 +215,74 @@ export const resolveProjectRoot = async (api, { timeoutMs = PATH_TIMEOUT_MS, pol
197
215
  return null;
198
216
  };
199
217
 
200
- const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime, attention) => runtime.jsx("box", {
218
+ const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime, attention, onStageSelect) => runtime.jsx("box", {
201
219
  flexDirection: "column",
202
- children: renderStagesElement(() => controller.resultFor(sessionId), theme, runtime, attention),
220
+ children: renderStagesElement(() => controller.resultFor(sessionId), theme, runtime, attention, controller.showDependencies, onStageSelect),
203
221
  });
204
222
 
223
+ const registerDependencyToggle = (api, controller) => {
224
+ if (typeof api?.keymap?.registerLayer !== "function") return () => {};
225
+ const command = {
226
+ name: DEPENDENCIES_COMMAND,
227
+ title: "Toggle sidebar dependencies",
228
+ desc: "Show or hide dependency IDs in the stages sidebar",
229
+ category: "Work Context",
230
+ namespace: "palette",
231
+ run: () => controller.toggleDependencies(),
232
+ };
233
+ return api.keymap.registerLayer({
234
+ commands: [command],
235
+ bindings: [{ key: DEPENDENCIES_SHORTCUT, cmd: DEPENDENCIES_COMMAND, desc: command.title }],
236
+ });
237
+ };
238
+
239
+ export const dependencyTreeOptions = (stages, width = 80) => {
240
+ const narrow = width < 50;
241
+ const tree = renderDependencyTree(stages, {
242
+ compact: narrow,
243
+ maxTitleLength: narrow ? Math.max(12, width - 18) : undefined,
244
+ });
245
+ return [
246
+ { title: "Close", value: "close", category: "Dependency tree" },
247
+ ...tree.split("\n").map((line) => ({ title: line, value: line, category: "Dependency tree" })),
248
+ ];
249
+ };
250
+
251
+ export const openDependencyTreeDialog = (api, result) => {
252
+ if (typeof api?.ui?.DialogSelect !== "function" || typeof api?.ui?.dialog?.replace !== "function") return false;
253
+ if (!result?.ok || !result.data?.workspace) {
254
+ api.ui?.toast?.({ message: "No work-context stages are available", variant: "warning" });
255
+ return false;
256
+ }
257
+ const width = api.renderer?.width || 80;
258
+ api.ui.dialog.setSize?.(width < 50 ? "small" : "large");
259
+ api.ui.dialog.replace(() => api.ui.DialogSelect({
260
+ title: `Dependency tree · ${result.data.workspace.title}`,
261
+ placeholder: "Dependency tree",
262
+ options: dependencyTreeOptions(result.data.stages, width),
263
+ onSelect: (option) => {
264
+ if (option.value === "close") api.ui.dialog.clear?.();
265
+ },
266
+ }));
267
+ return true;
268
+ };
269
+
270
+ const registerDependencyTree = (api, controller, sessionId) => {
271
+ if (typeof api?.keymap?.registerLayer !== "function") return () => {};
272
+ const command = {
273
+ name: TREE_COMMAND,
274
+ title: "Show dependency tree",
275
+ desc: "Open the full work-context dependency tree",
276
+ category: "Work Context",
277
+ namespace: "palette",
278
+ run: () => openDependencyTreeDialog(api, controller.resultFor(sessionId())),
279
+ };
280
+ return api.keymap.registerLayer({
281
+ commands: [command],
282
+ bindings: [{ key: TREE_SHORTCUT, cmd: TREE_COMMAND, desc: command.title }],
283
+ });
284
+ };
285
+
205
286
  const ACTIVE_WORKSPACE_SESSION = "__active_" + "work" + "_context_workspace__";
206
287
 
207
288
  // Optional TUI entry point. It is deliberately not imported by the server plugin.
@@ -223,8 +304,11 @@ export const tui = async (api, options = {}) => {
223
304
  createSignal: options.runtime?.createSignal,
224
305
  attention: api.workContextAttention,
225
306
  });
226
- await controller.load(initialSessionId);
307
+ const stageSwitcher = createStageSwitcherFlow(api);
308
+ const unregisterDependencyToggle = registerDependencyToggle(api, controller);
227
309
  let currentSessionId = initialSessionId;
310
+ const unregisterDependencyTree = registerDependencyTree(api, controller, () => currentSessionId || ACTIVE_WORKSPACE_SESSION);
311
+ await controller.load(initialSessionId);
228
312
  let storageWatcher;
229
313
  try {
230
314
  storageWatcher = fs.watch(path.join(projectRoot, ".work-context"), { recursive: true }, () => {
@@ -241,7 +325,7 @@ export const tui = async (api, options = {}) => {
241
325
  sidebar_content: (slotContext = {}, slotState = {}) => {
242
326
  const sessionId = sessionIdForSlot(api, initialSessionId, slotContext, slotState) || ACTIVE_WORKSPACE_SESSION;
243
327
  currentSessionId = sessionId;
244
- return renderStagesSlot(controller, api.theme, sessionId, options.runtime, api.workContextAttention);
328
+ return renderStagesSlot(controller, api.theme, sessionId, options.runtime, api.workContextAttention, (stage) => stageSwitcher.select(stage.id));
245
329
  },
246
330
  },
247
331
  });
@@ -263,6 +347,8 @@ export const tui = async (api, options = {}) => {
263
347
  disposeRegistration(unsubscribe);
264
348
  disposeRegistration(unsubscribeTool);
265
349
  disposeRegistration(unregisterSlot);
350
+ disposeRegistration(unregisterDependencyToggle);
351
+ disposeRegistration(unregisterDependencyTree);
266
352
  };
267
353
  api[ACTIVE_TUI_KEY] = cleanup;
268
354
  activeTuiInstances.set(api, cleanup);
@@ -6,6 +6,49 @@ const statusMarker = (status) => ({
6
6
  archived: "[-]",
7
7
  }[status] || "[?]");
8
8
 
9
+ const compareStageIds = (left, right) => Number(left.id) - Number(right.id);
10
+
11
+ /**
12
+ * Render normalized stages as a dependency-to-dependent forest. A stage may
13
+ * appear more than once when multiple dependency paths reach the same join.
14
+ */
15
+ export function renderDependencyTree(stages, { compact = false, maxTitleLength } = {}) {
16
+ const sortedStages = [...stages].sort(compareStageIds);
17
+ const byId = new Map(sortedStages.map((stage) => [stage.id, stage]));
18
+ const dependents = new Map(sortedStages.map((stage) => [stage.id, []]));
19
+
20
+ for (const stage of sortedStages) {
21
+ for (const dependency of stage.depends_on || []) {
22
+ dependents.get(dependency)?.push(stage);
23
+ }
24
+ }
25
+ for (const children of dependents.values()) children.sort(compareStageIds);
26
+
27
+ const roots = sortedStages.filter((stage) => !(stage.depends_on || []).some((dependency) => byId.has(dependency)));
28
+ const lines = [];
29
+ const branchCharacters = compact
30
+ ? { tee: "+- ", last: "\\- ", vertical: "| ", space: " " }
31
+ : { tee: "├─ ", last: "└─ ", vertical: "│ ", space: " " };
32
+ const stageTitle = (title) => maxTitleLength && title.length > maxTitleLength
33
+ ? `${title.slice(0, Math.max(1, maxTitleLength - 3))}...`
34
+ : title;
35
+ const render = (stage, prefix, branch, ancestors) => {
36
+ const cycle = ancestors.has(stage.id);
37
+ lines.push(`${prefix}${branch}${statusMarker(stage.status)} ${stage.id}. ${stageTitle(stage.title)}${cycle ? " [cycle]" : ""}`);
38
+ if (cycle) return;
39
+
40
+ const children = dependents.get(stage.id) || [];
41
+ const nextAncestors = new Set(ancestors).add(stage.id);
42
+ children.forEach((child, index) => {
43
+ const last = index === children.length - 1;
44
+ render(child, `${prefix}${branch ? (branch === branchCharacters.last ? branchCharacters.space : branchCharacters.vertical) : ""}`, last ? branchCharacters.last : branchCharacters.tee, nextAncestors);
45
+ });
46
+ };
47
+
48
+ for (const root of roots.length ? roots : sortedStages.slice(0, 1)) render(root, "", "", new Set());
49
+ return lines.join("\n");
50
+ }
51
+
9
52
  export function renderStagesPanel(result) {
10
53
  if (!result?.ok) return `work-context stages\n! unavailable: ${result?.error?.code || "STORAGE_ERROR"}`;
11
54
  const snapshot = result.data;
@@ -17,7 +60,7 @@ export function renderStagesPanel(result) {
17
60
  `Stages · ${snapshot.workspace.status}`,
18
61
  ];
19
62
  for (const stage of snapshot.stages) {
20
- lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}`);
63
+ lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${stage.depends_on?.length ? `\nDeps: ${stage.depends_on.join(", ")}` : ""}`);
21
64
  }
22
65
  if (result.stale) lines.push(`! stale: ${result.error?.code || "STORAGE_ERROR"}`);
23
66
  return lines.join("\n");
@@ -42,6 +42,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
42
42
  title: stage.title,
43
43
  status: stage.status,
44
44
  description: stage.description,
45
+ depends_on: stage.depends_on,
45
46
  current: stage.stage === session.stage,
46
47
  }));
47
48
  const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
@@ -43,6 +43,7 @@ const readWorkspace = (context, record, currentSession) => {
43
43
  title: stage.title,
44
44
  status: stage.status,
45
45
  description: stage.description,
46
+ depends_on: stage.depends_on,
46
47
  current: stage.stage === currentStage,
47
48
  })),
48
49
  currentStage,