pi-suite 0.3.7 → 0.3.8
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 +1 -1
- package/src/agents/child.ts +9 -3
- package/src/agents/history.ts +3 -3
- package/src/agents/index.ts +22 -21
- package/src/agents/manager.ts +40 -12
- package/src/agents/records.ts +4 -2
- package/src/agents/runner.ts +12 -3
- package/src/agents/runtime.ts +1 -1
- package/src/agents/schedules/menu.ts +1 -1
- package/src/agents/types.ts +2 -1
- package/src/agents/ui/runs.ts +33 -13
- package/src/agents/viewer.ts +17 -11
- package/src/agents/workflow/index.ts +32 -9
- package/src/agents/workflow/manager.ts +18 -6
- package/src/agents/workflow/ui/menu.ts +2 -2
- package/src/jobs/index.ts +49 -36
- package/src/jobs/manager-record.ts +2 -2
- package/src/jobs/manager.ts +30 -12
- package/src/jobs/monitors/runtime.ts +41 -27
- package/src/jobs/store.ts +49 -10
- package/src/jobs/tools.ts +2 -2
- package/src/jobs/types.ts +2 -0
- package/src/jobs/viewer/metadata.ts +6 -0
- package/src/jobs/viewer.ts +30 -25
- package/src/runtime/branch.ts +14 -0
- package/src/runtime/cleanup/command.ts +116 -0
- package/src/runtime/cleanup/locations.ts +91 -0
- package/src/runtime/cleanup/occupancy.ts +117 -0
- package/src/runtime/cleanup/paths.ts +44 -0
- package/src/runtime/cleanup/quarantine.ts +162 -0
- package/src/runtime/cleanup/scan.ts +297 -0
- package/src/runtime/cleanup/session-use.ts +62 -0
- package/src/runtime/cleanup/sessions.ts +119 -0
- package/src/runtime/json-store.ts +6 -0
- package/src/runtime/owner.ts +1 -1
- package/src/runtime/settings/index.ts +9 -1
- package/src/runtime/suite.ts +43 -1
- package/src/tasks/store.ts +18 -1
- package/src/tasks/viewer.ts +14 -12
- package/src/ui/actions.ts +1 -1
- package/src/ui/browser.ts +95 -43
- package/src/ui/scroll.ts +5 -1
package/src/runtime/owner.ts
CHANGED
|
@@ -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
|
|
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');
|
package/src/runtime/suite.ts
CHANGED
|
@@ -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
|
-
|
|
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);
|
package/src/tasks/store.ts
CHANGED
|
@@ -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 ?
|
|
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();
|
package/src/tasks/viewer.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ExtensionContext, Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
-
import {
|
|
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
|
-
|
|
37
|
-
|
|
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 {
|
|
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
|
|
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
|
-
//
|
|
82
|
-
|
|
83
|
-
|
|
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(() => {
|
|
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
|
|
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(
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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.
|
|
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
|
|
142
|
-
const
|
|
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
|
-
//
|
|
150
|
-
const
|
|
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.
|
|
154
|
-
else {
|
|
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.
|
|
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);
|