pi-suite 0.3.7 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/package.json +7 -7
  2. package/src/agents/child.ts +9 -3
  3. package/src/agents/history.ts +3 -3
  4. package/src/agents/index.ts +22 -21
  5. package/src/agents/manager.ts +40 -12
  6. package/src/agents/records.ts +4 -2
  7. package/src/agents/runner.ts +15 -4
  8. package/src/agents/runtime.ts +1 -1
  9. package/src/agents/schedules/menu.ts +1 -1
  10. package/src/agents/types.ts +2 -1
  11. package/src/agents/ui/runs.ts +33 -13
  12. package/src/agents/viewer.ts +17 -11
  13. package/src/agents/workflow/index.ts +32 -9
  14. package/src/agents/workflow/manager.ts +18 -6
  15. package/src/agents/workflow/ui/menu.ts +2 -2
  16. package/src/jobs/backends/pipe.ts +5 -5
  17. package/src/jobs/index.ts +49 -36
  18. package/src/jobs/manager-record.ts +2 -2
  19. package/src/jobs/manager.ts +30 -12
  20. package/src/jobs/monitors/compile.ts +1 -1
  21. package/src/jobs/monitors/runtime.ts +44 -29
  22. package/src/jobs/store.ts +49 -10
  23. package/src/jobs/terminal/session.ts +5 -5
  24. package/src/jobs/terminal/shell.ts +11 -1
  25. package/src/jobs/tools.ts +2 -2
  26. package/src/jobs/types.ts +2 -0
  27. package/src/jobs/viewer/metadata.ts +6 -0
  28. package/src/jobs/viewer.ts +30 -25
  29. package/src/runtime/branch.ts +14 -0
  30. package/src/runtime/cleanup/command.ts +116 -0
  31. package/src/runtime/cleanup/locations.ts +91 -0
  32. package/src/runtime/cleanup/occupancy.ts +117 -0
  33. package/src/runtime/cleanup/paths.ts +44 -0
  34. package/src/runtime/cleanup/quarantine.ts +162 -0
  35. package/src/runtime/cleanup/scan.ts +297 -0
  36. package/src/runtime/cleanup/session-use.ts +62 -0
  37. package/src/runtime/cleanup/sessions.ts +119 -0
  38. package/src/runtime/json-store.ts +6 -0
  39. package/src/runtime/owner.ts +1 -1
  40. package/src/runtime/settings/index.ts +9 -1
  41. package/src/runtime/suite.ts +43 -1
  42. package/src/tasks/store.ts +18 -1
  43. package/src/tasks/viewer.ts +14 -12
  44. package/src/ui/actions.ts +1 -1
  45. package/src/ui/browser.ts +95 -43
  46. package/src/ui/scroll.ts +5 -1
