dsh-message-rewind 1.2.2 → 1.2.4

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/client.test.js DELETED
@@ -1,420 +0,0 @@
1
- /**
2
- * Headless smoke test for the client half: it installs against a stubbed Cordis
3
- * context, then renders the message actions and the anchored edit/delete
4
- * popover with a minimal React stand-in. No browser and no real React are
5
- * involved; the popover's placement math is pure and tested on its own.
6
- */
7
- import assert from 'node:assert/strict';
8
- import { readFile } from 'node:fs/promises';
9
-
10
- const source = await readFile(new URL('./client.js', import.meta.url), 'utf8');
11
-
12
- /** React stand-in that keeps hook state per component slot across renders. */
13
- function makeReact() {
14
- const states = new Map();
15
- const refs = new Map();
16
- let slot = 'none';
17
- let index = 0;
18
- return {
19
- Fragment: 'Fragment',
20
- createElement: (type, props, ...children) => ({ type, props: props ?? {}, children }),
21
- __enter(name) { slot = name; index = 0; },
22
- useState(initial) {
23
- const key = `${slot}:${index++}`;
24
- if (!states.has(key)) states.set(key, typeof initial === 'function' ? initial() : initial);
25
- return [states.get(key), (next) => { states.set(key, next); }];
26
- },
27
- useRef(value) {
28
- const key = `${slot}:${index++}`;
29
- if (!refs.has(key)) refs.set(key, { current: value });
30
- return refs.get(key);
31
- },
32
- useMemo: (factory) => { index++; return factory(); },
33
- useCallback: (fn) => { index++; return fn; },
34
- useEffect: (effect) => { index++; effect(); },
35
- useSyncExternalStore: (_subscribe, getSnapshot) => { index++; return getSnapshot(); },
36
- useId: () => `id${index++}`,
37
- };
38
- }
39
-
40
- const react = makeReact();
41
-
42
- function makeElement(name) {
43
- return { dataset: {}, style: {}, textContent: '', remove() {}, setAttribute() {}, tagName: name };
44
- }
45
-
46
- function queryAll(root, predicate, found = []) {
47
- if (root === null || root === undefined) return found;
48
- if (Array.isArray(root)) { for (const item of root) queryAll(item, predicate, found); return found; }
49
- if (typeof root !== 'object') return found;
50
- if (predicate(root)) found.push(root);
51
- queryAll(root.children, predicate, found);
52
- return found;
53
- }
54
-
55
- const styleTags = [];
56
- const calls = [];
57
- const registrations = [];
58
- globalThis.document = {
59
- head: { appendChild: (node) => styleTags.push(node) },
60
- createElement: (name) => makeElement(name),
61
- activeElement: null,
62
- addEventListener() {},
63
- removeEventListener() {},
64
- documentElement: { clientWidth: 1280, clientHeight: 800 },
65
- };
66
- globalThis.window = {
67
- setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
68
- clearTimeout: (id) => globalThis.clearTimeout(id),
69
- __ModuleLoader__: { load: (definition) => { globalThis.__definition = definition; } },
70
- };
71
- Object.defineProperty(globalThis, 'navigator', { value: { clipboard: { writeText: () => Promise.resolve() } }, configurable: true });
72
- // The Host's `inspect` answer; the dialog tests below change it to exercise the
73
- // recorded-file and lost-snapshot branches.
74
- let inspectResult = { files: [], incomplete: false, unfinished: false };
75
- const knownSessions = {};
76
- const ctx = {
77
- effect: (fn) => { fn(); return () => {}; },
78
- locale: {
79
- register: (ns, locale, dict) => { calls.push(['locale.register', ns, locale, dict]); return () => {}; },
80
- bind: (ns) => (key) => `${ns}:${key}`,
81
- },
82
- connection: {
83
- rpc: {
84
- call: (channel, endpoint, payload) => {
85
- calls.push(['rpc.call', channel, endpoint, payload]);
86
- const value = endpoint === 'execute'
87
- ? { sessionId: 'child-1', restored: 0, sourceSessionId: payload.sessionId }
88
- : endpoint === 'purge'
89
- ? { removed: true, archivedOnly: false }
90
- : inspectResult;
91
- return Promise.resolve({ ok: true, value });
92
- },
93
- },
94
- },
95
- uiWorkspace: {
96
- // 0.2.2 refuses a Session the Client catalog does not know.
97
- openSession: (id) => {
98
- if (knownSessions[id] === undefined) throw new Error(`sessions.retain: unknown session ${id}`);
99
- calls.push(['openSession', id]);
100
- },
101
- },
102
- sessions: {
103
- list: { getSnapshot: () => ({ byId: knownSessions }) },
104
- refresh: () => { calls.push(['sessions.refresh']); knownSessions['child-1'] = { sessionId: 'child-1' }; return Promise.resolve(); },
105
- },
106
- slots: {
107
- inject: (name, callback) => { callback(); return () => {}; },
108
- // 0.2.2 rejects a second keyed entry at the same priority; a lower one shadows.
109
- register: (options, component) => {
110
- const clash = registrations.some((entry) => entry.options.name === options.name
111
- && entry.options.key !== undefined
112
- && entry.options.key === options.key
113
- && (entry.options.priority ?? 0) === (options.priority ?? 0));
114
- if (clash) throw new Error(`keyed slot "${options.name}" already has an entry for key "${options.key}" at priority ${options.priority ?? 0}`);
115
- registrations.push({ options, component });
116
- return () => {};
117
- },
118
- },
119
- };
120
-
121
- const originalError = globalThis.console.error;
122
- globalThis.console.error = (...args) => { throw args[0]; };
123
- // The shipped Chat plugin owns the same keyed seat at the default priority; a
124
- // same-priority second registration is what 0.2.2 refuses.
125
- registrations.push({ options: { name: 'conversation.chat.node', key: 'user', locale: '@deepseek-ai/dsh-client-ui-chat' }, component: () => null });
126
- new Function('window', source)(globalThis.window);
127
- const definition = globalThis.__definition;
128
- assert.equal(definition.id, 'dsh-message-rewind');
129
- const plugin = definition.factory((id) => {
130
- if (id === 'react') return react;
131
- throw new Error(`unexpected require: ${id}`);
132
- });
133
- assert.equal(plugin.name, 'dsh-message-rewind');
134
- assert.deepEqual(plugin.inject, ['slots', 'uiWorkspace', 'locale', 'connection', 'sessions']);
135
- plugin.apply(ctx);
136
- globalThis.console.error = originalError;
137
-
138
- assert.equal(styleTags.length, 1, 'one stylesheet is inserted');
139
- assert.deepEqual(calls.filter((call) => call[0] === 'locale.register').map((call) => call[2]), ['zh', 'en']);
140
- const nodeRegistration = registrations.find((entry) => entry.options.key === 'user' && entry.options.priority === -1);
141
- const overlayRegistration = registrations.find((entry) => entry.options.id === 'message-rewind.dialog');
142
- assert.ok(nodeRegistration, 'the user chat node renderer is registered');
143
- assert.equal(nodeRegistration.options.priority, -1, 'a lower priority shadows the shipped user row instead of colliding with it');
144
- assert.ok(overlayRegistration, 'the overlay dialog is registered');
145
-
146
- // --- render the user message row -------------------------------------------
147
- const rendered = [];
148
- const renderUser = (data, running = false) => {
149
- react.__enter('user');
150
- return nodeRegistration.component({
151
- node: { data },
152
- sessionId: 'session-1',
153
- renderFactorySlot: (name, props) => { rendered.push([name, props]); return { type: 'bubble' }; },
154
- loadImage: () => {},
155
- useSession: (selector) => selector({ running }),
156
- });
157
- };
158
- const data = { seq: 7, time: Date.now(), content: [{ type: 'text', text: 'hello' }] };
159
- const tree = renderUser(data);
160
- assert.equal(tree.type, 'div');
161
- assert.equal(tree.props.className, 'dmr-row');
162
- assert.equal(rendered[0][0], 'conversation.chat.user.content');
163
- assert.deepEqual(rendered[0][1].content, { text: 'hello', attachments: [], extraBlocks: [] });
164
- assert.equal(rendered[0][1].interactive, true);
165
- const actions = tree.children[1];
166
- assert.equal(actions.props.className, 'dmr-actions');
167
- const buttons = actions.children.filter(Boolean);
168
- assert.equal(buttons.length, 4, 'clock plus edit, delete and copy');
169
- const inner = buttons.slice(1);
170
- const [editButton, deleteButton] = inner;
171
- assert.equal(inner.length, 3, 'edit, delete and copy');
172
- assert.equal(editButton.props.className, 'dmr-action');
173
- assert.match(deleteButton.props.className, /dmr-danger/);
174
- assert.match(actions.children[0].children[0], /^\d{2}:\d{2}$/, 'today shows a 24h clock only');
175
-
176
- // an older message carries the localized date prefix, like the shipped row
177
- const oldTree = renderUser({ seq: 9, time: Date.now() - 400 * 24 * 60 * 60 * 1000, content: [{ type: 'text', text: 'old' }] });
178
- assert.match(oldTree.children[1].children[0].children[0], /^message-rewind:clock\.ymd \d{2}:\d{2}$/);
179
- assert.ok(renderUser(data, true).children[1].children[1].props.disabled, 'a running turn disables edit');
180
-
181
- // --- an attachment message disables edit just like the host does -----------
182
- const imageTicket = { attachmentId: 'img-1', mediaType: 'image/png', bytes: 1, width: 1, height: 1 };
183
- const imageTree = renderUser({ seq: 8, time: Date.now(), content: [{ type: 'image', attachment: imageTicket }] });
184
- const imageButtons = imageTree.children[1].children.filter(Boolean).slice(1);
185
- assert.equal(imageButtons[0].props.disabled, true, 'attachment messages disable edit');
186
- assert.equal(imageButtons[1].props.disabled, undefined, 'attachment messages stay deletable');
187
-
188
- // --- the dialog is a popover anchored to the clicked button -----------------
189
- const renderDialog = () => { react.__enter('dialog'); return overlayRegistration.component({}); };
190
- const popoverOf = (element) => {
191
- if (element?.type?.name === 'Popover') return element;
192
- return queryAll(element, (candidate) => candidate.type?.name === 'Popover').at(-1) ?? null;
193
- };
194
- // The overlay component returns the popover element; expand it the way React
195
- // would so the rendered tree (head, body, footer) can be inspected.
196
- const expand = (element) => {
197
- const popover = popoverOf(element);
198
- if (!popover) return null;
199
- const children = popover.children.length === 1 ? popover.children[0] : popover.children;
200
- react.__enter('popover');
201
- return popover.type({ ...popover.props, children });
202
- };
203
- const treeOf = () => expand(renderDialog());
204
- const clickAction = (element, anchor) => element.props.onClick(anchor === undefined ? undefined : { currentTarget: anchor });
205
- const tick = () => new Promise((resolve) => setImmediate(resolve));
206
-
207
- // --- edit flow --------------------------------------------------------------
208
- const editAnchor = { tagName: 'BUTTON', id: 'edit-trigger' };
209
- clickAction(editButton, editAnchor);
210
- const popover = popoverOf(renderDialog());
211
- assert.ok(popover, 'edit opens the popover');
212
- assert.equal(popover.props.kind, 'edit');
213
- assert.equal(popover.props.anchor, editAnchor, 'the popover points at the button that opened it');
214
- assert.equal(popover.props.title, 'message-rewind:editTitle');
215
- assert.equal(popover.props.note, 'message-rewind:editNote', 'one short note instead of a paragraph');
216
- let dialog = treeOf();
217
- let pop = dialog.children[0];
218
- assert.equal(dialog.props.className, 'dmr-layer', 'the popover is not a full-screen dialog');
219
- assert.equal(pop.props.className, 'dmr-pop dmr-pop-edit');
220
- assert.equal(pop.props.role, 'dialog');
221
- assert.equal(pop.props['aria-label'], 'message-rewind:editTitle');
222
- assert.equal(pop.props['data-side'], 'bottom', 'first paint assumes it hangs below the button');
223
- assert.equal(pop.props.style, undefined, 'no coordinates until the browser measures');
224
- assert.equal(pop.children[0].props.className, 'dmr-arrow');
225
- assert.equal(pop.children[1].props.className, 'dmr-head');
226
- assert.equal(pop.children[2].props.className, 'dmr-body');
227
- assert.equal(pop.children[3].props.className, 'dmr-footer');
228
- const textarea = () => queryAll(treeOf(), (element) => element.type === 'textarea').at(0);
229
- assert.equal(textarea().props.value, 'hello', 'the message text is prefilled on the first paint');
230
- textarea().props.onChange({ target: { value: 'hello there' } });
231
- assert.equal(textarea().props.value, 'hello there', 'typing stays local until save');
232
- textarea().props.onChange({ target: { value: 'hello' } });
233
- await tick();
234
- assert.equal(calls.filter((call) => call[0] === 'rpc.call').at(0)[2], 'inspect', 'opening edit inspects file changes');
235
- assert.deepEqual(calls.filter((call) => call[0] === 'rpc.call').at(0)[3], { sessionId: 'session-1', seq: 7 });
236
- const footer = () => queryAll(treeOf(), (element) => element.props?.className === 'dmr-footer').at(-1);
237
- assert.deepEqual(footer().children.filter(Boolean).map((button) => button.children.join('')), [
238
- 'message-rewind:cancel',
239
- 'message-rewind:save',
240
- ], 'cancel plus the primary action');
241
- footer().children.filter(Boolean).at(-1).props.onClick();
242
- await tick();
243
- assert.ok(!renderDialog(), 'a clean edit closes the popover after forking');
244
- assert.deepEqual(calls.filter((call) => call[0] === 'openSession'), [['openSession', 'child-1']], 'the branch is opened');
245
- const openedAt = calls.findIndex((call) => call[0] === 'openSession');
246
- const refreshedAt = calls.findIndex((call) => call[0] === 'sessions.refresh');
247
- assert.ok(refreshedAt !== -1 && refreshedAt < openedAt, 'the fresh child is pulled into the client catalog before it is opened');
248
- await new Promise((resolve) => setTimeout(resolve, 400));
249
- const purged = calls.filter((call) => call[0] === 'rpc.call' && call[2] === 'purge').at(-1);
250
- assert.deepEqual(purged[3], { sessionId: 'session-1' }, 'the untouched source is retired');
251
-
252
- // --- an edit that recorded file changes offers both rollback scopes ---------
253
- inspectResult = { files: ['test.txt', 'src/app.js'], incomplete: false, unfinished: false };
254
- clickAction(editButton, editAnchor);
255
- await tick();
256
- dialog = treeOf();
257
- const disclosure = queryAll(dialog, (element) => element.type === 'details').at(0);
258
- assert.equal(disclosure.props.className, 'dmr-files-block', 'the recorded files start collapsed');
259
- assert.equal(queryAll(disclosure, (element) => element.type === 'summary').at(0).children[1], 'message-rewind:filesCount');
260
- assert.deepEqual(
261
- queryAll(disclosure, (element) => element.type === 'li').map((item) => item.children.join('')),
262
- ['test.txt', 'src/app.js'],
263
- 'the recorded files are listed');
264
- const scope = queryAll(dialog, (element) => element.props?.role === 'radio');
265
- assert.equal(scope.length, 2, 'edit offers the shared scope control');
266
- assert.equal(scope[0].props['aria-checked'], true, 'messages-only is the default');
267
- assert.deepEqual(scope.map((option) => option.children.join('')), [
268
- 'message-rewind:messagesOnly',
269
- 'message-rewind:withFiles',
270
- ], 'a compact either/or, not two radio lines');
271
- scope[1].props.onClick();
272
- dialog = treeOf();
273
- const scopeAfter = queryAll(dialog, (element) => element.props?.role === 'radio');
274
- assert.equal(scopeAfter[1].props['aria-checked'], true, 'the choice sticks');
275
- assert.equal(queryAll(dialog, (element) => element.props?.className === 'dmr-hint').at(0).children[0], 'message-rewind:fileWarning',
276
- 'the consequence is only spelled out once files are chosen');
277
- const scopeButtons = footer().children.filter(Boolean);
278
- scopeButtons.at(-1).props.onClick();
279
- await tick();
280
- assert.deepEqual(
281
- calls.filter((call) => call[0] === 'rpc.call' && call[2] === 'execute').at(-1)[3],
282
- { sessionId: 'session-1', seq: 7, action: 'edit', text: 'hello', rewindFiles: true },
283
- 'the edited text is resent after the files roll back');
284
- assert.ok(!renderDialog(), 'the popover closes after rolling back and resending');
285
- await new Promise((resolve) => setTimeout(resolve, 400));
286
-
287
- // --- a lost snapshot leaves exactly one choice, so no control is shown ------
288
- inspectResult = { files: [], incomplete: true, unfinished: false };
289
- clickAction(editButton, editAnchor);
290
- await tick();
291
- dialog = treeOf();
292
- assert.equal(queryAll(dialog, (element) => element.props?.className === 'dmr-warning').at(0).children[0], 'message-rewind:incomplete');
293
- assert.equal(queryAll(dialog, (element) => element.props?.role === 'radio').length, 0, 'there is nothing to choose');
294
- const staleButtons = footer().children.filter(Boolean);
295
- assert.equal(staleButtons.length, 2, 'cancel plus the messages-only action');
296
- staleButtons[0].props.onClick();
297
- assert.ok(!renderDialog(), 'cancel closes the stale-snapshot popover');
298
- inspectResult = { files: [], incomplete: false, unfinished: false };
299
-
300
- // --- delete flow ------------------------------------------------------------
301
- const deleteAnchor = { tagName: 'BUTTON', id: 'delete-trigger' };
302
- clickAction(deleteButton, deleteAnchor);
303
- dialog = treeOf();
304
- pop = dialog.children[0];
305
- assert.equal(pop.props.className, 'dmr-pop dmr-pop-delete', 'the confirm bubble is narrower');
306
- assert.equal(popoverOf(renderDialog()).props.anchor, deleteAnchor, 'the delete bubble points at the bin');
307
- assert.equal(popoverOf(renderDialog()).props.note, 'message-rewind:deleteNote');
308
- assert.equal(queryAll(dialog, (element) => element.props?.className === 'dmr-hint').at(0).children[1], 'message-rewind:loading');
309
- const loadingFooter = queryAll(dialog, (element) => element.props?.className === 'dmr-footer').at(0);
310
- const loadingButtons = loadingFooter.children.filter(Boolean);
311
- assert.deepEqual(loadingButtons.map((button) => button.children.join('')), [
312
- 'message-rewind:cancel',
313
- 'message-rewind:deleteConfirm',
314
- ], 'the confirm stays put while the files are read');
315
- assert.ok(!loadingButtons[0].props.disabled, 'loading stays cancellable');
316
- assert.equal(loadingButtons[1].props.disabled, true, 'delete waits for the inspection');
317
- await tick();
318
- dialog = treeOf();
319
- const deleteFooter = queryAll(dialog, (element) => element.props?.className === 'dmr-footer').at(-1);
320
- const deleteButtons = deleteFooter.children.filter(Boolean);
321
- assert.equal(deleteButtons.length, 2, 'cancel plus delete');
322
- deleteButtons.at(-1).props.onClick();
323
- await tick();
324
- const execute = calls.filter((call) => call[0] === 'rpc.call' && call[2] === 'execute').at(-1);
325
- assert.deepEqual(execute[3], { sessionId: 'session-1', seq: 7, action: 'delete', text: '', rewindFiles: false });
326
- await tick();
327
- assert.deepEqual(calls.filter((call) => call[0] === 'openSession').at(-1), ['openSession', 'child-1']);
328
-
329
- // --- delete asks the same question, so it renders the same control ----------
330
- inspectResult = { files: ['test.txt'], incomplete: false, unfinished: false };
331
- clickAction(deleteButton, deleteAnchor);
332
- await tick();
333
- dialog = treeOf();
334
- const deleteScope = queryAll(dialog, (element) => element.props?.role === 'radio');
335
- assert.equal(deleteScope.length, 2, 'delete offers the same scope control');
336
- assert.equal(deleteScope[0].props['aria-checked'], true, 'messages-only is the default');
337
- deleteScope[1].props.onClick();
338
- const deleteActions = queryAll(treeOf(), (element) => element.props?.className === 'dmr-footer').at(-1).children.filter(Boolean);
339
- assert.deepEqual(deleteActions.map((button) => button.children.join('')), [
340
- 'message-rewind:cancel',
341
- 'message-rewind:deleteConfirm',
342
- ], 'the delete action follows the chosen scope');
343
- assert.match(deleteActions.at(-1).props.className, /dmr-destructive/, 'the destructive confirm is styled as such');
344
- deleteActions.at(-1).props.onClick();
345
- await tick();
346
- assert.deepEqual(
347
- calls.filter((call) => call[0] === 'rpc.call' && call[2] === 'execute').at(-1)[3],
348
- { sessionId: 'session-1', seq: 7, action: 'delete', text: '', rewindFiles: true },
349
- 'the chosen file scope reaches the Host');
350
- inspectResult = { files: [], incomplete: false, unfinished: false };
351
-
352
- // let the delayed purge settle before the failure-path test swaps the RPC stub
353
- await new Promise((resolve) => setTimeout(resolve, 400));
354
-
355
- // --- clicking the open action again toggles the popover ---------------------
356
- clickAction(editButton, editAnchor);
357
- assert.ok(renderDialog(), 'edit opens');
358
- textarea().props.onChange({ target: { value: 'unsent draft' } });
359
- assert.equal(textarea().props.value, 'unsent draft');
360
- clickAction(editButton, editAnchor);
361
- assert.ok(!renderDialog(), 'a second click on the same action closes it');
362
- clickAction(editButton, editAnchor);
363
- assert.equal(textarea().props.value, 'hello', 'a reopened popover starts from the message, not the old draft');
364
- clickAction(editButton, editAnchor);
365
- assert.ok(!renderDialog(), 'and closes again');
366
-
367
- // --- host failure codes are localized --------------------------------------
368
- ctx.connection.rpc.call = () => Promise.resolve({
369
- ok: false,
370
- error: { message: '请先停止当前运行', details: { rewindCode: 'open-turn' } },
371
- });
372
- clickAction(deleteButton, deleteAnchor);
373
- await tick();
374
- const failed = queryAll(treeOf(), (element) => element.props?.className === 'dmr-error').at(0);
375
- assert.equal(failed.children[0], 'message-rewind:error.open-turn');
376
- queryAll(treeOf(), (element) => element.props?.className === 'dmr-footer').at(0).children[0].props.onClick();
377
- assert.ok(!renderDialog(), 'cancel closes the failed popover');
378
-
379
- // --- a late response cannot resurrect a closed popover ----------------------
380
- ctx.connection.rpc.call = (channel, endpoint, payload) => {
381
- calls.push(['rpc.call', channel, endpoint, payload]);
382
- return new Promise((resolve) => {
383
- globalThis.setTimeout(() => resolve({ ok: true, value: { files: [], incomplete: false, unfinished: false } }), 20);
384
- });
385
- };
386
- clickAction(deleteButton, deleteAnchor);
387
- const loadingDialog = treeOf();
388
- assert.ok(loadingDialog, 'delete opens in the loading phase');
389
- const lateFooter = queryAll(loadingDialog, (element) => element.props?.className === 'dmr-footer').at(0);
390
- lateFooter.children[0].props.onClick();
391
- assert.ok(!renderDialog(), 'the loading phase can be cancelled');
392
- await new Promise((resolve) => setTimeout(resolve, 60));
393
- assert.ok(!renderDialog(), 'the late inspect response does not reopen the popover');
394
-
395
- // --- placement: below the button, flipped when needed, always on screen -----
396
- const geometry = source.match(/#region popover-geometry([\s\S]*?)#endregion/);
397
- assert.ok(geometry, 'the placement block is marked for extraction');
398
- const { placePopover } = new Function(`${geometry[1]}\nreturn { placePopover };`)();
399
- const wide = { width: 1280, height: 800 };
400
-
401
- assert.deepEqual(
402
- placePopover({ left: 1100, top: 100, width: 28, bottom: 128 }, { width: 320, height: 180 }, wide),
403
- { left: 952, top: 136, arrow: 157, below: true },
404
- 'hangs 8px below the button, centred on it, clamped to the right edge');
405
- assert.deepEqual(
406
- placePopover({ left: 600, top: 300, width: 28, bottom: 328 }, { width: 320, height: 180 }, { width: 1280, height: 400 }),
407
- { left: 454, top: 112, arrow: 155, below: false },
408
- 'flips above the button when the space below is too small');
409
- const edge = placePopover({ left: 8, top: 40, width: 28, bottom: 68 }, { width: 320, height: 180 }, wide);
410
- assert.deepEqual(edge, { left: 8, top: 76, arrow: 14, below: true }, 'the arrow stays clear of the rounded corner');
411
- assert.equal(
412
- placePopover({ left: 1252, top: 40, width: 28, bottom: 68 }, { width: 320, height: 180 }, wide).arrow,
413
- 295,
414
- 'and clear of the far corner too');
415
- assert.equal(
416
- placePopover({ left: 600, top: 40, width: 28, bottom: 68 }, { width: 320, height: 900 }, { width: 1280, height: 500 }).top,
417
- 8,
418
- 'an oversized popover pins to the top edge instead of running off screen');
419
-
420
- console.log('client self-check passed');
package/files.test.js DELETED
@@ -1,181 +0,0 @@
1
- /**
2
- * File-rewind self-check against a real temporary directory. The recorded
3
- * diffs are handcrafted to match what `dsh-workspace-changes` produces: it diffs
4
- * newline-terminated text with jsdiff but hands back every hunk line without its
5
- * newline — an empty body is one blank line — and a deletion is
6
- * `before: true, after: false`.
7
- */
8
- import assert from 'node:assert/strict';
9
- import { promises as fsp } from 'node:fs';
10
- import { tmpdir } from 'node:os';
11
- import { join } from 'node:path';
12
- import { planRewind, applyRewind, invert } from './files.js';
13
-
14
- let passed = 0;
15
- const check = (label, fn) => fn().then(() => { passed += 1; }, (error) => { throw new Error(`${label}: ${error.message}`); });
16
-
17
- const workspace = await fsp.mkdtemp(join(tmpdir(), 'dmr-files-'));
18
- const recordsFor = (entries) => entries.map(({ seq, files }) => ({
19
- seq,
20
- summary: { turn: 1, cwd: workspace, files, total: files.length, added: 0, deleted: 0 },
21
- }));
22
- const readDiffFrom = (table) => async (seq, index) => {
23
- const found = table[`${seq}:${index}`];
24
- if (!found) throw new Error(`no recorded diff for ${seq}:${index}`);
25
- return found;
26
- };
27
- const abs = (name) => join(workspace, name);
28
- const textDiff = (path, before, after, hunks) => ({ kind: 'text', path, display: path, before, after, hunks, coarse: false });
29
-
30
- // --- a turn that deleted a file is restorable ------------------------------
31
- const deletedName = 'deleted.txt';
32
- const deletedBefore = 'one\ntwo\n';
33
- const deletedDiff = textDiff(deletedName, true, false, [{ oldStart: 1, oldLines: 2, newStart: 0, newLines: 0, lines: ['-one\n', '-two\n'] }]);
34
- await check('deleted file is recreated', async () => {
35
- assert.deepEqual(await readExists(deletedName), null);
36
- const targets = await planRewind(readDiffFrom({ '1:0': deletedDiff }), recordsFor([{ seq: 1, files: [{ path: deletedName, display: deletedName }] }]));
37
- assert.deepEqual([...targets.values()][0].original, { exists: true, text: deletedBefore });
38
- await applyRewind(targets);
39
- assert.equal(await fsp.readFile(abs(deletedName), 'utf8'), deletedBefore);
40
- });
41
-
42
- // --- a turn that created a file is undone by removing it --------------------
43
- const createdName = 'created.txt';
44
- const createdDiff = textDiff(createdName, false, true, [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 1, lines: ['+abc'] }]);
45
- await check('created file is removed', async () => {
46
- await fsp.writeFile(abs(createdName), 'abc', 'utf8');
47
- const targets = await planRewind(readDiffFrom({ '2:0': createdDiff }), recordsFor([{ seq: 2, files: [{ path: createdName, display: createdName }] }]));
48
- assert.deepEqual([...targets.values()][0].original, { exists: false, text: null });
49
- await applyRewind(targets);
50
- await assert.rejects(() => fsp.stat(abs(createdName)));
51
- });
52
-
53
- // --- the recorder's hunk lines carry no newline; a blank line is one line ---
54
- const blankCreatedName = 'blank-created.txt';
55
- const blankCreatedDiff = textDiff(blankCreatedName, false, true, [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 3, lines: ['+a', '+', '+b'] }]);
56
- await check('created file with a blank line is removed', async () => {
57
- await fsp.writeFile(abs(blankCreatedName), 'a\n\nb\n', 'utf8');
58
- const targets = await planRewind(readDiffFrom({ '13:0': blankCreatedDiff }), recordsFor([{ seq: 13, files: [{ path: blankCreatedName, display: blankCreatedName }] }]));
59
- assert.deepEqual([...targets.values()][0].original, { exists: false, text: null });
60
- await applyRewind(targets);
61
- await assert.rejects(() => fsp.stat(abs(blankCreatedName)));
62
- });
63
-
64
- const blankEditedName = 'blank-edited.txt';
65
- const blankEditedDiff = textDiff(blankEditedName, true, true, [{ oldStart: 1, oldLines: 4, newStart: 1, newLines: 4, lines: [' a', ' ', '-b', '+B', ' c'] }]);
66
- await check('blank context line still inverts a modification', async () => {
67
- await fsp.writeFile(abs(blankEditedName), 'a\n\nB\nc\n', 'utf8');
68
- const targets = await planRewind(readDiffFrom({ '14:0': blankEditedDiff }), recordsFor([{ seq: 14, files: [{ path: blankEditedName, display: blankEditedName }] }]));
69
- await applyRewind(targets);
70
- assert.equal(await fsp.readFile(abs(blankEditedName), 'utf8'), 'a\n\nb\nc\n');
71
- });
72
-
73
- // --- a turn that modified a file is reverted -------------------------------
74
- const editedName = 'edited.txt';
75
- const editedDiff = textDiff(editedName, true, true, [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [' zero\n', ' one\n', '-two\n', '+TWO\n'] }]);
76
- await check('modified file is reverted', async () => {
77
- await fsp.writeFile(abs(editedName), 'zero\none\nTWO\n', 'utf8');
78
- const targets = await planRewind(readDiffFrom({ '3:0': editedDiff }), recordsFor([{ seq: 3, files: [{ path: editedName, display: editedName }] }]));
79
- await applyRewind(targets);
80
- assert.equal(await fsp.readFile(abs(editedName), 'utf8'), 'zero\none\ntwo\n');
81
- });
82
-
83
- // --- a file stored without a final newline still matches the diff ----------
84
- const bareName = 'bare.txt';
85
- const bareDiff = textDiff(bareName, true, true, [{ oldStart: 1, oldLines: 1, newStart: 1, newLines: 2, lines: [' x\n', '+y'] }]);
86
- await check('unterminated file is reverted', async () => {
87
- await fsp.writeFile(abs(bareName), 'x\ny', 'utf8');
88
- const targets = await planRewind(readDiffFrom({ '4:0': bareDiff }), recordsFor([{ seq: 4, files: [{ path: bareName, display: bareName }] }]));
89
- await applyRewind(targets);
90
- assert.equal(await fsp.readFile(abs(bareName), 'utf8'), 'x\n');
91
- });
92
-
93
- // --- a UTF-8 BOM survives the round trip -----------------------------------
94
- const bomName = 'bom.txt';
95
- const bomDiff = textDiff(bomName, true, true, [{ oldStart: 1, oldLines: 2, newStart: 1, newLines: 2, lines: [' \uFEFFone\n', '-two\n', '+TWO\n'] }]);
96
- await check('utf-8 BOM file is reverted without losing the BOM', async () => {
97
- const bom = Buffer.from([0xEF, 0xBB, 0xBF]);
98
- await fsp.writeFile(abs(bomName), Buffer.concat([bom, Buffer.from('one\nTWO\n', 'utf8')]));
99
- const targets = await planRewind(readDiffFrom({ '10:0': bomDiff }), recordsFor([{ seq: 10, files: [{ path: bomName, display: bomName }] }]));
100
- await applyRewind(targets);
101
- const bytes = await fsp.readFile(abs(bomName));
102
- assert.deepEqual([...bytes.subarray(0, 3)], [0xEF, 0xBB, 0xBF]);
103
- assert.equal(bytes.toString('utf8'), '\uFEFFone\ntwo\n');
104
- });
105
-
106
- // --- a created file edited after its turn is refused, not deleted ----------
107
- const createdLaterName = 'created-later.txt';
108
- const createdLaterDiff = textDiff(createdLaterName, false, true, [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 1, lines: ['+original\n'] }]);
109
- await check('created file edited later is refused', async () => {
110
- await fsp.writeFile(abs(createdLaterName), 'original\nplus a manual edit\n', 'utf8');
111
- await assert.rejects(
112
- () => planRewind(readDiffFrom({ '11:0': createdLaterDiff }), recordsFor([{ seq: 11, files: [{ path: createdLaterName, display: createdLaterName }] }])),
113
- /created-later\.txt:.*在记录之后又被修改过/,
114
- );
115
- await fsp.writeFile(abs(createdLaterName), 'original\n', 'utf8');
116
- const targets = await planRewind(readDiffFrom({ '12:0': createdLaterDiff }), recordsFor([{ seq: 12, files: [{ path: createdLaterName, display: createdLaterName }] }]));
117
- await applyRewind(targets);
118
- await assert.rejects(() => fsp.stat(abs(createdLaterName)));
119
- });
120
-
121
- // --- a file changed after that turn refuses instead of guessing -------------
122
- await check('conflicting later edit is refused', async () => {
123
- await fsp.writeFile(abs(editedName), 'zero\none\nTHREE\n', 'utf8');
124
- await assert.rejects(
125
- () => planRewind(readDiffFrom({ '5:0': editedDiff }), recordsFor([{ seq: 5, files: [{ path: editedName, display: editedName }] }])),
126
- /edited\.txt:.*(在记录之后又被修改过|文件版本已改变)/,
127
- );
128
- });
129
-
130
- // --- several turns on one path unwind newest first -------------------------
131
- const chainedName = 'chained.txt';
132
- const chainedCreated = textDiff(chainedName, false, true, [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 1, lines: ['+abc'] }]);
133
- const chainedEdited = textDiff(chainedName, true, true, [{ oldStart: 1, oldLines: 1, newStart: 1, newLines: 2, lines: [' abc\n', '+def\n'] }]);
134
- await check('multi-turn path unwinds to absent', async () => {
135
- await fsp.writeFile(abs(chainedName), 'abc\ndef\n', 'utf8');
136
- const targets = await planRewind(
137
- readDiffFrom({ '6:0': chainedCreated, '7:0': chainedEdited }),
138
- recordsFor([
139
- { seq: 6, files: [{ path: chainedName, display: chainedName }] },
140
- { seq: 7, files: [{ path: chainedName, display: chainedName }] },
141
- ]),
142
- );
143
- await applyRewind(targets);
144
- await assert.rejects(() => fsp.stat(abs(chainedName)));
145
- });
146
-
147
- // --- undo restores exactly what the rewind replaced --------------------------
148
- await check('undo restores the pre-rewind state', async () => {
149
- await fsp.writeFile(abs(editedName), 'zero\none\nTWO\n', 'utf8');
150
- const targets = await planRewind(readDiffFrom({ '8:0': editedDiff }), recordsFor([{ seq: 8, files: [{ path: editedName, display: editedName }] }]));
151
- const applied = await applyRewind(targets);
152
- assert.equal(await fsp.readFile(abs(editedName), 'utf8'), 'zero\none\ntwo\n');
153
- await applied.undo();
154
- assert.equal(await fsp.readFile(abs(editedName), 'utf8'), 'zero\none\nTWO\n');
155
- });
156
-
157
- // --- a path outside the recorded workspace is refused ----------------------
158
- await check('path outside the workspace is refused', async () => {
159
- await assert.rejects(
160
- () => planRewind(readDiffFrom({}), recordsFor([{ seq: 9, files: [{ path: '../escape.txt', display: '../escape.txt' }] }])),
161
- /不在该轮工作区内/,
162
- );
163
- });
164
-
165
- // --- invert is a pure total function on absence ----------------------------
166
- assert.deepEqual(invert({ exists: false, text: null }, deletedDiff), { exists: true, text: deletedBefore });
167
- assert.deepEqual(invert({ exists: true, text: 'abc' }, createdDiff), { exists: false, text: null });
168
- assert.throws(() => invert({ exists: true, text: 'abc changed' }, createdDiff), /在记录之后又被修改过/);
169
-
170
- async function readExists(name) {
171
- try {
172
- return await fsp.readFile(abs(name), 'utf8');
173
- } catch (error) {
174
- if (error.code === 'ENOENT') return null;
175
- throw error;
176
- }
177
- }
178
-
179
- await fsp.rm(workspace, { recursive: true, force: true });
180
- console.log(`files self-check passed (${passed} scenarios)`);
181
-