wherever-dev 0.11.2 → 0.12.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.
Files changed (48) hide show
  1. package/dist/drafts.d.ts +112 -0
  2. package/dist/drafts.d.ts.map +1 -0
  3. package/dist/drafts.js +265 -0
  4. package/dist/drafts.js.map +1 -0
  5. package/dist/index.js +72 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/session-pool.d.ts +8 -0
  8. package/dist/session-pool.d.ts.map +1 -1
  9. package/dist/session-pool.js +1 -1
  10. package/dist/session-pool.js.map +1 -1
  11. package/package.json +1 -1
  12. package/public/_app/immutable/assets/0.BS_EGmNW.css +1 -0
  13. package/public/_app/immutable/chunks/{CE0jm7EC.js → 55QXfSWV.js} +2 -2
  14. package/public/_app/immutable/chunks/{CE0jm7EC.js.map → 55QXfSWV.js.map} +1 -1
  15. package/public/_app/immutable/chunks/BeRKnBIj.js +3 -0
  16. package/public/_app/immutable/chunks/{itgD7vGH.js.map → BeRKnBIj.js.map} +1 -1
  17. package/public/_app/immutable/chunks/{Dtm96ZKi.js → C8CBGqeA.js} +2 -2
  18. package/public/_app/immutable/chunks/{Dtm96ZKi.js.map → C8CBGqeA.js.map} +1 -1
  19. package/public/_app/immutable/chunks/CuGyzHtA.js +2 -0
  20. package/public/_app/immutable/chunks/{8jn76iTS.js.map → CuGyzHtA.js.map} +1 -1
  21. package/public/_app/immutable/chunks/{CRRPBe07.js → Cum3gQOV.js} +2 -2
  22. package/public/_app/immutable/chunks/{CRRPBe07.js.map → Cum3gQOV.js.map} +1 -1
  23. package/public/_app/immutable/chunks/{CAWbdcQM.js → D5t5dKgW.js} +2 -2
  24. package/public/_app/immutable/chunks/{CAWbdcQM.js.map → D5t5dKgW.js.map} +1 -1
  25. package/public/_app/immutable/chunks/{BDmEqqqL.js → sERBGsNa.js} +2 -2
  26. package/public/_app/immutable/chunks/{BDmEqqqL.js.map → sERBGsNa.js.map} +1 -1
  27. package/public/_app/immutable/entry/app.DN0r_HfQ.js +3 -0
  28. package/public/_app/immutable/entry/{app.YbNg9lmT.js.map → app.DN0r_HfQ.js.map} +1 -1
  29. package/public/_app/immutable/entry/start.CSyfkZFS.js +2 -0
  30. package/public/_app/immutable/entry/start.CSyfkZFS.js.map +1 -0
  31. package/public/_app/immutable/nodes/{0.BwSufUPS.js → 0.BhHgt5Z6.js} +3 -3
  32. package/public/_app/immutable/nodes/{0.BwSufUPS.js.map → 0.BhHgt5Z6.js.map} +1 -1
  33. package/public/_app/immutable/nodes/1.B9mDAaoD.js +2 -0
  34. package/public/_app/immutable/nodes/{1.x8yi4PgO.js.map → 1.B9mDAaoD.js.map} +1 -1
  35. package/public/_app/immutable/nodes/2.BjlQDhkN.js +110 -0
  36. package/public/_app/immutable/nodes/2.BjlQDhkN.js.map +1 -0
  37. package/public/_app/version.json +1 -1
  38. package/public/index.html +15 -15
  39. package/public/service-worker.js +1 -1
  40. package/public/_app/immutable/assets/0.BnJtv5fG.css +0 -1
  41. package/public/_app/immutable/chunks/8jn76iTS.js +0 -2
  42. package/public/_app/immutable/chunks/itgD7vGH.js +0 -3
  43. package/public/_app/immutable/entry/app.YbNg9lmT.js +0 -3
  44. package/public/_app/immutable/entry/start.Mhebc2Bx.js +0 -2
  45. package/public/_app/immutable/entry/start.Mhebc2Bx.js.map +0 -1
  46. package/public/_app/immutable/nodes/1.x8yi4PgO.js +0 -2
  47. package/public/_app/immutable/nodes/2.BWbDsdRU.js +0 -104
  48. package/public/_app/immutable/nodes/2.BWbDsdRU.js.map +0 -1
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Hard cap on retained drafts, dropping the least recently touched. A draft is
3
+ * kept forever by definition, so without a cap this file is the one thing here
4
+ * that grows without bound.
5
+ */
6
+ export declare const MAX_DRAFTS = 100;
7
+ /** Per-draft character cap. A composer message is prose, not a file paste. */
8
+ export declare const MAX_DRAFT_CHARS = 20000;
9
+ /**
10
+ * Cap on the display metadata (`sessionId` / `cwd`). These are not user prose,
11
+ * they are values the client already holds, so anything longer is a client bug
12
+ * or an abuse attempt. Uncapped, ~100 saves of a 500 KB `cwd` would push the
13
+ * file past MAX_DRAFTS_FILE_BYTES and make the whole list unreadable.
14
+ */
15
+ export declare const MAX_DRAFT_META_CHARS = 1024;
16
+ export interface Draft {
17
+ /** Stable id: the handle for load/delete. */
18
+ id: string;
19
+ /** The message text, trimmed. Never blank. */
20
+ text: string;
21
+ /** Epoch ms first saved. */
22
+ createdAt: number;
23
+ /** Epoch ms of the last save of this same text (drives list order). */
24
+ updatedAt: number;
25
+ /** Session it was written in, if any. Display metadata only. */
26
+ sessionId?: string;
27
+ /** Working folder it was written in, if any. Display metadata only. */
28
+ cwd?: string;
29
+ }
30
+ /**
31
+ * The drafts file exists but cannot be trusted (unreadable, implausibly large,
32
+ * or not parseable). Every mutation is a read-modify-write, so this MUST abort
33
+ * the write rather than let an empty read overwrite the file: that file is the
34
+ * only copy of text the user explicitly asked to keep, and treating "I could not
35
+ * read it" as "it is empty" would delete every draft on the next save. Fail
36
+ * closed, keep the file, and tell the user which file to look at.
37
+ */
38
+ export declare class DraftsUnavailableError extends Error {
39
+ constructor(reason: string);
40
+ }
41
+ export declare function getDraftsPath(): string;
42
+ /** Newest-updated first, ties broken by id so the order is deterministic. */
43
+ export declare function sortDrafts(drafts: Draft[]): Draft[];
44
+ /**
45
+ * Parse the file. Returns NULL when the content is not a drafts file at all
46
+ * (truncated, corrupt, some other JSON), which callers must treat as "unknown",
47
+ * never as "empty" -- see DraftsUnavailableError. A malformed MEMBER inside an
48
+ * otherwise valid file is DROPPED rather than repaired: a draft is user-authored
49
+ * text, and inventing fields for it is worse than losing the one broken record.
50
+ * Accepts both the `{version, drafts}` envelope and a bare array, so a
51
+ * hand-written file works too.
52
+ */
53
+ export declare function parseDrafts(raw: string | null | undefined): Draft[] | null;
54
+ export declare function serializeDrafts(drafts: Draft[]): string;
55
+ export interface SaveDraftInput {
56
+ text: string;
57
+ id: string;
58
+ now: number;
59
+ sessionId?: string;
60
+ cwd?: string;
61
+ }
62
+ /**
63
+ * Add `text` to the list, returning the new list (newest first).
64
+ *
65
+ * - Blank text saves nothing: a whitespace-only draft is indistinguishable from
66
+ * the others in a list and there would be no way to tell them apart.
67
+ * - Text IDENTICAL to an existing draft does NOT duplicate it: the existing
68
+ * entry is touched (updatedAt) and floats to the top. Re-saving the same
69
+ * reusable prompt is the normal case, and a wall of identical rows is noise
70
+ * the user would then have to prune by hand.
71
+ */
72
+ /**
73
+ * Validate an incoming draft, returning an error message or null.
74
+ *
75
+ * ONE place decides what is acceptable, and the route turns a message into a
76
+ * 400. Overlong text is REJECTED rather than truncated: the client clears the
77
+ * composer once the server has the draft, so silently storing a prefix would
78
+ * destroy the tail of the message with no error and no undo.
79
+ */
80
+ export declare function validateDraftInput(input: {
81
+ text: unknown;
82
+ sessionId?: unknown;
83
+ cwd?: unknown;
84
+ }): string | null;
85
+ export declare function saveDraft(drafts: Draft[], input: SaveDraftInput): Draft[];
86
+ export declare function removeDraft(drafts: Draft[], id: string): Draft[];
87
+ /**
88
+ * Read the stored list. A MISSING file is genuinely an empty list; anything else
89
+ * that goes wrong throws DraftsUnavailableError, so a mutation aborts instead of
90
+ * overwriting a file it could not read (see that class). Callers that only
91
+ * display the list can catch and show the error; none of them may swallow it and
92
+ * carry on writing.
93
+ */
94
+ export declare function readDrafts(): Draft[];
95
+ /**
96
+ * Write the list. ATOMIC (tmp file + rename) because this file is the only copy
97
+ * of text the user explicitly asked to keep: a torn write from a crash or a full
98
+ * disk would otherwise lose every draft at once, and a truncated file is exactly
99
+ * the case parseDrafts has to throw away.
100
+ *
101
+ * Sync fs on purpose (like getWhereverConfig): the file is a few KB and this
102
+ * runs on a rare, human-initiated action, so there is nothing here to block the
103
+ * event loop with. Anything that could grow (the session listing, transcripts)
104
+ * is streamed elsewhere; this is not that.
105
+ */
106
+ export declare function writeDrafts(drafts: Draft[]): void;
107
+ export declare function newDraftId(): string;
108
+ /** Save `input` and persist. Returns the new list. */
109
+ export declare function addDraft(input: Omit<SaveDraftInput, 'id' | 'now'> & Partial<Pick<SaveDraftInput, 'id' | 'now'>>): Draft[];
110
+ /** Delete by id and persist. Returns the new list. */
111
+ export declare function deleteDraft(id: string): Draft[];
112
+ //# sourceMappingURL=drafts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drafts.d.ts","sourceRoot":"","sources":["../src/drafts.ts"],"names":[],"mappings":"AAwBA;;;;GAIG;AACH,eAAO,MAAM,UAAU,MAAM,CAAC;AAE9B,8EAA8E;AAC9E,eAAO,MAAM,eAAe,QAAQ,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,OAAO,CAAC;AAKzC,MAAM,WAAW,KAAK;IACpB,6CAA6C;IAC7C,EAAE,EAAE,MAAM,CAAC;IACX,8CAA8C;IAC9C,IAAI,EAAE,MAAM,CAAC;IACb,4BAA4B;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,uEAAuE;IACvE,SAAS,EAAE,MAAM,CAAC;IAClB,gEAAgE;IAChE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uEAAuE;IACvE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAOD;;;;;;;GAOG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;gBACnC,MAAM,EAAE,MAAM;CAI3B;AAED,wBAAgB,aAAa,IAAI,MAAM,CAEtC;AAED,6EAA6E;AAC7E,wBAAgB,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,KAAK,EAAE,CAEnD;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,KAAK,EAAE,GAAG,IAAI,CAmC1E;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,CAGvD;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;;;;;GASG;AACH;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE;IACxC,IAAI,EAAE,OAAO,CAAC;IACd,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,GAAG,CAAC,EAAE,OAAO,CAAC;CACf,GAAG,MAAM,GAAG,IAAI,CAkBhB;AAED,wBAAgB,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,cAAc,GAAG,KAAK,EAAE,CAkBzE;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,MAAM,GAAG,KAAK,EAAE,CAEhE;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,IAAI,KAAK,EAAE,CAmBpC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAejD;AAED,wBAAgB,UAAU,IAAI,MAAM,CAMnC;AAED,sDAAsD;AACtD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,cAAc,EAAE,IAAI,GAAG,KAAK,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,GAAG,KAAK,CAAC,CAAC,GAAG,KAAK,EAAE,CAUzH;AAED,sDAAsD;AACtD,wBAAgB,WAAW,CAAC,EAAE,EAAE,MAAM,GAAG,KAAK,EAAE,CAI/C"}
package/dist/drafts.js ADDED
@@ -0,0 +1,265 @@
1
+ // Saved drafts: messages the user chose to KEEP instead of sending.
2
+ //
3
+ // The store lives on the SERVER (`<config dir>/drafts.json`), not in a browser,
4
+ // because that is the whole point of wherever: the machine holds the state and
5
+ // any device picks it up. A draft written on a phone has to be there on the
6
+ // laptop, and clearing site data must not destroy it. (The composer's per-session
7
+ // AUTO-draft is a different thing and stays client-side: it is crash protection
8
+ // for the one text currently in the box, rewritten on every keystroke, and
9
+ // round-tripping that to the server per keystroke would be absurd.)
10
+ //
11
+ // Drafts are GLOBAL to a server, deliberately not scoped to a session: a prompt
12
+ // written while looking at one repo is often exactly what you want to send in
13
+ // another, and the home page (no session at all) is a place you want to load one.
14
+ // The originating session/cwd is retained as DISPLAY metadata only.
15
+ //
16
+ // This module is the ONE writer of the list: the client never merges, caps or
17
+ // dedupes a list of its own (it would be a second writer with no conflict rule,
18
+ // and the two would drift). Every mutation returns the whole new list, which the
19
+ // client adopts verbatim.
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { getWhereverConfigDir } from './session-pool.js';
23
+ /**
24
+ * Hard cap on retained drafts, dropping the least recently touched. A draft is
25
+ * kept forever by definition, so without a cap this file is the one thing here
26
+ * that grows without bound.
27
+ */
28
+ export const MAX_DRAFTS = 100;
29
+ /** Per-draft character cap. A composer message is prose, not a file paste. */
30
+ export const MAX_DRAFT_CHARS = 20000;
31
+ /**
32
+ * Cap on the display metadata (`sessionId` / `cwd`). These are not user prose,
33
+ * they are values the client already holds, so anything longer is a client bug
34
+ * or an abuse attempt. Uncapped, ~100 saves of a 500 KB `cwd` would push the
35
+ * file past MAX_DRAFTS_FILE_BYTES and make the whole list unreadable.
36
+ */
37
+ export const MAX_DRAFT_META_CHARS = 1024;
38
+ /** Max bytes read from drafts.json. Belt-and-braces against a corrupt file. */
39
+ const MAX_DRAFTS_FILE_BYTES = 5 * 1024 * 1024;
40
+ /**
41
+ * The drafts file exists but cannot be trusted (unreadable, implausibly large,
42
+ * or not parseable). Every mutation is a read-modify-write, so this MUST abort
43
+ * the write rather than let an empty read overwrite the file: that file is the
44
+ * only copy of text the user explicitly asked to keep, and treating "I could not
45
+ * read it" as "it is empty" would delete every draft on the next save. Fail
46
+ * closed, keep the file, and tell the user which file to look at.
47
+ */
48
+ export class DraftsUnavailableError extends Error {
49
+ constructor(reason) {
50
+ super(`${getDraftsPath()} could not be read (${reason}). Drafts left untouched.`);
51
+ this.name = 'DraftsUnavailableError';
52
+ }
53
+ }
54
+ export function getDraftsPath() {
55
+ return path.join(getWhereverConfigDir(), 'drafts.json');
56
+ }
57
+ /** Newest-updated first, ties broken by id so the order is deterministic. */
58
+ export function sortDrafts(drafts) {
59
+ return [...drafts].sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id));
60
+ }
61
+ /**
62
+ * Parse the file. Returns NULL when the content is not a drafts file at all
63
+ * (truncated, corrupt, some other JSON), which callers must treat as "unknown",
64
+ * never as "empty" -- see DraftsUnavailableError. A malformed MEMBER inside an
65
+ * otherwise valid file is DROPPED rather than repaired: a draft is user-authored
66
+ * text, and inventing fields for it is worse than losing the one broken record.
67
+ * Accepts both the `{version, drafts}` envelope and a bare array, so a
68
+ * hand-written file works too.
69
+ */
70
+ export function parseDrafts(raw) {
71
+ if (raw == null)
72
+ return null;
73
+ if (raw.trim().length === 0)
74
+ return [];
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(raw);
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ const arr = Array.isArray(parsed)
83
+ ? parsed
84
+ : parsed && typeof parsed === 'object' && Array.isArray(parsed.drafts)
85
+ ? parsed.drafts
86
+ : null;
87
+ if (!arr)
88
+ return null;
89
+ const out = [];
90
+ for (const item of arr) {
91
+ if (!item || typeof item !== 'object')
92
+ continue;
93
+ const d = item;
94
+ if (typeof d.id !== 'string' || d.id.length === 0)
95
+ continue;
96
+ if (typeof d.text !== 'string')
97
+ continue;
98
+ const text = d.text.trim();
99
+ if (text.length === 0)
100
+ continue;
101
+ const createdAt = typeof d.createdAt === 'number' ? d.createdAt : 0;
102
+ const updatedAt = typeof d.updatedAt === 'number' ? d.updatedAt : createdAt;
103
+ out.push({
104
+ id: d.id,
105
+ text,
106
+ createdAt,
107
+ updatedAt,
108
+ ...(typeof d.sessionId === 'string' ? { sessionId: d.sessionId } : {}),
109
+ ...(typeof d.cwd === 'string' ? { cwd: d.cwd } : {}),
110
+ });
111
+ }
112
+ return sortDrafts(out);
113
+ }
114
+ export function serializeDrafts(drafts) {
115
+ const file = { version: 1, drafts };
116
+ return JSON.stringify(file, null, 2);
117
+ }
118
+ /**
119
+ * Add `text` to the list, returning the new list (newest first).
120
+ *
121
+ * - Blank text saves nothing: a whitespace-only draft is indistinguishable from
122
+ * the others in a list and there would be no way to tell them apart.
123
+ * - Text IDENTICAL to an existing draft does NOT duplicate it: the existing
124
+ * entry is touched (updatedAt) and floats to the top. Re-saving the same
125
+ * reusable prompt is the normal case, and a wall of identical rows is noise
126
+ * the user would then have to prune by hand.
127
+ */
128
+ /**
129
+ * Validate an incoming draft, returning an error message or null.
130
+ *
131
+ * ONE place decides what is acceptable, and the route turns a message into a
132
+ * 400. Overlong text is REJECTED rather than truncated: the client clears the
133
+ * composer once the server has the draft, so silently storing a prefix would
134
+ * destroy the tail of the message with no error and no undo.
135
+ */
136
+ export function validateDraftInput(input) {
137
+ if (typeof input.text !== 'string' || input.text.trim().length === 0) {
138
+ return 'A draft cannot be empty';
139
+ }
140
+ if (input.text.trim().length > MAX_DRAFT_CHARS) {
141
+ return `A draft cannot exceed ${MAX_DRAFT_CHARS} characters`;
142
+ }
143
+ for (const [field, value] of [
144
+ ['sessionId', input.sessionId],
145
+ ['cwd', input.cwd],
146
+ ]) {
147
+ if (value === undefined || value === null)
148
+ continue;
149
+ if (typeof value !== 'string')
150
+ return `${field} must be a string`;
151
+ if (value.length > MAX_DRAFT_META_CHARS) {
152
+ return `${field} cannot exceed ${MAX_DRAFT_META_CHARS} characters`;
153
+ }
154
+ }
155
+ return null;
156
+ }
157
+ export function saveDraft(drafts, input) {
158
+ const text = input.text.trim();
159
+ if (text.length === 0 || text.length > MAX_DRAFT_CHARS)
160
+ return sortDrafts(drafts);
161
+ const existing = drafts.find((d) => d.text === text);
162
+ const next = existing
163
+ ? drafts.map((d) => (d.id === existing.id ? { ...d, updatedAt: input.now } : d))
164
+ : [
165
+ {
166
+ id: input.id,
167
+ text,
168
+ createdAt: input.now,
169
+ updatedAt: input.now,
170
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
171
+ ...(input.cwd ? { cwd: input.cwd } : {}),
172
+ },
173
+ ...drafts,
174
+ ];
175
+ return sortDrafts(next).slice(0, MAX_DRAFTS);
176
+ }
177
+ export function removeDraft(drafts, id) {
178
+ return sortDrafts(drafts.filter((d) => d.id !== id));
179
+ }
180
+ /**
181
+ * Read the stored list. A MISSING file is genuinely an empty list; anything else
182
+ * that goes wrong throws DraftsUnavailableError, so a mutation aborts instead of
183
+ * overwriting a file it could not read (see that class). Callers that only
184
+ * display the list can catch and show the error; none of them may swallow it and
185
+ * carry on writing.
186
+ */
187
+ export function readDrafts() {
188
+ const file = getDraftsPath();
189
+ let raw;
190
+ try {
191
+ if (!fs.existsSync(file))
192
+ return [];
193
+ const stat = fs.statSync(file);
194
+ if (stat.size > MAX_DRAFTS_FILE_BYTES) {
195
+ throw new DraftsUnavailableError(`${stat.size} bytes, implausibly large`);
196
+ }
197
+ raw = fs.readFileSync(file, 'utf8');
198
+ }
199
+ catch (err) {
200
+ if (err instanceof DraftsUnavailableError)
201
+ throw err;
202
+ throw new DraftsUnavailableError(err?.message || 'read failed');
203
+ }
204
+ const parsed = parseDrafts(raw);
205
+ if (parsed === null) {
206
+ throw new DraftsUnavailableError('not a valid drafts file');
207
+ }
208
+ return parsed;
209
+ }
210
+ /**
211
+ * Write the list. ATOMIC (tmp file + rename) because this file is the only copy
212
+ * of text the user explicitly asked to keep: a torn write from a crash or a full
213
+ * disk would otherwise lose every draft at once, and a truncated file is exactly
214
+ * the case parseDrafts has to throw away.
215
+ *
216
+ * Sync fs on purpose (like getWhereverConfig): the file is a few KB and this
217
+ * runs on a rare, human-initiated action, so there is nothing here to block the
218
+ * event loop with. Anything that could grow (the session listing, transcripts)
219
+ * is streamed elsewhere; this is not that.
220
+ */
221
+ export function writeDrafts(drafts) {
222
+ const file = getDraftsPath();
223
+ const dir = path.dirname(file);
224
+ fs.mkdirSync(dir, { recursive: true });
225
+ const tmp = path.join(dir, `.drafts.json.${process.pid}.tmp`);
226
+ try {
227
+ // 0600: these are the user's unsent private words, not shared config.
228
+ fs.writeFileSync(tmp, serializeDrafts(drafts), { encoding: 'utf8', mode: 0o600 });
229
+ fs.renameSync(tmp, file);
230
+ }
231
+ catch (err) {
232
+ try {
233
+ fs.unlinkSync(tmp);
234
+ }
235
+ catch { }
236
+ throw err;
237
+ }
238
+ }
239
+ export function newDraftId() {
240
+ try {
241
+ return globalThis.crypto.randomUUID();
242
+ }
243
+ catch {
244
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
245
+ }
246
+ }
247
+ /** Save `input` and persist. Returns the new list. */
248
+ export function addDraft(input) {
249
+ const next = saveDraft(readDrafts(), {
250
+ text: input.text,
251
+ id: input.id ?? newDraftId(),
252
+ now: input.now ?? Date.now(),
253
+ sessionId: input.sessionId,
254
+ cwd: input.cwd,
255
+ });
256
+ writeDrafts(next);
257
+ return next;
258
+ }
259
+ /** Delete by id and persist. Returns the new list. */
260
+ export function deleteDraft(id) {
261
+ const next = removeDraft(readDrafts(), id);
262
+ writeDrafts(next);
263
+ return next;
264
+ }
265
+ //# sourceMappingURL=drafts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drafts.js","sourceRoot":"","sources":["../src/drafts.ts"],"names":[],"mappings":"AAAA,oEAAoE;AACpE,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,kFAAkF;AAClF,gFAAgF;AAChF,2EAA2E;AAC3E,oEAAoE;AACpE,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,kFAAkF;AAClF,oEAAoE;AACpE,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,iFAAiF;AACjF,0BAA0B;AAE1B,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,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,IAAI,CAAC,GAAG,EAAE;QAC5B,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,GAAG,EAAE,KAAK,CAAC,GAAG;KACf,CAAC,CAAC;IACH,WAAW,CAAC,IAAI,CAAC,CAAC;IAClB,OAAO,IAAI,CAAC;AACd,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,WAAW,CAAC,EAAU;IACpC,MAAM,IAAI,GAAG,WAAW,CAAC,UAAU,EAAE,EAAE,EAAE,CAAC,CAAC;IAC3C,WAAW,CAAC,IAAI,CAAC,CAAC;IAClB,OAAO,IAAI,CAAC;AACd,CAAC"}
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ import { createServer as createHttpServer } from 'node:http';
3
3
  import { createServer as createHttpsServer, request as httpRequest } from 'node:https';