@@ -0,0 +1,119 @@
1
+ import { createReadStream, type Dirent } from 'node:fs';
2
+ import { readdir, realpath } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { CURRENT_SESSION_VERSION, parseSessionEntries, type SessionEntry, type SessionHeader } from '@earendil-works/pi-coding-agent';
6
+ import { AGENT_ENTRY, decodeAgentRecord } from '../../agents/records.ts';
7
+ import type { AgentRecord } from '../../agents/types.ts';
8
+ import { WORKFLOW_ENTRY_TYPE, decodeWorkflowEntry, type WorkflowEntryData } from '../../agents/workflow/entry.ts';
9
+ import { SESSION_ID, verifyDirectory, type Directory, type Home } from './locations.ts';
10
+ import { inspect, matches, pathKey, stamp, type FileStamp } from './paths.ts';
11
+
12
+ export type References = {paths: Set<string>; ids: Set<string>};
13
+ export const references = (): References => ({paths: new Set(), ids: new Set()});
14
+ export const addId = (refs: References, id: unknown) => {
15
+ if (typeof id === 'string' && /^(?:(?:job|agent|run)_[a-f0-9]{8}|wf_[a-f0-9]{12})$/.test(id)) refs.ids.add(id);
16
+ };
17
+ export function addPath(refs: References, path: string | undefined): void {
18
+ if (!path) return;
19
+ if (!isAbsolute(path)) throw new Error(`Non-absolute history reference: ${path}`);
20
+ refs.paths.add(pathKey(path));
21
+ }
22
+ export function agentReferences(refs: References, record: AgentRecord): void {
23
+ addPath(refs, record.sessionFile); addId(refs, record.parentRunId);
24
+ }
25
+ export function workflowReferences(refs: References, record: WorkflowEntryData): void {
26
+ addPath(refs, record.recordPath); addId(refs, record.resumedFrom);
27
+ for (const child of record.children) agentReferences(refs, child);
28
+ }
29
+
30
+ export async function entries(base: string, path: string): Promise<Dirent[]> {
31
+ const info = await inspect(base, path);
32
+ if (!info) return [];
33
+ if (!info.isDirectory()) throw new Error(`Expected a directory: ${path}`);
34
+ return readdir(path, {withFileTypes: true});
35
+ }
36
+ export type SavedSession = {path: string; base: string; header: SessionHeader; agents: Map<string, AgentRecord>;
37
+ workflows: Map<string, WorkflowEntryData>; refs: References; stamp: FileStamp; child: boolean};
38
+
39
+ const idTools = new Set(['job_get', 'job_read', 'job_stop', 'job_write', 'agent_get', 'agent_read', 'agent_send', 'agent_stop']);
40
+ export function collectReferences(refs: References, entry: SessionEntry, path: string): void {
41
+ if (entry.type === 'custom' && entry.customType === AGENT_ENTRY) agentReferences(refs, decodeAgentRecord(entry.data, path));
42
+ else if (entry.type === 'custom' && entry.customType === WORKFLOW_ENTRY_TYPE) workflowReferences(refs, decodeWorkflowEntry(entry.data));
43
+ else if (entry.type === 'message' && entry.message.role === 'assistant') assistantReferences(refs, entry.message);
44
+ }
45
+ export function assistantReferences(refs: References, message: Extract<Extract<SessionEntry, {type: 'message'}>['message'], {role: 'assistant'}>): void {
46
+ for (const item of message.content) if (item.type === 'toolCall' && item.arguments) {
47
+ const args = item.arguments;
48
+ if (idTools.has(item.name)) { addId(refs, args.id); addId(refs, args.runId); }
49
+ if (item.name === 'agent_workflow') addId(refs, args.resumeFromRunId);
50
+ const ids = item.name === 'wait' ? args.ids : item.name === 'goal_wait' ? args.waitFor : undefined;
51
+ if (Array.isArray(ids)) for (const id of ids) addId(refs, id);
52
+ }
53
+ }
54
+ async function session(base: string, path: string, child: boolean): Promise<SavedSession> {
55
+ const info = await inspect(base, path);
56
+ if (!info?.isFile()) throw new Error(`Not a regular session file: ${path}`);
57
+ const before = stamp(info), refs = references();
58
+ let header: SessionHeader | undefined;
59
+ const agents = new Map<string, AgentRecord>(), workflows = new Map<string, WorkflowEntryData>();
60
+ const input = createReadStream(path, {encoding: 'utf8'});
61
+ try {
62
+ for await (const line of createInterface({input, crlfDelay: Infinity})) {
63
+ if (!line.trim()) continue;
64
+ const entry = parseSessionEntries(line)[0];
65
+ if (!entry || typeof entry.type !== 'string') throw new Error(`Malformed JSONL: ${path}`);
66
+ if (!header) {
67
+ if (entry.type !== 'session' || typeof entry.id !== 'string' || !SESSION_ID.test(entry.id) || typeof entry.cwd !== 'string'
68
+ || !isAbsolute(entry.cwd) || entry.version !== undefined && (!Number.isInteger(entry.version) || entry.version < 1 || entry.version > CURRENT_SESSION_VERSION)
69
+ || entry.parentSession !== undefined && typeof entry.parentSession !== 'string') throw new Error(`Invalid session header: ${path}`);
70
+ header = entry;
71
+ addPath(refs, header.parentSession);
72
+ } else if (entry.type === 'custom' && entry.customType === AGENT_ENTRY) {
73
+ const record = decodeAgentRecord(entry.data, path);
74
+ agentReferences(refs, record); agents.set(record.runId, record);
75
+ } else if (entry.type === 'custom' && entry.customType === WORKFLOW_ENTRY_TYPE) {
76
+ const record = decodeWorkflowEntry(entry.data);
77
+ workflowReferences(refs, record); workflows.set(record.id, record);
78
+ } else if (entry.type === 'message' && entry.message.role === 'assistant') assistantReferences(refs, entry.message);
79
+ }
80
+ } finally { input.destroy(); }
81
+ if (!header || !matches(await inspect(base, path), before)) throw new Error(`Empty or changed session file: ${path}`);
82
+ return {base, path, header, agents, workflows, refs, child, stamp: before};
83
+ }
84
+
85
+ export async function readSessions(agentDir: string, homes: Home[], childRoots: Directory[], extraRoot?: string): Promise<SavedSession[]> {
86
+ const defaults = join(agentDir, 'sessions'), roots = new Map<string, {path: string; child: boolean}>();
87
+ const add = (path: string, child: boolean) => {
88
+ const key = pathKey(path), existing = roots.get(key);
89
+ roots.set(key, {path, child: child || existing?.child === true});
90
+ };
91
+ const locations = [...homes.map(home => home.root), ...childRoots];
92
+ for (const dir of locations) await verifyDirectory(dir);
93
+ for (const item of await entries(agentDir, defaults)) {
94
+ if (!item.isDirectory() && !item.isSymbolicLink() || item.name.startsWith('.')) continue;
95
+ // Pi follows workspace-level aliases. Scan their canonical target once, never move through the alias.
96
+ add(await realpath(join(defaults, item.name)), false);
97
+ }
98
+ for (const home of homes) add(home.root.path, false);
99
+ if (extraRoot) add(await realpath(extraRoot), false);
100
+ for (const item of [...roots.values()]) {
101
+ const child = join(item.path, 'subagents');
102
+ if (await inspect(item.path, child)) add(child, true);
103
+ }
104
+ for (const location of childRoots) add(location.path, true);
105
+ const result: SavedSession[] = [];
106
+ for (const {path, child} of roots.values()) {
107
+ for (const entry of await entries(path, path)) if (entry.name.endsWith('.jsonl')) {
108
+ result.push(await session(path, join(path, entry.name), child));
109
+ }
110
+ }
111
+ return result;
112
+ }
113
+
114
+ /** A legacy child header supplies provenance only for Pi's standard, inspectable layout. */
115
+ export function legacyOwnerPath(child: SavedSession, owner: string): string | undefined {
116
+ const parent = child.header.parentSession;
117
+ if (child.child && parent && basename(child.base) === 'subagents' && pathKey(dirname(child.base)) === pathKey(dirname(parent))
118
+ && basename(parent).endsWith(`_${owner}.jsonl`)) return parent;
119
+ }
@@ -44,6 +44,12 @@ async function unlock(path: string, token: string): Promise<void> {
44
44
  catch (error) { if (code(error) !== 'ENOENT') throw error; }
45
45
  }
