@samuelchung2010/dshift 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +116 -0
  4. package/README.md +116 -3
  5. package/assets/dshift-readme.gif +0 -0
  6. package/client.js +18831 -0
  7. package/cordis.patch.yml +58 -0
  8. package/docs/architecture.md +203 -0
  9. package/docs/configuration.md +103 -0
  10. package/docs/development.md +125 -0
  11. package/docs/limitations.md +74 -0
  12. package/docs/math-boxed-qquad.png +0 -0
  13. package/docs/math-boxed-single.png +0 -0
  14. package/docs/memory-integration.md +111 -0
  15. package/docs/perf/baseline-before.json +4872 -0
  16. package/docs/perf/baseline-before.summary.json +659 -0
  17. package/docs/perf/fixed-after.json +2927 -0
  18. package/docs/perf/fixed-after.summary.json +583 -0
  19. package/docs/perf/long-chat-performance.md +340 -0
  20. package/docs/perf/merged-after.json +1953 -0
  21. package/docs/perf/merged-after.summary.json +382 -0
  22. package/docs/perf/mount-after.json +82 -0
  23. package/docs/perf/mount-baseline.json +82 -0
  24. package/docs/user-guide.md +202 -0
  25. package/icon.svg +13 -0
  26. package/index.js +16 -0
  27. package/lib/api.js +336 -0
  28. package/lib/artifact/approval-bus.js +94 -0
  29. package/lib/artifact/prompt.js +99 -0
  30. package/lib/artifact/service.js +602 -0
  31. package/lib/artifact/workspace.js +260 -0
  32. package/lib/import/convert.js +343 -0
  33. package/lib/import/format.js +262 -0
  34. package/lib/import/index.js +585 -0
  35. package/lib/import/media.js +101 -0
  36. package/lib/import/zip.js +296 -0
  37. package/lib/memory-store.js +629 -0
  38. package/lib/memory-text.js +162 -0
  39. package/lib/memory.js +871 -0
  40. package/lib/model-config.js +280 -0
  41. package/lib/protocol.js +593 -0
  42. package/lib/service.js +2102 -0
  43. package/lib/store.js +1011 -0
  44. package/locale/en.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +49 -6
