@lune_99/pi-shell-inspector 0.1.0 → 1.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.
@@ -15,22 +15,31 @@ import {
15
15
  renderFooter,
16
16
  renderHeader,
17
17
  } from "./inspector/frame.ts";
18
- import { BODY_TOP, listWindowStart, paneGeometry, type PaneGeometry } from "./inspector/geometry.ts";
18
+ import {
19
+ BODY_TOP,
20
+ listWindowStart,
21
+ paneGeometry,
22
+ type PaneGeometry,
23
+ } from "./inspector/geometry.ts";
19
24
  import { CommandPreviews, type ThemeColor } from "./inspector/job-format.ts";
20
25
  import { OutputRowsCache } from "./inspector/output-rows.ts";
21
26
  import { OutputViewport } from "./inspector/output-viewport.ts";
22
27
  import { renderDetails, renderEmptyList, renderJobList } from "./inspector/panes.ts";
23
28
  import { ScrollbarVisibility } from "./inspector/scrollbar.ts";
24
29
  import { formatShellCommand } from "./shell-command.ts";
25
- import { shellManager } from "./shell-manager.ts";
30
+ import type { ShellJob, ShellManager } from "./shell-manager.ts";
26
31
 
27
32
  const REFRESH_INTERVAL_MS = 1000;
28
33
 
