pi-suite 0.3.1 → 0.3.5
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 +76 -29
- package/README.zh-CN.md +79 -32
- package/package.json +1 -1
- package/src/agents/index.ts +8 -6
- package/src/agents/render.ts +18 -8
- package/src/agents/schedules/menu.ts +2 -1
- package/src/agents/tools.ts +7 -6
- package/src/agents/ui/runs.ts +6 -7
- package/src/agents/ui/types.ts +5 -11
- package/src/agents/viewer-info.ts +12 -10
- package/src/agents/viewer.ts +4 -2
- package/src/agents/workflow/ui/progress.ts +5 -5
- package/src/ask/index.ts +4 -2
- package/src/ask/view.ts +13 -5
- package/src/goal/manager.ts +8 -0
- package/src/jobs/index.ts +6 -2
- package/src/jobs/output.ts +19 -7
- package/src/jobs/query.ts +27 -20
- package/src/jobs/render.ts +13 -4
- package/src/jobs/terminal/session.ts +73 -27
- package/src/jobs/tools.ts +9 -6
- package/src/jobs/viewer/component.ts +3 -1
- package/src/notify/index.ts +85 -0
- package/src/runtime/config.ts +5 -0
- package/src/runtime/notifications.ts +6 -1
- package/src/runtime/read.ts +163 -25
- package/src/runtime/responses/index.ts +19 -23
- package/src/runtime/responses/payload.ts +10 -7
- package/src/runtime/suite.ts +17 -6
- package/src/runtime/tools.ts +7 -2
- package/src/tasks/presentation.ts +5 -0
- package/src/tasks/query.ts +16 -8
- package/src/tasks/render.ts +14 -5
- package/src/tasks/tools.ts +5 -2
- package/src/tasks/viewer.ts +18 -9
- package/src/ui/browser.ts +14 -10
- package/src/ui/details.ts +22 -7
- package/src/ui/dock.ts +6 -1
- package/src/ui/rendering/read-page.ts +2 -1
- package/src/ui/structured-details.ts +57 -11
- package/src/ui/working.ts +11 -0
- package/third-party/UPSTREAM.md +17 -66
package/src/runtime/suite.ts
CHANGED
|
@@ -10,9 +10,10 @@ import { recordsIn } from '../agents/records.ts';
|
|
|
10
10
|
import { visibleAgent, type AgentType } from '../agents/types.ts';
|
|
11
11
|
import { registerSuiteCommand } from './settings/index.ts';
|
|
12
12
|
import { prepareClipboard } from './clipboard.ts';
|
|
13
|
+
import { CompletionNotifier, type FocusInput } from '../notify/index.ts';
|
|
13
14
|
import type { SubagentsDeps } from '../agents/commands.ts';
|
|
14
15
|
|
|
15
|
-
export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext) {
|
|
16
|
+
export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, focusInput?: FocusInput) {
|
|
16
17
|
let config = loadConfig(initial.cwd);
|
|
17
18
|
// Pi uses Jiti with shared dependency graphs: concurrent imports can expose unfinished
|
|
18
19
|
// exports. Load admitted stacks in order and finish registration before session_start returns.
|
|
@@ -54,7 +55,9 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext) {
|
|
|
54
55
|
}
|
|
55
56
|
const waits = new WaitRegistry();
|
|
56
57
|
const goal = config.modules.goal ? new goalApi![0].GoalManager(pi, binding, notifications, status, waits) : undefined;
|
|
57
|
-
const
|
|
58
|
+
const notifier = new CompletionNotifier(() => config.notify, focusInput);
|
|
59
|
+
const ask = config.modules.ask ? new AskManager(binding, notifications, dock, (status, ctx) => goal?.askResult(status, ctx),
|
|
60
|
+
() => notifier.show()) : undefined;
|
|
58
61
|
if (ask) registerAsk(pi, ask, () => config);
|
|
59
62
|
const creatorRoots = () => {
|
|
60
63
|
const ctx = binding.current?.ctx;
|
|
@@ -131,13 +134,15 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext) {
|
|
|
131
134
|
const bindSession = async (ctx: Parameters<SessionBinding["bind"]>[0], reason: "startup" | "reload" | "new" | "resume" | "fork", previousSessionFile?: string) => {
|
|
132
135
|
// Tree navigation has no shutdown event. Revoke the old readers and timers before
|
|
133
136
|
// rebinding, without appending their state into the branch the host just selected.
|
|
134
|
-
dock.detach(binding.current?.ctx);
|
|
137
|
+
notifier.detach(); dock.detach(binding.current?.ctx);
|
|
135
138
|
schedules?.stop(); ask?.cancel(); goal?.detach(); jobs?.detach(); workflows?.detach(); agents?.detach(); notifications.detach();
|
|
139
|
+
binding.revoke();
|
|
136
140
|
if (!firstBinding) config = loadConfig(ctx.cwd);
|
|
137
141
|
const goalReason = firstBinding ? reason : "tree";
|
|
138
142
|
firstBinding = false; cachedTypes = undefined;
|
|
139
143
|
await prepareClipboard(pi, ctx);
|
|
140
144
|
binding.bind(ctx);
|
|
145
|
+
notifier.bind(ctx);
|
|
141
146
|
recovery?.reset(ctx);
|
|
142
147
|
dock.bind(ctx, config.ui.maxRows);
|
|
143
148
|
status.bind(ctx.ui, { goal: config.goal.display, agents: config.agents.display, jobs: config.jobs.display }, goal !== undefined);
|
|
@@ -153,6 +158,7 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext) {
|
|
|
153
158
|
pi.on("session_tree", async (_event, ctx) => { await bindSession(ctx, "resume"); notifications.afterHostOperation(); });
|
|
154
159
|
pi.on("session_shutdown", async event => {
|
|
155
160
|
agentRpc?.detach();
|
|
161
|
+
notifier.detach();
|
|
156
162
|
schedules?.stop();
|
|
157
163
|
ask?.cancel(); await goal?.shutdown(event.reason);
|
|
158
164
|
tasks?.detach();
|
|
@@ -178,11 +184,16 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext) {
|
|
|
178
184
|
await goal?.beforeSettle(proposed);
|
|
179
185
|
return notifications.beforeSettle(proposed) ?? repair;
|
|
180
186
|
});
|
|
181
|
-
pi.on("agent_settled", async event => {
|
|
182
|
-
|
|
183
|
-
|
|
187
|
+
pi.on("agent_settled", async (event, ctx) => {
|
|
188
|
+
const captured = binding.current, delivery = notifications.deliverySequence;
|
|
189
|
+
recovery?.settled(); waits.steeringDelivered();
|
|
190
|
+
await goal?.settled(event.aborted);
|
|
184
191
|
if (event.aborted) jobs?.pauseWakes();
|
|
185
192
|
notifications.flush();
|
|
193
|
+
if (!captured || !binding.isCurrent(captured) || ctx.sessionManager.getSessionId() !== captured.sessionId) return;
|
|
194
|
+
// Goal's own commits may release the queue while settled() is awaited. By this
|
|
195
|
+
// boundary Pi has also finished any native retries, even on a final request error.
|
|
196
|
+
if (ctx.mode === 'tui' && !event.aborted && delivery === notifications.deliverySequence && !goal?.unattended) notifier.show();
|
|
186
197
|
});
|
|
187
198
|
registerSuiteCommand(pi, dock, notifications, () => config, subagentsDeps ? async ctx => {
|
|
188
199
|
const { showSubagents } = await import('../agents/ui/index.ts');
|
package/src/runtime/tools.ts
CHANGED
|
@@ -112,13 +112,18 @@ export function paginate<T>(items: T[], position: (item: T) => Position, cursor:
|
|
|
112
112
|
|
|
113
113
|
/** Byte-offset paging, regex search and default smart truncation; shared by job_read and agent_read. */
|
|
114
114
|
export const readFields = {
|
|
115
|
-
|
|
115
|
+
line: Type.Optional(Type.Integer({ description: '1-based start line; negative counts from the end (-50 = the last 50 lines). Lines are newline-separated lines of the raw log' })),
|
|
116
|
+
lines: Type.Optional(Type.Integer({ minimum: 1, maximum: READ_LIMITS.maxLines, description: 'With line: how many lines to read; default as many as limitBytes allows' })),
|
|
117
|
+
offset: Type.Optional(Type.Integer({ minimum: 0, description: 'Raw byte offset; returns nextOffset. With line: bytes after the start of that line' })),
|
|
116
118
|
limitBytes: Type.Optional(Type.Integer({ minimum: 64, maximum: READ_LIMITS.maxBytes, description: `Default ${READ_LIMITS.defaultBytes}` })),
|
|
117
119
|
search: Type.Optional(Type.String({ minLength: 1, maxLength: 500, description: 'Regex, /re/flags; case-insensitive by default' })),
|
|
118
120
|
context: Type.Optional(Type.Integer({ minimum: 0, maximum: READ_LIMITS.maxContext, description: `Lines around matches, default ${READ_LIMITS.defaultContext}` })),
|
|
119
121
|
};
|
|
120
|
-
export function rejectContextWithoutSearch(params: { search?: string; context?: number }): void {
|
|
122
|
+
export function rejectContextWithoutSearch(params: { search?: string; context?: number; line?: number; lines?: number }): void {
|
|
121
123
|
if (params.context !== undefined && params.search === undefined) throw new ToolError('INVALID_ARGS', 'context requires search. Add search or omit context.');
|
|
124
|
+
if (params.line === 0) throw new ToolError('INVALID_ARGS', 'line starts at 1; use a negative line to count from the end, e.g. -50 for the last 50 lines.');
|
|
125
|
+
if (params.lines !== undefined && params.line === undefined) throw new ToolError('INVALID_ARGS', 'lines requires line. Add line or omit lines.');
|
|
126
|
+
if (params.lines !== undefined && params.search !== undefined) throw new ToolError('INVALID_ARGS', 'lines cannot be combined with search; use limitBytes or context to bound a search.');
|
|
122
127
|
}
|
|
123
128
|
|
|
124
129
|
/** stop result shared by job_stop and agent_stop; affected lists every cascaded object's real state. */
|
|
@@ -2,6 +2,7 @@ import type { Theme } from '@earendil-works/pi-coding-agent';
|
|
|
2
2
|
import type { DerivedChange, EditReceipt, EditResult, TaskView } from './types.ts';
|
|
3
3
|
import { taskTitle } from './query.ts';
|
|
4
4
|
import { sanitizeText } from '../runtime/text.ts';
|
|
5
|
+
import { executionRow } from '../ui/dock/line.ts';
|
|
5
6
|
|
|
6
7
|
export const taskIcon = (state: string): string => ({ doing: '⟳', blocked: '⚠', done: '☑' })[state] ?? '☐';
|
|
7
8
|
// Reuse the Dock heading's accent for pending work across every task view.
|
|
@@ -11,6 +12,10 @@ export function taskRow(task: Pick<TaskView, 'id' | 'title' | 'parentId' | 'stat
|
|
|
11
12
|
const text = `${taskIcon(task.status)} ${taskHeading(task)}`;
|
|
12
13
|
return taskStyle(task, text, theme);
|
|
13
14
|
}
|
|
15
|
+
/** Reserve progress at the actual SelectList width, including in a split pane. */
|
|
16
|
+
export const taskBrowserRow = (label: string, task: TaskView, width: number): string =>
|
|
17
|
+
executionRow(label, task.progress ? `${task.progress.done}/${task.progress.total}` : '', undefined, width);
|
|
18
|
+
|
|
14
19
|
/** Apply trusted theme styling after readers have sanitized/truncated task data. */
|
|
15
20
|
export function taskStyle(task: Pick<TaskView, 'status'>, text: string, theme?: Theme): string {
|
|
16
21
|
if (!theme) return text;
|
package/src/tasks/query.ts
CHANGED
|
@@ -26,13 +26,21 @@ const taskHeading = (task: TaskView) => [part(task.id, 'id'), part(' '), part(ta
|
|
|
26
26
|
export const taskLabel = (task: TaskView): string => taskHeading(task).map(({text}) => text).join('');
|
|
27
27
|
export const taskTitle = (task: Pick<TaskView, 'title'>) => sanitizeText(task.title).replace(/[\r\n\t]/g, ' ').trim();
|
|
28
28
|
export const openBlockers = (task: TaskView, views: Map<string, TaskView>) => task.blockedBy.filter(id => views.get(id)?.status !== 'done');
|
|
29
|
-
export function taskDetailsView(task: TaskView, views: Map<string, TaskView>): StructuredDetails
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
29
|
+
export function taskDetailsView(task: TaskView, views: Map<string, TaskView>): StructuredDetails;
|
|
30
|
+
export function taskDetailsView(task: TaskView, views: Map<string, TaskView>, display: 'browser'): StructuredDetails | undefined;
|
|
31
|
+
export function taskDetailsView(task: TaskView, views: Map<string, TaskView>, display?: 'browser'): StructuredDetails | undefined {
|
|
32
|
+
// Only the interactive preview changes labels and omits records without a detail body.
|
|
33
|
+
const browser = display === 'browser';
|
|
34
|
+
const detailText = (text?: string) => text && (!browser || sanitizeText(text).trim()) ? text : undefined;
|
|
35
|
+
const reason = detailText(task.blockedReason), open = openBlockers(task, views);
|
|
36
|
+
const satisfied = browser ? task.blockedBy.filter(id => views.get(id)?.status === 'done') : [];
|
|
37
|
+
const body = [detailText(task.description), reason ? field(browser ? 'Blocked reason:' : 'blocked:', part(reason, 'error')) : undefined, null,
|
|
38
|
+
open.length ? field(browser ? 'Blocked by:' : 'blockedBy:', part(open.join(', '), 'id')) : undefined,
|
|
39
|
+
...satisfied.length ? [field('Depends on:', part(satisfied.join(', '), 'id'))] : [],
|
|
40
|
+
task.blocks.length ? field(browser ? 'Blocks:' : 'blocks:', part(task.blocks.join(', '), 'id')) : undefined,
|
|
41
|
+
task.owner ? field(browser ? 'Agent:' : 'agent:', part(task.owner, 'id')) : undefined,
|
|
42
|
+
task.jobIds.length ? field(browser ? 'Jobs:' : 'jobs:', part(task.jobIds.join(', '), 'id')) : undefined];
|
|
43
|
+
if (browser && !body.some(Boolean)) return;
|
|
44
|
+
return { rows: [taskHeading(task), ...browser ? [] : [task.parentId ? field('parent', part(task.parentId, 'id')) : undefined], null, ...body] };
|
|
37
45
|
}
|
|
38
46
|
export const taskDetails = (task: TaskView, views: Map<string, TaskView>): string[] => plainDetailLines(taskDetailsView(task, views));
|
package/src/tasks/render.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { toolRenderers, type ToolLine } from '../ui/tool-render.ts';
|
|
1
|
+
import { toolRenderers, type ToolExpandedRow, type ToolLine } from '../ui/tool-render.ts';
|
|
2
|
+
import type { StructuredDetails } from '../ui/structured-details.ts';
|
|
2
3
|
import { taskIcon, taskTone, taskHeading, receiptAction, receiptDisplay } from './presentation.ts';
|
|
3
4
|
import type { EditResult, TaskView } from './types.ts';
|
|
4
5
|
|
|
@@ -20,11 +21,19 @@ export const listRenderers = toolRenderers<{ state?: string; groupId?: string },
|
|
|
20
21
|
...nextCursor ? [{ label: 'more', value: 'next page available', tone: 'warning' as const }] : [], ...tasks.length ? [] : ['No tasks'],
|
|
21
22
|
],
|
|
22
23
|
});
|
|
23
|
-
export const getRenderers = toolRenderers<{ id: string }, { task: TaskView; generation: string }>({
|
|
24
|
+
export const getRenderers = toolRenderers<{ id: string }, { task: TaskView; generation: string; view?: StructuredDetails }>({
|
|
24
25
|
call: () => ({ icon: '⟳', tone: 'accent', title: 'Task' }),
|
|
25
26
|
collapsed: ({ task }) => ({ ...line(task), meta: task.progress ? [`${task.progress.done}/${task.progress.total}`] : [] }),
|
|
26
|
-
|
|
27
|
-
|
|
27
|
+
// Saved tool results without detail rows still have the original receipt text.
|
|
28
|
+
expanded: ({ generation, view }, _args, text) => view ? [{ label: 'generation', value: generation },
|
|
29
|
+
...view.rows.flatMap<ToolExpandedRow>(row => {
|
|
30
|
+
if (typeof row === 'string') return [row];
|
|
31
|
+
if (!row || !('length' in row)) return [];
|
|
32
|
+
const [head, ...rest] = row;
|
|
33
|
+
return head?.role === 'label'
|
|
34
|
+
? [{ label: head.text.trimEnd().replace(/:$/, ''), value: rest.map(part => part.text).join('') }]
|
|
35
|
+
: [row.map(part => part.text).join('')];
|
|
36
|
+
})] : [text],
|
|
28
37
|
});
|
|
29
38
|
export const editRenderers = toolRenderers<unknown, EditResult>({
|
|
30
39
|
call: () => ({ icon: '⟳', tone: 'accent', title: 'Updating tasks…' }),
|
|
@@ -47,7 +56,7 @@ export const editRenderers = toolRenderers<unknown, EditResult>({
|
|
|
47
56
|
...data.changes.map(change => ({ ...line({ ...change, status: change.after ?? change.before ?? 'todo' }),
|
|
48
57
|
summary: receiptDisplay(change).slice(receiptDisplay(change).indexOf(' · ') + 3) })),
|
|
49
58
|
...data.derived.map(change => ({ ...line(change), summary: change.status === 'blocked' ? 'blocked' : 'dependencies cleared' })),
|
|
50
|
-
...data.changes.
|
|
59
|
+
...data.changes.flatMap(change => Object.entries(change.fields ?? {}).map(([key, value]) => ({ label: `fields ${change.id} ${key}`, value: String(value) }))),
|
|
51
60
|
...data.progress.map(group => ({ label: `group ${group.id}`, value: `${group.done}/${group.total} ${group.status}`, tone: taskTone(group.status) })),
|
|
52
61
|
...data.warnings.map(warning => ({ label: 'warning', value: warning, tone: 'warning' as const })),
|
|
53
62
|
],
|
package/src/tasks/tools.ts
CHANGED
|
@@ -4,7 +4,8 @@ import { registerBoundTool, checkedArguments, LIST_LIMITS, paginate, textResult
|
|
|
4
4
|
import { boundedText } from '../runtime/read.ts';
|
|
5
5
|
import type { TasksModule } from './index.ts';
|
|
6
6
|
import { taskId, taskScope, groupId, generationSchema, type TaskScope, type TaskView } from './types.ts';
|
|
7
|
-
import {
|
|
7
|
+
import { plainDetailLines } from '../ui/structured-details.ts';
|
|
8
|
+
import { taskDetailsView, taskLabel, type TaskFilter } from './query.ts';
|
|
8
9
|
import { taskViews } from './model.ts';
|
|
9
10
|
import { editSchema, editArguments, editChanges } from './schema.ts';
|
|
10
11
|
import { requireGeneration } from './types.ts';
|
|
@@ -51,7 +52,9 @@ export function registerTaskTools(pi: ExtensionAPI, tasks: TasksModule): void {
|
|
|
51
52
|
async execute(_id, params, _signal, _update, ctx) {
|
|
52
53
|
const scope = (params as { scope?: TaskScope }).scope;
|
|
53
54
|
const { task, views } = await tasks.get(ctx, params.id, params.generation, scope);
|
|
54
|
-
|
|
55
|
+
// Persist the selected task's detail rows, not the Map of the entire list.
|
|
56
|
+
const view = taskDetailsView(task, views);
|
|
57
|
+
return textResult([`generation: ${params.generation}`, scope === 'assigned' ? `assigned task ${params.id} (parent list)` : undefined, ...plainDetailLines(view)], { task, generation: params.generation, view });
|
|
55
58
|
},
|
|
56
59
|
...getRenderers,
|
|
57
60
|
}, 'initial');
|
package/src/tasks/viewer.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import type { ExtensionContext, Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
-
import {
|
|
2
|
+
import { fuzzyFilter, type TUI } from '@earendil-works/pi-tui';
|
|
3
3
|
import { BrowserView, browseState } from '../ui/browser.ts';
|
|
4
|
-
import type
|
|
4
|
+
import { treePrefix, type Dock } from '../ui/dock.ts';
|
|
5
5
|
import type { SessionBinding } from '../runtime/binding.ts';
|
|
6
6
|
import { parseTaskReference, taskReferenceKey, type TasksModule } from './index.ts';
|
|
7
7
|
import { checkGeneration } from './types.ts';
|
|
8
8
|
import { queryTasks, taskDetailsView, taskTitle, type TaskFilter } from './query.ts';
|
|
9
9
|
import { taskViews } from './model.ts';
|
|
10
|
-
import { taskRow } from './presentation.ts';
|
|
10
|
+
import { taskBrowserRow, taskRow } from './presentation.ts';
|
|
11
11
|
import type { TaskData, TaskView } from './types.ts';
|
|
12
12
|
|
|
13
13
|
/** Selection keys include the source generation; numeric IDs are reusable. */
|
|
@@ -18,10 +18,11 @@ export class TaskBrowserView extends BrowserView {
|
|
|
18
18
|
const current = () => { const value = data(); if (value.generation !== generation) { generation = value.generation; groupId = undefined; } return value; };
|
|
19
19
|
const groups = () => taskViews(current()).filter(task => !task.parentId);
|
|
20
20
|
let views = new Map<string, TaskView>();
|
|
21
|
-
|
|
21
|
+
const browser = browseState();
|
|
22
|
+
super(tui, { title: 'Tasks', state: browser, subscribe, optionalDetails: true,
|
|
22
23
|
total: () => queryTasks(current(), {parentId: groupId, state: 'all'}).length,
|
|
23
24
|
selection: item => ({name: views.get(item.value)!.title, id: views.get(item.value)!.id}),
|
|
24
|
-
layout: { truncatePrimary: ({text, maxWidth}) =>
|
|
25
|
+
layout: { truncatePrimary: ({text, item, maxWidth}) => taskBrowserRow(text, views.get(item.value)!, maxWidth) },
|
|
25
26
|
controls: [
|
|
26
27
|
{ key: 'g', label: 'Group', selected: () => groupId ?? 'all', items: () => [{ value: 'all', label: 'All' },
|
|
27
28
|
...groups().map(group => ({ value: group.id, label: `${group.id}` }))], select: value => { groupId = value === 'all' ? undefined : value; } },
|
|
@@ -32,11 +33,19 @@ export class TaskBrowserView extends BrowserView {
|
|
|
32
33
|
if (groupId && !groups().some(group => group.id === groupId)) groupId = undefined;
|
|
33
34
|
const snapshot = current(); views = new Map(taskViews(snapshot).map(task => [taskReferenceKey(snapshot.generation, task.id), task]));
|
|
34
35
|
const byId = new Map([...views.values()].map(task => [task.id, task]));
|
|
35
|
-
|
|
36
|
-
label: taskRow(task),
|
|
37
|
-
description: task.progress ? `${task.progress.done}/${task.progress.total}` : '',
|
|
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),
|
|
38
38
|
search: `${task.id} ${task.title} ${task.description ?? ''} ${task.blockedReason ?? ''} ${task.status}`,
|
|
39
|
-
details: () => taskDetailsView(task, byId) }));
|
|
39
|
+
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;
|
|
40
49
|
} }, done, theme);
|
|
41
50
|
}
|
|
42
51
|
}
|
package/src/ui/browser.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { controlRows, cycle, divider, displayText, emptyRow, focusLabel, keyHint
|
|
|
13
13
|
export type { BrowseChoice, BrowseControl, BrowseSelection } from './browser-chrome.ts';
|
|
14
14
|
import { detailsContent, type StructuredDetails } from './structured-details.ts';
|
|
15
15
|
|
|
16
|
-
export interface BrowseItem extends SelectItem { search?: string; status?: string; display?: DisplayText; details?: () => string | StructuredDetails | Component }
|
|
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'> & {
|
|
18
18
|
truncatePrimary?: (context: Parameters<NonNullable<SelectListLayoutOptions['truncatePrimary']>>[0] & {theme?: Theme}) => string;
|
|
19
19
|
};
|
|
@@ -46,6 +46,8 @@ export interface BrowseOptions {
|
|
|
46
46
|
selection?: (item: BrowseItem) => BrowseSelection;
|
|
47
47
|
navigation?: ViewerNavigation;
|
|
48
48
|
layout?: BrowseLayout;
|
|
49
|
+
/** Use a full-width list and hide the Details shortcut when selection has no reader. */
|
|
50
|
+
optionalDetails?: boolean;
|
|
49
51
|
}
|
|
50
52
|
|
|
51
53
|
/** A shared native list owns selection identities; details never become another data source. */
|
|
@@ -142,9 +144,9 @@ export class BrowserView extends Container {
|
|
|
142
144
|
// A confirmation belongs to one record. Moving selection cannot stop the next one.
|
|
143
145
|
if (value !== this.actionOwner) { this.bar.disarm(); this.actionOwner = value; }
|
|
144
146
|
const item = this.items.find(item => item.value === value);
|
|
145
|
-
|
|
147
|
+
const details = item?.details?.();
|
|
148
|
+
if (!item || details === undefined) { this.reader = undefined; return; }
|
|
146
149
|
// Each identity retains its own search and scroll when another row or action is opened.
|
|
147
|
-
const details = item.details();
|
|
148
150
|
const content = typeof details === 'string' ? new Text(sanitizeText(details), 0, 0)
|
|
149
151
|
: 'rows' in details ? detailsContent(details, this.theme) : details;
|
|
150
152
|
this.reader = this.options.state.readers.get(item.value);
|
|
@@ -169,6 +171,7 @@ export class BrowserView extends Container {
|
|
|
169
171
|
const { pages } = this.options;
|
|
170
172
|
return !pages || pages.items()[0]?.value === pages.selected();
|
|
171
173
|
}
|
|
174
|
+
private showDetailsPane(): boolean { return !this.options.optionalDetails || this.reader !== undefined; }
|
|
172
175
|
private navigation(): string {
|
|
173
176
|
const hint = (key: string, action: string) => keyHint(key, action, this.theme);
|
|
174
177
|
if (this.focus === 'filter') return `Type to filter · ${hint('↑↓', 'select')} · ${hint('Enter', 'keep')} · ${hint('Esc', 'clear')}`;
|
|
@@ -179,7 +182,8 @@ export class BrowserView extends Container {
|
|
|
179
182
|
hint('Tab/Esc', 'list'), hint('↑↓ PgUp PgDn', 'scroll'), hint('/', 'search'), hint('n/N', 'next')].join(' · ');
|
|
180
183
|
return [...close, hint('Esc', this.options.state.query ? 'clear filter' : this.options.navigation ? 'back' : 'close'),
|
|
181
184
|
...pages ? [hint(`1-${Math.min(9, pages.items().length)} / ${firstPage ? '→' : '← →'} / [ ]`, 'page')] : [],
|
|
182
|
-
...controls.map(control => hint(control.key, control.label.toLowerCase())), hint('/', 'filter'),
|
|
185
|
+
...controls.map(control => hint(control.key, control.label.toLowerCase())), hint('/', 'filter'),
|
|
186
|
+
...this.showDetailsPane() ? [hint('Tab', 'details')] : []].join(' · ');
|
|
183
187
|
}
|
|
184
188
|
private help(): string {
|
|
185
189
|
const confirmation = this.bar.hint(this.theme);
|
|
@@ -203,21 +207,21 @@ export class BrowserView extends Container {
|
|
|
203
207
|
? this.composer.renderRows(width, Math.max(1, total - headerRows - 5)) : [];
|
|
204
208
|
const footerRows = composerRows.length || 1;
|
|
205
209
|
const height = Math.max(0, total - headerRows - footerRows - 3);
|
|
206
|
-
const
|
|
207
|
-
this.leftWidth =
|
|
208
|
-
const listHeight =
|
|
210
|
+
const split = width >= 80 && this.showDetailsPane();
|
|
211
|
+
this.leftWidth = split ? Math.min(52, Math.floor(width * 0.45)) : width;
|
|
212
|
+
const listHeight = split ? height : this.reader ? Math.min(height, this.focus === 'details' ? 2 : Math.max(2, Math.floor(height / 2))) : height;
|
|
209
213
|
this.visibleRows = Math.max(1, listHeight - 1);
|
|
210
214
|
this.update();
|
|
211
215
|
const listLines = readingWindow([paneHeading('List', this.leftWidth, this.active('list'), this.theme),
|
|
212
216
|
...this.items.length ? this.list.render(this.leftWidth) : [this.empty()]], listHeight);
|
|
213
|
-
const detailsHeight =
|
|
214
|
-
const detailsWidth =
|
|
217
|
+
const detailsHeight = split ? height : height - listHeight;
|
|
218
|
+
const detailsWidth = split ? width - this.leftWidth - 3 : width;
|
|
215
219
|
const detailBody = this.reader?.viewport(detailsWidth, Math.max(0, detailsHeight - 1), () => this.tui.requestRender()) ?? [];
|
|
216
220
|
const detailLines = readingWindow([this.reader ? readerHeading('Details', this.reader.position, this.reader.hasNewOutput, detailsWidth, this.theme, this.active('details'))
|
|
217
221
|
: paneHeading('Details', detailsWidth, false, this.theme), ...detailBody], detailsHeight);
|
|
218
222
|
// HStack combines already-bounded native list/reader output. It does not measure
|
|
219
223
|
// a live ScrollView twice at different widths or maintain another scroll offset.
|
|
220
|
-
const body =
|
|
224
|
+
const body = split ? new HStack([
|
|
221
225
|
{component: readingText(() => listLines), basis: this.leftWidth, shrink: 0},
|
|
222
226
|
{component: readingText(() => readingWindow([], height).map(() => divider(' │ ', this.theme))), basis: 3, shrink: 0},
|
|
223
227
|
{component: readingText(() => detailLines), basis: detailsWidth, shrink: 0},
|
package/src/ui/details.ts
CHANGED
|
@@ -10,12 +10,14 @@ import { commandFrame } from './frame.ts';
|
|
|
10
10
|
import { openReading, readingRows, readingText, readingWindow } from './reading.ts';
|
|
11
11
|
import { sanitizeText } from '../runtime/text.ts';
|
|
12
12
|
import { DoubleLeft, type ViewerNavigation } from './viewer/navigation.ts';
|
|
13
|
-
import {
|
|
13
|
+
import { plainDetailLines, readingDetailsContent, type StructuredDetails } from './structured-details.ts';
|
|
14
14
|
|
|
15
15
|
export interface DetailOptions {
|
|
16
16
|
title?: boolean;
|
|
17
17
|
/** One/two information rows; the shared frame supplies the separator and settles position. */
|
|
18
18
|
bottom?: (width: number) => string[];
|
|
19
|
+
/** One live status row directly under the content, above the metadata, e.g. the Working indicator. */
|
|
20
|
+
status?: (width: number) => string | undefined;
|
|
19
21
|
navigation?: ViewerNavigation;
|
|
20
22
|
keys?: KeybindingsManager;
|
|
21
23
|
}
|
|
@@ -53,13 +55,14 @@ export class DetailsView extends Container {
|
|
|
53
55
|
let information = this.options.bottom?.(width).slice(0, 2) ?? [];
|
|
54
56
|
let footer: string[] = [], bodyRows = 0;
|
|
55
57
|
const inline = this.composer.render(width);
|
|
58
|
+
const status = this.options.status?.(width), statusRows = status === undefined ? 0 : 1;
|
|
56
59
|
for (let pass = 0; pass < 2; pass++) {
|
|
57
60
|
const informationRows = this.options.bottom ? 1 + information.length : 0;
|
|
58
|
-
const footerLimit = Math.max(1, total - 2 - topRows - informationRows - 2);
|
|
61
|
+
const footerLimit = Math.max(1, total - 2 - topRows - informationRows - statusRows - 2);
|
|
59
62
|
footer = this.composer.active
|
|
60
63
|
? [...this.composer.renderRows(width, Math.max(1, footerLimit - 1)), this.composer.help()]
|
|
61
64
|
: this.reader.searching ? this.reader.search.render(width) : keyHelp(inline ?? help, width).slice(0, footerLimit);
|
|
62
|
-
bodyRows = Math.max(0, total - 3 - topRows - informationRows - footer.length);
|
|
65
|
+
bodyRows = Math.max(0, total - 3 - topRows - informationRows - statusRows - footer.length);
|
|
63
66
|
this.reader.updateLayout(lines.length, bodyRows, () => this.tui.requestRender());
|
|
64
67
|
const settled = this.options.bottom?.(width).slice(0, 2) ?? [];
|
|
65
68
|
const sameRows = settled.length === information.length;
|
|
@@ -72,7 +75,7 @@ export class DetailsView extends Container {
|
|
|
72
75
|
const body = readingWindow(lines.slice(this.reader.offset, this.reader.offset + bodyRows), bodyRows);
|
|
73
76
|
const top = [border(), ...topRows ? [readerHeading(this.title(), this.reader.position, this.reader.hasNewOutput, width, this.theme)] : []];
|
|
74
77
|
const metadata = this.options.bottom ? [separator(width, this.theme), ...information] : [];
|
|
75
|
-
const frame = new VStack([readingText(() => top), readingText(() => body), readingText(() => metadata),
|
|
78
|
+
const frame = new VStack([readingText(() => top), readingText(() => status === undefined ? body : [...body, status]), readingText(() => metadata),
|
|
76
79
|
readingText(() => [separator(width, this.theme), ...footer, border()])]);
|
|
77
80
|
return readingWindow(frame.render(width), total);
|
|
78
81
|
}
|
|
@@ -104,8 +107,20 @@ export async function showDetails(ctx: ExtensionContext, dock: Dock, title: stri
|
|
|
104
107
|
}
|
|
105
108
|
dock.setDetail(true);
|
|
106
109
|
try {
|
|
107
|
-
await openReading<void>(ctx, (tui, theme, keys, done) =>
|
|
108
|
-
typeof content !== 'string' ?
|
|
109
|
-
|
|
110
|
+
await openReading<void>(ctx, (tui, theme, keys, done) => {
|
|
111
|
+
const {body, output} = typeof content !== 'string' ? readingDetailsContent(content, theme) : {
|
|
112
|
+
body: format === 'text' ? new Text(sanitizeText(content), 0, 0) : new Markdown(content, 0, 0, getMarkdownTheme()),
|
|
113
|
+
};
|
|
114
|
+
const view = new DetailsView(tui, () => title, body, done, [], undefined, theme, {navigation, keys});
|
|
115
|
+
if (output) view.actions.push({key: 'e',
|
|
116
|
+
get label() { return output.expanded ? 'Collapse output' : 'Expand output'; },
|
|
117
|
+
run: () => {
|
|
118
|
+
// End follows the document tail. Stay at the summary instead of jumping to the end of the expanded result.
|
|
119
|
+
view.reader.pause();
|
|
120
|
+
output.toggle();
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
return view;
|
|
124
|
+
});
|
|
110
125
|
} finally { dock.setDetail(false); }
|
|
111
126
|
}
|
package/src/ui/dock.ts
CHANGED
|
@@ -41,6 +41,11 @@ export function heightBudget(rows: number, maxRows = 12, statusRow = false): num
|
|
|
41
41
|
return Math.max(0, Math.min(maxRows, Math.floor(rows / 2) - 1 - 3 - 2 - Number(statusRow)));
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
/** Share tree glyphs without making each caller use the same ancestry or width policy. */
|
|
45
|
+
export function treePrefix(kind: 'root' | 'child' | 'indent'): string {
|
|
46
|
+
return kind === 'root' ? '├─ ' : kind === 'child' ? '│ ' : ' ';
|
|
47
|
+
}
|
|
48
|
+
|
|
44
49
|
export class Dock implements Component {
|
|
45
50
|
private sources = new Map<string, DockSource>();
|
|
46
51
|
private tui?: TUI;
|
|
@@ -197,7 +202,7 @@ export class Dock implements Component {
|
|
|
197
202
|
...shown.map((row, index) => {
|
|
198
203
|
const selected = row.id === selectedId;
|
|
199
204
|
// Selection decorates the laid-out row; ancestry and suffix budgets never depend on focus.
|
|
200
|
-
const prefix = tree ? branch(row.parentId ? '
|
|
205
|
+
const prefix = tree ? branch(treePrefix(row.parentId ? 'child' : 'root'), index) : '';
|
|
201
206
|
const text = row.id.startsWith('overflow:') ? this.color('muted', this.row(row, Math.max(0, width - visibleWidth(prefix))))
|
|
202
207
|
: this.row(row, Math.max(0, width - visibleWidth(prefix)));
|
|
203
208
|
return selected ? selectedRow(prefix + text, width, this.theme, true, '') : prefix + text;
|
|
@@ -9,7 +9,8 @@ export function readPageFields(page: ReadPage & { stream: string }): ToolField[]
|
|
|
9
9
|
{ label: 'nextOffset', value: String(page.nextOffset) },
|
|
10
10
|
{ label: 'totalBytes', value: String(page.totalBytes) },
|
|
11
11
|
{ label: 'endOfStream', value: String(page.endOfStream) },
|
|
12
|
-
...page.
|
|
12
|
+
...page.firstLine !== undefined && page.lastLine !== undefined ? [{ label: 'lines', value: `${page.firstLine}-${page.lastLine}${page.totalLines !== undefined ? ` of ${page.totalLines}` : ''}` }] : [],
|
|
13
|
+
...page.matches !== undefined ? [{ label: 'matches', value: `${page.matches}${page.endOfStream ? '' : '+'}` }] : [],
|
|
13
14
|
...page.truncated ? [{ label: 'omittedBytes', value: String(page.truncated.omittedBytes) }] : [],
|
|
14
15
|
];
|
|
15
16
|
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import { Text } from '@earendil-works/pi-tui';
|
|
1
|
+
import { getMarkdownTheme, type Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Container, Markdown, Text, truncateToWidth, type Component } from '@earendil-works/pi-tui';
|
|
3
3
|
import { detailPartText, divider, heading, type DetailPart } from './browser-chrome.ts';
|
|
4
4
|
import { sanitizeText } from '../runtime/text.ts';
|
|
5
5
|
|
|
6
6
|
/** A section names the block below it (metadata, input, output) so long free text is never
|
|
7
7
|
* mistaken for a field value. It always starts a new group. */
|
|
8
8
|
export interface DetailSection { section: string }
|
|
9
|
-
export
|
|
9
|
+
export interface DetailOutput { output: string; markdown?: boolean }
|
|
10
|
+
export type DetailRow = string | readonly DetailPart[] | DetailSection | DetailOutput;
|
|
10
11
|
/** null marks a UI group break; undefined omits an optional row. */
|
|
11
12
|
export interface StructuredDetails { rows: readonly (DetailRow | null | undefined)[] }
|
|
12
13
|
|
|
@@ -15,27 +16,72 @@ export const statePart = (text: string | boolean, state = String(text)): DetailP
|
|
|
15
16
|
export const field = (label: string, value: DetailPart | string | number | boolean, ...suffix: DetailPart[]): DetailRow =>
|
|
16
17
|
[part(`${label} `, 'label'), typeof value === 'object' ? value : part(value), ...suffix];
|
|
17
18
|
export const section = (title: string): DetailSection => ({ section: title });
|
|
19
|
+
export const outputRow = (output: string, options?: Pick<DetailOutput, 'markdown'>): DetailOutput => ({ output, ...options });
|
|
18
20
|
const isSection = (row: DetailRow): row is DetailSection => typeof row === 'object' && 'section' in row;
|
|
21
|
+
const isOutput = (row: DetailRow): row is DetailOutput => typeof row === 'object' && 'output' in row;
|
|
19
22
|
const sectionText = (title: string, theme?: Theme) => `${divider('──', theme)} ${heading(sanitizeText(title), theme)} ${divider('──', theme)}`;
|
|
20
23
|
|
|
21
|
-
/**
|
|
24
|
+
/** Non-TUI receipts keep the original text: expansion is local to the interactive reader. */
|
|
22
25
|
export function plainDetailLines({ rows }: StructuredDetails): string[] {
|
|
23
|
-
return rows.flatMap(row => row == null ? [] : [typeof row === 'string' ? row : isSection(row) ? `── ${row.section} ──`
|
|
26
|
+
return rows.flatMap(row => row == null ? [] : [typeof row === 'string' ? row : isSection(row) ? `── ${row.section} ──`
|
|
27
|
+
: isOutput(row) ? row.output : row.map(({text}) => text).join('')]);
|
|
24
28
|
}
|
|
25
29
|
|
|
26
|
-
|
|
27
|
-
const lines: string[] = [];
|
|
30
|
+
function detailLines({ rows }: StructuredDetails, theme?: Theme): (string | DetailOutput)[] {
|
|
31
|
+
const lines: (string | DetailOutput)[] = [];
|
|
28
32
|
let gap = false;
|
|
29
33
|
for (const row of rows) {
|
|
30
34
|
if (row === undefined) continue;
|
|
31
35
|
if (row === null) { gap = true; continue; }
|
|
32
|
-
const line = isSection(row) ? sectionText(row.section, theme)
|
|
33
|
-
: (typeof row === 'string' ? [part(row)] : row).map(value => detailPartText(value, theme)).join('');
|
|
34
36
|
if ((gap || isSection(row)) && lines.length) lines.push('');
|
|
35
|
-
lines.push(
|
|
37
|
+
lines.push(isOutput(row) ? row : isSection(row) ? sectionText(row.section, theme)
|
|
38
|
+
: (typeof row === 'string' ? [part(row)] : row).map(value => detailPartText(value, theme)).join(''));
|
|
36
39
|
gap = false;
|
|
37
40
|
}
|
|
38
|
-
return lines
|
|
41
|
+
return lines;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const joinDetailLines = (lines: (string | DetailOutput)[]): string =>
|
|
45
|
+
lines.map(line => typeof line === 'string' ? line : sanitizeText(line.output)).join('\n');
|
|
46
|
+
|
|
47
|
+
export function detailsText(details: StructuredDetails, theme?: Theme): string {
|
|
48
|
+
return joinDetailLines(detailLines(details, theme));
|
|
39
49
|
}
|
|
40
50
|
|
|
41
51
|
export const detailsContent = (details: StructuredDetails, theme?: Theme): Text => new Text(detailsText(details, theme), 0, 0);
|
|
52
|
+
|
|
53
|
+
/** Output owns only its display state, not ToolRenderer's tool invocation and result templates. */
|
|
54
|
+
class DetailOutputView implements Component {
|
|
55
|
+
expanded = false;
|
|
56
|
+
private readonly summary: string;
|
|
57
|
+
private body?: Component;
|
|
58
|
+
|
|
59
|
+
constructor(private row: DetailOutput) {
|
|
60
|
+
const count = row.output ? row.output.split('\n').length : 0;
|
|
61
|
+
this.summary = `Output: ${count} ${count === 1 ? 'line' : 'lines'} · e expand`;
|
|
62
|
+
}
|
|
63
|
+
toggle(): void { this.expanded = !this.expanded; }
|
|
64
|
+
invalidate(): void { this.body?.invalidate(); }
|
|
65
|
+
render(width: number): readonly string[] {
|
|
66
|
+
if (!this.expanded) return [truncateToWidth(this.summary, width)];
|
|
67
|
+
// Defer Markdown construction until the user opens the result; keep its native render cache.
|
|
68
|
+
if (!this.body) {
|
|
69
|
+
const text = sanitizeText(this.row.output);
|
|
70
|
+
this.body = this.row.markdown ? new Markdown(text, 0, 0, getMarkdownTheme()) : new Text(text, 0, 0);
|
|
71
|
+
}
|
|
72
|
+
return this.body.render(width);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Only the dedicated detail reader binds a toggle; list previews still use static detailsContent. */
|
|
77
|
+
export function readingDetailsContent(details: StructuredDetails, theme?: Theme): { body: Component; output?: DetailOutputView } {
|
|
78
|
+
const lines = detailLines(details, theme);
|
|
79
|
+
const index = lines.findIndex(line => typeof line !== 'string');
|
|
80
|
+
const row = lines[index];
|
|
81
|
+
if (row === undefined || typeof row === 'string') return { body: new Text(joinDetailLines(lines), 0, 0) };
|
|
82
|
+
const output = new DetailOutputView(row), body = new Container();
|
|
83
|
+
body.addChild(new Text(joinDetailLines(lines.slice(0, index)), 0, 0));
|
|
84
|
+
body.addChild(output);
|
|
85
|
+
if (index + 1 < lines.length) body.addChild(new Text(joinDetailLines(lines.slice(index + 1)), 0, 0));
|
|
86
|
+
return {body, output};
|
|
87
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
|
|
3
|
+
// Same frames, interval and colors as Pi's built-in `Working` loader. pi-tui does not export its defaults.
|
|
4
|
+
const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
5
|
+
export const WORKING_INTERVAL_MS = 80;
|
|
6
|
+
|
|
7
|
+
/** One `⠇ Working` row. The frame follows the clock, so the caller only needs to re-render every interval. */
|
|
8
|
+
export function workingLine(theme: Theme, now = Date.now()): string {
|
|
9
|
+
const frame = FRAMES[Math.floor(now / WORKING_INTERVAL_MS) % FRAMES.length];
|
|
10
|
+
return `${theme.fg('accent', frame)} ${theme.fg('muted', 'Working')}`;
|
|
11
|
+
}
|