@anionex/dsh-turn-rewind 0.3.11 → 0.3.12
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/CHANGELOG.md +9 -0
- package/README.md +4 -2
- package/README.zh.md +3 -1
- package/lib/client.js +159 -8
- package/lib/client.js.map +1 -1
- package/lib/index.js +2 -1
- package/lib/rewind-host.js +67 -0
- package/lib/types/client/index.d.ts +65 -4
- package/lib/types/rewind-host.d.ts +11 -0
- package/package.json +5 -4
- package/src/client/index.tsx +209 -11
- package/src/index.ts +2 -1
- package/src/rewind-host.ts +88 -0
package/lib/rewind-host.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import { createDeadline } from './deadline.js';
|
|
3
4
|
import { ChangeLedgerError, errorMessage } from './errors.js';
|
|
4
5
|
import { discoverWorkspaceRoot } from './workspace.js';
|
|
@@ -611,6 +612,72 @@ function json(response, status, value) {
|
|
|
611
612
|
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
612
613
|
response.end(`${JSON.stringify(value)}\n`);
|
|
613
614
|
}
|
|
615
|
+
/** Same-origin route that replays one stored attachment's bytes to the browser. */
|
|
616
|
+
export const ATTACHMENT_HTTP_PATH = '/turn-rewind/attachment-bytes';
|
|
617
|
+
/** Register the attachment-bytes route consumed by the rewound composer draft. */
|
|
618
|
+
export function installAttachmentHttp(ctx) {
|
|
619
|
+
ctx.effect(() => ctx.webServer.register({
|
|
620
|
+
kind: 'exact',
|
|
621
|
+
path: ATTACHMENT_HTTP_PATH,
|
|
622
|
+
handler: createAttachmentHttpHandler(ctx),
|
|
623
|
+
}), 'change-ledger.attachmentHttp');
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Build the attachment-bytes route as a testable unit.
|
|
627
|
+
*
|
|
628
|
+
* Bytes travel in a JSON envelope shared by Web and Desktop carriers;
|
|
629
|
+
* the browser rebuilds a `File` from the verified message reference.
|
|
630
|
+
*/
|
|
631
|
+
export function createAttachmentHttpHandler(ctx) {
|
|
632
|
+
return async (request, response) => {
|
|
633
|
+
if (request.method !== 'GET') {
|
|
634
|
+
json(response, 405, { ok: false, error: 'method not allowed' });
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
try {
|
|
638
|
+
const url = new URL(request.url ?? ATTACHMENT_HTTP_PATH, 'http://dsh.local');
|
|
639
|
+
const attachmentId = requiredText(url.searchParams.get('attachmentId'), 'attachmentId');
|
|
640
|
+
const sessionId = requiredText(url.searchParams.get('sessionId'), 'sessionId');
|
|
641
|
+
const messageSeq = Number(url.searchParams.get('messageSeq'));
|
|
642
|
+
if (!url.searchParams.has('messageSeq') || !Number.isSafeInteger(messageSeq) || messageSeq < 0)
|
|
643
|
+
throw new Error('invalid messageSeq');
|
|
644
|
+
const kind = url.searchParams.get('kind');
|
|
645
|
+
if (kind !== 'image' && kind !== 'file')
|
|
646
|
+
throw new Error('invalid attachment kind');
|
|
647
|
+
const session = await readSession(ctx, sessionId);
|
|
648
|
+
const message = getSessionEvents(session).find(event => event.seq === messageSeq && event.type === 'user/message' && isDirectUserMessage(event));
|
|
649
|
+
const blocks = Array.isArray(message?.data.content) ? message.data.content : [];
|
|
650
|
+
const block = blocks.find(value => value?.type === kind && value.attachment?.attachmentId === attachmentId);
|
|
651
|
+
if (block === undefined) {
|
|
652
|
+
json(response, 404, { ok: false, error: 'attachment is not referenced by the selected message' });
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const store = ctx.get('attachments');
|
|
656
|
+
if (store === undefined) {
|
|
657
|
+
json(response, 503, { ok: false, error: 'attachment store is unavailable' });
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
const ref = block.attachment;
|
|
661
|
+
const hostPath = kind === 'image' ? store.imageHostPath(ref) : store.fileHostPath(ref);
|
|
662
|
+
if (hostPath === undefined) {
|
|
663
|
+
json(response, 503, { ok: false, error: 'attachment is not available from the local store' });
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
const bytes = await readFile(hostPath);
|
|
667
|
+
json(response, 200, {
|
|
668
|
+
ok: true,
|
|
669
|
+
attachmentId,
|
|
670
|
+
kind,
|
|
671
|
+
...(ref.mediaType === undefined ? {} : { mediaType: ref.mediaType }),
|
|
672
|
+
data: bytes.toString('base64'),
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
catch (error) {
|
|
676
|
+
const message = errorMessage(error);
|
|
677
|
+
json(response, message.includes('ENOENT') ? 404 : 400, { ok: false, error: 'unable to restore the selected attachment' });
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
}
|
|
614
681
|
export const MANAGE_HTTP_PATH = '/turn-rewind/manage';
|
|
615
682
|
/** Register the same-origin storage-management endpoint consumed by the settings card. */
|
|
616
683
|
export function installManageHttp(ctx, engine) {
|
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
import { type ReactNode } from 'react';
|
|
2
|
+
/** Durable reference carried by one `image` / `file` content block. */
|
|
3
|
+
interface AttachmentRefLike {
|
|
4
|
+
readonly attachmentId?: string;
|
|
5
|
+
readonly name?: string;
|
|
6
|
+
readonly mediaType?: string;
|
|
7
|
+
readonly bytes?: number;
|
|
8
|
+
}
|
|
2
9
|
interface ConversationNodeLike {
|
|
3
10
|
readonly kind: string;
|
|
4
11
|
readonly seq: number;
|
|
5
12
|
readonly content?: readonly {
|
|
6
13
|
readonly type: string;
|
|
7
14
|
readonly text?: string;
|
|
15
|
+
readonly attachment?: AttachmentRefLike;
|
|
8
16
|
}[];
|
|
9
17
|
}
|
|
10
18
|
interface ConversationChatNodeLike {
|
|
@@ -36,18 +44,29 @@ interface ConversationSnapshotLike extends ChatSnapshotLike {
|
|
|
36
44
|
/** Selector hook shape shared by `useSession` and `useChat`. */
|
|
37
45
|
type SnapshotSelectorHook = <T>(selector: (snapshot: ConversationSnapshotLike) => T) => T;
|
|
38
46
|
type RewindNodeLike = ConversationNodeLike | ConversationChatNodeLike;
|
|
47
|
+
/** One durable attachment that the restart has to hand back to the composer. */
|
|
48
|
+
interface RewindAttachment {
|
|
49
|
+
readonly kind: 'image' | 'file';
|
|
50
|
+
readonly attachmentId: string;
|
|
51
|
+
readonly name: string;
|
|
52
|
+
readonly mediaType: string;
|
|
53
|
+
readonly sourceSessionId?: string;
|
|
54
|
+
readonly messageSeq?: number;
|
|
55
|
+
}
|
|
39
56
|
interface RewindMatch {
|
|
40
57
|
readonly messageSeq: number;
|
|
41
58
|
readonly promptText: string;
|
|
59
|
+
/** Present only when the message carried attachments; absent keeps older doubles valid. */
|
|
60
|
+
readonly attachments?: readonly RewindAttachment[];
|
|
42
61
|
}
|
|
43
62
|
interface RewindMessageActionProps {
|
|
44
63
|
readonly matched: RewindMatch;
|
|
45
64
|
readonly sessionId: string;
|
|
46
|
-
readonly openRestoredSession: (sessionId: string, promptText: string) => Promise<void>;
|
|
65
|
+
readonly openRestoredSession: (sessionId: string, promptText: string, attachments?: readonly RewindAttachment[]) => Promise<void>;
|
|
47
66
|
}
|
|
48
67
|
interface RewindPortalBridgeProps {
|
|
49
68
|
readonly sessionId: string;
|
|
50
|
-
readonly openRestoredSession: (sessionId: string, promptText: string) => Promise<void>;
|
|
69
|
+
readonly openRestoredSession: (sessionId: string, promptText: string, attachments?: readonly RewindAttachment[]) => Promise<void>;
|
|
51
70
|
readonly useSession: SnapshotSelectorHook;
|
|
52
71
|
readonly useChat?: SnapshotSelectorHook;
|
|
53
72
|
}
|
|
@@ -82,6 +101,8 @@ interface ClientContextLike {
|
|
|
82
101
|
readonly input: {
|
|
83
102
|
for(scope: unknown): {
|
|
84
103
|
setDraft(text: string): void;
|
|
104
|
+
addAttachments?(ids: readonly string[]): boolean;
|
|
105
|
+
notify?(level: 'info' | 'error', text: string): void;
|
|
85
106
|
};
|
|
86
107
|
};
|
|
87
108
|
};
|
|
@@ -201,8 +222,16 @@ type UiLocale = 'zh' | 'en';
|
|
|
201
222
|
* @returns the language whose copy to render.
|
|
202
223
|
*/
|
|
203
224
|
export declare function resolveUiLocale(active: string | undefined): UiLocale;
|
|
204
|
-
/** Return the rewind anchor
|
|
225
|
+
/** Return the rewind anchor, editable text, and durable attachments owned by one direct user message. */
|
|
205
226
|
export declare function selectRewindMessage(node: ConversationNodeLike): RewindMatch | null;
|
|
227
|
+
/**
|
|
228
|
+
* Collect the durable `image` / `file` references carried by one user message.
|
|
229
|
+
*
|
|
230
|
+
* Keep missing references so restoration can report unavailable attachments.
|
|
231
|
+
* @param node - the direct user-message node the rewind anchors on.
|
|
232
|
+
* @returns attachments in message order; empty when the message has none.
|
|
233
|
+
*/
|
|
234
|
+
export declare function selectRewindAttachments(node: ConversationNodeLike): readonly RewindAttachment[];
|
|
206
235
|
/**
|
|
207
236
|
* Browser plugin entry: bridge every direct user-message action row to the rewind UI.
|
|
208
237
|
*
|
|
@@ -241,7 +270,39 @@ export declare function selectRewindMessageTarget(value: RewindNodeLike): {
|
|
|
241
270
|
readonly matched: RewindMatch;
|
|
242
271
|
readonly rowKey: string;
|
|
243
272
|
} | null;
|
|
244
|
-
|
|
273
|
+
/**
|
|
274
|
+
* Re-upload one durable attachment as a fresh draft attachment.
|
|
275
|
+
*
|
|
276
|
+
* The stored bytes are read back from the Host, wrapped in a `File`, and handed
|
|
277
|
+
* to the composer bridge, because the composer only understands browser files.
|
|
278
|
+
* @param attachment - durable reference taken from the rewound message.
|
|
279
|
+
* @returns the rebuilt file, or `undefined` when the Host cannot serve it.
|
|
280
|
+
*/
|
|
281
|
+
export declare function readAttachmentFile(attachment: RewindAttachment): Promise<File>;
|
|
282
|
+
/**
|
|
283
|
+
* Hand a rewound message's attachments back to the composer.
|
|
284
|
+
*
|
|
285
|
+
* Draft attachments are browser-owned `File`s with upload receipts, so the
|
|
286
|
+
* durable references are read back from the Host and registered exactly the way
|
|
287
|
+
* the composer's own picker does it: `createDrafts` allocates the drafts,
|
|
288
|
+
* `input.for(scope).addAttachments` adopts their draft IDs.
|
|
289
|
+
*
|
|
290
|
+
* Use the public session input facade, which exists before the visual editor
|
|
291
|
+
* mounts. Failures are surfaced to the rewind dialog and refused drafts are released.
|
|
292
|
+
* @param ctx - client context carrying the conversation service.
|
|
293
|
+
* @param sessionId - Session whose composer receives the files.
|
|
294
|
+
* @param attachments - durable references carried by the rewound message.
|
|
295
|
+
* @returns number of attachments actually restored.
|
|
296
|
+
*/
|
|
297
|
+
export declare function restoreComposerAttachments(ctx: ClientContextLike, sessionId: string, attachments: readonly RewindAttachment[], prepared?: readonly PromiseSettledResult<File>[]): Promise<number>;
|
|
298
|
+
/**
|
|
299
|
+
* Open the rewound Session and put the message back into its composer.
|
|
300
|
+
* @param ctx - client context carrying the Session navigation service.
|
|
301
|
+
* @param sessionId - target Session.
|
|
302
|
+
* @param promptText - message text to restore.
|
|
303
|
+
* @param attachments - attachments carried by that message.
|
|
304
|
+
*/
|
|
305
|
+
export declare function openSessionWithDraft(ctx: ClientContextLike, sessionId: string, promptText: string, attachments?: readonly RewindAttachment[]): Promise<void>;
|
|
245
306
|
/**
|
|
246
307
|
* Read one rewind response body without ever leaking a raw parse error.
|
|
247
308
|
*
|
|
@@ -184,6 +184,17 @@ export declare function installRewindHttp(ctx: Context, engine: ChangeLedgerEngi
|
|
|
184
184
|
export declare function createRewindHttpHandler(ctx: ConversationRestartContext & {
|
|
185
185
|
readonly agents?: AgentsLike;
|
|
186
186
|
}, engine: ChangeLedgerEngine, coordinator: TurnCheckpointCoordinator): (request: HttpRequestLike, response: HttpResponseLike) => Promise<void>;
|
|
187
|
+
/** Same-origin route that replays one stored attachment's bytes to the browser. */
|
|
188
|
+
export declare const ATTACHMENT_HTTP_PATH = "/turn-rewind/attachment-bytes";
|
|
189
|
+
/** Register the attachment-bytes route consumed by the rewound composer draft. */
|
|
190
|
+
export declare function installAttachmentHttp(ctx: Context): void;
|
|
191
|
+
/**
|
|
192
|
+
* Build the attachment-bytes route as a testable unit.
|
|
193
|
+
*
|
|
194
|
+
* Bytes travel in a JSON envelope shared by Web and Desktop carriers;
|
|
195
|
+
* the browser rebuilds a `File` from the verified message reference.
|
|
196
|
+
*/
|
|
197
|
+
export declare function createAttachmentHttpHandler(ctx: Pick<Context, 'get' | 'sessions' | 'sessionQuery'>): (request: HttpRequestLike, response: HttpResponseLike) => Promise<void>;
|
|
187
198
|
export declare const MANAGE_HTTP_PATH = "/turn-rewind/manage";
|
|
188
199
|
/** Register the same-origin storage-management endpoint consumed by the settings card. */
|
|
189
200
|
export declare function installManageHttp(ctx: Context, engine: ChangeLedgerEngine): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anionex/dsh-turn-rewind",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.12",
|
|
4
4
|
"description": "Turn-level conversation and workspace rewind for DeepSeek Harness, powered by a persistent Change Ledger",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
]
|
|
64
64
|
},
|
|
65
65
|
"compatibility": {
|
|
66
|
-
"dsh": ">=0.1.0-rc.8 <0.2.0 || ^0.1.7-rc.1 || 0.2.0-rc.2 || 0.2.1-rc.2 || 0.2.1-rc.3",
|
|
66
|
+
"dsh": ">=0.1.0-rc.8 <0.2.0 || ^0.1.7-rc.1 || 0.2.0-rc.2 || 0.2.1-rc.2 || 0.2.1-rc.3 || 0.2.1-rc.5",
|
|
67
67
|
"dshReleases": {
|
|
68
68
|
"0.1.0-rc.8": "compatible",
|
|
69
69
|
"0.1.1-rc.1": "compatible",
|
|
@@ -78,7 +78,8 @@
|
|
|
78
78
|
"0.1.7-rc.2": "compatible",
|
|
79
79
|
"0.2.0-rc.2": "compatible",
|
|
80
80
|
"0.2.1-rc.2": "compatible",
|
|
81
|
-
"0.2.1-rc.3": "compatible"
|
|
81
|
+
"0.2.1-rc.3": "compatible",
|
|
82
|
+
"0.2.1-rc.5": "compatible"
|
|
82
83
|
},
|
|
83
84
|
"profiles": [
|
|
84
85
|
"web"
|
|
@@ -104,7 +105,7 @@
|
|
|
104
105
|
"license": "BSD-3-Clause",
|
|
105
106
|
"peerDependencies": {
|
|
106
107
|
"@deepseek-ai/cordis": "^4.0.1",
|
|
107
|
-
"@deepseek-ai/dsh-settings": "0.2.1-rc.3 || >=0.1.0-rc.8 <0.2.0 || ^0.1.1-rc.1 || ^0.1.2-alpha.1 || ^0.1.5-rc.1 || 0.2.0-rc.2 || 0.2.1-rc.2",
|
|
108
|
+
"@deepseek-ai/dsh-settings": "0.2.1-rc.3 || >=0.1.0-rc.8 <0.2.0 || ^0.1.1-rc.1 || ^0.1.2-alpha.1 || ^0.1.5-rc.1 || 0.2.0-rc.2 || 0.2.1-rc.2 || 0.2.1-rc.5",
|
|
108
109
|
"@deepseek-ai/schemastery": "^3.18.1"
|
|
109
110
|
},
|
|
110
111
|
"peerDependenciesMeta": {
|
package/src/client/index.tsx
CHANGED
|
@@ -6,10 +6,22 @@ import {
|
|
|
6
6
|
Tooltip,
|
|
7
7
|
} from '@deepseek-ai/dsh-client-ui-primitives'
|
|
8
8
|
|
|
9
|
+
/** Durable reference carried by one `image` / `file` content block. */
|
|
10
|
+
interface AttachmentRefLike {
|
|
11
|
+
readonly attachmentId?: string
|
|
12
|
+
readonly name?: string
|
|
13
|
+
readonly mediaType?: string
|
|
14
|
+
readonly bytes?: number
|
|
15
|
+
}
|
|
16
|
+
|
|
9
17
|
interface ConversationNodeLike {
|
|
10
18
|
readonly kind: string
|
|
11
19
|
readonly seq: number
|
|
12
|
-
readonly content?: readonly {
|
|
20
|
+
readonly content?: readonly {
|
|
21
|
+
readonly type: string
|
|
22
|
+
readonly text?: string
|
|
23
|
+
readonly attachment?: AttachmentRefLike
|
|
24
|
+
}[]
|
|
13
25
|
}
|
|
14
26
|
|
|
15
27
|
interface ConversationChatNodeLike {
|
|
@@ -47,20 +59,40 @@ type SnapshotSelectorHook = <T>(selector: (snapshot: ConversationSnapshotLike) =
|
|
|
47
59
|
|
|
48
60
|
type RewindNodeLike = ConversationNodeLike | ConversationChatNodeLike
|
|
49
61
|
|
|
62
|
+
/** One durable attachment that the restart has to hand back to the composer. */
|
|
63
|
+
interface RewindAttachment {
|
|
64
|
+
readonly kind: 'image' | 'file'
|
|
65
|
+
readonly attachmentId: string
|
|
66
|
+
readonly name: string
|
|
67
|
+
readonly mediaType: string
|
|
68
|
+
readonly sourceSessionId?: string
|
|
69
|
+
readonly messageSeq?: number
|
|
70
|
+
}
|
|
71
|
+
|
|
50
72
|
interface RewindMatch {
|
|
51
73
|
readonly messageSeq: number
|
|
52
74
|
readonly promptText: string
|
|
75
|
+
/** Present only when the message carried attachments; absent keeps older doubles valid. */
|
|
76
|
+
readonly attachments?: readonly RewindAttachment[]
|
|
53
77
|
}
|
|
54
78
|
|
|
55
79
|
interface RewindMessageActionProps {
|
|
56
80
|
readonly matched: RewindMatch
|
|
57
81
|
readonly sessionId: string
|
|
58
|
-
readonly openRestoredSession: (
|
|
82
|
+
readonly openRestoredSession: (
|
|
83
|
+
sessionId: string,
|
|
84
|
+
promptText: string,
|
|
85
|
+
attachments?: readonly RewindAttachment[],
|
|
86
|
+
) => Promise<void>
|
|
59
87
|
}
|
|
60
88
|
|
|
61
89
|
interface RewindPortalBridgeProps {
|
|
62
90
|
readonly sessionId: string
|
|
63
|
-
readonly openRestoredSession: (
|
|
91
|
+
readonly openRestoredSession: (
|
|
92
|
+
sessionId: string,
|
|
93
|
+
promptText: string,
|
|
94
|
+
attachments?: readonly RewindAttachment[],
|
|
95
|
+
) => Promise<void>
|
|
64
96
|
readonly useSession: SnapshotSelectorHook
|
|
65
97
|
readonly useChat?: SnapshotSelectorHook
|
|
66
98
|
}
|
|
@@ -105,7 +137,7 @@ interface ClientContextLike {
|
|
|
105
137
|
}
|
|
106
138
|
readonly conversation: {
|
|
107
139
|
readonly input: {
|
|
108
|
-
for(scope: unknown): { setDraft(text: string): void }
|
|
140
|
+
for(scope: unknown): { setDraft(text: string): void; addAttachments?(ids: readonly string[]): boolean; notify?(level: 'info' | 'error', text: string): void }
|
|
109
141
|
}
|
|
110
142
|
}
|
|
111
143
|
get?(name: string): unknown
|
|
@@ -222,6 +254,15 @@ export interface ManageOverview {
|
|
|
222
254
|
|
|
223
255
|
const PATH = '/turn-rewind'
|
|
224
256
|
const MANAGE_PATH = '/turn-rewind/manage'
|
|
257
|
+
/** Same-origin route that replays one stored attachment's bytes. */
|
|
258
|
+
const ATTACHMENT_BYTES_PATH = '/turn-rewind/attachment-bytes'
|
|
259
|
+
|
|
260
|
+
/** One draft descriptor returned by the conversation service. */
|
|
261
|
+
interface DraftAttachmentLike {
|
|
262
|
+
readonly kind?: string
|
|
263
|
+
readonly id: string
|
|
264
|
+
}
|
|
265
|
+
|
|
225
266
|
const STYLE_ID = '@anionex/dsh-turn-rewind'
|
|
226
267
|
const styles = `
|
|
227
268
|
.dcl-rewind-tail{display:inline-flex;align-items:center;align-self:center;order:0;height:24px;margin-left:2px}
|
|
@@ -406,6 +447,7 @@ interface RewindText {
|
|
|
406
447
|
readonly invalidObject: string
|
|
407
448
|
readonly unknownStatus: (status: string) => string
|
|
408
449
|
readonly sessionNotReady: string
|
|
450
|
+
readonly attachmentsFailed: (names: string) => string
|
|
409
451
|
readonly unparsableResponse: (status: string) => string
|
|
410
452
|
readonly requestFailed: (status: string) => string
|
|
411
453
|
readonly emptyResponse: string
|
|
@@ -562,6 +604,7 @@ const ZH: RewindText = {
|
|
|
562
604
|
invalidObject: '服务器返回了无效对象',
|
|
563
605
|
unknownStatus: status => `未知回退状态:${status}`,
|
|
564
606
|
sessionNotReady: '新对话还没有准备好',
|
|
607
|
+
attachmentsFailed: names => `文字已恢复,但以下附件未恢复,请重新添加:${names}`,
|
|
565
608
|
unparsableResponse: status => `回退服务返回了无法解析的内容(HTTP ${status})。`,
|
|
566
609
|
requestFailed: status => `请求失败:${status}`,
|
|
567
610
|
emptyResponse: '回退服务返回了空响应。',
|
|
@@ -729,6 +772,7 @@ const EN: RewindText = {
|
|
|
729
772
|
invalidObject: 'The server returned an invalid object',
|
|
730
773
|
unknownStatus: status => `Unknown rewind status: ${status}`,
|
|
731
774
|
sessionNotReady: 'The new conversation is not ready yet',
|
|
775
|
+
attachmentsFailed: names => `The text was restored, but these attachments need to be added again: ${names}`,
|
|
732
776
|
unparsableResponse: status => `The rewind service returned content that could not be parsed (HTTP ${status}).`,
|
|
733
777
|
requestFailed: status => `Request failed: ${status}`,
|
|
734
778
|
emptyResponse: 'The rewind service returned an empty response.',
|
|
@@ -852,14 +896,43 @@ function hostLocale(ctx: ClientContextLike): string | undefined {
|
|
|
852
896
|
}
|
|
853
897
|
}
|
|
854
898
|
|
|
855
|
-
/** Return the rewind anchor
|
|
899
|
+
/** Return the rewind anchor, editable text, and durable attachments owned by one direct user message. */
|
|
856
900
|
export function selectRewindMessage(node: ConversationNodeLike): RewindMatch | null {
|
|
857
901
|
if (node.kind !== 'user' || !Number.isSafeInteger(node.seq) || node.seq < 0) return null
|
|
858
902
|
const promptText = (node.content ?? [])
|
|
859
903
|
.filter((block): block is { readonly type: string; readonly text: string } => block.type === 'text' && typeof block.text === 'string')
|
|
860
904
|
.map(block => block.text)
|
|
861
905
|
.join('\n')
|
|
862
|
-
|
|
906
|
+
const attachments = selectRewindAttachments(node)
|
|
907
|
+
return attachments.length === 0
|
|
908
|
+
? { messageSeq: node.seq, promptText }
|
|
909
|
+
: { messageSeq: node.seq, promptText, attachments }
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* Collect the durable `image` / `file` references carried by one user message.
|
|
914
|
+
*
|
|
915
|
+
* Keep missing references so restoration can report unavailable attachments.
|
|
916
|
+
* @param node - the direct user-message node the rewind anchors on.
|
|
917
|
+
* @returns attachments in message order; empty when the message has none.
|
|
918
|
+
*/
|
|
919
|
+
export function selectRewindAttachments(node: ConversationNodeLike): readonly RewindAttachment[] {
|
|
920
|
+
const attachments: RewindAttachment[] = []
|
|
921
|
+
for (const block of node.content ?? []) {
|
|
922
|
+
if (block.type !== 'image' && block.type !== 'file') continue
|
|
923
|
+
const attachment = block.attachment
|
|
924
|
+
const fallbackName = block.type === 'image' ? 'image' : 'file'
|
|
925
|
+
const mediaType = typeof attachment?.mediaType === 'string' && attachment.mediaType !== ''
|
|
926
|
+
? attachment.mediaType
|
|
927
|
+
: 'application/octet-stream'
|
|
928
|
+
attachments.push({
|
|
929
|
+
kind: block.type,
|
|
930
|
+
attachmentId: typeof attachment?.attachmentId === 'string' ? attachment.attachmentId : '',
|
|
931
|
+
name: typeof attachment?.name === 'string' && attachment.name !== '' ? attachment.name : fallbackName,
|
|
932
|
+
mediaType,
|
|
933
|
+
})
|
|
934
|
+
}
|
|
935
|
+
return attachments
|
|
863
936
|
}
|
|
864
937
|
|
|
865
938
|
/**
|
|
@@ -887,8 +960,12 @@ export function apply(ctx: ClientContextLike): void {
|
|
|
887
960
|
id: 'turn-rewind-portals',
|
|
888
961
|
order: 100,
|
|
889
962
|
inject: () => ({
|
|
890
|
-
openRestoredSession: async (
|
|
891
|
-
|
|
963
|
+
openRestoredSession: async (
|
|
964
|
+
sessionId: string,
|
|
965
|
+
promptText: string,
|
|
966
|
+
attachments?: readonly RewindAttachment[],
|
|
967
|
+
) => {
|
|
968
|
+
await openSessionWithDraft(ctx, sessionId, promptText, attachments)
|
|
892
969
|
},
|
|
893
970
|
}),
|
|
894
971
|
}, RewindMessagePortals))
|
|
@@ -1146,7 +1223,7 @@ export function RewindMessageAction({ matched, sessionId, openRestoredSession }:
|
|
|
1146
1223
|
const childSessionId = requiredString(result.sessionId, 'sessionId')
|
|
1147
1224
|
setCompleted(t.completedMessages)
|
|
1148
1225
|
try {
|
|
1149
|
-
await openRestoredSession(childSessionId, matched.promptText)
|
|
1226
|
+
await openRestoredSession(childSessionId, matched.promptText, matched.attachments?.map(attachment => ({ ...attachment, sourceSessionId: sessionId, messageSeq: matched.messageSeq })))
|
|
1150
1227
|
setOpen(false)
|
|
1151
1228
|
} catch (navigationError) {
|
|
1152
1229
|
setError(t.openFailed(messageOf(navigationError)))
|
|
@@ -1162,7 +1239,7 @@ export function RewindMessageAction({ matched, sessionId, openRestoredSession }:
|
|
|
1162
1239
|
requiredString(result.rescuePointId, 'rescuePointId')
|
|
1163
1240
|
setCompleted(t.completedBoth)
|
|
1164
1241
|
try {
|
|
1165
|
-
await openRestoredSession(childSessionId, matched.promptText)
|
|
1242
|
+
await openRestoredSession(childSessionId, matched.promptText, matched.attachments?.map(attachment => ({ ...attachment, sourceSessionId: sessionId, messageSeq: matched.messageSeq })))
|
|
1166
1243
|
setOpen(false)
|
|
1167
1244
|
} catch (navigationError) {
|
|
1168
1245
|
setError(t.restoredButOpenFailed(messageOf(navigationError)))
|
|
@@ -1756,6 +1833,23 @@ function collectPortalTargets(nodes: readonly RewindNodeLike[]): readonly Rewind
|
|
|
1756
1833
|
return targets
|
|
1757
1834
|
}
|
|
1758
1835
|
|
|
1836
|
+
/** Compare two attachment lists by identity: order and durable id both matter. */
|
|
1837
|
+
function sameAttachments(
|
|
1838
|
+
left: readonly RewindAttachment[] | undefined,
|
|
1839
|
+
right: readonly RewindAttachment[] | undefined,
|
|
1840
|
+
): boolean {
|
|
1841
|
+
const leftList = left ?? []
|
|
1842
|
+
const rightList = right ?? []
|
|
1843
|
+
return leftList.length === rightList.length && leftList.every((attachment, index) => {
|
|
1844
|
+
const other = rightList[index]
|
|
1845
|
+
return other !== undefined
|
|
1846
|
+
&& attachment.kind === other.kind
|
|
1847
|
+
&& attachment.attachmentId === other.attachmentId
|
|
1848
|
+
&& attachment.name === other.name
|
|
1849
|
+
&& attachment.mediaType === other.mediaType
|
|
1850
|
+
})
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1759
1853
|
function samePortalTargets(
|
|
1760
1854
|
left: readonly RewindPortalTarget[],
|
|
1761
1855
|
right: readonly RewindPortalTarget[],
|
|
@@ -1766,10 +1860,112 @@ function samePortalTargets(
|
|
|
1766
1860
|
&& target.container === other.container
|
|
1767
1861
|
&& target.matched.messageSeq === other.matched.messageSeq
|
|
1768
1862
|
&& target.matched.promptText === other.matched.promptText
|
|
1863
|
+
&& sameAttachments(target.matched.attachments, other.matched.attachments)
|
|
1769
1864
|
})
|
|
1770
1865
|
}
|
|
1771
1866
|
|
|
1772
|
-
|
|
1867
|
+
/**
|
|
1868
|
+
* Re-upload one durable attachment as a fresh draft attachment.
|
|
1869
|
+
*
|
|
1870
|
+
* The stored bytes are read back from the Host, wrapped in a `File`, and handed
|
|
1871
|
+
* to the composer bridge, because the composer only understands browser files.
|
|
1872
|
+
* @param attachment - durable reference taken from the rewound message.
|
|
1873
|
+
* @returns the rebuilt file, or `undefined` when the Host cannot serve it.
|
|
1874
|
+
*/
|
|
1875
|
+
export async function readAttachmentFile(attachment: RewindAttachment): Promise<File> {
|
|
1876
|
+
const query = new URLSearchParams({
|
|
1877
|
+
attachmentId: attachment.attachmentId,
|
|
1878
|
+
kind: attachment.kind,
|
|
1879
|
+
mediaType: attachment.mediaType,
|
|
1880
|
+
sessionId: attachment.sourceSessionId ?? '',
|
|
1881
|
+
messageSeq: String(attachment.messageSeq ?? ''),
|
|
1882
|
+
})
|
|
1883
|
+
const response = await fetch(`${ATTACHMENT_BYTES_PATH}?${query.toString()}`, {
|
|
1884
|
+
headers: { accept: 'application/json' },
|
|
1885
|
+
signal: AbortSignal.timeout(30_000),
|
|
1886
|
+
})
|
|
1887
|
+
const value = await responseJson(response) as { readonly data?: unknown }
|
|
1888
|
+
if (typeof value.data !== 'string') throw new Error(uiText().attachmentsFailed(attachment.name))
|
|
1889
|
+
const binary = atob(value.data)
|
|
1890
|
+
const bytes = new Uint8Array(binary.length)
|
|
1891
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
|
|
1892
|
+
return new File([bytes], attachment.name, { type: attachment.mediaType })
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
/**
|
|
1896
|
+
* Hand a rewound message's attachments back to the composer.
|
|
1897
|
+
*
|
|
1898
|
+
* Draft attachments are browser-owned `File`s with upload receipts, so the
|
|
1899
|
+
* durable references are read back from the Host and registered exactly the way
|
|
1900
|
+
* the composer's own picker does it: `createDrafts` allocates the drafts,
|
|
1901
|
+
* `input.for(scope).addAttachments` adopts their draft IDs.
|
|
1902
|
+
*
|
|
1903
|
+
* Use the public session input facade, which exists before the visual editor
|
|
1904
|
+
* mounts. Failures are surfaced to the rewind dialog and refused drafts are released.
|
|
1905
|
+
* @param ctx - client context carrying the conversation service.
|
|
1906
|
+
* @param sessionId - Session whose composer receives the files.
|
|
1907
|
+
* @param attachments - durable references carried by the rewound message.
|
|
1908
|
+
* @returns number of attachments actually restored.
|
|
1909
|
+
*/
|
|
1910
|
+
export async function restoreComposerAttachments(
|
|
1911
|
+
ctx: ClientContextLike,
|
|
1912
|
+
sessionId: string,
|
|
1913
|
+
attachments: readonly RewindAttachment[],
|
|
1914
|
+
prepared?: readonly PromiseSettledResult<File>[],
|
|
1915
|
+
): Promise<number> {
|
|
1916
|
+
if (attachments.length === 0) return 0
|
|
1917
|
+
const conversation = ctx.conversation as unknown as {
|
|
1918
|
+
createDrafts?(sessionId: string, files: readonly File[]): readonly DraftAttachmentLike[]
|
|
1919
|
+
releaseDraftAttachments?(drafts: readonly DraftAttachmentLike[]): void
|
|
1920
|
+
}
|
|
1921
|
+
const scope = ctx.sessions.scope(sessionId)
|
|
1922
|
+
const input = scope === undefined ? undefined : ctx.conversation.input.for(scope)
|
|
1923
|
+
const failed = (items: readonly RewindAttachment[]) => {
|
|
1924
|
+
const error = new Error(uiText().attachmentsFailed(items.map(item => item.name).join(', ')))
|
|
1925
|
+
// Navigation can unmount the originating dialog; retain the warning in the
|
|
1926
|
+
// destination session's composer instead of relying on that dialog alone.
|
|
1927
|
+
input?.notify?.('error', error.message)
|
|
1928
|
+
return error
|
|
1929
|
+
}
|
|
1930
|
+
if (typeof input?.addAttachments !== 'function' || typeof conversation.createDrafts !== 'function') throw failed(attachments)
|
|
1931
|
+
const results = prepared ?? await Promise.allSettled(attachments.map(readAttachmentFile))
|
|
1932
|
+
const files = results.flatMap(result => result.status === 'fulfilled' ? [result.value] : [])
|
|
1933
|
+
const missing = attachments.filter((_attachment, index) => results[index]?.status !== 'fulfilled')
|
|
1934
|
+
if (files.length === 0) throw failed(attachments)
|
|
1935
|
+
let drafts: readonly DraftAttachmentLike[]
|
|
1936
|
+
try { drafts = conversation.createDrafts(sessionId, files) } catch { throw failed(attachments) }
|
|
1937
|
+
let adopted = false
|
|
1938
|
+
try {
|
|
1939
|
+
adopted = drafts.length === files.length && input.addAttachments(drafts.map(draft => draft.id))
|
|
1940
|
+
} catch {
|
|
1941
|
+
adopted = false
|
|
1942
|
+
}
|
|
1943
|
+
if (!adopted) {
|
|
1944
|
+
// The composer refused the insertion (busy or locked); release the uploads
|
|
1945
|
+
// instead of leaving orphaned drafts behind.
|
|
1946
|
+
conversation.releaseDraftAttachments?.(drafts)
|
|
1947
|
+
throw failed(attachments)
|
|
1948
|
+
}
|
|
1949
|
+
if (missing.length !== 0) throw failed(missing)
|
|
1950
|
+
return drafts.length
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
/**
|
|
1954
|
+
* Open the rewound Session and put the message back into its composer.
|
|
1955
|
+
* @param ctx - client context carrying the Session navigation service.
|
|
1956
|
+
* @param sessionId - target Session.
|
|
1957
|
+
* @param promptText - message text to restore.
|
|
1958
|
+
* @param attachments - attachments carried by that message.
|
|
1959
|
+
*/
|
|
1960
|
+
export async function openSessionWithDraft(
|
|
1961
|
+
ctx: ClientContextLike,
|
|
1962
|
+
sessionId: string,
|
|
1963
|
+
promptText: string,
|
|
1964
|
+
attachments: readonly RewindAttachment[] = [],
|
|
1965
|
+
): Promise<void> {
|
|
1966
|
+
// Read before navigation so the new draft is not submitted while bytes are
|
|
1967
|
+
// still in flight, and never append attachments to a later user message.
|
|
1968
|
+
const prepared = await Promise.allSettled(attachments.map(readAttachmentFile))
|
|
1773
1969
|
if (typeof ctx.sessions.open === 'function') ctx.sessions.open(sessionId)
|
|
1774
1970
|
else {
|
|
1775
1971
|
const navigation = ctx.get?.('uiWorkspace') as { openSession(id: string): void } | undefined
|
|
@@ -1782,10 +1978,12 @@ export async function openSessionWithDraft(ctx: ClientContextLike, sessionId: st
|
|
|
1782
1978
|
const scope = ctx.sessions.scope(sessionId)
|
|
1783
1979
|
if (scope !== undefined) {
|
|
1784
1980
|
ctx.conversation.input.for(scope).setDraft(promptText)
|
|
1981
|
+
await restoreComposerAttachments(ctx, sessionId, attachments, prepared)
|
|
1785
1982
|
return
|
|
1786
1983
|
}
|
|
1787
1984
|
lastError = new Error(uiText().sessionNotReady)
|
|
1788
1985
|
} catch (error) {
|
|
1986
|
+
if (prepared.length !== 0 && ctx.sessions.scope(sessionId) !== undefined) throw error
|
|
1789
1987
|
lastError = error
|
|
1790
1988
|
}
|
|
1791
1989
|
await new Promise<void>(resolve => { setTimeout(resolve, 50) })
|
package/src/index.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { readFileSync } from 'node:fs'
|
|
6
6
|
import type { Context } from '@deepseek-ai/cordis'
|
|
7
7
|
import { ChangeLedgerEngine } from './engine.js'
|
|
8
|
-
import { installManageHttp, installRewindHttp, TurnCheckpointCoordinator } from './rewind-host.js'
|
|
8
|
+
import { installAttachmentHttp, installManageHttp, installRewindHttp, TurnCheckpointCoordinator } from './rewind-host.js'
|
|
9
9
|
import { installTurnRewindSettings, TurnRewindSettingsSchema } from './settings.js'
|
|
10
10
|
import type { ChangeLedgerConfig } from './types.js'
|
|
11
11
|
|
|
@@ -68,6 +68,7 @@ export class ChangeLedgerService {
|
|
|
68
68
|
ctx.inject(['webServer', 'sessions', 'sessionQuery', 'agents'], (scope: Context) => {
|
|
69
69
|
installRewindHttp(scope, this.engine, checkpoints)
|
|
70
70
|
installManageHttp(scope, this.engine)
|
|
71
|
+
installAttachmentHttp(scope)
|
|
71
72
|
})
|
|
72
73
|
installTurnRewindSettings(ctx, normalized, this.engine)
|
|
73
74
|
void this.engine.initialize().then((reconciled) => {
|