46
46
 
47
+ /** Serialize maintenance with other maintenance processes without taking any store's data lock. */
48
+ export async function withJsonFileLock<T>(path: string, prefix: string, action: () => Promise<T>): Promise<T> {
49
+ const token = await lock(path, prefix);
50
+ try { return await action(); } finally { await unlock(path, token); }
51
+ }
52
+
47
53
  export class JsonStore<Data> {
48
54
  protected data: Data;
49
55
  private queue = Promise.resolve();
@@ -7,7 +7,7 @@
7
7
  * stays observable but is marked stale so callers refuse new executions until it is idle.
8
8
  */
9
9
  export interface ExecutionOwner { readonly closed: boolean; busy(): boolean; shutdown(): Promise<void> }
10
- type ExistingOwner = Pick<ExecutionOwner, 'closed' | 'shutdown'> & Partial<Pick<ExecutionOwner, 'busy'>>;
10
+ type ExistingOwner = Pick<ExecutionOwner, 'closed' | 'shutdown'> & Partial<Pick<ExecutionOwner, 'busy'>> & {cleanupOwners?(): Iterable<string>};
11
11
  type Slot<T> = { implementation?: symbol; owner: T };
12
12
  export type OwnerHandle<T> = { owner: T; stale?: string };
13
13
 
@@ -14,7 +14,15 @@ export function registerSuiteCommand(pi: ExtensionAPI, dock: Dock, notices: Noti
14
14
  // Types can refresh saved config without re-registering modules or commands.
15
15
  const active = config();
16
16
  if (active.commands.exit) pi.registerCommand('exit', { description: 'Quit Pi', handler: async (_args, ctx) => quit(ctx) });
17
- pi.registerCommand('suite', { description: 'Configure Pi Suite settings', handler: async (_args, ctx) => {
17
+ pi.registerCommand('suite', { description: 'Configure Pi Suite or maintain orphaned session data', handler: async (args, ctx) => {
18
+ const cleanup = /^cleanup(?:\s+|$)(.*)$/s.exec(args.trim());
19
+ if (cleanup) {
20
+ const release = notices.hold();
21
+ try { const { cleanupCommand } = await import('../cleanup/command.ts'); await cleanupCommand(cleanup[1]!, ctx); }
22
+ catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), 'error'); }
23
+ finally { release(); }
24
+ return;
25
+ }
18
26
  const release = notices.hold();
19
27
  try {
20
28
  const { showSuiteSettings } = await import('./view.ts');
@@ -1,4 +1,5 @@
1
1
  import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import { globals as jobGlobals, key as jobKey } from '../jobs/registry.ts';
2
3
  import { loadConfig } from './config.ts';
3
4
  import { SessionBinding } from './binding.ts';
4
5
  import { Notifications } from './notifications.ts';
@@ -12,6 +13,8 @@ import { registerSuiteCommand } from './settings/index.ts';
12
13
  import { prepareClipboard } from './clipboard.ts';
13
14
  import { CompletionNotifier, type FocusInput } from '../notify/index.ts';
14
15
  import type { SubagentsDeps } from '../agents/commands.ts';
16
+ import { handoffSessionUse, publishSessionReferences, registerSessionUse, retireSessionUse } from './cleanup/session-use.ts';
17
+ import type { SessionUse } from './cleanup/occupancy.ts';
15
18
 
16
19
  export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, focusInput?: FocusInput) {
17
20
  let config = loadConfig(initial.cwd);
@@ -131,6 +134,24 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, f
131
134
  });
132
135
 
133
136
  let firstBinding = true;
137
+ let use: SessionUse | undefined;
138
+ publishSessionReferences(pi, () => use);
139
+ let observedFile: string | undefined;
140
+ let locationWarning = false;
141
+ // Pi assigns a path at session creation but first writes it with conversation data.
142
+ // Remember established storage once per binding, never on token/output updates.
143
+ const rememberLocation = async (ctx: ExtensionContext) => {
144
+ const session = ctx.sessionManager, file = session.getSessionFile();
145
+ if (!file || file === observedFile || locationWarning) return;
146
+ try {
147
+ const { rememberSession } = await import('./cleanup/locations.ts');
148
+ if (await rememberSession(getAgentDir(), session)) observedFile = file;
149
+ } catch (error) {
150
+ locationWarning = true;
151
+ ctx.ui.notify(`Cannot record session location for cleanup: ${String(error)}`, 'warning');
152
+ }
153
+ };
154
+ pi.on('turn_end', async (_event, ctx) => { await rememberLocation(ctx); });
134
155
  const bindSession = async (ctx: Parameters<SessionBinding["bind"]>[0], reason: "startup" | "reload" | "new" | "resume" | "fork", previousSessionFile?: string) => {
135
156
  // Tree navigation has no shutdown event. Revoke the old readers and timers before
136
157
  // rebinding, without appending their state into the branch the host just selected.
@@ -140,8 +161,11 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, f
140
161
  if (!firstBinding) config = loadConfig(ctx.cwd);
141
162
  const goalReason = firstBinding ? reason : "tree";
142
163
  firstBinding = false; cachedTypes = undefined;
164
+ if (!use) use = await registerSessionUse(getAgentDir(), ctx);
143
165
  await prepareClipboard(pi, ctx);
144
166
  binding.bind(ctx);
167
+ observedFile = undefined; locationWarning = false;
168
+ await rememberLocation(ctx);
145
169
  notifier.bind(ctx);
146
170
  recovery?.reset(ctx);
147
171
  dock.bind(ctx, config.ui.maxRows);
@@ -176,7 +200,25 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, f
176
200
  workflows?.detach(); agents?.detach();
177
201
  recovery?.reset();
178
202
  notifications.detach(); status.detach(); dock.detach(binding.current?.ctx); binding.revoke();
179
- return Promise.all([quit, agentQuit, workflowQuit, scheduleQuit]).then(() => { if (agents) pi.events.emit('subagents:disposed', {}); });
203
+ const outgoing = use;
204
+ const jobRuntime = jobGlobals[jobKey]?.manager;
205
+ use = undefined;
206
+ return Promise.all([quit, agentQuit, workflowQuit, scheduleQuit]).then(async () => {
207
+ if (outgoing) {
208
+ const retire = async () => {
209
+ await schedules?.drain();
210
+ await retireSessionUse(outgoing, () => Boolean(agents?.manager.cleanupOwners?.().has(outgoing.owner)
211
+ || workflows?.manager.cleanupOwners?.().has(outgoing.owner)
212
+ || jobRuntime?.cleanupOwners && [...jobRuntime.cleanupOwners()].includes(outgoing.owner)), listener => [
213
+ agents?.manager.subscribe(listener), workflows?.manager.subscribe(listener), jobRuntime?.subscribe(listener),
214
+ ].filter(callback => callback !== undefined));
215
+ };
216
+ if (event.reason === 'quit') await retire();
217
+ // Keep the outgoing lease until the replacement publishes its own references.
218
+ else handoffSessionUse(outgoing, event.reason === 'reload' ? outgoing.owner : event.targetSessionFile, retire);
219
+ }
220
+ if (agents) pi.events.emit('subagents:disposed', {});
221
+ });
180
222
  });
181
223
  pi.on("agent_before_settle", async event => {
182
224
  const repair = recovery?.beforeSettle(event);
@@ -57,6 +57,23 @@ function decode(value: unknown, generation: string): TaskData {
57
57
  if (!Value.Check(storeSchema, value)) throw new Error('Invalid version or task data');
58
58
  validateHierarchy(value); return value;
59
59
  }
60
+
61
+ // The task directory can also contain unversioned, flat task lists. Recognize the
62
+ // distinct on-disk shape, not just a missing version; malformed Suite files must fail.
63
+ const foreignTaskStore = Type.Object({ nextId: Type.Integer({minimum: 1}), tasks: Type.Array(Type.Object({
64
+ id: Type.String(), subject: Type.String(), description: Type.Optional(Type.String()), activeForm: Type.Optional(Type.String()),
65
+ status: Type.Union([Type.Literal('pending'), Type.Literal('in_progress'), Type.Literal('completed')]),
66
+ blockedBy: Type.Array(Type.String()), blocks: Type.Array(Type.String()),
67
+ owner: Type.Optional(Type.String()), metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
68
+ createdAt: Type.Integer(), updatedAt: Type.Integer(),
69
+ }, {additionalProperties: false}), {minItems: 1}) }, {additionalProperties: false});
70
+
71
+ export function cleanupTaskSnapshot(path: string): Promise<TaskData | null> {
72
+ return new JsonStore<TaskData | null>(path, null, value =>
73
+ Value.Check(foreignTaskStore, value) ? null : decode(value, initialGeneration(path)), 'TASK').snapshot();
74
+ }
75
+
76
+ const initialGeneration = (path: string) => `initial:${createHash('sha256').update(path).digest('hex')}`;
60
77
  const display = (data: TaskData): TaskDisplay[] => taskViews(data).map(({ id, title, parentId, status, updatedAt, progress }) =>
61
78
  ({ id, title, parentId, status, updatedAt, progress }));
62
79
  const complete = (data: TaskData) => data.tasks.length > 0 && taskViews(data).every(task => task.status === 'done');
@@ -68,7 +85,7 @@ export class TaskStore extends JsonStore<TaskData> {
68
85
  constructor(path?: string, legacy?: Promise<unknown>) {
69
86
  // Readers/processes of an uninitialized or v3 file must agree before the first locked
70
87
  // commit. Clear then replaces this capability with a fresh, unpredictable generation.
71
- const initial = emptyTasks(path ? `initial:${createHash('sha256').update(path).digest('hex')}` : undefined);
88
+ const initial = emptyTasks(path ? initialGeneration(path) : undefined);
72
89
  super(path, initial, value => decode(value, initial.generation), 'TASK');
73
90
  this.initialGeneration = initial.generation;
74
91
  this.ready = legacy ? legacy.then(value => { this.data = decode(value, initial.generation); }) : Promise.resolve();
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionContext, Theme } from '@earendil-works/pi-coding-agent';
2
- import { fuzzyFilter, type TUI } from '@earendil-works/pi-tui';
2
+ import type { TUI } from '@earendil-works/pi-tui';
3
3
  import { BrowserView, browseState } from '../ui/browser.ts';
4
4
  import { treePrefix, type Dock } from '../ui/dock.ts';
5
5
  import type { SessionBinding } from '../runtime/binding.ts';
@@ -20,6 +20,17 @@ export class TaskBrowserView extends BrowserView {
20
20
  let views = new Map<string, TaskView>();
21
21
  const browser = browseState();
22
22
  super(tui, { title: 'Tasks', state: browser, subscribe, optionalDetails: true,
23
+ // Fuzzy ranking may separate a child from its parent; draw only uninterrupted branches.
24
+ decorateMatches: items => {
25
+ let parent: string | undefined;
26
+ return items.map(row => {
27
+ const {id, parentId} = views.get(row.value)!;
28
+ const prefix = !parentId ? 'root' : parentId === parent ? 'child' : 'indent';
29
+ if (prefix === 'root') parent = id;
30
+ else if (prefix === 'indent') parent = undefined;
31
+ return {...row, label: treePrefix(prefix) + row.label};
32
+ });
33
+ },
23
34
  total: () => queryTasks(current(), {parentId: groupId, state: 'all'}).length,
24
35
  selection: item => ({name: views.get(item.value)!.title, id: views.get(item.value)!.id}),
25
36
  layout: { truncatePrimary: ({text, item, maxWidth}) => taskBrowserRow(text, views.get(item.value)!, maxWidth) },
@@ -33,19 +44,10 @@ export class TaskBrowserView extends BrowserView {
33
44
  if (groupId && !groups().some(group => group.id === groupId)) groupId = undefined;
34
45
  const snapshot = current(); views = new Map(taskViews(snapshot).map(task => [taskReferenceKey(snapshot.generation, task.id), task]));
35
46
  const byId = new Map([...views.values()].map(task => [task.id, task]));
36
- const rows = queryTasks(snapshot, { parentId: groupId, state }).map(task => ({ value: taskReferenceKey(snapshot.generation, task.id), status: task.status,
37
- id: task.id, parentId: task.parentId, label: taskRow(task),
47
+ return queryTasks(snapshot, { parentId: groupId, state }).map(task => ({ value: taskReferenceKey(snapshot.generation, task.id), status: task.status,
48
+ label: taskRow(task),
38
49
  search: `${task.id} ${task.title} ${task.description ?? ''} ${task.blockedReason ?? ''} ${task.status}`,
39
50
  details: () => taskDetailsView(task, byId, 'browser') }));
40
- // Fuzzy filtering also ranks matches, so connect only uninterrupted child runs
41
- // following their own parent in the same search order used by BrowserView.
42
- let parent: string | undefined;
43
- for (const row of fuzzyFilter(rows, browser.query, row => row.search)) {
44
- if (!row.parentId) { parent = row.id; row.label = treePrefix('root') + row.label; }
45
- else if (row.parentId === parent) row.label = treePrefix('child') + row.label;
46
- else { parent = undefined; row.label = treePrefix('indent') + row.label; }
47
- }
48
- return rows;
49
51
  } }, done, theme);
50
52
  }
51
53
  }
package/src/ui/actions.ts CHANGED
@@ -30,7 +30,7 @@ export class ActionBar {
30
30
  }
31
31
  /** One confirmation wording for every destructive key keeps the prompt in the UI's language. */
32
32
  hint(theme?: Theme): string | undefined {
33
- this.available();
33
+ if (this.armed) this.available();
34
34
  return this.armed && confirmation(keyLabel(this.armed.key), this.armed.label.toLowerCase(), theme);
35
35
  }
36
36
  render(theme?: Theme, exclude: readonly KeyId[] = []): string {
package/src/ui/browser.ts CHANGED
@@ -11,7 +11,7 @@ import { openReading, readingRows, readingText, readingWindow } from './reading.
11
11
  import { DoubleLeft, type ViewerNavigation } from './viewer/navigation.ts';
12
12
  import { controlRows, cycle, divider, displayText, emptyRow, focusLabel, keyHint, paneHeading, readerHeading, recordStyle, selectedRow, separator, statusLabels, statusRow, titleRow, type BrowseChoice, type BrowseControl, type BrowseSelection, type DisplayText } from './browser-chrome.ts';
13
13
  export type { BrowseChoice, BrowseControl, BrowseSelection } from './browser-chrome.ts';
14
- import { detailsContent, type StructuredDetails } from './structured-details.ts';
14
+ import { detailsText, type StructuredDetails } from './structured-details.ts';
15
15
 
16
16
  export interface BrowseItem extends SelectItem { search?: string; status?: string; display?: DisplayText; details?: () => string | StructuredDetails | Component | undefined }
17
17
  export type BrowseLayout = Omit<SelectListLayoutOptions, 'truncatePrimary'> & {
@@ -29,6 +29,8 @@ export const browseState = (): BrowseState => ({ query: '', readers: new Map() }
29
29
  /** One page of a multi-page command: its own list state plus the shared page switcher. */
30
30
  export interface BrowsePage { state: BrowseState; pages: BrowseChoice; navigation?: ViewerNavigation }
31
31
  export interface BrowseOptions {
32
+ /** Optional decoration after fuzzy ranking, without reloading the source rows. */
33
+ decorateMatches?: (items: BrowseItem[]) => BrowseItem[];
32
34
  title: string; items: () => BrowseItem[]; state: BrowseState;
33
35
  /** Page tabs live in the title row and switch with 1–9 or [ ]; they are not a focus stop. */
34
36
  pages?: BrowseChoice;
@@ -38,8 +40,10 @@ export interface BrowseOptions {
38
40
  /** Total before domain filters, when the page exposes a larger scope than items(). */
39
41
  total?: () => number;
40
42
  controls?: BrowseControl[];
41
- subscribe?: (refresh: () => void) => () => void;
43
+ subscribe?: (refresh: (defer?: boolean) => void) => () => void;
42
44
  ticking?: () => boolean;
45
+ /** Clock-driven sources without a stable row snapshot (e.g. schedules). */
46
+ refreshOnTick?: boolean;
43
47
  actions?: (item: BrowseItem, done: (value?: string) => void) => DetailAction[];
44
48
  /** Enter always resolves the selected value; pages only name what that opens. */
45
49
  open?: string;
@@ -56,9 +60,15 @@ export class BrowserView extends Container {
56
60
  readonly capturesViewportInput = true;
57
61
  private input = new Input({ prompt: '' });
58
62
  private list!: SelectList;
63
+ private painted?: {items: BrowseItem[]; start: number; rows: number; view: SelectList};
64
+ private source: BrowseItem[] = [];
59
65
  private items: BrowseItem[] = [];
66
+ private indices = new Map<string, number>();
60
67
  private total = 0;
61
- private fingerprint = '';
68
+ private query?: string;
69
+ private listRows = 0;
70
+ private dirty = true;
71
+ private deferred = false;
62
72
  private visibleRows = 8;
63
73
  private focus: BrowseFocus;
64
74
  private bar: ActionBar;
@@ -78,12 +88,24 @@ export class BrowserView extends Container {
78
88
  this.bar = new ActionBar(() => this.actions(), request => this.composer.open(request));
79
89
  this.input.setValue(options.state.query);
80
90
  this.update();
81
- // Streaming events share one render request; elapsed-time ticks only read live snapshots.
82
- this.unsubscribe = options.subscribe?.(() => {
83
- this.refreshTimer ??= setTimeout(() => { this.refreshTimer = undefined; tui.requestRender(); }, 40);
91
+ // Lifecycle updates must be visible on the next paint or input. Streaming output
92
+ // only changes live ordering, so it can wait for the existing repaint batch.
93
+ this.unsubscribe = options.subscribe?.((defer = false) => {
94
+ if (!defer) this.dirty = true;
95
+ this.refreshTimer ??= setTimeout(() => {
96
+ this.refreshTimer = undefined;
97
+ if (this.deferred) this.dirty = true;
98
+ this.deferred = false; tui.requestRender();
99
+ }, 40);
100
+ this.deferred ||= defer;
84
101
  });
85
102
  if (options.ticking) {
86
- this.clock = setInterval(() => { if (options.ticking!()) tui.requestRender(); }, 1000);
103
+ this.clock = setInterval(() => {
104
+ if (!options.ticking!()) return;
105
+ if (options.refreshOnTick) this.dirty = true;
106
+ else this.syncDetails();
107
+ tui.requestRender();
108
+ }, 1000);
87
109
  this.clock.unref();
88
110
  }
89
111
  }
@@ -93,39 +115,67 @@ export class BrowserView extends Container {
93
115
  }
94
116
  override invalidate(): void { this.list.invalidate(); this.reader?.invalidate(); }
95
117
  getSelectedItem(): SelectItem | null { return this.list.getSelectedItem(); }
96
- private selectedItem(): BrowseItem | undefined { return this.items.find(item => item.value === this.list?.getSelectedItem()?.value); }
118
+ private selectedItem(): BrowseItem | undefined { return (this.list?.getSelectedItem() as BrowseItem | null) ?? undefined; }
97
119
  private actions(): DetailAction[] {
98
120
  const item = this.selectedItem();
99
121
  return item ? this.options.actions?.(item, this.done) ?? [] : [];
100
122
  }
101
- private update(reset = false): void {
102
- const oldIndex = this.items.findIndex(item => item.value === this.list?.getSelectedItem()?.value);
103
- const all = this.options.items().map(item => ({ ...item, label: item.display ? displayText(item.display, this.theme) : sanitizeText(item.label).replace(/[\r\n\t]/g, ' '),
104
- description: item.description === undefined ? undefined : sanitizeText(item.description).replace(/[\r\n\t]/g, ' ') }));
105
- this.total = this.options.total?.() ?? all.length;
106
- this.items = fuzzyFilter(all, this.options.state.query, item => item.search ?? `${item.label} ${item.description ?? ''}`);
107
- const fingerprint = JSON.stringify([this.visibleRows, this.items.map(item => [item.value, item.label, item.description, item.status])]);
108
- if (reset || fingerprint !== this.fingerprint || !this.list) {
109
- const previous = reset ? undefined : this.list?.getSelectedItem()?.value ?? this.options.state.selected;
110
- const index = this.items.findIndex(item => item.value === previous);
111
- // Native SelectList still owns selection and scrolling. Its selectedText callback receives
112
- // the complete visible row, so background and marker do not require a parallel renderer.
113
- this.list = new SelectList(this.items, this.visibleRows, { ...getSelectListTheme(),
114
- selectedText: text => selectedRow(text, this.leftWidth, this.theme, this.active('list')) }, {
115
- ...this.options.layout, truncatePrimary: context => {
116
- const text = this.options.layout?.truncatePrimary?.({...context, theme: this.theme}) ?? truncateToWidth(context.text, context.maxWidth, '');
117
- return (context.item as BrowseItem).display ? text : recordStyle(text, (context.item as BrowseItem).status, this.theme);
118
- },
119
- });
120
- this.list.setSelectedIndex(index >= 0 ? index : reset ? 0 : Math.max(0, Math.min(oldIndex, this.items.length - 1)));
121
- this.list.onSelectionChange = () => this.changed();
122
- this.list.onSelect = () => this.select();
123
- this.list.onCancel = () => this.done();
124
- this.fingerprint = fingerprint;
123
+ private update(resetSelection = false): void {
124
+ const query = this.options.state.query, rebuild = this.dirty || query !== this.query;
125
+ if (resetSelection && !rebuild) {
126
+ this.list.setSelectedIndex(0);
127
+ this.syncDetails();
125
128
  }
126
- this.changed();
129
+ if (!rebuild && this.listRows === this.visibleRows) return;
130
+ const previous = this.selectedItem()?.value ?? this.options.state.selected;
131
+ const oldIndex = previous === undefined ? 0 : this.indices.get(previous) ?? 0;
132
+ const reset = resetSelection || this.query !== undefined && query !== this.query;
133
+ if (this.dirty) {
134
+ this.source = this.options.items().map(item => ({ ...item, label: item.display ? displayText(item.display, this.theme) : sanitizeText(item.label).replace(/[\r\n\t]/g, ' '),
135
+ description: item.description === undefined ? undefined : sanitizeText(item.description).replace(/[\r\n\t]/g, ' ') }));
136
+ this.total = this.options.total?.() ?? this.source.length;
137
+ this.dirty = false;
138
+ }
139
+ if (rebuild) {
140
+ const matched = fuzzyFilter(this.source, query, item => item.search ?? `${item.label} ${item.description ?? ''}`);
141
+ this.items = this.options.decorateMatches?.(matched) ?? matched;
142
+ this.indices = new Map(this.items.map((item, index) => [item.value, index]));
143
+ this.painted = undefined;
144
+ this.query = query;
145
+ }
146
+ // Native SelectList owns navigation/scrolling; resize need only give it a new row budget.
147
+ this.list = this.createList(this.items);
148
+ this.listRows = this.visibleRows;
149
+ const index = previous === undefined ? undefined : this.indices.get(previous);
150
+ this.list.setSelectedIndex(reset ? 0 : index ?? oldIndex);
151
+ this.list.onSelectionChange = () => this.syncDetails();
152
+ this.list.onSelect = () => this.select();
153
+ this.list.onCancel = () => this.done();
154
+ if (rebuild) this.syncDetails();
127
155
  this.setFocus(this.focus);
128
156
  }
157
+ private createList(items: BrowseItem[]): SelectList {
158
+ return new SelectList(items, this.visibleRows, { ...getSelectListTheme(),
159
+ selectedText: text => selectedRow(text, this.leftWidth, this.theme, this.active('list')) }, {
160
+ ...this.options.layout, truncatePrimary: context => {
161
+ const text = this.options.layout?.truncatePrimary?.({...context, theme: this.theme}) ?? truncateToWidth(context.text, context.maxWidth, '');
162
+ return (context.item as BrowseItem).display ? text : recordStyle(text, (context.item as BrowseItem).status, this.theme);
163
+ },
164
+ });
165
+ }
166
+ private renderList(): string[] {
167
+ const {minPrimaryColumnWidth: min, maxPrimaryColumnWidth: max} = this.options.layout ?? {};
168
+ // Variable description columns need the full set for width measurement. For fixed columns,
169
+ // paint only the native centered slice. The browser already clips the native overflow line.
170
+ if (min !== undefined && max !== undefined && min !== max || this.items.length <= this.visibleRows) return this.list.render(this.leftWidth);
171
+ const index = this.indices.get(this.selectedItem()!.value)!;
172
+ const start = Math.max(0, Math.min(index - Math.floor(this.visibleRows / 2), this.items.length - this.visibleRows));
173
+ if (this.painted?.items !== this.items || this.painted.start !== start || this.painted.rows !== this.visibleRows) {
174
+ this.painted = {items: this.items, start, rows: this.visibleRows, view: this.createList(this.items.slice(start, start + this.visibleRows))};
175
+ }
176
+ this.painted.view.setSelectedIndex(index - start);
177
+ return this.painted.view.render(this.leftWidth);
178
+ }
129
179
  private setFocus(focus: BrowseFocus): void {
130
180
  this.focus = this.options.state.focus = focus === 'details' && !this.reader ? 'list' : focus;
131
181
  if (this.focus !== 'list') this.bar.disarm();
@@ -138,20 +188,22 @@ export class BrowserView extends Container {
138
188
  const prefix = `${focusLabel(label, active, this.theme)} `;
139
189
  return truncateToWidth(prefix + render(Math.max(1, width - visibleWidth(prefix))), width);
140
190
  }
141
- private changed(): void {
142
- const value = this.list.getSelectedItem()?.value;
191
+ private syncDetails(): void {
192
+ const item = this.selectedItem(), value = item?.value;
143
193
  this.options.state.selected = value;
144
194
  // A confirmation belongs to one record. Moving selection cannot stop the next one.
145
195
  if (value !== this.actionOwner) { this.bar.disarm(); this.actionOwner = value; }
146
- const item = this.items.find(item => item.value === value);
147
196
  const details = item?.details?.();
148
197
  if (!item || details === undefined) { this.reader = undefined; return; }
149
- // Each identity retains its own search and scroll when another row or action is opened.
150
- const content = typeof details === 'string' ? new Text(sanitizeText(details), 0, 0)
151
- : 'rows' in details ? detailsContent(details, this.theme) : details;
198
+ // Keep native wrapping and the reader's search/scroll state across unchanged details.
199
+ const text = typeof details === 'string' ? sanitizeText(details) : 'rows' in details ? detailsText(details, this.theme) : undefined;
152
200
  this.reader = this.options.state.readers.get(item.value);
153
- if (this.reader) this.reader.setContent(content);
154
- else { this.reader = new ScrollView(content); this.options.state.readers.set(item.value, this.reader); }
201
+ if (this.reader && text !== undefined) this.reader.setText(text);
202
+ else {
203
+ const content = text === undefined ? details as Component : new Text(text, 0, 0);
204
+ if (this.reader) this.reader.setContent(content);
205
+ else { this.reader = new ScrollView(content); this.options.state.readers.set(item.value, this.reader); }
206
+ }
155
207
  }
156
208
  private select(): void { const value = this.list.getSelectedItem()?.value; if (value !== undefined) this.done(value); }
157
209
  private setQuery(query: string): void { this.input.setValue(query); this.options.state.query = query; this.update(true); }
@@ -213,7 +265,7 @@ export class BrowserView extends Container {
213
265
  this.visibleRows = Math.max(1, listHeight - 1);
214
266
  this.update();
215
267
  const listLines = readingWindow([paneHeading('List', this.leftWidth, this.active('list'), this.theme),
216
- ...this.items.length ? this.list.render(this.leftWidth) : [this.empty()]], listHeight);
268
+ ...this.items.length ? this.renderList() : [this.empty()]], listHeight);
217
269
  const detailsHeight = split ? height : height - listHeight;
218
270
  const detailsWidth = split ? width - this.leftWidth - 3 : width;
219
271
  const detailBody = this.reader?.viewport(detailsWidth, Math.max(0, detailsHeight - 1), () => this.tui.requestRender()) ?? [];
@@ -284,7 +336,7 @@ export class BrowserView extends Container {
284
336
  const page = pages?.items().find((_page, index) => index < 9 && matchesKey(data, String(index + 1) as KeyId));
285
337
  const control = controls.find(control => matchesKey(data, control.key));
286
338
  if (page && page.value !== pages!.selected()) pages!.select(page.value, this.done);
287
- else if (control) cycle(control, this.done);
339
+ else if (control) { cycle(control, this.done); this.dirty = true; }
288
340
  }
289
341
  }
290
342
  }
package/src/ui/scroll.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { stripVTControlCharacters } from 'node:util';
2
- import { Container, Input, Key, ScrollView as NativeScrollView, matchesKey,
2
+ import { Container, Input, Key, Text, ScrollView as NativeScrollView, matchesKey,
3
3
  type Component } from '@earendil-works/pi-tui';
4
4
  import { readingWindow } from './reading.ts';
5
5
 
@@ -72,6 +72,10 @@ export class ScrollView extends NativeScrollView {
72
72
  }
73
73
  get position(): string { return `${this.lines.length ? this.offset + 1 : 0}/${this.lines.length}`; }
74
74
  get atBottom(): boolean { return this.offset >= Math.max(0, this.lines.length - this.viewportHeight); }
75
+ setText(text: string): void {
76
+ if (this.content instanceof Text) this.content.setText(text);
77
+ else this.setContent(new Text(text, 0, 0));
78
+ }
75
79
  setContent(content: Component): void {
76
80
  if (this.content === content) return;
77
81
  this.content = content; this.document.clear(); this.document.addChild(content);