4
4
  import { WebSocketServer, WebSocket } from 'ws';
5
5
  import { SessionPool, getWhereverConfig, detectRemoteRepo } from './session-pool.js';
6
+ import { readDrafts, addDraft, deleteDraft, validateDraftInput } from './drafts.js';
6
7
  import { searchConversations } from './conversation-search.js';
7
8
  import { INITIAL_HISTORY_LIMIT, HISTORY_PAGE_SIZE } from './protocol.js';
8
9
  import fs from 'node:fs';
@@ -779,6 +780,7 @@ async function main() {
779
780
  }
780
781
  const isApiRequest = pathname.startsWith('/sessions') ||
781
782
  pathname.startsWith('/search') ||
783
+ pathname.startsWith('/drafts') ||
782
784
  pathname.startsWith('/models') ||
783
785
  pathname.startsWith('/config') ||
784
786
  pathname.startsWith('/check-path') ||
@@ -819,6 +821,76 @@ async function main() {
819
821
  sendJSON(res, 200, { models });
820
822
  return;
821
823
  }
824
+ // --- Saved drafts (messages kept instead of sent) ----------------------
825
+ // Server-side on purpose: a draft saved on a phone must be there on the
826
+ // laptop, so the store is <config dir>/drafts.json, not browser storage.
827
+ // Behind the same token gate as the other API routes (via isApiRequest).
828
+ // Every mutation answers with the WHOLE new list, so the client never has to
829
+ // merge/cap/dedupe a list of its own: drafts.ts is the only writer.
830
+ if (pathname === '/drafts' && req.method === 'GET') {
831
+ try {
832
+ sendJSON(res, 200, { drafts: readDrafts() });
833
+ }
834
+ catch (err) {
835
+ // An unreadable/corrupt store is reported, never flattened to an empty
836
+ // list: the client would mirror that empty list over its offline copy.
837
+ sendJSON(res, 500, { error: err.message || 'Failed to read drafts' });
838
+ }
839
+ return;
840
+ }
841
+ if (pathname === '/drafts' && req.method === 'POST') {
842
+ let parsed;
843
+ try {
844
+ parsed = JSON.parse((await readBody(req)) || '{}');
845
+ }
846
+ catch {
847
+ sendJSON(res, 400, { error: 'Invalid request' });
848
+ return;
849
+ }
850
+ const invalid = validateDraftInput(parsed);
851
+ if (invalid) {
852
+ // Rejected, not truncated: the composer clears itself once the server
853
+ // has the draft, so a silently stored prefix would lose the tail.
854
+ sendJSON(res, 400, { error: invalid });
855
+ return;
856
+ }
857
+ try {
858
+ const drafts = addDraft({
859
+ text: parsed.text,
860
+ sessionId: typeof parsed.sessionId === 'string' ? parsed.sessionId : undefined,
861
+ cwd: typeof parsed.cwd === 'string' ? parsed.cwd : undefined,
862
+ });
863
+ sendJSON(res, 200, { drafts });
864
+ }
865
+ catch (err) {
866
+ sendJSON(res, 500, { error: err.message || 'Failed to save draft' });
867
+ }
868
+ return;
869
+ }
870
+ // POST rather than DELETE, mirroring /session/delete: the same shape as the
871
+ // rest of this API, and it survives proxies that drop the DELETE method.
872
+ if (pathname === '/drafts/delete' && req.method === 'POST') {
873
+ let parsed;
874
+ try {
875
+ parsed = JSON.parse((await readBody(req)) || '{}');
876
+ }
877
+ catch {
878
+ sendJSON(res, 400, { error: 'Invalid request' });
879
+ return;
880
+ }
881
+ const id = typeof parsed.id === 'string' ? parsed.id : '';
882
+ if (!id) {
883
+ sendJSON(res, 400, { error: 'Missing draft id' });
884
+ return;
885
+ }
886
+ try {
887
+ sendJSON(res, 200, { drafts: deleteDraft(id) });
888
+ }
889
+ catch (err) {
890
+ sendJSON(res, 500, { error: err.message || 'Failed to delete draft' });
891
+ }
892
+ return;
893
+ }
822
894
  if (pathname === '/config' && req.method === 'GET') {
823
895
  const config = getWhereverConfig();
824
896
  let searchFolder = config.searchFolder;