@anionex/dsh-turn-rewind 0.3.11 → 0.3.13
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 +20 -0
- package/README.md +7 -2
- package/README.zh.md +6 -1
- package/lib/client.js +342 -13
- package/lib/client.js.map +1 -1
- package/lib/index.js +2 -1
- package/lib/rewind-host.js +187 -0
- package/lib/types/client/index.d.ts +87 -7
- package/lib/types/rewind-host.d.ts +22 -0
- package/package.json +6 -4
- package/src/client/index.tsx +392 -18
- package/src/index.ts +2 -1
- package/src/rewind-host.ts +223 -0
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,21 +59,46 @@ 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: (
|
|
64
|
-
|
|
91
|
+
readonly openRestoredSession: (
|
|
92
|
+
sessionId: string,
|
|
93
|
+
promptText: string,
|
|
94
|
+
attachments?: readonly RewindAttachment[],
|
|
95
|
+
) => Promise<void>
|
|
96
|
+
/**
|
|
97
|
+
* Legacy 0.1.x chat snapshot hooks kept optional for older test doubles and
|
|
98
|
+
* hosts; DSH 0.2.0 stopped injecting them, so the bridge reads the Host turn
|
|
99
|
+
* anchor endpoint instead.
|
|
100
|
+
*/
|
|
101
|
+
readonly useSession?: SnapshotSelectorHook
|
|
65
102
|
readonly useChat?: SnapshotSelectorHook
|
|
66
103
|
}
|
|
67
104
|
|
|
@@ -105,7 +142,7 @@ interface ClientContextLike {
|
|
|
105
142
|
}
|
|
106
143
|
readonly conversation: {
|
|
107
144
|
readonly input: {
|
|
108
|
-
for(scope: unknown): { setDraft(text: string): void }
|
|
145
|
+
for(scope: unknown): { setDraft(text: string): void; addAttachments?(ids: readonly string[]): boolean; notify?(level: 'info' | 'error', text: string): void }
|
|
109
146
|
}
|
|
110
147
|
}
|
|
111
148
|
get?(name: string): unknown
|
|
@@ -222,6 +259,17 @@ export interface ManageOverview {
|
|
|
222
259
|
|
|
223
260
|
const PATH = '/turn-rewind'
|
|
224
261
|
const MANAGE_PATH = '/turn-rewind/manage'
|
|
262
|
+
/** Same-origin route mapping each rendered turn number to its Session user-message seq. */
|
|
263
|
+
const TURNS_PATH = '/turn-rewind/turns'
|
|
264
|
+
/** Same-origin route that replays one stored attachment's bytes. */
|
|
265
|
+
const ATTACHMENT_BYTES_PATH = '/turn-rewind/attachment-bytes'
|
|
266
|
+
|
|
267
|
+
/** One draft descriptor returned by the conversation service. */
|
|
268
|
+
interface DraftAttachmentLike {
|
|
269
|
+
readonly kind?: string
|
|
270
|
+
readonly id: string
|
|
271
|
+
}
|
|
272
|
+
|
|
225
273
|
const STYLE_ID = '@anionex/dsh-turn-rewind'
|
|
226
274
|
const styles = `
|
|
227
275
|
.dcl-rewind-tail{display:inline-flex;align-items:center;align-self:center;order:0;height:24px;margin-left:2px}
|
|
@@ -406,6 +454,7 @@ interface RewindText {
|
|
|
406
454
|
readonly invalidObject: string
|
|
407
455
|
readonly unknownStatus: (status: string) => string
|
|
408
456
|
readonly sessionNotReady: string
|
|
457
|
+
readonly attachmentsFailed: (names: string) => string
|
|
409
458
|
readonly unparsableResponse: (status: string) => string
|
|
410
459
|
readonly requestFailed: (status: string) => string
|
|
411
460
|
readonly emptyResponse: string
|
|
@@ -562,6 +611,7 @@ const ZH: RewindText = {
|
|
|
562
611
|
invalidObject: '服务器返回了无效对象',
|
|
563
612
|
unknownStatus: status => `未知回退状态:${status}`,
|
|
564
613
|
sessionNotReady: '新对话还没有准备好',
|
|
614
|
+
attachmentsFailed: names => `文字已恢复,但以下附件未恢复,请重新添加:${names}`,
|
|
565
615
|
unparsableResponse: status => `回退服务返回了无法解析的内容(HTTP ${status})。`,
|
|
566
616
|
requestFailed: status => `请求失败:${status}`,
|
|
567
617
|
emptyResponse: '回退服务返回了空响应。',
|
|
@@ -729,6 +779,7 @@ const EN: RewindText = {
|
|
|
729
779
|
invalidObject: 'The server returned an invalid object',
|
|
730
780
|
unknownStatus: status => `Unknown rewind status: ${status}`,
|
|
731
781
|
sessionNotReady: 'The new conversation is not ready yet',
|
|
782
|
+
attachmentsFailed: names => `The text was restored, but these attachments need to be added again: ${names}`,
|
|
732
783
|
unparsableResponse: status => `The rewind service returned content that could not be parsed (HTTP ${status}).`,
|
|
733
784
|
requestFailed: status => `Request failed: ${status}`,
|
|
734
785
|
emptyResponse: 'The rewind service returned an empty response.',
|
|
@@ -852,14 +903,43 @@ function hostLocale(ctx: ClientContextLike): string | undefined {
|
|
|
852
903
|
}
|
|
853
904
|
}
|
|
854
905
|
|
|
855
|
-
/** Return the rewind anchor
|
|
906
|
+
/** Return the rewind anchor, editable text, and durable attachments owned by one direct user message. */
|
|
856
907
|
export function selectRewindMessage(node: ConversationNodeLike): RewindMatch | null {
|
|
857
908
|
if (node.kind !== 'user' || !Number.isSafeInteger(node.seq) || node.seq < 0) return null
|
|
858
909
|
const promptText = (node.content ?? [])
|
|
859
910
|
.filter((block): block is { readonly type: string; readonly text: string } => block.type === 'text' && typeof block.text === 'string')
|
|
860
911
|
.map(block => block.text)
|
|
861
912
|
.join('\n')
|
|
862
|
-
|
|
913
|
+
const attachments = selectRewindAttachments(node)
|
|
914
|
+
return attachments.length === 0
|
|
915
|
+
? { messageSeq: node.seq, promptText }
|
|
916
|
+
: { messageSeq: node.seq, promptText, attachments }
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* Collect the durable `image` / `file` references carried by one user message.
|
|
921
|
+
*
|
|
922
|
+
* Keep missing references so restoration can report unavailable attachments.
|
|
923
|
+
* @param node - the direct user-message node the rewind anchors on.
|
|
924
|
+
* @returns attachments in message order; empty when the message has none.
|
|
925
|
+
*/
|
|
926
|
+
export function selectRewindAttachments(node: ConversationNodeLike): readonly RewindAttachment[] {
|
|
927
|
+
const attachments: RewindAttachment[] = []
|
|
928
|
+
for (const block of node.content ?? []) {
|
|
929
|
+
if (block.type !== 'image' && block.type !== 'file') continue
|
|
930
|
+
const attachment = block.attachment
|
|
931
|
+
const fallbackName = block.type === 'image' ? 'image' : 'file'
|
|
932
|
+
const mediaType = typeof attachment?.mediaType === 'string' && attachment.mediaType !== ''
|
|
933
|
+
? attachment.mediaType
|
|
934
|
+
: 'application/octet-stream'
|
|
935
|
+
attachments.push({
|
|
936
|
+
kind: block.type,
|
|
937
|
+
attachmentId: typeof attachment?.attachmentId === 'string' ? attachment.attachmentId : '',
|
|
938
|
+
name: typeof attachment?.name === 'string' && attachment.name !== '' ? attachment.name : fallbackName,
|
|
939
|
+
mediaType,
|
|
940
|
+
})
|
|
941
|
+
}
|
|
942
|
+
return attachments
|
|
863
943
|
}
|
|
864
944
|
|
|
865
945
|
/**
|
|
@@ -887,8 +967,12 @@ export function apply(ctx: ClientContextLike): void {
|
|
|
887
967
|
id: 'turn-rewind-portals',
|
|
888
968
|
order: 100,
|
|
889
969
|
inject: () => ({
|
|
890
|
-
openRestoredSession: async (
|
|
891
|
-
|
|
970
|
+
openRestoredSession: async (
|
|
971
|
+
sessionId: string,
|
|
972
|
+
promptText: string,
|
|
973
|
+
attachments?: readonly RewindAttachment[],
|
|
974
|
+
) => {
|
|
975
|
+
await openSessionWithDraft(ctx, sessionId, promptText, attachments)
|
|
892
976
|
},
|
|
893
977
|
}),
|
|
894
978
|
}, RewindMessagePortals))
|
|
@@ -950,11 +1034,162 @@ export function collectChatNodes(
|
|
|
950
1034
|
return typeof store.values === 'function' ? Array.from(store.values() as Iterable<RewindNodeLike>) : []
|
|
951
1035
|
}
|
|
952
1036
|
|
|
953
|
-
/**
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1037
|
+
/** Read the Host turn anchors that map a rendered `data-chat-turn` row to an event seq. */
|
|
1038
|
+
async function fetchTurnAnchors(sessionId: string, signal: AbortSignal): Promise<ReadonlyMap<number, RewindMatch>> {
|
|
1039
|
+
const query = new URLSearchParams({ sessionId })
|
|
1040
|
+
const response = await fetch(`${TURNS_PATH}?${query.toString()}`, {
|
|
1041
|
+
headers: { accept: 'application/json' },
|
|
1042
|
+
cache: 'no-store',
|
|
1043
|
+
signal,
|
|
1044
|
+
})
|
|
1045
|
+
if (!response.ok) return new Map()
|
|
1046
|
+
return parseTurnAnchors(await response.json() as unknown)
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** Narrow the turn-anchor payload into per-turn {@link RewindMatch} entries. */
|
|
1050
|
+
function parseTurnAnchors(body: unknown): ReadonlyMap<number, RewindMatch> {
|
|
1051
|
+
const anchors = new Map<number, RewindMatch>()
|
|
1052
|
+
if (body === null || typeof body !== 'object') return anchors
|
|
1053
|
+
const turns = (body as { turns?: unknown }).turns
|
|
1054
|
+
if (!Array.isArray(turns)) return anchors
|
|
1055
|
+
for (const value of turns) {
|
|
1056
|
+
if (value === null || typeof value !== 'object') continue
|
|
1057
|
+
const record = value as Record<string, unknown>
|
|
1058
|
+
const turn = record.turn
|
|
1059
|
+
const userSeq = record.userSeq
|
|
1060
|
+
if (!Number.isSafeInteger(turn) || !Number.isSafeInteger(userSeq)) continue
|
|
1061
|
+
const promptText = typeof record.promptText === 'string' ? record.promptText : ''
|
|
1062
|
+
const attachments = parseTurnAttachments(record.attachments)
|
|
1063
|
+
anchors.set(turn as number, {
|
|
1064
|
+
messageSeq: userSeq as number,
|
|
1065
|
+
promptText,
|
|
1066
|
+
...(attachments.length === 0 ? {} : { attachments }),
|
|
1067
|
+
})
|
|
1068
|
+
}
|
|
1069
|
+
return anchors
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/** Narrow one Host attachment reference; malformed entries are dropped. */
|
|
1073
|
+
function parseTurnAttachments(value: unknown): readonly RewindAttachment[] {
|
|
1074
|
+
if (!Array.isArray(value)) return []
|
|
1075
|
+
const attachments: RewindAttachment[] = []
|
|
1076
|
+
for (const item of value) {
|
|
1077
|
+
if (item === null || typeof item !== 'object') continue
|
|
1078
|
+
const record = item as Record<string, unknown>
|
|
1079
|
+
if (record.kind !== 'image' && record.kind !== 'file') continue
|
|
1080
|
+
const kind = record.kind
|
|
1081
|
+
attachments.push({
|
|
1082
|
+
kind,
|
|
1083
|
+
attachmentId: typeof record.attachmentId === 'string' ? record.attachmentId : '',
|
|
1084
|
+
name: typeof record.name === 'string' && record.name !== '' ? record.name : kind,
|
|
1085
|
+
mediaType: typeof record.mediaType === 'string' && record.mediaType !== '' ? record.mediaType : 'application/octet-stream',
|
|
1086
|
+
})
|
|
1087
|
+
}
|
|
1088
|
+
return attachments
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/**
|
|
1092
|
+
* Map every rendered user-message row onto its Host turn anchor.
|
|
1093
|
+
*
|
|
1094
|
+
* DSH 0.2.x flow rows carry `data-chat-flow-kind="user"` and `data-chat-turn` but
|
|
1095
|
+
* no event seq; the Host endpoint supplies the seq and the message text the
|
|
1096
|
+
* restart dialog needs. Duplicate grouped rows keep the first portal target.
|
|
1097
|
+
* @param anchors - per-turn rewind matches loaded from the Host.
|
|
1098
|
+
* @returns one portal target per direct user message, in document order.
|
|
1099
|
+
*/
|
|
1100
|
+
function sessionRows(sessionId: string): HTMLElement[] {
|
|
1101
|
+
return Array.from(document.querySelectorAll<HTMLElement>('[data-conversation-session]'))
|
|
1102
|
+
.filter(root => root.dataset.conversationSession === sessionId)
|
|
1103
|
+
.flatMap(root => Array.from(root.querySelectorAll<HTMLElement>('[data-chat-flow-kind="user"][data-chat-turn]')))
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
function collectDomPortalTargets(anchors: ReadonlyMap<number, RewindMatch>, sessionId: string): readonly RewindPortalTarget[] {
|
|
1107
|
+
if (anchors.size === 0) return []
|
|
1108
|
+
const targets: RewindPortalTarget[] = []
|
|
1109
|
+
const seen = new Set<number>()
|
|
1110
|
+
for (const row of sessionRows(sessionId)) {
|
|
1111
|
+
const turn = Number(row.dataset.chatTurn)
|
|
1112
|
+
if (!Number.isSafeInteger(turn)) continue
|
|
1113
|
+
const matched = anchors.get(turn)
|
|
1114
|
+
if (matched === undefined || seen.has(matched.messageSeq)) continue
|
|
1115
|
+
const actions = findActionsContainer(row)
|
|
1116
|
+
if (!(actions instanceof HTMLElement)) continue
|
|
1117
|
+
seen.add(matched.messageSeq)
|
|
1118
|
+
targets.push({ container: actions, matched })
|
|
1119
|
+
}
|
|
1120
|
+
return targets
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/** 0.2.x bridge: rendered DOM rows matched through Host-provided turn anchors. */
|
|
1124
|
+
function DomRewindMessagePortals({ sessionId, openRestoredSession }: RewindPortalBridgeProps): ReactNode {
|
|
1125
|
+
const [targets, setTargets] = useState<readonly RewindPortalTarget[]>([])
|
|
1126
|
+
const anchors = useRef<ReadonlyMap<number, RewindMatch>>(new Map())
|
|
1127
|
+
|
|
1128
|
+
useLayoutEffect(() => {
|
|
1129
|
+
let active = true
|
|
1130
|
+
let queued = false
|
|
1131
|
+
let loading = false
|
|
1132
|
+
let retry: ReturnType<typeof setTimeout> | undefined
|
|
1133
|
+
const controller = new AbortController()
|
|
1134
|
+
anchors.current = new Map()
|
|
1135
|
+
const refresh = (): void => {
|
|
1136
|
+
if (!active) return
|
|
1137
|
+
const next = collectDomPortalTargets(anchors.current, sessionId)
|
|
1138
|
+
setTargets(current => samePortalTargets(current, next) ? current : next)
|
|
1139
|
+
const missing = sessionRows(sessionId).some(row => Number.isSafeInteger(Number(row.dataset.chatTurn)) && !anchors.current.has(Number(row.dataset.chatTurn)))
|
|
1140
|
+
if (missing && !loading && retry === undefined) void load()
|
|
1141
|
+
}
|
|
1142
|
+
const queueRefresh = (): void => {
|
|
1143
|
+
if (queued || !active) return
|
|
1144
|
+
queued = true
|
|
1145
|
+
queueMicrotask(() => {
|
|
1146
|
+
queued = false
|
|
1147
|
+
refresh()
|
|
1148
|
+
})
|
|
1149
|
+
}
|
|
1150
|
+
const load = async (): Promise<void> => {
|
|
1151
|
+
if (!active || loading) return
|
|
1152
|
+
loading = true
|
|
1153
|
+
try {
|
|
1154
|
+
const loaded = await fetchTurnAnchors(sessionId, controller.signal)
|
|
1155
|
+
if (!active) return
|
|
1156
|
+
anchors.current = loaded
|
|
1157
|
+
} catch {
|
|
1158
|
+
// A transient failure is retried only while a rendered turn lacks an anchor.
|
|
1159
|
+
} finally {
|
|
1160
|
+
loading = false
|
|
1161
|
+
if (active) {
|
|
1162
|
+
// Bound retries when the DOM precedes persistence, and avoid fetching
|
|
1163
|
+
// again for every streamed token or portal insertion.
|
|
1164
|
+
retry = setTimeout(() => {
|
|
1165
|
+
retry = undefined
|
|
1166
|
+
queueRefresh()
|
|
1167
|
+
}, 1000)
|
|
1168
|
+
queueRefresh()
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
void load()
|
|
1173
|
+
refresh()
|
|
1174
|
+
const observer = new MutationObserver(queueRefresh)
|
|
1175
|
+
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-chat-turn'] })
|
|
1176
|
+
return () => {
|
|
1177
|
+
active = false
|
|
1178
|
+
controller.abort()
|
|
1179
|
+
clearTimeout(retry)
|
|
1180
|
+
observer.disconnect()
|
|
1181
|
+
}
|
|
1182
|
+
}, [sessionId])
|
|
1183
|
+
|
|
1184
|
+
return targets.map(target => createPortal(
|
|
1185
|
+
<RewindMessageAction matched={target.matched} sessionId={sessionId} openRestoredSession={openRestoredSession} />,
|
|
1186
|
+
target.container,
|
|
1187
|
+
`${sessionId}:${String(target.matched.messageSeq)}`,
|
|
1188
|
+
))
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
/** Legacy bridge for 0.1.x hosts that still inject a chat snapshot hook. */
|
|
1192
|
+
function LegacyRewindMessagePortals({ sessionId, openRestoredSession, readSnapshot }: RewindPortalBridgeProps & { readonly readSnapshot: SnapshotSelectorHook }): ReactNode {
|
|
958
1193
|
const chatOf = (snapshot: ConversationSnapshotLike): ChatSnapshotLike => snapshot.chat ?? snapshot
|
|
959
1194
|
const chatOrder = readSnapshot<readonly string[] | null>(snapshot => chatOf(snapshot).order ?? null)
|
|
960
1195
|
const chatStore = readSnapshot<ChatNodeStoreLike | readonly RewindNodeLike[] | null>(
|
|
@@ -995,6 +1230,20 @@ export function RewindMessagePortals({ sessionId, openRestoredSession, useSessio
|
|
|
995
1230
|
))
|
|
996
1231
|
}
|
|
997
1232
|
|
|
1233
|
+
/**
|
|
1234
|
+
* Session-scoped bridge that portals rewind controls into direct user-message action rows.
|
|
1235
|
+
*
|
|
1236
|
+
* DSH 0.1.x passes chat snapshot hooks; DSH 0.2.0 stopped injecting them, so the
|
|
1237
|
+
* bridge falls back to DOM rows plus the Host turn-anchor endpoint.
|
|
1238
|
+
*/
|
|
1239
|
+
export function RewindMessagePortals(props: RewindPortalBridgeProps): ReactNode {
|
|
1240
|
+
const readSnapshot = props.useChat ?? props.useSession
|
|
1241
|
+
if (readSnapshot === undefined) {
|
|
1242
|
+
return <DomRewindMessagePortals key={props.sessionId} sessionId={props.sessionId} openRestoredSession={props.openRestoredSession} />
|
|
1243
|
+
}
|
|
1244
|
+
return <LegacyRewindMessagePortals {...props} readSnapshot={readSnapshot} />
|
|
1245
|
+
}
|
|
1246
|
+
|
|
998
1247
|
/** User-message action and its review-first file/conversation restore dialog. */
|
|
999
1248
|
export function RewindMessageAction({ matched, sessionId, openRestoredSession }: RewindMessageActionProps): ReactNode {
|
|
1000
1249
|
const t = useText()
|
|
@@ -1146,7 +1395,7 @@ export function RewindMessageAction({ matched, sessionId, openRestoredSession }:
|
|
|
1146
1395
|
const childSessionId = requiredString(result.sessionId, 'sessionId')
|
|
1147
1396
|
setCompleted(t.completedMessages)
|
|
1148
1397
|
try {
|
|
1149
|
-
await openRestoredSession(childSessionId, matched.promptText)
|
|
1398
|
+
await openRestoredSession(childSessionId, matched.promptText, matched.attachments?.map(attachment => ({ ...attachment, sourceSessionId: sessionId, messageSeq: matched.messageSeq })))
|
|
1150
1399
|
setOpen(false)
|
|
1151
1400
|
} catch (navigationError) {
|
|
1152
1401
|
setError(t.openFailed(messageOf(navigationError)))
|
|
@@ -1162,7 +1411,7 @@ export function RewindMessageAction({ matched, sessionId, openRestoredSession }:
|
|
|
1162
1411
|
requiredString(result.rescuePointId, 'rescuePointId')
|
|
1163
1412
|
setCompleted(t.completedBoth)
|
|
1164
1413
|
try {
|
|
1165
|
-
await openRestoredSession(childSessionId, matched.promptText)
|
|
1414
|
+
await openRestoredSession(childSessionId, matched.promptText, matched.attachments?.map(attachment => ({ ...attachment, sourceSessionId: sessionId, messageSeq: matched.messageSeq })))
|
|
1166
1415
|
setOpen(false)
|
|
1167
1416
|
} catch (navigationError) {
|
|
1168
1417
|
setError(t.restoredButOpenFailed(messageOf(navigationError)))
|
|
@@ -1736,7 +1985,11 @@ function findActionsContainer(row: Element): Element | null {
|
|
|
1736
1985
|
return queryInside(legacy, ACTIONS_SELECTOR) ?? legacy.lastElementChild
|
|
1737
1986
|
}
|
|
1738
1987
|
|
|
1739
|
-
|
|
1988
|
+
/**
|
|
1989
|
+
* Legacy chat-snapshot bridge kept for 0.1.x hosts and test doubles.
|
|
1990
|
+
* DSH 0.2.0 uses {@link collectDomPortalTargets} instead.
|
|
1991
|
+
*/
|
|
1992
|
+
export function collectPortalTargets(nodes: readonly RewindNodeLike[]): readonly RewindPortalTarget[] {
|
|
1740
1993
|
const rows = new Map<string, HTMLElement>()
|
|
1741
1994
|
for (const element of Array.from(document.querySelectorAll<HTMLElement>(
|
|
1742
1995
|
'[data-chat-flow-kind="user"][data-chat-anchor-key]',
|
|
@@ -1756,6 +2009,23 @@ function collectPortalTargets(nodes: readonly RewindNodeLike[]): readonly Rewind
|
|
|
1756
2009
|
return targets
|
|
1757
2010
|
}
|
|
1758
2011
|
|
|
2012
|
+
/** Compare two attachment lists by identity: order and durable id both matter. */
|
|
2013
|
+
function sameAttachments(
|
|
2014
|
+
left: readonly RewindAttachment[] | undefined,
|
|
2015
|
+
right: readonly RewindAttachment[] | undefined,
|
|
2016
|
+
): boolean {
|
|
2017
|
+
const leftList = left ?? []
|
|
2018
|
+
const rightList = right ?? []
|
|
2019
|
+
return leftList.length === rightList.length && leftList.every((attachment, index) => {
|
|
2020
|
+
const other = rightList[index]
|
|
2021
|
+
return other !== undefined
|
|
2022
|
+
&& attachment.kind === other.kind
|
|
2023
|
+
&& attachment.attachmentId === other.attachmentId
|
|
2024
|
+
&& attachment.name === other.name
|
|
2025
|
+
&& attachment.mediaType === other.mediaType
|
|
2026
|
+
})
|
|
2027
|
+
}
|
|
2028
|
+
|
|
1759
2029
|
function samePortalTargets(
|
|
1760
2030
|
left: readonly RewindPortalTarget[],
|
|
1761
2031
|
right: readonly RewindPortalTarget[],
|
|
@@ -1766,10 +2036,112 @@ function samePortalTargets(
|
|
|
1766
2036
|
&& target.container === other.container
|
|
1767
2037
|
&& target.matched.messageSeq === other.matched.messageSeq
|
|
1768
2038
|
&& target.matched.promptText === other.matched.promptText
|
|
2039
|
+
&& sameAttachments(target.matched.attachments, other.matched.attachments)
|
|
1769
2040
|
})
|
|
1770
2041
|
}
|
|
1771
2042
|
|
|
1772
|
-
|
|
2043
|
+
/**
|
|
2044
|
+
* Re-upload one durable attachment as a fresh draft attachment.
|
|
2045
|
+
*
|
|
2046
|
+
* The stored bytes are read back from the Host, wrapped in a `File`, and handed
|
|
2047
|
+
* to the composer bridge, because the composer only understands browser files.
|
|
2048
|
+
* @param attachment - durable reference taken from the rewound message.
|
|
2049
|
+
* @returns the rebuilt file, or `undefined` when the Host cannot serve it.
|
|
2050
|
+
*/
|
|
2051
|
+
export async function readAttachmentFile(attachment: RewindAttachment): Promise<File> {
|
|
2052
|
+
const query = new URLSearchParams({
|
|
2053
|
+
attachmentId: attachment.attachmentId,
|
|
2054
|
+
kind: attachment.kind,
|
|
2055
|
+
mediaType: attachment.mediaType,
|
|
2056
|
+
sessionId: attachment.sourceSessionId ?? '',
|
|
2057
|
+
messageSeq: String(attachment.messageSeq ?? ''),
|
|
2058
|
+
})
|
|
2059
|
+
const response = await fetch(`${ATTACHMENT_BYTES_PATH}?${query.toString()}`, {
|
|
2060
|
+
headers: { accept: 'application/json' },
|
|
2061
|
+
signal: AbortSignal.timeout(30_000),
|
|
2062
|
+
})
|
|
2063
|
+
const value = await responseJson(response) as { readonly data?: unknown }
|
|
2064
|
+
if (typeof value.data !== 'string') throw new Error(uiText().attachmentsFailed(attachment.name))
|
|
2065
|
+
const binary = atob(value.data)
|
|
2066
|
+
const bytes = new Uint8Array(binary.length)
|
|
2067
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
|
|
2068
|
+
return new File([bytes], attachment.name, { type: attachment.mediaType })
|
|
2069
|
+
}
|
|
2070
|
+
|
|
2071
|
+
/**
|
|
2072
|
+
* Hand a rewound message's attachments back to the composer.
|
|
2073
|
+
*
|
|
2074
|
+
* Draft attachments are browser-owned `File`s with upload receipts, so the
|
|
2075
|
+
* durable references are read back from the Host and registered exactly the way
|
|
2076
|
+
* the composer's own picker does it: `createDrafts` allocates the drafts,
|
|
2077
|
+
* `input.for(scope).addAttachments` adopts their draft IDs.
|
|
2078
|
+
*
|
|
2079
|
+
* Use the public session input facade, which exists before the visual editor
|
|
2080
|
+
* mounts. Failures are surfaced to the rewind dialog and refused drafts are released.
|
|
2081
|
+
* @param ctx - client context carrying the conversation service.
|
|
2082
|
+
* @param sessionId - Session whose composer receives the files.
|
|
2083
|
+
* @param attachments - durable references carried by the rewound message.
|
|
2084
|
+
* @returns number of attachments actually restored.
|
|
2085
|
+
*/
|
|
2086
|
+
export async function restoreComposerAttachments(
|
|
2087
|
+
ctx: ClientContextLike,
|
|
2088
|
+
sessionId: string,
|
|
2089
|
+
attachments: readonly RewindAttachment[],
|
|
2090
|
+
prepared?: readonly PromiseSettledResult<File>[],
|
|
2091
|
+
): Promise<number> {
|
|
2092
|
+
if (attachments.length === 0) return 0
|
|
2093
|
+
const conversation = ctx.conversation as unknown as {
|
|
2094
|
+
createDrafts?(sessionId: string, files: readonly File[]): readonly DraftAttachmentLike[]
|
|
2095
|
+
releaseDraftAttachments?(drafts: readonly DraftAttachmentLike[]): void
|
|
2096
|
+
}
|
|
2097
|
+
const scope = ctx.sessions.scope(sessionId)
|
|
2098
|
+
const input = scope === undefined ? undefined : ctx.conversation.input.for(scope)
|
|
2099
|
+
const failed = (items: readonly RewindAttachment[]) => {
|
|
2100
|
+
const error = new Error(uiText().attachmentsFailed(items.map(item => item.name).join(', ')))
|
|
2101
|
+
// Navigation can unmount the originating dialog; retain the warning in the
|
|
2102
|
+
// destination session's composer instead of relying on that dialog alone.
|
|
2103
|
+
input?.notify?.('error', error.message)
|
|
2104
|
+
return error
|
|
2105
|
+
}
|
|
2106
|
+
if (typeof input?.addAttachments !== 'function' || typeof conversation.createDrafts !== 'function') throw failed(attachments)
|
|
2107
|
+
const results = prepared ?? await Promise.allSettled(attachments.map(readAttachmentFile))
|
|
2108
|
+
const files = results.flatMap(result => result.status === 'fulfilled' ? [result.value] : [])
|
|
2109
|
+
const missing = attachments.filter((_attachment, index) => results[index]?.status !== 'fulfilled')
|
|
2110
|
+
if (files.length === 0) throw failed(attachments)
|
|
2111
|
+
let drafts: readonly DraftAttachmentLike[]
|
|
2112
|
+
try { drafts = conversation.createDrafts(sessionId, files) } catch { throw failed(attachments) }
|
|
2113
|
+
let adopted = false
|
|
2114
|
+
try {
|
|
2115
|
+
adopted = drafts.length === files.length && input.addAttachments(drafts.map(draft => draft.id))
|
|
2116
|
+
} catch {
|
|
2117
|
+
adopted = false
|
|
2118
|
+
}
|
|
2119
|
+
if (!adopted) {
|
|
2120
|
+
// The composer refused the insertion (busy or locked); release the uploads
|
|
2121
|
+
// instead of leaving orphaned drafts behind.
|
|
2122
|
+
conversation.releaseDraftAttachments?.(drafts)
|
|
2123
|
+
throw failed(attachments)
|
|
2124
|
+
}
|
|
2125
|
+
if (missing.length !== 0) throw failed(missing)
|
|
2126
|
+
return drafts.length
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
/**
|
|
2130
|
+
* Open the rewound Session and put the message back into its composer.
|
|
2131
|
+
* @param ctx - client context carrying the Session navigation service.
|
|
2132
|
+
* @param sessionId - target Session.
|
|
2133
|
+
* @param promptText - message text to restore.
|
|
2134
|
+
* @param attachments - attachments carried by that message.
|
|
2135
|
+
*/
|
|
2136
|
+
export async function openSessionWithDraft(
|
|
2137
|
+
ctx: ClientContextLike,
|
|
2138
|
+
sessionId: string,
|
|
2139
|
+
promptText: string,
|
|
2140
|
+
attachments: readonly RewindAttachment[] = [],
|
|
2141
|
+
): Promise<void> {
|
|
2142
|
+
// Read before navigation so the new draft is not submitted while bytes are
|
|
2143
|
+
// still in flight, and never append attachments to a later user message.
|
|
2144
|
+
const prepared = await Promise.allSettled(attachments.map(readAttachmentFile))
|
|
1773
2145
|
if (typeof ctx.sessions.open === 'function') ctx.sessions.open(sessionId)
|
|
1774
2146
|
else {
|
|
1775
2147
|
const navigation = ctx.get?.('uiWorkspace') as { openSession(id: string): void } | undefined
|
|
@@ -1782,10 +2154,12 @@ export async function openSessionWithDraft(ctx: ClientContextLike, sessionId: st
|
|
|
1782
2154
|
const scope = ctx.sessions.scope(sessionId)
|
|
1783
2155
|
if (scope !== undefined) {
|
|
1784
2156
|
ctx.conversation.input.for(scope).setDraft(promptText)
|
|
2157
|
+
await restoreComposerAttachments(ctx, sessionId, attachments, prepared)
|
|
1785
2158
|
return
|
|
1786
2159
|
}
|
|
1787
2160
|
lastError = new Error(uiText().sessionNotReady)
|
|
1788
2161
|
} catch (error) {
|
|
2162
|
+
if (prepared.length !== 0 && ctx.sessions.scope(sessionId) !== undefined) throw error
|
|
1789
2163
|
lastError = error
|
|
1790
2164
|
}
|
|
1791
2165
|
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) => {
|