@narumitw/pi-notes 0.0.0 → 0.2.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.
package/src/workspace.ts CHANGED
@@ -1,26 +1,63 @@
1
1
  import type { ExtensionCommandContext, KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
+ decodeKittyPrintable,
3
4
  Editor,
4
5
  type EditorTheme,
6
+ getKeybindings,
5
7
  Key,
6
8
  Markdown,
7
9
  matchesKey,
10
+ setKeybindings,
8
11
  type TUI,
12
+ TUI_KEYBINDINGS,
13
+ KeybindingsManager as TuiKeybindingsManager,
14
+ type TuiMouseEvent,
15
+ type TuiMouseEventResult,
9
16
  truncateToWidth,
10
17
  visibleWidth,
11
18
  } from "@earendil-works/pi-tui";
12
- import { runCustomInteraction } from "@narumitw/pi-tui-kit/custom-interaction";
13
19
  import { hardWrapTerminalDocument, sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
14
20
  import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
15
21
  import { createNotesChildSession, type NotesChildSession } from "./child-session.js";
16
22
  import { MAX_TRANSCRIPT_CHARS, MAX_TRANSCRIPT_MESSAGES, WIDE_WORKSPACE_COLUMNS } from "./constants.js";
23
+ import { runFullscreenInteraction } from "./fullscreen.js";
17
24
  import type { NoteSnapshot, NotesStorage } from "./storage.js";
18
25
 
19
26
  type CreateChildSession = typeof createNotesChildSession;
20
27
  type Pane = "chat" | "preview";
21
28
 
29
+ // Tab remains workspace navigation unless another focused-editor action shares its input.
30
+ const EDITOR_PRIORITY_ACTIONS = [
31
+ "tui.editor.cursorUp",
32
+ "tui.editor.cursorDown",
33
+ "tui.editor.historyPrevious",
34
+ "tui.editor.historyNext",
35
+ "tui.editor.cursorLeft",
36
+ "tui.editor.cursorRight",
37
+ "tui.editor.cursorWordLeft",
38
+ "tui.editor.cursorWordRight",
39
+ "tui.editor.cursorLineStart",
40
+ "tui.editor.cursorLineEnd",
41
+ "tui.editor.jumpForward",
42
+ "tui.editor.jumpBackward",
43
+ "tui.editor.pageUp",
44
+ "tui.editor.pageDown",
45
+ "tui.editor.deleteCharBackward",
46
+ "tui.editor.deleteCharForward",
47
+ "tui.editor.deleteWordBackward",
48
+ "tui.editor.deleteWordForward",
49
+ "tui.editor.deleteToLineStart",
50
+ "tui.editor.deleteToLineEnd",
51
+ "tui.editor.yank",
52
+ "tui.editor.yankPop",
53
+ "tui.editor.undo",
54
+ "tui.input.newLine",
55
+ "tui.input.submit",
56
+ ] as const;
57
+
22
58
  export interface NotesWorkspaceDependencies {
23
59
  createChildSession?: CreateChildSession;
60
+ runInteraction?: typeof runFullscreenInteraction;
24
61
  }
25
62
 
26
63
  export interface OpenNotesWorkspaceOptions {
@@ -35,7 +72,8 @@ export interface OpenNotesWorkspaceOptions {
35
72
  }
36
73
 
37
74
  export async function openNotesWorkspace(options: OpenNotesWorkspaceOptions): Promise<void> {
38
- const interaction = await runCustomInteraction<"closed">(options.ctx, {
75
+ const runInteraction = options.dependencies?.runInteraction ?? runFullscreenInteraction;
76
+ const interaction = await runInteraction<"closed">(options.ctx, {
39
77
  signal: options.signal,
40
78
  isCurrent: options.isCurrent,
41
79
  create: ({ tui, theme, keybindings, signal, complete }) =>
@@ -83,6 +121,7 @@ export class NotesWorkspace {
83
121
  private child: NotesChildSession | undefined;
84
122
  private unsubscribe = () => {};
85
123
  private note: NoteSnapshot | undefined;
124
+ private notePath: string;
86
125
  private status = "Opening embedded note session…";
87
126
  private error: string | undefined;
88
127
  private pane: Pane = "chat";
@@ -99,11 +138,15 @@ export class NotesWorkspace {
99
138
  private promptTask: Promise<unknown> | undefined;
100
139
  private promptPreflightPending = false;
101
140
  private stopPromise: Promise<void> | undefined;
141
+ private editorMouseBounds:
142
+ | { x: number; y: number; width: number; visibleHeight: number; lineOffset: number; fullHeight: number }
143
+ | undefined;
102
144
  private _focused = false;
103
145
  private inPaste = false;
104
146
 
105
147
  constructor(options: NotesWorkspaceOptions) {
106
148
  this.options = options;
149
+ this.notePath = options.notePath;
107
150
  this.tui = options.tui;
108
151
  this.theme = options.theme;
109
152
  this.keybindings = options.keybindings;
@@ -143,9 +186,10 @@ export class NotesWorkspace {
143
186
 
144
187
  render(width: number): string[] {
145
188
  const safeWidth = Math.max(1, width);
146
- const availableRows = Math.max(1, this.tui.terminal.rows - 4);
189
+ const availableRows = Math.max(1, this.tui.terminal.rows - (this.tui.mode === "fullscreen" ? 0 : 4));
190
+ this.editorMouseBounds = undefined;
147
191
  const title = truncateToWidth(
148
- this.theme.fg("accent", this.theme.bold(`Pi Notes · ${sanitizeTerminalText(this.options.notePath)}`)),
192
+ this.theme.fg("accent", this.theme.bold(sanitizeTerminalText(this.notePath))),
149
193
  safeWidth,
150
194
  );
151
195
  const hint = truncateToWidth(this.theme.fg("muted", this.hintText()), safeWidth);
@@ -164,6 +208,10 @@ export class NotesWorkspace {
164
208
  this.close();
165
209
  return;
166
210
  }
211
+ if (this.editorOwnsWorkspaceCollision(data)) {
212
+ this.handlePriorityEditorInput(data);
213
+ return;
214
+ }
167
215
  if (this.keybindings.matches(data, "tui.select.cancel")) {
168
216
  this.close();
169
217
  return;
@@ -187,6 +235,35 @@ export class NotesWorkspace {
187
235
  this.tui.requestRender();
188
236
  }
189
237
 
238
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
239
+ if (this.disposed || this.finished) return undefined;
240
+ if (event.type === "wheel") {
241
+ const lines = Math.trunc(event.wheelDelta ?? 0);
242
+ if (lines === 0) return { handled: true, render: false };
243
+ this.scrollPane(this.paneAt(event.x, event.width), lines);
244
+ return { handled: true };
245
+ }
246
+ const bounds = this.editorMouseBounds;
247
+ if (
248
+ !bounds ||
249
+ event.x < bounds.x ||
250
+ event.x >= bounds.x + bounds.width ||
251
+ event.y < bounds.y ||
252
+ event.y >= bounds.y + bounds.visibleHeight
253
+ ) {
254
+ return undefined;
255
+ }
256
+ this.pane = "chat";
257
+ this.editor.focused = this._focused;
258
+ return this.editor.handleMouse({
259
+ ...event,
260
+ x: event.x - bounds.x,
261
+ y: event.y - bounds.y + bounds.lineOffset,
262
+ width: bounds.width,
263
+ height: bounds.fullHeight,
264
+ });
265
+ }
266
+
190
267
  invalidate(): void {
191
268
  this.editor.invalidate();
192
269
  }
@@ -221,19 +298,20 @@ export class NotesWorkspace {
221
298
  private async start(): Promise<void> {
222
299
  const generation = this.generation;
223
300
  try {
224
- const note = await this.options.storage.readNote(this.options.notePath, this.signal());
301
+ const note = await this.options.storage.readNote(this.notePath, this.signal());
225
302
  if (!this.isCurrent(generation)) return;
226
303
  this.note = note;
227
304
  const child = await this.options.createChildSession({
228
305
  agentDir: this.options.agentDir,
229
306
  storage: this.options.storage,
230
- notePath: this.options.notePath,
307
+ notePath: this.notePath,
231
308
  parentModel: this.options.parentModel,
232
309
  thinkingLevel: this.options.thinkingLevel,
233
310
  signal: this.signal(),
234
311
  onNoteChanged: (changed) => {
235
312
  if (!this.isCurrent(generation)) return;
236
313
  this.note = changed;
314
+ this.notePath = changed.relativePath;
237
315
  this.previewScroll = Math.min(this.previewScroll, this.maxPreviewScroll());
238
316
  this.tui.requestRender();
239
317
  },
@@ -297,7 +375,7 @@ export class NotesWorkspace {
297
375
  })
298
376
  .then(async () => {
299
377
  if (!this.isCurrent(generation)) return;
300
- const note = await this.options.storage.readNote(this.options.notePath, this.signal());
378
+ const note = await this.options.storage.readNote(this.notePath, this.signal());
301
379
  if (!this.isCurrent(generation)) return;
302
380
  this.note = note;
303
381
  this.status = "Ready";
@@ -325,7 +403,7 @@ export class NotesWorkspace {
325
403
  const separator = " │ ";
326
404
  const leftWidth = Math.max(1, Math.floor((width - visibleWidth(separator)) * 0.52));
327
405
  const rightWidth = Math.max(1, width - leftWidth - visibleWidth(separator));
328
- const left = this.renderChat(leftWidth, rows);
406
+ const left = this.renderChat(leftWidth, rows, 0, 1);
329
407
  const right = this.renderPreview(rightWidth, rows);
330
408
  const lines: string[] = [];
331
409
  for (let index = 0; index < rows; index += 1) {
@@ -337,10 +415,10 @@ export class NotesWorkspace {
337
415
  }
338
416
 
339
417
  private renderNarrow(width: number, rows: number): string[] {
340
- return this.pane === "chat" ? this.renderChat(width, rows) : this.renderPreview(width, rows);
418
+ return this.pane === "chat" ? this.renderChat(width, rows, 0, 1) : this.renderPreview(width, rows);
341
419
  }
342
420
 
343
- private renderChat(width: number, rows: number): string[] {
421
+ private renderChat(width: number, rows: number, originX: number, originY: number): string[] {
344
422
  const editorLines = this.editor.render(width);
345
423
  const header = truncateToWidth(
346
424
  this.theme.fg(this.pane === "chat" ? "accent" : "muted", `Chat · ${this.status}`),
@@ -358,7 +436,22 @@ export class NotesWorkspace {
358
436
  if (this.followTranscript) this.transcriptScroll = this.maxTranscriptScroll();
359
437
  this.transcriptScroll = clamp(this.transcriptScroll, 0, this.maxTranscriptScroll());
360
438
  const visible = transcript.slice(this.transcriptScroll, this.transcriptScroll + viewportRows);
361
- return [header, ...visible, ...errorLines, ...editorLines].slice(-rows);
439
+ const content = [header, ...visible, ...errorLines, ...editorLines];
440
+ const firstVisibleRow = Math.max(0, content.length - rows);
441
+ const editorStartRow = content.length - editorLines.length;
442
+ const firstVisibleEditorRow = Math.max(firstVisibleRow, editorStartRow);
443
+ const visibleEditorHeight = Math.max(0, content.length - firstVisibleEditorRow);
444
+ if (visibleEditorHeight > 0) {
445
+ this.editorMouseBounds = {
446
+ x: originX,
447
+ y: originY + firstVisibleEditorRow - firstVisibleRow,
448
+ width,
449
+ visibleHeight: visibleEditorHeight,
450
+ lineOffset: firstVisibleEditorRow - editorStartRow,
451
+ fullHeight: editorLines.length,
452
+ };
453
+ }
454
+ return content.slice(firstVisibleRow);
362
455
  }
363
456
 
364
457
  private renderPreview(width: number, rows: number): string[] {
@@ -414,24 +507,58 @@ export class NotesWorkspace {
414
507
  return lines;
415
508
  }
416
509
 
510
+ private editorOwnsWorkspaceCollision(data: string): boolean {
511
+ return (
512
+ this.pane === "chat" &&
513
+ (EDITOR_PRIORITY_ACTIONS.some((action) => this.keybindings.matches(data, action)) ||
514
+ matchesKey(data, "shift+backspace") ||
515
+ matchesKey(data, "shift+delete") ||
516
+ matchesKey(data, "shift+space") ||
517
+ isEditorNewLineAlias(data) ||
518
+ isEditorPrintableInput(data))
519
+ );
520
+ }
521
+
522
+ private handlePriorityEditorInput(data: string): void {
523
+ if (!this.keybindings.matches(data, "tui.input.tab")) {
524
+ this.editor.handleInput(data);
525
+ this.tui.requestRender();
526
+ return;
527
+ }
528
+ const current = getKeybindings();
529
+ const bindings = current.getResolvedBindings();
530
+ bindings["tui.input.tab"] = [];
531
+ setKeybindings(new TuiKeybindingsManager(TUI_KEYBINDINGS, bindings));
532
+ try {
533
+ this.editor.handleInput(data);
534
+ } finally {
535
+ setKeybindings(current);
536
+ }
537
+ this.tui.requestRender();
538
+ }
539
+
417
540
  private scroll(direction: -1 | 1): void {
418
- if (this.pane === "preview") {
419
- this.previewScroll = clamp(
420
- this.previewScroll + direction * Math.max(1, this.previewRows - 1),
421
- 0,
422
- this.maxPreviewScroll(),
423
- );
541
+ const rows = this.pane === "preview" ? this.previewRows : this.transcriptRows;
542
+ this.scrollPane(this.pane, direction * Math.max(1, rows - 1));
543
+ }
544
+
545
+ private scrollPane(pane: Pane, lines: number): void {
546
+ if (pane === "preview") {
547
+ this.previewScroll = clamp(this.previewScroll + lines, 0, this.maxPreviewScroll());
424
548
  } else {
425
- this.transcriptScroll = clamp(
426
- this.transcriptScroll + direction * Math.max(1, this.transcriptRows - 1),
427
- 0,
428
- this.maxTranscriptScroll(),
429
- );
549
+ this.transcriptScroll = clamp(this.transcriptScroll + lines, 0, this.maxTranscriptScroll());
430
550
  this.followTranscript = this.transcriptScroll === this.maxTranscriptScroll();
431
551
  }
432
552
  this.tui.requestRender();
433
553
  }
434
554
 
555
+ private paneAt(x: number, width: number): Pane {
556
+ if (width < WIDE_WORKSPACE_COLUMNS) return this.pane;
557
+ const separatorWidth = visibleWidth(" │ ");
558
+ const leftWidth = Math.max(1, Math.floor((width - separatorWidth) * 0.52));
559
+ return x < leftWidth + Math.floor(separatorWidth / 2) ? "chat" : "preview";
560
+ }
561
+
435
562
  private maxTranscriptScroll(): number {
436
563
  return Math.max(0, this.transcriptLineCount - this.transcriptRows);
437
564
  }
@@ -441,7 +568,7 @@ export class NotesWorkspace {
441
568
  }
442
569
 
443
570
  private hintText(): string {
444
- return "Submit sends · Switch-pane action changes Chat/Preview · Page actions scroll · Cancel closes · Ctrl+C hard-cancels";
571
+ return "Submit sends · Switch-pane action changes Chat/Preview · Page scrolls Preview · Wheel scrolls panes · Cancel closes · Ctrl+C hard-cancels";
445
572
  }
446
573
 
447
574
  private handlePaste(data: string): boolean {
@@ -503,6 +630,35 @@ export class NotesWorkspace {
503
630
  }
504
631
  }
505
632
 
633
+ function isEditorNewLineAlias(data: string): boolean {
634
+ // Mirror Pi Editor's unconditional compatibility inputs so workspace shortcuts cannot preempt them.
635
+ return (
636
+ (data.charCodeAt(0) === 10 && data.length > 1) ||
637
+ data === "\u001b\r" ||
638
+ data === "\u001b[13;2~" ||
639
+ (data.length > 1 && data.includes("\u001b") && data.includes("\r")) ||
640
+ (data === "\n" && data.length === 1)
641
+ );
642
+ }
643
+
644
+ function isEditorPrintableInput(data: string): boolean {
645
+ // Pi's root export exposes the Kitty decoder; mirror Editor's xterm modifyOtherKeys fallback.
646
+ if (decodeKittyPrintable(data) !== undefined || data.charCodeAt(0) >= 32) return true;
647
+ const modifyOtherKeysPrefix = "\u001b[27;";
648
+ if (!data.startsWith(modifyOtherKeysPrefix)) return false;
649
+ const match = data.slice(modifyOtherKeysPrefix.length).match(/^(\d+);(\d+)~$/u);
650
+ if (!match) return false;
651
+ const modifier = (Number.parseInt(match[1] ?? "", 10) - 1) & ~(64 | 128);
652
+ const codepoint = Number.parseInt(match[2] ?? "", 10);
653
+ if ((modifier & ~1) !== 0 || !Number.isFinite(codepoint) || codepoint < 32) return false;
654
+ try {
655
+ String.fromCodePoint(codepoint);
656
+ return true;
657
+ } catch {
658
+ return false;
659
+ }
660
+ }
661
+
506
662
  function transcriptSection(message: unknown): { role: string; text: string } | undefined {
507
663
  if (!message || typeof message !== "object") return undefined;
508
664
  const record = message as { role?: unknown; content?: unknown };