-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathchatHistory.ts
More file actions
586 lines (531 loc) · 17.3 KB
/
Copy pathchatHistory.ts
File metadata and controls
586 lines (531 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
import type { Message } from "@earendil-works/pi-ai";
import { invoke } from "@tauri-apps/api/core";
import { normalizeConversationSystemPrompt } from "../context/systemPrompt";
import {
type ConversationViewState,
createTranscriptProjection,
getActiveSegment,
type HistoryMessageRef,
normalizeConversationState,
type StoredChatContextMeta,
type StoredContextSegment,
type StoredSummaryMessage,
type TranscriptSegmentSlice,
} from "../conversation/conversationState";
import { parseHistorySegments, type SerializedHistorySegment } from "./chatHistoryParser";
// Single window/page size for every windowed history read (open, load
// earlier, edit-resend replace) — one contract, one constant.
export const CHAT_HISTORY_WINDOW_MESSAGES = 360;
export type ChatHistorySummary = {
id: string;
title: string;
providerId: string;
model: string;
sessionId?: string;
cwd?: string;
selectedModelJson?: string;
messageCount?: number;
createdAt: number;
updatedAt: number;
isPinned?: boolean;
pinnedAt?: number | null;
isShared?: boolean;
isPending?: boolean;
};
export type ChatHistoryShareStatus = {
conversationId: string;
enabled: boolean;
token?: string;
createdAt?: number;
updatedAt?: number;
redactToolContent?: boolean;
};
export type ChatHistoryListPage = {
items: ChatHistorySummary[];
totalCount: number;
};
export type ChatHistoryListFilter = {
cwd?: string;
cwdEmpty?: boolean;
};
export type ChatHistoryWorkdirSummary = {
path: string;
conversationCount: number;
updatedAt: number;
};
export type ChatHistoryWorkdirsResponse = {
workdirs: ChatHistoryWorkdirSummary[];
};
type ChatHistorySegmentWireRecord = {
segmentIndex: number;
segmentId: string;
summaryJson?: string | null;
messagesJson: string;
messageCount: number;
startMessageId?: string;
endMessageId?: string;
createdAt: number;
updatedAt: number;
};
type ChatHistorySegmentWindowWireRecord = {
segmentIndex: number;
segmentId: string;
summaryJson?: string | null;
messagesJson: string;
startMessageIndex: number;
messageCount: number;
createdAt: number;
updatedAt: number;
};
type ActiveSegmentParserPayload = {
kind: "active";
record: Omit<ChatHistorySegmentWireRecord, "summaryJson" | "messagesJson">;
};
type WindowSegmentParserPayload = {
kind: "window";
record: Omit<ChatHistorySegmentWindowWireRecord, "summaryJson" | "messagesJson">;
};
type HistorySegmentParserPayload = ActiveSegmentParserPayload | WindowSegmentParserPayload;
type ChatHistoryWindowWireRecord = {
conversation: ChatHistorySummary;
segments: ChatHistorySegmentWindowWireRecord[];
activeSegment: ChatHistorySegmentWireRecord | null;
contextMetaJson: string;
activeSegmentIndex: number;
totalSegmentCount: number;
totalMessageCount: number;
returnedMessageCount: number;
oldestOffset: number;
hasMoreBefore: boolean;
revision: string;
updatedAt: number;
};
export type ChatHistoryWindowRecord = {
conversation: ChatHistorySummary;
meta: StoredChatContextMeta;
segments: TranscriptSegmentSlice[];
activeSegment?: StoredContextSegment;
returnedMessageCount: number;
oldestOffset: number;
hasMoreBefore: boolean;
revision: string;
updatedAt: number;
};
export type ConversationPersistenceCursor = {
activeSegmentIndex: number;
activeSegmentId: string;
};
// Shared assembly for a full window record → runtime view state: the active
// segment becomes the (only) runtime segment, the window's segment slices
// become the transcript projection. Used by open, gateway-bridge readiness
// and edit-resend replace.
export function buildConversationStateFromWindow(
record: ChatHistoryWindowRecord,
): ConversationViewState {
if (!record.activeSegment) throw new Error("历史窗口缺少活跃分段");
return normalizeConversationState({
meta: record.meta,
segments: [record.activeSegment],
transcript: createTranscriptProjection({
segments: record.segments,
activeSegmentIndex: record.meta.activeSegmentIndex,
oldestMessageOffset: record.oldestOffset,
hasMoreBefore: record.hasMoreBefore,
revision: record.revision,
}),
});
}
export function buildChatHistoryRevision(params: {
conversationId: string;
updatedAt: number;
activeSegmentIndex: number;
totalSegmentCount: number;
totalMessageCount: number;
}) {
return `${params.conversationId.trim()}:${params.updatedAt}:${params.activeSegmentIndex}:${params.totalSegmentCount}:${params.totalMessageCount}`;
}
const conversationWriteQueues = new Map<string, Promise<void>>();
type ChatHistoryUpsertInput = {
id: string;
title: string;
providerId: string;
model: string;
sessionId?: string;
cwd?: string;
selectedModelJson?: string;
contextMetaJson: string;
activeSegmentIndex: number;
totalSegmentCount: number;
totalMessageCount: number;
segments: ChatHistorySegmentWireRecord[];
createdAt?: number;
updatedAt: number;
};
type ChatHistoryConversationInput = Omit<ChatHistoryUpsertInput, "segments">;
type ChatHistorySegmentMutationInput = {
conversation: ChatHistoryConversationInput;
segment: ChatHistorySegmentWireRecord;
};
function normalizeStoredSummaryMessage(parsed: unknown): StoredSummaryMessage {
if (
!parsed ||
typeof parsed !== "object" ||
!("role" in parsed) ||
!("id" in parsed) ||
!("content" in parsed) ||
!("timestamp" in parsed) ||
!("summaryMeta" in parsed) ||
parsed.role !== "summary" ||
typeof parsed.id !== "string" ||
typeof parsed.content !== "string" ||
typeof parsed.timestamp !== "number" ||
!parsed.summaryMeta ||
typeof parsed.summaryMeta !== "object"
) {
throw new Error("历史摘要数据格式无效");
}
return parsed as StoredSummaryMessage;
}
function parseStoredChatContextMeta(
raw: string,
counts: Pick<
StoredChatContextMeta,
"activeSegmentIndex" | "totalSegmentCount" | "totalMessageCount"
>,
fallbackSystemPrompt?: string,
): StoredChatContextMeta {
const parsed = JSON.parse(raw) as Partial<StoredChatContextMeta> | null;
if (!parsed || typeof parsed !== "object") {
throw new Error("历史上下文元数据格式无效");
}
const systemPrompt = normalizeConversationSystemPrompt(
typeof parsed.systemPrompt === "string" ? parsed.systemPrompt : fallbackSystemPrompt,
);
return {
schemaVersion: 3,
systemPrompt,
tools: Array.isArray(parsed.tools) ? parsed.tools : undefined,
activeSegmentIndex: counts.activeSegmentIndex,
totalSegmentCount: counts.totalSegmentCount,
totalMessageCount: counts.totalMessageCount,
};
}
export async function listChatHistory(
page: number,
pageSize: number,
filter?: ChatHistoryListFilter,
) {
return invoke<ChatHistoryListPage>("chat_history_list", {
page,
pageSize,
cwd: filter?.cwd,
cwdEmpty: filter?.cwdEmpty,
});
}
export async function listChatHistoryWorkdirs() {
return invoke<ChatHistoryWorkdirsResponse>("chat_history_workdirs");
}
export async function listSharedChatHistory(page: number, pageSize: number) {
return invoke<ChatHistoryListPage>("chat_history_shared_list", { page, pageSize });
}
export async function getChatHistoryWindow(params: {
id: string;
maxMessages: number;
beforeOffset?: number;
expectedRevision?: string;
includeActiveSegment: boolean;
fallbackSystemPrompt?: string;
}): Promise<ChatHistoryWindowRecord> {
const record = await invoke<ChatHistoryWindowWireRecord>("chat_history_get_window", {
id: params.id,
maxMessages: params.maxMessages,
beforeOffset: params.beforeOffset,
expectedRevision: params.expectedRevision,
includeActiveSegment: params.includeActiveSegment,
});
const parsed = await parseChatHistoryWindowRecord(record, params.fallbackSystemPrompt);
if (params.includeActiveSegment && !parsed.activeSegment) {
throw new Error("历史窗口缺少活跃分段");
}
return parsed;
}
async function parseChatHistoryWindowRecord(
record: ChatHistoryWindowWireRecord,
fallbackSystemPrompt?: string,
): Promise<ChatHistoryWindowRecord> {
const activeSerialized: SerializedHistorySegment<HistorySegmentParserPayload>[] =
record.activeSegment
? (() => {
const { summaryJson, messagesJson, ...payload } = record.activeSegment;
return [
{
payload: { kind: "active", record: payload },
summaryJson,
messagesJson,
},
];
})()
: [];
const serializedSegments: SerializedHistorySegment<HistorySegmentParserPayload>[] = [
...activeSerialized,
...record.segments.map(({ summaryJson, messagesJson, ...payload }) => ({
payload: { kind: "window", record: payload } satisfies WindowSegmentParserPayload,
summaryJson,
messagesJson,
})),
];
const parsedSegments = await parseHistorySegments(serializedSegments);
const activeSegment = parsedSegments.find((segment) => segment.payload.kind === "active");
return {
conversation: record.conversation,
meta: parseStoredChatContextMeta(record.contextMetaJson, record, fallbackSystemPrompt),
segments: parsedSegments.flatMap(({ payload, summary, messages }) =>
payload.kind === "window"
? [
{
segmentIndex: payload.record.segmentIndex,
segmentId: payload.record.segmentId,
summary: summary ? normalizeStoredSummaryMessage(summary) : undefined,
messages,
startMessageIndex: payload.record.startMessageIndex,
createdAt: payload.record.createdAt,
updatedAt: payload.record.updatedAt,
},
]
: [],
),
activeSegment:
activeSegment?.payload.kind === "active"
? {
...activeSegment.payload.record,
summary: activeSegment.summary
? normalizeStoredSummaryMessage(activeSegment.summary)
: undefined,
messages: activeSegment.messages,
}
: undefined,
returnedMessageCount: record.returnedMessageCount,
oldestOffset: record.oldestOffset,
hasMoreBefore: record.hasMoreBefore,
revision: record.revision,
updatedAt: record.updatedAt,
};
}
export async function replaceChatHistoryFromMessage(params: {
id: string;
baseMessageRef: HistoryMessageRef;
replacementMessage: Message;
maxMessages: number;
expectedRevision: string;
fallbackSystemPrompt?: string;
}): Promise<ChatHistoryWindowRecord> {
return withConversationWriteLock(params.id, async () => {
const record = await invoke<ChatHistoryWindowWireRecord>("chat_history_replace_from_message", {
id: params.id,
baseMessageRef: params.baseMessageRef,
replacementMessage: params.replacementMessage,
maxMessages: params.maxMessages,
expectedRevision: params.expectedRevision,
});
const parsed = await parseChatHistoryWindowRecord(record, params.fallbackSystemPrompt);
if (!parsed.activeSegment) throw new Error("历史替换结果缺少活跃分段");
return parsed;
});
}
function withConversationWriteLock<T>(conversationId: string, task: () => Promise<T>): Promise<T> {
const key = conversationId.trim();
if (!key) {
return task();
}
const previous = conversationWriteQueues.get(key) ?? Promise.resolve();
const next = previous.catch(() => undefined).then(task);
const tail = next.then(
() => undefined,
() => undefined,
);
conversationWriteQueues.set(key, tail);
return next.finally(() => {
if (conversationWriteQueues.get(key) === tail) {
conversationWriteQueues.delete(key);
}
});
}
function buildChatHistoryConversationInput(params: {
conversationId: string;
providerId: string;
model: string;
sessionId?: string;
cwd?: string;
selectedModelJson?: string;
title: string;
createdAt?: number;
updatedAt: number;
state: ConversationViewState;
}): ChatHistoryConversationInput {
const {
conversationId,
providerId,
model,
sessionId,
cwd,
selectedModelJson,
title,
createdAt,
updatedAt,
state,
} = params;
return {
id: conversationId,
title,
providerId,
model,
sessionId,
cwd,
selectedModelJson,
contextMetaJson: JSON.stringify(state.meta),
activeSegmentIndex: state.meta.activeSegmentIndex,
totalSegmentCount: state.meta.totalSegmentCount,
totalMessageCount: state.meta.totalMessageCount,
createdAt,
updatedAt,
};
}
function buildChatHistorySegmentInput(segment: StoredContextSegment): ChatHistorySegmentWireRecord {
return {
segmentIndex: segment.segmentIndex,
segmentId: segment.segmentId,
summaryJson: segment.summary ? JSON.stringify(segment.summary) : undefined,
messagesJson: JSON.stringify(segment.messages),
messageCount: segment.messageCount,
startMessageId: segment.startMessageId,
endMessageId: segment.endMessageId,
createdAt: segment.createdAt,
updatedAt: segment.updatedAt,
};
}
// Raw IPC wrappers: callers must already hold the conversation write lock.
async function upsertChatHistoryRaw(input: ChatHistoryUpsertInput) {
return invoke<ChatHistorySummary>("chat_history_upsert", { input });
}
async function upsertChatHistoryActiveSegmentRaw(input: ChatHistorySegmentMutationInput) {
return invoke<ChatHistorySummary>("chat_history_upsert_active_segment", { input });
}
async function appendChatHistorySegmentRaw(input: ChatHistorySegmentMutationInput) {
return invoke<ChatHistorySummary>("chat_history_append_segment", { input });
}
export async function renameChatHistory(id: string, title: string) {
return withConversationWriteLock(id, () =>
invoke<ChatHistorySummary>("chat_history_rename", { id, title }),
);
}
export async function branchChatHistory(id: string, baseMessageRef: HistoryMessageRef) {
return withConversationWriteLock(id, () =>
invoke<ChatHistorySummary>("chat_history_branch", { id, baseMessageRef }),
);
}
export async function setChatHistoryPinned(id: string, isPinned: boolean) {
return withConversationWriteLock(id, () =>
invoke<ChatHistorySummary>("chat_history_set_pinned", { id, isPinned }),
);
}
export async function setChatHistoryModel(id: string, selectedModelJson: string) {
return withConversationWriteLock(id, () =>
invoke<ChatHistorySummary>("chat_history_set_model", { id, selectedModelJson }),
);
}
export async function setChatHistoryCwd(id: string, cwd: string) {
return withConversationWriteLock(id, () =>
invoke<ChatHistorySummary>("chat_history_set_cwd", { id, cwd }),
);
}
export async function getChatHistoryShare(id: string) {
return invoke<ChatHistoryShareStatus>("chat_history_share_get", { id });
}
export async function setChatHistoryShare(
id: string,
enabled: boolean,
options?: { redactToolContent?: boolean },
) {
return withConversationWriteLock(id, () =>
invoke<ChatHistoryShareStatus>("chat_history_share_set", {
id,
enabled,
redactToolContent: options?.redactToolContent,
}),
);
}
export async function deleteChatHistory(id: string) {
return withConversationWriteLock(id, async () => {
await invoke<void>("chat_history_delete", { id });
});
}
type PersistConversationRuntimeParams = {
conversationId: string;
providerId: string;
model: string;
sessionId?: string;
cwd?: string;
selectedModelJson?: string;
title: string;
createdAt?: number;
updatedAt: number;
state: ConversationViewState;
getPersistenceCursor: () => ConversationPersistenceCursor | null;
commitPersistenceCursor: (cursor: ConversationPersistenceCursor) => void;
};
async function writeConversationRuntime(
conversation: ChatHistoryConversationInput,
cursor: ConversationPersistenceCursor | null,
state: ConversationViewState,
) {
const activeSegment = getActiveSegment(state);
if (!activeSegment) {
throw new Error("无法持久化缺少活跃分段的会话");
}
if (!cursor) {
if (state.segments[0]?.segmentIndex !== 0) {
throw new Error("已存在的历史会话缺少持久化游标");
}
return upsertChatHistoryRaw({
...conversation,
segments: state.segments.map(buildChatHistorySegmentInput),
});
}
if (activeSegment.segmentIndex === cursor.activeSegmentIndex) {
if (activeSegment.segmentId !== cursor.activeSegmentId) {
throw new Error("活跃历史分段身份与持久化游标不一致");
}
return upsertChatHistoryActiveSegmentRaw({
conversation,
segment: buildChatHistorySegmentInput(activeSegment),
});
}
if (activeSegment.segmentIndex === cursor.activeSegmentIndex + 1) {
return appendChatHistorySegmentRaw({
conversation,
segment: buildChatHistorySegmentInput(activeSegment),
});
}
throw new Error(
`不支持的历史分段跳变:${cursor.activeSegmentIndex} -> ${activeSegment.segmentIndex}`,
);
}
export async function persistConversationRuntime(params: PersistConversationRuntimeParams) {
return withConversationWriteLock(params.conversationId, async () => {
const conversation = buildChatHistoryConversationInput(params);
const summary = await writeConversationRuntime(
conversation,
params.getPersistenceCursor(),
params.state,
);
const activeSegment = getActiveSegment(params.state);
if (!activeSegment) {
throw new Error("持久化成功后缺少活跃分段");
}
params.commitPersistenceCursor({
activeSegmentIndex: activeSegment.segmentIndex,
activeSegmentId: activeSegment.segmentId,
});
return summary;
});
}