@sion10032/pi-sessions 0.0.0-stage → 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/undo.ts ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * `/undo`: rewind the current session to just before its newest user message.
3
+ *
4
+ * Unlike `/fork`, which writes a child session file, undo stays in the same
5
+ * file: the tail is cut from the JSONL and the session is reloaded from disk,
6
+ * so the abandoned turn leaves neither a fork subtree nor an unselected branch
7
+ * behind in `/tree`.
8
+ */
9
+ import { readFileSync, renameSync, writeFileSync } from "node:fs";
10
+ import { basename, dirname, join } from "node:path";
11
+
12
+ import type { ExtensionCommandContext, SessionManager } from "@earendil-works/pi-coding-agent";
13
+
14
+ /** Where an undo rewinds to: the parent entry, and the prompt to restore. */
15
+ export interface UndoTarget {
16
+ entryId: string;
17
+ parentId: string | null;
18
+ /** The prompt text, as `/fork` would put it back in the editor. */
19
+ text: string;
20
+ }
21
+
22
+ /**
23
+ * The newest user message on the active branch, nearest the leaf. Only real
24
+ * user messages count: injected `custom_message` entries, bash results and
25
+ * compaction summaries are not something the user typed, so they are skipped
26
+ * even when they sit above the prompt.
27
+ */
28
+ export function findUndoTarget(
29
+ sessionManager: Pick<SessionManager, "getBranch">,
30
+ ): UndoTarget | undefined {
31
+ for (const entry of [...sessionManager.getBranch()].reverse()) {
32
+ if (entry.type !== "message" || entry.message.role !== "user") continue;
33
+ return {
34
+ entryId: entry.id,
35
+ parentId: entry.parentId,
36
+ text: messageText(entry.message.content),
37
+ };
38
+ }
39
+ return undefined;
40
+ }
41
+
42
+ /** Text of a user message, extracted the way pi's fork path extracts it. */
43
+ function messageText(content: string | readonly { type: string; text?: string }[]): string {
44
+ if (typeof content === "string") return content;
45
+ return content
46
+ .filter((part) => part.type === "text" && typeof part.text === "string")
47
+ .map((part) => part.text ?? "")
48
+ .join("");
49
+ }
50
+
51
+ /** How many rows an undo kept and dropped. */
52
+ export interface TruncateResult {
53
+ kept: number;
54
+ removed: number;
55
+ }
56
+
57
+ /**
58
+ * Keep the header row and every row up to and including the last row whose
59
+ * parsed `id` is `throughId`, dropping the rest. `throughId === null` keeps the
60
+ * header alone, which is what undoing the very first prompt leaves behind.
61
+ *
62
+ * Rows are compared by parsed id rather than by index because a session file is
63
+ * append-ordered across branches: rows written after the kept one belong either
64
+ * to the abandoned turn or to an older branch, and both go.
65
+ */
66
+ export function truncateSessionFile(file: string, throughId: string | null): TruncateResult {
67
+ const rows = readFileSync(file, "utf8").split("\n");
68
+ while (rows.length > 0 && rows[rows.length - 1] === "") rows.pop();
69
+ const keepIndex = throughId === null ? 0 : lastRowWithId(rows, throughId);
70
+ if (keepIndex === -1) throw new Error(`Session entry not found: ${throughId}`);
71
+ const kept = rows.slice(0, keepIndex + 1);
72
+ writeAtomically(file, `${kept.join("\n")}\n`);
73
+ return { kept: kept.length, removed: rows.length - kept.length };
74
+ }
75
+
76
+ /** Index of the last row that parses to an entry with this id, or -1. */
77
+ function lastRowWithId(rows: string[], id: string): number {
78
+ for (let index = rows.length - 1; index >= 0; index -= 1) {
79
+ if (parseRowId(rows[index]!) === id) return index;
80
+ }
81
+ return -1;
82
+ }
83
+
84
+ /** The `id` of one JSONL row; blank and unparseable rows have none. */
85
+ function parseRowId(row: string): string | undefined {
86
+ if (row.trim() === "") return undefined;
87
+ try {
88
+ const parsed: unknown = JSON.parse(row);
89
+ if (typeof parsed !== "object" || parsed === null) return undefined;
90
+ const id = (parsed as { id?: unknown }).id;
91
+ return typeof id === "string" ? id : undefined;
92
+ } catch {
93
+ return undefined;
94
+ }
95
+ }
96
+
97
+ /** Replace `file` in one step; pi appends per entry and holds no descriptor, so a rename is safe. */
98
+ function writeAtomically(file: string, content: string): void {
99
+ const tmp = join(dirname(file), `.${basename(file)}.tmp`);
100
+ writeFileSync(tmp, content);
101
+ renameSync(tmp, file);
102
+ }
103
+
104
+ /** A thrown value's message, for a one-line notification. */
105
+ function errorMessage(error: unknown): string {
106
+ return error instanceof Error ? error.message : String(error);
107
+ }
108
+
109
+ /**
110
+ * Whether the host already replaced this command's session. Every `ctx` member
111
+ * is a getter that asserts the extension runner is still active, so reading one
112
+ * after a replacement throws.
113
+ */
114
+ function isStale(ctx: ExtensionCommandContext): boolean {
115
+ try {
116
+ ctx.sessionManager.getSessionFile();
117
+ return false;
118
+ } catch {
119
+ return true;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Rewind the current session to just before its newest user message: cut the
125
+ * tail from the file, reload the session from it, and put the prompt back in
126
+ * the editor when the editor is empty.
127
+ *
128
+ * The cut happens before the reload because the reload reads the file, so a
129
+ * reload the host refuses has to put the original bytes back. Once the host has
130
+ * replaced the session the old context is stale and the file is what the new
131
+ * session already holds, so nothing is restored after that point.
132
+ */
133
+ export async function runUndo(ctx: ExtensionCommandContext): Promise<void> {
134
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) {
135
+ ctx.ui.notify("Wait for the current response to finish before undoing", "warning");
136
+ return;
137
+ }
138
+ const file = ctx.sessionManager.getSessionFile();
139
+ if (file === undefined) {
140
+ ctx.ui.notify("This session has no saved file yet", "warning");
141
+ return;
142
+ }
143
+ const target = findUndoTarget(ctx.sessionManager);
144
+ if (target === undefined) {
145
+ ctx.ui.notify("No user message to undo", "warning");
146
+ return;
147
+ }
148
+ const editorEmpty = ctx.ui.getEditorText().trim() === "";
149
+ const original = readFileSync(file, "utf8");
150
+ let removed = 0;
151
+ let swapped = false;
152
+ try {
153
+ removed = truncateSessionFile(file, target.parentId).removed;
154
+ } catch (error) {
155
+ ctx.ui.notify(`Undo failed: ${errorMessage(error)}`, "error");
156
+ return;
157
+ }
158
+ try {
159
+ const result = await ctx.switchSession(file, {
160
+ withSession: async (next) => {
161
+ swapped = true;
162
+ try {
163
+ if (editorEmpty) next.ui.setEditorText(target.text);
164
+ else next.ui.notify("Undo: editor kept as-is, prompt not restored", "warning");
165
+ next.ui.notify(`Undone: rewound before your last message (${removed} entries removed)`, "info");
166
+ } catch (error) {
167
+ next.ui.notify(`Undo failed: ${errorMessage(error)}`, "error");
168
+ }
169
+ },
170
+ });
171
+ if (result.cancelled && !swapped) {
172
+ writeAtomically(file, original);
173
+ ctx.ui.notify("Undo cancelled, session unchanged", "warning");
174
+ }
175
+ } catch (error) {
176
+ // A throw can arrive before the reload starts or after the host already
177
+ // swapped in the truncated session; only the first may put the old bytes
178
+ // back. After a swap this context is stale, and so is its notice.
179
+ if (swapped || isStale(ctx)) return;
180
+ writeAtomically(file, original);
181
+ ctx.ui.notify(`Undo failed: ${errorMessage(error)}`, "error");
182
+ }
183
+ }