@@ -0,0 +1,585 @@
1
+ /**
2
+ * Import of a DeepSeek chat export ZIP into the native Chat history.
3
+ *
4
+ * The flow is deliberately staged, because an export is a large local file and
5
+ * the browser must stay usable while it is handled:
6
+ *
7
+ * 1. `ingest` streams the upload to a staging file inside the plugin's data
8
+ * directory, reads the manifest and the conversation index, and returns a
9
+ * preview. Nothing is written to the history yet.
10
+ * 2. `start` runs a background job over the conversations the user selected.
11
+ * Each conversation file is inflated on its own, converted, and merged; the
12
+ * history is written in batches, so a large import neither blocks the browser
13
+ * nor rewrites the whole document once per conversation.
14
+ * 3. `status` is polled by the browser for progress, then for the final result
15
+ * and the refreshed sidebar.
16
+ *
17
+ * Re-importing is idempotent: every conversation carries a stable source id, and
18
+ * an id the history already holds is skipped instead of duplicated. A
19
+ * conversation that fails is reported and the rest continue; the history
20
+ * document is backed up before the first write.
21
+ */
22
+
23
+ import { promises as fs } from 'node:fs'
24
+ import path from 'node:path'
25
+ import { randomUUID } from 'node:crypto'
26
+ import { ZipArchive, ZipError } from './zip.js'
27
+ import {
28
+ ExportFormatError, SUPPORTED_EXPORT_FORMAT_VERSION, readManifest, readSessionFile, readSessionIndex,
29
+ } from './format.js'
30
+ import { SOURCE_KIND, convertConversation } from './convert.js'
31
+ import { ImportMediaStore, isSupportedMediaExtension } from './media.js'
32
+
33
+ /** An import step that cannot continue; `code` selects the browser explanation. */
34
+ export class ImportError extends Error {
35
+ constructor(code, message, { status = 400, cause } = {}) {
36
+ super(message, cause === undefined ? undefined : { cause })
37
+ this.name = 'ImportError'
38
+ this.code = code
39
+ this.status = status
40
+ }
41
+ }
42
+
43
+ const TOKEN_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u
44
+ const MAX_MANIFEST_BYTES = 1024 * 1024
45
+ const MAX_INDEX_BYTES = 64 * 1024 * 1024
46
+ /** Conversations converted between two history writes. */
47
+ const BATCH_CONVERSATIONS = 40
48
+ /** Marker placed in the file name of the pre-import state backup. */
49
+ const BACKUP_LABEL = 'import-backup'
50
+ /** Finished jobs kept for a late poll; older ones are dropped. */
51
+ const JOBS_KEPT = 4
52
+ const MAX_FAILURES_REPORTED = 40
53
+
54
+ /** Default deployment limits, each overridable through the plugin config. */
55
+ export const IMPORT_LIMITS = {
56
+ /** Largest export ZIP accepted. Exports of a long history reach ~150 MB. */
57
+ maxUploadBytes: 512 * 1024 * 1024,
58
+ /** Largest single JSON entry inflated (one conversation file). */
59
+ maxEntryBytes: 128 * 1024 * 1024,
60
+ /** Largest single image recovered. */
61
+ maxMediaBytes: 32 * 1024 * 1024,
62
+ /** Total image bytes one import may write. */
63
+ maxMediaTotalBytes: 1024 * 1024 * 1024,
64
+ /** How long an uploaded archive waits for the user to start the import. */
65
+ stagingTtlMs: 30 * 60 * 1000,
66
+ }
67
+
68
+ function extensionOf(name) {
69
+ const value = typeof name === 'string' ? name : ''
70
+ const dot = value.lastIndexOf('.')
71
+ return dot > 0 && dot < value.length - 1 ? value.slice(dot + 1).toLowerCase() : ''
72
+ }
73
+
74
+ function errorCode(error) {
75
+ if (error instanceof ImportError) return error.code
76
+ if (error instanceof ZipError) return error.code
77
+ if (error instanceof ExportFormatError) return error.code
78
+ return 'INTERNAL'
79
+ }
80
+
81
+ function describe(error) {
82
+ return error instanceof Error ? error.message : String(error)
83
+ }
84
+
85
+ /** Sort index rows most recently updated first, so the newest chats lead. */
86
+ function rankRows(rows) {
87
+ return [...rows].sort((left, right) => (
88
+ (right.updatedAt ?? 0) - (left.updatedAt ?? 0)
89
+ || (right.insertedAt ?? 0) - (left.insertedAt ?? 0)
90
+ || (left.id < right.id ? -1 : 1)
91
+ ))
92
+ }
93
+
94
+ /**
95
+ * Every archive entry one conversation's file fragments name, as `export_path`.
96
+ * Branches are included, so switching versions after the import still finds the
97
+ * images of the other branch.
98
+ */
99
+ function mediaEntriesOf(file) {
100
+ const paths = new Set()
101
+ for (const message of file.messages) {
102
+ if (message.role !== 'USER') continue
103
+ for (const fragment of message.fragments) {
104
+ if (fragment?.type !== 'FILE') continue
105
+ for (const entry of fragment.files) {
106
+ if (!entry.isImage || entry.exportPath === undefined) continue
107
+ paths.add(entry.exportPath)
108
+ }
109
+ }
110
+ }
111
+ return paths
112
+ }
113
+
114
+ export class ChatImportManager {
115
+ /**
116
+ * @param options - history store, data directory, logger and limit overrides.
117
+ */
118
+ constructor({ store, directory, logger = console, limits = {} } = {}) {
119
+ this.store = store
120
+ this.directory = directory
121
+ this.logger = logger
122
+ this.limits = { ...IMPORT_LIMITS, ...limits }
123
+ this.stagingDirectory = path.join(directory, 'imports', 'staging')
124
+ this.media = new ImportMediaStore(path.join(directory, 'imports', 'media'))
125
+ /** Staged archives by token; `{ token, path, name, bytes, at }`. */
126
+ this.staged = new Map()
127
+ this.jobs = new Map()
128
+ this.active = null
129
+ this.disposed = false
130
+ }
131
+
132
+ /** Remove one staged archive and forget its token. */
133
+ async dropStaged(token) {
134
+ const staged = this.staged.get(token)
135
+ this.staged.delete(token)
136
+ if (staged === undefined) return false
137
+ await fs.rm(staged.directory, { recursive: true, force: true }).catch(() => {})
138
+ return true
139
+ }
140
+
141
+ /** Delete staged archives that no longer belong to a live import. */
142
+ async sweepStaging() {
143
+ const now = Date.now()
144
+ for (const [token, staged] of this.staged) {
145
+ if (this.active?.token === token) continue
146
+ if (now - staged.at <= this.limits.stagingTtlMs) continue
147
+ await this.dropStaged(token)
148
+ }
149
+ // A crash can leave a directory whose token was never registered; drop those
150
+ // as well instead of letting an interrupted upload occupy disk forever.
151
+ let entries
152
+ try {
153
+ entries = await fs.readdir(this.stagingDirectory, { withFileTypes: true })
154
+ } catch {
155
+ return
156
+ }
157
+ for (const entry of entries) {
158
+ if (!entry.isDirectory() || this.staged.has(entry.name) || this.active?.token === entry.name) continue
159
+ const directory = path.join(this.stagingDirectory, entry.name)
160
+ try {
161
+ const info = await fs.stat(directory)
162
+ if (now - info.mtimeMs <= this.limits.stagingTtlMs) continue
163
+ } catch {
164
+ continue
165
+ }
166
+ await fs.rm(directory, { recursive: true, force: true }).catch(() => {})
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Stream one uploaded archive to the staging area and read its preview.
172
+ *
173
+ * The request body is written chunk by chunk, so the browser's upload never
174
+ * becomes one big buffer on the Host, and the size cap is enforced as bytes
175
+ * arrive. Running out of space, a truncated body, or a non-ZIP file removes
176
+ * the partial file before the error leaves this method.
177
+ *
178
+ * @param request - the HTTP request carrying the archive.
179
+ * @param name - the file name to report back.
180
+ * @returns the preview.
181
+ */
182
+ async ingest(request, name) {
183
+ if (this.disposed) throw new ImportError('DISPOSED', 'the chat plugin was unloaded', { status: 503 })
184
+ await this.sweepStaging()
185
+ const declared = Number(request.headers.get('content-length') ?? '0')
186
+ const limit = this.limits.maxUploadBytes
187
+ if (Number.isFinite(declared) && declared > limit) {
188
+ throw new ImportError('ARCHIVE_TOO_LARGE', `the archive exceeds the ${limit}-byte import limit`, { status: 413 })
189
+ }
190
+ if (request.body === null || request.body === undefined) {
191
+ throw new ImportError('EMPTY_UPLOAD', 'the request carried no file', { status: 400 })
192
+ }
193
+ const token = randomUUID()
194
+ const directory = path.join(this.stagingDirectory, token)
195
+ const target = path.join(directory, 'export.zip')
196
+ await fs.mkdir(directory, { recursive: true })
197
+ let bytes = 0
198
+ let handle
199
+ try {
200
+ handle = await fs.open(target, 'w')
201
+ for await (const chunk of request.body) {
202
+ bytes += chunk.length
203
+ if (bytes > limit) {
204
+ throw new ImportError('ARCHIVE_TOO_LARGE', `the archive exceeds the ${limit}-byte import limit`, { status: 413 })
205
+ }
206
+ await handle.write(chunk)
207
+ }
208
+ await handle.close()
209
+ handle = undefined
210
+ if (bytes === 0) throw new ImportError('EMPTY_UPLOAD', 'the request carried no file', { status: 400 })
211
+ const preview = await this.readPreview(target, name, bytes)
212
+ const staged = { token, path: target, directory, name, bytes, at: Date.now() }
213
+ this.staged.set(token, staged)
214
+ return { token, ...preview }
215
+ } catch (error) {
216
+ if (handle !== undefined) await handle.close().catch(() => {})
217
+ await fs.rm(directory, { recursive: true, force: true }).catch(() => {})
218
+ if (error instanceof ImportError || error instanceof ZipError || error instanceof ExportFormatError) {
219
+ throw new ImportError(errorCode(error), describe(error), { status: error.status ?? 400, cause: error })
220
+ }
221
+ throw new ImportError('INGEST_FAILED', describe(error), { status: 500, cause: error })
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Read the manifest and the conversation index of one archive.
227
+ * @returns `{ file, formatVersion, conversations, stats }`.
228
+ */
229
+ async readPreview(archivePath, name, bytes) {
230
+ const archive = await ZipArchive.open(archivePath, {
231
+ maxArchiveBytes: this.limits.maxUploadBytes,
232
+ maxEntryBytes: this.limits.maxEntryBytes,
233
+ })
234
+ try {
235
+ const manifestBytes = await archive.read('manifest.json', MAX_MANIFEST_BYTES)
236
+ if (manifestBytes === undefined) throw new ImportError('MISSING_MANIFEST', 'the archive has no manifest.json')
237
+ const manifest = readManifest(manifestBytes)
238
+ if (manifest.version !== SUPPORTED_EXPORT_FORMAT_VERSION) {
239
+ throw new ImportError(
240
+ 'UNSUPPORTED_VERSION',
241
+ `export format version ${manifest.version} is not supported`,
242
+ )
243
+ }
244
+ const indexBytes = await archive.read('chat_session_index.json', MAX_INDEX_BYTES)
245
+ if (indexBytes === undefined) throw new ImportError('MISSING_INDEX', 'the archive has no conversation index')
246
+ const rows = rankRows(readSessionIndex(indexBytes))
247
+ const imported = this.store.importedSourceIds(SOURCE_KIND)
248
+ const conversations = rows.map((row) => ({
249
+ sourceId: row.id,
250
+ title: row.title,
251
+ messageCount: row.messageCount,
252
+ createdAt: row.insertedAt ?? null,
253
+ updatedAt: row.updatedAt ?? null,
254
+ pinned: row.pinned,
255
+ imported: imported.has(row.id),
256
+ }))
257
+ const already = conversations.filter(conversation => conversation.imported).length
258
+ return {
259
+ file: { name, bytes },
260
+ formatVersion: manifest.version,
261
+ conversations,
262
+ stats: { total: conversations.length, imported: already, importable: conversations.length - already },
263
+ }
264
+ } catch (error) {
265
+ if (error instanceof ImportError || error instanceof ZipError || error instanceof ExportFormatError) {
266
+ throw new ImportError(errorCode(error), describe(error), { status: 400, cause: error })
267
+ }
268
+ throw new ImportError('PREVIEW_FAILED', describe(error), { status: 500, cause: error })
269
+ } finally {
270
+ await archive.close()
271
+ }
272
+ }
273
+
274
+ /** One job snapshot, safe to serialize to the browser. */
275
+ snapshot(job) {
276
+ return {
277
+ id: job.id,
278
+ state: job.state,
279
+ total: job.total,
280
+ done: job.done,
281
+ imported: job.imported.length,
282
+ skipped: job.skipped.length,
283
+ failed: job.failures.length,
284
+ startedAt: job.startedAt,
285
+ updatedAt: job.updatedAt,
286
+ media: job.media,
287
+ failures: job.failures.slice(0, MAX_FAILURES_REPORTED),
288
+ skippedItems: job.skipped.slice(0, MAX_FAILURES_REPORTED),
289
+ error: job.error,
290
+ backup: job.backup ?? null,
291
+ }
292
+ }
293
+
294
+ /** Final sidebar state, attached to a finished job so one poll refreshes the list. */
295
+ finalPayload(job) {
296
+ return {
297
+ job: this.snapshot(job),
298
+ conversations: this.store.listSummaries(),
299
+ folders: this.store.listFolders(),
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Start importing the selected conversations.
305
+ * @param options - `{ token, ids }`.
306
+ * @returns `{ job }`, already running in the background.
307
+ */
308
+ async start({ token, ids } = {}) {
309
+ if (this.disposed) throw new ImportError('DISPOSED', 'the chat plugin was unloaded', { status: 503 })
310
+ if (typeof token !== 'string' || !TOKEN_PATTERN.test(token)) {
311
+ throw new ImportError('INVALID_REQUEST', 'the import token is not valid')
312
+ }
313
+ if (this.active !== null) {
314
+ throw new ImportError('BUSY', 'another import is still running', { status: 409 })
315
+ }
316
+ const staged = this.staged.get(token)
317
+ if (staged === undefined) {
318
+ throw new ImportError('TOKEN_EXPIRED', 'the uploaded archive is no longer available; choose the file again', { status: 410 })
319
+ }
320
+ const wanted = new Set(Array.isArray(ids) ? ids.filter(id => typeof id === 'string' && id !== '') : [])
321
+ if (wanted.size === 0) throw new ImportError('NO_SELECTION', 'no conversation was selected')
322
+
323
+ const archive = await ZipArchive.open(staged.path, {
324
+ maxArchiveBytes: this.limits.maxUploadBytes,
325
+ maxEntryBytes: this.limits.maxEntryBytes,
326
+ })
327
+ let rows
328
+ try {
329
+ const indexBytes = await archive.read('chat_session_index.json', MAX_INDEX_BYTES)
330
+ if (indexBytes === undefined) throw new ImportError('MISSING_INDEX', 'the archive has no conversation index')
331
+ rows = rankRows(readSessionIndex(indexBytes)).filter(row => wanted.has(row.id))
332
+ } catch (error) {
333
+ throw new ImportError(errorCode(error), describe(error), { status: 400, cause: error })
334
+ } finally {
335
+ await archive.close()
336
+ }
337
+ if (rows.length === 0) throw new ImportError('NO_SELECTION', 'none of the selected conversations is in the archive')
338
+
339
+ const job = {
340
+ id: randomUUID(),
341
+ token,
342
+ state: 'running',
343
+ total: rows.length,
344
+ done: 0,
345
+ imported: [],
346
+ skipped: [],
347
+ failures: [],
348
+ media: { restored: 0, bytes: 0, omitted: 0 },
349
+ startedAt: Date.now(),
350
+ updatedAt: Date.now(),
351
+ error: null,
352
+ backup: null,
353
+ cancelRequested: false,
354
+ rows,
355
+ }
356
+ this.jobs.set(job.id, job)
357
+ this.active = job
358
+ this.trimJobs()
359
+ // The job runs detached: the browser polls `status`, which is what keeps the
360
+ // request short and the progress observable from any render.
361
+ void this.run(job, staged).catch((error) => {
362
+ job.state = 'failed'
363
+ job.error = describe(error)
364
+ job.updatedAt = Date.now()
365
+ this.logger.warn?.('deepseek-chat: import failed', describe(error))
366
+ }).finally(() => {
367
+ if (this.active === job) this.active = null
368
+ job.updatedAt = Date.now()
369
+ void fs.rm(staged.directory, { recursive: true, force: true }).catch(() => {})
370
+ this.staged.delete(job.token)
371
+ })
372
+ return { job: this.snapshot(job) }
373
+ }
374
+
375
+ /** Keep only the most recent jobs; older ones are no longer polled. */
376
+ trimJobs() {
377
+ if (this.jobs.size <= JOBS_KEPT) return
378
+ for (const [id, job] of this.jobs) {
379
+ if (this.jobs.size <= JOBS_KEPT) break
380
+ if (job.state === 'running') continue
381
+ this.jobs.delete(id)
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Run one import job to completion.
387
+ *
388
+ * Each conversation is handled inside its own try: a malformed tree, a missing
389
+ * entry, or an unexpected conversion failure is recorded and the next
390
+ * conversation continues. Converted conversations are written in batches
391
+ * through the store, so an interrupted import leaves the history exactly as
392
+ * the last completed batch wrote it.
393
+ */
394
+ async run(job, staged) {
395
+ const archive = await ZipArchive.open(staged.path, {
396
+ maxArchiveBytes: this.limits.maxUploadBytes,
397
+ maxEntryBytes: this.limits.maxEntryBytes,
398
+ }).catch(() => null)
399
+ if (archive === null) {
400
+ job.state = 'failed'
401
+ job.error = 'the uploaded archive could not be reopened'
402
+ return
403
+ }
404
+ let batch = []
405
+ const flush = async () => {
406
+ if (batch.length === 0) return
407
+ const drafts = batch
408
+ batch = []
409
+ try {
410
+ const result = await this.store.adoptConversations(drafts.map(entry => entry.draft))
411
+ const accepted = new Set(result.added)
412
+ for (const entry of drafts) {
413
+ if (accepted.has(entry.draft.id)) {
414
+ job.imported.push(entry.result)
415
+ } else {
416
+ job.skipped.push({ sourceId: entry.sourceId, title: entry.title, reason: 'duplicate' })
417
+ }
418
+ }
419
+ } catch (error) {
420
+ // A failed history write ends the job: continuing would only stack more
421
+ // conversations in memory that the document does not hold.
422
+ for (const entry of drafts) {
423
+ job.failures.push({ sourceId: entry.sourceId, title: entry.title, code: 'WRITE_FAILED', reason: describe(error) })
424
+ }
425
+ job.error = `the chat history could not be written: ${describe(error)}`
426
+ job.state = 'failed'
427
+ }
428
+ }
429
+ try {
430
+ try {
431
+ job.backup = await this.store.backup(BACKUP_LABEL)
432
+ } catch (error) {
433
+ // A backup that cannot be made does not make the import unsafe: the store
434
+ // still writes atomically, and the failure is reported in the result.
435
+ job.error = `the previous history could not be backed up: ${describe(error)}`
436
+ }
437
+ for (const row of job.rows) {
438
+ if (job.state === 'failed') break
439
+ if (job.cancelRequested) break
440
+ let entry
441
+ try {
442
+ if (this.store.findBySource(SOURCE_KIND, row.id) !== undefined) {
443
+ job.skipped.push({ sourceId: row.id, title: row.title, reason: 'already-imported' })
444
+ job.done += 1
445
+ job.updatedAt = Date.now()
446
+ continue
447
+ }
448
+ entry = await this.convertRow(archive, row, job)
449
+ } catch (error) {
450
+ job.failures.push({
451
+ sourceId: row.id,
452
+ title: row.title,
453
+ code: errorCode(error),
454
+ reason: describe(error).slice(0, 300),
455
+ })
456
+ job.done += 1
457
+ job.updatedAt = Date.now()
458
+ await this.yieldTurn()
459
+ continue
460
+ }
461
+ job.done += 1
462
+ job.updatedAt = Date.now()
463
+ batch.push(entry)
464
+ if (batch.length >= BATCH_CONVERSATIONS) await flush()
465
+ await this.yieldTurn()
466
+ }
467
+ await flush()
468
+ if (job.state !== 'failed') {
469
+ job.state = job.cancelRequested ? 'cancelled' : 'done'
470
+ }
471
+ } catch (error) {
472
+ job.state = 'failed'
473
+ job.error = describe(error)
474
+ this.logger.warn?.('deepseek-chat: import stopped', describe(error))
475
+ } finally {
476
+ await archive.close()
477
+ job.updatedAt = Date.now()
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Convert one selected conversation, recovering the images of its tree first.
483
+ * @returns `{ draft, result, sourceId, title }` for the next history batch.
484
+ */
485
+ async convertRow(archive, row, job) {
486
+ const entryName = `chat_sessions/${row.id}.json`
487
+ const bytes = await archive.read(entryName, this.limits.maxEntryBytes)
488
+ if (bytes === undefined) throw new ImportError('MISSING_ENTRY', 'the archive has no file for this conversation')
489
+ const file = readSessionFile(bytes)
490
+ const recovered = new Map()
491
+ for (const exportPath of mediaEntriesOf(file)) {
492
+ if (job.media.bytes >= this.limits.maxMediaTotalBytes) {
493
+ job.media.omitted += 1
494
+ continue
495
+ }
496
+ const extension = extensionOf(exportPath)
497
+ if (!isSupportedMediaExtension(extension)) {
498
+ job.media.omitted += 1
499
+ continue
500
+ }
501
+ const declared = archive.sizeOf(exportPath)
502
+ if (declared === undefined) {
503
+ job.media.omitted += 1
504
+ continue
505
+ }
506
+ if (declared > this.limits.maxMediaBytes) {
507
+ job.media.omitted += 1
508
+ continue
509
+ }
510
+ let data
511
+ try {
512
+ data = await archive.read(exportPath, this.limits.maxMediaBytes)
513
+ } catch {
514
+ job.media.omitted += 1
515
+ continue
516
+ }
517
+ if (data === undefined) {
518
+ job.media.omitted += 1
519
+ continue
520
+ }
521
+ const saved = await this.media.save(data, extension)
522
+ if (saved === undefined) {
523
+ job.media.omitted += 1
524
+ continue
525
+ }
526
+ job.media.bytes += saved.size
527
+ recovered.set(exportPath, saved)
528
+ }
529
+ const { draft, stats } = convertConversation(file, row, {
530
+ importedAt: Date.now(),
531
+ resolveMedia: exportPath => recovered.get(exportPath),
532
+ })
533
+ job.media.restored += stats.restoredImages
534
+ return {
535
+ draft,
536
+ sourceId: row.id,
537
+ title: draft.title || row.title,
538
+ result: {
539
+ sourceId: row.id,
540
+ conversationId: draft.id,
541
+ title: draft.title || row.title,
542
+ messages: stats.messages,
543
+ images: stats.restoredImages,
544
+ },
545
+ }
546
+ }
547
+
548
+ /** Let the event loop run one turn: inflation and JSON parsing are synchronous. */
549
+ async yieldTurn() {
550
+ await new Promise((resolve) => setImmediate(resolve))
551
+ }
552
+
553
+ /** Progress of one job, or null when the job is unknown or expired. */
554
+ status(id) {
555
+ if (typeof id !== 'string' || id === '') return null
556
+ const job = this.jobs.get(id)
557
+ if (job === undefined) return null
558
+ return job.state === 'running' ? { job: this.snapshot(job) } : this.finalPayload(job)
559
+ }
560
+
561
+ /** Ask one running job to stop after the conversation it is handling. */
562
+ cancel(id) {
563
+ const job = typeof id === 'string' ? this.jobs.get(id) : undefined
564
+ if (job === undefined) throw new ImportError('NOT_FOUND', 'the import job does not exist', { status: 404 })
565
+ if (job.state !== 'running') return { job: this.snapshot(job) }
566
+ job.cancelRequested = true
567
+ job.updatedAt = Date.now()
568
+ return { job: this.snapshot(job) }
569
+ }
570
+
571
+ /** Resolve one stored image for the media route. */
572
+ async mediaFile(media) {
573
+ return this.media.resolve(media)
574
+ }
575
+
576
+ /** Stop timers and release staged archives; a running job is asked to cancel. */
577
+ dispose() {
578
+ this.disposed = true
579
+ if (this.active !== null) this.active.cancelRequested = true
580
+ this.active = null
581
+ for (const token of [...this.staged.keys()]) {
582
+ void this.dropStaged(token)
583
+ }
584
+ }
585
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Local byte storage for images recovered from an imported chat export.
3
+ *
4
+ * DeepSeek's export carries the image bytes next to each conversation, but the
5
+ * original files live on DeepSeek's file service, which this plugin does not
6
+ * re-upload to (an import must not cost API usage). The bytes are therefore kept
7
+ * in the plugin's own data directory under a content address: the same image is
8
+ * written once no matter how often it is referenced or how many exports include
9
+ * it, and a re-import reuses the existing file.
10
+ *
11
+ * A stored name is `{sha256}.{ext}` and is validated before it is turned into a
12
+ * path, so a request for a media handle can never reach another file.
13
+ */
14
+
15
+ import { promises as fs } from 'node:fs'
16
+ import path from 'node:path'
17
+ import { createHash } from 'node:crypto'
18
+
19
+ /** Extensions this store accepts; they are all safe to serve as an image. */
20
+ const CONTENT_TYPES = new Map([
21
+ ['png', 'image/png'],
22
+ ['jpg', 'image/jpeg'],
23
+ ['jpeg', 'image/jpeg'],
24
+ ['webp', 'image/webp'],
25
+ ['gif', 'image/gif'],
26
+ ['bmp', 'image/bmp'],
27
+ ['avif', 'image/avif'],
28
+ ['svg', 'image/svg+xml'],
29
+ ])
30
+
31
+ const MEDIA_NAME = /^([a-f0-9]{64})\.([a-z0-9]{2,5})$/u
32
+
33
+ const SUPPORTED_EXTENSIONS = new Set(CONTENT_TYPES.keys())
34
+
35
+ /** Whether one extension can be stored and served. */
36
+ export function isSupportedMediaExtension(extension) {
37
+ return SUPPORTED_EXTENSIONS.has(extension)
38
+ }
39
+
40
+ /** Whether one stored media handle is well formed. */
41
+ export function isMediaName(value) {
42
+ return typeof value === 'string' && MEDIA_NAME.test(value)
43
+ }
44
+
45
+ export class ImportMediaStore {
46
+ /** @param directory - directory holding the content-addressed files. */
47
+ constructor(directory) {
48
+ this.directory = directory
49
+ }
50
+
51
+ /**
52
+ * Store one image.
53
+ * @param bytes - image data.
54
+ * @param extension - lower-case extension without the dot.
55
+ * @returns `{ media, size }`, or undefined when the type is not served.
56
+ */
57
+ async save(bytes, extension) {
58
+ if (!isSupportedMediaExtension(extension)) return undefined
59
+ const digest = createHash('sha256').update(bytes).digest('hex')
60
+ const media = `${digest}.${extension}`
61
+ const target = path.join(this.directory, media)
62
+ try {
63
+ await fs.access(target)
64
+ return { media, size: bytes.length }
65
+ } catch {
66
+ // Not stored yet.
67
+ }
68
+ await fs.mkdir(this.directory, { recursive: true })
69
+ const temporary = `${target}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`
70
+ await fs.writeFile(temporary, bytes)
71
+ try {
72
+ await fs.rename(temporary, target)
73
+ } catch (error) {
74
+ await fs.rm(temporary, { force: true }).catch(() => {})
75
+ // A concurrent import may have written the same address first; reusing it
76
+ // is the point of a content address, so only a missing file is an error.
77
+ if (error?.code !== 'EEXIST' && error?.code !== 'EPERM' && error?.code !== 'EACCES') throw error
78
+ }
79
+ return { media, size: bytes.length }
80
+ }
81
+
82
+ /**
83
+ * Resolve one stored media handle.
84
+ * @param media - validated name, `{sha256}.{ext}`.
85
+ * @returns the absolute path and content type, or undefined for an invalid or missing file.
86
+ */
87
+ async resolve(media) {
88
+ if (!isMediaName(media)) return undefined
89
+ const extension = media.slice(media.indexOf('.') + 1)
90
+ const contentType = CONTENT_TYPES.get(extension)
91
+ if (contentType === undefined) return undefined
92
+ const target = path.join(this.directory, media)
93
+ try {
94
+ const info = await fs.stat(target)
95
+ if (!info.isFile()) return undefined
96
+ return { path: target, contentType, size: info.size }
97
+ } catch {
98
+ return undefined
99
+ }
100
+ }
101
+ }