@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/README.md +32 -15
- package/package.json +1 -1
- package/src/child-session.ts +54 -15
- package/src/constants.ts +8 -3
- package/src/fullscreen.ts +253 -0
- package/src/menu.ts +212 -53
- package/src/note-picker.ts +735 -0
- package/src/notes-extension.ts +92 -16
- package/src/storage.ts +178 -26
- package/src/template-editor.ts +664 -0
- package/src/workspace.ts +179 -23
package/README.md
CHANGED
|
@@ -8,10 +8,14 @@
|
|
|
8
8
|
|
|
9
9
|
- Keeps every managed item as an equal Markdown note without built-in note types.
|
|
10
10
|
- Discovers notes and user-managed templates dynamically under Pi's configured agent directory.
|
|
11
|
-
-
|
|
12
|
-
-
|
|
11
|
+
- Creates a blank or templated note immediately under a collision-safe temporary name without asking for a filename.
|
|
12
|
+
- Lets the embedded agent proactively rename the current note when its purpose becomes clear.
|
|
13
|
+
- Opens notes directly, deletes a highlighted note after confirmation, or inserts its canonical absolute path into the parent editor without replacing the draft.
|
|
14
|
+
- Edits existing templates with cancellation and stale-write protection.
|
|
15
|
+
- Shows a fullscreen split Chat/Preview workspace on wide terminals and fullscreen tabs on narrow terminals.
|
|
16
|
+
- Gives the embedded agent only tools scoped to the currently open note.
|
|
13
17
|
- Persists a separate child conversation for each normalized note path without replacing the parent Pi session.
|
|
14
|
-
- Creates and updates
|
|
18
|
+
- Creates, renames, and updates managed Markdown with traversal, symlink, stale-revision, and same-process race checks.
|
|
15
19
|
|
|
16
20
|
## 📦 Install
|
|
17
21
|
|
|
@@ -45,7 +49,7 @@ Run Pi in TUI mode, then open the manager:
|
|
|
45
49
|
/notes
|
|
46
50
|
```
|
|
47
51
|
|
|
48
|
-
Choose
|
|
52
|
+
Choose **Open a note…**, **Create a note…**, **Paste a note path…**, or **Manage templates…**. Existing note names appear only after opening the dedicated note list. In that list, Enter opens the highlighted note and the configured `app.session.delete` binding (`Ctrl+D` by default) asks to delete it. New notes can be blank or copy a Markdown template found at `${getAgentDir()}/pi-notes/templates/`; the extension opens the note immediately as `untitled.md`, an available numbered variant, or a generated fallback, then the embedded agent renames it when the note's purpose is clear. The extension does not seed templates.
|
|
49
53
|
|
|
50
54
|
## 🧭 How it works
|
|
51
55
|
|
|
@@ -53,14 +57,19 @@ Choose an existing note or **Create a note…**. New notes can be blank or copy
|
|
|
53
57
|
flowchart LR
|
|
54
58
|
P[Parent Pi session] -->|/notes| M[Notes manager]
|
|
55
59
|
M --> W[Temporary notes workspace]
|
|
60
|
+
M --> D[Confirm and delete note]
|
|
61
|
+
M --> I[Paste canonical path into parent draft]
|
|
62
|
+
M --> E[Edit existing template]
|
|
56
63
|
W --> C[Isolated child AgentSession]
|
|
57
64
|
W --> V[Markdown preview]
|
|
58
65
|
C --> N[Current note only]
|
|
59
|
-
|
|
60
|
-
|
|
66
|
+
C -->|Rename current note| N
|
|
67
|
+
E --> T[User templates]
|
|
68
|
+
T -->|Initial content| N
|
|
69
|
+
C --> S[Per-path child history]
|
|
61
70
|
```
|
|
62
71
|
|
|
63
|
-
Opening a note temporarily
|
|
72
|
+
Opening a note temporarily switches the terminal to a dedicated fullscreen workspace whose title is the note's relative path. On wide terminals, the mouse wheel scrolls the Chat or Preview pane under the pointer; on narrow terminals, it scrolls the active pane. Closing the workspace aborts child work, disposes the child session, and restores the unchanged parent conversation and editor.
|
|
64
73
|
|
|
65
74
|
All data is below `getAgentDir()`, which honors `PI_CODING_AGENT_DIR`:
|
|
66
75
|
|
|
@@ -77,7 +86,13 @@ New managed directories use mode `0700` and newly created notes use `0600` where
|
|
|
77
86
|
|
|
78
87
|
`/notes` opens the browse/create manager and accepts no arguments. It requires Pi TUI mode and rejects RPC, print, and JSON modes.
|
|
79
88
|
|
|
80
|
-
The manager rescans notes and templates when each screen opens.
|
|
89
|
+
The manager rescans notes and templates when each screen opens. Its first level contains actions only; **Open a note…** shows the current note list on a separate screen. Enter opens the highlighted note. The effective `app.session.delete` binding (`Ctrl+D` by default) shows the exact relative path in quoted, terminal-safe escaped form and its byte size before deletion. Cancelling leaves the note unchanged. A confirmed deletion succeeds only while the selected file still has the reviewed revision, then refreshes the list and highlights a neighboring note. It removes the Markdown file but preserves its path-keyed child conversation under `pi-notes/sessions/`.
|
|
90
|
+
|
|
91
|
+
**Paste a note path…** resolves the selected regular file again, closes the manager, and inserts its canonical absolute path at the parent editor's current cursor without replacing the existing draft. Paths containing terminal or display-direction controls are rejected because Pi's paste handling cannot preserve them safely.
|
|
92
|
+
|
|
93
|
+
**Manage templates…** opens an existing template in a Pi-style multiline editor. The editor preserves leading and trailing whitespace and hides terminal controls as spaces without changing their raw values. It rejects pasted text containing an ambiguous bracketed-paste terminator rather than silently reordering it. Because terminal paste framing cannot represent a literal terminator unambiguously, the first save after a paste asks you to review the content and press save again. Cancelling or submitting unchanged content returns to the manager without writing. A changed template is published atomically only if its revision is still current; if another process changed it, Pi Notes preserves that external content, reports the conflict, and refreshes the manager.
|
|
94
|
+
|
|
95
|
+
Creating a note copies the selected template exactly once and does not ask for a path. Pi Notes tries `untitled.md`, `untitled-2.md`, and further numbered variants before using a generated fallback, without overwriting an existing note or reusing a temporary path that has child-session history. Later template changes do not classify or alter the created note.
|
|
81
96
|
|
|
82
97
|
## Embedded assistant
|
|
83
98
|
|
|
@@ -85,30 +100,32 @@ The child session inherits the parent's selected model and thinking level when t
|
|
|
85
100
|
|
|
86
101
|
The child receives only these tools:
|
|
87
102
|
|
|
88
|
-
- `read_current_note` reads the open note and returns its revision.
|
|
103
|
+
- `read_current_note` reads the open note and returns its relative path and revision.
|
|
89
104
|
- `edit_current_note` replaces one unique exact fragment using the latest revision.
|
|
90
105
|
- `replace_current_note` replaces the complete open note using the latest revision.
|
|
106
|
+
- `rename_current_note` renames the open note using the latest revision and a new relative `.md` destination.
|
|
91
107
|
|
|
92
|
-
|
|
108
|
+
The content tools accept no path, and the rename tool accepts no source path. A batch containing `rename_current_note` executes in source order. To rename and change content in one response, the assistant must call rename first and then at most one content mutation with the same latest revision; renaming preserves that revision. Any later mutation must wait for the preceding content mutation's returned revision. A successful rename updates the live workspace title and keeps subsequent tools bound to the renamed note. Templates affect initial note content only and never become skills, prompt instructions, persistent types, or durable template associations.
|
|
93
109
|
|
|
94
110
|
## 🔒 Security and privacy
|
|
95
111
|
|
|
96
112
|
- The managed notes-root path, note content, child prompts, tool results, and relevant child conversation history are sent to the selected model provider when the embedded agent runs.
|
|
97
113
|
- Model and credential configuration is read from Pi's configured agent directory. A provider registered only in another extension's in-memory runtime is not inherited.
|
|
98
114
|
- Child history remains on disk under `pi-notes/sessions/` until the user removes it.
|
|
99
|
-
- Note operations reject absolute paths, traversal, special files, and symlinked managed paths. Same-directory temporary files and atomic publication preserve the previous
|
|
100
|
-
- Revision checks detect stale writes, but another process can still change a file immediately around publication; this extension does not provide cross-process locking or an OS sandbox.
|
|
115
|
+
- Note and template operations reject absolute paths, traversal, special files, and symlinked managed paths. Rename refuses an existing destination and paths deeper than the discovery limit so renamed notes remain available in menus. Same-directory temporary files and atomic publication preserve the previous content when a managed write fails.
|
|
116
|
+
- Revision checks detect stale writes, renames, and deletions, but another process can still change a file immediately around publication; this extension does not provide cross-process locking or an OS sandbox.
|
|
101
117
|
- Note paths and content are treated as untrusted terminal text and sanitized only for display; raw Markdown content and valid raw file identities remain unchanged on disk.
|
|
102
|
-
-
|
|
118
|
+
- Deleting a note does not delete its child-session history. Removing or disabling the package leaves all data under `getAgentDir()/pi-notes/` untouched.
|
|
103
119
|
|
|
104
120
|
## 🚧 Limitations
|
|
105
121
|
|
|
106
122
|
- Notes and templates must be regular `.md` files no larger than 45,000 UTF-8 bytes or 1,800 lines.
|
|
107
123
|
- Discovery shows at most 1,000 files, descends at most 16 directories, and reports at most 100 scan issues per pass.
|
|
108
124
|
- Each note path supports at most 100 saved child-session files. The visible transcript is bounded to the latest 200 messages and 50,000 characters.
|
|
109
|
-
-
|
|
125
|
+
- A rename keeps the currently open child conversation, but reopening the renamed note starts a separate child conversation unless the new path already has history. Renaming a note outside the extension has the same path-associated behavior.
|
|
110
126
|
- Parent-only dynamic providers and runtime-only provider state are unavailable to the child; use a provider reconstructable from Pi's normal model and credential files.
|
|
111
|
-
-
|
|
127
|
+
- There is no manual rename UI, child-history deletion UI, tags, backlinks, full-text index, direct `/notes <path>` route, template language, settings, or bundled skill.
|
|
128
|
+
- Template management edits existing files only; create, rename, delete, agent-assisted template work, and Pi's external-editor shortcut are not supported.
|
|
112
129
|
- Cross-process locking, large notes, rich-text editing, attachments, synchronization, and collaborative editing are not supported.
|
|
113
130
|
|
|
114
131
|
## 🗂️ Package layout
|
package/package.json
CHANGED
package/src/child-session.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
1
|
import type { Dir } from "node:fs";
|
|
3
2
|
import { lstat, mkdir, opendir, realpath } from "node:fs/promises";
|
|
4
3
|
import { isAbsolute, join, relative, sep } from "node:path";
|
|
@@ -14,8 +13,10 @@ import {
|
|
|
14
13
|
SettingsManager,
|
|
15
14
|
} from "@earendil-works/pi-coding-agent";
|
|
16
15
|
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
17
|
-
import { CHILD_TOOL_NAMES, MAX_SESSION_FILES_PER_NOTE, NOTES_SYSTEM_PROMPT } from "./constants.js";
|
|
18
|
-
import type
|
|
16
|
+
import { CHILD_TOOL_NAMES, MAX_SCAN_DEPTH, MAX_SESSION_FILES_PER_NOTE, NOTES_SYSTEM_PROMPT } from "./constants.js";
|
|
17
|
+
import { type NoteSnapshot, type NotesStorage, noteSessionKey } from "./storage.js";
|
|
18
|
+
|
|
19
|
+
export { noteSessionKey };
|
|
19
20
|
|
|
20
21
|
export interface CreateNotesChildSessionOptions {
|
|
21
22
|
agentDir: string;
|
|
@@ -133,21 +134,23 @@ export function createCurrentNoteTools(
|
|
|
133
134
|
notePath: string,
|
|
134
135
|
onNoteChanged?: (snapshot: NoteSnapshot) => void,
|
|
135
136
|
) {
|
|
137
|
+
let currentPath = notePath;
|
|
138
|
+
|
|
136
139
|
const readTool = defineTool({
|
|
137
140
|
name: "read_current_note",
|
|
138
141
|
label: "Read current note",
|
|
139
|
-
description: "Read the complete current Markdown note and return its
|
|
142
|
+
description: "Read the complete current Markdown note and return its relative path and revision.",
|
|
140
143
|
parameters: Type.Object({}),
|
|
141
144
|
async execute(_toolCallId, _params, signal) {
|
|
142
|
-
const note = await storage.readNote(
|
|
145
|
+
const note = await storage.readNote(currentPath, signal);
|
|
143
146
|
return {
|
|
144
147
|
content: [
|
|
145
148
|
{
|
|
146
149
|
type: "text" as const,
|
|
147
|
-
text: `
|
|
150
|
+
text: `Path: ${note.relativePath}\nRevision: ${note.revision}\nBytes: ${note.size}\n\n${note.content}`,
|
|
148
151
|
},
|
|
149
152
|
],
|
|
150
|
-
details: { revision: note.revision, size: note.size },
|
|
153
|
+
details: { relativePath: note.relativePath, revision: note.revision, size: note.size },
|
|
151
154
|
};
|
|
152
155
|
},
|
|
153
156
|
});
|
|
@@ -163,7 +166,7 @@ export function createCurrentNoteTools(
|
|
|
163
166
|
newText: Type.String({ description: "Replacement text" }),
|
|
164
167
|
}),
|
|
165
168
|
async execute(_toolCallId, params, signal) {
|
|
166
|
-
const note = await storage.editNote(
|
|
169
|
+
const note = await storage.editNote(currentPath, params.revision, params.oldText, params.newText, signal);
|
|
167
170
|
notifyNoteChanged(onNoteChanged, note);
|
|
168
171
|
return mutationResult(note);
|
|
169
172
|
},
|
|
@@ -179,17 +182,36 @@ export function createCurrentNoteTools(
|
|
|
179
182
|
content: Type.String({ description: "Complete replacement Markdown" }),
|
|
180
183
|
}),
|
|
181
184
|
async execute(_toolCallId, params, signal) {
|
|
182
|
-
const note = await storage.replaceNote(
|
|
185
|
+
const note = await storage.replaceNote(currentPath, params.revision, params.content, signal);
|
|
183
186
|
notifyNoteChanged(onNoteChanged, note);
|
|
184
187
|
return mutationResult(note);
|
|
185
188
|
},
|
|
186
189
|
});
|
|
187
190
|
|
|
188
|
-
|
|
189
|
-
|
|
191
|
+
const renameTool = defineTool({
|
|
192
|
+
name: "rename_current_note",
|
|
193
|
+
label: "Rename current note",
|
|
194
|
+
description:
|
|
195
|
+
"Rename the current note to a concise, descriptive relative Markdown path. When combining this with one content mutation in the same response, call this tool first and give both calls the same latest revision; renaming preserves the content revision. This tool accepts no source path, rejects stale revisions, and never overwrites another note.",
|
|
196
|
+
parameters: Type.Object({
|
|
197
|
+
revision: Type.String({ description: "Latest revision returned by a current-note tool" }),
|
|
198
|
+
newPath: Type.String({
|
|
199
|
+
minLength: 4,
|
|
200
|
+
maxLength: 1_024,
|
|
201
|
+
description: `New relative path below the notes root, ending in .md, with at most ${MAX_SCAN_DEPTH} parent directories`,
|
|
202
|
+
}),
|
|
203
|
+
}),
|
|
204
|
+
executionMode: "sequential",
|
|
205
|
+
async execute(_toolCallId, params, signal) {
|
|
206
|
+
const previousPath = currentPath;
|
|
207
|
+
const note = await storage.renameNote(previousPath, params.revision, params.newPath, signal);
|
|
208
|
+
currentPath = note.relativePath;
|
|
209
|
+
notifyNoteChanged(onNoteChanged, note);
|
|
210
|
+
return renameResult(previousPath, note);
|
|
211
|
+
},
|
|
212
|
+
});
|
|
190
213
|
|
|
191
|
-
|
|
192
|
-
return createHash("sha256").update(notePath).digest("hex");
|
|
214
|
+
return [readTool, editTool, replaceTool, renameTool];
|
|
193
215
|
}
|
|
194
216
|
|
|
195
217
|
async function selectNoteSessionManager(
|
|
@@ -330,10 +352,27 @@ function mutationResult(note: NoteSnapshot) {
|
|
|
330
352
|
content: [
|
|
331
353
|
{
|
|
332
354
|
type: "text" as const,
|
|
333
|
-
text: `Updated the current note.\nRevision: ${note.revision}\nBytes: ${note.size}`,
|
|
355
|
+
text: `Updated the current note.\nPath: ${note.relativePath}\nRevision: ${note.revision}\nBytes: ${note.size}`,
|
|
334
356
|
},
|
|
335
357
|
],
|
|
336
|
-
details: { revision: note.revision, size: note.size },
|
|
358
|
+
details: { relativePath: note.relativePath, revision: note.revision, size: note.size },
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function renameResult(previousPath: string, note: NoteSnapshot) {
|
|
363
|
+
return {
|
|
364
|
+
content: [
|
|
365
|
+
{
|
|
366
|
+
type: "text" as const,
|
|
367
|
+
text: `Renamed the current note from ${previousPath} to ${note.relativePath}.\nRevision: ${note.revision}\nBytes: ${note.size}`,
|
|
368
|
+
},
|
|
369
|
+
],
|
|
370
|
+
details: {
|
|
371
|
+
previousPath,
|
|
372
|
+
relativePath: note.relativePath,
|
|
373
|
+
revision: note.revision,
|
|
374
|
+
size: note.size,
|
|
375
|
+
},
|
|
337
376
|
};
|
|
338
377
|
}
|
|
339
378
|
|
package/src/constants.ts
CHANGED
|
@@ -13,10 +13,15 @@ export const MAX_TRANSCRIPT_MESSAGES = 200;
|
|
|
13
13
|
export const MAX_TRANSCRIPT_CHARS = 50_000;
|
|
14
14
|
export const WIDE_WORKSPACE_COLUMNS = 100;
|
|
15
15
|
|
|
16
|
-
export const CHILD_TOOL_NAMES = [
|
|
16
|
+
export const CHILD_TOOL_NAMES = [
|
|
17
|
+
"read_current_note",
|
|
18
|
+
"edit_current_note",
|
|
19
|
+
"replace_current_note",
|
|
20
|
+
"rename_current_note",
|
|
21
|
+
] as const;
|
|
17
22
|
|
|
18
23
|
export const NOTES_SYSTEM_PROMPT = `You are the assistant for one Markdown note.
|
|
19
24
|
|
|
20
|
-
Work only on the current note. Read it before editing. Use edit_current_note for precise changes and replace_current_note only when a full replacement is necessary. Every mutation requires the latest revision returned by read_current_note or a successful mutation. If a revision is stale, read again before retrying.
|
|
25
|
+
Work only on the current note. Read it before editing. Use edit_current_note for precise changes and replace_current_note only when a full replacement is necessary. New notes may have a temporary untitled filename. Once the note's purpose is clear, proactively use rename_current_note to give it a concise, descriptive relative Markdown path; do not ask the user to choose a filename. Every mutation requires the latest revision returned by read_current_note or a successful mutation. To rename and change content in one response, call rename_current_note first, then at most one content mutation with the same latest revision; renaming preserves that revision and the calls execute in source order. Wait for a successful content mutation's returned revision before issuing another mutation. If a revision is stale, read again before retrying.
|
|
21
26
|
|
|
22
|
-
You have no access to other notes, templates, sessions, project files, or a shell. Do not claim that you changed content unless a mutation tool succeeded. Keep the note valid Markdown and preserve unrelated content.`;
|
|
27
|
+
You have no access to other notes, templates, sessions, project files, or a shell. Do not claim that you changed content or the filename unless a mutation tool succeeded. Keep the note valid Markdown and preserve unrelated content.`;
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import type { ExtensionCommandContext, KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type Component, type OverlayHandle, type TUI, TuiAltScreen, truncateToWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import type {
|
|
4
|
+
CustomInteractionComponent,
|
|
5
|
+
RunCustomInteractionOptions,
|
|
6
|
+
RunCustomInteractionResult,
|
|
7
|
+
} from "@narumitw/pi-tui-kit/custom-interaction";
|
|
8
|
+
|
|
9
|
+
export type NotesFullscreenTuiFactory = (parent: TUI) => TuiAltScreen;
|
|
10
|
+
|
|
11
|
+
interface FullscreenInteractionDependencies {
|
|
12
|
+
createTui?: NotesFullscreenTuiFactory;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type FullscreenOutcome<Value> =
|
|
16
|
+
| { kind: "completed"; value: Value }
|
|
17
|
+
| { kind: "stale" }
|
|
18
|
+
| { kind: "error"; error: unknown };
|
|
19
|
+
|
|
20
|
+
export async function runFullscreenInteraction<Value>(
|
|
21
|
+
ctx: ExtensionCommandContext,
|
|
22
|
+
options: RunCustomInteractionOptions<Value>,
|
|
23
|
+
dependencies: FullscreenInteractionDependencies = {},
|
|
24
|
+
): Promise<RunCustomInteractionResult<Value>> {
|
|
25
|
+
if (options.signal?.aborted || !(options.isCurrent?.() ?? true)) return { kind: "stale" };
|
|
26
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) return { kind: "unsupported", mode: ctx.mode };
|
|
27
|
+
|
|
28
|
+
let host: FullscreenInteractionHost<Value> | undefined;
|
|
29
|
+
let outcome: FullscreenOutcome<Value> | undefined;
|
|
30
|
+
let uiFailed = false;
|
|
31
|
+
let uiError: unknown;
|
|
32
|
+
try {
|
|
33
|
+
outcome = await ctx.ui.custom<FullscreenOutcome<Value> | undefined>(
|
|
34
|
+
(parent, theme, keybindings, done) => {
|
|
35
|
+
host = new FullscreenInteractionHost({
|
|
36
|
+
ctx,
|
|
37
|
+
parent,
|
|
38
|
+
theme,
|
|
39
|
+
keybindings,
|
|
40
|
+
done,
|
|
41
|
+
options,
|
|
42
|
+
createTui:
|
|
43
|
+
dependencies.createTui ??
|
|
44
|
+
((source) =>
|
|
45
|
+
new TuiAltScreen(source.terminal, source.getShowHardwareCursor(), undefined, {
|
|
46
|
+
mouse: true,
|
|
47
|
+
})),
|
|
48
|
+
});
|
|
49
|
+
return host;
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
overlay: true,
|
|
53
|
+
onHandle: (handle) => host?.setParentOverlay(handle),
|
|
54
|
+
},
|
|
55
|
+
);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
uiFailed = true;
|
|
58
|
+
uiError = error;
|
|
59
|
+
}
|
|
60
|
+
if (uiFailed || outcome === undefined) host?.dispose();
|
|
61
|
+
try {
|
|
62
|
+
await host?.waitForPending();
|
|
63
|
+
} catch (error) {
|
|
64
|
+
uiFailed = true;
|
|
65
|
+
uiError = error;
|
|
66
|
+
}
|
|
67
|
+
if (uiFailed) outcome = { kind: "error", error: uiError };
|
|
68
|
+
|
|
69
|
+
if (options.signal?.aborted || !(options.isCurrent?.() ?? true) || outcome?.kind === "stale") {
|
|
70
|
+
return { kind: "stale" };
|
|
71
|
+
}
|
|
72
|
+
if (outcome?.kind === "completed") return outcome;
|
|
73
|
+
if (outcome?.kind === "error") {
|
|
74
|
+
await options.onError?.(ctx, outcome.error);
|
|
75
|
+
return outcome;
|
|
76
|
+
}
|
|
77
|
+
return { kind: "stale" };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface FullscreenInteractionHostOptions<Value> {
|
|
81
|
+
ctx: ExtensionCommandContext;
|
|
82
|
+
parent: TUI;
|
|
83
|
+
theme: Theme;
|
|
84
|
+
keybindings: KeybindingsManager;
|
|
85
|
+
done(outcome: FullscreenOutcome<Value>): void;
|
|
86
|
+
options: RunCustomInteractionOptions<Value>;
|
|
87
|
+
createTui: NotesFullscreenTuiFactory;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
class FullscreenInteractionHost<Value> implements Component {
|
|
91
|
+
private readonly lifetime = new AbortController();
|
|
92
|
+
private readonly signal: AbortSignal;
|
|
93
|
+
private readonly startPromise: Promise<void>;
|
|
94
|
+
private removeUpstreamAbort = () => {};
|
|
95
|
+
private parentOverlay: OverlayHandle | undefined;
|
|
96
|
+
private fullscreen: TuiAltScreen | undefined;
|
|
97
|
+
private component: CustomInteractionComponent | undefined;
|
|
98
|
+
private parentStopped = false;
|
|
99
|
+
private fullscreenStarted = false;
|
|
100
|
+
private componentDisposed = false;
|
|
101
|
+
private stopping = false;
|
|
102
|
+
private finished = false;
|
|
103
|
+
private finishPromise: Promise<void> | undefined;
|
|
104
|
+
private startFailed = false;
|
|
105
|
+
private startError: unknown;
|
|
106
|
+
|
|
107
|
+
constructor(private readonly host: FullscreenInteractionHostOptions<Value>) {
|
|
108
|
+
this.signal = host.options.signal
|
|
109
|
+
? AbortSignal.any([host.options.signal, this.lifetime.signal])
|
|
110
|
+
: this.lifetime.signal;
|
|
111
|
+
const abort = () => void this.finish({ kind: "stale" });
|
|
112
|
+
host.options.signal?.addEventListener("abort", abort, { once: true });
|
|
113
|
+
this.removeUpstreamAbort = () => host.options.signal?.removeEventListener("abort", abort);
|
|
114
|
+
this.startPromise = Promise.resolve()
|
|
115
|
+
.then(() => this.start())
|
|
116
|
+
.catch((error: unknown) => {
|
|
117
|
+
this.startFailed = true;
|
|
118
|
+
this.startError = error;
|
|
119
|
+
});
|
|
120
|
+
void this.startPromise.then(() => {
|
|
121
|
+
if (this.startFailed) void this.finish({ kind: "error", error: this.startError });
|
|
122
|
+
});
|
|
123
|
+
if (host.options.signal?.aborted) abort();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
setParentOverlay(handle: OverlayHandle): void {
|
|
127
|
+
this.parentOverlay = handle;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
render(width: number): string[] {
|
|
131
|
+
return [truncateToWidth(this.host.theme.fg("muted", "Opening Pi Notes fullscreen workspace…"), width)];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
invalidate(): void {}
|
|
135
|
+
|
|
136
|
+
dispose(): void {
|
|
137
|
+
void this.finish({ kind: "stale" });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async waitForPending(): Promise<void> {
|
|
141
|
+
await this.startPromise;
|
|
142
|
+
await this.finishPromise;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private async start(): Promise<void> {
|
|
146
|
+
if (this.stopping) return;
|
|
147
|
+
if (this.signal.aborted || !(this.host.options.isCurrent?.() ?? true)) {
|
|
148
|
+
void this.finish({ kind: "stale" });
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
this.host.parent.stop({ preserveScreen: true });
|
|
152
|
+
this.parentStopped = true;
|
|
153
|
+
if (this.stopping) return;
|
|
154
|
+
|
|
155
|
+
this.fullscreen = this.host.createTui(this.host.parent);
|
|
156
|
+
this.fullscreenStarted = true;
|
|
157
|
+
this.fullscreen.start();
|
|
158
|
+
if (this.stopping) return;
|
|
159
|
+
|
|
160
|
+
this.component = await this.host.options.create({
|
|
161
|
+
ctx: this.host.ctx,
|
|
162
|
+
tui: this.fullscreen,
|
|
163
|
+
theme: this.host.theme,
|
|
164
|
+
keybindings: this.host.keybindings,
|
|
165
|
+
signal: this.signal,
|
|
166
|
+
complete: (value) => {
|
|
167
|
+
const outcome =
|
|
168
|
+
this.signal.aborted || !(this.host.options.isCurrent?.() ?? true)
|
|
169
|
+
? ({ kind: "stale" } as const)
|
|
170
|
+
: ({ kind: "completed", value } as const);
|
|
171
|
+
void this.finish(outcome);
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
if (this.stopping) return;
|
|
175
|
+
if (this.signal.aborted || !(this.host.options.isCurrent?.() ?? true)) {
|
|
176
|
+
void this.finish({ kind: "stale" });
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
this.fullscreen.setLayoutRoot(this.component);
|
|
180
|
+
this.fullscreen.setFocus(this.component);
|
|
181
|
+
this.fullscreen.requestRender();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private finish(outcome: FullscreenOutcome<Value>): Promise<void> {
|
|
185
|
+
if (this.finishPromise) return this.finishPromise;
|
|
186
|
+
this.stopping = true;
|
|
187
|
+
this.lifetime.abort(new DOMException("Pi Notes fullscreen interaction closed", "AbortError"));
|
|
188
|
+
this.removeUpstreamAbort();
|
|
189
|
+
this.removeUpstreamAbort = () => {};
|
|
190
|
+
this.finishPromise = (async () => {
|
|
191
|
+
await this.startPromise;
|
|
192
|
+
let cleanupError: unknown;
|
|
193
|
+
try {
|
|
194
|
+
this.disposeComponent();
|
|
195
|
+
} catch (error) {
|
|
196
|
+
cleanupError = error;
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
await this.component?.waitForPending?.();
|
|
200
|
+
} catch (error) {
|
|
201
|
+
cleanupError ??= error;
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
this.fullscreen?.setFocus(null);
|
|
205
|
+
} catch (error) {
|
|
206
|
+
cleanupError ??= error;
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
this.fullscreen?.setLayoutRoot(undefined);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
cleanupError ??= error;
|
|
212
|
+
}
|
|
213
|
+
if (this.fullscreenStarted) {
|
|
214
|
+
try {
|
|
215
|
+
await this.fullscreen?.terminal.drainInput();
|
|
216
|
+
} catch (error) {
|
|
217
|
+
cleanupError ??= error;
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
this.fullscreen?.stop({ preserveScreen: true });
|
|
221
|
+
} catch (error) {
|
|
222
|
+
cleanupError ??= error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
this.parentOverlay?.setHidden(true);
|
|
227
|
+
} catch (error) {
|
|
228
|
+
cleanupError ??= error;
|
|
229
|
+
}
|
|
230
|
+
if (this.parentStopped) {
|
|
231
|
+
try {
|
|
232
|
+
this.host.parent.start();
|
|
233
|
+
this.host.parent.renderNow(false);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
cleanupError ??= error;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (this.finished) return;
|
|
239
|
+
this.finished = true;
|
|
240
|
+
const stale = this.host.options.signal?.aborted || !(this.host.options.isCurrent?.() ?? true);
|
|
241
|
+
this.host.done(
|
|
242
|
+
stale ? { kind: "stale" } : cleanupError === undefined ? outcome : { kind: "error", error: cleanupError },
|
|
243
|
+
);
|
|
244
|
+
})();
|
|
245
|
+
return this.finishPromise;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private disposeComponent(): void {
|
|
249
|
+
if (!this.component || this.componentDisposed) return;
|
|
250
|
+
this.componentDisposed = true;
|
|
251
|
+
this.component.dispose?.();
|
|
252
|
+
}
|
|
253
|
+
}
|