29
- export async function openShellInspector(ctx: ExtensionContext): Promise<void> {
34
+ export async function openShellInspector(
35
+ ctx: ExtensionContext,
36
+ manager: ShellManager,
37
+ ): Promise<void> {
30
38
  await ctx.ui.custom<void>(
31
39
  (tui, _theme, _keybindings, done) => {
32
40
  const inspector = new ShellInspector(
33
41
  ctx,
42
+ manager,
34
43
  () => tui.requestRender(),
35
44
  () => done(),
36
45
  () => tui.terminal.rows,
@@ -62,17 +71,22 @@ export async function openShellInspector(ctx: ExtensionContext): Promise<void> {
62
71
  interface FrameLayout {
63
72
  geometry: PaneGeometry;
64
73
  listStart: number;
74
+ /** Job IDs as the list showed them, so a click selects the shell the user saw in that row. */
75
+ order: readonly string[];
65
76
  /** Columns of the back-to-bottom label on the bottom separator, while one is drawn. */
66
77
  backToBottom?: { start: number; end: number };
67
78
  }
68
79
 
69
80
  export class ShellInspector implements Component {
70
81
  private readonly ctx: ExtensionContext;
82
+ private readonly manager: ShellManager;
71
83
  private readonly requestRender: () => void;
72
84
  private readonly close: () => void;
73
85
  private readonly terminalRows: () => number;
74
86
  private readonly theme: Theme;
75
87
 
88
+ private selectedId: string | undefined;
89
+ /** Row of the selection in the last frame, which a cleared shell leaves to the next one. */
76
90
  private selectedIndex = 0;
77
91
  private unsubscribeJobs: (() => void) | undefined;
78
92
  private refreshTimer: ReturnType<typeof setInterval> | undefined;
@@ -87,12 +101,14 @@ export class ShellInspector implements Component {
87
101
 
88
102
  constructor(
89
103
  ctx: ExtensionContext,
104
+ manager: ShellManager,
90
105
  requestRender: () => void,
91
106
  close: () => void,
92
107
  terminalRows: () => number = () => 40,
93
108
  theme: Theme = ctx.ui.theme,
94
109
  ) {
95
110
  this.ctx = ctx;
111
+ this.manager = manager;
96
112
  this.requestRender = requestRender;
97
113
  this.close = close;
98
114
  this.terminalRows = terminalRows;
@@ -101,11 +117,11 @@ export class ShellInspector implements Component {
101
117
  this.scrollbars = new ScrollbarVisibility(() => this.requestRender());
102
118
  this.footerNotice = new FooterNotice(() => this.requestRender());
103
119
 
104
- // The index is memory-only state on the manager: reopening the overlay resumes the last
105
- // selection, while a fresh session starts on the first shell.
106
- this.selectedIndex = shellManager.getInspectorIndex();
120
+ // The selection is memory-only state on the manager: reopening the overlay resumes the last
121
+ // shell, while a fresh session starts on the first shell.
122
+ this.selectedId = this.manager.getInspectorJobId();
107
123
 
108
- this.unsubscribeJobs = shellManager.subscribe(() => {
124
+ this.unsubscribeJobs = this.manager.subscribe(() => {
109
125
  this.syncRefreshTimer();
110
126
  this.requestRender();
111
127
  });
@@ -120,26 +136,22 @@ export class ShellInspector implements Component {
120
136
  return;
121
137
  }
122
138
 
123
- const jobs = shellManager.getAllJobsList();
139
+ const selected = this.selectedJob();
124
140
 
125
- if (jobs.length === 0) {
141
+ if (!selected) {
126
142
  return;
127
143
  }
128
144
 
129
145
  if (data === "x") {
130
- const chosenJob = jobs[this.selectedIndex];
131
-
132
- if (chosenJob) {
133
- shellManager.settleJob(chosenJob.id, {
134
- type: "killed",
135
- error: "Shell killed by user",
136
- });
137
- }
146
+ this.manager.settleJob(selected.id, {
147
+ type: "killed",
148
+ error: "Shell killed by user",
149
+ });
138
150
  return;
139
151
  }
140
152
 
141
153
  if (data === "c") {
142
- this.clearSelectedJob(jobs[this.selectedIndex]);
154
+ this.clearSelectedJob(selected);
143
155
  return;
144
156
  }
145
157
 
@@ -216,45 +228,48 @@ export class ShellInspector implements Component {
216
228
  }
217
229
 
218
230
  const row = event.y - BODY_TOP;
219
- const index = layout.listStart + row;
220
- const jobCount = shellManager.getAllJobsList().length;
221
231
 
222
- if (
223
- event.x < 1 ||
224
- event.x >= rightStart - 1 ||
225
- row < 0 ||
226
- row >= bodyHeight ||
227
- index >= jobCount
228
- ) {
232
+ if (event.x < 1 || event.x >= rightStart - 1 || row < 0 || row >= bodyHeight) {
229
233
  return undefined;
230
234
  }
231
235
 
232
- this.selectJob(index, jobCount);
236
+ const jobs = this.listedJobs();
237
+ const index = jobs.findIndex((job) => job.id === layout.order[layout.listStart + row]);
238
+
239
+ if (index === -1) {
240
+ return undefined;
241
+ }
242
+
243
+ this.selectJob(jobs, index);
233
244
 
234
245
  return { handled: true };
235
246
  }
236
247
 
237
248
  render(width: number): string[] {
238
- const jobs = shellManager.getAllJobsList();
249
+ const jobs = this.listedJobs();
239
250
  const hasJobs = jobs.length > 0;
240
251
 
241
252
  this.syncRefreshTimer();
242
253
 
254
+ const index = this.selectionIndex(jobs);
255
+
243
256
  if (hasJobs) {
244
- this.selectedIndex = Math.min(this.selectedIndex, jobs.length - 1);
257
+ this.selectedIndex = index;
258
+ this.selectedId = jobs[index]!.id;
245
259
  } else {
246
260
  this.selectedIndex = 0;
261
+ this.selectedId = undefined;
247
262
  this.viewport.reset();
248
263
  }
249
264
 
250
- // The clamped index is what the user sees, so it is also what a later reopen should restore.
251
- shellManager.setInspectorIndex(this.selectedIndex);
265
+ // The shell the user sees is also what a later reopen should restore.
266
+ this.manager.setInspectorJobId(this.selectedId);
252
267
 
253
268
  const geometry = paneGeometry(width, this.terminalRows());
254
269
  const { bodyHeight, leftWidth, rightWidth } = geometry;
255
270
  const listStart = listWindowStart(this.selectedIndex, jobs.length, bodyHeight);
256
271
 
257
- const layout: FrameLayout = { geometry, listStart };
272
+ const layout: FrameLayout = { geometry, listStart, order: jobs.map((job) => job.id) };
258
273
  this.layout = layout;
259
274
 
260
275
  const left = hasJobs
@@ -284,7 +299,7 @@ export class ShellInspector implements Component {
284
299
  this.previews,
285
300
  {
286
301
  job,
287
- output: this.outputs.get(shellManager, job.id, this.outputWidth),
302
+ output: this.outputs.get(this.manager, job.id, this.outputWidth),
288
303
  viewport: this.viewport,
289
304
  showScrollbar: this.scrollbars.isVisible("output"),
290
305
  },
@@ -298,7 +313,7 @@ export class ShellInspector implements Component {
298
313
  this.theme,
299
314
  geometry.innerWidth,
300
315
  jobs.length,
301
- shellManager.jobsStatusStat.runningCount,
316
+ this.manager.jobsStatusStat.runningCount,
302
317
  );
303
318
  const separator = renderBottomSeparator(
304
319
  this.theme,
@@ -337,14 +352,19 @@ export class ShellInspector implements Component {
337
352
  this.unsubscribeJobs = undefined;
338
353
  }
339
354
 
340
- private clearSelectedJob(job: Readonly<{ id: string; label?: string; command: string }> | undefined): void {
355
+ private clearSelectedJob(
356
+ job: Readonly<{ id: string; label?: string; command: string }> | undefined,
357
+ ): void {
341
358
  if (!job) {
342
359
  return;
343
360
  }
344
361
 
345
- if (shellManager.clearJob(job.id)) {
362
+ if (this.manager.clearJob(job.id)) {
346
363
  this.viewport.follow();
347
- this.showNotice(`Cleared ${formatShellCommand(job.label ?? job.command, 28)}`, "success");
364
+ this.showNotice(
365
+ `Cleared ${formatShellCommand(job.label ?? job.command, 28)}`,
366
+ "success",
367
+ );
348
368
  } else {
349
369
  this.showNotice("Clear failed, only completed, failed, or killed", "accent");
350
370
  }
@@ -355,29 +375,61 @@ export class ShellInspector implements Component {
355
375
  this.requestRender();
356
376
  }
357
377
 
378
+ /**
379
+ * Running shells first. Both parts keep start order, so rows move only as shells start or settle.
380
+ */
381
+ private listedJobs(): readonly Readonly<ShellJob>[] {
382
+ const jobs = this.manager.getAllJobsList();
383
+
384
+ return [
385
+ ...jobs.filter((job) => job.status === "running"),
386
+ ...jobs.filter((job) => job.status !== "running"),
387
+ ];
388
+ }
389
+
390
+ /**
391
+ * The selected shell's row, or -1 without shells. A cleared shell leaves its row to the next one.
392
+ */
393
+ private selectionIndex(jobs: readonly Readonly<ShellJob>[]): number {
394
+ const index = jobs.findIndex((job) => job.id === this.selectedId);
395
+
396
+ return index === -1 ? Math.min(this.selectedIndex, jobs.length - 1) : index;
397
+ }
398
+
399
+ private selectedJob(): Readonly<ShellJob> | undefined {
400
+ const jobs = this.listedJobs();
401
+
402
+ return jobs[this.selectionIndex(jobs)];
403
+ }
404
+
358
405
  private moveSelection(step: number): void {
359
- const jobCount = shellManager.getAllJobsList().length;
406
+ const jobs = this.listedJobs();
360
407
 
361
- if (jobCount === 0 || step === 0) {
408
+ if (jobs.length === 0 || step === 0) {
362
409
  return;
363
410
  }
364
411
 
365
- this.selectJob(Math.min(jobCount - 1, Math.max(0, this.selectedIndex + step)), jobCount);
412
+ const index = this.selectionIndex(jobs);
413
+
414
+ this.selectJob(jobs, Math.min(jobs.length - 1, Math.max(0, index + step)));
366
415
  }
367
416
 
368
- private selectJob(index: number, jobCount: number): void {
369
- if (index === this.selectedIndex) {
417
+ private selectJob(jobs: readonly Readonly<ShellJob>[], index: number): void {
418
+ const job = jobs[index];
419
+
420
+ if (!job || job.id === this.selectedId) {
370
421
  return;
371
422
  }
372
423
 
424
+ this.selectedId = job.id;
373
425
  this.selectedIndex = index;
374
- shellManager.setInspectorIndex(index);
426
+ this.manager.setInspectorJobId(job.id);
375
427
 
376
428
  // A different job has a different output; reading it from the middle would be confusing.
377
429
  this.viewport.follow();
378
430
  this.scrollbars.hide("output");
379
431
 
380
- if (this.layout && jobCount > this.layout.geometry.bodyHeight) {
432
+ if (this.layout && jobs.length > this.layout.geometry.bodyHeight) {
381
433
  this.scrollbars.show("jobs");
382
434
  }
383
435
 
@@ -385,14 +437,14 @@ export class ShellInspector implements Component {
385
437
  }
386
438
 
387
439
  private scrollOutput(step: number): void {
388
- const job = shellManager.getAllJobsList()[this.selectedIndex];
440
+ const job = this.selectedJob();
389
441
 
390
442
  if (!job) {
391
443
  return;
392
444
  }
393
445
 
394
446
  const result = this.viewport.scrollBy(step, () =>
395
- this.outputs.get(shellManager, job.id, this.outputWidth),
447
+ this.outputs.get(this.manager, job.id, this.outputWidth),
396
448
  );
397
449
 
398
450
  if (result === "ignored") {
@@ -423,7 +475,7 @@ export class ShellInspector implements Component {
423
475
  }
424
476
 
425
477
  private syncRefreshTimer(): void {
426
- const hasRunningJobs = shellManager.jobsStatusStat.runningCount > 0;
478
+ const hasRunningJobs = this.manager.jobsStatusStat.runningCount > 0;
427
479
 
428
480
  if (hasRunningJobs && !this.refreshTimer) {
429
481
  this.refreshTimer = setInterval(() => {
@@ -1,14 +1,16 @@
1
- import { DEFAULT_MAX_LINES, truncateTail, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ import {
2
+ DEFAULT_MAX_LINES,
3
+ truncateTail,
4
+ type ExtensionAPI,
5
+ type ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
2
7
  import xterm, { type Terminal as XtermTerminal } from "@xterm/headless";
3
8
 
4
9
  // @xterm/headless ships CommonJS, and its UMD factory hides the exports from Node's
5
10
  // named-export detection, so the class has to come off the default import.
6
11
  const { Terminal } = xterm;
7
12
 
8
- import {
9
- appendFileSync,
10
- writeFileSync,
11
- } from "node:fs";
13
+ import { appendFileSync, writeFileSync } from "node:fs";
12
14
  import { join } from "node:path";
13
15
  import { randomUUID } from "node:crypto";
14
16
  import { tmpdir } from "node:os";
@@ -35,11 +37,7 @@ const screenRevisions = new WeakMap<XtermTerminal, number>();
35
37
  // Beside the terminal instead of on ShellJob: the job record is what tests and the snapshot see.
36
38
  const screenFeeds = new WeakMap<XtermTerminal, ScreenFeed>();
37
39
 
38
- export type ShellJobStatus =
39
- | "running"
40
- | "completed"
41
- | "failed"
42
- | "killed";
40
+ export type ShellJobStatus = "running" | "completed" | "failed" | "killed";
43
41
 
44
42
  export interface ShellJob {
45
43
  id: string;
@@ -95,22 +93,22 @@ export type ShellManagerEvent =
95
93
  | { type: "job-killed"; id: string }
96
94
  | { type: "job-cleared"; id: string }
97
95
  | { type: "output-updated"; id: string }
98
- | { type: "jobs-cleared" }
96
+ | { type: "jobs-cleared" };
99
97
 
100
98
  export type ShellJobOutcome =
101
99
  | {
102
- type: "completed";
103
- exitCode?: number;
104
- }
100
+ type: "completed";
101
+ exitCode?: number;
102
+ }
105
103
  | {
106
- type: "failed";
107
- error: string;
108
- exitCode?: number;
109
- }
104
+ type: "failed";
105
+ error: string;
106
+ exitCode?: number;
107
+ }
110
108
  | {
111
- type: "killed";
112
- error?: string;
113
- };
109
+ type: "killed";
110
+ error?: string;
111
+ };
114
112
 
115
113
  export type ShellManagerListener = (event: ShellManagerEvent) => void;
116
114
 
@@ -120,12 +118,12 @@ export class ShellManager {
120
118
  readonly jobsStatusStat: JobsStatusStat;
121
119
 
122
120
  /**
123
- * 0-based index of the shell the inspector last showed.
121
+ * ID of the shell the inspector last showed.
124
122
  *
125
123
  * Memory-only view state: it stays out of the session snapshot, so a reloaded, resumed or
126
124
  * tree-restored session opens the inspector on the first shell again.
127
125
  */
128
- private inspectorIndex = 0;
126
+ private inspectorJobId: string | undefined;
129
127
 
130
128
  constructor() {
131
129
  this.jobsStatusStat = {
@@ -173,12 +171,12 @@ export class ShellManager {
173
171
 
174
172
  this.emit({
175
173
  type: "job-started",
176
- id: input.id
174
+ id: input.id,
177
175
  });
178
176
  }
179
177
 
180
178
  /**
181
- *
179
+ *
182
180
  * @param pi The extension API instance, used to persist the current state of all jobs and their statistics to the pi session log.
183
181
  */
184
182
  clearAllJobs(pi?: ExtensionAPI): void {
@@ -191,8 +189,8 @@ export class ShellManager {
191
189
  // Persist the current state of all jobs and their statistics to the pi session log.
192
190
  if (pi) {
193
191
  pi.appendEntry("pi-shell-inspector-view-status", {
194
- jobs: this.getAllJobsList().map(job => this.getJobSnapshot(job.id)),
195
- stats: this.getAllJobsStatusStat()
192
+ jobs: this.getAllJobsList().map((job) => this.getJobSnapshot(job.id)),
193
+ stats: this.getAllJobsStatusStat(),
196
194
  });
197
195
  }
198
196
 
@@ -204,16 +202,13 @@ export class ShellManager {
204
202
  // clear the manager status before emitting the jobs-cleared event
205
203
  this.jobs.clear();
206
204
  this.clearManagerstatus();
207
- this.inspectorIndex = 0;
205
+ this.inspectorJobId = undefined;
208
206
  this.emit({
209
- type: "jobs-cleared"
207
+ type: "jobs-cleared",
210
208
  });
211
- };
209
+ }
212
210
 
213
- appendOutput(
214
- id: string,
215
- chunk: string,
216
- ): void {
211
+ appendOutput(id: string, chunk: string): void {
217
212
  const job = this.getRunningJob(id);
218
213
  const next = job.output.content + chunk;
219
214
  job.output.totalBytes += Buffer.byteLength(chunk);
@@ -228,10 +223,7 @@ export class ShellManager {
228
223
  if (!truncation.truncated) {
229
224
  job.output.content = next;
230
225
  } else {
231
- const path = join(
232
- tmpdir(),
233
- `pi-shell-inspector-bash-${randomUUID()}.log`,
234
- );
226
+ const path = join(tmpdir(), `pi-shell-inspector-bash-${randomUUID()}.log`);
235
227
  writeFileSync(path, next, "utf8");
236
228
 
237
229
  job.output.fullOutputPath = path;
@@ -248,7 +240,7 @@ export class ShellManager {
248
240
 
249
241
  this.emit({
250
242
  type: "output-updated",
251
- id: id
243
+ id: id,
252
244
  });
253
245
  }
254
246
 
@@ -317,24 +309,20 @@ export class ShellManager {
317
309
  return Array.from(this.jobs.values());
318
310
  }
319
311
 
320
- getInspectorIndex(): number {
321
- return this.inspectorIndex;
312
+ getInspectorJobId(): string | undefined {
313
+ return this.inspectorJobId;
322
314
  }
323
315
 
324
- setInspectorIndex(index: number): void {
325
- this.inspectorIndex = index;
316
+ setInspectorJobId(id: string | undefined): void {
317
+ this.inspectorJobId = id;
326
318
  }
327
319
 
328
320
  getRunningJobsList(): readonly Readonly<ShellJob>[] {
329
- return Array.from(this.jobs.values()).filter(
330
- (job) => job.status === "running",
331
- );
321
+ return Array.from(this.jobs.values()).filter((job) => job.status === "running");
332
322
  }
333
323
 
334
324
  getCompletedJobsList(): readonly Readonly<ShellJob>[] {
335
- return Array.from(this.jobs.values()).filter(
336
- (job) => job.status === "completed",
337
- );
325
+ return Array.from(this.jobs.values()).filter((job) => job.status === "completed");
338
326
  }
339
327
 
340
328
  getAllJobsStatusStat(): JobsStatusStat {
@@ -354,10 +342,7 @@ export class ShellManager {
354
342
  };
355
343
  }
356
344
 
357
- settleJob(
358
- id: string,
359
- outcome: ShellJobOutcome,
360
- ): boolean {
345
+ settleJob(id: string, outcome: ShellJobOutcome): boolean {
361
346
  // Settling is idempotent: the detached execution can race session teardown, and a job that
362
347
  // is unknown or no longer running must not be settled again (or counted twice).
363
348
  if (this.getJob(id)?.status !== "running") {
@@ -379,9 +364,9 @@ export class ShellManager {
379
364
  const shellStateEntry = [...ctx.sessionManager.getBranch()]
380
365
  .reverse()
381
366
  .find(
382
- entry =>
367
+ (entry) =>
383
368
  entry.type === "custom" &&
384
- entry.customType === "pi-shell-inspector-view-status"
369
+ entry.customType === "pi-shell-inspector-view-status",
385
370
  );
386
371
 
387
372
  if (!shellStateEntry || shellStateEntry.type !== "custom") return;
@@ -420,9 +405,7 @@ export class ShellManager {
420
405
  const job = this.requireJob(id);
421
406
 
422
407
  if (job.status !== "running") {
423
- throw new Error(
424
- `Shell job "${id}" is not running: ${job.status}`,
425
- );
408
+ throw new Error(`Shell job "${id}" is not running: ${job.status}`);
426
409
  }
427
410
 
428
411
  return job;
@@ -432,7 +415,7 @@ export class ShellManager {
432
415
  for (const listener of this.listeners) {
433
416
  try {
434
417
  listener(event);
435
- } catch (error) {
418
+ } catch {
436
419
  // Ignore errors thrown by listeners to prevent one failing listener from affecting others.
437
420
  }
438
421
  }
@@ -452,15 +435,11 @@ export class ShellManager {
452
435
 
453
436
  this.emit({
454
437
  type: "job-completed",
455
- id: id
438
+ id: id,
456
439
  });
457
440
  }
458
441
 
459
- private failJob(
460
- id: string,
461
- error: string,
462
- exitCode?: number,
463
- ): void {
442
+ private failJob(id: string, error: string, exitCode?: number): void {
464
443
  const job = this.getRunningJob(id);
465
444
  const now = Date.now();
466
445
 
@@ -475,7 +454,7 @@ export class ShellManager {
475
454
 
476
455
  this.emit({
477
456
  type: "job-failed",
478
- id: id
457
+ id: id,
479
458
  });
480
459
  }
481
460
 
@@ -495,7 +474,7 @@ export class ShellManager {
495
474
 
496
475
  this.emit({
497
476
  type: "job-killed",
498
- id: id
477
+ id: id,
499
478
  });
500
479
  }
501
480
 
@@ -526,7 +505,7 @@ export class ShellManager {
526
505
 
527
506
  this.emit({
528
507
  type: "job-cleared",
529
- id: id
508
+ id: id,
530
509
  });
531
510
  return true;
532
511
  }
@@ -562,8 +541,8 @@ export class ShellManager {
562
541
  totalLines: job.output.totalLines,
563
542
  totalBytes: job.output.totalBytes,
564
543
  fullOutputPath: job.output.fullOutputPath,
565
- }
566
- }
544
+ },
545
+ };
567
546
  }
568
547
  }
569
548
 
@@ -589,7 +568,3 @@ function disposeScreen(terminal: XtermTerminal): void {
589
568
  screenFeeds.get(terminal)?.dispose();
590
569
  terminal.dispose();
591
570
  }
592
-
593
- // Shared singleton: its state outlives extension reloads, which is why the
594
- // extension clears it explicitly on session start.
595
- export const shellManager = new ShellManager();