@lsamien/yaoyao 0.4.75
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/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +103 -0
- package/THIRD_PARTY_NOTICES.md +16 -0
- package/bin/desktop-service-sync.mjs +43 -0
- package/bin/hermes-yaoyao-updater.mjs +315 -0
- package/bin/hermes-yaoyao.mjs +246 -0
- package/bin/lib/data-home.d.mts +4 -0
- package/bin/lib/data-home.mjs +24 -0
- package/bin/lib/data-migration.d.mts +2 -0
- package/bin/lib/data-migration.mjs +107 -0
- package/bin/lib/desktop-activation.d.mts +4 -0
- package/bin/lib/desktop-activation.mjs +18 -0
- package/bin/lib/managed-data-migration.mjs +45 -0
- package/bin/lib/release-source.d.mts +2 -0
- package/bin/lib/release-source.mjs +23 -0
- package/bin/lib/runtime-release.mjs +78 -0
- package/bin/lib/service-data.mjs +57 -0
- package/bin/lib/service-update.mjs +372 -0
- package/bin/migrate-data-home.mjs +20 -0
- package/build-info.json +657 -0
- package/desktop/main.mjs +679 -0
- package/dist/assets/AboutDialog-BvuJp8Pe.js +2 -0
- package/dist/assets/AboutDialog-BvuJp8Pe.js.map +1 -0
- package/dist/assets/AboutDialog-DC5YWX39.css +1 -0
- package/dist/assets/BotAutomationsView-Ddgs5Hes.js +2 -0
- package/dist/assets/BotAutomationsView-Ddgs5Hes.js.map +1 -0
- package/dist/assets/BotAutomationsView-DeJ-e3y5.css +1 -0
- package/dist/assets/BotPluginsDialog-Db5dTqvg.css +1 -0
- package/dist/assets/BotPluginsDialog-xPqUSyHS.js +2 -0
- package/dist/assets/BotPluginsDialog-xPqUSyHS.js.map +1 -0
- package/dist/assets/BotSettingsDialog-BkjoAZtf.css +1 -0
- package/dist/assets/BotSettingsDialog-wLz_KGzX.js +5 -0
- package/dist/assets/BotSettingsDialog-wLz_KGzX.js.map +1 -0
- package/dist/assets/ChatView-DRPu2nKr.js +2 -0
- package/dist/assets/ChatView-DRPu2nKr.js.map +1 -0
- package/dist/assets/ChatView-Dx8YlcPr.css +1 -0
- package/dist/assets/ChevronForwardOutline-D--GIQK6.js +2 -0
- package/dist/assets/ChevronForwardOutline-D--GIQK6.js.map +1 -0
- package/dist/assets/ComputerPanel-Byr2_yKj.js +2 -0
- package/dist/assets/ComputerPanel-Byr2_yKj.js.map +1 -0
- package/dist/assets/ComputerPanel-CQOv4v8E.css +1 -0
- package/dist/assets/ComputerViewerView-BBAs4bzi.css +1 -0
- package/dist/assets/ComputerViewerView-DJ6hB-5e.js +2 -0
- package/dist/assets/ComputerViewerView-DJ6hB-5e.js.map +1 -0
- package/dist/assets/ConversationsView-C_VZl5g2.css +1 -0
- package/dist/assets/ConversationsView-cu1Yrq68.js +6 -0
- package/dist/assets/ConversationsView-cu1Yrq68.js.map +1 -0
- package/dist/assets/FilesView-DAIzo9Ps.css +1 -0
- package/dist/assets/FilesView-h9oJFmZt.js +2 -0
- package/dist/assets/FilesView-h9oJFmZt.js.map +1 -0
- package/dist/assets/FloatingResourceSearch-BF2XOLd-.css +1 -0
- package/dist/assets/FloatingResourceSearch-TofG1_DV.js +9 -0
- package/dist/assets/FloatingResourceSearch-TofG1_DV.js.map +1 -0
- package/dist/assets/HistoryView-Bh0SU969.js +2 -0
- package/dist/assets/HistoryView-Bh0SU969.js.map +1 -0
- package/dist/assets/HistoryView-DvuCAjlo.css +1 -0
- package/dist/assets/KanbanView-B-2vG4w7.css +1 -0
- package/dist/assets/KanbanView-CcqMOzB7.js +2 -0
- package/dist/assets/KanbanView-CcqMOzB7.js.map +1 -0
- package/dist/assets/LocalVmSettingsPanel-C8PIgMr3.js +2 -0
- package/dist/assets/LocalVmSettingsPanel-C8PIgMr3.js.map +1 -0
- package/dist/assets/LocalVmSettingsPanel-Dedfhqlq.css +1 -0
- package/dist/assets/RunnerSettingsPanel-CfxxQKpV.css +1 -0
- package/dist/assets/RunnerSettingsPanel-CvNnWcdH.js +4 -0
- package/dist/assets/RunnerSettingsPanel-CvNnWcdH.js.map +1 -0
- package/dist/assets/StandaloneDialog-BbNWY6IJ.js +2 -0
- package/dist/assets/StandaloneDialog-BbNWY6IJ.js.map +1 -0
- package/dist/assets/StandaloneDialog-Bg5U9bMJ.css +1 -0
- package/dist/assets/UpdateCheckDialog-C357uDSE.js +2 -0
- package/dist/assets/UpdateCheckDialog-C357uDSE.js.map +1 -0
- package/dist/assets/UpdateCheckDialog-CRlyWnE7.css +1 -0
- package/dist/assets/WorkspaceKnowledgePanel-B6xMyHdp.css +1 -0
- package/dist/assets/WorkspaceKnowledgePanel-CE7qsu2i.js +2 -0
- package/dist/assets/WorkspaceKnowledgePanel-CE7qsu2i.js.map +1 -0
- package/dist/assets/WorkspaceRoutinesPanel-CLsHmBuH.css +1 -0
- package/dist/assets/WorkspaceRoutinesPanel-DybBh6PZ.js +2 -0
- package/dist/assets/WorkspaceRoutinesPanel-DybBh6PZ.js.map +1 -0
- package/dist/assets/WorkspaceShell-7wn8iTne.css +1 -0
- package/dist/assets/WorkspaceShell-kp1ObJTk.js +44 -0
- package/dist/assets/WorkspaceShell-kp1ObJTk.js.map +1 -0
- package/dist/assets/WorkspaceView-CtNI0_AO.js +2 -0
- package/dist/assets/WorkspaceView-CtNI0_AO.js.map +1 -0
- package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js +3 -0
- package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js.map +1 -0
- package/dist/assets/browser-B97PQaMt.js +11 -0
- package/dist/assets/browser-B97PQaMt.js.map +1 -0
- package/dist/assets/docx-preview-YvkiVUyQ.js +22 -0
- package/dist/assets/docx-preview-YvkiVUyQ.js.map +1 -0
- package/dist/assets/index-GQxxBKs2.js +17 -0
- package/dist/assets/index-GQxxBKs2.js.map +1 -0
- package/dist/assets/index-g5POnMkp.css +1 -0
- package/dist/assets/localVm-owThjmhy.js +2 -0
- package/dist/assets/localVm-owThjmhy.js.map +1 -0
- package/dist/assets/pdf-pqGpzpl1.js +55 -0
- package/dist/assets/pdf-pqGpzpl1.js.map +1 -0
- package/dist/assets/pdf.worker.min-iDqQPrd3.mjs +31 -0
- package/dist/assets/sessionOwnership-BTz0Fyp5.css +1 -0
- package/dist/assets/sessionOwnership-bedp16q1.js +6 -0
- package/dist/assets/sessionOwnership-bedp16q1.js.map +1 -0
- package/dist/assets/viewModels-BYFb-v4u.js +38 -0
- package/dist/assets/viewModels-BYFb-v4u.js.map +1 -0
- package/dist/assets/viewModels-CkZuSvKm.css +1 -0
- package/dist/brand/AppIcon-1024.png +0 -0
- package/dist/icons/apple-touch-icon.png +0 -0
- package/dist/icons/favicon-32.png +0 -0
- package/dist/icons/icon-192.png +0 -0
- package/dist/icons/icon-512.png +0 -0
- package/dist/icons/logo-64.png +0 -0
- package/dist/index.html +19 -0
- package/dist/manifest.webmanifest +21 -0
- package/dist/setting-previews/dark.png +0 -0
- package/dist/setting-previews/light.png +0 -0
- package/dist/setting-previews/system.png +0 -0
- package/dist-server/runner/agent.js +563 -0
- package/dist-server/runner/browser/installation.js +180 -0
- package/dist-server/runner/browser/publicProxy.js +157 -0
- package/dist-server/runner/browser/runtime.js +622 -0
- package/dist-server/runner/browser/types.js +8 -0
- package/dist-server/runner/computers/commandProcess.js +127 -0
- package/dist-server/runner/computers/compose.js +139 -0
- package/dist-server/runner/computers/computer-image/Dockerfile +101 -0
- package/dist-server/runner/computers/computer-image/Dockerfile.cursor +27 -0
- package/dist-server/runner/computers/computer-image/Dockerfile.network +9 -0
- package/dist-server/runner/computers/computer-image/compose_bridge.py +329 -0
- package/dist-server/runner/computers/computer-image/cursor-browser.sh +6 -0
- package/dist-server/runner/computers/computer-image/cursor-desktop.py +86 -0
- package/dist-server/runner/computers/computer-image/network_gateway.py +197 -0
- package/dist-server/runner/computers/computer-image/prepare-firefox.sh +11 -0
- package/dist-server/runner/computers/computer-image/skill_bundle.py +111 -0
- package/dist-server/runner/computers/computerFailures.js +30 -0
- package/dist-server/runner/computers/container.js +652 -0
- package/dist-server/runner/computers/dataSnapshot.js +62 -0
- package/dist-server/runner/computers/desktopClose.js +41 -0
- package/dist-server/runner/computers/imageCli.js +42 -0
- package/dist-server/runner/computers/imageManagement.js +321 -0
- package/dist-server/runner/computers/images.js +130 -0
- package/dist-server/runner/computers/localVm.js +270 -0
- package/dist-server/runner/computers/maintenance.js +96 -0
- package/dist-server/runner/computers/maintenanceCli.js +59 -0
- package/dist-server/runner/computers/migrateUserData.js +62 -0
- package/dist-server/runner/computers/pool.js +407 -0
- package/dist-server/runner/computers/third-party/openmausbot/LICENSE +202 -0
- package/dist-server/runner/computers/third-party/openmausbot/NOTICE +4 -0
- package/dist-server/runner/computers/userData.js +128 -0
- package/dist-server/runner/computers/workspaceRecovery.js +120 -0
- package/dist-server/runner/config.js +37 -0
- package/dist-server/runner/hermes-bots-bridge/README.md +102 -0
- package/dist-server/runner/hermes-bots-bridge/__init__.py +59 -0
- package/dist-server/runner/hermes-bots-bridge/bootstrap.py +31 -0
- package/dist-server/runner/hermes-bots-bridge/bridge_runtime.py +1179 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/bridge.js +2 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/manifest.json +9 -0
- package/dist-server/runner/hermes-bots-bridge/dashboard/plugin_api.py +132 -0
- package/dist-server/runner/hermes-bots-bridge/file_transfer.py +146 -0
- package/dist-server/runner/hermes-bots-bridge/model_settings.py +136 -0
- package/dist-server/runner/hermes-bots-bridge/plugin.yaml +4 -0
- package/dist-server/runner/hermes-bots-bridge/profile_runtime_repair.py +77 -0
- package/dist-server/runner/index.js +75 -0
- package/dist-server/runner/install-hermes-bridge.py +192 -0
- package/dist-server/runner/managedBrowser.js +266 -0
- package/dist-server/runner/network/computerProxy.js +117 -0
- package/dist-server/runner/network/managedProxy.js +96 -0
- package/dist-server/runner/network/publicDestination.js +47 -0
- package/dist-server/runner/network/socketBroker.js +131 -0
- package/dist-server/runner/network/upstreamProxy.js +118 -0
- package/dist-server/runner/worker/control.js +212 -0
- package/dist-server/runner/worker/fileTransfer.js +9 -0
- package/dist-server/runner/worker/gateway.js +1009 -0
- package/dist-server/runner/worker/guest_proxy.py +116 -0
- package/dist-server/runner/worker/hermes_worker.py +310 -0
- package/dist-server/runner/worker/hostTools.js +115 -0
- package/dist-server/runner/worker/process.js +123 -0
- package/dist-server/runner/worker/profileSession.js +144 -0
- package/dist-server/runner/worker/profile_skills.py +361 -0
- package/dist-server/runner/worker/skill_bundle.py +111 -0
- package/dist-server/runner/worker/skills.js +119 -0
- package/dist-server/runner/worker/taskEnvironment.js +35 -0
- package/dist-server/server/accountPairing.js +72 -0
- package/dist-server/server/allowedHostsConfiguration.js +170 -0
- package/dist-server/server/apns.js +261 -0
- package/dist-server/server/apnsConfiguration.js +298 -0
- package/dist-server/server/app.js +639 -0
- package/dist-server/server/botModelSettings.js +60 -0
- package/dist-server/server/botPlugins/connectedApps.js +213 -0
- package/dist-server/server/botPlugins/httpMcp.js +117 -0
- package/dist-server/server/botPlugins/stdioMcp.js +263 -0
- package/dist-server/server/botPlugins/workspacePlugins.js +353 -0
- package/dist-server/server/browserFiles.js +79 -0
- package/dist-server/server/buildIdentity.js +18 -0
- package/dist-server/server/chatCache.js +1651 -0
- package/dist-server/server/chatEventProjection.js +70 -0
- package/dist-server/server/chatTranscriptApi.js +145 -0
- package/dist-server/server/chatTranscriptStore.js +1021 -0
- package/dist-server/server/chatUnread.js +34 -0
- package/dist-server/server/codexAuthorization.js +149 -0
- package/dist-server/server/composeDesktops.js +69 -0
- package/dist-server/server/computerControls.js +122 -0
- package/dist-server/server/computerNames.js +41 -0
- package/dist-server/server/config.js +176 -0
- package/dist-server/server/dashboardController.js +120 -0
- package/dist-server/server/dashboardSupervisor.js +176 -0
- package/dist-server/server/desktopActivation.js +26 -0
- package/dist-server/server/desktopEnvironments.js +600 -0
- package/dist-server/server/desktopHostProtocol.js +17 -0
- package/dist-server/server/desktopHosts.js +117 -0
- package/dist-server/server/errors.js +12 -0
- package/dist-server/server/executionSettings.js +171 -0
- package/dist-server/server/fcm.js +247 -0
- package/dist-server/server/fcmConfiguration.js +270 -0
- package/dist-server/server/fileAccess.js +103 -0
- package/dist-server/server/fileTransfer.js +98 -0
- package/dist-server/server/githubReleases.js +73 -0
- package/dist-server/server/grokAuth.js +333 -0
- package/dist-server/server/grokCloud.js +458 -0
- package/dist-server/server/hermesBotRelay.js +117 -0
- package/dist-server/server/hermesBridge.js +245 -0
- package/dist-server/server/hostToolSettings.js +60 -0
- package/dist-server/server/imageManagement.js +55 -0
- package/dist-server/server/index.js +132 -0
- package/dist-server/server/leases.js +69 -0
- package/dist-server/server/localAuth.js +737 -0
- package/dist-server/server/localVm.js +358 -0
- package/dist-server/server/loopbackAuthorization.js +58 -0
- package/dist-server/server/managedBrowserTools.js +16 -0
- package/dist-server/server/managedBrowsers.js +735 -0
- package/dist-server/server/notificationText.js +125 -0
- package/dist-server/server/openVikingConfiguration.js +222 -0
- package/dist-server/server/openVikingMemoryProvider.js +279 -0
- package/dist-server/server/openVikingService.js +177 -0
- package/dist-server/server/openVikingSessionSync.js +286 -0
- package/dist-server/server/pairing.js +342 -0
- package/dist-server/server/profileIdentities.js +103 -0
- package/dist-server/server/pushCoordinator.js +1422 -0
- package/dist-server/server/pushEventAdapter.js +31 -0
- package/dist-server/server/pushEvents.js +1218 -0
- package/dist-server/server/realtimeApi.js +330 -0
- package/dist-server/server/realtimeBroker.js +835 -0
- package/dist-server/server/realtimeProtocol.js +353 -0
- package/dist-server/server/realtimeReceipts.js +60 -0
- package/dist-server/server/releases.js +46 -0
- package/dist-server/server/routes.js +2156 -0
- package/dist-server/server/runnerHub.js +687 -0
- package/dist-server/server/security.js +196 -0
- package/dist-server/server/serverIdentity.js +31 -0
- package/dist-server/server/serviceInstance.js +178 -0
- package/dist-server/server/sessionWorkingDirectory.js +39 -0
- package/dist-server/server/sharedComputers.js +221 -0
- package/dist-server/server/subaccountAccess.js +28 -0
- package/dist-server/server/taskCoordinator.js +580 -0
- package/dist-server/server/toolOperationJournal.js +81 -0
- package/dist-server/server/updateManager.js +340 -0
- package/dist-server/server/uploads.js +265 -0
- package/dist-server/server/upstream.js +375 -0
- package/dist-server/server/upstreamReadCache.js +133 -0
- package/dist-server/server/vmComputer.js +96 -0
- package/dist-server/server/websocket.js +753 -0
- package/dist-server/server/workspaceAssets.js +192 -0
- package/dist-server/server/workspaceCollaboration.js +224 -0
- package/dist-server/server/workspaceDiscussion.js +23 -0
- package/dist-server/server/workspaceEnvironment.js +43 -0
- package/dist-server/server/workspaceGateway.js +509 -0
- package/dist-server/server/workspaceInspector.js +47 -0
- package/dist-server/server/workspaceKnowledge.js +557 -0
- package/dist-server/server/workspaceKnowledgeRoutes.js +78 -0
- package/dist-server/server/workspaceKnowledgeTools.js +105 -0
- package/dist-server/server/workspaceMemoryContext.js +34 -0
- package/dist-server/server/workspaceMemorySynthesis.js +201 -0
- package/dist-server/server/workspaceMentions.js +31 -0
- package/dist-server/server/workspacePairedNode.js +166 -0
- package/dist-server/server/workspacePrompt.js +93 -0
- package/dist-server/server/workspaceRelay.js +90 -0
- package/dist-server/server/workspaceRemoteAgents.js +191 -0
- package/dist-server/server/workspaceRoutes.js +703 -0
- package/dist-server/server/workspaceRoutineTools.js +109 -0
- package/dist-server/server/workspaceRoutines.js +163 -0
- package/dist-server/server/workspaceRuntime.js +1363 -0
- package/dist-server/server/workspaceScheduler.js +592 -0
- package/dist-server/server/workspaceStore.js +1220 -0
- package/dist-server/server/workspaceSync.js +129 -0
- package/dist-server/server/workspaceTeamTools.js +312 -0
- package/dist-server/server/workspaceToolLease.js +280 -0
- package/dist-server/shared/agentIdentity.js +90 -0
- package/dist-server/shared/agentTasks.js +1 -0
- package/dist-server/shared/botEnvironment.js +28 -0
- package/dist-server/shared/botModelSettings.js +3 -0
- package/dist-server/shared/chatTools.js +32 -0
- package/dist-server/shared/chatTranscript.js +50 -0
- package/dist-server/shared/composeDesktops.js +1 -0
- package/dist-server/shared/computerControl.js +1 -0
- package/dist-server/shared/desktopEnvironment.js +1 -0
- package/dist-server/shared/desktopHost.js +1 -0
- package/dist-server/shared/executionEnvironment.js +1 -0
- package/dist-server/shared/fileTransfer.js +5 -0
- package/dist-server/shared/fileTransferEndpoint.mjs +133 -0
- package/dist-server/shared/grokAuth.js +1 -0
- package/dist-server/shared/hermesBridge.js +1 -0
- package/dist-server/shared/hostPaths.mjs +22 -0
- package/dist-server/shared/imageManagement.js +1 -0
- package/dist-server/shared/index.js +1 -0
- package/dist-server/shared/localVm.js +9 -0
- package/dist-server/shared/managedBrowser.js +1 -0
- package/dist-server/shared/messageFiles.js +90 -0
- package/dist-server/shared/openVikingSync.js +1 -0
- package/dist-server/shared/runner.js +2 -0
- package/dist-server/shared/serverFiles.js +55 -0
- package/dist-server/shared/serverIdentity.js +1 -0
- package/dist-server/shared/sse.js +47 -0
- package/dist-server/shared/types.js +8 -0
- package/dist-server/shared/workspace.js +61 -0
- package/dist-server/shared/workspaceKnowledge.js +1 -0
- package/dist-server/shared/workspaceLifecycle.js +1 -0
- package/dist-server/shared/workspaceMessagePatch.js +63 -0
- package/dist-server/shared/workspacePanels.js +1 -0
- package/dist-server/shared/workspacePlugins.js +1 -0
- package/licenses/LaoA-GrokBot/LICENSE +21 -0
- package/licenses/OpenMausBot/LICENSE +202 -0
- package/licenses/OpenMausBot/NOTICE +6 -0
- package/package.json +122 -0
- package/release.json +6 -0
|
@@ -0,0 +1,1651 @@
|
|
|
1
|
+
import { ChatTranscriptStore } from './chatTranscriptStore.js';
|
|
2
|
+
import { isFinalChatResult } from './chatUnread.js';
|
|
3
|
+
import { HttpError } from './errors.js';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
+
import { chmodSync, createReadStream, existsSync, mkdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
8
|
+
function object(value) {
|
|
9
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
10
|
+
? value : undefined;
|
|
11
|
+
}
|
|
12
|
+
function parseResponse(response) {
|
|
13
|
+
if (response.status < 200 || response.status >= 300)
|
|
14
|
+
return undefined;
|
|
15
|
+
try {
|
|
16
|
+
return object(JSON.parse(response.body.toString('utf8')));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function headerRecord(headers) {
|
|
23
|
+
return JSON.stringify(Object.fromEntries([...headers.entries()].filter(([name]) => name.toLowerCase() !== 'set-cookie')));
|
|
24
|
+
}
|
|
25
|
+
function responseFromRow(row) {
|
|
26
|
+
return {
|
|
27
|
+
status: Number(row.status),
|
|
28
|
+
headers: new Headers(JSON.parse(String(row.headers))),
|
|
29
|
+
body: Buffer.from(String(row.body), 'base64'),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function profileOf(value, fallback = '') {
|
|
33
|
+
return String(value.profile ?? value.profile_name ?? fallback).trim();
|
|
34
|
+
}
|
|
35
|
+
function sessionIDOf(value) {
|
|
36
|
+
return String(value.id ?? value.session_id ?? value.sessionId ?? '').trim();
|
|
37
|
+
}
|
|
38
|
+
function sessionSource(value) {
|
|
39
|
+
return String(value.source ?? '').trim();
|
|
40
|
+
}
|
|
41
|
+
function sessionTitle(value) {
|
|
42
|
+
return String(value.title ?? '').trim();
|
|
43
|
+
}
|
|
44
|
+
// Hermes uses Unix seconds; local route registration uses milliseconds. Keep
|
|
45
|
+
// the public summary in seconds so Web and iOS compare the same activity time.
|
|
46
|
+
function timestampSeconds(value) {
|
|
47
|
+
if (typeof value !== 'number' && typeof value !== 'string')
|
|
48
|
+
return undefined;
|
|
49
|
+
const numeric = Number(value);
|
|
50
|
+
const seconds = Number.isFinite(numeric)
|
|
51
|
+
? numeric > 10_000_000_000 ? numeric / 1_000 : numeric
|
|
52
|
+
: typeof value === 'string' ? Date.parse(value) / 1_000 : NaN;
|
|
53
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds : undefined;
|
|
54
|
+
}
|
|
55
|
+
function firstTimestamp(value, keys) {
|
|
56
|
+
for (const key of keys) {
|
|
57
|
+
const timestamp = timestampSeconds(value[key]);
|
|
58
|
+
if (timestamp !== undefined)
|
|
59
|
+
return timestamp;
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
const START_TIME_KEYS = ['started_at', 'startedAt', 'session_started', 'created_at', 'createdAt'];
|
|
64
|
+
const ACTIVITY_TIME_KEYS = ['last_active', 'last_active_at', 'last_activity_at', 'lastActive', 'updated_at', 'updatedAt'];
|
|
65
|
+
function mergeSessionMetadata(previous, incoming) {
|
|
66
|
+
const summary = { ...previous, ...incoming };
|
|
67
|
+
// A messages response can carry title/model metadata, but its envelope is
|
|
68
|
+
// not a replacement for the session detail.
|
|
69
|
+
delete summary.messages;
|
|
70
|
+
delete summary.pagination;
|
|
71
|
+
const started = firstTimestamp(incoming, START_TIME_KEYS) ?? firstTimestamp(previous, START_TIME_KEYS);
|
|
72
|
+
const activity = firstTimestamp(incoming, ACTIVITY_TIME_KEYS) ?? firstTimestamp(previous, ACTIVITY_TIME_KEYS);
|
|
73
|
+
if (started !== undefined)
|
|
74
|
+
summary.started_at = started;
|
|
75
|
+
if (activity !== undefined)
|
|
76
|
+
summary.last_active = activity;
|
|
77
|
+
return summary;
|
|
78
|
+
}
|
|
79
|
+
function messageTimeBounds(messages) {
|
|
80
|
+
let first;
|
|
81
|
+
let last;
|
|
82
|
+
for (const message of messages) {
|
|
83
|
+
const time = firstTimestamp(message, ['timestamp', 'created_at', 'createdAt']);
|
|
84
|
+
if (time === undefined)
|
|
85
|
+
continue;
|
|
86
|
+
first = Math.min(first ?? time, time);
|
|
87
|
+
last = Math.max(last ?? time, time);
|
|
88
|
+
}
|
|
89
|
+
return { first, last };
|
|
90
|
+
}
|
|
91
|
+
function isPlaceholderTitle(value) {
|
|
92
|
+
return new Set([
|
|
93
|
+
'', '新对话', '新会话', '未命名对话', '未命名会话', 'new conversation', 'new session', 'untitled',
|
|
94
|
+
]).has(value.trim().toLowerCase());
|
|
95
|
+
}
|
|
96
|
+
function messageID(value, fallback) {
|
|
97
|
+
const id = String(value.id ?? value.row_id ?? value.message_id ?? value.messageId ?? '').trim();
|
|
98
|
+
return id || createHash('sha256').update(JSON.stringify(value) + fallback).digest('hex');
|
|
99
|
+
}
|
|
100
|
+
function bool(value) {
|
|
101
|
+
return value === true || value === 1 || value === '1' || value === 'true';
|
|
102
|
+
}
|
|
103
|
+
const PATH_PATTERN = /(?:file:\/\/)?(\/(?:Users|private|var|tmp)\/[^\s<>'"`)\]}]+\.[A-Za-z0-9]{1,12})/g;
|
|
104
|
+
function referencedPaths(value, output = new Set()) {
|
|
105
|
+
if (typeof value === 'string') {
|
|
106
|
+
for (const match of value.matchAll(PATH_PATTERN))
|
|
107
|
+
output.add(match[1]);
|
|
108
|
+
}
|
|
109
|
+
else if (Array.isArray(value)) {
|
|
110
|
+
for (const child of value)
|
|
111
|
+
referencedPaths(child, output);
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
const record = object(value);
|
|
115
|
+
if (record)
|
|
116
|
+
for (const child of Object.values(record))
|
|
117
|
+
referencedPaths(child, output);
|
|
118
|
+
}
|
|
119
|
+
return output;
|
|
120
|
+
}
|
|
121
|
+
export class ChatCacheStore {
|
|
122
|
+
synchronizingHistory = false;
|
|
123
|
+
db;
|
|
124
|
+
assetsRoot;
|
|
125
|
+
transcripts;
|
|
126
|
+
closed = false;
|
|
127
|
+
get isClosed() { return this.closed; }
|
|
128
|
+
constructor(home, legacySingleUserID) {
|
|
129
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
130
|
+
const path = join(home, 'chat-cache.sqlite3');
|
|
131
|
+
this.db = new DatabaseSync(path);
|
|
132
|
+
chmodSync(path, 0o600);
|
|
133
|
+
this.assetsRoot = join(home, 'chat-cache-assets');
|
|
134
|
+
mkdirSync(this.assetsRoot, { recursive: true, mode: 0o700 });
|
|
135
|
+
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
|
|
136
|
+
CREATE TABLE IF NOT EXISTS chat_sessions(
|
|
137
|
+
owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
|
|
138
|
+
runtime_id TEXT, source TEXT NOT NULL, data TEXT NOT NULL, authoritative_title TEXT,
|
|
139
|
+
authoritative_title_at INTEGER NOT NULL DEFAULT 0,
|
|
140
|
+
owned_at INTEGER, ownership_evidence TEXT,
|
|
141
|
+
sync_state TEXT NOT NULL DEFAULT 'stale', complete INTEGER NOT NULL DEFAULT 0,
|
|
142
|
+
last_event_seq INTEGER NOT NULL DEFAULT 0, last_synced_at INTEGER NOT NULL,
|
|
143
|
+
PRIMARY KEY(owner,profile,session_id));
|
|
144
|
+
CREATE TABLE IF NOT EXISTS chat_messages(
|
|
145
|
+
owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
|
|
146
|
+
message_id TEXT NOT NULL, position INTEGER NOT NULL, data TEXT NOT NULL,
|
|
147
|
+
content_hash TEXT NOT NULL, PRIMARY KEY(owner,profile,session_id,message_id));
|
|
148
|
+
CREATE INDEX IF NOT EXISTS chat_messages_position ON chat_messages(owner,profile,session_id,position);
|
|
149
|
+
CREATE TABLE IF NOT EXISTS chat_events(
|
|
150
|
+
owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
|
|
151
|
+
event_seq INTEGER NOT NULL, event_type TEXT NOT NULL, payload TEXT NOT NULL,
|
|
152
|
+
received_at INTEGER NOT NULL, PRIMARY KEY(owner,profile,session_id,event_seq,event_type));
|
|
153
|
+
CREATE TABLE IF NOT EXISTS chat_attachments(
|
|
154
|
+
owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
|
|
155
|
+
source_path TEXT NOT NULL, sha256 TEXT, mime_type TEXT, size INTEGER,
|
|
156
|
+
local_path TEXT, state TEXT NOT NULL DEFAULT 'pending', updated_at INTEGER NOT NULL,
|
|
157
|
+
PRIMARY KEY(owner,profile,session_id,source_path));
|
|
158
|
+
CREATE INDEX IF NOT EXISTS chat_attachments_source ON chat_attachments(owner,source_path);
|
|
159
|
+
CREATE TABLE IF NOT EXISTS chat_sync_cursors(
|
|
160
|
+
owner TEXT NOT NULL, profile TEXT NOT NULL, generation TEXT,
|
|
161
|
+
event_cursor INTEGER NOT NULL DEFAULT 0, sync_state TEXT NOT NULL DEFAULT 'stale',
|
|
162
|
+
last_synced_at INTEGER NOT NULL, PRIMARY KEY(owner,profile));
|
|
163
|
+
CREATE TABLE IF NOT EXISTS chat_snapshots(
|
|
164
|
+
owner TEXT NOT NULL, cache_key TEXT NOT NULL, kind TEXT NOT NULL,
|
|
165
|
+
profile TEXT NOT NULL, session_id TEXT, status INTEGER NOT NULL,
|
|
166
|
+
headers TEXT NOT NULL, body TEXT NOT NULL, sync_state TEXT NOT NULL,
|
|
167
|
+
saved_at INTEGER NOT NULL, PRIMARY KEY(owner,cache_key));
|
|
168
|
+
CREATE TABLE IF NOT EXISTS chat_meta(
|
|
169
|
+
key TEXT PRIMARY KEY, value TEXT NOT NULL);`);
|
|
170
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS chat_local_state(
|
|
171
|
+
owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
|
|
172
|
+
pinned INTEGER, read_count INTEGER NOT NULL DEFAULT 0,
|
|
173
|
+
assistant_id TEXT, PRIMARY KEY(owner,profile,session_id));
|
|
174
|
+
CREATE TABLE IF NOT EXISTS chat_session_aliases(owner TEXT NOT NULL,profile TEXT NOT NULL,alias_id TEXT NOT NULL,session_id TEXT NOT NULL,PRIMARY KEY(owner,profile,alias_id));
|
|
175
|
+
CREATE TABLE IF NOT EXISTS chat_recovery_jobs(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,force INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(owner,profile,session_id));
|
|
176
|
+
CREATE TABLE IF NOT EXISTS chat_event_receipts(
|
|
177
|
+
owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL, event_id TEXT NOT NULL,
|
|
178
|
+
PRIMARY KEY(owner,profile,session_id,event_id));
|
|
179
|
+
CREATE TABLE IF NOT EXISTS chat_message_identities(
|
|
180
|
+
owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
|
|
181
|
+
message_id TEXT NOT NULL, client_message_id TEXT NOT NULL,
|
|
182
|
+
PRIMARY KEY(owner,profile,session_id,message_id),
|
|
183
|
+
UNIQUE(owner,profile,session_id,client_message_id));`);
|
|
184
|
+
const localColumns = this.db.prepare('PRAGMA table_info(chat_local_state)').all();
|
|
185
|
+
for (const [name, type] of [['title', 'TEXT'], ['archived', 'INTEGER'], ['read_initialized', 'INTEGER NOT NULL DEFAULT 0'], ['final_read_count', 'INTEGER']]) {
|
|
186
|
+
if (!localColumns.some(c => c.name === name))
|
|
187
|
+
this.db.exec(`ALTER TABLE chat_local_state ADD COLUMN ${name} ${type}`);
|
|
188
|
+
}
|
|
189
|
+
const sessionColumns = this.db.prepare('PRAGMA table_info(chat_sessions)').all();
|
|
190
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
191
|
+
try {
|
|
192
|
+
if (!sessionColumns.some(column => column.name === 'sync_revision')) {
|
|
193
|
+
this.db.exec('ALTER TABLE chat_sessions ADD COLUMN sync_revision INTEGER NOT NULL DEFAULT 0');
|
|
194
|
+
}
|
|
195
|
+
if (!sessionColumns.some(column => column.name === 'message_total')) {
|
|
196
|
+
this.db.exec('ALTER TABLE chat_sessions ADD COLUMN message_total INTEGER');
|
|
197
|
+
}
|
|
198
|
+
if (!sessionColumns.some(column => column.name === 'metadata_complete')) {
|
|
199
|
+
this.db.exec('ALTER TABLE chat_sessions ADD COLUMN metadata_complete INTEGER NOT NULL DEFAULT 0');
|
|
200
|
+
this.db.exec("UPDATE chat_sessions SET metadata_complete=1 WHERE json_valid(data) AND (json_type(data,'$.message_count') IS NOT NULL OR json_type(data,'$.model') IS NOT NULL)");
|
|
201
|
+
}
|
|
202
|
+
if (!sessionColumns.some(column => column.name === 'authoritative_title')) {
|
|
203
|
+
this.db.exec('ALTER TABLE chat_sessions ADD COLUMN authoritative_title TEXT');
|
|
204
|
+
}
|
|
205
|
+
if (!sessionColumns.some(column => column.name === 'authoritative_title_at')) {
|
|
206
|
+
this.db.exec('ALTER TABLE chat_sessions ADD COLUMN authoritative_title_at INTEGER NOT NULL DEFAULT 0');
|
|
207
|
+
}
|
|
208
|
+
if (!sessionColumns.some(column => column.name === 'owned_at')) {
|
|
209
|
+
this.db.exec('ALTER TABLE chat_sessions ADD COLUMN owned_at INTEGER');
|
|
210
|
+
}
|
|
211
|
+
if (!sessionColumns.some(column => column.name === 'ownership_evidence')) {
|
|
212
|
+
this.db.exec('ALTER TABLE chat_sessions ADD COLUMN ownership_evidence TEXT');
|
|
213
|
+
}
|
|
214
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS chat_sessions_owned
|
|
215
|
+
ON chat_sessions(owner,profile,owned_at,last_synced_at)`);
|
|
216
|
+
const ownershipMigration = this.db.prepare("SELECT value FROM chat_meta WHERE key='ownership-registry-v1'").get();
|
|
217
|
+
if (!ownershipMigration) {
|
|
218
|
+
// A single cached owner is trusted only when the persisted local user
|
|
219
|
+
// database independently confirms the same sole identity.
|
|
220
|
+
const legacyOwners = this.db.prepare('SELECT DISTINCT owner FROM chat_sessions ORDER BY owner').all();
|
|
221
|
+
if (legacyOwners.length === 1 && legacyOwners[0].owner === legacySingleUserID) {
|
|
222
|
+
this.db.exec(`UPDATE chat_sessions SET
|
|
223
|
+
owned_at=COALESCE(owned_at,last_synced_at),
|
|
224
|
+
ownership_evidence=COALESCE(ownership_evidence,'legacy-single-user')`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
// Recover interrupted/new-schema writes only from explicit command proof.
|
|
228
|
+
this.db.exec(`UPDATE chat_sessions SET
|
|
229
|
+
owned_at=COALESCE(owned_at,(
|
|
230
|
+
SELECT MIN(chat_events.received_at) FROM chat_events
|
|
231
|
+
WHERE chat_events.owner=chat_sessions.owner
|
|
232
|
+
AND chat_events.profile=chat_sessions.profile
|
|
233
|
+
AND chat_events.session_id=chat_sessions.session_id
|
|
234
|
+
AND chat_events.event_type IN ('command:session.create','command:session.branch')
|
|
235
|
+
)),
|
|
236
|
+
ownership_evidence=COALESCE(ownership_evidence,'command-migration')
|
|
237
|
+
WHERE EXISTS (
|
|
238
|
+
SELECT 1 FROM chat_events
|
|
239
|
+
WHERE chat_events.owner=chat_sessions.owner
|
|
240
|
+
AND chat_events.profile=chat_sessions.profile
|
|
241
|
+
AND chat_events.session_id=chat_sessions.session_id
|
|
242
|
+
AND chat_events.event_type IN ('command:session.create','command:session.branch')
|
|
243
|
+
)`);
|
|
244
|
+
const legacyTitles = this.db.prepare(`SELECT owner,profile,session_id,data FROM chat_sessions
|
|
245
|
+
WHERE authoritative_title IS NULL`).all();
|
|
246
|
+
const backfillTitle = this.db.prepare(`UPDATE chat_sessions SET authoritative_title=?
|
|
247
|
+
WHERE owner=? AND profile=? AND session_id=? AND authoritative_title IS NULL`);
|
|
248
|
+
for (const row of legacyTitles) {
|
|
249
|
+
let summary = {};
|
|
250
|
+
try {
|
|
251
|
+
summary = object(JSON.parse(row.data)) ?? {};
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const title = sessionTitle(summary);
|
|
257
|
+
if (!isPlaceholderTitle(title))
|
|
258
|
+
backfillTitle.run(title, row.owner, row.profile, row.session_id);
|
|
259
|
+
}
|
|
260
|
+
if (!this.db.prepare("SELECT 1 FROM chat_meta WHERE key='session-activity-v1'").get()) {
|
|
261
|
+
const rows = this.db.prepare(`SELECT owner,profile,session_id,source,data,owned_at,message_total
|
|
262
|
+
FROM chat_sessions WHERE owned_at IS NOT NULL`).all();
|
|
263
|
+
const update = this.db.prepare(`UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?`);
|
|
264
|
+
for (const row of rows) {
|
|
265
|
+
let stored;
|
|
266
|
+
try {
|
|
267
|
+
stored = object(JSON.parse(row.data)) ?? {};
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
const summary = mergeSessionMetadata({}, stored);
|
|
273
|
+
if (Array.isArray(stored.messages) || !firstTimestamp(summary, START_TIME_KEYS)
|
|
274
|
+
|| !firstTimestamp(summary, ACTIVITY_TIME_KEYS)) {
|
|
275
|
+
const messages = this.db.prepare(`SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=?`)
|
|
276
|
+
.all(row.owner, row.profile, row.session_id);
|
|
277
|
+
const bounds = messageTimeBounds(messages.flatMap(message => {
|
|
278
|
+
try {
|
|
279
|
+
return [object(JSON.parse(message.data)) ?? {}];
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
return [];
|
|
283
|
+
}
|
|
284
|
+
}));
|
|
285
|
+
summary.started_at = firstTimestamp(summary, START_TIME_KEYS) ?? bounds.first ?? timestampSeconds(row.owned_at);
|
|
286
|
+
summary.last_active = Math.max(firstTimestamp(summary, ACTIVITY_TIME_KEYS) ?? 0, bounds.last ?? 0) || summary.started_at;
|
|
287
|
+
if (row.message_total !== null)
|
|
288
|
+
summary.message_count = row.message_total;
|
|
289
|
+
}
|
|
290
|
+
summary.id = row.session_id;
|
|
291
|
+
summary.profile = row.profile;
|
|
292
|
+
summary.source = sessionSource(summary) || row.source;
|
|
293
|
+
update.run(JSON.stringify(summary), row.owner, row.profile, row.session_id);
|
|
294
|
+
}
|
|
295
|
+
this.db.prepare("INSERT INTO chat_meta(key,value) VALUES('session-activity-v1','complete')").run();
|
|
296
|
+
}
|
|
297
|
+
// List bodies written before ownership became an explicit projection do
|
|
298
|
+
// not carry `owned` and may have been filtered by `source`. Rebuild them on
|
|
299
|
+
// first use after every restart instead of serving a semantically old page.
|
|
300
|
+
this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE kind='list'").run();
|
|
301
|
+
this.db.prepare(`INSERT INTO chat_meta(key,value) VALUES('ownership-registry-v1','complete')
|
|
302
|
+
ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run();
|
|
303
|
+
this.db.prepare(`INSERT OR IGNORE INTO chat_local_state(owner,profile,session_id)
|
|
304
|
+
SELECT owner,profile,session_id FROM chat_sessions WHERE owned_at IS NOT NULL`).run();
|
|
305
|
+
this.db.exec('COMMIT');
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
this.db.exec('ROLLBACK');
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
this.transcripts = new ChatTranscriptStore(this.db, (owner, profile, id, rows) => this.userMessageIdentities(owner, profile, id, rows, false));
|
|
312
|
+
}
|
|
313
|
+
close() { this.closed = true; this.transcripts.close(); this.db.close(); }
|
|
314
|
+
stats() {
|
|
315
|
+
const count = (table) => Number(this.db.prepare(`SELECT COUNT(*) count FROM ${table}`).get().count);
|
|
316
|
+
const bytes = Number(this.db.prepare(`SELECT COALESCE(SUM(size),0) bytes FROM chat_attachments WHERE state='cached'`).get().bytes);
|
|
317
|
+
return {
|
|
318
|
+
sessions: Number(this.db.prepare(`SELECT COUNT(*) count FROM chat_sessions
|
|
319
|
+
WHERE owned_at IS NOT NULL`).get().count),
|
|
320
|
+
messages: count('chat_messages'),
|
|
321
|
+
events: count('chat_events'),
|
|
322
|
+
attachments: count('chat_attachments'),
|
|
323
|
+
attachmentBytes: bytes,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
snapshot(owner, key) {
|
|
327
|
+
const row = this.db.prepare('SELECT status,headers,body,sync_state FROM chat_snapshots WHERE owner=? AND cache_key=?')
|
|
328
|
+
.get(owner, key);
|
|
329
|
+
return row ? { response: responseFromRow(row), state: String(row.sync_state) } : undefined;
|
|
330
|
+
}
|
|
331
|
+
localList(owner, profile, page) {
|
|
332
|
+
const offset = Math.max(0, Math.trunc(page.offset ?? 0)), limit = Math.max(1, Math.min(200, Math.trunc(page.limit ?? 100)));
|
|
333
|
+
const where = `s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)
|
|
334
|
+
AND s.source NOT IN ('cron','ios_group','yaoyao_workspace')
|
|
335
|
+
AND (?='include' OR COALESCE(l.archived,json_extract(s.data,'$.archived'),json_extract(s.data,'$.is_archived'),0)=CASE WHEN ?='only' THEN 1 ELSE 0 END)`;
|
|
336
|
+
const args = [owner, profile, profile, page.archived ?? 'exclude', page.archived ?? 'exclude'];
|
|
337
|
+
const total = Number(this.db.prepare(`SELECT count(*) n FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id) WHERE ${where}`).get(...args).n);
|
|
338
|
+
const rows = this.db.prepare(`SELECT s.profile,s.session_id,s.data,s.sync_state,s.complete,l.title local_title,
|
|
339
|
+
COALESCE(l.pinned,json_extract(s.data,'$.pinned'),json_extract(s.data,'$.is_pinned'),0) pin
|
|
340
|
+
FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id) WHERE ${where}
|
|
341
|
+
ORDER BY pin DESC, COALESCE(json_extract(s.data,'$.last_active'),0) DESC, s.session_id
|
|
342
|
+
LIMIT ? OFFSET ?`).all(...args, limit, offset);
|
|
343
|
+
const unread = new Map(this.unread(owner, profile).sessions.map(row => [JSON.stringify([row.profile, row.session_id]), row.final_unread_count]));
|
|
344
|
+
return { status: 200, headers: new Headers({ 'content-type': 'application/json' }), body: Buffer.from(JSON.stringify({
|
|
345
|
+
sessions: rows.map(r => ({ ...JSON.parse(r.data), ...(r.local_title != null ? { title: r.local_title } : {}), id: r.session_id, profile: r.profile, owned: true, pinned: !!r.pin,
|
|
346
|
+
final_unread_count: unread.get(JSON.stringify([r.profile, r.session_id])) ?? 0,
|
|
347
|
+
sync_state: r.sync_state, history_complete: !!r.complete })), total, offset, limit,
|
|
348
|
+
sync_state: this.needsListMetadata(owner, profile) ? 'syncing' : 'current'
|
|
349
|
+
})) };
|
|
350
|
+
}
|
|
351
|
+
missingSessions(owner, profile) {
|
|
352
|
+
return this.db.prepare(`SELECT profile,session_id FROM chat_sessions WHERE owner=? AND owned_at IS NOT NULL
|
|
353
|
+
AND (?='' OR profile=?) AND (metadata_complete=0 OR complete=0) LIMIT 100`)
|
|
354
|
+
.all(owner, profile, profile);
|
|
355
|
+
}
|
|
356
|
+
pins(owner, profile) {
|
|
357
|
+
return this.db.prepare(`SELECT s.session_id FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id)
|
|
358
|
+
WHERE s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)
|
|
359
|
+
AND COALESCE(l.pinned,json_extract(s.data,'$.pinned'),json_extract(s.data,'$.is_pinned'),0)=1 ORDER BY s.last_synced_at DESC`)
|
|
360
|
+
.all(owner, profile, profile).map(r => r.session_id);
|
|
361
|
+
}
|
|
362
|
+
unread(owner, profile) {
|
|
363
|
+
const sessions = this.db.prepare(`SELECT s.profile,s.session_id,COALESCE(s.message_total,0) message_count,
|
|
364
|
+
CASE WHEN COALESCE(l.read_initialized,0)=1 THEN COALESCE(l.final_read_count,l.read_count) ELSE COALESCE(s.message_total,0) END final_read_count,
|
|
365
|
+
CASE WHEN COALESCE(l.read_initialized,0)=1 THEN l.read_count ELSE COALESCE(s.message_total,0) END read_message_count FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id)
|
|
366
|
+
WHERE s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)`).all(owner, profile, profile)
|
|
367
|
+
.map(({ final_read_count, ...r }) => {
|
|
368
|
+
this.transcripts.seed(owner, r.profile, r.session_id);
|
|
369
|
+
r.message_count = this.transcripts.total(owner, r.profile, r.session_id);
|
|
370
|
+
return { ...r, updated_at: Date.now(), unread_count: Math.max(0, r.message_count - r.read_message_count),
|
|
371
|
+
final_unread_count: this.transcripts.unread(owner, r.profile, r.session_id) };
|
|
372
|
+
});
|
|
373
|
+
return { profile, supported: true, total_unread: sessions.reduce((n, r) => n + r.unread_count, 0), sessions };
|
|
374
|
+
}
|
|
375
|
+
markRead(owner, profile, id, count) {
|
|
376
|
+
id = this.canonicalSessionID(owner, profile, id);
|
|
377
|
+
this.requireOwned(owner, profile, id);
|
|
378
|
+
this.transcripts.seed(owner, profile, id);
|
|
379
|
+
const total = this.transcripts.total(owner, profile, id);
|
|
380
|
+
const read = Math.max(0, Math.min(total, count ?? total));
|
|
381
|
+
// Reading a streaming placeholder must not consume its future final answer.
|
|
382
|
+
// Keep the original cursor untouched for existing consumers.
|
|
383
|
+
const pending = this.db.prepare(`SELECT MIN(position) position FROM chat_messages
|
|
384
|
+
WHERE owner=? AND profile=? AND session_id=? AND position<?
|
|
385
|
+
AND message_id=(SELECT assistant_id FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?)
|
|
386
|
+
AND json_extract(data,'$.role')='assistant' AND json_extract(data,'$.status')='streaming'`)
|
|
387
|
+
.get(owner, profile, id, read, owner, profile, id);
|
|
388
|
+
const finalRead = pending.position ?? read;
|
|
389
|
+
this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,read_count,final_read_count,read_initialized) VALUES(?,?,?,?,?,1)
|
|
390
|
+
ON CONFLICT(owner,profile,session_id) DO UPDATE SET read_count=MAX(read_count,excluded.read_count),
|
|
391
|
+
final_read_count=MAX(COALESCE(final_read_count,read_count),excluded.final_read_count),read_initialized=1`).run(owner, profile, id, read, finalRead);
|
|
392
|
+
this.transcripts.seed(owner, profile, id);
|
|
393
|
+
this.transcripts.markRead(owner, profile, id, count ?? Infinity);
|
|
394
|
+
return this.unread(owner, profile).sessions.find(r => r.session_id === id);
|
|
395
|
+
}
|
|
396
|
+
requireOwned(owner, profile, id) {
|
|
397
|
+
if (!this.ownsSession(owner, profile, id))
|
|
398
|
+
throw new HttpError(404, '会话不存在', 'session_not_found');
|
|
399
|
+
}
|
|
400
|
+
patchLocal(owner, profile, id, patch) {
|
|
401
|
+
id = this.canonicalSessionID(owner, profile, id);
|
|
402
|
+
this.requireOwned(owner, profile, id);
|
|
403
|
+
this.db.exec('SAVEPOINT local_chat_patch');
|
|
404
|
+
try {
|
|
405
|
+
if (typeof patch.pinned === 'boolean')
|
|
406
|
+
this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,pinned) VALUES(?,?,?,?)
|
|
407
|
+
ON CONFLICT(owner,profile,session_id) DO UPDATE SET pinned=excluded.pinned`).run(owner, profile, id, patch.pinned ? 1 : 0);
|
|
408
|
+
const row = this.localDetail(owner, profile, id);
|
|
409
|
+
const data = { ...JSON.parse(row.response.body.toString()), ...patch };
|
|
410
|
+
this.db.prepare("UPDATE chat_sessions SET data=?,sync_state=CASE WHEN sync_state='gap' THEN sync_state WHEN complete=1 THEN 'current' ELSE sync_state END WHERE owner=? AND profile=? AND session_id=?").run(JSON.stringify(data), owner, profile, id);
|
|
411
|
+
for (const key of ['title', 'archived'])
|
|
412
|
+
if (patch[key] !== undefined) {
|
|
413
|
+
const value = key === 'archived' ? (patch[key] ? 1 : 0) : String(patch[key]);
|
|
414
|
+
this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,${key}) VALUES(?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET ${key}=excluded.${key}`).run(owner, profile, id, value);
|
|
415
|
+
}
|
|
416
|
+
if (typeof patch.title === 'string')
|
|
417
|
+
this.recordAuthoritativeTitle(owner, profile, id, patch.title);
|
|
418
|
+
this.db.prepare("UPDATE chat_sessions SET sync_state=CASE WHEN complete=1 THEN 'current' ELSE sync_state END WHERE owner=? AND profile=? AND session_id=?").run(owner, profile, id);
|
|
419
|
+
this.transcripts.sessionChanged(owner, profile, id, { eventType: 'session.info', payload: data });
|
|
420
|
+
this.db.exec('RELEASE local_chat_patch');
|
|
421
|
+
}
|
|
422
|
+
catch (e) {
|
|
423
|
+
this.db.exec('ROLLBACK TO local_chat_patch; RELEASE local_chat_patch');
|
|
424
|
+
throw e;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
projectedMessageID(owner, profile, id) {
|
|
428
|
+
return this.transcripts.head(owner, profile, id).current;
|
|
429
|
+
}
|
|
430
|
+
updateTranscriptSummary(owner, profile, id) {
|
|
431
|
+
const total = this.transcripts.total(owner, profile, id);
|
|
432
|
+
const lastRow = this.db.prepare('SELECT data FROM chat_transcript_messages WHERE owner=? AND profile=? AND session_id=? AND deleted=0 ORDER BY seq DESC LIMIT 1').get(owner, profile, id);
|
|
433
|
+
const last = lastRow ? JSON.parse(String(lastRow.data)) : undefined;
|
|
434
|
+
const row = this.db.prepare('SELECT data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?').get(owner, profile, id);
|
|
435
|
+
if (!row)
|
|
436
|
+
return;
|
|
437
|
+
const data = JSON.parse(String(row.data));
|
|
438
|
+
data.message_count = total;
|
|
439
|
+
if (last) {
|
|
440
|
+
data.last_active = last.timestamp;
|
|
441
|
+
if (typeof last.content === 'string' && last.content.trim())
|
|
442
|
+
data.preview = last.content.slice(0, 160);
|
|
443
|
+
}
|
|
444
|
+
this.db.prepare("UPDATE chat_sessions SET data=?,sync_state=CASE WHEN sync_state='gap' THEN sync_state WHEN complete=1 THEN 'current' ELSE sync_state END WHERE owner=? AND profile=? AND session_id=?").run(JSON.stringify(data), owner, profile, id);
|
|
445
|
+
const currentID = this.transcripts.head(owner, profile, id).current;
|
|
446
|
+
const current = currentID ? this.transcripts.message(owner, profile, id, currentID) : undefined;
|
|
447
|
+
for (const message of [last, current].filter(Boolean))
|
|
448
|
+
for (const path of referencedPaths(message))
|
|
449
|
+
this.db.prepare(`INSERT OR IGNORE INTO chat_attachments(owner,profile,session_id,source_path,state,updated_at) VALUES(?,?,?,?,'pending',?)`).run(owner, profile, id, path, Date.now());
|
|
450
|
+
}
|
|
451
|
+
needsListMetadata(owner, profile) {
|
|
452
|
+
return Boolean(this.db.prepare(`SELECT 1 FROM chat_sessions WHERE owner=? AND owned_at IS NOT NULL
|
|
453
|
+
AND (?='' OR profile=?) AND metadata_complete=0 LIMIT 1`).get(owner, profile, profile));
|
|
454
|
+
}
|
|
455
|
+
localDetail(owner, profile, sessionID) {
|
|
456
|
+
const row = this.db.prepare(`SELECT data,sync_state FROM chat_sessions
|
|
457
|
+
WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`)
|
|
458
|
+
.get(owner, profile, sessionID);
|
|
459
|
+
if (!row)
|
|
460
|
+
return undefined;
|
|
461
|
+
const local = this.db.prepare('SELECT title,archived,pinned FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner, profile, sessionID);
|
|
462
|
+
return { response: { status: 200, headers: new Headers({ 'content-type': 'application/json' }),
|
|
463
|
+
body: Buffer.from(JSON.stringify({ ...JSON.parse(row.data), ...(local?.title != null ? { title: local.title } : {}), ...(local?.archived != null ? { archived: !!local.archived } : {}), owned: true, pinned: local?.pinned != null ? !!local.pinned : bool(JSON.parse(row.data).pinned), sync_state: row.sync_state })) }, state: row.sync_state };
|
|
464
|
+
}
|
|
465
|
+
revision(owner, profile, sessionID) {
|
|
466
|
+
return Number(this.db.prepare('SELECT sync_revision FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
|
|
467
|
+
.get(owner, profile, sessionID)?.sync_revision ?? 0);
|
|
468
|
+
}
|
|
469
|
+
hasMessage(owner, profile, sessionID, message, position) {
|
|
470
|
+
const id = messageID(message, String(position));
|
|
471
|
+
const row = this.db.prepare('SELECT position FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?')
|
|
472
|
+
.get(owner, profile, sessionID, id);
|
|
473
|
+
if (row && row.position !== position)
|
|
474
|
+
throw new Error('Stored history changed; explicit refresh is required');
|
|
475
|
+
return Boolean(row);
|
|
476
|
+
}
|
|
477
|
+
putSnapshot(owner, key, kind, profile, sessionID, response, ownedList = false, requestStartedAt = Date.now(), metadataResponse = response) {
|
|
478
|
+
const payload = parseResponse(response);
|
|
479
|
+
if (!payload)
|
|
480
|
+
return false;
|
|
481
|
+
if (kind === 'list' && !ownedList)
|
|
482
|
+
return false;
|
|
483
|
+
const isOwnedChat = ownedList || this.payloadBelongsToOwnedChat(owner, profile, sessionID, payload);
|
|
484
|
+
if (!isOwnedChat)
|
|
485
|
+
return false;
|
|
486
|
+
const now = Date.now();
|
|
487
|
+
this.db.exec('SAVEPOINT chat_snapshot');
|
|
488
|
+
try {
|
|
489
|
+
// Hydrate all registered sessions from the unsliced upstream list, while
|
|
490
|
+
// persisting only the owner-filtered page as the public response snapshot.
|
|
491
|
+
this.ingestPayload(owner, profile, sessionID, parseResponse(metadataResponse) ?? payload, now, kind, requestStartedAt);
|
|
492
|
+
if (kind === 'messages' && sessionID && !this.synchronizingHistory && !this.transcripts.head(owner, profile, sessionID).running) {
|
|
493
|
+
this.transcripts.reconcile(owner, profile, sessionID);
|
|
494
|
+
this.updateTranscriptSummary(owner, profile, sessionID);
|
|
495
|
+
}
|
|
496
|
+
this.db.prepare(`INSERT INTO chat_snapshots(owner,cache_key,kind,profile,session_id,status,headers,body,sync_state,saved_at)
|
|
497
|
+
VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,cache_key) DO UPDATE SET status=excluded.status,headers=excluded.headers,
|
|
498
|
+
body=excluded.body,sync_state='current',saved_at=excluded.saved_at`)
|
|
499
|
+
.run(owner, key, kind, profile, sessionID ?? null, response.status, headerRecord(response.headers), response.body.toString('base64'), 'current', now);
|
|
500
|
+
this.db.exec('RELEASE chat_snapshot');
|
|
501
|
+
return true;
|
|
502
|
+
}
|
|
503
|
+
catch (error) {
|
|
504
|
+
this.db.exec('ROLLBACK TO chat_snapshot; RELEASE chat_snapshot');
|
|
505
|
+
throw error;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
applySync(owner, profile, sessionID, revision, pages, force) {
|
|
509
|
+
if (this.revision(owner, profile, sessionID) !== revision || this.transcripts.head(owner, profile, sessionID).running)
|
|
510
|
+
return false;
|
|
511
|
+
this.db.exec('SAVEPOINT history_sync');
|
|
512
|
+
this.synchronizingHistory = true;
|
|
513
|
+
try {
|
|
514
|
+
this.transcripts.archive([owner, profile, sessionID]);
|
|
515
|
+
if (force)
|
|
516
|
+
this.db.prepare('DELETE FROM chat_messages WHERE owner=? AND profile=? AND session_id=?').run(owner, profile, sessionID);
|
|
517
|
+
// Recovery promotes locally generated stream identities to upstream row IDs.
|
|
518
|
+
// Remove only replaced rows inside the verified window; keep older coverage.
|
|
519
|
+
if (!force) {
|
|
520
|
+
const windows = pages.filter(p => p.kind === 'messages').map(p => parseResponse(p.response)).filter(Boolean);
|
|
521
|
+
for (const window of windows) {
|
|
522
|
+
const pagination = window.pagination ?? {}, messages = window.messages;
|
|
523
|
+
if (!Array.isArray(messages) || !Number.isSafeInteger(pagination.total))
|
|
524
|
+
continue;
|
|
525
|
+
const identified = this.userMessageIdentities(owner, profile, sessionID, messages, false);
|
|
526
|
+
const end = pagination.total - Number(pagination.offset ?? 0), start = end - messages.length;
|
|
527
|
+
const ids = new Set(messages.map((m, index) => messageID(m, String(start + index))));
|
|
528
|
+
const existing = this.db.prepare('SELECT message_id,data,position FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND position>=? AND position<?').all(owner, profile, sessionID, start, end);
|
|
529
|
+
for (const row of existing) {
|
|
530
|
+
if (ids.has(row.message_id))
|
|
531
|
+
continue;
|
|
532
|
+
const value = JSON.parse(row.data);
|
|
533
|
+
const incoming = messages[row.position - start];
|
|
534
|
+
if (incoming && value.role === 'assistant' && incoming.role === 'assistant' && /^event:/.test(row.message_id)
|
|
535
|
+
&& typeof value.content === 'string' && value.content.length > 0 && value.content === incoming.content)
|
|
536
|
+
this.transcripts.promote(owner, profile, sessionID, row.message_id, messageID(incoming, String(row.position)));
|
|
537
|
+
if (value.role === 'user' && value.status === 'pending' && !identified.some(m => m.role === 'user'
|
|
538
|
+
&& value.client_message_id && m.client_message_id === value.client_message_id))
|
|
539
|
+
throw new Error('Unconfirmed submission must be reconciled before history replacement');
|
|
540
|
+
this.db.prepare('DELETE FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?').run(owner, profile, sessionID, row.message_id);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
this.db.prepare("DELETE FROM chat_snapshots WHERE owner=? AND profile=? AND session_id=? AND kind='messages'").run(owner, profile, sessionID);
|
|
545
|
+
for (const page of pages)
|
|
546
|
+
this.putSnapshot(owner, page.key, page.kind, profile, sessionID, page.response, false, page.startedAt);
|
|
547
|
+
// Resolve legacy identities only after all pages are stored. Resolving
|
|
548
|
+
// pages individually could consume a send before seeing an ambiguous row.
|
|
549
|
+
const coverage = this.db.prepare('SELECT complete,message_total FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
|
|
550
|
+
.get(owner, profile, sessionID);
|
|
551
|
+
if (coverage?.complete)
|
|
552
|
+
this.userMessageIdentities(owner, profile, sessionID, pages.flatMap(page => {
|
|
553
|
+
const messages = page.kind === 'messages' ? parseResponse(page.response)?.messages : undefined;
|
|
554
|
+
return Array.isArray(messages) ? messages.flatMap(value => object(value) ? [object(value)] : []) : [];
|
|
555
|
+
}));
|
|
556
|
+
const latest = this.db.prepare("SELECT message_id FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND json_extract(data,'$.role')='assistant' ORDER BY position DESC LIMIT 1").get(owner, profile, sessionID);
|
|
557
|
+
if (latest)
|
|
558
|
+
this.db.prepare('UPDATE chat_local_state SET assistant_id=? WHERE owner=? AND profile=? AND session_id=?').run(latest.message_id, owner, profile, sessionID);
|
|
559
|
+
this.transcripts.reconcile(owner, profile, sessionID);
|
|
560
|
+
this.updateTranscriptSummary(owner, profile, sessionID);
|
|
561
|
+
this.transcripts.sessionChanged(owner, profile, sessionID, { eventType: 'history.synced' });
|
|
562
|
+
this.synchronizingHistory = false;
|
|
563
|
+
this.db.exec('RELEASE history_sync');
|
|
564
|
+
return true;
|
|
565
|
+
}
|
|
566
|
+
catch (error) {
|
|
567
|
+
this.synchronizingHistory = false;
|
|
568
|
+
this.db.exec('ROLLBACK TO history_sync; RELEASE history_sync');
|
|
569
|
+
throw error;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
userMessageIdentities(owner, profile, sessionID, messages, recoverLegacy = true) {
|
|
573
|
+
const scope = [owner, profile, sessionID];
|
|
574
|
+
const bindings = this.db.prepare(`SELECT message_id,client_message_id FROM chat_message_identities
|
|
575
|
+
WHERE owner=? AND profile=? AND session_id=?`).all(...scope);
|
|
576
|
+
const byServer = new Map(bindings.map(row => [row.message_id, row.client_message_id]));
|
|
577
|
+
const byClient = new Map(bindings.map(row => [row.client_message_id, row.message_id]));
|
|
578
|
+
const serverID = (message) => {
|
|
579
|
+
const id = String(message.id ?? message.message_id ?? '').trim();
|
|
580
|
+
return message.role === 'user' && id && !id.startsWith('user:') ? id : '';
|
|
581
|
+
};
|
|
582
|
+
const bind = (id, client) => {
|
|
583
|
+
if (!id || !client || byServer.has(id) || byClient.has(client))
|
|
584
|
+
return;
|
|
585
|
+
this.db.prepare('INSERT INTO chat_message_identities VALUES(?,?,?,?,?)').run(...scope, id, client);
|
|
586
|
+
byServer.set(id, client);
|
|
587
|
+
byClient.set(client, id);
|
|
588
|
+
};
|
|
589
|
+
for (const message of messages) {
|
|
590
|
+
bind(serverID(message), String(message.client_message_id ?? message.clientMessageId ?? ''));
|
|
591
|
+
}
|
|
592
|
+
if (recoverLegacy && messages.some(message => serverID(message) && !byServer.has(serverID(message)))) {
|
|
593
|
+
// Older gateways omit client IDs. Recover only a mutually unique match
|
|
594
|
+
// inside a confirmed, non-queued submission's time window. Never dedupe
|
|
595
|
+
// by text or position alone, and include other pages when testing uniqueness.
|
|
596
|
+
const events = this.db.prepare(`SELECT event_type,payload,received_at FROM chat_events
|
|
597
|
+
WHERE owner=? AND profile=? AND session_id=?
|
|
598
|
+
AND event_type IN ('command:prompt.submit','command:session.steer','command.confirmed','command.rejected','message.start')
|
|
599
|
+
ORDER BY received_at,event_seq`)
|
|
600
|
+
.all(...scope);
|
|
601
|
+
const confirmed = new Map(), rejected = new Set();
|
|
602
|
+
for (const event of events) {
|
|
603
|
+
const payload = JSON.parse(event.payload);
|
|
604
|
+
if (event.event_type === 'command.confirmed' && payload.status !== 'queued')
|
|
605
|
+
confirmed.set(payload.delivery_id, event.received_at);
|
|
606
|
+
if (event.event_type === 'command.rejected')
|
|
607
|
+
rejected.add(payload.delivery_id);
|
|
608
|
+
}
|
|
609
|
+
const stored = this.db.prepare(`SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=?
|
|
610
|
+
AND json_extract(data,'$.role')='user'`).all(...scope);
|
|
611
|
+
const candidates = new Map();
|
|
612
|
+
for (const message of [...stored.map(row => JSON.parse(row.data)), ...messages]) {
|
|
613
|
+
const id = serverID(message);
|
|
614
|
+
if (id && !byServer.has(id))
|
|
615
|
+
candidates.set(id, message);
|
|
616
|
+
}
|
|
617
|
+
const matches = new Map(), claims = new Map();
|
|
618
|
+
const submissions = events.filter(event => event.event_type === 'command:prompt.submit' || event.event_type === 'command:session.steer');
|
|
619
|
+
for (const [index, event] of submissions.entries()) {
|
|
620
|
+
if (event.event_type !== 'command:prompt.submit')
|
|
621
|
+
continue;
|
|
622
|
+
const payload = JSON.parse(event.payload), delivery = String(payload._delivery_id ?? '');
|
|
623
|
+
const client = delivery.replace(/^(web|ios):prompt:/, '');
|
|
624
|
+
const acceptedAt = confirmed.get(delivery);
|
|
625
|
+
if (!client || byClient.has(client) || payload.queued || rejected.has(delivery) || acceptedAt === undefined)
|
|
626
|
+
continue;
|
|
627
|
+
const start = event.received_at / 1000;
|
|
628
|
+
const nextStart = submissions[index + 1]?.received_at ?? Infinity;
|
|
629
|
+
const runStart = events.find(candidate => candidate.event_type === 'message.start'
|
|
630
|
+
&& candidate.received_at >= event.received_at && candidate.received_at < nextStart);
|
|
631
|
+
// The receipt can precede the gateway's DB insert by a few milliseconds.
|
|
632
|
+
// A deferred agent build may start later; the next submission always
|
|
633
|
+
// closes this window, including when users rapidly repeat the same text.
|
|
634
|
+
const end = Math.min((runStart?.received_at ?? acceptedAt) + 1000, event.received_at + 120_000) / 1000;
|
|
635
|
+
const ids = [...candidates].flatMap(([id, message]) => {
|
|
636
|
+
const time = firstTimestamp(message, ['timestamp', 'created_at', 'createdAt']);
|
|
637
|
+
return time !== undefined && time >= start && time <= end && time < nextStart / 1000
|
|
638
|
+
&& message.content === (payload.text ?? payload.input ?? '') ? [id] : [];
|
|
639
|
+
});
|
|
640
|
+
matches.set(client, ids);
|
|
641
|
+
for (const id of ids)
|
|
642
|
+
claims.set(id, (claims.get(id) ?? 0) + 1);
|
|
643
|
+
}
|
|
644
|
+
for (const [client, ids] of matches) {
|
|
645
|
+
if (ids.length === 1 && claims.get(ids[0]) === 1)
|
|
646
|
+
bind(ids[0], client);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return messages.map(message => {
|
|
650
|
+
const client = byServer.get(serverID(message));
|
|
651
|
+
return client ? { ...message, client_message_id: client } : message;
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
messagePage(owner, profile, sessionID, offset, limit) {
|
|
655
|
+
if (!this.ownsSession(owner, profile, sessionID))
|
|
656
|
+
return this.sourceMessagePage(owner, profile, sessionID, offset, limit);
|
|
657
|
+
this.transcripts.seed(owner, profile, sessionID);
|
|
658
|
+
const known = this.db.prepare('SELECT complete,message_total FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?').get(owner, profile, sessionID);
|
|
659
|
+
if (!known?.complete && !this.transcripts.total(owner, profile, sessionID))
|
|
660
|
+
return undefined;
|
|
661
|
+
const all = this.transcripts.all(owner, profile, sessionID), end = Math.max(0, all.length - offset), start = Math.max(0, end - limit);
|
|
662
|
+
const total = known?.complete ? all.length : Math.max(all.length, Number(known?.message_total ?? 0));
|
|
663
|
+
if (!known?.complete && offset >= all.length && offset < total)
|
|
664
|
+
return undefined;
|
|
665
|
+
const detail = this.localDetail(owner, profile, sessionID);
|
|
666
|
+
return { state: detail.state, response: { status: 200, headers: new Headers({ 'content-type': 'application/json' }), body: Buffer.from(JSON.stringify({
|
|
667
|
+
session_id: sessionID, session: JSON.parse(detail.response.body.toString()), messages: all.slice(start, end),
|
|
668
|
+
pagination: { total, returned: end - start, offset, limit, has_more: start > 0 || total > all.length }
|
|
669
|
+
})) } };
|
|
670
|
+
}
|
|
671
|
+
sourceMessagePage(owner, profile, sessionID, offset, limit) {
|
|
672
|
+
const session = this.db.prepare(`SELECT data,sync_state,complete,message_total FROM chat_sessions
|
|
673
|
+
WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID);
|
|
674
|
+
if (!session)
|
|
675
|
+
return undefined;
|
|
676
|
+
const totalRow = this.db.prepare('SELECT COUNT(*) count, MAX(position)+1 extent FROM chat_messages WHERE owner=? AND profile=? AND session_id=?')
|
|
677
|
+
.get(owner, profile, sessionID);
|
|
678
|
+
if (session.message_total == null && !bool(session.complete))
|
|
679
|
+
return undefined;
|
|
680
|
+
const total = Number(session.message_total ?? totalRow.extent ?? 0);
|
|
681
|
+
const end = Math.max(0, total - offset);
|
|
682
|
+
const start = Math.max(0, end - limit);
|
|
683
|
+
const rows = this.db.prepare(`SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=?
|
|
684
|
+
AND position>=? AND position<? ORDER BY position`).all(owner, profile, sessionID, start, end);
|
|
685
|
+
if (rows.length !== end - start)
|
|
686
|
+
return undefined; // Fetch only an actually missing page.
|
|
687
|
+
const messages = this.userMessageIdentities(owner, profile, sessionID, rows.map(row => JSON.parse(row.data)), bool(session.complete));
|
|
688
|
+
const body = Buffer.from(JSON.stringify({
|
|
689
|
+
session_id: sessionID,
|
|
690
|
+
session: JSON.parse(this.localDetail(owner, profile, sessionID).response.body.toString()),
|
|
691
|
+
messages,
|
|
692
|
+
pagination: {
|
|
693
|
+
total,
|
|
694
|
+
returned: messages.length,
|
|
695
|
+
offset,
|
|
696
|
+
limit,
|
|
697
|
+
has_more: start > 0,
|
|
698
|
+
},
|
|
699
|
+
}));
|
|
700
|
+
return {
|
|
701
|
+
response: { status: 200, headers: new Headers({ 'content-type': 'application/json; charset=utf-8' }), body },
|
|
702
|
+
state: String(session.sync_state),
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
recordEvent(owner, profile, sessionID, frame) {
|
|
706
|
+
const rawSeq = Number(frame.seq ?? frame.sequence ?? 0);
|
|
707
|
+
const type = String(frame.type ?? 'unknown');
|
|
708
|
+
const payload = JSON.stringify(frame.payload ?? {});
|
|
709
|
+
const eventID = String(frame.delivery_id ?? (rawSeq > 0 ? `${frame.epoch ?? ''}:${rawSeq}:${type}` : randomUUID()));
|
|
710
|
+
const seq = Number.parseInt(createHash('sha256').update(eventID).digest('hex').slice(0, 12), 16);
|
|
711
|
+
const now = Date.now();
|
|
712
|
+
this.db.exec('SAVEPOINT live_event');
|
|
713
|
+
try {
|
|
714
|
+
const receipt = this.db.prepare('INSERT OR IGNORE INTO chat_event_receipts VALUES(?,?,?,?)').run(owner, profile, sessionID, eventID);
|
|
715
|
+
if (!receipt.changes) {
|
|
716
|
+
this.db.exec('RELEASE live_event');
|
|
717
|
+
return false;
|
|
718
|
+
}
|
|
719
|
+
const previous = this.db.prepare(`SELECT last_event_seq FROM chat_sessions
|
|
720
|
+
WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID);
|
|
721
|
+
const lastSeen = Number(previous?.last_event_seq ?? 0);
|
|
722
|
+
const inserted = this.db.prepare(`INSERT OR IGNORE INTO chat_events(owner,profile,session_id,event_seq,event_type,payload,received_at)
|
|
723
|
+
VALUES(?,?,?,?,?,?,?)`).run(owner, profile, sessionID, Number.isSafeInteger(seq) ? seq : 0, type, payload, now);
|
|
724
|
+
if (!inserted.changes) {
|
|
725
|
+
this.db.exec('RELEASE live_event');
|
|
726
|
+
return false;
|
|
727
|
+
}
|
|
728
|
+
const state = type === 'gateway.reset' || type.includes('reset')
|
|
729
|
+
|| (!frame.epoch && rawSeq > 0 && lastSeen > 0 && rawSeq > lastSeen + 1) ? 'gap' : 'stale';
|
|
730
|
+
const metadataOnly = ['session.info', 'session.title', 'session.title.updated', 'session.usage', 'gateway.ready'].includes(type) && state !== 'gap';
|
|
731
|
+
this.db.prepare(`UPDATE chat_sessions SET sync_state=CASE WHEN ? THEN sync_state WHEN sync_state='gap' THEN 'gap' ELSE ? END,
|
|
732
|
+
sync_revision=sync_revision+?,last_event_seq=MAX(last_event_seq,?),last_synced_at=?
|
|
733
|
+
WHERE owner=? AND profile=? AND session_id=?`).run(metadataOnly ? 1 : 0, state, metadataOnly ? 0 : 1, rawSeq > 0 ? rawSeq : lastSeen, now, owner, profile, sessionID);
|
|
734
|
+
if (type === 'session.info') {
|
|
735
|
+
const payload = object(frame.payload) ?? {};
|
|
736
|
+
const info = object(payload.info) ?? payload;
|
|
737
|
+
const row = this.db.prepare('SELECT data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
|
|
738
|
+
.get(owner, profile, sessionID);
|
|
739
|
+
if (row) {
|
|
740
|
+
const summary = object(JSON.parse(row.data)) ?? {};
|
|
741
|
+
for (const field of ['model', 'provider', 'fast'])
|
|
742
|
+
if (info[field] !== undefined)
|
|
743
|
+
summary[field] = info[field];
|
|
744
|
+
this.db.prepare('UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?')
|
|
745
|
+
.run(JSON.stringify(summary), owner, profile, sessionID);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
if (type === 'session.title' || type === 'session.title.updated') {
|
|
749
|
+
const title = String(object(frame.payload)?.title ?? frame.title ?? '').trim();
|
|
750
|
+
if (title)
|
|
751
|
+
this.updateOwnedSessionTitle(owner, profile, sessionID, title, now);
|
|
752
|
+
}
|
|
753
|
+
this.db.prepare(`UPDATE chat_snapshots SET sync_state=? WHERE owner=? AND (session_id=? OR kind='list')
|
|
754
|
+
AND (?=0 OR kind<>'messages')`).run(state, owner, sessionID, metadataOnly ? 1 : 0);
|
|
755
|
+
this.db.prepare(`INSERT INTO chat_sync_cursors(owner,profile,event_cursor,sync_state,last_synced_at)
|
|
756
|
+
VALUES(?,?,?,?,?) ON CONFLICT(owner,profile) DO UPDATE SET event_cursor=MAX(event_cursor,excluded.event_cursor),
|
|
757
|
+
sync_state=excluded.sync_state,last_synced_at=excluded.last_synced_at`)
|
|
758
|
+
.run(owner, profile, rawSeq > 0 ? rawSeq : lastSeen, state, now);
|
|
759
|
+
if (this.ownsSession(owner, profile, sessionID)) {
|
|
760
|
+
this.transcripts.recordSource([owner, profile, sessionID], frame);
|
|
761
|
+
this.transcripts.reduce(owner, profile, sessionID, type, object(frame.payload) ?? {});
|
|
762
|
+
this.updateTranscriptSummary(owner, profile, sessionID);
|
|
763
|
+
}
|
|
764
|
+
this.db.exec('RELEASE live_event');
|
|
765
|
+
return true;
|
|
766
|
+
}
|
|
767
|
+
catch (e) {
|
|
768
|
+
this.db.exec('ROLLBACK TO live_event; RELEASE live_event');
|
|
769
|
+
throw e;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
canonicalSessionID(owner, profile, id) {
|
|
773
|
+
let current = id;
|
|
774
|
+
const seen = new Set();
|
|
775
|
+
for (let n = 0; n < 32 && !seen.has(current); n++) {
|
|
776
|
+
seen.add(current);
|
|
777
|
+
const row = this.db.prepare('SELECT session_id FROM chat_session_aliases WHERE owner=? AND profile=? AND alias_id=?').get(owner, profile, current);
|
|
778
|
+
if (!row)
|
|
779
|
+
break;
|
|
780
|
+
current = row.session_id;
|
|
781
|
+
}
|
|
782
|
+
return current;
|
|
783
|
+
}
|
|
784
|
+
migrateRuntimeSession(owner, profile, id, runtime) {
|
|
785
|
+
const old = this.db.prepare('SELECT session_id FROM chat_sessions WHERE owner=? AND profile=? AND runtime_id=? AND session_id<>? AND owned_at IS NOT NULL').get(owner, profile, runtime, id);
|
|
786
|
+
if (!old || this.ownsSession(owner, profile, id))
|
|
787
|
+
return;
|
|
788
|
+
this.db.exec('SAVEPOINT migrate_live_route');
|
|
789
|
+
try {
|
|
790
|
+
for (const table of ['chat_sessions', 'chat_messages', 'chat_events', 'chat_snapshots', 'chat_attachments', 'chat_local_state', 'chat_event_receipts', 'chat_recovery_jobs', 'chat_message_identities'])
|
|
791
|
+
this.db.prepare(`UPDATE ${table} SET session_id=? WHERE owner=? AND profile=? AND session_id=?`).run(id, owner, profile, old.session_id);
|
|
792
|
+
this.db.prepare('INSERT OR REPLACE INTO chat_session_aliases VALUES(?,?,?,?)').run(owner, profile, old.session_id, id);
|
|
793
|
+
this.db.prepare('UPDATE chat_session_aliases SET session_id=? WHERE owner=? AND profile=? AND session_id=?').run(id, owner, profile, old.session_id);
|
|
794
|
+
this.db.prepare("UPDATE chat_sessions SET data=json_set(data,'$.id',?) WHERE owner=? AND profile=? AND session_id=?").run(id, owner, profile, id);
|
|
795
|
+
this.transcripts.migrate(owner, profile, old.session_id, id);
|
|
796
|
+
this.db.exec('RELEASE migrate_live_route');
|
|
797
|
+
}
|
|
798
|
+
catch (e) {
|
|
799
|
+
this.db.exec('ROLLBACK TO migrate_live_route; RELEASE migrate_live_route');
|
|
800
|
+
throw e;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
recordRoute(owner, profile, sessionID, runtimeID, running) {
|
|
804
|
+
this.db.exec('SAVEPOINT chat_route');
|
|
805
|
+
try {
|
|
806
|
+
this.migrateRuntimeSession(owner, profile, sessionID, runtimeID);
|
|
807
|
+
const now = Date.now();
|
|
808
|
+
const summary = { id: sessionID, profile, source: 'unknown', title: '新对话', started_at: now, last_active: now };
|
|
809
|
+
this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_synced_at,owned_at,ownership_evidence)
|
|
810
|
+
VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET runtime_id=excluded.runtime_id,
|
|
811
|
+
last_synced_at=excluded.last_synced_at,owned_at=COALESCE(chat_sessions.owned_at,excluded.owned_at),
|
|
812
|
+
ownership_evidence=COALESCE(chat_sessions.ownership_evidence,excluded.ownership_evidence)`)
|
|
813
|
+
.run(owner, profile, sessionID, runtimeID, 'unknown', JSON.stringify(summary), 'stale', 0, now, now, 'route-confirmed');
|
|
814
|
+
this.markListsStale(owner);
|
|
815
|
+
if (running !== undefined)
|
|
816
|
+
this.transcripts.sessionChanged(owner, profile, sessionID, { eventType: 'route.resumed', payload: { running } });
|
|
817
|
+
this.db.exec('RELEASE chat_route');
|
|
818
|
+
}
|
|
819
|
+
catch (error) {
|
|
820
|
+
this.db.exec('ROLLBACK TO chat_route; RELEASE chat_route');
|
|
821
|
+
throw error;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
recordCommand(owner, profile, sessionID, method, params) {
|
|
825
|
+
this.db.exec('SAVEPOINT chat_command');
|
|
826
|
+
try {
|
|
827
|
+
const now = Date.now();
|
|
828
|
+
const source = sessionSource(params) || 'unknown';
|
|
829
|
+
const establishesOwnership = method === 'session.create' || method === 'session.branch';
|
|
830
|
+
const summary = { id: sessionID, profile, source, title: '新对话', started_at: now, last_active: now };
|
|
831
|
+
this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,source,data,sync_state,complete,last_synced_at,owned_at,ownership_evidence)
|
|
832
|
+
VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET
|
|
833
|
+
source=CASE WHEN excluded.source='unknown' THEN chat_sessions.source ELSE excluded.source END,
|
|
834
|
+
sync_state=CASE WHEN chat_sessions.sync_state='gap' THEN 'gap' ELSE 'stale' END,sync_revision=chat_sessions.sync_revision+1,last_synced_at=excluded.last_synced_at,
|
|
835
|
+
owned_at=COALESCE(chat_sessions.owned_at,excluded.owned_at),
|
|
836
|
+
ownership_evidence=COALESCE(chat_sessions.ownership_evidence,excluded.ownership_evidence)`)
|
|
837
|
+
.run(owner, profile, sessionID, source, JSON.stringify(summary), 'stale', 0, now, establishesOwnership ? now : null, establishesOwnership ? `command:${method}` : null);
|
|
838
|
+
if (method === 'session.create')
|
|
839
|
+
this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,read_initialized) VALUES(?,?,?,1) ON CONFLICT(owner,profile,session_id) DO UPDATE SET read_initialized=1`).run(owner, profile, sessionID);
|
|
840
|
+
if (method === 'session.create')
|
|
841
|
+
this.db.prepare(`UPDATE chat_sessions SET complete=1,metadata_complete=1,message_total=0,sync_state='current' WHERE owner=? AND profile=? AND session_id=? AND message_total IS NULL`).run(owner, profile, sessionID);
|
|
842
|
+
this.transcripts.seed(owner, profile, sessionID);
|
|
843
|
+
if ((method === 'prompt.submit' || method === 'session.steer') && params._delivery_id) {
|
|
844
|
+
this.transcripts.reduce(owner, profile, sessionID, 'command.submitted', { ...params, method, delivery_id: params._delivery_id });
|
|
845
|
+
this.updateTranscriptSummary(owner, profile, sessionID);
|
|
846
|
+
}
|
|
847
|
+
const payload = JSON.stringify(params);
|
|
848
|
+
const seq = Number.parseInt(createHash('sha256').update(`${method}:${payload}`).digest('hex').slice(0, 12), 16);
|
|
849
|
+
this.db.prepare(`INSERT OR IGNORE INTO chat_events(owner,profile,session_id,event_seq,event_type,payload,received_at)
|
|
850
|
+
VALUES(?,?,?,?,?,?,?)`).run(owner, profile, sessionID, seq, `command:${method}`, payload, now);
|
|
851
|
+
this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE owner=? AND (session_id=? OR kind='list')")
|
|
852
|
+
.run(owner, sessionID);
|
|
853
|
+
this.db.exec('RELEASE chat_command');
|
|
854
|
+
}
|
|
855
|
+
catch (error) {
|
|
856
|
+
this.db.exec('ROLLBACK TO chat_command; RELEASE chat_command');
|
|
857
|
+
throw error;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
fileSourceMessage(owner, profile, sessionID, messageID) {
|
|
861
|
+
const canonical = this.transcripts.resolveMessage(owner, profile, sessionID, messageID);
|
|
862
|
+
if (canonical)
|
|
863
|
+
return canonical;
|
|
864
|
+
const row = this.db.prepare('SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?')
|
|
865
|
+
.get(owner, profile, sessionID, messageID);
|
|
866
|
+
return row ? JSON.parse(String(row.data)) : undefined;
|
|
867
|
+
}
|
|
868
|
+
markListsStale(owner) {
|
|
869
|
+
this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE owner=? AND kind='list'").run(owner);
|
|
870
|
+
}
|
|
871
|
+
invalidateOwnedMetadata(owner) {
|
|
872
|
+
return this.db.prepare(`UPDATE chat_sessions SET metadata_complete=0,sync_revision=sync_revision+1
|
|
873
|
+
WHERE owner=? AND owned_at IS NOT NULL AND source NOT IN ('cron','ios_group','yaoyao_workspace')
|
|
874
|
+
RETURNING profile,session_id`).all(owner);
|
|
875
|
+
}
|
|
876
|
+
refreshMetadata(owner, profile, id, revision, response, startedAt) {
|
|
877
|
+
const payload = parseResponse(response), summary = object(payload?.session) ?? payload;
|
|
878
|
+
const total = summary?.message_count ?? summary?.messageCount;
|
|
879
|
+
const row = this.db.prepare('SELECT metadata_complete,complete,message_total,sync_state FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
|
|
880
|
+
.get(owner, profile, id);
|
|
881
|
+
if (!row || row.metadata_complete || !row.complete || total == null || Number(total) !== row.message_total || this.revision(owner, profile, id) !== revision)
|
|
882
|
+
return false;
|
|
883
|
+
this.db.exec('SAVEPOINT metadata_refresh');
|
|
884
|
+
try {
|
|
885
|
+
const metadata = { ...summary };
|
|
886
|
+
delete metadata.messages;
|
|
887
|
+
const headers = new Headers(response.headers);
|
|
888
|
+
headers.delete('content-length');
|
|
889
|
+
const metadataResponse = { ...response, headers, body: Buffer.from(JSON.stringify(metadata)) };
|
|
890
|
+
if (!this.putSnapshot(owner, `detail:${profile}:${id}`, 'detail', profile, id, metadataResponse, false, startedAt))
|
|
891
|
+
throw new Error('Invalid conversation metadata');
|
|
892
|
+
// A metadata invalidation must not replace or downgrade the durable live tail.
|
|
893
|
+
this.db.prepare('UPDATE chat_sessions SET sync_state=? WHERE owner=? AND profile=? AND session_id=?').run(row.sync_state, owner, profile, id);
|
|
894
|
+
this.db.exec('RELEASE metadata_refresh');
|
|
895
|
+
return true;
|
|
896
|
+
}
|
|
897
|
+
catch (error) {
|
|
898
|
+
this.db.exec('ROLLBACK TO metadata_refresh; RELEASE metadata_refresh');
|
|
899
|
+
throw error;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
recordAuthoritativeTitle(owner, profile, sessionID, title) {
|
|
903
|
+
const normalized = title.trim();
|
|
904
|
+
if (!normalized)
|
|
905
|
+
return;
|
|
906
|
+
this.updateOwnedSessionTitle(owner, profile, sessionID, normalized, Date.now());
|
|
907
|
+
this.db.prepare(`UPDATE chat_snapshots SET sync_state='stale'
|
|
908
|
+
WHERE owner=? AND (session_id=? OR kind='list')`).run(owner, sessionID);
|
|
909
|
+
}
|
|
910
|
+
deleteSession(owner, profile, sessionID) {
|
|
911
|
+
const assets = this.db.prepare(`SELECT DISTINCT local_path FROM chat_attachments
|
|
912
|
+
WHERE owner=? AND profile=? AND session_id=? AND local_path IS NOT NULL`)
|
|
913
|
+
.all(owner, profile, sessionID);
|
|
914
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
915
|
+
try {
|
|
916
|
+
for (const table of ['chat_messages', 'chat_events', 'chat_attachments', 'chat_local_state', 'chat_event_receipts', 'chat_recovery_jobs', 'chat_session_aliases', 'chat_message_identities', 'chat_sessions']) {
|
|
917
|
+
this.db.prepare(`DELETE FROM ${table} WHERE owner=? AND profile=? AND session_id=?`).run(owner, profile, sessionID);
|
|
918
|
+
}
|
|
919
|
+
this.db.prepare("DELETE FROM chat_snapshots WHERE owner=? AND ((profile=? AND session_id=?) OR kind='list')")
|
|
920
|
+
.run(owner, profile, sessionID);
|
|
921
|
+
this.transcripts.remove(owner, profile, sessionID);
|
|
922
|
+
this.db.exec('COMMIT');
|
|
923
|
+
for (const asset of assets) {
|
|
924
|
+
const referenced = this.db.prepare('SELECT 1 ok FROM chat_attachments WHERE local_path=? LIMIT 1').get(asset.local_path);
|
|
925
|
+
if (!referenced)
|
|
926
|
+
try {
|
|
927
|
+
unlinkSync(asset.local_path);
|
|
928
|
+
}
|
|
929
|
+
catch { /* Already absent. */ }
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
catch (error) {
|
|
933
|
+
this.db.exec('ROLLBACK');
|
|
934
|
+
throw error;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
attachment(owner, sourcePath) {
|
|
938
|
+
const row = this.db.prepare(`SELECT local_path,mime_type FROM chat_attachments
|
|
939
|
+
WHERE owner=? AND source_path=? AND state='cached' ORDER BY updated_at DESC LIMIT 1`).get(owner, sourcePath);
|
|
940
|
+
const localPath = row?.local_path ? String(row.local_path) : '';
|
|
941
|
+
return localPath && existsSync(localPath) ? { localPath, ...(row?.mime_type ? { mimeType: String(row.mime_type) } : {}) } : undefined;
|
|
942
|
+
}
|
|
943
|
+
knowsAttachment(owner, sourcePath) {
|
|
944
|
+
return Boolean(this.db.prepare('SELECT 1 ok FROM chat_attachments WHERE owner=? AND source_path=? LIMIT 1').get(owner, sourcePath));
|
|
945
|
+
}
|
|
946
|
+
ownsSession(owner, profile, sessionID) {
|
|
947
|
+
sessionID = this.canonicalSessionID(owner, profile, sessionID);
|
|
948
|
+
return Boolean(this.db.prepare('SELECT 1 ok FROM chat_sessions WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL').get(owner, profile, sessionID));
|
|
949
|
+
}
|
|
950
|
+
ownedSessionMetadata(owner, profile, sessionID) {
|
|
951
|
+
const row = this.db.prepare(`SELECT authoritative_title FROM chat_sessions
|
|
952
|
+
WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`)
|
|
953
|
+
.get(owner, profile, sessionID);
|
|
954
|
+
const local = this.db.prepare('SELECT title FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner, profile, sessionID);
|
|
955
|
+
const authoritativeTitle = String(local?.title ?? row?.authoritative_title ?? '').trim();
|
|
956
|
+
return {
|
|
957
|
+
owned: Boolean(row),
|
|
958
|
+
...(authoritativeTitle ? { authoritativeTitle } : {}),
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
mergeOwnedSessionsIntoList(owner, fallbackProfile, response, page = {}) {
|
|
962
|
+
const payload = parseResponse(response);
|
|
963
|
+
if (!payload)
|
|
964
|
+
return response;
|
|
965
|
+
const collectionKey = Array.isArray(payload.items)
|
|
966
|
+
? 'items'
|
|
967
|
+
: Array.isArray(payload.sessions) ? 'sessions' : undefined;
|
|
968
|
+
if (!collectionKey)
|
|
969
|
+
return response;
|
|
970
|
+
const rows = (fallbackProfile
|
|
971
|
+
? this.db.prepare(`SELECT profile,session_id,source,data,authoritative_title,last_synced_at FROM chat_sessions
|
|
972
|
+
WHERE owner=? AND profile=? AND owned_at IS NOT NULL`)
|
|
973
|
+
.all(owner, fallbackProfile)
|
|
974
|
+
: this.db.prepare(`SELECT profile,session_id,source,data,authoritative_title,last_synced_at FROM chat_sessions
|
|
975
|
+
WHERE owner=? AND owned_at IS NOT NULL`).all(owner));
|
|
976
|
+
const owned = new Map(rows.map(row => [
|
|
977
|
+
`${row.profile}\u0000${row.session_id}`,
|
|
978
|
+
row,
|
|
979
|
+
]));
|
|
980
|
+
const merged = new Map();
|
|
981
|
+
for (const [key, row] of owned) {
|
|
982
|
+
let stored = {};
|
|
983
|
+
try {
|
|
984
|
+
stored = object(JSON.parse(row.data)) ?? {};
|
|
985
|
+
}
|
|
986
|
+
catch { /* Ignore damaged display metadata. */ }
|
|
987
|
+
const storedSource = sessionSource(stored);
|
|
988
|
+
merged.set(key, {
|
|
989
|
+
...stored,
|
|
990
|
+
id: row.session_id,
|
|
991
|
+
profile: row.profile,
|
|
992
|
+
source: storedSource && storedSource !== 'unknown' ? storedSource : row.source,
|
|
993
|
+
...(row.authoritative_title?.trim() ? { title: row.authoritative_title.trim() } : {}),
|
|
994
|
+
_yaoyao_registry_activity: row.last_synced_at,
|
|
995
|
+
owned: true,
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
for (const value of payload[collectionKey]) {
|
|
999
|
+
const session = object(value);
|
|
1000
|
+
if (!session)
|
|
1001
|
+
continue;
|
|
1002
|
+
const id = sessionIDOf(session);
|
|
1003
|
+
const profile = profileOf(session, fallbackProfile) || 'default';
|
|
1004
|
+
if (!id)
|
|
1005
|
+
continue;
|
|
1006
|
+
const key = `${profile}\u0000${id}`;
|
|
1007
|
+
const row = owned.get(key);
|
|
1008
|
+
if (row) {
|
|
1009
|
+
const title = row.authoritative_title?.trim();
|
|
1010
|
+
merged.set(key, {
|
|
1011
|
+
...mergeSessionMetadata(merged.get(key) ?? {}, session),
|
|
1012
|
+
...(title ? { title } : {}),
|
|
1013
|
+
_yaoyao_registry_activity: row.last_synced_at,
|
|
1014
|
+
owned: true,
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
const activity = (session) => firstTimestamp(session, ACTIVITY_TIME_KEYS) ?? firstTimestamp(session, START_TIME_KEYS) ?? 0;
|
|
1019
|
+
const archived = (session) => bool(session.is_archived ?? session.isArchived ?? session.archived);
|
|
1020
|
+
const pinned = (session) => bool(session.is_pinned ?? session.isPinned ?? session.pinned);
|
|
1021
|
+
const archivedMode = page.archived ?? 'exclude';
|
|
1022
|
+
const allSessions = [...merged.values()]
|
|
1023
|
+
.filter(session => archivedMode === 'include'
|
|
1024
|
+
|| (archivedMode === 'only' ? archived(session) : !archived(session)))
|
|
1025
|
+
.sort((left, right) => Number(pinned(right)) - Number(pinned(left))
|
|
1026
|
+
|| activity(right) - activity(left));
|
|
1027
|
+
const offset = Math.max(0, Math.trunc(page.offset ?? 0));
|
|
1028
|
+
const limit = Math.max(1, Math.min(500, Math.trunc(page.limit ?? 100)));
|
|
1029
|
+
const sessions = allSessions.slice(offset, offset + limit).map((session) => {
|
|
1030
|
+
const publicSession = mergeSessionMetadata({}, session);
|
|
1031
|
+
delete publicSession._yaoyao_registry_activity;
|
|
1032
|
+
return publicSession;
|
|
1033
|
+
});
|
|
1034
|
+
const body = Buffer.from(JSON.stringify({
|
|
1035
|
+
...payload,
|
|
1036
|
+
[collectionKey]: sessions,
|
|
1037
|
+
total: allSessions.length,
|
|
1038
|
+
offset,
|
|
1039
|
+
limit,
|
|
1040
|
+
}));
|
|
1041
|
+
const headers = new Headers(response.headers);
|
|
1042
|
+
headers.delete('content-length');
|
|
1043
|
+
return { ...response, headers, body };
|
|
1044
|
+
}
|
|
1045
|
+
excludeOwnedSessionsFromList(owner, fallbackProfile, response, page = {}) {
|
|
1046
|
+
const payload = parseResponse(response);
|
|
1047
|
+
if (!payload)
|
|
1048
|
+
return response;
|
|
1049
|
+
const collectionKey = Array.isArray(payload.items)
|
|
1050
|
+
? 'items'
|
|
1051
|
+
: Array.isArray(payload.sessions) ? 'sessions' : undefined;
|
|
1052
|
+
if (!collectionKey)
|
|
1053
|
+
return response;
|
|
1054
|
+
const allSessions = payload[collectionKey].filter((value) => {
|
|
1055
|
+
const session = object(value);
|
|
1056
|
+
if (!session)
|
|
1057
|
+
return true;
|
|
1058
|
+
const id = sessionIDOf(session);
|
|
1059
|
+
const profile = profileOf(session, fallbackProfile) || 'default';
|
|
1060
|
+
return !id || !this.ownsSession(owner, profile, id);
|
|
1061
|
+
});
|
|
1062
|
+
const offset = Math.max(0, Math.trunc(page.offset ?? 0));
|
|
1063
|
+
const limit = Math.max(1, Math.min(500, Math.trunc(page.limit ?? 100)));
|
|
1064
|
+
const sessions = allSessions.slice(offset, offset + limit);
|
|
1065
|
+
const headers = new Headers(response.headers);
|
|
1066
|
+
headers.delete('content-length');
|
|
1067
|
+
return {
|
|
1068
|
+
...response,
|
|
1069
|
+
headers,
|
|
1070
|
+
body: Buffer.from(JSON.stringify({
|
|
1071
|
+
...payload,
|
|
1072
|
+
[collectionKey]: sessions,
|
|
1073
|
+
total: allSessions.length,
|
|
1074
|
+
offset,
|
|
1075
|
+
limit,
|
|
1076
|
+
})),
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
markSessionOwnership(owner, fallbackProfile, sessionID, response) {
|
|
1080
|
+
const payload = parseResponse(response);
|
|
1081
|
+
if (!payload)
|
|
1082
|
+
return response;
|
|
1083
|
+
const session = object(payload.session);
|
|
1084
|
+
const candidate = session ?? payload;
|
|
1085
|
+
const id = sessionIDOf(candidate) || sessionID;
|
|
1086
|
+
const profile = profileOf(candidate, fallbackProfile) || fallbackProfile || 'default';
|
|
1087
|
+
const row = this.db.prepare(`SELECT authoritative_title FROM chat_sessions
|
|
1088
|
+
WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`).get(owner, profile, id);
|
|
1089
|
+
const owned = Boolean(row);
|
|
1090
|
+
const local = this.db.prepare('SELECT title FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner, profile, id);
|
|
1091
|
+
const title = String(local?.title ?? row?.authoritative_title ?? '').trim();
|
|
1092
|
+
const body = session
|
|
1093
|
+
? Buffer.from(JSON.stringify({
|
|
1094
|
+
...payload,
|
|
1095
|
+
session: { ...session, ...(title ? { title } : {}), owned },
|
|
1096
|
+
owned,
|
|
1097
|
+
}))
|
|
1098
|
+
: Buffer.from(JSON.stringify({ ...payload, ...(title ? { title } : {}), owned }));
|
|
1099
|
+
const headers = new Headers(response.headers);
|
|
1100
|
+
headers.delete('content-length');
|
|
1101
|
+
return { ...response, headers, body };
|
|
1102
|
+
}
|
|
1103
|
+
markOwnedSearchResults(owner, fallbackProfile, response, view, limit = 100) {
|
|
1104
|
+
const payload = parseResponse(response);
|
|
1105
|
+
if (!payload || !Array.isArray(payload.results))
|
|
1106
|
+
return response;
|
|
1107
|
+
const marked = payload.results.map((value) => {
|
|
1108
|
+
const session = object(value);
|
|
1109
|
+
if (!session)
|
|
1110
|
+
return value;
|
|
1111
|
+
const id = sessionIDOf(session);
|
|
1112
|
+
const profile = profileOf(session, fallbackProfile) || fallbackProfile || 'default';
|
|
1113
|
+
const metadata = id
|
|
1114
|
+
? this.ownedSessionMetadata(owner, profile, id)
|
|
1115
|
+
: { owned: false };
|
|
1116
|
+
return {
|
|
1117
|
+
...session,
|
|
1118
|
+
...(metadata.authoritativeTitle ? { title: metadata.authoritativeTitle } : {}),
|
|
1119
|
+
owned: metadata.owned,
|
|
1120
|
+
};
|
|
1121
|
+
});
|
|
1122
|
+
const projected = marked.filter((value) => {
|
|
1123
|
+
if (!view)
|
|
1124
|
+
return true;
|
|
1125
|
+
const session = object(value);
|
|
1126
|
+
if (!session)
|
|
1127
|
+
return false;
|
|
1128
|
+
return view === 'chat' ? session.owned === true : session.owned !== true;
|
|
1129
|
+
});
|
|
1130
|
+
const results = projected.slice(0, Math.max(1, Math.min(100, Math.trunc(limit))));
|
|
1131
|
+
const headers = new Headers(response.headers);
|
|
1132
|
+
headers.delete('content-length');
|
|
1133
|
+
return {
|
|
1134
|
+
...response,
|
|
1135
|
+
headers,
|
|
1136
|
+
body: Buffer.from(JSON.stringify({ ...payload, results, total: projected.length })),
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
storeAttachment(owner, sourcePath, response) {
|
|
1140
|
+
if (response.status !== 200 || !response.body.length)
|
|
1141
|
+
return undefined;
|
|
1142
|
+
const sha256 = createHash('sha256').update(response.body).digest('hex');
|
|
1143
|
+
const directory = join(this.assetsRoot, sha256.slice(0, 2));
|
|
1144
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
1145
|
+
const target = join(directory, sha256);
|
|
1146
|
+
if (!existsSync(target)) {
|
|
1147
|
+
const temporary = `${target}.${process.pid}.tmp`;
|
|
1148
|
+
writeFileSync(temporary, response.body, { mode: 0o600 });
|
|
1149
|
+
renameSync(temporary, target);
|
|
1150
|
+
}
|
|
1151
|
+
const mimeType = response.headers.get('content-type')?.split(';', 1)[0];
|
|
1152
|
+
this.db.prepare(`UPDATE chat_attachments SET sha256=?,mime_type=?,size=?,local_path=?,state='cached',updated_at=?
|
|
1153
|
+
WHERE owner=? AND source_path=?`).run(sha256, mimeType ?? null, response.body.length, target, Date.now(), owner, sourcePath);
|
|
1154
|
+
return target;
|
|
1155
|
+
}
|
|
1156
|
+
assetStream(path) {
|
|
1157
|
+
return { stream: createReadStream(path), size: statSync(path).size };
|
|
1158
|
+
}
|
|
1159
|
+
payloadBelongsToOwnedChat(owner, profile, sessionID, payload) {
|
|
1160
|
+
const session = object(payload.session) ?? (sessionID ? payload : undefined);
|
|
1161
|
+
if (session) {
|
|
1162
|
+
const id = sessionIDOf(session) || sessionID || '';
|
|
1163
|
+
const sessionProfile = profileOf(session, profile) || profile || 'default';
|
|
1164
|
+
if (id && this.ownsSession(owner, sessionProfile, id))
|
|
1165
|
+
return true;
|
|
1166
|
+
}
|
|
1167
|
+
const sessions = Array.isArray(payload.items) ? payload.items : Array.isArray(payload.sessions) ? payload.sessions : [];
|
|
1168
|
+
if (sessions.some(value => {
|
|
1169
|
+
const candidate = object(value);
|
|
1170
|
+
if (!candidate)
|
|
1171
|
+
return false;
|
|
1172
|
+
const id = sessionIDOf(candidate);
|
|
1173
|
+
const sessionProfile = profileOf(candidate, profile) || profile || 'default';
|
|
1174
|
+
return Boolean(id && this.ownsSession(owner, sessionProfile, id));
|
|
1175
|
+
}))
|
|
1176
|
+
return true;
|
|
1177
|
+
return Boolean(sessionID && this.ownsSession(owner, profile || 'default', sessionID));
|
|
1178
|
+
}
|
|
1179
|
+
ingestPayload(owner, fallbackProfile, sessionID, payload, now, kind, requestStartedAt) {
|
|
1180
|
+
const candidates = [];
|
|
1181
|
+
const direct = object(payload.session);
|
|
1182
|
+
if (direct)
|
|
1183
|
+
candidates.push(direct);
|
|
1184
|
+
const listed = Array.isArray(payload.items) ? payload.items : Array.isArray(payload.sessions) ? payload.sessions : [];
|
|
1185
|
+
for (const value of listed)
|
|
1186
|
+
if (object(value))
|
|
1187
|
+
candidates.push(object(value));
|
|
1188
|
+
if (sessionID && !direct && (sessionIDOf(payload) || sessionSource(payload) || typeof payload.title === 'string')) {
|
|
1189
|
+
candidates.push(payload);
|
|
1190
|
+
}
|
|
1191
|
+
for (const session of candidates) {
|
|
1192
|
+
const id = sessionIDOf(session) || sessionID || '';
|
|
1193
|
+
if (!id)
|
|
1194
|
+
continue;
|
|
1195
|
+
const profile = profileOf(session, fallbackProfile) || fallbackProfile || 'default';
|
|
1196
|
+
const registered = this.ownsSession(owner, profile, id);
|
|
1197
|
+
const source = sessionSource(session);
|
|
1198
|
+
if (!registered)
|
|
1199
|
+
continue;
|
|
1200
|
+
const titleRow = this.db.prepare(`SELECT data,authoritative_title,authoritative_title_at FROM chat_sessions
|
|
1201
|
+
WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, id);
|
|
1202
|
+
const authoritativeTitle = String(titleRow?.authoritative_title ?? '').trim();
|
|
1203
|
+
const authoritativeTitleAt = Number(titleRow?.authoritative_title_at ?? 0);
|
|
1204
|
+
const incomingTitle = sessionTitle(session);
|
|
1205
|
+
const preservesAuthoritativeTitle = Boolean(authoritativeTitle)
|
|
1206
|
+
&& (kind !== 'detail' || isPlaceholderTitle(incomingTitle)
|
|
1207
|
+
|| requestStartedAt <= authoritativeTitleAt);
|
|
1208
|
+
let previous = {};
|
|
1209
|
+
try {
|
|
1210
|
+
previous = object(JSON.parse(titleRow?.data ?? '{}')) ?? {};
|
|
1211
|
+
}
|
|
1212
|
+
catch { /* Recover from incoming metadata. */ }
|
|
1213
|
+
const storedSession = mergeSessionMetadata(previous, session);
|
|
1214
|
+
if (preservesAuthoritativeTitle)
|
|
1215
|
+
storedSession.title = authoritativeTitle;
|
|
1216
|
+
const metadataComplete = kind !== 'messages' || direct ? 1 : 0;
|
|
1217
|
+
this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_synced_at,metadata_complete)
|
|
1218
|
+
VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET data=excluded.data,
|
|
1219
|
+
metadata_complete=MAX(chat_sessions.metadata_complete,excluded.metadata_complete),
|
|
1220
|
+
source=CASE WHEN excluded.source='unknown' THEN chat_sessions.source ELSE excluded.source END,
|
|
1221
|
+
sync_state='current',last_synced_at=excluded.last_synced_at`)
|
|
1222
|
+
.run(owner, profile, id, null, source || 'unknown', JSON.stringify(storedSession), 'current', 0, now, metadataComplete);
|
|
1223
|
+
const acceptedTitle = sessionTitle(storedSession);
|
|
1224
|
+
if (acceptedTitle && !isPlaceholderTitle(acceptedTitle)
|
|
1225
|
+
&& (!authoritativeTitle || kind === 'detail')) {
|
|
1226
|
+
this.db.prepare(`UPDATE chat_sessions SET authoritative_title=?,authoritative_title_at=?
|
|
1227
|
+
WHERE owner=? AND profile=? AND session_id=?`).run(acceptedTitle, Math.max(requestStartedAt, authoritativeTitleAt), owner, profile, id);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
const messages = Array.isArray(payload.messages) ? payload.messages.flatMap(value => object(value) ? [object(value)] : []) : [];
|
|
1231
|
+
if (!Array.isArray(payload.messages) || !sessionID)
|
|
1232
|
+
return;
|
|
1233
|
+
const profile = fallbackProfile || profileOf(direct ?? {}, 'default') || 'default';
|
|
1234
|
+
const pagination = object(payload.pagination) ?? {};
|
|
1235
|
+
const offset = Math.max(0, Number(pagination.offset ?? payload.offset ?? 0) || 0);
|
|
1236
|
+
const storedDetail = this.localDetail(owner, profile, sessionID);
|
|
1237
|
+
const storedSummary = storedDetail ? parseResponse(storedDetail.response) ?? {} : {};
|
|
1238
|
+
const total = Math.max(offset + messages.length, Number(pagination.total ?? payload.total ?? storedSummary.message_count ?? storedSummary.messageCount ?? 0) || 0);
|
|
1239
|
+
const start = Math.max(0, total - offset - messages.length);
|
|
1240
|
+
this.userMessageIdentities(owner, profile, sessionID, messages, false).forEach((message, index) => {
|
|
1241
|
+
const data = JSON.stringify(message);
|
|
1242
|
+
this.db.prepare(`INSERT INTO chat_messages(owner,profile,session_id,message_id,position,data,content_hash)
|
|
1243
|
+
VALUES(?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id,message_id) DO UPDATE SET position=excluded.position,
|
|
1244
|
+
data=excluded.data,content_hash=excluded.content_hash
|
|
1245
|
+
WHERE chat_messages.content_hash<>excluded.content_hash OR chat_messages.position<>excluded.position`)
|
|
1246
|
+
.run(owner, profile, sessionID, messageID(message, String(start + index)), start + index, data, createHash('sha256').update(data).digest('hex'));
|
|
1247
|
+
for (const sourcePath of referencedPaths(message)) {
|
|
1248
|
+
this.db.prepare(`INSERT INTO chat_attachments(owner,profile,session_id,source_path,state,updated_at)
|
|
1249
|
+
VALUES(?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id,source_path) DO UPDATE SET updated_at=excluded.updated_at`)
|
|
1250
|
+
.run(owner, profile, sessionID, sourcePath, 'pending', now);
|
|
1251
|
+
}
|
|
1252
|
+
});
|
|
1253
|
+
const coverage = this.db.prepare(`SELECT COUNT(*) count, COUNT(DISTINCT position) positions, MIN(position) first, MAX(position) last
|
|
1254
|
+
FROM chat_messages WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID);
|
|
1255
|
+
const complete = total === 0 ? coverage.count === 0
|
|
1256
|
+
: coverage.count === total && coverage.positions === total && coverage.first === 0 && coverage.last === total - 1;
|
|
1257
|
+
const row = this.db.prepare('SELECT data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
|
|
1258
|
+
.get(owner, profile, sessionID);
|
|
1259
|
+
const summary = mergeSessionMetadata({}, object(JSON.parse(row.data)) ?? {});
|
|
1260
|
+
const bounds = messageTimeBounds(messages);
|
|
1261
|
+
if (!firstTimestamp(summary, START_TIME_KEYS) && bounds.first !== undefined)
|
|
1262
|
+
summary.started_at = bounds.first;
|
|
1263
|
+
if (bounds.last !== undefined) {
|
|
1264
|
+
summary.last_active = Math.max(firstTimestamp(summary, ACTIVITY_TIME_KEYS) ?? 0, bounds.last);
|
|
1265
|
+
}
|
|
1266
|
+
summary.message_count = total;
|
|
1267
|
+
this.db.prepare('UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?')
|
|
1268
|
+
.run(JSON.stringify(summary), owner, profile, sessionID);
|
|
1269
|
+
this.db.prepare(`UPDATE chat_sessions SET complete=?,message_total=?,sync_state='current',last_synced_at=?
|
|
1270
|
+
WHERE owner=? AND profile=? AND session_id=?`).run(complete ? 1 : 0, total, now, owner, profile, sessionID);
|
|
1271
|
+
}
|
|
1272
|
+
updateOwnedSessionTitle(owner, profile, sessionID, title, now) {
|
|
1273
|
+
const row = this.db.prepare(`SELECT source,data FROM chat_sessions
|
|
1274
|
+
WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`).get(owner, profile, sessionID);
|
|
1275
|
+
if (!row)
|
|
1276
|
+
return;
|
|
1277
|
+
let summary = {};
|
|
1278
|
+
try {
|
|
1279
|
+
summary = object(JSON.parse(String(row.data))) ?? {};
|
|
1280
|
+
}
|
|
1281
|
+
catch { /* Rebuild damaged display metadata below. */ }
|
|
1282
|
+
const storedSource = sessionSource(summary);
|
|
1283
|
+
const source = storedSource && storedSource !== 'unknown'
|
|
1284
|
+
? storedSource
|
|
1285
|
+
: String(row.source || 'unknown');
|
|
1286
|
+
this.db.prepare(`UPDATE chat_sessions SET data=?,authoritative_title=?,authoritative_title_at=?,sync_state='stale',last_synced_at=?
|
|
1287
|
+
WHERE owner=? AND profile=? AND session_id=?`).run(JSON.stringify({
|
|
1288
|
+
...summary,
|
|
1289
|
+
id: sessionID,
|
|
1290
|
+
profile,
|
|
1291
|
+
source,
|
|
1292
|
+
title,
|
|
1293
|
+
}), title, now, now, owner, profile, sessionID);
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
export class ChatCacheCoordinator {
|
|
1297
|
+
store;
|
|
1298
|
+
upstream;
|
|
1299
|
+
mode;
|
|
1300
|
+
reconciling = new Map();
|
|
1301
|
+
onSynchronized = () => { };
|
|
1302
|
+
constructor(store, upstream, mode = 'prefer-local') {
|
|
1303
|
+
this.store = store;
|
|
1304
|
+
this.upstream = upstream;
|
|
1305
|
+
this.mode = mode;
|
|
1306
|
+
const timer = setTimeout(() => {
|
|
1307
|
+
this.retryTimers.delete(timer);
|
|
1308
|
+
if (this.store.isClosed || this.stopped)
|
|
1309
|
+
return;
|
|
1310
|
+
void this.restoreReadPositions();
|
|
1311
|
+
for (const row of this.store.db.prepare("SELECT owner,profile,session_id FROM chat_sessions WHERE owned_at IS NOT NULL").all()) {
|
|
1312
|
+
this.store.transcripts.seed(row.owner, row.profile, row.session_id);
|
|
1313
|
+
}
|
|
1314
|
+
for (const row of this.store.db.prepare("SELECT * FROM chat_transcript_repairs WHERE status='pending'").all())
|
|
1315
|
+
this.schedule(row.owner, row.profile, row.session_id, true);
|
|
1316
|
+
for (const row of this.store.db.prepare('SELECT * FROM chat_recovery_jobs').all())
|
|
1317
|
+
this.schedule(row.owner, row.profile, row.session_id, !!row.force);
|
|
1318
|
+
}, 0);
|
|
1319
|
+
timer.unref();
|
|
1320
|
+
this.retryTimers.add(timer);
|
|
1321
|
+
}
|
|
1322
|
+
diagnostics = { localReads: 0, recoveryAttempts: 0, recoveryFailures: 0, recoveryCompleted: 0 };
|
|
1323
|
+
async restoreReadPositions() {
|
|
1324
|
+
if (this.stopped || this.store.isClosed)
|
|
1325
|
+
return;
|
|
1326
|
+
const scopes = this.store.db.prepare('SELECT DISTINCT owner,profile FROM chat_local_state WHERE read_initialized=0').all();
|
|
1327
|
+
let failed = false;
|
|
1328
|
+
for (let i = 0; i < scopes.length; i += 2)
|
|
1329
|
+
await Promise.all(scopes.slice(i, i + 2).map(async ({ owner, profile }) => {
|
|
1330
|
+
if (this.stopped || this.store.isClosed)
|
|
1331
|
+
return;
|
|
1332
|
+
try {
|
|
1333
|
+
const response = await this.upstream.request('/api/session-unread', { search: new URLSearchParams({ profile }) });
|
|
1334
|
+
if (this.stopped || this.store.isClosed)
|
|
1335
|
+
return;
|
|
1336
|
+
if (response.status >= 500)
|
|
1337
|
+
throw new Error('Read-position import unavailable');
|
|
1338
|
+
const payload = parseResponse(response), rows = Array.isArray(payload?.sessions) ? payload.sessions : [];
|
|
1339
|
+
this.store.db.exec('SAVEPOINT read_position_import');
|
|
1340
|
+
try {
|
|
1341
|
+
for (const raw of rows) {
|
|
1342
|
+
const r = object(raw);
|
|
1343
|
+
if (!r)
|
|
1344
|
+
continue;
|
|
1345
|
+
const id = String(r.session_id ?? r.sessionId ?? '');
|
|
1346
|
+
const count = Math.max(0, Number(r.read_message_count ?? r.readMessageCount ?? 0) || 0);
|
|
1347
|
+
this.store.db.prepare('UPDATE chat_local_state SET read_count=?,read_initialized=1 WHERE owner=? AND profile=? AND session_id=? AND read_initialized=0').run(count, owner, profile, id);
|
|
1348
|
+
}
|
|
1349
|
+
this.store.db.prepare(`UPDATE chat_local_state SET read_count=COALESCE((SELECT message_total FROM chat_sessions s WHERE s.owner=chat_local_state.owner AND s.profile=chat_local_state.profile AND s.session_id=chat_local_state.session_id),0),read_initialized=1 WHERE owner=? AND profile=? AND read_initialized=0`).run(owner, profile);
|
|
1350
|
+
this.store.db.exec('RELEASE read_position_import');
|
|
1351
|
+
}
|
|
1352
|
+
catch (e) {
|
|
1353
|
+
this.store.db.exec('ROLLBACK TO read_position_import; RELEASE read_position_import');
|
|
1354
|
+
throw e;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
catch {
|
|
1358
|
+
failed = true;
|
|
1359
|
+
}
|
|
1360
|
+
}));
|
|
1361
|
+
if (failed && !this.stopped && !this.store.isClosed) {
|
|
1362
|
+
const timer = setTimeout(() => { this.retryTimers.delete(timer); void this.restoreReadPositions(); }, 30_000);
|
|
1363
|
+
timer.unref();
|
|
1364
|
+
this.retryTimers.add(timer);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
jobs = new Map();
|
|
1368
|
+
activeJobs = new Set();
|
|
1369
|
+
retryTimers = new Set();
|
|
1370
|
+
stopped = false;
|
|
1371
|
+
close() { this.stopped = true; for (const timer of this.retryTimers)
|
|
1372
|
+
clearTimeout(timer); this.retryTimers.clear(); this.jobs.clear(); }
|
|
1373
|
+
schedule(owner, profile, id, force = false) {
|
|
1374
|
+
if (this.stopped || this.store.isClosed || !this.store.ownsSession(owner, profile, id))
|
|
1375
|
+
return;
|
|
1376
|
+
const key = JSON.stringify([owner, profile, id]), previous = this.jobs.get(key);
|
|
1377
|
+
if (previous) {
|
|
1378
|
+
previous.force ||= force;
|
|
1379
|
+
if (force)
|
|
1380
|
+
this.store.db.prepare('UPDATE chat_recovery_jobs SET force=1 WHERE owner=? AND profile=? AND session_id=?').run(owner, profile, id);
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
this.store.db.prepare('INSERT INTO chat_recovery_jobs VALUES(?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET force=MAX(force,excluded.force)').run(owner, profile, id, force ? 1 : 0);
|
|
1384
|
+
this.jobs.set(key, { owner, profile, id, force, attempt: 0 });
|
|
1385
|
+
const timer = setTimeout(() => { this.retryTimers.delete(timer); this.drain(); }, 0);
|
|
1386
|
+
timer.unref();
|
|
1387
|
+
this.retryTimers.add(timer);
|
|
1388
|
+
}
|
|
1389
|
+
drain() {
|
|
1390
|
+
if (this.stopped || this.store.isClosed)
|
|
1391
|
+
return;
|
|
1392
|
+
for (const [key, job] of this.jobs) {
|
|
1393
|
+
if (this.activeJobs.size >= 2)
|
|
1394
|
+
break;
|
|
1395
|
+
if (this.activeJobs.has(key) || job.attempt < 0)
|
|
1396
|
+
continue;
|
|
1397
|
+
this.activeJobs.add(key);
|
|
1398
|
+
this.diagnostics.recoveryAttempts++;
|
|
1399
|
+
const force = job.force;
|
|
1400
|
+
job.force = false;
|
|
1401
|
+
void this.reconcile(job.owner, job.profile, job.id, force).then(() => {
|
|
1402
|
+
if (this.stopped || this.store.isClosed)
|
|
1403
|
+
return;
|
|
1404
|
+
if (job.force) {
|
|
1405
|
+
job.attempt = 0;
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
this.diagnostics.recoveryCompleted++;
|
|
1409
|
+
this.jobs.delete(key);
|
|
1410
|
+
this.store.db.prepare('DELETE FROM chat_recovery_jobs WHERE owner=? AND profile=? AND session_id=?').run(job.owner, job.profile, job.id);
|
|
1411
|
+
}).catch(() => {
|
|
1412
|
+
if (this.stopped || this.store.isClosed)
|
|
1413
|
+
return;
|
|
1414
|
+
this.diagnostics.recoveryFailures++;
|
|
1415
|
+
job.force ||= force;
|
|
1416
|
+
const attempt = Math.abs(job.attempt) + 1;
|
|
1417
|
+
job.attempt = -attempt;
|
|
1418
|
+
const timer = setTimeout(() => { this.retryTimers.delete(timer); job.attempt = attempt; this.drain(); }, Math.min(30_000, 1000 * 2 ** Math.min(attempt - 1, 5)));
|
|
1419
|
+
timer.unref();
|
|
1420
|
+
this.retryTimers.add(timer);
|
|
1421
|
+
}).finally(() => { this.activeJobs.delete(key); this.drain(); });
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
readLocal(owner, kind, profile, id, page, force = false) {
|
|
1425
|
+
this.diagnostics.localReads++;
|
|
1426
|
+
if (id)
|
|
1427
|
+
id = this.store.canonicalSessionID(owner, profile, id);
|
|
1428
|
+
if (kind === 'list') {
|
|
1429
|
+
for (const row of this.store.missingSessions(owner, profile))
|
|
1430
|
+
this.schedule(owner, row.profile, row.session_id, force);
|
|
1431
|
+
return { response: this.store.localList(owner, profile, page), source: 'local', state: this.store.needsListMetadata(owner, profile) ? 'syncing' : 'current' };
|
|
1432
|
+
}
|
|
1433
|
+
this.store.requireOwned(owner, profile, id);
|
|
1434
|
+
const local = kind === 'detail' ? this.store.localDetail(owner, profile, id) : this.store.messagePage(owner, profile, id, page.offset ?? 0, page.limit ?? 100);
|
|
1435
|
+
if (force || !local || local.state === 'gap')
|
|
1436
|
+
this.schedule(owner, profile, id, force);
|
|
1437
|
+
if (!local)
|
|
1438
|
+
throw new HttpError(409, '历史正在后台补齐,请稍后重试', 'CHAT_HISTORY_SYNC_PENDING');
|
|
1439
|
+
return { response: local.response, source: 'local', state: this.jobs.has(JSON.stringify([owner, profile, id])) ? 'syncing' : local.state };
|
|
1440
|
+
}
|
|
1441
|
+
async read(owner, key, kind, profile, sessionID, load, ownedList = false, listPage = {}) {
|
|
1442
|
+
if (this.mode === 'upstream-only') {
|
|
1443
|
+
const upstreamResponse = await load();
|
|
1444
|
+
return {
|
|
1445
|
+
response: kind === 'list' && ownedList
|
|
1446
|
+
? this.store.mergeOwnedSessionsIntoList(owner, profile, upstreamResponse, listPage)
|
|
1447
|
+
: upstreamResponse,
|
|
1448
|
+
source: 'upstream',
|
|
1449
|
+
state: 'current',
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
if (this.mode === 'prefer-local' && kind === 'list' && ownedList && !this.store.needsListMetadata(owner, profile)) {
|
|
1453
|
+
return { response: this.store.localList(owner, profile, listPage), source: 'local', state: 'current' };
|
|
1454
|
+
}
|
|
1455
|
+
const local = kind === 'list' && ownedList && this.store.needsListMetadata(owner, profile) ? undefined : kind === 'detail' && sessionID
|
|
1456
|
+
? this.store.localDetail(owner, profile, sessionID) ?? this.store.snapshot(owner, key)
|
|
1457
|
+
: this.store.snapshot(owner, key);
|
|
1458
|
+
const projectedLocal = local && kind === 'list' && ownedList
|
|
1459
|
+
? {
|
|
1460
|
+
...local,
|
|
1461
|
+
response: this.store.mergeOwnedSessionsIntoList(owner, profile, local.response, listPage),
|
|
1462
|
+
}
|
|
1463
|
+
: local;
|
|
1464
|
+
if (this.mode === 'prefer-local' && local) {
|
|
1465
|
+
return { response: projectedLocal.response, source: 'local', state: local.state };
|
|
1466
|
+
}
|
|
1467
|
+
try {
|
|
1468
|
+
const requestStartedAt = Date.now();
|
|
1469
|
+
const upstreamResponse = await load();
|
|
1470
|
+
if (this.mode === 'prefer-local' && local && upstreamResponse.status >= 500) {
|
|
1471
|
+
return { response: projectedLocal.response, source: 'local', state: 'stale' };
|
|
1472
|
+
}
|
|
1473
|
+
const response = kind === 'list' && ownedList
|
|
1474
|
+
? this.store.mergeOwnedSessionsIntoList(owner, profile, upstreamResponse, listPage)
|
|
1475
|
+
: upstreamResponse;
|
|
1476
|
+
this.store.putSnapshot(owner, key, kind, profile, sessionID, response, ownedList, requestStartedAt, upstreamResponse);
|
|
1477
|
+
return { response, source: 'upstream', state: 'current' };
|
|
1478
|
+
}
|
|
1479
|
+
catch (error) {
|
|
1480
|
+
if (this.mode === 'prefer-local' && local)
|
|
1481
|
+
return { response: projectedLocal.response, source: 'local', state: 'stale' };
|
|
1482
|
+
throw error;
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
async messages(owner, key, profile, sessionID, offset, limit, load) {
|
|
1486
|
+
if (this.mode === 'prefer-local') {
|
|
1487
|
+
// A completion may still be committing its authoritative tail. Join it for
|
|
1488
|
+
// the latest page; older, already stored pages never wait for the network.
|
|
1489
|
+
if (offset === 0)
|
|
1490
|
+
await this.reconciling.get(JSON.stringify([owner, profile, sessionID]))?.catch(() => { });
|
|
1491
|
+
const page = this.store.messagePage(owner, profile, sessionID, offset, limit);
|
|
1492
|
+
if (page)
|
|
1493
|
+
return { response: page.response, source: 'local', state: page.state };
|
|
1494
|
+
}
|
|
1495
|
+
return this.read(owner, key, 'messages', profile, sessionID, load);
|
|
1496
|
+
}
|
|
1497
|
+
observe(owner, profile, sessionID, frame) {
|
|
1498
|
+
if (!this.store.recordEvent(owner, profile, sessionID, frame))
|
|
1499
|
+
return;
|
|
1500
|
+
if (String(frame.type).includes('reset') || this.store.localDetail(owner, profile, sessionID)?.state === 'gap'
|
|
1501
|
+
|| (['message.complete', 'run.completed'].includes(String(frame.type)) && this.store.localDetail(owner, profile, sessionID)?.state !== 'current')) {
|
|
1502
|
+
this.schedule(owner, profile, sessionID);
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
observeGlobal(owner, type, upstreamInvalidation = false) {
|
|
1506
|
+
if (type !== 'sessions.changed' || this.stopped || this.store.isClosed)
|
|
1507
|
+
return;
|
|
1508
|
+
this.store.markListsStale(owner);
|
|
1509
|
+
if (upstreamInvalidation)
|
|
1510
|
+
for (const row of this.store.invalidateOwnedMetadata(owner))
|
|
1511
|
+
this.schedule(owner, row.profile, row.session_id);
|
|
1512
|
+
}
|
|
1513
|
+
command(owner, profile, sessionID, method, params) {
|
|
1514
|
+
this.store.recordCommand(owner, profile, sessionID, method, params);
|
|
1515
|
+
}
|
|
1516
|
+
route(owner, profile, sessionID, runtimeID, running) {
|
|
1517
|
+
this.store.recordRoute(owner, profile, sessionID, runtimeID, running);
|
|
1518
|
+
}
|
|
1519
|
+
async reconcile(owner, profile, sessionID, force = false) {
|
|
1520
|
+
if (this.store.isClosed)
|
|
1521
|
+
return;
|
|
1522
|
+
sessionID = this.store.canonicalSessionID(owner, profile, sessionID);
|
|
1523
|
+
if (this.stopped || this.store.isClosed || !this.store.ownsSession(owner, profile, sessionID))
|
|
1524
|
+
return;
|
|
1525
|
+
const key = JSON.stringify([owner, profile, sessionID]);
|
|
1526
|
+
const pending = this.reconciling.get(key);
|
|
1527
|
+
if (pending) {
|
|
1528
|
+
const failed = await pending.then(() => false, () => true);
|
|
1529
|
+
if (failed || force || this.store.localDetail(owner, profile, sessionID)?.state !== 'current') {
|
|
1530
|
+
return this.reconcile(owner, profile, sessionID, force);
|
|
1531
|
+
}
|
|
1532
|
+
return;
|
|
1533
|
+
}
|
|
1534
|
+
const task = (async () => {
|
|
1535
|
+
if (this.store.transcripts.head(owner, profile, sessionID).running)
|
|
1536
|
+
throw new Error('Conversation is running; defer history repair');
|
|
1537
|
+
const repair = this.store.db.prepare("SELECT 1 FROM chat_transcript_repairs WHERE owner=? AND profile=? AND session_id=? AND status='pending'").get(owner, profile, sessionID);
|
|
1538
|
+
force ||= !!repair;
|
|
1539
|
+
const revision = this.store.revision(owner, profile, sessionID);
|
|
1540
|
+
const previous = this.store.sourceMessagePage(owner, profile, sessionID, 0, 1);
|
|
1541
|
+
const previousTotal = previous ? Number(object(parseResponse(previous.response)?.pagination)?.total ?? 0) : 0;
|
|
1542
|
+
const detailPath = `/api/sessions/${encodeURIComponent(sessionID)}`;
|
|
1543
|
+
const detailStartedAt = Date.now();
|
|
1544
|
+
const detail = await this.upstream.request(detailPath, { search: new URLSearchParams({ profile }), cache: 'reload' });
|
|
1545
|
+
if (this.stopped || this.store.isClosed)
|
|
1546
|
+
return;
|
|
1547
|
+
if (detail.status !== 200)
|
|
1548
|
+
throw new Error('Unable to synchronize conversation metadata');
|
|
1549
|
+
if (!force && this.store.refreshMetadata(owner, profile, sessionID, revision, detail, detailStartedAt)) {
|
|
1550
|
+
this.onSynchronized(owner, profile, sessionID);
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
const detailPayload = parseResponse(detail) ?? {};
|
|
1554
|
+
const detailSummary = object(detailPayload.session) ?? detailPayload;
|
|
1555
|
+
const summaryTotal = Math.max(0, Number(detailSummary.message_count ?? detailSummary.messageCount ?? previousTotal) || 0);
|
|
1556
|
+
const pages = [{ key: `detail:${profile}:${sessionID}`, kind: 'detail', response: detail, startedAt: detailStartedAt, offset: 0 }];
|
|
1557
|
+
let offset = 0;
|
|
1558
|
+
let done = false;
|
|
1559
|
+
let expectedTotal;
|
|
1560
|
+
let resolvedTotal = summaryTotal;
|
|
1561
|
+
// Stop as soon as the authoritative tail overlaps durable messages. Only
|
|
1562
|
+
// explicit refresh (or uncached history) walks all the way to the beginning.
|
|
1563
|
+
for (let page = 0; page < 1_000; page++) {
|
|
1564
|
+
const search = new URLSearchParams({ profile, offset: String(offset), limit: '100', order: 'latest', include_compacted: 'true' });
|
|
1565
|
+
const startedAt = Date.now();
|
|
1566
|
+
const response = await this.upstream.request(`${detailPath}/messages`, { search, cache: 'reload' });
|
|
1567
|
+
if (this.stopped || this.store.isClosed)
|
|
1568
|
+
return;
|
|
1569
|
+
const payload = parseResponse(response);
|
|
1570
|
+
if (response.status !== 200 || !Array.isArray(payload?.messages))
|
|
1571
|
+
throw new Error('Unable to synchronize conversation messages');
|
|
1572
|
+
const messages = payload.messages.flatMap(value => object(value) ? [object(value)] : []);
|
|
1573
|
+
const pagination = object(payload.pagination) ?? {};
|
|
1574
|
+
const explicitTotal = pagination.total ?? payload.total;
|
|
1575
|
+
const total = Math.max(offset + messages.length, Number(explicitTotal ?? summaryTotal) || 0);
|
|
1576
|
+
if (!force && total < previousTotal)
|
|
1577
|
+
throw new Error('Stored history changed; explicit refresh is required');
|
|
1578
|
+
if (explicitTotal !== undefined) {
|
|
1579
|
+
if (expectedTotal !== undefined && expectedTotal !== total)
|
|
1580
|
+
throw new Error('Conversation changed during synchronization');
|
|
1581
|
+
expectedTotal = total;
|
|
1582
|
+
}
|
|
1583
|
+
const anchors = !force ? messages.map((message, index) => this.store.hasMessage(owner, profile, sessionID, message, total - offset - messages.length + index)) : [];
|
|
1584
|
+
const overlap = anchors.some(Boolean);
|
|
1585
|
+
pages.push({ key: `messages:${profile}:${sessionID}:${offset}:100`, kind: 'messages', response, startedAt, offset });
|
|
1586
|
+
const more = pagination.hasMore ?? pagination.has_more ?? payload.hasMore ?? payload.has_more;
|
|
1587
|
+
const hasMore = more === undefined ? messages.length >= 100 : bool(more);
|
|
1588
|
+
if (overlap || !hasMore) {
|
|
1589
|
+
if (!overlap && expectedTotal !== undefined && expectedTotal !== offset + messages.length)
|
|
1590
|
+
throw new Error('Conversation pagination ended before its declared total');
|
|
1591
|
+
resolvedTotal = overlap ? total : offset + messages.length;
|
|
1592
|
+
done = true;
|
|
1593
|
+
break;
|
|
1594
|
+
}
|
|
1595
|
+
if (!messages.length)
|
|
1596
|
+
break;
|
|
1597
|
+
offset += messages.length;
|
|
1598
|
+
}
|
|
1599
|
+
if (!done)
|
|
1600
|
+
throw new Error('Conversation synchronization is incomplete');
|
|
1601
|
+
// Newer Hermes omits total/has_more. Once the end is known, project the
|
|
1602
|
+
// same verified total onto every page before assigning absolute positions.
|
|
1603
|
+
for (let index = 0; index < pages.length; index++) {
|
|
1604
|
+
const entry = pages[index];
|
|
1605
|
+
const payload = parseResponse(entry.response);
|
|
1606
|
+
if (entry.kind === 'detail') {
|
|
1607
|
+
const summary = object(payload.session) ?? payload;
|
|
1608
|
+
summary.message_count = resolvedTotal;
|
|
1609
|
+
}
|
|
1610
|
+
else {
|
|
1611
|
+
const pagination = object(payload.pagination) ?? {};
|
|
1612
|
+
const pageOffset = entry.offset;
|
|
1613
|
+
payload.pagination = { ...pagination, total: resolvedTotal, offset: pageOffset,
|
|
1614
|
+
has_more: pageOffset + payload.messages.length < resolvedTotal };
|
|
1615
|
+
}
|
|
1616
|
+
const headers = new Headers(entry.response.headers);
|
|
1617
|
+
headers.delete('content-length');
|
|
1618
|
+
entry.response = { ...entry.response, headers, body: Buffer.from(JSON.stringify(payload)) };
|
|
1619
|
+
}
|
|
1620
|
+
if (!this.store.applySync(owner, profile, sessionID, revision, pages, force)) {
|
|
1621
|
+
// Preserve the invalidation when a newer event arrived during the read.
|
|
1622
|
+
// Its completion joins this flight and schedules the next tail read.
|
|
1623
|
+
throw new Error('Conversation changed during refresh; retry after the reply completes');
|
|
1624
|
+
}
|
|
1625
|
+
else {
|
|
1626
|
+
if (this.store.db.prepare("SELECT 1 FROM chat_transcript_repairs WHERE owner=? AND profile=? AND session_id=? AND status='pending'").get(owner, profile, sessionID))
|
|
1627
|
+
throw new Error('History identity is not yet confirmed; preserve the existing conversation');
|
|
1628
|
+
this.onSynchronized(owner, profile, sessionID);
|
|
1629
|
+
}
|
|
1630
|
+
})().finally(() => { if (this.reconciling.get(key) === task)
|
|
1631
|
+
this.reconciling.delete(key); });
|
|
1632
|
+
this.reconciling.set(key, task);
|
|
1633
|
+
return task;
|
|
1634
|
+
}
|
|
1635
|
+
async cacheAttachment(owner, sourcePath) {
|
|
1636
|
+
if (this.mode === 'upstream-only' || !this.store.knowsAttachment(owner, sourcePath) || this.store.attachment(owner, sourcePath))
|
|
1637
|
+
return;
|
|
1638
|
+
try {
|
|
1639
|
+
const response = await this.upstream.request('/api/files/download', {
|
|
1640
|
+
search: new URLSearchParams({ path: sourcePath }), maxResponseBytes: 100 * 1_024 * 1_024,
|
|
1641
|
+
});
|
|
1642
|
+
this.store.storeAttachment(owner, sourcePath, response);
|
|
1643
|
+
}
|
|
1644
|
+
catch { /* The next authorized request can retry. */ }
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
export function chatCacheKey(kind, profile, sessionID, search) {
|
|
1648
|
+
const normalized = new URLSearchParams(search);
|
|
1649
|
+
normalized.sort();
|
|
1650
|
+
return [kind, profile, sessionID ?? '', normalized.toString()].join(':');
|
|
1651
|
+
}
|