zidane-gui 9.1.13 → 9.1.14
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/migrations/0002_browser_state.sql +18 -0
- package/out/main/chunks/{history-pager-B5iwhWqn.js → history-pager-DCty1YTu.js} +12 -23
- package/out/main/chunks/{remote-hosts-DmiOiwKi.js → remote-hosts-ZyXkwftF.js} +3 -3
- package/out/main/history-worker.js +1 -1
- package/out/main/index.js +1666 -729
- package/out/preload/index.mjs +20 -3
- package/out/renderer/assets/{43YPWK3Q-BVJpf1u1.js → 43YPWK3Q-DqQmzBPu.js} +6 -6
- package/out/renderer/assets/{45MVAN6X-BWuIeWOc.js → 45MVAN6X-CYP7xDN8.js} +5 -5
- package/out/renderer/assets/{46GJKBLZ-41BAHmt4.js → 46GJKBLZ-Co9yrG8W.js} +10 -10
- package/out/renderer/assets/{63WH7YNF-DuatnhlB.js → 63WH7YNF-JjkWKCFV.js} +8 -8
- package/out/renderer/assets/{6DDU7VKX-BAI-vKC1.js → 6DDU7VKX-BbtUMWO4.js} +6 -6
- package/out/renderer/assets/{CLQLV5VT-CmHu2HE3.js → CLQLV5VT-Ba6obVJu.js} +6 -6
- package/out/renderer/assets/{CUSPXG5M-DE3uzfbs.js → CUSPXG5M-BeHLB3vL.js} +6 -6
- package/out/renderer/assets/{CodeEditor-CIwCP1F_.js → CodeEditor-BaTPNKEc.js} +3 -3
- package/out/renderer/assets/{ComposerEditor-leA8S_Yk.js → ComposerEditor-C-40aCPQ.js} +2 -2
- package/out/renderer/assets/{D3L7O4X2-BZ4caDcX.js → D3L7O4X2-Bz5JjvM3.js} +4 -4
- package/out/renderer/assets/{D5TW5CPZ-BXdKc68h.js → D5TW5CPZ-COD7XA6N.js} +1 -1
- package/out/renderer/assets/{DiffsTab-CyRIVfQk.js → DiffsTab-BMAwuAR-.js} +5 -5
- package/out/renderer/assets/{EGADTWYV-Bf6Kicdv.js → EGADTWYV-DnX4xYm9.js} +5 -5
- package/out/renderer/assets/{EOJSJZXM-NAa-K4U0.js → EOJSJZXM-C1MKUH-z.js} +8 -8
- package/out/renderer/assets/{EditorWorkers-CY0St-9O.js → EditorWorkers-BgCbhgVz.js} +4 -4
- package/out/renderer/assets/{FilesTab-CnRw0KCN.js → FilesTab-BKwUG683.js} +36 -12
- package/out/renderer/assets/{G2OEIG6X-BarwxCkp.js → G2OEIG6X-Dtesfr7X.js} +5 -5
- package/out/renderer/assets/{GXJ2T77W-CyQVHlsG.js → GXJ2T77W-BkncFrMb.js} +6 -6
- package/out/renderer/assets/{HX3UMAK7-BcoG4mYG.js → HX3UMAK7-DyzWjT_c.js} +5 -5
- package/out/renderer/assets/{IU7WZTP6-kOLrUSwF.js → IU7WZTP6-C4qRhHoM.js} +1 -1
- package/out/renderer/assets/{J5J2NR2G-DE-SGCIz.js → J5J2NR2G-2GjekDt4.js} +4 -4
- package/out/renderer/assets/{JRCWTJEL-DZY5HKk0.js → JRCWTJEL-Dto8Fjzi.js} +3 -3
- package/out/renderer/assets/{KHUP5TOH-DevvG2jY.js → KHUP5TOH-DWatm9RV.js} +1 -1
- package/out/renderer/assets/{L74FQTH5-CnOj-zIY.js → L74FQTH5-YWQWDmAR.js} +4 -4
- package/out/renderer/assets/{LAV4ZXOS-BATWssHi.js → LAV4ZXOS-BDeemsOt.js} +6 -6
- package/out/renderer/assets/{LBIZYCRR-BXTsyX1O.js → LBIZYCRR-CuJZ9kCp.js} +7 -7
- package/out/renderer/assets/{LFFXNLRS-BpnXEoXM.js → LFFXNLRS-CYLYOq-d.js} +3 -3
- package/out/renderer/assets/{LLLWOAQD-BjLHR3Pk.js → LLLWOAQD-B6r0O-b8.js} +1 -1
- package/out/renderer/assets/{LTYQZ5U5-CDOIyknV.js → LTYQZ5U5-C6Vwu29l.js} +8 -8
- package/out/renderer/assets/{NDSCUZ25-Bl1idg0d.js → NDSCUZ25-D49aLwGZ.js} +2 -2
- package/out/renderer/assets/{NMN3IKWL-BYE2yrn3.js → NMN3IKWL-CmFbUlVt.js} +9 -9
- package/out/renderer/assets/{NMUA3R2D-Xl410xeQ.js → NMUA3R2D-BmYN27sp.js} +7 -7
- package/out/renderer/assets/{NY5A6PPW-CkzCXBsB.js → NY5A6PPW-CFmWX6Y1.js} +3 -3
- package/out/renderer/assets/{OHJ2EJXK-DCVoLmOH.js → OHJ2EJXK-BkSNlV9q.js} +1 -1
- package/out/renderer/assets/{OU2GIT2H-DG4LbVmY.js → OU2GIT2H-Df8P_VMV.js} +4 -4
- package/out/renderer/assets/{PDMLSE6I-Cr8MjczD.js → PDMLSE6I-B1fxTWPk.js} +2 -2
- package/out/renderer/assets/{PJ7X32S5-DFZu5Xsj.js → PJ7X32S5-jmIr_WuS.js} +5 -5
- package/out/renderer/assets/{RLLQ44NJ-D-LvBssh.js → RLLQ44NJ-Bk5ATCRc.js} +7 -7
- package/out/renderer/assets/{S6DWMCK5-BQEAXG2z.js → S6DWMCK5-ru17f61y.js} +8 -8
- package/out/renderer/assets/{STIOTUT7-jszPNHGr.js → STIOTUT7-D3W8oemx.js} +6 -6
- package/out/renderer/assets/{SXSLPWUD-CEMEDuKR.js → SXSLPWUD-BP8ObIM3.js} +2 -2
- package/out/renderer/assets/{TR4WJQGX-8wGWCKKm.js → TR4WJQGX-DwQDLHm2.js} +1 -1
- package/out/renderer/assets/{UWRPUF3N-ONJaPLUk.js → UWRPUF3N-BefBSoyh.js} +1 -1
- package/out/renderer/assets/{VSWIZJ7B-DbkRTlJD.js → VSWIZJ7B-QwUQICP_.js} +1 -1
- package/out/renderer/assets/{WM7NR6YK-CFy2rge0.js → WM7NR6YK-CRccSJmx.js} +4 -4
- package/out/renderer/assets/{WXKV2YEK-BFHYSpQF.js → WXKV2YEK-AiJtxeS-.js} +3 -3
- package/out/renderer/assets/{XLHPVVFU-BJFPh1Rn.js → XLHPVVFU-CISC9r_V.js} +1 -1
- package/out/renderer/assets/{YNX532HU-3QqofRh5.js → YNX532HU-CY_1HOiG.js} +5 -5
- package/out/renderer/assets/{YUPSMAUO-COLbQro8.js → YUPSMAUO-Cv2Ryk3Q.js} +1 -1
- package/out/renderer/assets/{ZFRCZTLK-BuPbgRNC.js → ZFRCZTLK-xOx-Cqik.js} +6 -6
- package/out/renderer/assets/{ZZDR4CN3-Do4onAxu.js → ZZDR4CN3-CDsCY6PX.js} +4 -4
- package/out/renderer/assets/{core-T80gwwf3.js → core-Cst33ux7.js} +2942 -2524
- package/out/renderer/assets/{file-tabs-DWQZlQfx.js → file-tabs-CUVbBbPB.js} +5 -5
- package/out/renderer/assets/{ghostty-web-DXNGAB4P.js → ghostty-web-DsF2lzXq.js} +1 -1
- package/out/renderer/assets/{highlights-Yvd7kpJw.js → highlights-BWQ-BGwF.js} +3 -3
- package/out/renderer/assets/{highlights-B0vcJ7-n.js → highlights-D9DV-gLr.js} +2 -2
- package/out/renderer/assets/{index-CsOxRbAw.css → index-C5y0Nb6N.css} +16 -1
- package/out/renderer/assets/{index-BbyDWT39.js → index-CPbTfv_f.js} +435 -351
- package/out/renderer/assets/{kit-DgkO1_s6.js → kit-BpS6VboD.js} +3240 -1662
- package/out/renderer/assets/{langs-7bXaMxtL.js → langs-CC8eNbvY.js} +1 -1
- package/out/renderer/assets/{lazy-DE7xn_YD.js → lazy-DtE8TmIe.js} +3 -3
- package/out/renderer/assets/{loader-CdKsI-e2.js → loader-BWgWjzVT.js} +1 -1
- package/out/renderer/assets/{pierre-theme-BouAfjrk.js → pierre-theme-DkKyEYzW.js} +7 -7
- package/out/renderer/assets/{shiki-CIKuDsHH.js → shiki-CahOMWmD.js} +3 -3
- package/out/renderer/assets/{stream-tokenizer-JLLsdqkH.js → stream-tokenizer-CtslDDLQ.js} +1 -1
- package/out/renderer/assets/{themes-mM7Qtyxf.js → themes-BVPDzAaq.js} +2 -2
- package/out/renderer/assets/{useDetachCleanup-1PVBQ1U4.js → useDetachCleanup-CSuE-TQs.js} +2 -2
- package/out/renderer/assets/{useFolderChanges-_vflCTEj.js → useFolderChanges-Cqx0tE4p.js} +3 -3
- package/out/renderer/index.html +4 -4
- package/package.json +3 -3
package/out/main/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFileSync, mkdirSync, writeFileSync, renameSync, existsSync, accessSync, constants, statSync, readdirSync, rmSync, mkdtempSync, realpathSync, createReadStream } from "node:fs";
|
|
2
2
|
import { resolve, join, dirname, delimiter, basename, isAbsolute, extname, relative } from "node:path";
|
|
3
|
-
import { resolveStorageDirs, shellPath, mergePath, shellPathAsync, createWorkerRpcClient, WorkerUnavailableError, watchFileChanges, readTurnsAt, readTranscript, createMachineLinkHandlers, createMachineHandlers, IPC_BUILD_ID, IPC_PROTOCOL_VERSION, defaultSocketPath, probeSocket, ensureDaemonRunning, connectIpcClient, IpcVersionMismatchError,
|
|
3
|
+
import { resolveStorageDirs, shellPath, mergePath, shellPathAsync, createWorkerRpcClient, WorkerUnavailableError, watchFileChanges, readTurnsAt, readTranscript, createMachineLinkHandlers, createMachineHandlers, runWorkspaceExecStream, loadSessionDocument, IPC_BUILD_ID, IPC_PROTOCOL_VERSION, defaultSocketPath, probeSocket, ensureDaemonRunning, connectIpcClient, IpcVersionMismatchError, WorkerRequestError, loadEventsPage, IpcErrorCode, runRemoteOAuth, extensionInstallErrorData, runBlockOnHost, createExtensionsClient, createHostImagePort, decisionsPort, mcpStatusOf } from "zidane/ipc";
|
|
4
4
|
import { homedir, tmpdir, userInfo, hostname, availableParallelism } from "node:os";
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
6
|
import { config } from "dotenv";
|
|
@@ -8,9 +8,9 @@ import * as electron from "electron";
|
|
|
8
8
|
import { shell, app, BrowserWindow, ipcMain, nativeImage, Notification, session, webContents, utilityProcess, protocol, Tray, Menu, powerMonitor, dialog, net, nativeTheme } from "electron";
|
|
9
9
|
import { createSharedWatches, migrateSessionArtifactDirs, createRingBufferSink, fanoutSink, consoleSink, createLogger, installExtensionFromSpec, ExtensionInstallError, updateInstalledExtension, removeInstalledExtension, createExtensionHostRuntimeBridge, registerExtensionApiHostModules, inlineLoadedExtension, loadableExtensionDirs, discoverAndBuildExtensionRegistry, disposeExtensionRegistry, toWireConfigSchema, defaultExtensionScanPaths, createSqliteDriver, createSqliteWriteQueue, createSqliteSessionStore, loginMcpServer, saveMcpClientSecret, resolveInlineSuggestion, createPathAutocompleteProvider, refreshArtifact as refreshArtifact$1, BUILTIN_ARTIFACT_KINDS, renderArtifactRow, sessionsBadges, isThinkingLevel, panelHostRuntime, panelSummaries, loadExtensionPanel, runExtensionPanelAction, subscribeExtensionPanel, normalizeBadgeTarget, extensionBadgeActions, runBadgeAction, createCompletionRunner, completionProviderSummaries, listExtensionPaletteItems, runExtensionPaletteItem, subscribeExtensionPalette, createExtension, listActionSummaries, probeActionStatuses, runExtensionAction, parseGithubRefKey, githubPullUrl, pullFromMeta, githubPullConfirmedAt, isPullFresh, viewForRead, queueGithubPull, pullMeta, referenceProviderWires, createReferenceResolver, GITHUB_PULL_PROVIDER_ID, GITHUB_ISSUE_PROVIDER_ID, registerSessionProcess, treeProcesses, createGpuReader, createOwnedProcesses, listSessionProcesses, listOwnedProcesses, ownCommands, readProcessTree, labelSessions, originTotals, createMainThreadMeter, createSampler, readOsThreads, configureGithubClient, createFileGithubStateStore } from "zidane";
|
|
10
10
|
import { randomUUID, createHash, randomBytes } from "node:crypto";
|
|
11
|
-
import { parseEditorCommand, keybindingsPath, stripJsonComments, normalizeBindingValue, ensureKeybindingsFile, credentialsPath, applyApiKeyEnv, BUILTIN_PROVIDERS, readCredentials, detectAuth, supportsOAuth, signsInWithIntegration, runIntegrationSignIn, runOAuthLogin, DEFAULT_OAUTH_ACCOUNT_LABEL, setProviderCredential, mcpsWritePath, upsertMcpServer, discoverProjectMcps, removeMcpServer, compactPath as compactPath$1, createExtensionMcpHost, createFileMcpCredentialStore, projectRootOf, runningEstimateViews, resolveConfig, scopeCwd, settingsFromStored, DEFAULT_SETTINGS, SETTINGS_DEFAULTS_VERSION_KEY, SETTINGS_DEFAULTS_VERSION, enforceSettingsInvariants, sparseSettingsUpdate, createMcpStatusTracker, describeForkFailure, DEFAULT_SPACE_ID, SPACE_METADATA_KEY, TITLE_SOURCE_KEY, createCapabilityProbe, createPromptSubmissions, localDayString, summarizeUsage,
|
|
11
|
+
import { parseEditorCommand, keybindingsPath, stripJsonComments, normalizeBindingValue, ensureKeybindingsFile, credentialsPath, applyApiKeyEnv, BUILTIN_PROVIDERS, readCredentials, detectAuth, supportsOAuth, signsInWithIntegration, runIntegrationSignIn, runOAuthLogin, DEFAULT_OAUTH_ACCOUNT_LABEL, setProviderCredential, mcpsWritePath, upsertMcpServer, discoverProjectMcps, removeMcpServer, compactPath as compactPath$1, createExtensionMcpHost, createFileMcpCredentialStore, projectRootOf, runningEstimateViews, resolveConfig, scopeCwd, settingsFromStored, DEFAULT_SETTINGS, SETTINGS_DEFAULTS_VERSION_KEY, SETTINGS_DEFAULTS_VERSION, enforceSettingsInvariants, sparseSettingsUpdate, createMcpStatusTracker, importFromClaudeCode, historySince, describeForkFailure, DEFAULT_SPACE_ID, SPACE_METADATA_KEY, TITLE_SOURCE_KEY, createCapabilityProbe, createPromptSubmissions, localDayString, summarizeUsage, fileEntriesFromPaths, WORKSPACE_MAX_ENTRIES, WORKSPACE_MAX_FILE_BYTES, gitStatusOf, assembleDiff, importEntries, hostImportItems, toolResultText, sumRunCosts, lastContextSizeFromTurns, createChatHost, findGitRoot, availableAgents, liveAgentProfiles, groupArtifacts, defaultModelOf, restoreModelOptions, enabledModelOptions, modelOptionsFor, backfillAccountEmails, readProviderCredential, isSecretCustomField, removeProviderCredential, setPreferredCredential, removeStoredCredential, setCredentialLabel, providerFieldViews, configuredProviderFields, sessionEnvironmentSummary, sessionModelFallbacks, readSessionSpaceId, isMainSession, readSessionAccount, deriveSessionTitle, isStaleRunMarker, cachedRepoKeyOf, spaceIdForNewSession, newSessionModel, defaultSessionModel, defaultSessionKnobs, defaultSessionAgent, modelSupportsReasoning, deleteSessionData, writeSessionExport, hasClaudeCodeSetup, countClaudeSessionFiles, previewClaudeImport, runInProgress, runProgress, resolveSessionCwd, effectiveContextWindow, fmtTokens, getContextWindow, listProjectFiles, discoverProjectPlugins, applyEnvironmentSettingsChange, folderLocation, connectorGithubToken, listExtensionSource, hasUntimedOpenCalls, withRunningCallStarts, listSafelists, removeFromSafelist, buildModelCatalog, modelsForDescriptor, listDecisionModels, listImageModels, testDecisionModel, testModel, providerFactoryOptions, describeTitleStatus, overlayHostSettings, splitHostSettingsPatch, settingsToWire, storeHasDurability, onboardingInstallSignals, needsOnboarding, mergeOnboardingState, migratedOnboardingRecords, detectOnboardingEnvironment, onboardingProviders, BUILTIN_THEMES, toolCallPreview, readSessionEnvironment, assertEnvironmentReady, discoverProjectSkills, fetchAllProviderUsage, fetchProviderUsage, redeemProviderReset, fetchGithubUsage, forgetGitCaches, createGitWatches, watchGitRepository, listWorkspace, resolvePaths, readWorkspaceFile, writeWorkspaceFile, invalidateDiagnostics, listDiagnosticsTools, supersededTools, runDiagnostics, gitStatus, gitDiff, gitShowHead, searchWorkspace, gitInfo, gitOriginUrl, gitPr, gitCommit, gitBranches, gitPrList, gitSwitch, gitCreateBranch, gitSync, workspaceEntryOps, changedCatalogItems, writeCredentialEntry, readCredentialEntry, createProviderBuilder, createArtifactKindsHost, createCatalogPorts, resolveSessionModel, linkCatalogs, readKeybindingsRaw, cloneRepository, fetchRepoInfo, compareSemver, checkForUpdate, watchInstalledVersion, isAutoInstallCandidate, findInstalledCompanion, followRunningUpdate, describeUpdateLockHolder, upgradeError, startUpdateWorker, autoInstallViaWorker, serveWorkspaceMedia } from "zidane/chat";
|
|
12
12
|
import { execFile, spawn } from "node:child_process";
|
|
13
|
-
import { MEDIA_BY_EXTENSION, createPresenceMerge, createHostIndex, LOCAL_HOST_NAME, LOCAL_HOST_KEY, isMethodNotFound, HostRemovedError, sideSessionParent, orchestratedBy, BrowserOpError, normalizeBrowserUrl, isAllowedBrowserUrl, BROWSER_OUTLINE_MAX_ELEMENTS, BROWSER_TEXT_MAX_CHARS, BROWSER_EVALUATE_MAX_BYTES, BROWSER_MAX_WAIT_MS, BROWSER_ACTION_TIMEOUT_MS, BROWSER_WAIT_TIMEOUT_MS, BROWSER_OPEN_MOUNT_MS, TERMINAL_VIEW_MAX_LINES, daemonGate, remoteHostsGate, ARTIFACT_BADGES_MAX, readSessionFacets, isExtensionSpaceId, spacesEnabled, extensionSpace, usageHomeBlock, recentSessionsHomeBlock, HostRegistryError, SYNC_MODES, SYNC_CATEGORIES, isValidMachineName, toMachineName, engagedKillSwitches, isPaletteContext, BASH_CALL_ID_PREFIX, parseMachineKind, mediaTypeOfPath } from "zidane/chat/pure";
|
|
13
|
+
import { MEDIA_BY_EXTENSION, createPresenceMerge, createHostIndex, LOCAL_HOST_NAME, LOCAL_HOST_KEY, isMethodNotFound, HostRemovedError, sideSessionParent, orchestratedBy, BrowserOpError, normalizeBrowserUrl, isAllowedBrowserUrl, BROWSER_OUTLINE_MAX_ELEMENTS, BROWSER_TEXT_MAX_CHARS, BROWSER_EVALUATE_MAX_BYTES, BROWSER_MAX_WAIT_MS, BROWSER_ACTION_TIMEOUT_MS, BROWSER_WAIT_TIMEOUT_MS, BROWSER_OPEN_MOUNT_MS, resolveViewport, TERMINAL_VIEW_MAX_LINES, daemonGate, remoteHostsGate, ARTIFACT_BADGES_MAX, readSessionFacets, isExtensionSpaceId, spacesEnabled, extensionSpace, usageHomeBlock, recentSessionsHomeBlock, HostRegistryError, SYNC_MODES, SYNC_CATEGORIES, isValidMachineName, toMachineName, engagedKillSwitches, isPaletteContext, BASH_CALL_ID_PREFIX, parseMachineKind, mediaTypeOfPath } from "zidane/chat/pure";
|
|
14
14
|
import { createRequire } from "node:module";
|
|
15
15
|
import { DatabaseSync } from "node:sqlite";
|
|
16
16
|
import { changeExtensionOrigin, configuredExtensions, createExtensionsConfigSync, reloadChangedExtensions, readExtensionInstallOrigin, applyExtensionsConfigReport, mergeWireSettings, runtimeSettingsWire, normalizeBadgeTarget as normalizeBadgeTarget$1, isJson, isUiHostModule, resolveUiEntries, UI_TOKEN_NAMES, MAX_LINK_URL_LENGTH, LINK_SOURCES, classifyUiImport, NoUiError, createFileStoragePort, projectStorageFolder, createCredentialsAuthStore, extensionRuntimeOf, loadExtensionsConfig, createConfigSettingsLayer, builtinKeymapEntries } from "zidane/extensions";
|
|
@@ -25,7 +25,7 @@ import { promisify, isDeepStrictEqual } from "node:util";
|
|
|
25
25
|
import { m as mergeUsageBuckets, n as newestUsageDay } from "./chunks/usage-sql-DiITGx8Q.js";
|
|
26
26
|
import { Buffer as Buffer$1 } from "node:buffer";
|
|
27
27
|
import { connect } from "node:net";
|
|
28
|
-
import { a as createLocalHistoryPager, E as EVENTS_PAGE_TURNS } from "./chunks/history-pager-
|
|
28
|
+
import { a as createLocalHistoryPager, E as EVENTS_PAGE_TURNS } from "./chunks/history-pager-DCty1YTu.js";
|
|
29
29
|
import { tailTruncate } from "zidane/tools";
|
|
30
30
|
import { fetchDistManifest, distBaseUrl } from "zidane/dist-feed";
|
|
31
31
|
import { request } from "node:http";
|
|
@@ -376,8 +376,7 @@ function setWindowFactory(make) {
|
|
|
376
376
|
}
|
|
377
377
|
function openMainWindow() {
|
|
378
378
|
if (main && !main.isDestroyed()) {
|
|
379
|
-
main
|
|
380
|
-
main.focus();
|
|
379
|
+
bringForward(main, true);
|
|
381
380
|
return main;
|
|
382
381
|
}
|
|
383
382
|
if (!factory) throw new Error("window factory not set");
|
|
@@ -735,6 +734,74 @@ function resolveDaemonSpawnCommand(options = {}) {
|
|
|
735
734
|
"Cannot start daemon. Install the Zidane CLI, or install Bun with an accessible zidane daemon entry."
|
|
736
735
|
);
|
|
737
736
|
}
|
|
737
|
+
const RELAYED_MAX = 512;
|
|
738
|
+
function sessionOf(signal) {
|
|
739
|
+
const id = signal.sessionId;
|
|
740
|
+
return typeof id === "string" ? id : void 0;
|
|
741
|
+
}
|
|
742
|
+
function createResumingRelay(deliver2) {
|
|
743
|
+
const relayed = /* @__PURE__ */ new Map();
|
|
744
|
+
let epoch;
|
|
745
|
+
let held = null;
|
|
746
|
+
let generation = 0;
|
|
747
|
+
const pass = (signal, meta) => {
|
|
748
|
+
const sessionId = sessionOf(signal);
|
|
749
|
+
if (meta && sessionId !== void 0) {
|
|
750
|
+
const last = relayed.get(sessionId);
|
|
751
|
+
if (last !== void 0 && meta.seq <= last) return;
|
|
752
|
+
relayed.delete(sessionId);
|
|
753
|
+
relayed.set(sessionId, meta.seq);
|
|
754
|
+
if (relayed.size > RELAYED_MAX) relayed.delete(relayed.keys().next().value);
|
|
755
|
+
if (signal.kind === "sessions:changed" && signal.op === "delete") relayed.delete(sessionId);
|
|
756
|
+
}
|
|
757
|
+
deliver2(signal);
|
|
758
|
+
};
|
|
759
|
+
return {
|
|
760
|
+
relay(signal, meta) {
|
|
761
|
+
if (held) held.push({ signal, ...meta ? { meta } : {} });
|
|
762
|
+
else pass(signal, meta);
|
|
763
|
+
},
|
|
764
|
+
async attach(client2) {
|
|
765
|
+
const mine = ++generation;
|
|
766
|
+
const current2 = () => generation === mine;
|
|
767
|
+
const release = () => {
|
|
768
|
+
if (!current2() || !held) return;
|
|
769
|
+
const queue = held;
|
|
770
|
+
held = null;
|
|
771
|
+
for (const { signal, meta } of queue) pass(signal, meta);
|
|
772
|
+
};
|
|
773
|
+
const next = client2.hello.signalEpoch;
|
|
774
|
+
const sameProcess = next !== void 0 && next === epoch;
|
|
775
|
+
if (!sameProcess) relayed.clear();
|
|
776
|
+
epoch = next;
|
|
777
|
+
if (!sameProcess || relayed.size === 0) {
|
|
778
|
+
release();
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
held ??= [];
|
|
782
|
+
try {
|
|
783
|
+
await Promise.all(
|
|
784
|
+
[...relayed].map(async ([sessionId, afterSeq]) => {
|
|
785
|
+
const result = await client2.request("sessions.resume", { sessionId, epoch: next, afterSeq }).catch(() => null);
|
|
786
|
+
if (!current2()) return;
|
|
787
|
+
if (!result?.ok) {
|
|
788
|
+
relayed.delete(sessionId);
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
for (const { seq, signal } of result.signals) pass(signal, { seq });
|
|
792
|
+
})
|
|
793
|
+
);
|
|
794
|
+
} finally {
|
|
795
|
+
release();
|
|
796
|
+
}
|
|
797
|
+
},
|
|
798
|
+
forget() {
|
|
799
|
+
generation++;
|
|
800
|
+
held = null;
|
|
801
|
+
relayed.clear();
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
}
|
|
738
805
|
const buffer = createRingBufferSink();
|
|
739
806
|
let broadcast$2 = null;
|
|
740
807
|
function installLogBroadcast(fn) {
|
|
@@ -744,8 +811,8 @@ const guiLogSink = fanoutSink([
|
|
|
744
811
|
buffer,
|
|
745
812
|
...process.env.ZIDANE_DEBUG ? [consoleSink({ minLevel: "warn" })] : [],
|
|
746
813
|
{
|
|
747
|
-
emit(
|
|
748
|
-
broadcast$2?.(
|
|
814
|
+
emit(record2) {
|
|
815
|
+
broadcast$2?.(record2);
|
|
749
816
|
}
|
|
750
817
|
}
|
|
751
818
|
]);
|
|
@@ -812,6 +879,46 @@ const settingsRepo = {
|
|
|
812
879
|
return Object.fromEntries(rows.map((row) => [row.key.slice(prefix.length), row.value]));
|
|
813
880
|
}
|
|
814
881
|
};
|
|
882
|
+
const BROWSER_LEGACY_IMPORTED = "browser_legacy_imported";
|
|
883
|
+
const browserStateRepo = {
|
|
884
|
+
load() {
|
|
885
|
+
const sessions = getDb().prepare("SELECT * FROM browser_sessions ORDER BY updated_at ASC").all();
|
|
886
|
+
const recents = getDb().prepare("SELECT * FROM browser_recents ORDER BY project_key, position ASC").all();
|
|
887
|
+
return { sessions, recents };
|
|
888
|
+
},
|
|
889
|
+
putSession(row) {
|
|
890
|
+
getDb().prepare(
|
|
891
|
+
`INSERT INTO browser_sessions (session_key, url, color_scheme, device_json, updated_at) VALUES (?, ?, ?, ?, ?)
|
|
892
|
+
ON CONFLICT(session_key) DO UPDATE SET url = excluded.url, color_scheme = excluded.color_scheme,
|
|
893
|
+
device_json = excluded.device_json, updated_at = excluded.updated_at`
|
|
894
|
+
).run(row.session_key, row.url, row.color_scheme, row.device_json, row.updated_at);
|
|
895
|
+
},
|
|
896
|
+
deleteSession(sessionKey2) {
|
|
897
|
+
getDb().prepare("DELETE FROM browser_sessions WHERE session_key = ?").run(sessionKey2);
|
|
898
|
+
},
|
|
899
|
+
/** The project's recent pages, replaced by `pages` in their order. */
|
|
900
|
+
setRecents(projectKey, pages2) {
|
|
901
|
+
const database = getDb();
|
|
902
|
+
const insert = database.prepare(
|
|
903
|
+
"INSERT INTO browser_recents (project_key, position, url, title, visited_at) VALUES (?, ?, ?, ?, ?)"
|
|
904
|
+
);
|
|
905
|
+
database.exec("BEGIN");
|
|
906
|
+
try {
|
|
907
|
+
database.prepare("DELETE FROM browser_recents WHERE project_key = ?").run(projectKey);
|
|
908
|
+
pages2.forEach((p, i) => insert.run(projectKey, i, p.url, p.title, p.visited_at));
|
|
909
|
+
database.exec("COMMIT");
|
|
910
|
+
} catch (err) {
|
|
911
|
+
database.exec("ROLLBACK");
|
|
912
|
+
throw err;
|
|
913
|
+
}
|
|
914
|
+
},
|
|
915
|
+
legacyImported() {
|
|
916
|
+
return settingsRepo.get(BROWSER_LEGACY_IMPORTED) !== null;
|
|
917
|
+
},
|
|
918
|
+
markLegacyImported() {
|
|
919
|
+
settingsRepo.set(BROWSER_LEGACY_IMPORTED, String(Date.now()));
|
|
920
|
+
}
|
|
921
|
+
};
|
|
815
922
|
const pendingApprovalsRepo = {
|
|
816
923
|
list() {
|
|
817
924
|
const rows = getDb().prepare("SELECT * FROM pending_approvals ORDER BY created_at ASC").all();
|
|
@@ -992,7 +1099,7 @@ async function readWorkerThreads() {
|
|
|
992
1099
|
return Promise.all(
|
|
993
1100
|
[...tracked].map(async (entry) => {
|
|
994
1101
|
const now = entry.worker.performance.eventLoopUtilization();
|
|
995
|
-
const
|
|
1102
|
+
const busy2 = entry.last ? entry.worker.performance.eventLoopUtilization(now, entry.last).utilization : 0;
|
|
996
1103
|
entry.last = now;
|
|
997
1104
|
await Promise.race([readHeap(entry), wait$1(HEAP_WAIT_MS)]);
|
|
998
1105
|
return {
|
|
@@ -1000,7 +1107,7 @@ async function readWorkerThreads() {
|
|
|
1000
1107
|
label: entry.name,
|
|
1001
1108
|
pid: process.pid,
|
|
1002
1109
|
kind: "worker",
|
|
1003
|
-
busy,
|
|
1110
|
+
busy: busy2,
|
|
1004
1111
|
...entry.heap !== void 0 ? { heap: entry.heap } : {}
|
|
1005
1112
|
};
|
|
1006
1113
|
})
|
|
@@ -1496,16 +1603,9 @@ function open() {
|
|
|
1496
1603
|
function prepare(sql) {
|
|
1497
1604
|
return open().driver.prepare(sql);
|
|
1498
1605
|
}
|
|
1499
|
-
function runWrite(fn) {
|
|
1500
|
-
return open().writes.run(fn);
|
|
1501
|
-
}
|
|
1502
1606
|
function pendingWrites() {
|
|
1503
1607
|
return open().writes.pending();
|
|
1504
1608
|
}
|
|
1505
|
-
function runImmediate(fn) {
|
|
1506
|
-
const { driver, writes } = open();
|
|
1507
|
-
return writes.run(() => driver.immediate(fn));
|
|
1508
|
-
}
|
|
1509
1609
|
function headerFromRow(header) {
|
|
1510
1610
|
return {
|
|
1511
1611
|
id: header.id,
|
|
@@ -1551,6 +1651,7 @@ function buildListFilter(filter) {
|
|
|
1551
1651
|
};
|
|
1552
1652
|
}
|
|
1553
1653
|
const SIDEBAR_HEADER_COLUMNS = `s.id, s.agent_id, s.project_root, s.status, s.metadata, s.created_at, s.updated_at, s.rev,
|
|
1654
|
+
s.last_user_message_at,
|
|
1554
1655
|
(SELECT COUNT(*) FROM artifacts a WHERE a.session_id = s.id) AS artifact_count`;
|
|
1555
1656
|
const SIDEBAR_COUNTS_SQL = `
|
|
1556
1657
|
SELECT
|
|
@@ -1626,6 +1727,7 @@ function sidebarRows(where, limit, params) {
|
|
|
1626
1727
|
return [
|
|
1627
1728
|
{
|
|
1628
1729
|
...headerFromRow(h),
|
|
1730
|
+
...typeof h.last_user_message_at === "number" ? { lastUserMessageAt: h.last_user_message_at } : {},
|
|
1629
1731
|
turnCount: counts.turnCount,
|
|
1630
1732
|
userMessageCount: counts.userMessageCount,
|
|
1631
1733
|
runCount: counts.runCount,
|
|
@@ -1736,40 +1838,6 @@ function sessionsSchemaVersion() {
|
|
|
1736
1838
|
function getSessionStore() {
|
|
1737
1839
|
return open().store;
|
|
1738
1840
|
}
|
|
1739
|
-
async function patchSessionMetadata(id, patch, opts = {}) {
|
|
1740
|
-
const bump = opts.bumpUpdatedAt !== false;
|
|
1741
|
-
await runImmediate(() => {
|
|
1742
|
-
const header = prepare("SELECT metadata FROM sessions WHERE id = ?").get(id);
|
|
1743
|
-
if (!header) return;
|
|
1744
|
-
const merged = JSON.stringify({ ...safeParseRecord(header.metadata), ...patch });
|
|
1745
|
-
if (bump) {
|
|
1746
|
-
prepare("UPDATE sessions SET metadata = ?, updated_at = ?, rev = rev + 1 WHERE id = ?").run(
|
|
1747
|
-
merged,
|
|
1748
|
-
Date.now(),
|
|
1749
|
-
id
|
|
1750
|
-
);
|
|
1751
|
-
} else {
|
|
1752
|
-
prepare("UPDATE sessions SET metadata = ?, rev = rev + 1 WHERE id = ?").run(merged, id);
|
|
1753
|
-
}
|
|
1754
|
-
});
|
|
1755
|
-
}
|
|
1756
|
-
async function patchSessionScope(id, patch) {
|
|
1757
|
-
const sets = [];
|
|
1758
|
-
const params = [];
|
|
1759
|
-
if (patch.projectRoot !== void 0) {
|
|
1760
|
-
sets.push("project_root = ?");
|
|
1761
|
-
params.push(patch.projectRoot === "" ? null : patch.projectRoot);
|
|
1762
|
-
}
|
|
1763
|
-
if (patch.agentId !== void 0) {
|
|
1764
|
-
sets.push("agent_id = ?");
|
|
1765
|
-
params.push(patch.agentId);
|
|
1766
|
-
}
|
|
1767
|
-
if (sets.length === 0) return;
|
|
1768
|
-
sets.push("updated_at = ?", "rev = rev + 1");
|
|
1769
|
-
params.push(Date.now());
|
|
1770
|
-
params.push(id);
|
|
1771
|
-
await runWrite(() => prepare(`UPDATE sessions SET ${sets.join(", ")} WHERE id = ?`).run(...params));
|
|
1772
|
-
}
|
|
1773
1841
|
function getSessionHeader(id) {
|
|
1774
1842
|
const header = prepare(
|
|
1775
1843
|
"SELECT id, agent_id, project_root, status, metadata, created_at, updated_at FROM sessions WHERE id = ?"
|
|
@@ -2233,11 +2301,11 @@ function forgetServerLiveResults(hostId2) {
|
|
|
2233
2301
|
function withLiveResults(sessionId, events) {
|
|
2234
2302
|
const results = bySession.get(sessionId);
|
|
2235
2303
|
if (!results || results.size === 0) return events;
|
|
2236
|
-
const
|
|
2304
|
+
const saved2 = new Set(events.flatMap((e) => e.kind === "tool-result" && e.callId ? [e.callId] : []));
|
|
2237
2305
|
const out = [];
|
|
2238
2306
|
for (const event of events) {
|
|
2239
2307
|
out.push(event);
|
|
2240
|
-
if (event.kind !== "tool" || !event.callId ||
|
|
2308
|
+
if (event.kind !== "tool" || !event.callId || saved2.has(event.callId)) continue;
|
|
2241
2309
|
const live = results.get(event.callId);
|
|
2242
2310
|
if (!live) continue;
|
|
2243
2311
|
out.push({
|
|
@@ -2276,6 +2344,7 @@ function invalidationsOf(signal, hostId2, cwdOf2) {
|
|
|
2276
2344
|
// A machine came or went, or this computer started or stopped using a server as one:
|
|
2277
2345
|
// the environment kinds a new chat can pick (`local@<machine>`) changed with it.
|
|
2278
2346
|
case "machine:status":
|
|
2347
|
+
case "machine:changed":
|
|
2279
2348
|
case "machine:links":
|
|
2280
2349
|
return [{ topic: "settings", hostId: host2 }];
|
|
2281
2350
|
case "turn:end":
|
|
@@ -2452,8 +2521,8 @@ function appIconPath(id) {
|
|
|
2452
2521
|
return id === DEFAULT_APP_ICON ? join(RESOURCES, "icon.png") : join(RESOURCES, "app-icons", `${id}.png`);
|
|
2453
2522
|
}
|
|
2454
2523
|
function currentAppIcon() {
|
|
2455
|
-
const
|
|
2456
|
-
return isAppIconId(
|
|
2524
|
+
const saved2 = settingsRepo.get(SETTING_KEY);
|
|
2525
|
+
return isAppIconId(saved2) ? saved2 : DEFAULT_APP_ICON;
|
|
2457
2526
|
}
|
|
2458
2527
|
const artworks = /* @__PURE__ */ new Map();
|
|
2459
2528
|
const macIcons = /* @__PURE__ */ new Map();
|
|
@@ -2578,6 +2647,193 @@ function registerAppIconIpc() {
|
|
|
2578
2647
|
setAppIcon(id);
|
|
2579
2648
|
});
|
|
2580
2649
|
}
|
|
2650
|
+
let draining = false;
|
|
2651
|
+
let busy = false;
|
|
2652
|
+
const refusers = /* @__PURE__ */ new Map();
|
|
2653
|
+
let boundTimer;
|
|
2654
|
+
let pidTimer;
|
|
2655
|
+
const waiters$1 = /* @__PURE__ */ new Set();
|
|
2656
|
+
const DRAIN_WAIT_MS = 6e4;
|
|
2657
|
+
const PID_POLL_MS = 1e3;
|
|
2658
|
+
const DATABASE_FREE_METHODS = /* @__PURE__ */ new Set([
|
|
2659
|
+
"agents.list",
|
|
2660
|
+
"artifacts.badges",
|
|
2661
|
+
"artifacts.list",
|
|
2662
|
+
"auth.status",
|
|
2663
|
+
"chat.deliveryState",
|
|
2664
|
+
"chat.isRunning",
|
|
2665
|
+
"chat.listWork",
|
|
2666
|
+
"commands.list",
|
|
2667
|
+
"completions.providers",
|
|
2668
|
+
"daemon.info",
|
|
2669
|
+
"drafts.get",
|
|
2670
|
+
"drafts.set",
|
|
2671
|
+
"drafts.setAttachments",
|
|
2672
|
+
"environments.list",
|
|
2673
|
+
"files.list",
|
|
2674
|
+
"files.location",
|
|
2675
|
+
"files.search",
|
|
2676
|
+
"fs.listDirs",
|
|
2677
|
+
"fs.roots",
|
|
2678
|
+
"fs.searchDirs",
|
|
2679
|
+
"git.branches",
|
|
2680
|
+
"git.diff",
|
|
2681
|
+
"git.fileStatus",
|
|
2682
|
+
"git.status",
|
|
2683
|
+
"host.capabilities",
|
|
2684
|
+
"logs.list",
|
|
2685
|
+
"machines.links.status",
|
|
2686
|
+
"machines.list",
|
|
2687
|
+
"mcp.instances",
|
|
2688
|
+
"models.list",
|
|
2689
|
+
"orchestration.list",
|
|
2690
|
+
"orchestration.read",
|
|
2691
|
+
"orchestration.transcript",
|
|
2692
|
+
"palette.list",
|
|
2693
|
+
"panels.list",
|
|
2694
|
+
"perf.history",
|
|
2695
|
+
"perf.threads",
|
|
2696
|
+
"plans.get",
|
|
2697
|
+
"prefs.get",
|
|
2698
|
+
"presence.list",
|
|
2699
|
+
"queue.list",
|
|
2700
|
+
"references.providers",
|
|
2701
|
+
"schedules.fires",
|
|
2702
|
+
"schedules.list",
|
|
2703
|
+
"schedules.status",
|
|
2704
|
+
"search.set",
|
|
2705
|
+
"sessions.artifacts",
|
|
2706
|
+
"sessions.blockRuns",
|
|
2707
|
+
"sessions.cacheImpact",
|
|
2708
|
+
"sessions.cacheReport",
|
|
2709
|
+
"sessions.contextBreakdown",
|
|
2710
|
+
"sessions.contextSegments",
|
|
2711
|
+
"sessions.environmentActions",
|
|
2712
|
+
"sessions.get",
|
|
2713
|
+
"sessions.getHeader",
|
|
2714
|
+
"sessions.getMeta",
|
|
2715
|
+
"sessions.getToolResult",
|
|
2716
|
+
"sessions.getTurn",
|
|
2717
|
+
"sessions.getTurns",
|
|
2718
|
+
"sessions.historySince",
|
|
2719
|
+
"sessions.list",
|
|
2720
|
+
"sessions.listMeta",
|
|
2721
|
+
"sessions.loadEvents",
|
|
2722
|
+
"sessions.titleStatus",
|
|
2723
|
+
"sessions.workspaceFileSize",
|
|
2724
|
+
"sessions.workspaceListFiles",
|
|
2725
|
+
"sessions.workspaceReadFile",
|
|
2726
|
+
"settings.get",
|
|
2727
|
+
"sidebar.getSpace",
|
|
2728
|
+
"sidebar.getViews",
|
|
2729
|
+
"usage.providers",
|
|
2730
|
+
"usage.summary"
|
|
2731
|
+
]);
|
|
2732
|
+
class OlderDaemonBusyError extends Error {
|
|
2733
|
+
constructor() {
|
|
2734
|
+
super(
|
|
2735
|
+
"An older zidane daemon is still finishing its work, and this window saves nothing beside it. To stop it, open the daemon menu (the dot in the footer) and choose Restart daemon now; or wait for its runs to end."
|
|
2736
|
+
);
|
|
2737
|
+
this.name = "OlderDaemonBusyError";
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
function olderDaemonDraining() {
|
|
2741
|
+
return draining;
|
|
2742
|
+
}
|
|
2743
|
+
function olderDaemonAlive() {
|
|
2744
|
+
return draining && refuserAlive();
|
|
2745
|
+
}
|
|
2746
|
+
function olderDaemonRefused(daemonPid) {
|
|
2747
|
+
return draining && daemonPid !== void 0 && refusers.has(daemonPid);
|
|
2748
|
+
}
|
|
2749
|
+
function olderDaemonPids() {
|
|
2750
|
+
if (!draining) return [];
|
|
2751
|
+
return [...refusers].filter(([daemonPid, refuser]) => !refuser.gone && isAlive$1(daemonPid)).map(([daemonPid]) => daemonPid);
|
|
2752
|
+
}
|
|
2753
|
+
const busyListeners = /* @__PURE__ */ new Set();
|
|
2754
|
+
function onOlderDaemonBusy(listener) {
|
|
2755
|
+
busyListeners.add(listener);
|
|
2756
|
+
return () => busyListeners.delete(listener);
|
|
2757
|
+
}
|
|
2758
|
+
function refuserAlive() {
|
|
2759
|
+
for (const [daemonPid, refuser] of refusers) if (!refuser.gone && isAlive$1(daemonPid)) return true;
|
|
2760
|
+
return false;
|
|
2761
|
+
}
|
|
2762
|
+
function olderDaemonBusy() {
|
|
2763
|
+
return busy;
|
|
2764
|
+
}
|
|
2765
|
+
function isAlive$1(processId) {
|
|
2766
|
+
try {
|
|
2767
|
+
process.kill(processId, 0);
|
|
2768
|
+
return true;
|
|
2769
|
+
} catch (err) {
|
|
2770
|
+
return err.code === "EPERM";
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
function startOlderDaemonDrain(daemonPid, exited) {
|
|
2774
|
+
if (daemonPid !== void 0) {
|
|
2775
|
+
const known = refusers.get(daemonPid);
|
|
2776
|
+
if (known) Object.assign(known, { gone: false, exited });
|
|
2777
|
+
else refusers.set(daemonPid, { gone: false, exited });
|
|
2778
|
+
watchRefusers();
|
|
2779
|
+
}
|
|
2780
|
+
if (draining) return;
|
|
2781
|
+
draining = true;
|
|
2782
|
+
busy = false;
|
|
2783
|
+
boundTimer = setTimeout(() => {
|
|
2784
|
+
busy = true;
|
|
2785
|
+
const failed = [...waiters$1];
|
|
2786
|
+
waiters$1.clear();
|
|
2787
|
+
for (const waiter of failed) waiter.reject(new OlderDaemonBusyError());
|
|
2788
|
+
for (const listener of [...busyListeners]) listener();
|
|
2789
|
+
}, DRAIN_WAIT_MS);
|
|
2790
|
+
boundTimer.unref?.();
|
|
2791
|
+
}
|
|
2792
|
+
function watchRefusers() {
|
|
2793
|
+
if (pidTimer) return;
|
|
2794
|
+
pidTimer = setInterval(() => {
|
|
2795
|
+
const exits = [];
|
|
2796
|
+
let running2 = false;
|
|
2797
|
+
for (const [daemonPid, refuser] of refusers) {
|
|
2798
|
+
if (refuser.gone) continue;
|
|
2799
|
+
if (isAlive$1(daemonPid)) {
|
|
2800
|
+
running2 = true;
|
|
2801
|
+
continue;
|
|
2802
|
+
}
|
|
2803
|
+
refuser.gone = true;
|
|
2804
|
+
exits.push(refuser.exited ?? settleOlderDaemonDrain);
|
|
2805
|
+
}
|
|
2806
|
+
if (!running2 && pidTimer) {
|
|
2807
|
+
clearInterval(pidTimer);
|
|
2808
|
+
pidTimer = void 0;
|
|
2809
|
+
}
|
|
2810
|
+
for (const exit of exits) exit();
|
|
2811
|
+
}, PID_POLL_MS);
|
|
2812
|
+
pidTimer.unref?.();
|
|
2813
|
+
}
|
|
2814
|
+
function endOlderDaemonDrain() {
|
|
2815
|
+
if (boundTimer) clearTimeout(boundTimer);
|
|
2816
|
+
if (pidTimer) clearInterval(pidTimer);
|
|
2817
|
+
boundTimer = void 0;
|
|
2818
|
+
pidTimer = void 0;
|
|
2819
|
+
refusers.clear();
|
|
2820
|
+
if (!draining) return;
|
|
2821
|
+
draining = false;
|
|
2822
|
+
busy = false;
|
|
2823
|
+
const resolved = [...waiters$1];
|
|
2824
|
+
waiters$1.clear();
|
|
2825
|
+
for (const waiter of resolved) waiter.resolve();
|
|
2826
|
+
}
|
|
2827
|
+
function settleOlderDaemonDrain() {
|
|
2828
|
+
if (!draining) return;
|
|
2829
|
+
if (refuserAlive()) return;
|
|
2830
|
+
endOlderDaemonDrain();
|
|
2831
|
+
}
|
|
2832
|
+
function untilOlderDaemonGone(method) {
|
|
2833
|
+
if (!draining || method !== void 0 && DATABASE_FREE_METHODS.has(method)) return null;
|
|
2834
|
+
if (busy) return Promise.reject(new OlderDaemonBusyError());
|
|
2835
|
+
return new Promise((resolve2, reject) => waiters$1.add({ resolve: resolve2, reject }));
|
|
2836
|
+
}
|
|
2581
2837
|
let handlers = null;
|
|
2582
2838
|
const NO_PEER = { ready: true, watching: null, send: () => void 0 };
|
|
2583
2839
|
function embeddedMachineHandlers() {
|
|
@@ -2634,15 +2890,16 @@ const EMBEDDED = {
|
|
|
2634
2890
|
...p.since !== void 0 ? { since: p.since } : {},
|
|
2635
2891
|
...p.limit !== void 0 ? { limit: p.limit } : {}
|
|
2636
2892
|
}) ?? [],
|
|
2637
|
-
|
|
2638
|
-
|
|
2893
|
+
// Writes go through the host's store, so the session's row (its artifact count) is announced.
|
|
2894
|
+
"artifacts.delete": async (host2, p) => {
|
|
2895
|
+
const store = host2().store;
|
|
2639
2896
|
if (!store.deleteArtifact) return false;
|
|
2640
2897
|
await store.deleteArtifact(p.sessionId, p.artifactId);
|
|
2641
2898
|
broadcast({ kind: "artifact:changed", sessionId: p.sessionId, op: "delete", artifactId: p.artifactId });
|
|
2642
2899
|
return true;
|
|
2643
2900
|
},
|
|
2644
|
-
"artifacts.upsert": async (
|
|
2645
|
-
const stored = await
|
|
2901
|
+
"artifacts.upsert": async (host2, p) => {
|
|
2902
|
+
const stored = await host2().store.upsertArtifact?.(p.artifact) ?? null;
|
|
2646
2903
|
if (stored) {
|
|
2647
2904
|
broadcast({
|
|
2648
2905
|
kind: "artifact:changed",
|
|
@@ -2676,8 +2933,13 @@ const EMBEDDED = {
|
|
|
2676
2933
|
"sessions.setFavorite": (host2, p) => host2().patchSessionMeta(p.sessionId, { favorite: p.favorite }, { bumpUpdatedAt: false }),
|
|
2677
2934
|
"sessions.setAgentId": async (host2, p) => {
|
|
2678
2935
|
const rebuild = host2().agentSwitchRebuilds(p.sessionId, p.agentId);
|
|
2679
|
-
await host2().setLiveSessionAgentId(p.sessionId, p.agentId)
|
|
2680
|
-
|
|
2936
|
+
if (!await host2().setLiveSessionAgentId(p.sessionId, p.agentId)) {
|
|
2937
|
+
const store = host2().store;
|
|
2938
|
+
const data = await store.load(p.sessionId);
|
|
2939
|
+
if (!data) throw new Error(`Session "${p.sessionId}" not found.`);
|
|
2940
|
+
const next = { ...data, agentId: p.agentId, updatedAt: Date.now() };
|
|
2941
|
+
await (store.saveMeta ? store.saveMeta(next, { metaKeys: [] }) : store.save(next));
|
|
2942
|
+
}
|
|
2681
2943
|
if (rebuild) await host2().disposeAgentForRebuild(p.sessionId);
|
|
2682
2944
|
},
|
|
2683
2945
|
"sessions.setEffort": (host2, p) => host2().patchSessionMeta(p.sessionId, { effort: p.effort }),
|
|
@@ -2715,6 +2977,8 @@ const EMBEDDED = {
|
|
|
2715
2977
|
"sessions.rewind": (host2, p) => host2().rewindSession(p.sessionId, p.turnId, { inclusive: p.inclusive }),
|
|
2716
2978
|
"sessions.setFolder": (host2, p) => host2().setSessionFolder(p.sessionId, p.cwd),
|
|
2717
2979
|
"sessions.appendTurns": (host2, p) => host2().appendTurns(p.sessionId, p.turns, { whenIdle: p.whenIdle === true }),
|
|
2980
|
+
// The reconnect ladder's second step, from the host's (announcing) store.
|
|
2981
|
+
"sessions.historySince": (host2, p) => historySince(host2().store, p.sessionId, p.afterPos, p.historyId),
|
|
2718
2982
|
"queue.list": (host2, p) => host2().queueList(p.sessionId),
|
|
2719
2983
|
"queue.add": (host2, p) => submissions(host2).queueAdd(p.sessionId, p.text, p.activatedSkills, p.attachments, void 0, void 0, p.delivery),
|
|
2720
2984
|
"queue.remove": (host2, p) => host2().queueRemove(p.sessionId, p.id),
|
|
@@ -2766,7 +3030,17 @@ const EMBEDDED = {
|
|
|
2766
3030
|
"machines.share.stop": (_host, p) => embeddedMachineHandlers()["machines.share.stop"](p, NO_PEER),
|
|
2767
3031
|
"machines.useServer": (_host, p) => embeddedMachineHandlers()["machines.useServer"](p, NO_PEER),
|
|
2768
3032
|
"mcp.instances": (host2, p) => host2().mcpServers.instances(p?.cwd),
|
|
2769
|
-
"mcp.restart": async (host2, p) => ({ restarted: await host2().mcpServers.restart(p.name, p.cwd) })
|
|
3033
|
+
"mcp.restart": async (host2, p) => ({ restarted: await host2().mcpServers.restart(p.name, p.cwd) }),
|
|
3034
|
+
// Imports through the host's store, which announces each session, as the daemon's `claudeImport.run` does.
|
|
3035
|
+
"claudeImport.run": (host2, p) => importFromClaudeCode(host2().store, {
|
|
3036
|
+
cwd: scopeCwd(p.cwd ?? ""),
|
|
3037
|
+
sessions: p.sessions,
|
|
3038
|
+
mcps: p.mcps,
|
|
3039
|
+
skills: p.skills,
|
|
3040
|
+
commands: p.commands,
|
|
3041
|
+
agents: p.agents ?? p.commands,
|
|
3042
|
+
allProjects: p.allProjects
|
|
3043
|
+
})
|
|
2770
3044
|
};
|
|
2771
3045
|
let localProbe = null;
|
|
2772
3046
|
function localCapabilities(host2) {
|
|
@@ -2778,7 +3052,7 @@ function localCapabilities(host2) {
|
|
|
2778
3052
|
...d.reason ? { reason: d.reason } : {}
|
|
2779
3053
|
})),
|
|
2780
3054
|
roots: () => [homedir()],
|
|
2781
|
-
allows: () => ({ remoteInstalls: false, asMachine: false, sync: false
|
|
3055
|
+
allows: () => ({ remoteInstalls: false, asMachine: false, sync: false })
|
|
2782
3056
|
});
|
|
2783
3057
|
return localProbe;
|
|
2784
3058
|
}
|
|
@@ -2799,6 +3073,7 @@ function hostClient() {
|
|
|
2799
3073
|
return daemon2 ? daemonHostClient(daemon2) : embeddedHostClient();
|
|
2800
3074
|
}
|
|
2801
3075
|
async function hostRequest(method, params, options = {}) {
|
|
3076
|
+
await untilOlderDaemonGone(method);
|
|
2802
3077
|
const client2 = hostClient();
|
|
2803
3078
|
if (client2.mode === "embedded" || !options.fallback) return client2.request(method, params);
|
|
2804
3079
|
try {
|
|
@@ -2813,13 +3088,29 @@ async function hostRequest(method, params, options = {}) {
|
|
|
2813
3088
|
}
|
|
2814
3089
|
}
|
|
2815
3090
|
function hostNotify(method, params) {
|
|
3091
|
+
const draining2 = untilOlderDaemonGone(method);
|
|
3092
|
+
if (draining2) {
|
|
3093
|
+
void draining2.then(
|
|
3094
|
+
() => hostClient().notify(method, params),
|
|
3095
|
+
(err) => guiLog.warn(`${method} dropped: an older daemon is still busy`, {
|
|
3096
|
+
scope: "daemon",
|
|
3097
|
+
error: err?.message ?? String(err)
|
|
3098
|
+
})
|
|
3099
|
+
);
|
|
3100
|
+
return;
|
|
3101
|
+
}
|
|
2816
3102
|
hostClient().notify(method, params);
|
|
2817
3103
|
}
|
|
3104
|
+
async function hostCreateSession(params) {
|
|
3105
|
+
await untilOlderDaemonGone("sessions.create");
|
|
3106
|
+
return hostClient().createSession(params);
|
|
3107
|
+
}
|
|
2818
3108
|
const hostClient$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
2819
3109
|
__proto__: null,
|
|
2820
3110
|
daemonHostClient,
|
|
2821
3111
|
embeddedHostClient,
|
|
2822
3112
|
hostClient,
|
|
3113
|
+
hostCreateSession,
|
|
2823
3114
|
hostNotify,
|
|
2824
3115
|
hostRequest
|
|
2825
3116
|
}, Symbol.toStringTag, { value: "Module" }));
|
|
@@ -2847,7 +3138,7 @@ const localHost$1 = {
|
|
|
2847
3138
|
remote: false,
|
|
2848
3139
|
request: (method, params, options) => hostRequest(method, params, options),
|
|
2849
3140
|
notify: (method, params) => hostNotify(method, params),
|
|
2850
|
-
createSession: (params) =>
|
|
3141
|
+
createSession: (params) => hostCreateSession(params)
|
|
2851
3142
|
};
|
|
2852
3143
|
function storeHasSession(sessionId) {
|
|
2853
3144
|
try {
|
|
@@ -3259,9 +3550,9 @@ function createUsageBuckets(deps2) {
|
|
|
3259
3550
|
}
|
|
3260
3551
|
async function restore() {
|
|
3261
3552
|
try {
|
|
3262
|
-
const
|
|
3263
|
-
if (!held &&
|
|
3264
|
-
held = { buckets:
|
|
3553
|
+
const saved2 = JSON.parse(await readFile(deps2.savedFile(), "utf8"));
|
|
3554
|
+
if (!held && saved2.format === SAVED_FORMAT && saved2.dbPath === deps2.dbPath() && saved2.schemaVersion === deps2.schemaVersion() && isBuckets(saved2.buckets)) {
|
|
3555
|
+
held = { buckets: saved2.buckets, loadedAt: 0, fullAt: null };
|
|
3265
3556
|
}
|
|
3266
3557
|
} catch {
|
|
3267
3558
|
}
|
|
@@ -3269,14 +3560,14 @@ function createUsageBuckets(deps2) {
|
|
|
3269
3560
|
function save(buckets) {
|
|
3270
3561
|
saving = saving.then(async () => {
|
|
3271
3562
|
const file = deps2.savedFile();
|
|
3272
|
-
const
|
|
3563
|
+
const saved2 = {
|
|
3273
3564
|
format: SAVED_FORMAT,
|
|
3274
3565
|
dbPath: deps2.dbPath(),
|
|
3275
3566
|
schemaVersion: deps2.schemaVersion(),
|
|
3276
3567
|
buckets
|
|
3277
3568
|
};
|
|
3278
3569
|
await mkdir(dirname(file), { recursive: true });
|
|
3279
|
-
await writeFile(`${file}.tmp`, JSON.stringify(
|
|
3570
|
+
await writeFile(`${file}.tmp`, JSON.stringify(saved2));
|
|
3280
3571
|
await rename(`${file}.tmp`, file);
|
|
3281
3572
|
}).catch(debugFailure);
|
|
3282
3573
|
}
|
|
@@ -3372,6 +3663,15 @@ async function getUsageSummary(range, { now = /* @__PURE__ */ new Date(), projec
|
|
|
3372
3663
|
}
|
|
3373
3664
|
const BROWSER_DEVTOOLS_PARTITION = "zidane-browser-devtools";
|
|
3374
3665
|
const BROWSER_DEVTOOLS_BLANK = "devtools://devtools/bundled/Images/empty.svg";
|
|
3666
|
+
const DEVICE_MARGIN = 16;
|
|
3667
|
+
function deviceFit(slot, device) {
|
|
3668
|
+
const room = {
|
|
3669
|
+
width: Math.max(1, slot.width - DEVICE_MARGIN * 2),
|
|
3670
|
+
height: Math.max(1, slot.height - DEVICE_MARGIN * 2)
|
|
3671
|
+
};
|
|
3672
|
+
const scale = Math.min(1, room.width / device.width, room.height / device.height);
|
|
3673
|
+
return Math.max(0.05, Math.floor(scale * 100) / 100);
|
|
3674
|
+
}
|
|
3375
3675
|
const HELPERS = {
|
|
3376
3676
|
pause: "annotatePause",
|
|
3377
3677
|
remove: "annotateRemove",
|
|
@@ -3538,6 +3838,35 @@ function pageHelpers(markColor) {
|
|
|
3538
3838
|
report?.(JSON.stringify({ kind, x: point.clientX ?? null, y: point.clientY ?? null }));
|
|
3539
3839
|
};
|
|
3540
3840
|
window.addEventListener("pointerdown", human("pointer"), true);
|
|
3841
|
+
let lastTouchEnd = null;
|
|
3842
|
+
let clickedAfterTouch = false;
|
|
3843
|
+
let tapClickUntil = 0;
|
|
3844
|
+
let tapClicked = false;
|
|
3845
|
+
window.addEventListener(
|
|
3846
|
+
"touchend",
|
|
3847
|
+
(e) => {
|
|
3848
|
+
if (!e.isTrusted) return;
|
|
3849
|
+
lastTouchEnd = e;
|
|
3850
|
+
clickedAfterTouch = false;
|
|
3851
|
+
},
|
|
3852
|
+
true
|
|
3853
|
+
);
|
|
3854
|
+
window.addEventListener(
|
|
3855
|
+
"click",
|
|
3856
|
+
(e) => {
|
|
3857
|
+
if (!e.isTrusted) return;
|
|
3858
|
+
if (Date.now() < tapClickUntil) {
|
|
3859
|
+
if (tapClicked) {
|
|
3860
|
+
e.preventDefault();
|
|
3861
|
+
e.stopImmediatePropagation();
|
|
3862
|
+
return;
|
|
3863
|
+
}
|
|
3864
|
+
tapClicked = true;
|
|
3865
|
+
}
|
|
3866
|
+
if (lastTouchEnd) clickedAfterTouch = true;
|
|
3867
|
+
},
|
|
3868
|
+
true
|
|
3869
|
+
);
|
|
3541
3870
|
window.addEventListener("keydown", human("key"), true);
|
|
3542
3871
|
const INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
|
|
3543
3872
|
"button",
|
|
@@ -4305,7 +4634,30 @@ function pageHelpers(markColor) {
|
|
|
4305
4634
|
mutations = 0;
|
|
4306
4635
|
},
|
|
4307
4636
|
mutations: () => mutations,
|
|
4308
|
-
viewport: () => ({ width: innerWidth, height: innerHeight, dpr: devicePixelRatio })
|
|
4637
|
+
viewport: () => ({ width: innerWidth, height: innerHeight, dpr: devicePixelRatio }),
|
|
4638
|
+
tapOutcome: () => {
|
|
4639
|
+
const outcome2 = lastTouchEnd?.defaultPrevented ? "cancelled" : clickedAfterTouch ? "clicked" : null;
|
|
4640
|
+
lastTouchEnd = null;
|
|
4641
|
+
clickedAfterTouch = false;
|
|
4642
|
+
tapClicked = false;
|
|
4643
|
+
tapClickUntil = outcome2 === null ? Date.now() + 500 : 0;
|
|
4644
|
+
return outcome2;
|
|
4645
|
+
},
|
|
4646
|
+
/*
|
|
4647
|
+
* After an emulation change: until the screen has the device's size
|
|
4648
|
+
* (`null`: any), then two frames, so the next capture shows the new
|
|
4649
|
+
* layout. Bounded by `ms`: a page that does not draw still answers.
|
|
4650
|
+
*/
|
|
4651
|
+
settle: (width, height, ms) => new Promise((resolve22) => {
|
|
4652
|
+
const end = Date.now() + ms;
|
|
4653
|
+
setTimeout(resolve22, ms);
|
|
4654
|
+
const check = () => {
|
|
4655
|
+
if (width === null || screen.width === width && screen.height === height || Date.now() > end)
|
|
4656
|
+
requestAnimationFrame(() => requestAnimationFrame(() => resolve22()));
|
|
4657
|
+
else requestAnimationFrame(check);
|
|
4658
|
+
};
|
|
4659
|
+
check();
|
|
4660
|
+
})
|
|
4309
4661
|
};
|
|
4310
4662
|
}
|
|
4311
4663
|
const PAGE_HELPERS_SOURCE = `(${pageHelpers.toString()})(${JSON.stringify(MARK_COLOR)})`;
|
|
@@ -4314,6 +4666,7 @@ const WORLD = "zidane";
|
|
|
4314
4666
|
const CDP_TIMEOUT_MS = 1e4;
|
|
4315
4667
|
const CONSOLE_CAP = 300;
|
|
4316
4668
|
const SCREENSHOT_MAX_WIDTH = 1280;
|
|
4669
|
+
const VIEWPORT_SETTLE_MS = 2e3;
|
|
4317
4670
|
const OWN_INPUT_ECHO_MS = 3e3;
|
|
4318
4671
|
const HELPERS_MISSING = "__zg_missing__";
|
|
4319
4672
|
const WORLD_GONE = /context|Execution context was destroyed|Inspected target navigated|Cannot find/i;
|
|
@@ -4369,7 +4722,7 @@ class PageDriver {
|
|
|
4369
4722
|
drivingTimer = null;
|
|
4370
4723
|
driving = false;
|
|
4371
4724
|
tokens = /* @__PURE__ */ new Set();
|
|
4372
|
-
/** The color scheme and device the
|
|
4725
|
+
/** The session's color scheme and device (the toolbar's or the agent's); re-applied whenever the debugger attaches again. */
|
|
4373
4726
|
emulation = null;
|
|
4374
4727
|
/** The page's own user agent, restored when a device's goes away. */
|
|
4375
4728
|
ownUserAgent = null;
|
|
@@ -4386,15 +4739,25 @@ class PageDriver {
|
|
|
4386
4739
|
return raceAbort(work, signal);
|
|
4387
4740
|
}
|
|
4388
4741
|
/**
|
|
4389
|
-
* Emulate a color scheme and a device
|
|
4390
|
-
*
|
|
4742
|
+
* Emulate a color scheme and a device, after any running operation. Kept:
|
|
4743
|
+
* a reattached debugger applies it again. A page that never had either is
|
|
4744
|
+
* left alone (nothing attaches to it for nothing), and the same emulation
|
|
4745
|
+
* again is not sent twice.
|
|
4391
4746
|
*/
|
|
4392
4747
|
setEmulation(next) {
|
|
4393
4748
|
const work = this.chain.then(async () => {
|
|
4394
4749
|
if (this.contents.isDestroyed()) return;
|
|
4750
|
+
const plain = next.colorScheme === "system" && !next.device;
|
|
4751
|
+
if (this.emulation ? JSON.stringify(this.emulation) === JSON.stringify(next) : plain) return;
|
|
4752
|
+
const prev = this.emulation;
|
|
4395
4753
|
this.emulation = next;
|
|
4396
|
-
|
|
4397
|
-
|
|
4754
|
+
try {
|
|
4755
|
+
if (this.attached) await this.applyEmulation();
|
|
4756
|
+
else await this.ensureAttached();
|
|
4757
|
+
} catch (err) {
|
|
4758
|
+
this.emulation = prev;
|
|
4759
|
+
throw err;
|
|
4760
|
+
}
|
|
4398
4761
|
});
|
|
4399
4762
|
this.chain = work.catch(() => void 0);
|
|
4400
4763
|
return work;
|
|
@@ -4497,6 +4860,8 @@ class PageDriver {
|
|
|
4497
4860
|
return this.evaluate(input);
|
|
4498
4861
|
case "console":
|
|
4499
4862
|
return Promise.resolve(this.consoleSince(input));
|
|
4863
|
+
case "viewport":
|
|
4864
|
+
return this.settleViewport();
|
|
4500
4865
|
}
|
|
4501
4866
|
}
|
|
4502
4867
|
// ---------------------------------------------------------------------------
|
|
@@ -4551,12 +4916,33 @@ class PageDriver {
|
|
|
4551
4916
|
return { ...shot, visible };
|
|
4552
4917
|
}
|
|
4553
4918
|
async status() {
|
|
4554
|
-
const viewport = await this.helper("viewport", [], 1500).catch(
|
|
4919
|
+
const viewport = await this.helper("viewport", [], 1500).catch(
|
|
4920
|
+
() => void 0
|
|
4921
|
+
);
|
|
4922
|
+
const mobile = this.emulation?.device?.mobile ?? false;
|
|
4555
4923
|
return {
|
|
4556
4924
|
url: this.contents.getURL(),
|
|
4557
4925
|
title: this.contents.getTitle(),
|
|
4558
4926
|
loading: this.contents.isLoading(),
|
|
4559
|
-
...viewport ? { viewport: { width: viewport.width, height: viewport.height } } : {}
|
|
4927
|
+
...viewport ? { viewport: { width: viewport.width, height: viewport.height, dpr: viewport.dpr, mobile } } : {}
|
|
4928
|
+
};
|
|
4929
|
+
}
|
|
4930
|
+
/**
|
|
4931
|
+
* The agent's viewport change, applied before this runs (`setEmulation` is
|
|
4932
|
+
* queued first): once the page laid out at it, where it ended up.
|
|
4933
|
+
*/
|
|
4934
|
+
async settleViewport() {
|
|
4935
|
+
const device = this.emulation?.device ?? null;
|
|
4936
|
+
await this.helper(
|
|
4937
|
+
"settle",
|
|
4938
|
+
[device?.width ?? null, device?.height ?? null, VIEWPORT_SETTLE_MS],
|
|
4939
|
+
VIEWPORT_SETTLE_MS + 2e3,
|
|
4940
|
+
true
|
|
4941
|
+
).catch(() => void 0);
|
|
4942
|
+
return {
|
|
4943
|
+
status: await this.status(),
|
|
4944
|
+
device: device?.label ?? null,
|
|
4945
|
+
colorScheme: this.emulation?.colorScheme ?? "system"
|
|
4560
4946
|
};
|
|
4561
4947
|
}
|
|
4562
4948
|
async navigate(input) {
|
|
@@ -4724,9 +5110,19 @@ class PageDriver {
|
|
|
4724
5110
|
this.events.pointer({ ...point, phase: "move" });
|
|
4725
5111
|
const until = Date.now() + OWN_INPUT_ECHO_MS;
|
|
4726
5112
|
this.ownPointers = [...this.ownPointers.filter((p) => p.until > Date.now()), { ...point, until }];
|
|
4727
|
-
const
|
|
5113
|
+
const scale = this.emulation?.device?.scale ?? 1;
|
|
5114
|
+
const at = { x: point.x * scale, y: point.y * scale };
|
|
4728
5115
|
await this.annotations.withoutCapture(async () => {
|
|
4729
|
-
|
|
5116
|
+
if (this.emulation?.device?.mobile) {
|
|
5117
|
+
await this.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [at] });
|
|
5118
|
+
await this.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
|
|
5119
|
+
if (await this.helper("tapOutcome", []).catch(() => null) !== null) {
|
|
5120
|
+
this.events.pointer({ ...point, phase: "click" });
|
|
5121
|
+
return;
|
|
5122
|
+
}
|
|
5123
|
+
}
|
|
5124
|
+
const base = { ...at, button: "left", clickCount: 1 };
|
|
5125
|
+
await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", ...at });
|
|
4730
5126
|
await this.send("Input.dispatchMouseEvent", { type: "mousePressed", ...base });
|
|
4731
5127
|
this.events.pointer({ ...point, phase: "click" });
|
|
4732
5128
|
await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", ...base });
|
|
@@ -4977,7 +5373,7 @@ class PageDriver {
|
|
|
4977
5373
|
/** Call `globalThis.__zg[name](...args)` in the isolated world; helper errors become `BrowserOpError`s. */
|
|
4978
5374
|
async helper(name, args, timeoutMs = CDP_TIMEOUT_MS, awaitPromise = false) {
|
|
4979
5375
|
const expression = `globalThis.__zg ? globalThis.__zg.${name}(...${JSON.stringify(args)}) : ${JSON.stringify(HELPERS_MISSING)}`;
|
|
4980
|
-
for (let
|
|
5376
|
+
for (let attempt2 = 0; ; attempt2++) {
|
|
4981
5377
|
const contextId = await this.ensureWorld();
|
|
4982
5378
|
let res;
|
|
4983
5379
|
try {
|
|
@@ -4987,7 +5383,7 @@ class PageDriver {
|
|
|
4987
5383
|
timeoutMs
|
|
4988
5384
|
);
|
|
4989
5385
|
} catch (err) {
|
|
4990
|
-
if (
|
|
5386
|
+
if (attempt2 < 2 && WORLD_GONE.test(String(err.message))) {
|
|
4991
5387
|
this.contextId = null;
|
|
4992
5388
|
continue;
|
|
4993
5389
|
}
|
|
@@ -4995,7 +5391,7 @@ class PageDriver {
|
|
|
4995
5391
|
}
|
|
4996
5392
|
if (res.exceptionDetails) throw new BrowserOpError("failed", exceptionText(res.exceptionDetails));
|
|
4997
5393
|
if (res.result.value === HELPERS_MISSING) {
|
|
4998
|
-
if (
|
|
5394
|
+
if (attempt2 >= 2) throw new BrowserOpError("failed", "The page helpers could not be loaded in this document.");
|
|
4999
5395
|
try {
|
|
5000
5396
|
await this.installHelpers(contextId);
|
|
5001
5397
|
} catch (err) {
|
|
@@ -5278,9 +5674,247 @@ function hardenGuest(win, guest) {
|
|
|
5278
5674
|
child.webContents.on("will-redirect", refuse);
|
|
5279
5675
|
});
|
|
5280
5676
|
}
|
|
5677
|
+
const BROWSER_SESSION_DEFAULTS = Object.freeze({
|
|
5678
|
+
url: "",
|
|
5679
|
+
colorScheme: "system",
|
|
5680
|
+
device: null
|
|
5681
|
+
});
|
|
5682
|
+
function asColorScheme(value) {
|
|
5683
|
+
return value === "system" || value === "light" || value === "dark" ? value : null;
|
|
5684
|
+
}
|
|
5685
|
+
function asBrowserDevice(value) {
|
|
5686
|
+
const d = value;
|
|
5687
|
+
if (!d || typeof d !== "object") return void 0;
|
|
5688
|
+
const size = (n) => typeof n === "number" && Number.isFinite(n) && n >= 1 && n <= 1e4;
|
|
5689
|
+
const text2 = (s, max) => typeof s === "string" && s.length > 0 && s.length <= max;
|
|
5690
|
+
const ok = text2(d.id, 64) && text2(d.label, 128) && size(d.width) && size(d.height) && (d.dpr === null || typeof d.dpr === "number" && d.dpr > 0 && d.dpr <= 8) && typeof d.mobile === "boolean" && (d.userAgent === null || text2(d.userAgent, 512));
|
|
5691
|
+
return ok ? {
|
|
5692
|
+
id: d.id,
|
|
5693
|
+
label: d.label,
|
|
5694
|
+
width: d.width,
|
|
5695
|
+
height: d.height,
|
|
5696
|
+
dpr: d.dpr,
|
|
5697
|
+
mobile: d.mobile,
|
|
5698
|
+
userAgent: d.userAgent
|
|
5699
|
+
} : void 0;
|
|
5700
|
+
}
|
|
5701
|
+
const MAX_BROWSER_SESSIONS = 50;
|
|
5702
|
+
const MAX_RECENT_PAGES = 6;
|
|
5703
|
+
function createBrowserState(repo, send, now = Date.now) {
|
|
5704
|
+
let cache = null;
|
|
5705
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
5706
|
+
const load2 = () => {
|
|
5707
|
+
if (cache) return cache;
|
|
5708
|
+
const rows = repo.load();
|
|
5709
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
5710
|
+
for (const row of rows.sessions) sessions.set(row.session_key, sessionFromRow(row));
|
|
5711
|
+
const recents = /* @__PURE__ */ new Map();
|
|
5712
|
+
for (const row of rows.recents) {
|
|
5713
|
+
const list = recents.get(row.project_key) ?? [];
|
|
5714
|
+
list.push({ url: row.url, title: row.title, visitedAt: row.visited_at });
|
|
5715
|
+
recents.set(row.project_key, list);
|
|
5716
|
+
}
|
|
5717
|
+
cache = { sessions, recents };
|
|
5718
|
+
return cache;
|
|
5719
|
+
};
|
|
5720
|
+
const session2 = (sessionId) => load2().sessions.get(sessionId) ?? BROWSER_SESSION_DEFAULTS;
|
|
5721
|
+
const writeSession = (sessionId, next) => {
|
|
5722
|
+
const { sessions } = load2();
|
|
5723
|
+
sessions.delete(sessionId);
|
|
5724
|
+
if (isDefault(next)) repo.deleteSession(sessionId);
|
|
5725
|
+
else {
|
|
5726
|
+
sessions.set(sessionId, next);
|
|
5727
|
+
repo.putSession(rowFromSession(sessionId, next, now()));
|
|
5728
|
+
}
|
|
5729
|
+
send({ kind: "session", sessionId, session: next });
|
|
5730
|
+
for (const old of [...sessions.keys()].slice(0, Math.max(0, sessions.size - MAX_BROWSER_SESSIONS))) {
|
|
5731
|
+
const dropped = sessions.get(old);
|
|
5732
|
+
sessions.delete(old);
|
|
5733
|
+
repo.deleteSession(old);
|
|
5734
|
+
send({ kind: "session", sessionId: old, session: BROWSER_SESSION_DEFAULTS });
|
|
5735
|
+
if (dropped.colorScheme !== "system" || dropped.device)
|
|
5736
|
+
for (const listener of listeners) listener(old, { colorScheme: "system", device: null });
|
|
5737
|
+
}
|
|
5738
|
+
};
|
|
5739
|
+
const writeRecents = (project, pages2) => {
|
|
5740
|
+
const { recents } = load2();
|
|
5741
|
+
const kept = pages2.slice(0, MAX_RECENT_PAGES);
|
|
5742
|
+
if (kept.length) recents.set(project, kept);
|
|
5743
|
+
else recents.delete(project);
|
|
5744
|
+
repo.setRecents(
|
|
5745
|
+
project,
|
|
5746
|
+
kept.map((p) => ({ url: p.url, title: p.title, visited_at: p.visitedAt }))
|
|
5747
|
+
);
|
|
5748
|
+
send({ kind: "recents", project, pages: kept });
|
|
5749
|
+
};
|
|
5750
|
+
return {
|
|
5751
|
+
snapshot() {
|
|
5752
|
+
const { sessions, recents } = load2();
|
|
5753
|
+
return { sessions: Object.fromEntries(sessions), recents: Object.fromEntries(recents) };
|
|
5754
|
+
},
|
|
5755
|
+
session: session2,
|
|
5756
|
+
/** The toolbar's or the agent's color scheme and device for the session. */
|
|
5757
|
+
setEmulation(sessionId, emulation) {
|
|
5758
|
+
const prev = session2(sessionId);
|
|
5759
|
+
if (prev.colorScheme === emulation.colorScheme && sameDevice(prev.device, emulation.device)) return;
|
|
5760
|
+
writeSession(sessionId, { ...prev, colorScheme: emulation.colorScheme, device: emulation.device });
|
|
5761
|
+
for (const listener of listeners)
|
|
5762
|
+
listener(sessionId, { colorScheme: emulation.colorScheme, device: emulation.device });
|
|
5763
|
+
},
|
|
5764
|
+
/** The page's last committed URL; `''` forgets it (the start page). */
|
|
5765
|
+
rememberUrl(sessionId, url) {
|
|
5766
|
+
const prev = session2(sessionId);
|
|
5767
|
+
if (prev.url === url) return;
|
|
5768
|
+
writeSession(sessionId, { ...prev, url });
|
|
5769
|
+
},
|
|
5770
|
+
/** A page that loaded goes first in its project's recents; an in-page route of it is the same visit. */
|
|
5771
|
+
recordVisit(project, url, title) {
|
|
5772
|
+
const list = load2().recents.get(project) ?? [];
|
|
5773
|
+
const key = pageKey(url);
|
|
5774
|
+
const prev = list.find((e) => pageKey(e.url) === key);
|
|
5775
|
+
writeRecents(project, [
|
|
5776
|
+
{ url, title: title || prev?.title || "", visitedAt: now() },
|
|
5777
|
+
...list.filter((e) => pageKey(e.url) !== key)
|
|
5778
|
+
]);
|
|
5779
|
+
},
|
|
5780
|
+
/** A title that arrived after the load. */
|
|
5781
|
+
retitle(project, url, title) {
|
|
5782
|
+
const list = load2().recents.get(project);
|
|
5783
|
+
const key = pageKey(url);
|
|
5784
|
+
const entry = list?.find((e) => pageKey(e.url) === key);
|
|
5785
|
+
if (!list || !entry || entry.title === title) return;
|
|
5786
|
+
writeRecents(
|
|
5787
|
+
project,
|
|
5788
|
+
list.map((e) => e === entry ? { ...e, title } : e)
|
|
5789
|
+
);
|
|
5790
|
+
},
|
|
5791
|
+
removeRecent(project, url) {
|
|
5792
|
+
const list = load2().recents.get(project);
|
|
5793
|
+
if (!list?.some((e) => e.url === url)) return;
|
|
5794
|
+
writeRecents(
|
|
5795
|
+
project,
|
|
5796
|
+
list.filter((e) => e.url !== url)
|
|
5797
|
+
);
|
|
5798
|
+
},
|
|
5799
|
+
/**
|
|
5800
|
+
* What older versions kept in each window's localStorage, taken once
|
|
5801
|
+
* (a second window importing the same copy changes nothing), even after
|
|
5802
|
+
* something was saved here: what was saved stays. Folders were This
|
|
5803
|
+
* computer's, whose project keys are the bare paths.
|
|
5804
|
+
*/
|
|
5805
|
+
importLegacy(legacy) {
|
|
5806
|
+
if (repo.legacyImported()) return false;
|
|
5807
|
+
const { sessions, recents } = load2();
|
|
5808
|
+
const pages2 = record(legacy.pages);
|
|
5809
|
+
const emulation = record(legacy.emulation);
|
|
5810
|
+
const ids = [.../* @__PURE__ */ new Set([...Object.keys(pages2), ...Object.keys(emulation)])].filter((id) => !sessions.has(id));
|
|
5811
|
+
for (const id of ids.slice(-MAX_BROWSER_SESSIONS)) {
|
|
5812
|
+
const saved2 = record(emulation[id]);
|
|
5813
|
+
const url = typeof pages2[id] === "string" ? pages2[id] : "";
|
|
5814
|
+
writeSession(id, {
|
|
5815
|
+
url,
|
|
5816
|
+
colorScheme: asColorScheme(saved2.colorScheme) ?? "system",
|
|
5817
|
+
device: asBrowserDevice(saved2.device) ?? null
|
|
5818
|
+
});
|
|
5819
|
+
}
|
|
5820
|
+
for (const [folder, list] of Object.entries(record(legacy.recent))) {
|
|
5821
|
+
if (!folder || !Array.isArray(list) || recents.has(folder)) continue;
|
|
5822
|
+
const entries = list.map((e) => {
|
|
5823
|
+
if (typeof e === "string") return { url: e, title: "", visitedAt: 0 };
|
|
5824
|
+
const entry = e;
|
|
5825
|
+
if (typeof entry?.url !== "string") return null;
|
|
5826
|
+
return { url: entry.url, title: String(entry.title ?? ""), visitedAt: Number(entry.visitedAt) || 0 };
|
|
5827
|
+
}).filter((e) => e !== null);
|
|
5828
|
+
if (entries.length) writeRecents(folder, entries);
|
|
5829
|
+
}
|
|
5830
|
+
repo.markLegacyImported();
|
|
5831
|
+
return true;
|
|
5832
|
+
},
|
|
5833
|
+
onEmulation(listener) {
|
|
5834
|
+
listeners.add(listener);
|
|
5835
|
+
return () => listeners.delete(listener);
|
|
5836
|
+
}
|
|
5837
|
+
};
|
|
5838
|
+
}
|
|
5839
|
+
function pageKey(url) {
|
|
5840
|
+
try {
|
|
5841
|
+
const u = new URL(url);
|
|
5842
|
+
return `${u.origin}${u.pathname.replace(/\/+$/, "") || "/"}`;
|
|
5843
|
+
} catch {
|
|
5844
|
+
return url;
|
|
5845
|
+
}
|
|
5846
|
+
}
|
|
5847
|
+
function isDefault(s) {
|
|
5848
|
+
return s.url === "" && s.colorScheme === "system" && s.device === null;
|
|
5849
|
+
}
|
|
5850
|
+
function sameDevice(a, b) {
|
|
5851
|
+
if (a === b) return true;
|
|
5852
|
+
if (!a || !b) return false;
|
|
5853
|
+
return a.id === b.id && a.label === b.label && a.width === b.width && a.height === b.height && a.dpr === b.dpr && a.mobile === b.mobile && a.userAgent === b.userAgent;
|
|
5854
|
+
}
|
|
5855
|
+
function sessionFromRow(row) {
|
|
5856
|
+
let device = null;
|
|
5857
|
+
try {
|
|
5858
|
+
device = row.device_json ? JSON.parse(row.device_json) : null;
|
|
5859
|
+
} catch {
|
|
5860
|
+
}
|
|
5861
|
+
return {
|
|
5862
|
+
url: row.url,
|
|
5863
|
+
colorScheme: asColorScheme(row.color_scheme) ?? "system",
|
|
5864
|
+
device: asBrowserDevice(device) ?? null
|
|
5865
|
+
};
|
|
5866
|
+
}
|
|
5867
|
+
function rowFromSession(sessionId, s, updatedAt) {
|
|
5868
|
+
return {
|
|
5869
|
+
session_key: sessionId,
|
|
5870
|
+
url: s.url,
|
|
5871
|
+
color_scheme: s.colorScheme,
|
|
5872
|
+
device_json: s.device ? JSON.stringify(s.device) : null,
|
|
5873
|
+
updated_at: updatedAt
|
|
5874
|
+
};
|
|
5875
|
+
}
|
|
5876
|
+
function record(value) {
|
|
5877
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
5878
|
+
}
|
|
5281
5879
|
const pages$1 = /* @__PURE__ */ new Map();
|
|
5282
5880
|
const waiters = /* @__PURE__ */ new Map();
|
|
5283
5881
|
const OPEN_TIMEOUT_MS = BROWSER_OPEN_MOUNT_MS;
|
|
5882
|
+
const slotSizes = /* @__PURE__ */ new Map();
|
|
5883
|
+
const MAX_SLOT_SIZES = 200;
|
|
5884
|
+
let saved = null;
|
|
5885
|
+
function browserState() {
|
|
5886
|
+
if (saved) return saved;
|
|
5887
|
+
saved = createBrowserState(browserStateRepo, (change) => {
|
|
5888
|
+
for (const win of appWindows()) win.webContents.send("browser:stateChanged", change);
|
|
5889
|
+
});
|
|
5890
|
+
saved.onEmulation((sessionId) => applyEmulation(sessionId));
|
|
5891
|
+
return saved;
|
|
5892
|
+
}
|
|
5893
|
+
function emulationFor(sessionId) {
|
|
5894
|
+
const { colorScheme, device } = browserState().session(sessionId);
|
|
5895
|
+
if (!device) return { colorScheme, device: null };
|
|
5896
|
+
const slot = slotSizes.get(sessionId);
|
|
5897
|
+
return { colorScheme, device: { ...device, scale: slot ? deviceFit(slot, device) : 1 } };
|
|
5898
|
+
}
|
|
5899
|
+
function applyEmulation(sessionId) {
|
|
5900
|
+
const page = pages$1.get(sessionId);
|
|
5901
|
+
if (page && !page.contents.isDestroyed())
|
|
5902
|
+
void page.driver.setEmulation(emulationFor(sessionId)).catch(() => void 0);
|
|
5903
|
+
}
|
|
5904
|
+
function setBrowserEmulation(sessionId, emulation) {
|
|
5905
|
+
browserState().setEmulation(sessionId, emulation);
|
|
5906
|
+
}
|
|
5907
|
+
function setBrowserSlotSize(sessionId, size) {
|
|
5908
|
+
const prev = slotSizes.get(sessionId);
|
|
5909
|
+
if (prev?.width === size.width && prev.height === size.height) return;
|
|
5910
|
+
slotSizes.delete(sessionId);
|
|
5911
|
+
slotSizes.set(sessionId, size);
|
|
5912
|
+
for (const id of slotSizes.keys()) {
|
|
5913
|
+
if (slotSizes.size <= MAX_SLOT_SIZES) break;
|
|
5914
|
+
if (!pages$1.has(id)) slotSizes.delete(id);
|
|
5915
|
+
}
|
|
5916
|
+
applyEmulation(sessionId);
|
|
5917
|
+
}
|
|
5284
5918
|
function unwait(sessionId, set, waiter) {
|
|
5285
5919
|
set.delete(waiter);
|
|
5286
5920
|
if (set.size === 0 && waiters.get(sessionId) === set) waiters.delete(sessionId);
|
|
@@ -5313,6 +5947,7 @@ function registerBrowserPage(sessionId, webContentsId, host2) {
|
|
|
5313
5947
|
});
|
|
5314
5948
|
const page = { sessionId, contents, driver };
|
|
5315
5949
|
pages$1.set(sessionId, page);
|
|
5950
|
+
applyEmulation(sessionId);
|
|
5316
5951
|
contents.once("destroyed", () => devtoolsWindows.get(contents)?.close());
|
|
5317
5952
|
contents.once("destroyed", () => {
|
|
5318
5953
|
if (pages$1.get(sessionId)?.contents === contents) pages$1.delete(sessionId);
|
|
@@ -5380,12 +6015,6 @@ async function captureAnnotatedBrowserPage(sessionId) {
|
|
|
5380
6015
|
if (!page || page.contents.isDestroyed()) return null;
|
|
5381
6016
|
return page.driver.captureAnnotated();
|
|
5382
6017
|
}
|
|
5383
|
-
async function emulateBrowserPage(sessionId, emulation) {
|
|
5384
|
-
const page = pages$1.get(sessionId);
|
|
5385
|
-
if (!page || page.contents.isDestroyed()) return false;
|
|
5386
|
-
await page.driver.setEmulation(emulation);
|
|
5387
|
-
return true;
|
|
5388
|
-
}
|
|
5389
6018
|
async function captureBrowserPage(sessionId) {
|
|
5390
6019
|
const page = pages$1.get(sessionId);
|
|
5391
6020
|
if (!page || page.contents.isDestroyed()) return null;
|
|
@@ -5487,9 +6116,12 @@ async function runBrowserOp(sessionId, op, input, signal) {
|
|
|
5487
6116
|
const page2 = await mountPage(sessionId, url ?? void 0, show, signal);
|
|
5488
6117
|
return await page2.driver.firstLoad(15e3, signal);
|
|
5489
6118
|
}
|
|
6119
|
+
const resolve2 = () => resolveViewport(input, browserState().session(sessionId));
|
|
6120
|
+
if (op === "viewport") resolve2();
|
|
5490
6121
|
const page = await awaitPage(sessionId, PAGE_GRACE_MS, signal);
|
|
5491
6122
|
if (!page)
|
|
5492
6123
|
throw new BrowserOpError("no_page", "The browser has no page for this session yet. Call browser_open first.");
|
|
6124
|
+
if (op === "viewport") browserState().setEmulation(sessionId, resolve2());
|
|
5493
6125
|
return page.driver.run(op, input, signal);
|
|
5494
6126
|
}
|
|
5495
6127
|
const hostId = `gui-${randomUUID()}`;
|
|
@@ -5859,63 +6491,418 @@ function registerTerminalIpc() {
|
|
|
5859
6491
|
return clientForTerminal(id).request("terminal.setHidden", { terminalId: id, hidden: hidden === true });
|
|
5860
6492
|
});
|
|
5861
6493
|
}
|
|
5862
|
-
function
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
|
|
5870
|
-
return
|
|
6494
|
+
async function runShellOnServer(client2, sessionId, run) {
|
|
6495
|
+
const startedAt = Date.now();
|
|
6496
|
+
try {
|
|
6497
|
+
const { streamed: _streamed, ...result } = await runWorkspaceExecStream(
|
|
6498
|
+
client2,
|
|
6499
|
+
{ sessionId, command: run.command },
|
|
6500
|
+
{ signal: run.signal, ...run.onChunk ? { onChunk: run.onChunk } : {} }
|
|
6501
|
+
);
|
|
6502
|
+
return result;
|
|
6503
|
+
} catch (err) {
|
|
6504
|
+
if (!run.signal.aborted) throw err;
|
|
6505
|
+
return { output: "", exitCode: null, durationMs: Date.now() - startedAt, aborted: true, overflowed: false };
|
|
5871
6506
|
}
|
|
5872
|
-
return signal;
|
|
5873
6507
|
}
|
|
5874
|
-
|
|
5875
|
-
|
|
6508
|
+
const ENVIRONMENT_WORKSPACE_SCHEME = "zidane-env://";
|
|
6509
|
+
function environmentWorkspaceUri(key) {
|
|
6510
|
+
return `${ENVIRONMENT_WORKSPACE_SCHEME}${encodeURIComponent(key)}`;
|
|
5876
6511
|
}
|
|
5877
|
-
function
|
|
5878
|
-
|
|
5879
|
-
|
|
5880
|
-
|
|
5881
|
-
|
|
5882
|
-
|
|
5883
|
-
|
|
5884
|
-
|
|
5885
|
-
const batch = pinned === null ? signals : signals.filter((s) => s.kind !== "event" || s.sessionId === pinned);
|
|
5886
|
-
if (batch.length > 0) win.webContents.send("chat:stream:batch", batch);
|
|
6512
|
+
function environmentWorkspaceSession(cwd) {
|
|
6513
|
+
if (typeof cwd !== "string" || !cwd.startsWith(ENVIRONMENT_WORKSPACE_SCHEME)) return void 0;
|
|
6514
|
+
const encoded = cwd.slice(ENVIRONMENT_WORKSPACE_SCHEME.length);
|
|
6515
|
+
if (!encoded) return void 0;
|
|
6516
|
+
try {
|
|
6517
|
+
return asSessionKey(decodeURIComponent(encoded));
|
|
6518
|
+
} catch {
|
|
6519
|
+
return void 0;
|
|
5887
6520
|
}
|
|
5888
6521
|
}
|
|
5889
|
-
function
|
|
5890
|
-
|
|
5891
|
-
|
|
5892
|
-
|
|
5893
|
-
|
|
5894
|
-
|
|
5895
|
-
|
|
5896
|
-
|
|
5897
|
-
|
|
5898
|
-
|
|
5899
|
-
|
|
5900
|
-
|
|
5901
|
-
|
|
5902
|
-
win.webContents.send(channel2, payload);
|
|
5903
|
-
}
|
|
6522
|
+
function wireEntries(call, sessionId) {
|
|
6523
|
+
return {
|
|
6524
|
+
create: (path, kind, options = {}) => call("sessions.workspaceCreate", {
|
|
6525
|
+
sessionId,
|
|
6526
|
+
path,
|
|
6527
|
+
kind,
|
|
6528
|
+
...options.content ? { content: Buffer$1.from(options.content).toString("base64") } : {},
|
|
6529
|
+
...options.freeName ? { freeName: true } : {}
|
|
6530
|
+
}),
|
|
6531
|
+
move: (from, to) => call("sessions.workspaceMove", { sessionId, from, to }),
|
|
6532
|
+
copy: (from, toDir) => call("sessions.workspaceCopy", { sessionId, from, toDir }),
|
|
6533
|
+
remove: (path) => call("sessions.workspaceRemove", { sessionId, path })
|
|
6534
|
+
};
|
|
5904
6535
|
}
|
|
5905
|
-
|
|
5906
|
-
const
|
|
5907
|
-
|
|
5908
|
-
|
|
5909
|
-
|
|
5910
|
-
|
|
5911
|
-
|
|
5912
|
-
|
|
5913
|
-
|
|
5914
|
-
|
|
6536
|
+
function opsFor(key) {
|
|
6537
|
+
const { host: routed, sessionId } = sessionHost(key);
|
|
6538
|
+
if (routed.remote) {
|
|
6539
|
+
return {
|
|
6540
|
+
exec: (command, timeoutSeconds) => routed.call("sessions.workspaceExec", { sessionId, command, ...timeoutSeconds ? { timeoutSeconds } : {} }),
|
|
6541
|
+
read: (path) => routed.call("sessions.workspaceReadFile", { sessionId, path }),
|
|
6542
|
+
write: (path, content) => routed.call("sessions.workspaceWriteFile", { sessionId, path, content }),
|
|
6543
|
+
entries: wireEntries((method, params) => routed.call(method, params), sessionId),
|
|
6544
|
+
emptyDirs: () => routed.call("sessions.workspaceEmptyDirs", { sessionId }).catch(() => [])
|
|
6545
|
+
};
|
|
5915
6546
|
}
|
|
5916
|
-
const
|
|
5917
|
-
|
|
5918
|
-
|
|
6547
|
+
const daemon2 = getDaemonClient();
|
|
6548
|
+
if (daemon2) {
|
|
6549
|
+
return {
|
|
6550
|
+
exec: (command, timeoutSeconds) => daemon2.request("sessions.workspaceExec", {
|
|
6551
|
+
sessionId,
|
|
6552
|
+
command,
|
|
6553
|
+
...timeoutSeconds ? { timeoutSeconds } : {}
|
|
6554
|
+
}),
|
|
6555
|
+
read: (path) => daemon2.request("sessions.workspaceReadFile", { sessionId, path }),
|
|
6556
|
+
write: (path, content) => daemon2.request("sessions.workspaceWriteFile", { sessionId, path, content }),
|
|
6557
|
+
entries: wireEntries(
|
|
6558
|
+
(method, params) => daemon2.request(method, params),
|
|
6559
|
+
sessionId
|
|
6560
|
+
),
|
|
6561
|
+
emptyDirs: () => daemon2.request("sessions.workspaceEmptyDirs", { sessionId }).catch(() => [])
|
|
6562
|
+
};
|
|
6563
|
+
}
|
|
6564
|
+
const host2 = getChatHost();
|
|
6565
|
+
return {
|
|
6566
|
+
exec: (command, timeoutSeconds) => host2.workspaceExec(sessionId, command, timeoutSeconds ? { timeoutSeconds } : {}),
|
|
6567
|
+
read: (path) => host2.workspaceReadFile(sessionId, path),
|
|
6568
|
+
write: (path, content) => host2.workspaceWriteFile(sessionId, path, content),
|
|
6569
|
+
entries: {
|
|
6570
|
+
create: (path, kind, options) => host2.workspaceCreate(sessionId, path, kind, options),
|
|
6571
|
+
move: (from, to) => host2.workspaceMove(sessionId, from, to),
|
|
6572
|
+
copy: (from, toDir) => host2.workspaceCopy(sessionId, from, toDir),
|
|
6573
|
+
remove: (path) => host2.workspaceRemove(sessionId, path)
|
|
6574
|
+
},
|
|
6575
|
+
emptyDirs: () => host2.workspaceEmptyDirs(sessionId).catch(() => [])
|
|
6576
|
+
};
|
|
6577
|
+
}
|
|
6578
|
+
function q(value) {
|
|
6579
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
6580
|
+
}
|
|
6581
|
+
function safeRel(rel) {
|
|
6582
|
+
const segments = rel.split("/").filter((s) => s && s !== ".");
|
|
6583
|
+
return rel.startsWith("/") || segments.includes("..") ? null : segments.join("/");
|
|
6584
|
+
}
|
|
6585
|
+
async function lsFiles(ops) {
|
|
6586
|
+
const result = await ops.exec("git ls-files -z --cached --others --exclude-standard", 30);
|
|
6587
|
+
return result.exitCode === 0 ? result.stdout.split("\0").filter(Boolean) : null;
|
|
6588
|
+
}
|
|
6589
|
+
async function listEnvironmentWorkspace(sessionId) {
|
|
6590
|
+
const ops = opsFor(sessionId);
|
|
6591
|
+
const [listed, emptyDirs] = await Promise.all([lsFiles(ops), ops.emptyDirs()]);
|
|
6592
|
+
const files = listed ?? (await ops.exec(`find . -type f -not -path './.git/*' | head -n ${WORKSPACE_MAX_ENTRIES}`, 30)).stdout.split("\n").map((line) => line.replace(/^\.\//, "")).filter(Boolean);
|
|
6593
|
+
const entries = [
|
|
6594
|
+
...files.slice(0, WORKSPACE_MAX_ENTRIES).map((path) => ({ path, kind: "file" })),
|
|
6595
|
+
...emptyDirs.map((path) => ({ path: `${path}/`, kind: "dir" }))
|
|
6596
|
+
];
|
|
6597
|
+
return entries.slice(0, WORKSPACE_MAX_ENTRIES).sort((a, b) => a.path.localeCompare(b.path));
|
|
6598
|
+
}
|
|
6599
|
+
function environmentEntries(sessionId) {
|
|
6600
|
+
return opsFor(sessionId).entries;
|
|
6601
|
+
}
|
|
6602
|
+
async function importIntoEnvironment(sessionId, dir, paths) {
|
|
6603
|
+
try {
|
|
6604
|
+
return await importEntries(opsFor(sessionId).entries.create, dir, await hostImportItems(paths));
|
|
6605
|
+
} catch (error) {
|
|
6606
|
+
return { ok: false, reason: "denied", message: error instanceof Error ? error.message : String(error), paths: [] };
|
|
6607
|
+
}
|
|
6608
|
+
}
|
|
6609
|
+
async function fileMeta(ops, rel) {
|
|
6610
|
+
const result = await ops.exec(
|
|
6611
|
+
`[ -f ${q(rel)} ] || exit 3; printf '%s %s ' "$(stat -c %s ${q(rel)})" "$(stat -c %Y ${q(rel)})"; head -c 8192 ${q(rel)} | tr -dc '\\000' | wc -c`,
|
|
6612
|
+
15
|
|
6613
|
+
);
|
|
6614
|
+
if (result.exitCode !== 0) return null;
|
|
6615
|
+
const [size, mtime, nuls] = result.stdout.trim().split(/\s+/).map(Number);
|
|
6616
|
+
if (!Number.isFinite(size) || !Number.isFinite(mtime)) return null;
|
|
6617
|
+
return { size, mtimeMs: mtime * 1e3, binary: (nuls ?? 0) > 0 };
|
|
6618
|
+
}
|
|
6619
|
+
async function readEnvironmentFile(sessionId, rel) {
|
|
6620
|
+
const path = safeRel(rel);
|
|
6621
|
+
if (path === null) return null;
|
|
6622
|
+
const ops = opsFor(sessionId);
|
|
6623
|
+
const meta = await fileMeta(ops, path);
|
|
6624
|
+
if (!meta) return null;
|
|
6625
|
+
const base = { path: rel, size: meta.size, mtimeMs: meta.mtimeMs };
|
|
6626
|
+
if (meta.size > WORKSPACE_MAX_FILE_BYTES) return { ...base, contents: "", truncated: true, binary: false };
|
|
6627
|
+
if (meta.binary) return { ...base, contents: "", truncated: false, binary: true };
|
|
6628
|
+
const contents = await ops.read(path).catch(() => null);
|
|
6629
|
+
return contents === null ? null : { ...base, contents, truncated: false, binary: false };
|
|
6630
|
+
}
|
|
6631
|
+
async function writeEnvironmentFile(sessionId, rel, contents, expectedMtimeMs) {
|
|
6632
|
+
const path = safeRel(rel);
|
|
6633
|
+
if (path === null) return { ok: false, reason: "denied" };
|
|
6634
|
+
const ops = opsFor(sessionId);
|
|
6635
|
+
const meta = await fileMeta(ops, path);
|
|
6636
|
+
if (!meta) return { ok: false, reason: "missing" };
|
|
6637
|
+
if (Math.floor(meta.mtimeMs / 1e3) !== Math.floor(expectedMtimeMs / 1e3)) return { ok: false, reason: "changed" };
|
|
6638
|
+
try {
|
|
6639
|
+
await ops.write(path, contents);
|
|
6640
|
+
} catch {
|
|
6641
|
+
return { ok: false, reason: "denied" };
|
|
6642
|
+
}
|
|
6643
|
+
const after = await fileMeta(ops, path);
|
|
6644
|
+
return { ok: true, mtimeMs: after?.mtimeMs ?? Date.now() };
|
|
6645
|
+
}
|
|
6646
|
+
async function environmentGitStatus(sessionId) {
|
|
6647
|
+
const ops = opsFor(sessionId);
|
|
6648
|
+
return gitStatusOf(async (untracked) => {
|
|
6649
|
+
const result = await ops.exec(`git status --porcelain=v1 -z --untracked-files=${untracked}`, 30);
|
|
6650
|
+
return result.exitCode === 0 ? result.stdout : null;
|
|
6651
|
+
});
|
|
6652
|
+
}
|
|
6653
|
+
async function environmentGitDiff(sessionId, rel, context = 3) {
|
|
6654
|
+
const path = rel === void 0 ? void 0 : safeRel(rel);
|
|
6655
|
+
if (path === null) return "";
|
|
6656
|
+
const ops = opsFor(sessionId);
|
|
6657
|
+
const target = path ? ` -- ${q(path)}` : "";
|
|
6658
|
+
const unified = Number.isFinite(context) ? `-U${Math.max(0, Math.floor(context))}` : "-U999999";
|
|
6659
|
+
const tracked2 = await ops.exec(`git diff HEAD --no-color --no-ext-diff ${unified}${target}`, 60);
|
|
6660
|
+
const untrackedList = await ops.exec(`git ls-files --others --exclude-standard -z${target}`, 30);
|
|
6661
|
+
return assembleDiff(
|
|
6662
|
+
tracked2.exitCode === 0 ? tracked2.stdout : "",
|
|
6663
|
+
untrackedList.stdout.split("\0").filter(Boolean),
|
|
6664
|
+
4,
|
|
6665
|
+
async (file) => {
|
|
6666
|
+
const read = await readEnvironmentFile(sessionId, file);
|
|
6667
|
+
return read && !read.binary && !read.truncated ? read.contents : null;
|
|
6668
|
+
}
|
|
6669
|
+
);
|
|
6670
|
+
}
|
|
6671
|
+
async function environmentGitShowHead(sessionId, rel) {
|
|
6672
|
+
const path = safeRel(rel);
|
|
6673
|
+
if (path === null) return null;
|
|
6674
|
+
const result = await opsFor(sessionId).exec(`git show ${q(`HEAD:${path}`)}`, 30);
|
|
6675
|
+
return result.exitCode === 0 ? result.stdout : null;
|
|
6676
|
+
}
|
|
6677
|
+
async function listEnvironmentProjectFiles(sessionId) {
|
|
6678
|
+
const paths = await lsFiles(opsFor(sessionId));
|
|
6679
|
+
return paths ? fileEntriesFromPaths(paths, "git") : [];
|
|
6680
|
+
}
|
|
6681
|
+
const SHELL_TIMEOUT_SECONDS = 10 * 60;
|
|
6682
|
+
async function runInEnvironment(sessionId, run) {
|
|
6683
|
+
const { host: routed, sessionId: id } = sessionHost(sessionId);
|
|
6684
|
+
if (routed.remote) {
|
|
6685
|
+
const client2 = routed.server.client;
|
|
6686
|
+
if (!client2) throw new Error(`${routed.name} is offline.`);
|
|
6687
|
+
return runShellOnServer(client2, id, run);
|
|
6688
|
+
}
|
|
6689
|
+
const startedAt = Date.now();
|
|
6690
|
+
const aborted = new Promise((resolve2) => {
|
|
6691
|
+
if (run.signal.aborted) resolve2(null);
|
|
6692
|
+
else run.signal.addEventListener("abort", () => resolve2(null), { once: true });
|
|
6693
|
+
});
|
|
6694
|
+
const result = await Promise.race([opsFor(sessionId).exec(run.command, SHELL_TIMEOUT_SECONDS), aborted]);
|
|
6695
|
+
const durationMs = Date.now() - startedAt;
|
|
6696
|
+
if (!result) return { output: "", exitCode: null, durationMs, aborted: true, overflowed: false };
|
|
6697
|
+
const output = [result.stdout, result.stderr].filter(Boolean).join(result.stdout.endsWith("\n") ? "" : "\n");
|
|
6698
|
+
run.onChunk?.(output);
|
|
6699
|
+
return { output, exitCode: result.exitCode, durationMs, aborted: false, overflowed: false };
|
|
6700
|
+
}
|
|
6701
|
+
function serverSessionRow(hostId2, row, meta) {
|
|
6702
|
+
const key = sessionKey(hostId2, row.id);
|
|
6703
|
+
return {
|
|
6704
|
+
id: key,
|
|
6705
|
+
title: meta?.title ?? row.title,
|
|
6706
|
+
turnCount: meta?.turnCount ?? 0,
|
|
6707
|
+
userMessageCount: meta?.userMessageCount ?? 0,
|
|
6708
|
+
runCount: meta?.runCount ?? 0,
|
|
6709
|
+
...row.projectRoot ? { projectRoot: row.projectRoot } : {},
|
|
6710
|
+
...row.repoKey ? { repoKey: row.repoKey } : {},
|
|
6711
|
+
createdAt: row.createdAt,
|
|
6712
|
+
updatedAt: row.updatedAt,
|
|
6713
|
+
...row.lastUserMessageAt !== void 0 ? { lastUserMessageAt: row.lastUserMessageAt } : {},
|
|
6714
|
+
cwd: row.cwd,
|
|
6715
|
+
status: row.status,
|
|
6716
|
+
...row.status === "running" && row.runStartedAt !== void 0 ? { runStartedAt: row.runStartedAt } : {},
|
|
6717
|
+
...row.status === "running" && row.runEstimates ? { runEstimates: row.runEstimates } : {},
|
|
6718
|
+
...row.agentId ? { agentId: row.agentId } : {},
|
|
6719
|
+
...row.effort ? { effort: row.effort } : {},
|
|
6720
|
+
...row.modelOptions && Object.keys(row.modelOptions).length > 0 ? { modelOptions: row.modelOptions } : {},
|
|
6721
|
+
...row.providerKey ? { providerKey: row.providerKey } : {},
|
|
6722
|
+
...row.modelId ? { modelId: row.modelId } : {},
|
|
6723
|
+
...row.account ? { account: row.account } : {},
|
|
6724
|
+
...row.modelFallbacks && row.modelFallbacks.length > 0 ? { modelFallbacks: row.modelFallbacks } : {},
|
|
6725
|
+
archived: row.archived,
|
|
6726
|
+
...row.favorite ? { favorite: true } : {},
|
|
6727
|
+
...meta?.scheduleId ?? row.scheduleId ? { scheduleId: meta?.scheduleId ?? row.scheduleId } : {},
|
|
6728
|
+
...row.isMain ? { isMain: true } : {},
|
|
6729
|
+
...row.spaceId ? { spaceId: row.spaceId } : {},
|
|
6730
|
+
...row.environment ? { environment: row.environment } : {},
|
|
6731
|
+
...meta?.artifactCount !== void 0 ? { artifactCount: meta.artifactCount } : {},
|
|
6732
|
+
workspace: environmentWorkspaceUri(key),
|
|
6733
|
+
hostId: hostId2
|
|
6734
|
+
};
|
|
6735
|
+
}
|
|
6736
|
+
const lastLists = /* @__PURE__ */ new Map();
|
|
6737
|
+
function remote(hostId2) {
|
|
6738
|
+
const host2 = hostFor({ hostId: hostId2 });
|
|
6739
|
+
if (!host2.remote) throw new Error(`"${hostId2}" is not a server.`);
|
|
6740
|
+
return host2;
|
|
6741
|
+
}
|
|
6742
|
+
async function listServerSessions(hostId2, filter) {
|
|
6743
|
+
const archive = filter?.archive ?? "active";
|
|
6744
|
+
const cacheKey = `${hostId2}\0${archive}`;
|
|
6745
|
+
const host2 = remote(hostId2);
|
|
6746
|
+
if (!host2.server.client) return lastLists.get(cacheKey) ?? [];
|
|
6747
|
+
try {
|
|
6748
|
+
const [rows, metas] = await Promise.all([
|
|
6749
|
+
host2.call("sessions.list", { archive }),
|
|
6750
|
+
host2.call("sessions.listMeta", {}).catch(() => [])
|
|
6751
|
+
]);
|
|
6752
|
+
const metaById = new Map(metas.map((meta) => [meta.id, meta]));
|
|
6753
|
+
const directory2 = getHostDirectory();
|
|
6754
|
+
const list = rows.map((row) => {
|
|
6755
|
+
directory2.noteSessionHost(row.id, hostId2);
|
|
6756
|
+
return serverSessionRow(hostId2, row, metaById.get(row.id));
|
|
6757
|
+
});
|
|
6758
|
+
lastLists.set(cacheKey, list);
|
|
6759
|
+
return list;
|
|
6760
|
+
} catch {
|
|
6761
|
+
return lastLists.get(cacheKey) ?? [];
|
|
6762
|
+
}
|
|
6763
|
+
}
|
|
6764
|
+
async function searchServerSessions(query, filter) {
|
|
6765
|
+
const servers = getHostDirectory().servers().filter((server) => server.client !== null);
|
|
6766
|
+
const answers = await Promise.all(
|
|
6767
|
+
servers.map(async (server) => {
|
|
6768
|
+
try {
|
|
6769
|
+
const rows = await listServerSessions(server.id, filter);
|
|
6770
|
+
if (rows.length === 0) return [];
|
|
6771
|
+
const matches = await remote(server.id).call("history.searchAll", {
|
|
6772
|
+
query,
|
|
6773
|
+
sessionIds: rows.map((row) => sessionIdOf(row.id)),
|
|
6774
|
+
excerptLimit: 1
|
|
6775
|
+
});
|
|
6776
|
+
return rows.flatMap((row) => {
|
|
6777
|
+
const match = matches[sessionIdOf(row.id)];
|
|
6778
|
+
if (!match) return [];
|
|
6779
|
+
return [
|
|
6780
|
+
{
|
|
6781
|
+
sessionId: row.id,
|
|
6782
|
+
title: row.title,
|
|
6783
|
+
excerpt: match.excerpts[0]?.text ?? "",
|
|
6784
|
+
matchCount: Math.max(1, match.matchedTurnIds.length),
|
|
6785
|
+
updatedAt: row.updatedAt
|
|
6786
|
+
}
|
|
6787
|
+
];
|
|
6788
|
+
});
|
|
6789
|
+
} catch {
|
|
6790
|
+
return [];
|
|
6791
|
+
}
|
|
6792
|
+
})
|
|
6793
|
+
);
|
|
6794
|
+
return answers.flat();
|
|
6795
|
+
}
|
|
6796
|
+
function forgetServerSessions(hostId2) {
|
|
6797
|
+
for (const key of [...lastLists.keys()]) if (key.startsWith(`${hostId2}\0`)) lastLists.delete(key);
|
|
6798
|
+
}
|
|
6799
|
+
function remoteSession(key) {
|
|
6800
|
+
const { host: host2, sessionId } = sessionHost(key);
|
|
6801
|
+
return host2.remote ? { host: host2, sessionId } : null;
|
|
6802
|
+
}
|
|
6803
|
+
async function serverSessionExportDocument(key) {
|
|
6804
|
+
const remote2 = remoteSession(key);
|
|
6805
|
+
if (!remote2) return null;
|
|
6806
|
+
return loadSessionDocument((method, params) => remote2.host.call(method, params), remote2.sessionId);
|
|
6807
|
+
}
|
|
6808
|
+
async function serverToolResultText(key, callId, turnId) {
|
|
6809
|
+
const remote2 = remoteSession(key);
|
|
6810
|
+
if (!remote2) return null;
|
|
6811
|
+
const { host: host2, sessionId } = remote2;
|
|
6812
|
+
try {
|
|
6813
|
+
return await host2.call("sessions.getToolResult", { sessionId, callId, ...turnId ? { turnId } : {} });
|
|
6814
|
+
} catch (err) {
|
|
6815
|
+
if (!isUnsupportedMethod(err)) return null;
|
|
6816
|
+
}
|
|
6817
|
+
const data = await host2.call("sessions.get", { sessionId }).catch(() => null);
|
|
6818
|
+
for (const turn of data?.turns ?? []) {
|
|
6819
|
+
for (const block of turn.content) {
|
|
6820
|
+
if (block.type === "tool_result" && block.callId === callId) return toolResultText(block.output);
|
|
6821
|
+
}
|
|
6822
|
+
}
|
|
6823
|
+
return null;
|
|
6824
|
+
}
|
|
6825
|
+
async function serverSessionUsage(key) {
|
|
6826
|
+
const remote2 = remoteSession(key);
|
|
6827
|
+
if (!remote2) return null;
|
|
6828
|
+
const { host: host2, sessionId } = remote2;
|
|
6829
|
+
const header = await host2.call("sessions.getHeader", { sessionId, usage: true }).catch(() => null);
|
|
6830
|
+
if (!header) return null;
|
|
6831
|
+
if (header.contextTokens !== void 0 || header.costUsd !== void 0) {
|
|
6832
|
+
return {
|
|
6833
|
+
metadata: header.metadata,
|
|
6834
|
+
contextTokens: header.contextTokens ?? 0,
|
|
6835
|
+
costUsd: header.costUsd ?? 0,
|
|
6836
|
+
runCount: header.runCount,
|
|
6837
|
+
...header.runStartedAt !== void 0 ? { run: { startedAt: header.runStartedAt, outputTokens: header.runOutputTokens ?? 0 } } : {}
|
|
6838
|
+
};
|
|
6839
|
+
}
|
|
6840
|
+
const data = await host2.call("sessions.get", { sessionId }).catch(() => null);
|
|
6841
|
+
if (!data) return null;
|
|
6842
|
+
return {
|
|
6843
|
+
metadata: data.metadata ?? {},
|
|
6844
|
+
contextTokens: lastContextSizeFromTurns(data.turns, data.runs),
|
|
6845
|
+
costUsd: sumRunCosts(data.runs),
|
|
6846
|
+
runCount: data.runs.length
|
|
6847
|
+
};
|
|
6848
|
+
}
|
|
6849
|
+
function keyedSignal(signal, hostId2) {
|
|
6850
|
+
if (signal.kind === "approval:request") {
|
|
6851
|
+
return {
|
|
6852
|
+
...signal,
|
|
6853
|
+
request: { ...signal.request, sessionId: sessionKey(hostId2, signal.request.sessionId) }
|
|
6854
|
+
};
|
|
6855
|
+
}
|
|
6856
|
+
if ("sessionId" in signal && typeof signal.sessionId === "string") {
|
|
6857
|
+
return { ...signal, sessionId: sessionKey(hostId2, signal.sessionId) };
|
|
6858
|
+
}
|
|
6859
|
+
return signal;
|
|
6860
|
+
}
|
|
6861
|
+
function sendChatStream(signal) {
|
|
6862
|
+
sendToAllWindows("chat:stream", signal, signal.kind === "event" ? { session: signal.sessionId } : void 0);
|
|
6863
|
+
}
|
|
6864
|
+
function sendChatStreamBatch(signals) {
|
|
6865
|
+
const windows = appWindows();
|
|
6866
|
+
if (windows.length === 0) {
|
|
6867
|
+
console.warn("[stream] broadcast had 0 windows; event lost on chat:stream:batch");
|
|
6868
|
+
return;
|
|
6869
|
+
}
|
|
6870
|
+
for (const win of windows) {
|
|
6871
|
+
const pinned = pinnedSessionOf(win);
|
|
6872
|
+
const batch = pinned === null ? signals : signals.filter((s) => s.kind !== "event" || s.sessionId === pinned);
|
|
6873
|
+
if (batch.length > 0) win.webContents.send("chat:stream:batch", batch);
|
|
6874
|
+
}
|
|
6875
|
+
}
|
|
6876
|
+
function sendToAllWindows(channel2, payload, opts) {
|
|
6877
|
+
const windows = appWindows();
|
|
6878
|
+
if (windows.length === 0) {
|
|
6879
|
+
if (!opts?.bufferedElsewhere) {
|
|
6880
|
+
console.warn(`[stream] broadcast had 0 windows; event lost on ${channel2}`);
|
|
6881
|
+
}
|
|
6882
|
+
return;
|
|
6883
|
+
}
|
|
6884
|
+
for (const win of windows) {
|
|
6885
|
+
if (opts?.session !== void 0) {
|
|
6886
|
+
const pinned = pinnedSessionOf(win);
|
|
6887
|
+
if (pinned !== null && pinned !== opts.session) continue;
|
|
6888
|
+
}
|
|
6889
|
+
win.webContents.send(channel2, payload);
|
|
6890
|
+
}
|
|
6891
|
+
}
|
|
6892
|
+
const DELTA_FLUSH_MS = 16;
|
|
6893
|
+
const pendingDeltas = [];
|
|
6894
|
+
let deltaFlushTimer = null;
|
|
6895
|
+
function flushPendingDeltas(sessionId) {
|
|
6896
|
+
if (pendingDeltas.length === 0) {
|
|
6897
|
+
if (deltaFlushTimer && sessionId === void 0) {
|
|
6898
|
+
clearTimeout(deltaFlushTimer);
|
|
6899
|
+
deltaFlushTimer = null;
|
|
6900
|
+
}
|
|
6901
|
+
return;
|
|
6902
|
+
}
|
|
6903
|
+
const drained = [];
|
|
6904
|
+
for (let i = 0; i < pendingDeltas.length; ) {
|
|
6905
|
+
if (sessionId === void 0 || pendingDeltas[i].sessionId === sessionId) {
|
|
5919
6906
|
drained.push(pendingDeltas[i]);
|
|
5920
6907
|
pendingDeltas.splice(i, 1);
|
|
5921
6908
|
} else {
|
|
@@ -5968,17 +6955,31 @@ function isStreamDelta(event) {
|
|
|
5968
6955
|
}
|
|
5969
6956
|
let daemonSignalsLive = false;
|
|
5970
6957
|
let daemonHealth = "disconnected";
|
|
5971
|
-
|
|
5972
|
-
|
|
6958
|
+
let daemonState = { connected: false, health: "disconnected" };
|
|
6959
|
+
function setDaemonHealth(next, options = {}) {
|
|
6960
|
+
const live = next === "connected";
|
|
6961
|
+
const resuming = !live && (options.resuming ?? daemonEnabled());
|
|
6962
|
+
if (daemonHealth === next && daemonState.resuming === true === resuming) {
|
|
5973
6963
|
return;
|
|
5974
6964
|
}
|
|
6965
|
+
const healthChanged = daemonHealth !== next;
|
|
5975
6966
|
daemonHealth = next;
|
|
5976
|
-
daemonSignalsLive =
|
|
5977
|
-
for (const listener of healthListeners) listener(next);
|
|
6967
|
+
daemonSignalsLive = live;
|
|
6968
|
+
if (healthChanged) for (const listener of healthListeners) listener(next);
|
|
6969
|
+
const epoch = live ? getDaemonClient()?.hello.signalEpoch : void 0;
|
|
6970
|
+
daemonState = {
|
|
6971
|
+
connected: live,
|
|
6972
|
+
health: next,
|
|
6973
|
+
...epoch !== void 0 ? { epoch } : {},
|
|
6974
|
+
...resuming ? { resuming: true } : {}
|
|
6975
|
+
};
|
|
5978
6976
|
for (const window2 of appWindows()) {
|
|
5979
|
-
window2.webContents.send("daemon:state",
|
|
6977
|
+
window2.webContents.send("daemon:state", daemonState);
|
|
5980
6978
|
}
|
|
5981
6979
|
}
|
|
6980
|
+
function getDaemonState() {
|
|
6981
|
+
return daemonState;
|
|
6982
|
+
}
|
|
5982
6983
|
const healthListeners = /* @__PURE__ */ new Set();
|
|
5983
6984
|
function onDaemonHealth(listener) {
|
|
5984
6985
|
healthListeners.add(listener);
|
|
@@ -5998,9 +6999,53 @@ function onSettingsChangedSignal(listener) {
|
|
|
5998
6999
|
function broadcast(hostSignal, hostId2 = LOCAL_SESSION_HOST) {
|
|
5999
7000
|
if (hostId2 === LOCAL_SESSION_HOST && hostSignal.kind === "sessions:changed" && hostSignal.op === "delete")
|
|
6000
7001
|
desktopExtensionsHost()?.removeSession(hostSignal.sessionId);
|
|
6001
|
-
if (hostId2 === LOCAL_SESSION_HOST) peekChatHost()?.facets.observe(hostSignal);
|
|
6002
7002
|
routeToRenderer(keyedSignal(hostSignal, hostId2), hostSignal, hostId2);
|
|
6003
7003
|
}
|
|
7004
|
+
let localSessionRow = null;
|
|
7005
|
+
function setLocalSessionRows(build) {
|
|
7006
|
+
localSessionRow = build;
|
|
7007
|
+
}
|
|
7008
|
+
const sentRows = /* @__PURE__ */ new Map();
|
|
7009
|
+
const SENT_ROWS_KEPT = 2e3;
|
|
7010
|
+
function relaySessionRow(change) {
|
|
7011
|
+
if (change.op === "delete") {
|
|
7012
|
+
sentRows.delete(change.sessionId);
|
|
7013
|
+
sendToAllWindows("sessions:changed", change);
|
|
7014
|
+
return { send: true, listed: true };
|
|
7015
|
+
}
|
|
7016
|
+
const row = change.row;
|
|
7017
|
+
const json = row ? JSON.stringify(row) : "";
|
|
7018
|
+
const before = sentRows.get(change.sessionId);
|
|
7019
|
+
if (change.op === "update" && before?.json === json) return { send: false, listed: false };
|
|
7020
|
+
const listing = row ? JSON.stringify([
|
|
7021
|
+
row.title,
|
|
7022
|
+
row.archived,
|
|
7023
|
+
row.favorite,
|
|
7024
|
+
row.spaceId,
|
|
7025
|
+
row.projectRoot,
|
|
7026
|
+
row.cwd,
|
|
7027
|
+
row.status,
|
|
7028
|
+
row.isMain
|
|
7029
|
+
]) : "";
|
|
7030
|
+
sentRows.delete(change.sessionId);
|
|
7031
|
+
sentRows.set(change.sessionId, { json, listing });
|
|
7032
|
+
if (sentRows.size > SENT_ROWS_KEPT) sentRows.delete(sentRows.keys().next().value);
|
|
7033
|
+
sendToAllWindows("sessions:changed", change);
|
|
7034
|
+
return { send: true, listed: change.op === "create" || before?.listing !== listing };
|
|
7035
|
+
}
|
|
7036
|
+
function windowRowOf(signal, hostId2) {
|
|
7037
|
+
if (signal.op === "delete" || signal.row.sideOf) return void 0;
|
|
7038
|
+
if (hostId2 !== LOCAL_SESSION_HOST) return serverSessionRow(hostId2, signal.row);
|
|
7039
|
+
return localSessionRow?.(signal.sessionId) ?? void 0;
|
|
7040
|
+
}
|
|
7041
|
+
function announceLocalSessionRow(sessionId) {
|
|
7042
|
+
const row = localSessionRow?.(sessionId);
|
|
7043
|
+
if (!row) return;
|
|
7044
|
+
const key = sessionKey(LOCAL_SESSION_HOST, sessionId);
|
|
7045
|
+
flushPendingDeltas(key);
|
|
7046
|
+
const { send, listed } = relaySessionRow({ op: "update", sessionId: key, row });
|
|
7047
|
+
if (send && listed) emitInvalidate({ topic: "sessions", hostId: void 0, sessionId: key });
|
|
7048
|
+
}
|
|
6004
7049
|
function broadcastLocal(signal) {
|
|
6005
7050
|
routeToRenderer(signal, null, LOCAL_SESSION_HOST);
|
|
6006
7051
|
}
|
|
@@ -6027,6 +7072,19 @@ function routeToRenderer(signal, raw, hostId2) {
|
|
|
6027
7072
|
if (signal.kind === "run:end") {
|
|
6028
7073
|
invalidateUsageSummaryCache();
|
|
6029
7074
|
}
|
|
7075
|
+
if (signal.kind === "sessions:changed") {
|
|
7076
|
+
if (signal.op === "delete") {
|
|
7077
|
+
forgetLiveResults(signal.sessionId);
|
|
7078
|
+
forgetInlineSuggestSeq(signal.sessionId);
|
|
7079
|
+
}
|
|
7080
|
+
const row = raw?.kind === "sessions:changed" ? windowRowOf(raw, hostId2) : void 0;
|
|
7081
|
+
const { listed } = relaySessionRow(
|
|
7082
|
+
signal.op === "delete" ? { op: "delete", sessionId: signal.sessionId } : { op: signal.op, sessionId: signal.sessionId, ...row ? { row } : {} }
|
|
7083
|
+
);
|
|
7084
|
+
if (listed) for (const event of invalidationsOf(signal, hostId2, localSessionCwd)) emitInvalidate(event);
|
|
7085
|
+
if (raw && isAttentionSignal(signal)) noteAttentionSignal(signal);
|
|
7086
|
+
return;
|
|
7087
|
+
}
|
|
6030
7088
|
for (const event of invalidationsOf(signal, hostId2, localSessionCwd)) emitInvalidate(event);
|
|
6031
7089
|
if (raw && isAttentionSignal(signal)) noteAttentionSignal(signal);
|
|
6032
7090
|
switch (signal.kind) {
|
|
@@ -6068,13 +7126,6 @@ function routeToRenderer(signal, raw, hostId2) {
|
|
|
6068
7126
|
decision: signal.decision
|
|
6069
7127
|
});
|
|
6070
7128
|
return;
|
|
6071
|
-
case "sessions:changed":
|
|
6072
|
-
if (signal.op === "delete") {
|
|
6073
|
-
forgetLiveResults(signal.sessionId);
|
|
6074
|
-
forgetInlineSuggestSeq(signal.sessionId);
|
|
6075
|
-
}
|
|
6076
|
-
sendToAllWindows("sessions:changed", { op: signal.op, sessionId: signal.sessionId });
|
|
6077
|
-
return;
|
|
6078
7129
|
case "sessions:facets":
|
|
6079
7130
|
sendToAllWindows("sessions:facets", { sessionId: signal.sessionId, facets: signal.facets });
|
|
6080
7131
|
return;
|
|
@@ -6165,11 +7216,29 @@ function routeToRenderer(signal, raw, hostId2) {
|
|
|
6165
7216
|
status: signal.status
|
|
6166
7217
|
});
|
|
6167
7218
|
return;
|
|
7219
|
+
case "machine:changed": {
|
|
7220
|
+
const { kind: _kind, ...change } = signal;
|
|
7221
|
+
sendToAllWindows("machines:changed", { hostId: hostId2, ...change });
|
|
7222
|
+
return;
|
|
7223
|
+
}
|
|
7224
|
+
case "machine:join": {
|
|
7225
|
+
const { kind: _kind, ...event } = signal;
|
|
7226
|
+
sendToAllWindows("machines:join", { hostId: hostId2, ...event });
|
|
7227
|
+
return;
|
|
7228
|
+
}
|
|
6168
7229
|
case "machine:links":
|
|
6169
7230
|
if (hostId2 === LOCAL_SESSION_HOST) sendToAllWindows("machines:links", signal.links);
|
|
6170
7231
|
return;
|
|
6171
7232
|
case "machine:notification":
|
|
6172
7233
|
return;
|
|
7234
|
+
case "history:changed": {
|
|
7235
|
+
const { kind: _kind, events, ...change } = signal;
|
|
7236
|
+
sendToAllWindows(
|
|
7237
|
+
"sessions:history",
|
|
7238
|
+
events ? { ...change, events: attachAttachmentsToUserPrompts(clipToolResultEvents(events), [], change.sessionId) } : signal.events === null ? { ...change, events: null } : change
|
|
7239
|
+
);
|
|
7240
|
+
return;
|
|
7241
|
+
}
|
|
6173
7242
|
// A streamed `!` command's output goes to the connection that started it (`server-shell.ts` reads it there).
|
|
6174
7243
|
case "workspace:exec:data":
|
|
6175
7244
|
case "workspace:exec:exit":
|
|
@@ -6190,7 +7259,7 @@ function routeToRenderer(signal, raw, hostId2) {
|
|
|
6190
7259
|
return;
|
|
6191
7260
|
// A server's sync record: its arrive through `forwardServerSignal` (`hosts:syncChanged`); This computer has none.
|
|
6192
7261
|
case "sync:changed":
|
|
6193
|
-
// A server's tokens: its
|
|
7262
|
+
// A server's tokens: its arrive through `forwardServerSignal` (`hosts:tokensChanged`); This computer has none.
|
|
6194
7263
|
case "tokens:changed":
|
|
6195
7264
|
return;
|
|
6196
7265
|
// ALLOWLIST — only signal kinds the renderer's stream reducer actually
|
|
@@ -6228,7 +7297,6 @@ function routeToRenderer(signal, raw, hostId2) {
|
|
|
6228
7297
|
case "stream:progress":
|
|
6229
7298
|
case "stream:retry":
|
|
6230
7299
|
case "stream:retry:cleared":
|
|
6231
|
-
case "prompt-turns":
|
|
6232
7300
|
// GUI-local: the debounced "an extension panel has new content" push.
|
|
6233
7301
|
case "panel:changed":
|
|
6234
7302
|
case "palette:changed":
|
|
@@ -6381,12 +7449,30 @@ function onStateTick(listener, intervalMs = STATE_TICK_MS) {
|
|
|
6381
7449
|
};
|
|
6382
7450
|
}
|
|
6383
7451
|
const RETRY_MS = 5e3;
|
|
7452
|
+
const MAX_RETRY_MS = 6e4;
|
|
6384
7453
|
let client = null;
|
|
6385
7454
|
let retryTimer = null;
|
|
7455
|
+
let retryDueAt = 0;
|
|
6386
7456
|
let offStateTick = null;
|
|
6387
7457
|
let connecting = false;
|
|
6388
7458
|
let started = false;
|
|
6389
7459
|
let deferredForLocalWork = false;
|
|
7460
|
+
let startsOlderStreak = 0;
|
|
7461
|
+
let missedExit = null;
|
|
7462
|
+
const daemonSignals = createResumingRelay(deliver);
|
|
7463
|
+
function dropDaemonState() {
|
|
7464
|
+
daemonSignals.forget();
|
|
7465
|
+
setDaemonHealth("disconnected", { resuming: false });
|
|
7466
|
+
}
|
|
7467
|
+
onOlderDaemonBusy(() => {
|
|
7468
|
+
if (!client) drainHealth();
|
|
7469
|
+
});
|
|
7470
|
+
function deliver(signal) {
|
|
7471
|
+
broadcast(signal);
|
|
7472
|
+
if (signal.kind === "settings:changed" && !daemonEnabled()) {
|
|
7473
|
+
setImmediate(() => refreshDaemonClient());
|
|
7474
|
+
}
|
|
7475
|
+
}
|
|
6390
7476
|
let lastDaemon;
|
|
6391
7477
|
let lastRefusal;
|
|
6392
7478
|
let lastError;
|
|
@@ -6396,12 +7482,21 @@ function getDaemonConnectionInfo() {
|
|
|
6396
7482
|
socketPath: defaultSocketPath(),
|
|
6397
7483
|
window: { protocolVersion: IPC_PROTOCOL_VERSION, buildId: IPC_BUILD_ID },
|
|
6398
7484
|
...daemon2 ? { daemon: daemon2 } : {},
|
|
6399
|
-
...!client && lastRefusal ? { refused: lastRefusal } : {},
|
|
7485
|
+
...!client && lastRefusal ? { refused: refusalStatus(lastRefusal) } : {},
|
|
6400
7486
|
...!client && lastError ? { error: lastError } : {}
|
|
6401
7487
|
};
|
|
6402
7488
|
}
|
|
7489
|
+
function refusalStatus(refusal2) {
|
|
7490
|
+
const { startsOlder, ...rest } = refusal2;
|
|
7491
|
+
return {
|
|
7492
|
+
...rest,
|
|
7493
|
+
...startsOlder && !olderDaemonDraining() ? { startsOlder: true } : {},
|
|
7494
|
+
...rest.direction === "daemon-older" && olderDaemonBusy() ? { busy: true } : {}
|
|
7495
|
+
};
|
|
7496
|
+
}
|
|
6403
7497
|
async function forceReconnectDaemon() {
|
|
6404
7498
|
stopRetry();
|
|
7499
|
+
startsOlderStreak = 0;
|
|
6405
7500
|
if (client) {
|
|
6406
7501
|
const current2 = client;
|
|
6407
7502
|
setClient(null);
|
|
@@ -6454,7 +7549,10 @@ function refreshDaemonClient() {
|
|
|
6454
7549
|
current2.close();
|
|
6455
7550
|
guiLog.info("disabled, chat runs in this process again", { scope: "daemon" });
|
|
6456
7551
|
}
|
|
6457
|
-
|
|
7552
|
+
dropDaemonState();
|
|
7553
|
+
startsOlderStreak = 0;
|
|
7554
|
+
settleOlderDaemonDrain();
|
|
7555
|
+
if (!olderDaemonDraining()) rehydratePendingApprovals();
|
|
6458
7556
|
stopRetry();
|
|
6459
7557
|
offStateTick ??= onStateTick(refreshDaemonClient);
|
|
6460
7558
|
return;
|
|
@@ -6466,14 +7564,19 @@ function refreshDaemonClient() {
|
|
|
6466
7564
|
}
|
|
6467
7565
|
void tryConnect();
|
|
6468
7566
|
}
|
|
6469
|
-
function
|
|
7567
|
+
function retryDelay() {
|
|
7568
|
+
return startsOlderStreak > 1 ? Math.min(RETRY_MS * 2 ** (startsOlderStreak - 1), MAX_RETRY_MS) : RETRY_MS;
|
|
7569
|
+
}
|
|
7570
|
+
function scheduleRetry(delay = retryDelay(), sooner = false) {
|
|
6470
7571
|
if (retryTimer) {
|
|
6471
|
-
return;
|
|
7572
|
+
if (!sooner || retryDueAt <= Date.now() + delay) return;
|
|
7573
|
+
stopRetry();
|
|
6472
7574
|
}
|
|
7575
|
+
retryDueAt = Date.now() + delay;
|
|
6473
7576
|
retryTimer = setTimeout(() => {
|
|
6474
7577
|
retryTimer = null;
|
|
6475
7578
|
refreshDaemonClient();
|
|
6476
|
-
},
|
|
7579
|
+
}, delay);
|
|
6477
7580
|
retryTimer.unref?.();
|
|
6478
7581
|
}
|
|
6479
7582
|
function stopRetry() {
|
|
@@ -6482,24 +7585,60 @@ function stopRetry() {
|
|
|
6482
7585
|
retryTimer = null;
|
|
6483
7586
|
}
|
|
6484
7587
|
}
|
|
7588
|
+
const SETTLE = {
|
|
7589
|
+
connected: () => {
|
|
7590
|
+
setDaemonSignalsLive(true);
|
|
7591
|
+
stopRetry();
|
|
7592
|
+
guiLog.info("connected, chats run on the daemon", { scope: "daemon", socket: defaultSocketPath() });
|
|
7593
|
+
},
|
|
7594
|
+
disabled: settleDisabled,
|
|
7595
|
+
deferred: () => {
|
|
7596
|
+
if (olderDaemonDraining()) drainHealth();
|
|
7597
|
+
else dropDaemonState();
|
|
7598
|
+
scheduleRetry(RETRY_MS, true);
|
|
7599
|
+
},
|
|
7600
|
+
"older-draining": () => {
|
|
7601
|
+
drainHealth();
|
|
7602
|
+
scheduleRetry();
|
|
7603
|
+
},
|
|
7604
|
+
failed: fellBack
|
|
7605
|
+
};
|
|
7606
|
+
let lastStartAt = Number.NEGATIVE_INFINITY;
|
|
6485
7607
|
async function tryConnect() {
|
|
6486
7608
|
connecting = true;
|
|
6487
|
-
|
|
7609
|
+
let outcome2 = "failed";
|
|
7610
|
+
try {
|
|
7611
|
+
outcome2 = await attempt();
|
|
7612
|
+
} finally {
|
|
7613
|
+
connecting = false;
|
|
7614
|
+
SETTLE[outcome2]();
|
|
7615
|
+
const exit = missedExit;
|
|
7616
|
+
missedExit = null;
|
|
7617
|
+
if (exit && olderDaemonDraining()) exit();
|
|
7618
|
+
}
|
|
7619
|
+
}
|
|
7620
|
+
function deferForLocalWork() {
|
|
7621
|
+
startsOlderStreak = 0;
|
|
7622
|
+
if (!deferredForLocalWork) {
|
|
7623
|
+
deferredForLocalWork = true;
|
|
7624
|
+
guiLog.info("a local run is in flight, attaching to the daemon when it ends", { scope: "daemon" });
|
|
7625
|
+
}
|
|
7626
|
+
return "deferred";
|
|
7627
|
+
}
|
|
7628
|
+
async function attempt() {
|
|
7629
|
+
if (getChatHost().hasActiveWork()) return deferForLocalWork();
|
|
7630
|
+
if (!olderDaemonBusy()) setDaemonHealth("connecting");
|
|
7631
|
+
let spawned = false;
|
|
6488
7632
|
try {
|
|
6489
7633
|
const socketPath = defaultSocketPath();
|
|
6490
7634
|
if (!await probeSocket(socketPath)) {
|
|
6491
|
-
if (!daemonEnabled()) return;
|
|
7635
|
+
if (!daemonEnabled()) return "disabled";
|
|
7636
|
+
spawned = true;
|
|
7637
|
+
lastStartAt = Date.now();
|
|
6492
7638
|
await ensureDaemonRunning({ socketPath, spawnCommand: resolveDaemonSpawnCommand() });
|
|
6493
7639
|
}
|
|
6494
|
-
if (!daemonEnabled()) return;
|
|
6495
|
-
if (getChatHost().hasActiveWork())
|
|
6496
|
-
if (!deferredForLocalWork) {
|
|
6497
|
-
deferredForLocalWork = true;
|
|
6498
|
-
guiLog.info("a local run is in flight, attaching to the daemon when it ends", { scope: "daemon" });
|
|
6499
|
-
}
|
|
6500
|
-
scheduleRetry();
|
|
6501
|
-
return;
|
|
6502
|
-
}
|
|
7640
|
+
if (!daemonEnabled()) return "disabled";
|
|
7641
|
+
if (getChatHost().hasActiveWork()) return deferForLocalWork();
|
|
6503
7642
|
deferredForLocalWork = false;
|
|
6504
7643
|
let closed = false;
|
|
6505
7644
|
const next = await connectIpcClient({
|
|
@@ -6513,27 +7652,22 @@ async function tryConnect() {
|
|
|
6513
7652
|
});
|
|
6514
7653
|
if (!daemonEnabled() || closed || getChatHost().hasActiveWork()) {
|
|
6515
7654
|
next.close();
|
|
6516
|
-
|
|
6517
|
-
setDaemonHealth("disconnected");
|
|
6518
|
-
scheduleRetry();
|
|
6519
|
-
}
|
|
6520
|
-
return;
|
|
7655
|
+
return daemonEnabled() ? "failed" : "disabled";
|
|
6521
7656
|
}
|
|
6522
7657
|
setClient(next);
|
|
7658
|
+
endOlderDaemonDrain();
|
|
6523
7659
|
lastDaemon = next.hello;
|
|
6524
7660
|
lastRefusal = void 0;
|
|
6525
7661
|
lastError = void 0;
|
|
6526
|
-
|
|
6527
|
-
|
|
6528
|
-
|
|
6529
|
-
|
|
6530
|
-
|
|
6531
|
-
|
|
6532
|
-
setDaemonSignalsLive(true);
|
|
6533
|
-
stopRetry();
|
|
6534
|
-
guiLog.info("connected, chats run on the daemon", { scope: "daemon", socket: socketPath });
|
|
7662
|
+
startsOlderStreak = 0;
|
|
7663
|
+
const resumed = daemonSignals.attach(next);
|
|
7664
|
+
next.onSignal(daemonSignals.relay);
|
|
7665
|
+
await resumed;
|
|
7666
|
+
if (client !== next || closed) return daemonEnabled() ? "failed" : "disabled";
|
|
7667
|
+
return "connected";
|
|
6535
7668
|
} catch (error) {
|
|
6536
7669
|
if (error instanceof IpcVersionMismatchError) {
|
|
7670
|
+
const previous = lastRefusal;
|
|
6537
7671
|
if (error.daemon) lastDaemon = error.daemon;
|
|
6538
7672
|
const theirs = error.daemon?.protocolVersion;
|
|
6539
7673
|
lastRefusal = {
|
|
@@ -6541,24 +7675,92 @@ async function tryConnect() {
|
|
|
6541
7675
|
direction: theirs === void 0 || theirs === IPC_PROTOCOL_VERSION ? "unknown" : theirs > IPC_PROTOCOL_VERSION ? "daemon-newer" : "daemon-older"
|
|
6542
7676
|
};
|
|
6543
7677
|
lastError = void 0;
|
|
7678
|
+
if (lastRefusal.direction === "daemon-older") {
|
|
7679
|
+
const refusing = error.daemon?.pid;
|
|
7680
|
+
if (olderDaemonRefused(refusing)) {
|
|
7681
|
+
if (previous?.startsOlder) lastRefusal.startsOlder = true;
|
|
7682
|
+
return "older-draining";
|
|
7683
|
+
}
|
|
7684
|
+
const startedHere = spawned && (error.daemon?.startedAt ?? lastStartAt) >= lastStartAt;
|
|
7685
|
+
if (startedHere) {
|
|
7686
|
+
lastRefusal.startsOlder = true;
|
|
7687
|
+
startsOlderStreak++;
|
|
7688
|
+
guiLog.warn("the daemon this window starts is older than the app, chats run in this process", {
|
|
7689
|
+
scope: "daemon",
|
|
7690
|
+
error: error.message
|
|
7691
|
+
});
|
|
7692
|
+
if (refusing === void 0) return "failed";
|
|
7693
|
+
startOlderDaemonDrain(refusing, startedOlderExited);
|
|
7694
|
+
return "older-draining";
|
|
7695
|
+
}
|
|
7696
|
+
startsOlderStreak = 0;
|
|
7697
|
+
if (!olderDaemonDraining()) {
|
|
7698
|
+
guiLog.info("an older daemon is finishing its runs; requests wait for the new one", {
|
|
7699
|
+
scope: "daemon",
|
|
7700
|
+
error: error.message
|
|
7701
|
+
});
|
|
7702
|
+
}
|
|
7703
|
+
startOlderDaemonDrain(error.daemon?.pid, olderDaemonExited);
|
|
7704
|
+
return "older-draining";
|
|
7705
|
+
}
|
|
7706
|
+
startsOlderStreak = 0;
|
|
6544
7707
|
guiLog.warn("version mismatch, staying in-process (will keep probing)", {
|
|
6545
7708
|
scope: "daemon",
|
|
6546
7709
|
error: error.message
|
|
6547
7710
|
});
|
|
6548
7711
|
} else {
|
|
6549
7712
|
lastRefusal = void 0;
|
|
7713
|
+
startsOlderStreak = 0;
|
|
6550
7714
|
lastError = error instanceof Error ? error.message : String(error);
|
|
6551
7715
|
guiLog.warn("Daemon startup or connection failed", {
|
|
6552
7716
|
scope: "daemon",
|
|
6553
7717
|
error: error instanceof Error ? error.message : String(error)
|
|
6554
7718
|
});
|
|
6555
7719
|
}
|
|
6556
|
-
|
|
6557
|
-
|
|
7720
|
+
return "failed";
|
|
7721
|
+
}
|
|
7722
|
+
}
|
|
7723
|
+
function drainHealth() {
|
|
7724
|
+
setDaemonHealth(olderDaemonBusy() ? "disconnected" : "connecting");
|
|
7725
|
+
}
|
|
7726
|
+
function fellBack() {
|
|
7727
|
+
settleOlderDaemonDrain();
|
|
7728
|
+
if (olderDaemonDraining()) {
|
|
7729
|
+
drainHealth();
|
|
6558
7730
|
scheduleRetry();
|
|
6559
|
-
|
|
6560
|
-
connecting = false;
|
|
7731
|
+
return;
|
|
6561
7732
|
}
|
|
7733
|
+
dropDaemonState();
|
|
7734
|
+
rehydratePendingApprovals();
|
|
7735
|
+
scheduleRetry();
|
|
7736
|
+
}
|
|
7737
|
+
function settleDisabled() {
|
|
7738
|
+
dropDaemonState();
|
|
7739
|
+
settleOlderDaemonDrain();
|
|
7740
|
+
if (!olderDaemonDraining()) rehydratePendingApprovals();
|
|
7741
|
+
}
|
|
7742
|
+
function olderDaemonExited() {
|
|
7743
|
+
if (olderDaemonAlive()) return;
|
|
7744
|
+
if (connecting) {
|
|
7745
|
+
missedExit = olderDaemonExited;
|
|
7746
|
+
return;
|
|
7747
|
+
}
|
|
7748
|
+
stopRetry();
|
|
7749
|
+
const wait2 = lastStartAt + RETRY_MS - Date.now();
|
|
7750
|
+
if (wait2 > 0) {
|
|
7751
|
+
scheduleRetry(wait2);
|
|
7752
|
+
return;
|
|
7753
|
+
}
|
|
7754
|
+
refreshDaemonClient();
|
|
7755
|
+
}
|
|
7756
|
+
function startedOlderExited() {
|
|
7757
|
+
if (olderDaemonAlive()) return;
|
|
7758
|
+
if (connecting) {
|
|
7759
|
+
missedExit = startedOlderExited;
|
|
7760
|
+
return;
|
|
7761
|
+
}
|
|
7762
|
+
stopRetry();
|
|
7763
|
+
fellBack();
|
|
6562
7764
|
}
|
|
6563
7765
|
function handleDisconnect() {
|
|
6564
7766
|
if (!client) {
|
|
@@ -6576,6 +7778,7 @@ function sendPrompt(opts) {
|
|
|
6576
7778
|
prompt: opts.prompt,
|
|
6577
7779
|
// One id per submission: the daemon runs a resend of it once.
|
|
6578
7780
|
requestId: randomUUID(),
|
|
7781
|
+
...opts.clientMessageId ? { clientMessageId: opts.clientMessageId } : {},
|
|
6579
7782
|
...opts.activatedSkills ? { activatedSkills: opts.activatedSkills } : {},
|
|
6580
7783
|
...opts.attachments ? { attachments: opts.attachments } : {},
|
|
6581
7784
|
...opts.keepDraft ? { keepDraft: true } : {}
|
|
@@ -6637,439 +7840,85 @@ async function localRunningSessions() {
|
|
|
6637
7840
|
try {
|
|
6638
7841
|
const ids = new Set((await client2.request("presence.list", {})).filter((e) => e.running).map((e) => e.sessionId));
|
|
6639
7842
|
return (sessionId) => ids.has(sessionId);
|
|
6640
|
-
} catch {
|
|
6641
|
-
return null;
|
|
6642
|
-
}
|
|
6643
|
-
}
|
|
6644
|
-
function listRunningWork(key, options) {
|
|
6645
|
-
return sessionRequest("chat.listWork", key, options?.children ? { children: true } : {});
|
|
6646
|
-
}
|
|
6647
|
-
function cancelRunningWork(key, id, reason) {
|
|
6648
|
-
return sessionRequest("chat.cancelWork", key, { id, ...reason ? { reason } : {} });
|
|
6649
|
-
}
|
|
6650
|
-
function getPlansSnapshot(key) {
|
|
6651
|
-
return sessionRequest("plans.get", key, {});
|
|
6652
|
-
}
|
|
6653
|
-
async function listArtifacts(query) {
|
|
6654
|
-
try {
|
|
6655
|
-
return "sessionId" in query ? await sessionRequest("sessions.artifacts", query.sessionId, {}) : await hostRequest("artifacts.list", { projectRoot: query.projectRoot });
|
|
6656
|
-
} catch {
|
|
6657
|
-
return [];
|
|
6658
|
-
}
|
|
6659
|
-
}
|
|
6660
|
-
async function deleteArtifact(key, artifactId) {
|
|
6661
|
-
try {
|
|
6662
|
-
return await sessionRequest("artifacts.delete", key, { artifactId });
|
|
6663
|
-
} catch {
|
|
6664
|
-
return false;
|
|
6665
|
-
}
|
|
6666
|
-
}
|
|
6667
|
-
async function refreshSessionArtifact(key, artifact, opts, registry) {
|
|
6668
|
-
const updated = await refreshArtifact$1(artifact, registry, opts);
|
|
6669
|
-
if (!updated) {
|
|
6670
|
-
return null;
|
|
6671
|
-
}
|
|
6672
|
-
try {
|
|
6673
|
-
return await hostFor({ key }).request("artifacts.upsert", {
|
|
6674
|
-
artifact: { ...updated, sessionId: sessionIdOf(key) }
|
|
6675
|
-
});
|
|
6676
|
-
} catch {
|
|
6677
|
-
return null;
|
|
6678
|
-
}
|
|
6679
|
-
}
|
|
6680
|
-
function editSessionPlan(key, planId, op) {
|
|
6681
|
-
return sessionRequest("plans.edit", key, { planId, op });
|
|
6682
|
-
}
|
|
6683
|
-
function controlSessionPlan(key, planId, action) {
|
|
6684
|
-
return sessionRequest("plans.control", key, { planId, action });
|
|
6685
|
-
}
|
|
6686
|
-
function getContextBreakdown(key) {
|
|
6687
|
-
return sessionRequest("sessions.contextBreakdown", key, {});
|
|
6688
|
-
}
|
|
6689
|
-
function getSessionSystemMd(key) {
|
|
6690
|
-
return sessionRequest("sessions.systemMd", key, {});
|
|
6691
|
-
}
|
|
6692
|
-
function getSessionContextSegments(key) {
|
|
6693
|
-
return sessionRequest("sessions.contextSegments", key, {});
|
|
6694
|
-
}
|
|
6695
|
-
function getSessionCacheImpact(key, change) {
|
|
6696
|
-
return orNullWhenUnsupported(sessionRequest("sessions.cacheImpact", key, { change }));
|
|
6697
|
-
}
|
|
6698
|
-
function getSessionCacheReport(key) {
|
|
6699
|
-
return orNullWhenUnsupported(sessionRequest("sessions.cacheReport", key, {}));
|
|
6700
|
-
}
|
|
6701
|
-
function orNullWhenUnsupported(request2) {
|
|
6702
|
-
return request2.catch((err) => {
|
|
6703
|
-
if (isUnsupportedMethod(err)) return null;
|
|
6704
|
-
throw err;
|
|
6705
|
-
});
|
|
6706
|
-
}
|
|
6707
|
-
function ensureMainSession() {
|
|
6708
|
-
return hostRequest("orchestration.main", {});
|
|
6709
|
-
}
|
|
6710
|
-
function createSessionSystemOverride(key) {
|
|
6711
|
-
return sessionRequest("sessions.createSystemOverride", key, {});
|
|
6712
|
-
}
|
|
6713
|
-
async function compactSessionNow(key) {
|
|
6714
|
-
await sessionRequest("sessions.compact", key, {});
|
|
6715
|
-
}
|
|
6716
|
-
function shutdownChat() {
|
|
6717
|
-
flushDeltaCoalescer();
|
|
6718
|
-
return getChatHost().shutdown();
|
|
6719
|
-
}
|
|
6720
|
-
async function runShellOnServer(client2, sessionId, run) {
|
|
6721
|
-
const startedAt = Date.now();
|
|
6722
|
-
try {
|
|
6723
|
-
const { streamed: _streamed, ...result } = await runWorkspaceExecStream(
|
|
6724
|
-
client2,
|
|
6725
|
-
{ sessionId, command: run.command },
|
|
6726
|
-
{ signal: run.signal, ...run.onChunk ? { onChunk: run.onChunk } : {} }
|
|
6727
|
-
);
|
|
6728
|
-
return result;
|
|
6729
|
-
} catch (err) {
|
|
6730
|
-
if (!run.signal.aborted) throw err;
|
|
6731
|
-
return { output: "", exitCode: null, durationMs: Date.now() - startedAt, aborted: true, overflowed: false };
|
|
6732
|
-
}
|
|
6733
|
-
}
|
|
6734
|
-
const ENVIRONMENT_WORKSPACE_SCHEME = "zidane-env://";
|
|
6735
|
-
function environmentWorkspaceUri(key) {
|
|
6736
|
-
return `${ENVIRONMENT_WORKSPACE_SCHEME}${encodeURIComponent(key)}`;
|
|
6737
|
-
}
|
|
6738
|
-
function environmentWorkspaceSession(cwd) {
|
|
6739
|
-
if (typeof cwd !== "string" || !cwd.startsWith(ENVIRONMENT_WORKSPACE_SCHEME)) return void 0;
|
|
6740
|
-
const encoded = cwd.slice(ENVIRONMENT_WORKSPACE_SCHEME.length);
|
|
6741
|
-
if (!encoded) return void 0;
|
|
6742
|
-
try {
|
|
6743
|
-
return asSessionKey(decodeURIComponent(encoded));
|
|
6744
|
-
} catch {
|
|
6745
|
-
return void 0;
|
|
6746
|
-
}
|
|
6747
|
-
}
|
|
6748
|
-
function wireEntries(call, sessionId) {
|
|
6749
|
-
return {
|
|
6750
|
-
create: (path, kind, options = {}) => call("sessions.workspaceCreate", {
|
|
6751
|
-
sessionId,
|
|
6752
|
-
path,
|
|
6753
|
-
kind,
|
|
6754
|
-
...options.content ? { content: Buffer$1.from(options.content).toString("base64") } : {},
|
|
6755
|
-
...options.freeName ? { freeName: true } : {}
|
|
6756
|
-
}),
|
|
6757
|
-
move: (from, to) => call("sessions.workspaceMove", { sessionId, from, to }),
|
|
6758
|
-
copy: (from, toDir) => call("sessions.workspaceCopy", { sessionId, from, toDir }),
|
|
6759
|
-
remove: (path) => call("sessions.workspaceRemove", { sessionId, path })
|
|
6760
|
-
};
|
|
6761
|
-
}
|
|
6762
|
-
function opsFor(key) {
|
|
6763
|
-
const { host: routed, sessionId } = sessionHost(key);
|
|
6764
|
-
if (routed.remote) {
|
|
6765
|
-
return {
|
|
6766
|
-
exec: (command, timeoutSeconds) => routed.call("sessions.workspaceExec", { sessionId, command, ...timeoutSeconds ? { timeoutSeconds } : {} }),
|
|
6767
|
-
read: (path) => routed.call("sessions.workspaceReadFile", { sessionId, path }),
|
|
6768
|
-
write: (path, content) => routed.call("sessions.workspaceWriteFile", { sessionId, path, content }),
|
|
6769
|
-
entries: wireEntries((method, params) => routed.call(method, params), sessionId),
|
|
6770
|
-
emptyDirs: () => routed.call("sessions.workspaceEmptyDirs", { sessionId }).catch(() => [])
|
|
6771
|
-
};
|
|
6772
|
-
}
|
|
6773
|
-
const daemon2 = getDaemonClient();
|
|
6774
|
-
if (daemon2) {
|
|
6775
|
-
return {
|
|
6776
|
-
exec: (command, timeoutSeconds) => daemon2.request("sessions.workspaceExec", {
|
|
6777
|
-
sessionId,
|
|
6778
|
-
command,
|
|
6779
|
-
...timeoutSeconds ? { timeoutSeconds } : {}
|
|
6780
|
-
}),
|
|
6781
|
-
read: (path) => daemon2.request("sessions.workspaceReadFile", { sessionId, path }),
|
|
6782
|
-
write: (path, content) => daemon2.request("sessions.workspaceWriteFile", { sessionId, path, content }),
|
|
6783
|
-
entries: wireEntries(
|
|
6784
|
-
(method, params) => daemon2.request(method, params),
|
|
6785
|
-
sessionId
|
|
6786
|
-
),
|
|
6787
|
-
emptyDirs: () => daemon2.request("sessions.workspaceEmptyDirs", { sessionId }).catch(() => [])
|
|
6788
|
-
};
|
|
6789
|
-
}
|
|
6790
|
-
const host2 = getChatHost();
|
|
6791
|
-
return {
|
|
6792
|
-
exec: (command, timeoutSeconds) => host2.workspaceExec(sessionId, command, timeoutSeconds ? { timeoutSeconds } : {}),
|
|
6793
|
-
read: (path) => host2.workspaceReadFile(sessionId, path),
|
|
6794
|
-
write: (path, content) => host2.workspaceWriteFile(sessionId, path, content),
|
|
6795
|
-
entries: {
|
|
6796
|
-
create: (path, kind, options) => host2.workspaceCreate(sessionId, path, kind, options),
|
|
6797
|
-
move: (from, to) => host2.workspaceMove(sessionId, from, to),
|
|
6798
|
-
copy: (from, toDir) => host2.workspaceCopy(sessionId, from, toDir),
|
|
6799
|
-
remove: (path) => host2.workspaceRemove(sessionId, path)
|
|
6800
|
-
},
|
|
6801
|
-
emptyDirs: () => host2.workspaceEmptyDirs(sessionId).catch(() => [])
|
|
6802
|
-
};
|
|
6803
|
-
}
|
|
6804
|
-
function q(value) {
|
|
6805
|
-
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
6806
|
-
}
|
|
6807
|
-
function safeRel(rel) {
|
|
6808
|
-
const segments = rel.split("/").filter((s) => s && s !== ".");
|
|
6809
|
-
return rel.startsWith("/") || segments.includes("..") ? null : segments.join("/");
|
|
6810
|
-
}
|
|
6811
|
-
async function lsFiles(ops) {
|
|
6812
|
-
const result = await ops.exec("git ls-files -z --cached --others --exclude-standard", 30);
|
|
6813
|
-
return result.exitCode === 0 ? result.stdout.split("\0").filter(Boolean) : null;
|
|
6814
|
-
}
|
|
6815
|
-
async function listEnvironmentWorkspace(sessionId) {
|
|
6816
|
-
const ops = opsFor(sessionId);
|
|
6817
|
-
const [listed, emptyDirs] = await Promise.all([lsFiles(ops), ops.emptyDirs()]);
|
|
6818
|
-
const files = listed ?? (await ops.exec(`find . -type f -not -path './.git/*' | head -n ${WORKSPACE_MAX_ENTRIES}`, 30)).stdout.split("\n").map((line) => line.replace(/^\.\//, "")).filter(Boolean);
|
|
6819
|
-
const entries = [
|
|
6820
|
-
...files.slice(0, WORKSPACE_MAX_ENTRIES).map((path) => ({ path, kind: "file" })),
|
|
6821
|
-
...emptyDirs.map((path) => ({ path: `${path}/`, kind: "dir" }))
|
|
6822
|
-
];
|
|
6823
|
-
return entries.slice(0, WORKSPACE_MAX_ENTRIES).sort((a, b) => a.path.localeCompare(b.path));
|
|
6824
|
-
}
|
|
6825
|
-
function environmentEntries(sessionId) {
|
|
6826
|
-
return opsFor(sessionId).entries;
|
|
6827
|
-
}
|
|
6828
|
-
async function importIntoEnvironment(sessionId, dir, paths) {
|
|
6829
|
-
try {
|
|
6830
|
-
return await importEntries(opsFor(sessionId).entries.create, dir, await hostImportItems(paths));
|
|
6831
|
-
} catch (error) {
|
|
6832
|
-
return { ok: false, reason: "denied", message: error instanceof Error ? error.message : String(error), paths: [] };
|
|
6833
|
-
}
|
|
6834
|
-
}
|
|
6835
|
-
async function fileMeta(ops, rel) {
|
|
6836
|
-
const result = await ops.exec(
|
|
6837
|
-
`[ -f ${q(rel)} ] || exit 3; printf '%s %s ' "$(stat -c %s ${q(rel)})" "$(stat -c %Y ${q(rel)})"; head -c 8192 ${q(rel)} | tr -dc '\\000' | wc -c`,
|
|
6838
|
-
15
|
|
6839
|
-
);
|
|
6840
|
-
if (result.exitCode !== 0) return null;
|
|
6841
|
-
const [size, mtime, nuls] = result.stdout.trim().split(/\s+/).map(Number);
|
|
6842
|
-
if (!Number.isFinite(size) || !Number.isFinite(mtime)) return null;
|
|
6843
|
-
return { size, mtimeMs: mtime * 1e3, binary: (nuls ?? 0) > 0 };
|
|
6844
|
-
}
|
|
6845
|
-
async function readEnvironmentFile(sessionId, rel) {
|
|
6846
|
-
const path = safeRel(rel);
|
|
6847
|
-
if (path === null) return null;
|
|
6848
|
-
const ops = opsFor(sessionId);
|
|
6849
|
-
const meta = await fileMeta(ops, path);
|
|
6850
|
-
if (!meta) return null;
|
|
6851
|
-
const base = { path: rel, size: meta.size, mtimeMs: meta.mtimeMs };
|
|
6852
|
-
if (meta.size > WORKSPACE_MAX_FILE_BYTES) return { ...base, contents: "", truncated: true, binary: false };
|
|
6853
|
-
if (meta.binary) return { ...base, contents: "", truncated: false, binary: true };
|
|
6854
|
-
const contents = await ops.read(path).catch(() => null);
|
|
6855
|
-
return contents === null ? null : { ...base, contents, truncated: false, binary: false };
|
|
6856
|
-
}
|
|
6857
|
-
async function writeEnvironmentFile(sessionId, rel, contents, expectedMtimeMs) {
|
|
6858
|
-
const path = safeRel(rel);
|
|
6859
|
-
if (path === null) return { ok: false, reason: "denied" };
|
|
6860
|
-
const ops = opsFor(sessionId);
|
|
6861
|
-
const meta = await fileMeta(ops, path);
|
|
6862
|
-
if (!meta) return { ok: false, reason: "missing" };
|
|
6863
|
-
if (Math.floor(meta.mtimeMs / 1e3) !== Math.floor(expectedMtimeMs / 1e3)) return { ok: false, reason: "changed" };
|
|
6864
|
-
try {
|
|
6865
|
-
await ops.write(path, contents);
|
|
6866
|
-
} catch {
|
|
6867
|
-
return { ok: false, reason: "denied" };
|
|
6868
|
-
}
|
|
6869
|
-
const after = await fileMeta(ops, path);
|
|
6870
|
-
return { ok: true, mtimeMs: after?.mtimeMs ?? Date.now() };
|
|
6871
|
-
}
|
|
6872
|
-
async function environmentGitStatus(sessionId) {
|
|
6873
|
-
const ops = opsFor(sessionId);
|
|
6874
|
-
return gitStatusOf(async (untracked) => {
|
|
6875
|
-
const result = await ops.exec(`git status --porcelain=v1 -z --untracked-files=${untracked}`, 30);
|
|
6876
|
-
return result.exitCode === 0 ? result.stdout : null;
|
|
6877
|
-
});
|
|
6878
|
-
}
|
|
6879
|
-
async function environmentGitDiff(sessionId, rel, context = 3) {
|
|
6880
|
-
const path = rel === void 0 ? void 0 : safeRel(rel);
|
|
6881
|
-
if (path === null) return "";
|
|
6882
|
-
const ops = opsFor(sessionId);
|
|
6883
|
-
const target = path ? ` -- ${q(path)}` : "";
|
|
6884
|
-
const unified = Number.isFinite(context) ? `-U${Math.max(0, Math.floor(context))}` : "-U999999";
|
|
6885
|
-
const tracked2 = await ops.exec(`git diff HEAD --no-color --no-ext-diff ${unified}${target}`, 60);
|
|
6886
|
-
const untrackedList = await ops.exec(`git ls-files --others --exclude-standard -z${target}`, 30);
|
|
6887
|
-
return assembleDiff(
|
|
6888
|
-
tracked2.exitCode === 0 ? tracked2.stdout : "",
|
|
6889
|
-
untrackedList.stdout.split("\0").filter(Boolean),
|
|
6890
|
-
4,
|
|
6891
|
-
async (file) => {
|
|
6892
|
-
const read = await readEnvironmentFile(sessionId, file);
|
|
6893
|
-
return read && !read.binary && !read.truncated ? read.contents : null;
|
|
6894
|
-
}
|
|
6895
|
-
);
|
|
7843
|
+
} catch {
|
|
7844
|
+
return null;
|
|
7845
|
+
}
|
|
6896
7846
|
}
|
|
6897
|
-
|
|
6898
|
-
|
|
6899
|
-
if (path === null) return null;
|
|
6900
|
-
const result = await opsFor(sessionId).exec(`git show ${q(`HEAD:${path}`)}`, 30);
|
|
6901
|
-
return result.exitCode === 0 ? result.stdout : null;
|
|
7847
|
+
function listRunningWork(key, options) {
|
|
7848
|
+
return sessionRequest("chat.listWork", key, options?.children ? { children: true } : {});
|
|
6902
7849
|
}
|
|
6903
|
-
|
|
6904
|
-
|
|
6905
|
-
return paths ? fileEntriesFromPaths(paths, "git") : [];
|
|
7850
|
+
function cancelRunningWork(key, id, reason) {
|
|
7851
|
+
return sessionRequest("chat.cancelWork", key, { id, ...reason ? { reason } : {} });
|
|
6906
7852
|
}
|
|
6907
|
-
|
|
6908
|
-
|
|
6909
|
-
const { host: routed, sessionId: id } = sessionHost(sessionId);
|
|
6910
|
-
if (routed.remote) {
|
|
6911
|
-
const client2 = routed.server.client;
|
|
6912
|
-
if (!client2) throw new Error(`${routed.name} is offline.`);
|
|
6913
|
-
return runShellOnServer(client2, id, run);
|
|
6914
|
-
}
|
|
6915
|
-
const startedAt = Date.now();
|
|
6916
|
-
const aborted = new Promise((resolve2) => {
|
|
6917
|
-
if (run.signal.aborted) resolve2(null);
|
|
6918
|
-
else run.signal.addEventListener("abort", () => resolve2(null), { once: true });
|
|
6919
|
-
});
|
|
6920
|
-
const result = await Promise.race([opsFor(sessionId).exec(run.command, SHELL_TIMEOUT_SECONDS), aborted]);
|
|
6921
|
-
const durationMs = Date.now() - startedAt;
|
|
6922
|
-
if (!result) return { output: "", exitCode: null, durationMs, aborted: true, overflowed: false };
|
|
6923
|
-
const output = [result.stdout, result.stderr].filter(Boolean).join(result.stdout.endsWith("\n") ? "" : "\n");
|
|
6924
|
-
run.onChunk?.(output);
|
|
6925
|
-
return { output, exitCode: result.exitCode, durationMs, aborted: false, overflowed: false };
|
|
7853
|
+
function getPlansSnapshot(key) {
|
|
7854
|
+
return sessionRequest("plans.get", key, {});
|
|
6926
7855
|
}
|
|
6927
|
-
function
|
|
6928
|
-
|
|
6929
|
-
|
|
6930
|
-
|
|
6931
|
-
|
|
6932
|
-
|
|
6933
|
-
userMessageCount: meta?.userMessageCount ?? 0,
|
|
6934
|
-
runCount: meta?.runCount ?? 0,
|
|
6935
|
-
...row.projectRoot ? { projectRoot: row.projectRoot } : {},
|
|
6936
|
-
...row.repoKey ? { repoKey: row.repoKey } : {},
|
|
6937
|
-
createdAt: row.createdAt,
|
|
6938
|
-
updatedAt: row.updatedAt,
|
|
6939
|
-
cwd: row.cwd,
|
|
6940
|
-
status: row.status,
|
|
6941
|
-
...row.status === "running" && row.runStartedAt !== void 0 ? { runStartedAt: row.runStartedAt } : {},
|
|
6942
|
-
...row.status === "running" && row.runEstimates ? { runEstimates: row.runEstimates } : {},
|
|
6943
|
-
...row.agentId ? { agentId: row.agentId } : {},
|
|
6944
|
-
...row.effort ? { effort: row.effort } : {},
|
|
6945
|
-
...row.modelOptions && Object.keys(row.modelOptions).length > 0 ? { modelOptions: row.modelOptions } : {},
|
|
6946
|
-
...row.providerKey ? { providerKey: row.providerKey } : {},
|
|
6947
|
-
...row.modelId ? { modelId: row.modelId } : {},
|
|
6948
|
-
...row.account ? { account: row.account } : {},
|
|
6949
|
-
...row.modelFallbacks && row.modelFallbacks.length > 0 ? { modelFallbacks: row.modelFallbacks } : {},
|
|
6950
|
-
archived: row.archived,
|
|
6951
|
-
...row.favorite ? { favorite: true } : {},
|
|
6952
|
-
...meta?.scheduleId ?? row.scheduleId ? { scheduleId: meta?.scheduleId ?? row.scheduleId } : {},
|
|
6953
|
-
...row.isMain ? { isMain: true } : {},
|
|
6954
|
-
...row.spaceId ? { spaceId: row.spaceId } : {},
|
|
6955
|
-
...row.environment ? { environment: row.environment } : {},
|
|
6956
|
-
...meta?.artifactCount !== void 0 ? { artifactCount: meta.artifactCount } : {},
|
|
6957
|
-
workspace: environmentWorkspaceUri(key),
|
|
6958
|
-
hostId: hostId2
|
|
6959
|
-
};
|
|
7856
|
+
async function listArtifacts(query) {
|
|
7857
|
+
try {
|
|
7858
|
+
return "sessionId" in query ? await sessionRequest("sessions.artifacts", query.sessionId, {}) : await hostRequest("artifacts.list", { projectRoot: query.projectRoot });
|
|
7859
|
+
} catch {
|
|
7860
|
+
return [];
|
|
7861
|
+
}
|
|
6960
7862
|
}
|
|
6961
|
-
|
|
6962
|
-
|
|
6963
|
-
|
|
6964
|
-
|
|
6965
|
-
|
|
7863
|
+
async function deleteArtifact(key, artifactId) {
|
|
7864
|
+
try {
|
|
7865
|
+
return await sessionRequest("artifacts.delete", key, { artifactId });
|
|
7866
|
+
} catch {
|
|
7867
|
+
return false;
|
|
7868
|
+
}
|
|
6966
7869
|
}
|
|
6967
|
-
async function
|
|
6968
|
-
const
|
|
6969
|
-
|
|
6970
|
-
|
|
6971
|
-
|
|
7870
|
+
async function refreshSessionArtifact(key, artifact, opts, registry) {
|
|
7871
|
+
const updated = await refreshArtifact$1(artifact, registry, opts);
|
|
7872
|
+
if (!updated) {
|
|
7873
|
+
return null;
|
|
7874
|
+
}
|
|
6972
7875
|
try {
|
|
6973
|
-
|
|
6974
|
-
|
|
6975
|
-
host2.call("sessions.listMeta", {}).catch(() => [])
|
|
6976
|
-
]);
|
|
6977
|
-
const metaById = new Map(metas.map((meta) => [meta.id, meta]));
|
|
6978
|
-
const directory2 = getHostDirectory();
|
|
6979
|
-
const list = rows.map((row) => {
|
|
6980
|
-
directory2.noteSessionHost(row.id, hostId2);
|
|
6981
|
-
return serverSessionRow(hostId2, row, metaById.get(row.id));
|
|
7876
|
+
return await hostFor({ key }).request("artifacts.upsert", {
|
|
7877
|
+
artifact: { ...updated, sessionId: sessionIdOf(key) }
|
|
6982
7878
|
});
|
|
6983
|
-
lastLists.set(cacheKey, list);
|
|
6984
|
-
return list;
|
|
6985
7879
|
} catch {
|
|
6986
|
-
return
|
|
7880
|
+
return null;
|
|
6987
7881
|
}
|
|
6988
7882
|
}
|
|
6989
|
-
|
|
6990
|
-
|
|
6991
|
-
const answers = await Promise.all(
|
|
6992
|
-
servers.map(async (server) => {
|
|
6993
|
-
try {
|
|
6994
|
-
const rows = await listServerSessions(server.id, filter);
|
|
6995
|
-
if (rows.length === 0) return [];
|
|
6996
|
-
const matches = await remote(server.id).call("history.searchAll", {
|
|
6997
|
-
query,
|
|
6998
|
-
sessionIds: rows.map((row) => sessionIdOf(row.id)),
|
|
6999
|
-
excerptLimit: 1
|
|
7000
|
-
});
|
|
7001
|
-
return rows.flatMap((row) => {
|
|
7002
|
-
const match = matches[sessionIdOf(row.id)];
|
|
7003
|
-
if (!match) return [];
|
|
7004
|
-
return [
|
|
7005
|
-
{
|
|
7006
|
-
sessionId: row.id,
|
|
7007
|
-
title: row.title,
|
|
7008
|
-
excerpt: match.excerpts[0]?.text ?? "",
|
|
7009
|
-
matchCount: Math.max(1, match.matchedTurnIds.length),
|
|
7010
|
-
updatedAt: row.updatedAt
|
|
7011
|
-
}
|
|
7012
|
-
];
|
|
7013
|
-
});
|
|
7014
|
-
} catch {
|
|
7015
|
-
return [];
|
|
7016
|
-
}
|
|
7017
|
-
})
|
|
7018
|
-
);
|
|
7019
|
-
return answers.flat();
|
|
7883
|
+
function editSessionPlan(key, planId, op) {
|
|
7884
|
+
return sessionRequest("plans.edit", key, { planId, op });
|
|
7020
7885
|
}
|
|
7021
|
-
function
|
|
7022
|
-
|
|
7886
|
+
function controlSessionPlan(key, planId, action) {
|
|
7887
|
+
return sessionRequest("plans.control", key, { planId, action });
|
|
7023
7888
|
}
|
|
7024
|
-
function
|
|
7025
|
-
|
|
7026
|
-
return host2.remote ? { host: host2, sessionId } : null;
|
|
7889
|
+
function getContextBreakdown(key) {
|
|
7890
|
+
return sessionRequest("sessions.contextBreakdown", key, {});
|
|
7027
7891
|
}
|
|
7028
|
-
|
|
7029
|
-
|
|
7030
|
-
if (!remote2) return null;
|
|
7031
|
-
return loadSessionDocument((method, params) => remote2.host.call(method, params), remote2.sessionId);
|
|
7892
|
+
function getSessionSystemMd(key) {
|
|
7893
|
+
return sessionRequest("sessions.systemMd", key, {});
|
|
7032
7894
|
}
|
|
7033
|
-
|
|
7034
|
-
|
|
7035
|
-
if (!remote2) return null;
|
|
7036
|
-
const { host: host2, sessionId } = remote2;
|
|
7037
|
-
try {
|
|
7038
|
-
return await host2.call("sessions.getToolResult", { sessionId, callId, ...turnId ? { turnId } : {} });
|
|
7039
|
-
} catch (err) {
|
|
7040
|
-
if (!isUnsupportedMethod(err)) return null;
|
|
7041
|
-
}
|
|
7042
|
-
const data = await host2.call("sessions.get", { sessionId }).catch(() => null);
|
|
7043
|
-
for (const turn of data?.turns ?? []) {
|
|
7044
|
-
for (const block of turn.content) {
|
|
7045
|
-
if (block.type === "tool_result" && block.callId === callId) return toolResultText(block.output);
|
|
7046
|
-
}
|
|
7047
|
-
}
|
|
7048
|
-
return null;
|
|
7895
|
+
function getSessionContextSegments(key) {
|
|
7896
|
+
return sessionRequest("sessions.contextSegments", key, {});
|
|
7049
7897
|
}
|
|
7050
|
-
|
|
7051
|
-
|
|
7052
|
-
|
|
7053
|
-
|
|
7054
|
-
|
|
7055
|
-
|
|
7056
|
-
|
|
7057
|
-
|
|
7058
|
-
|
|
7059
|
-
|
|
7060
|
-
|
|
7061
|
-
|
|
7062
|
-
|
|
7063
|
-
|
|
7064
|
-
|
|
7065
|
-
|
|
7066
|
-
|
|
7067
|
-
|
|
7068
|
-
|
|
7069
|
-
|
|
7070
|
-
|
|
7071
|
-
|
|
7072
|
-
|
|
7898
|
+
function getSessionCacheImpact(key, change) {
|
|
7899
|
+
return orNullWhenUnsupported(sessionRequest("sessions.cacheImpact", key, { change }));
|
|
7900
|
+
}
|
|
7901
|
+
function getSessionCacheReport(key) {
|
|
7902
|
+
return orNullWhenUnsupported(sessionRequest("sessions.cacheReport", key, {}));
|
|
7903
|
+
}
|
|
7904
|
+
function orNullWhenUnsupported(request2) {
|
|
7905
|
+
return request2.catch((err) => {
|
|
7906
|
+
if (isUnsupportedMethod(err)) return null;
|
|
7907
|
+
throw err;
|
|
7908
|
+
});
|
|
7909
|
+
}
|
|
7910
|
+
function ensureMainSession() {
|
|
7911
|
+
return hostRequest("orchestration.main", {});
|
|
7912
|
+
}
|
|
7913
|
+
function createSessionSystemOverride(key) {
|
|
7914
|
+
return sessionRequest("sessions.createSystemOverride", key, {});
|
|
7915
|
+
}
|
|
7916
|
+
async function compactSessionNow(key) {
|
|
7917
|
+
await sessionRequest("sessions.compact", key, {});
|
|
7918
|
+
}
|
|
7919
|
+
function shutdownChat() {
|
|
7920
|
+
flushDeltaCoalescer();
|
|
7921
|
+
return getChatHost().shutdown();
|
|
7073
7922
|
}
|
|
7074
7923
|
function retractRemovedServer(removed) {
|
|
7075
7924
|
const reason = `${removed.name} was removed`;
|
|
@@ -7108,8 +7957,7 @@ function watchServerRemovals() {
|
|
|
7108
7957
|
function perfWatchError(err) {
|
|
7109
7958
|
if (isMethodNotFound(err)) return { kind: "unavailable" };
|
|
7110
7959
|
const detail = err instanceof Error ? err.message : String(err);
|
|
7111
|
-
|
|
7112
|
-
return { kind: code === IpcErrorCode.Forbidden ? "refused" : "failed", detail };
|
|
7960
|
+
return { kind: "failed", detail };
|
|
7113
7961
|
}
|
|
7114
7962
|
function keyed(hostId2, sample) {
|
|
7115
7963
|
if (!sample.processes.some((p) => p.session)) return sample;
|
|
@@ -7195,6 +8043,21 @@ const remotePerf = createRemotePerf({
|
|
|
7195
8043
|
return host2.call(method, params);
|
|
7196
8044
|
}
|
|
7197
8045
|
});
|
|
8046
|
+
const relays = /* @__PURE__ */ new Map();
|
|
8047
|
+
function relayOf(hostId2) {
|
|
8048
|
+
let relay = relays.get(hostId2);
|
|
8049
|
+
if (!relay) {
|
|
8050
|
+
relay = createResumingRelay((signal) => forwardServerSignal(hostId2, signal));
|
|
8051
|
+
relays.set(hostId2, relay);
|
|
8052
|
+
}
|
|
8053
|
+
return relay;
|
|
8054
|
+
}
|
|
8055
|
+
function relayServerSignal(hostId2, signal, meta) {
|
|
8056
|
+
relayOf(hostId2).relay(signal, meta);
|
|
8057
|
+
}
|
|
8058
|
+
function resumeServerSignals(hostId2, client2) {
|
|
8059
|
+
return relayOf(hostId2).attach(client2);
|
|
8060
|
+
}
|
|
7198
8061
|
function terminalScopeOf(terminal) {
|
|
7199
8062
|
if (terminal.sessionId || !terminal.scope) return terminal.sessionId;
|
|
7200
8063
|
return terminal.scope.draftId ? `draft:${terminal.scope.draftId}` : `project:${terminal.scope.root}`;
|
|
@@ -7238,6 +8101,10 @@ function forwardServerSignal(hostId2, signal) {
|
|
|
7238
8101
|
case "sync:changed":
|
|
7239
8102
|
sendToAllWindows("hosts:syncChanged", { hostId: hostId2 }, { bufferedElsewhere: true });
|
|
7240
8103
|
return;
|
|
8104
|
+
// Its tokens changed (a create, a revoke, a pairing, the CLI): the open Hosts page of that server re-reads them.
|
|
8105
|
+
case "tokens:changed":
|
|
8106
|
+
sendToAllWindows("hosts:tokensChanged", { hostId: hostId2 }, { bufferedElsewhere: true });
|
|
8107
|
+
return;
|
|
7241
8108
|
case "presence:changed":
|
|
7242
8109
|
for (const entry of signal.sessions) directory2.noteSessionHost(entry.sessionId, hostId2);
|
|
7243
8110
|
sendToAllWindows("presence:changed", { sessions: setHostPresence(hostId2, signal.sessions) });
|
|
@@ -7353,15 +8220,22 @@ async function syncRemoteHosts(appVersion = "zidane-gui") {
|
|
|
7353
8220
|
}
|
|
7354
8221
|
if (controller) return controller;
|
|
7355
8222
|
starting ??= (async () => {
|
|
7356
|
-
const { startRemoteHosts } = await import("./chunks/remote-hosts-
|
|
8223
|
+
const { startRemoteHosts } = await import("./chunks/remote-hosts-ZyXkwftF.js");
|
|
7357
8224
|
if (!remoteHostsEnabled()) return null;
|
|
7358
8225
|
watchServerRemovals();
|
|
7359
8226
|
controller = startRemoteHosts({
|
|
7360
8227
|
dataDir: userDataDir(),
|
|
7361
8228
|
directory: getHostDirectory(),
|
|
7362
8229
|
appVersion,
|
|
7363
|
-
onSignal:
|
|
7364
|
-
onConnected: (hostId2) => {
|
|
8230
|
+
onSignal: relayServerSignal,
|
|
8231
|
+
onConnected: (hostId2, client2) => {
|
|
8232
|
+
void resumeServerSignals(hostId2, client2).catch(
|
|
8233
|
+
(err) => guiLog.warn("server resume failed", {
|
|
8234
|
+
scope: "hosts",
|
|
8235
|
+
hostId: hostId2,
|
|
8236
|
+
error: err instanceof Error ? err.message : String(err)
|
|
8237
|
+
})
|
|
8238
|
+
);
|
|
7365
8239
|
for (const listener of connectedListeners) listener(hostId2);
|
|
7366
8240
|
},
|
|
7367
8241
|
// Settings sync (Settings › Hosts › a server › Sync): this computer's state, the shared state.json.
|
|
@@ -7970,9 +8844,6 @@ function tooOldServerError(err, host2, action) {
|
|
|
7970
8844
|
const version = host2.server.serverVersion ?? host2.server.client?.hello.appVersion;
|
|
7971
8845
|
return new Error(`This server${version ? ` (v${version})` : ""} is too old for ${action}. Update zidane-server.`);
|
|
7972
8846
|
}
|
|
7973
|
-
function announceSessionsTouch(sessionId) {
|
|
7974
|
-
hostNotify("sessions.touch", { sessionId });
|
|
7975
|
-
}
|
|
7976
8847
|
const GIT_REPO_CACHE_TTL_MS = 5 * 6e4;
|
|
7977
8848
|
const gitRepoCache = /* @__PURE__ */ new Map();
|
|
7978
8849
|
function isGitRepoCached(cwd) {
|
|
@@ -7994,7 +8865,7 @@ function invalidateGitRepoCache() {
|
|
|
7994
8865
|
gitRepoCache.clear();
|
|
7995
8866
|
}
|
|
7996
8867
|
function announceRowChanged(sessionId) {
|
|
7997
|
-
|
|
8868
|
+
announceLocalSessionRow(sessionId);
|
|
7998
8869
|
}
|
|
7999
8870
|
const staleRunAnswers = createRevalidatingCache({
|
|
8000
8871
|
maxEntries: 256,
|
|
@@ -8045,12 +8916,12 @@ const daemonRowRecords = /* @__PURE__ */ new WeakMap();
|
|
|
8045
8916
|
function daemonRowProviders(meta, cwd) {
|
|
8046
8917
|
const keys = daemonProviderKeys(cwd);
|
|
8047
8918
|
if (keys) {
|
|
8048
|
-
let
|
|
8049
|
-
if (!
|
|
8050
|
-
|
|
8051
|
-
daemonRowRecords.set(keys,
|
|
8919
|
+
let record2 = daemonRowRecords.get(keys);
|
|
8920
|
+
if (!record2) {
|
|
8921
|
+
record2 = { ...BUILTIN_PROVIDERS, ...Object.fromEntries([...keys].map((key) => [key, true])) };
|
|
8922
|
+
daemonRowRecords.set(keys, record2);
|
|
8052
8923
|
}
|
|
8053
|
-
return
|
|
8924
|
+
return record2;
|
|
8054
8925
|
}
|
|
8055
8926
|
const daemon2 = daemonReads();
|
|
8056
8927
|
if (daemon2 && !pendingDaemonRows.has(cwd)) {
|
|
@@ -8108,6 +8979,7 @@ function sidebarRowFromMeta(meta, settings) {
|
|
|
8108
8979
|
...meta.projectRoot ? { projectRoot: meta.projectRoot } : {},
|
|
8109
8980
|
createdAt: meta.createdAt,
|
|
8110
8981
|
updatedAt: meta.updatedAt,
|
|
8982
|
+
...meta.lastUserMessageAt !== void 0 ? { lastUserMessageAt: meta.lastUserMessageAt } : {},
|
|
8111
8983
|
cwd,
|
|
8112
8984
|
/*
|
|
8113
8985
|
* Cached git check — `meta.projectRoot` can't stand in: it falls back
|
|
@@ -8177,6 +9049,7 @@ function localExtensionSpace(spaceId, cwd) {
|
|
|
8177
9049
|
return entry ? extensionSpace(entry.item, entry.extension) : void 0;
|
|
8178
9050
|
}
|
|
8179
9051
|
function registerSessionChannels({ ipc }) {
|
|
9052
|
+
setLocalSessionRows(buildSidebarRow);
|
|
8180
9053
|
registerSessionListChannels(ipc);
|
|
8181
9054
|
registerSessionEditChannels(ipc);
|
|
8182
9055
|
}
|
|
@@ -8301,14 +9174,9 @@ function registerSessionEditChannels(ipc) {
|
|
|
8301
9174
|
});
|
|
8302
9175
|
ipc.handle("sessions:setFavorite", async (_e, key, favorite) => {
|
|
8303
9176
|
const value = favorite === true;
|
|
8304
|
-
|
|
8305
|
-
|
|
8306
|
-
|
|
8307
|
-
const { host: host2, sessionId } = sessionHost(key);
|
|
8308
|
-
if (host2.remote || !isUnsupportedMethod(err)) throw tooOldServerError(err, host2, "starring sessions");
|
|
8309
|
-
await patchSessionMetadata(sessionId, { favorite: value }, { bumpUpdatedAt: false });
|
|
8310
|
-
announceSessionsTouch(sessionId);
|
|
8311
|
-
}
|
|
9177
|
+
await sessionRequest("sessions.setFavorite", key, { favorite: value }, { fallback: true }).catch(
|
|
9178
|
+
(err) => Promise.reject(tooOldServerError(err, sessionHost(key).host, "starring sessions"))
|
|
9179
|
+
);
|
|
8312
9180
|
});
|
|
8313
9181
|
ipc.handle("sessions:setSpace", async (_e, key, spaceId) => {
|
|
8314
9182
|
const { host: host2, sessionId: id } = sessionHost(key);
|
|
@@ -8355,12 +9223,7 @@ function registerSessionEditChannels(ipc) {
|
|
|
8355
9223
|
await sessionRequest("sessions.editTurnText", id, { turnId, text: text2 }, { fallback: true });
|
|
8356
9224
|
});
|
|
8357
9225
|
ipc.handle("sessions:rewind", async (_e, id, turnId, opts) => {
|
|
8358
|
-
await sessionRequest(
|
|
8359
|
-
"sessions.rewind",
|
|
8360
|
-
id,
|
|
8361
|
-
{ turnId, inclusive: opts?.inclusive === true },
|
|
8362
|
-
{ fallback: true }
|
|
8363
|
-
).catch((err) => Promise.reject(tooOldServerError(err, sessionHost(id).host, "rewinding sessions")));
|
|
9226
|
+
await sessionRequest("sessions.rewind", id, { turnId, inclusive: opts?.inclusive === true }, { fallback: true });
|
|
8364
9227
|
});
|
|
8365
9228
|
ipc.handle("sessions:sideSession", async (_e, key) => {
|
|
8366
9229
|
const { host: host2, sessionId: id } = sessionHost(key);
|
|
@@ -8578,7 +9441,7 @@ function registerClaudeImportChannels({ ipc }) {
|
|
|
8578
9441
|
);
|
|
8579
9442
|
ipc.handle(
|
|
8580
9443
|
"claudeImport:run",
|
|
8581
|
-
(_e, cwd, opts) =>
|
|
9444
|
+
(_e, cwd, opts) => hostRequest("claudeImport.run", {
|
|
8582
9445
|
cwd: scopeCwd(cwd ?? ""),
|
|
8583
9446
|
sessions: opts.sessions,
|
|
8584
9447
|
mcps: opts.mcps,
|
|
@@ -8886,17 +9749,19 @@ function isAlive(pid) {
|
|
|
8886
9749
|
async function restartDaemon(force) {
|
|
8887
9750
|
const info = getDaemonConnectionInfo();
|
|
8888
9751
|
const pid = info.daemon?.pid;
|
|
9752
|
+
const pids = [.../* @__PURE__ */ new Set([...pid !== void 0 ? [pid] : [], ...olderDaemonPids()])];
|
|
8889
9753
|
const reply = await requestShutdown(info.socketPath, !force);
|
|
8890
|
-
guiLog.info("daemon restart requested", { scope: "daemon", force, pid, reply });
|
|
9754
|
+
guiLog.info("daemon restart requested", { scope: "daemon", force, pid, pids, reply });
|
|
8891
9755
|
if (reply?.deferred) {
|
|
8892
9756
|
return { deferred: true };
|
|
8893
9757
|
}
|
|
8894
|
-
if (force &&
|
|
9758
|
+
if (force && pids.length > 0) {
|
|
8895
9759
|
await new Promise((resolve2) => setTimeout(resolve2, FORCE_KILL_AFTER_MS));
|
|
8896
|
-
|
|
8897
|
-
|
|
9760
|
+
for (const target of pids) {
|
|
9761
|
+
if (!isAlive(target)) continue;
|
|
9762
|
+
guiLog.warn("daemon still running after shutdown, terminating it", { scope: "daemon", pid: target });
|
|
8898
9763
|
try {
|
|
8899
|
-
process.kill(
|
|
9764
|
+
process.kill(target, "SIGTERM");
|
|
8900
9765
|
} catch {
|
|
8901
9766
|
}
|
|
8902
9767
|
}
|
|
@@ -8932,6 +9797,7 @@ function registerDaemonControlIpc() {
|
|
|
8932
9797
|
}
|
|
8933
9798
|
function registerDaemonChannels({ ipc }) {
|
|
8934
9799
|
ipc.handle("daemon:health", () => getDaemonHealth());
|
|
9800
|
+
ipc.handle("daemon:current", () => getDaemonState());
|
|
8935
9801
|
registerDaemonControlIpc();
|
|
8936
9802
|
}
|
|
8937
9803
|
function registerDiscoveryChannels({ ipc }) {
|
|
@@ -9450,6 +10316,13 @@ function storedToolResults() {
|
|
|
9450
10316
|
function closeStoredToolResults() {
|
|
9451
10317
|
shared?.close();
|
|
9452
10318
|
}
|
|
10319
|
+
function positioned(page) {
|
|
10320
|
+
return page.pos !== void 0 ? {
|
|
10321
|
+
pos: page.pos,
|
|
10322
|
+
floor: page.floor ?? page.pos,
|
|
10323
|
+
...page.historyId !== void 0 ? { historyId: page.historyId } : {}
|
|
10324
|
+
} : {};
|
|
10325
|
+
}
|
|
9453
10326
|
function registerHistoryChannels({ ipc, serverPageTurns }) {
|
|
9454
10327
|
const pager = createLocalHistoryPager({
|
|
9455
10328
|
source: {
|
|
@@ -9479,7 +10352,8 @@ function registerHistoryChannels({ ipc, serverPageTurns }) {
|
|
|
9479
10352
|
return {
|
|
9480
10353
|
events: attachAttachmentsToUserPrompts(events, page.imagePrompts, key),
|
|
9481
10354
|
firstSeq: page.cursor ?? 0,
|
|
9482
|
-
hasMore: page.cursor !== void 0 && page.cursor > 0
|
|
10355
|
+
hasMore: page.cursor !== void 0 && page.cursor > 0,
|
|
10356
|
+
...positioned(page)
|
|
9483
10357
|
};
|
|
9484
10358
|
};
|
|
9485
10359
|
const loadServerEvents = async (key, before) => {
|
|
@@ -9504,7 +10378,8 @@ function registerHistoryChannels({ ipc, serverPageTurns }) {
|
|
|
9504
10378
|
// Its running calls' starts too: whether it runs is the server's to say, so the page's open calls decide.
|
|
9505
10379
|
events: clipToolResultEvents(await withRunningStarts(key, before, page.events)),
|
|
9506
10380
|
firstSeq: page.cursor ?? 0,
|
|
9507
|
-
hasMore: page.cursor !== void 0 && page.cursor > 0
|
|
10381
|
+
hasMore: page.cursor !== void 0 && page.cursor > 0,
|
|
10382
|
+
...positioned(page)
|
|
9508
10383
|
};
|
|
9509
10384
|
};
|
|
9510
10385
|
ipc.handle("sessions:loadEvents", async (_e, id, opts) => {
|
|
@@ -9517,6 +10392,19 @@ function registerHistoryChannels({ ipc, serverPageTurns }) {
|
|
|
9517
10392
|
const before = Math.floor(beforeSeq);
|
|
9518
10393
|
return sessionHost(id).host.remote ? loadServerEvents(id, before) : loadEventsPage$1(id, before);
|
|
9519
10394
|
});
|
|
10395
|
+
ipc.handle("sessions:historySince", async (_e, key, afterPos, historyId) => {
|
|
10396
|
+
if (typeof afterPos !== "number" || !Number.isSafeInteger(afterPos) || afterPos < 0) return null;
|
|
10397
|
+
if (typeof historyId !== "string" || historyId.length === 0) return null;
|
|
10398
|
+
const since = await sessionRequest("sessions.historySince", key, { afterPos, historyId });
|
|
10399
|
+
if (!since?.ok) return null;
|
|
10400
|
+
return {
|
|
10401
|
+
events: clipToolResultEvents(since.events),
|
|
10402
|
+
pos: since.pos,
|
|
10403
|
+
floor: since.floor,
|
|
10404
|
+
historyId: since.historyId,
|
|
10405
|
+
...since.after !== void 0 ? { after: since.after } : {}
|
|
10406
|
+
};
|
|
10407
|
+
});
|
|
9520
10408
|
ipc.handle(
|
|
9521
10409
|
"sessions:toolResultText",
|
|
9522
10410
|
async (_e, key, callId, turnId) => {
|
|
@@ -9603,7 +10491,7 @@ function serverOf(hostId2) {
|
|
|
9603
10491
|
if (!host2.remote) throw new Error("This computer is managed in its own settings.");
|
|
9604
10492
|
return host2;
|
|
9605
10493
|
}
|
|
9606
|
-
function text(value, what) {
|
|
10494
|
+
function text$1(value, what) {
|
|
9607
10495
|
if (typeof value !== "string" || !value.trim() || value.length > MAX_ARG) throw new Error(`${what} is required.`);
|
|
9608
10496
|
return value.trim();
|
|
9609
10497
|
}
|
|
@@ -9639,10 +10527,10 @@ function kindOf(value) {
|
|
|
9639
10527
|
}
|
|
9640
10528
|
function targetOf(value) {
|
|
9641
10529
|
const target = value ?? {};
|
|
9642
|
-
if (typeof target.provider === "string") return { provider: text(target.provider, "A provider") };
|
|
10530
|
+
if (typeof target.provider === "string") return { provider: text$1(target.provider, "A provider") };
|
|
9643
10531
|
if (typeof target.mcpServer === "string")
|
|
9644
10532
|
return {
|
|
9645
|
-
mcpServer: text(target.mcpServer, "An MCP server"),
|
|
10533
|
+
mcpServer: text$1(target.mcpServer, "An MCP server"),
|
|
9646
10534
|
...typeof target.cwd === "string" && target.cwd ? { cwd: target.cwd } : {}
|
|
9647
10535
|
};
|
|
9648
10536
|
throw new Error("Sign in to a provider or an MCP server.");
|
|
@@ -9660,14 +10548,14 @@ function registerHostActionChannels({ ipc }) {
|
|
|
9660
10548
|
"hosts:oauth",
|
|
9661
10549
|
async (_e, hostId2, target, flowKey) => {
|
|
9662
10550
|
const host2 = serverOf(hostId2);
|
|
9663
|
-
return flows.run({ request: host2.call }, targetOf(target), text(flowKey, "A flow key"));
|
|
10551
|
+
return flows.run({ request: host2.call }, targetOf(target), text$1(flowKey, "A flow key"));
|
|
9664
10552
|
}
|
|
9665
10553
|
);
|
|
9666
10554
|
ipc.handle(
|
|
9667
10555
|
"hosts:oauthPaste",
|
|
9668
|
-
(_e, flowKey, input) => flows.paste(text(flowKey, "A flow key"), typeof input === "string" ? input.slice(0, 8192) : "")
|
|
10556
|
+
(_e, flowKey, input) => flows.paste(text$1(flowKey, "A flow key"), typeof input === "string" ? input.slice(0, 8192) : "")
|
|
9669
10557
|
);
|
|
9670
|
-
ipc.handle("hosts:oauthCancel", (_e, flowKey) => flows.cancel(text(flowKey, "A flow key")));
|
|
10558
|
+
ipc.handle("hosts:oauthCancel", (_e, flowKey) => flows.cancel(text$1(flowKey, "A flow key")));
|
|
9671
10559
|
ipc.handle("hosts:methods", (_e, hostId2) => {
|
|
9672
10560
|
const methods = serverOf(hostId2).server.client?.hello.methods;
|
|
9673
10561
|
return methods ? [...methods] : null;
|
|
@@ -9680,24 +10568,24 @@ function registerHostActionChannels({ ipc }) {
|
|
|
9680
10568
|
"hosts:install",
|
|
9681
10569
|
async (_e, hostId2, kind, spec, options) => serverOf(hostId2).call("catalog.install", {
|
|
9682
10570
|
kind: kindOf(kind),
|
|
9683
|
-
spec: text(spec, "A source"),
|
|
10571
|
+
spec: text$1(spec, "A source"),
|
|
9684
10572
|
...Array.isArray(options?.skills) ? { skills: options.skills.filter((s) => typeof s === "string") } : {},
|
|
9685
10573
|
...options?.all === true ? { all: true } : {},
|
|
9686
10574
|
...options?.overwrite === true ? { overwrite: true } : {},
|
|
9687
|
-
...typeof options?.extension === "string" && options.extension ? { extension: text(options.extension, "An extension") } : {}
|
|
10575
|
+
...typeof options?.extension === "string" && options.extension ? { extension: text$1(options.extension, "An extension") } : {}
|
|
9688
10576
|
})
|
|
9689
10577
|
);
|
|
9690
10578
|
ipc.handle(
|
|
9691
10579
|
"hosts:browseExtensions",
|
|
9692
10580
|
async (_e, hostId2, input) => current(
|
|
9693
|
-
serverOf(hostId2).call("extensions.browse", { source: text(input, "A source") }),
|
|
10581
|
+
serverOf(hostId2).call("extensions.browse", { source: text$1(input, "A source") }),
|
|
9694
10582
|
"browse extension sources"
|
|
9695
10583
|
)
|
|
9696
10584
|
);
|
|
9697
10585
|
ipc.handle(
|
|
9698
10586
|
"hosts:changeExtensionOrigin",
|
|
9699
10587
|
async (_e, hostId2, name, source) => {
|
|
9700
|
-
const params = { name: text(name, "A name"), scope: "user", source: text(source, "A source") };
|
|
10588
|
+
const params = { name: text$1(name, "A name"), scope: "user", source: text$1(source, "A source") };
|
|
9701
10589
|
try {
|
|
9702
10590
|
const { message: message2 } = await current(
|
|
9703
10591
|
serverOf(hostId2).call("extensions.changeOrigin", params),
|
|
@@ -9713,11 +10601,11 @@ function registerHostActionChannels({ ipc }) {
|
|
|
9713
10601
|
);
|
|
9714
10602
|
ipc.handle(
|
|
9715
10603
|
"hosts:uninstall",
|
|
9716
|
-
async (_e, hostId2, kind, name) => serverOf(hostId2).call("catalog.remove", { kind: kindOf(kind), name: text(name, "A name") })
|
|
10604
|
+
async (_e, hostId2, kind, name) => serverOf(hostId2).call("catalog.remove", { kind: kindOf(kind), name: text$1(name, "A name") })
|
|
9717
10605
|
);
|
|
9718
10606
|
ipc.handle(
|
|
9719
10607
|
"hosts:update",
|
|
9720
|
-
async (_e, hostId2, kind, name) => serverOf(hostId2).call("catalog.update", { kind: kindOf(kind), name: text(name, "A name") })
|
|
10608
|
+
async (_e, hostId2, kind, name) => serverOf(hostId2).call("catalog.update", { kind: kindOf(kind), name: text$1(name, "A name") })
|
|
9721
10609
|
);
|
|
9722
10610
|
ipc.handle("hosts:mcpUpsert", async (_e, hostId2, config2, options) => {
|
|
9723
10611
|
if (typeof config2 !== "object" || config2 === null) throw new Error("An MCP server is required.");
|
|
@@ -9726,17 +10614,17 @@ function registerHostActionChannels({ ipc }) {
|
|
|
9726
10614
|
});
|
|
9727
10615
|
ipc.handle(
|
|
9728
10616
|
"hosts:mcpRemove",
|
|
9729
|
-
async (_e, hostId2, name) => serverOf(hostId2).call("mcp.remove", { name: text(name, "A name") })
|
|
10617
|
+
async (_e, hostId2, name) => serverOf(hostId2).call("mcp.remove", { name: text$1(name, "A name") })
|
|
9730
10618
|
);
|
|
9731
10619
|
ipc.handle("hosts:mcpTest", async (_e, hostId2, name, cwd) => {
|
|
9732
10620
|
const folder = folderOf(cwd);
|
|
9733
10621
|
return current(
|
|
9734
|
-
serverOf(hostId2).call("mcp.test", { name: text(name, "A name"), ...folder ? { cwd: folder } : {} }),
|
|
10622
|
+
serverOf(hostId2).call("mcp.test", { name: text$1(name, "A name"), ...folder ? { cwd: folder } : {} }),
|
|
9735
10623
|
"test MCP servers"
|
|
9736
10624
|
);
|
|
9737
10625
|
});
|
|
9738
10626
|
ipc.handle("hosts:mcpSignOut", async (_e, hostId2, name) => {
|
|
9739
|
-
await current(serverOf(hostId2).call("mcp.signOut", { name: text(name, "A name") }), "sign out of MCP servers");
|
|
10627
|
+
await current(serverOf(hostId2).call("mcp.signOut", { name: text$1(name, "A name") }), "sign out of MCP servers");
|
|
9740
10628
|
});
|
|
9741
10629
|
ipc.handle("hosts:mcpInstances", async (_e, hostId2, cwd) => {
|
|
9742
10630
|
const folder = folderOf(cwd);
|
|
@@ -9750,7 +10638,7 @@ function registerHostActionChannels({ ipc }) {
|
|
|
9750
10638
|
ipc.handle("hosts:mcpRestart", async (_e, hostId2, name, cwd) => {
|
|
9751
10639
|
const folder = folderOf(cwd);
|
|
9752
10640
|
const { restarted } = await current(
|
|
9753
|
-
serverOf(hostId2).call("mcp.restart", { name: text(name, "A name"), ...folder ? { cwd: folder } : {} }),
|
|
10641
|
+
serverOf(hostId2).call("mcp.restart", { name: text$1(name, "A name"), ...folder ? { cwd: folder } : {} }),
|
|
9754
10642
|
"restart MCP servers"
|
|
9755
10643
|
);
|
|
9756
10644
|
return restarted;
|
|
@@ -9781,9 +10669,6 @@ function summarize(server, entry) {
|
|
|
9781
10669
|
...server.serverName ? { serverName: server.serverName } : {},
|
|
9782
10670
|
...server.serverVersion ? { serverVersion: server.serverVersion } : {},
|
|
9783
10671
|
...server.client?.hello.machineServe ? { machineServe: true } : {},
|
|
9784
|
-
// An older server's `approve` scope reads as chat: it can't change the server's settings either.
|
|
9785
|
-
...server.client?.hello.scope ? { scope: server.client.hello.scope === "admin" ? "admin" : "chat" } : {},
|
|
9786
|
-
...server.client?.hello.adminCommands ? { adminCommands: server.client.hello.adminCommands } : {},
|
|
9787
10672
|
...server.client?.hello.homeDir ? { home: server.client.hello.homeDir } : {},
|
|
9788
10673
|
...entry?.addedAt ? { addedAt: entry.addedAt } : {},
|
|
9789
10674
|
...entry?.lastConnectedAt ? { lastConnectedAt: entry.lastConnectedAt } : {}
|
|
@@ -9848,14 +10733,6 @@ function requiredText(value, max, what) {
|
|
|
9848
10733
|
}
|
|
9849
10734
|
function folderAllows(hello) {
|
|
9850
10735
|
const methods = hello?.methods;
|
|
9851
|
-
const reaches = (method) => !methods || methods.includes(method);
|
|
9852
|
-
if (hello?.clone !== void 0 || hello?.createFolders !== void 0) {
|
|
9853
|
-
return {
|
|
9854
|
-
createFolders: hello.createFolders === true && reaches("fs.mkdir"),
|
|
9855
|
-
clone: hello.clone === true && reaches("git.clone"),
|
|
9856
|
-
searchFolders: reaches("fs.searchDirs")
|
|
9857
|
-
};
|
|
9858
|
-
}
|
|
9859
10736
|
if (!methods) return void 0;
|
|
9860
10737
|
return {
|
|
9861
10738
|
createFolders: methods.includes("fs.mkdir"),
|
|
@@ -10127,9 +11004,7 @@ function registerHostChannels({ ipc }) {
|
|
|
10127
11004
|
allows: {
|
|
10128
11005
|
remoteInstalls: hello?.remoteInstalls === true,
|
|
10129
11006
|
asMachine: hello?.machineServe === true,
|
|
10130
|
-
sync: hello?.sync === true
|
|
10131
|
-
clone: hello?.clone === true,
|
|
10132
|
-
createFolders: hello?.createFolders === true
|
|
11007
|
+
sync: hello?.sync === true
|
|
10133
11008
|
},
|
|
10134
11009
|
workspace: { roots: [] },
|
|
10135
11010
|
probedAt: Date.now(),
|
|
@@ -10137,6 +11012,15 @@ function registerHostChannels({ ipc }) {
|
|
|
10137
11012
|
};
|
|
10138
11013
|
}
|
|
10139
11014
|
});
|
|
11015
|
+
ipc.handle("hosts:tokensList", async (_e, hostId2) => remoteOnly(hostId2).call("tokens.list", {}));
|
|
11016
|
+
ipc.handle(
|
|
11017
|
+
"hosts:tokenCreate",
|
|
11018
|
+
async (_e, hostId2, name) => remoteOnly(hostId2).call("tokens.create", { name: requiredText(name, 100, "A name") })
|
|
11019
|
+
);
|
|
11020
|
+
ipc.handle("hosts:tokenRevoke", async (_e, hostId2, id) => {
|
|
11021
|
+
await remoteOnly(hostId2).call("tokens.revoke", { id: requiredText(id, 100, "A token id") });
|
|
11022
|
+
});
|
|
11023
|
+
ipc.handle("hosts:pairBrowser", async (_e, hostId2) => remoteOnly(hostId2).call("tokens.pair", {}));
|
|
10140
11024
|
ipc.handle("hosts:installTool", async (_e, hostId2, name) => {
|
|
10141
11025
|
if (typeof name !== "string" || !name || name.length > 64) throw new Error("A tool name is required.");
|
|
10142
11026
|
return remoteOnly(hostId2).call("host.installTool", { name });
|
|
@@ -10234,14 +11118,32 @@ async function shareStart(hostId2, name, roots, token) {
|
|
|
10234
11118
|
}
|
|
10235
11119
|
const server = hostFor({ hostId: hostId2 });
|
|
10236
11120
|
if (!server.remote) throw new Error("Share this computer with a saved server.");
|
|
10237
|
-
const minted = await server.call("tokens.createMachineToken", { name }).
|
|
10238
|
-
|
|
11121
|
+
const minted = await server.call("tokens.createMachineToken", { name }).then(
|
|
11122
|
+
(made2) => made2.token,
|
|
11123
|
+
(err) => err
|
|
11124
|
+
);
|
|
11125
|
+
const made = typeof minted === "string" ? minted : await joinWithCode(server, name).catch((err) => err);
|
|
11126
|
+
if (typeof made !== "string")
|
|
10239
11127
|
return {
|
|
10240
11128
|
ok: false,
|
|
10241
11129
|
needsToken: true,
|
|
10242
|
-
message: `${server.name}
|
|
11130
|
+
message: `${server.name} did not create a machine token: ${message(minted)} Paste one from \`zidane server token create --name ${name} --machine\`.`
|
|
10243
11131
|
};
|
|
10244
|
-
return { ok: true, links: await hostRequest("machines.share.start", { hostId: hostId2, name, roots, token:
|
|
11132
|
+
return { ok: true, links: await hostRequest("machines.share.start", { hostId: hostId2, name, roots, token: made }) };
|
|
11133
|
+
}
|
|
11134
|
+
async function joinWithCode(server, name) {
|
|
11135
|
+
const { code } = await server.call("tokens.machineInvite", { name });
|
|
11136
|
+
const { joinPairUrl } = await import("zidane/ipc/browser");
|
|
11137
|
+
const response = await fetch(joinPairUrl(server.server.url), {
|
|
11138
|
+
method: "POST",
|
|
11139
|
+
headers: { "content-type": "application/json" },
|
|
11140
|
+
body: JSON.stringify({ code, name }),
|
|
11141
|
+
signal: AbortSignal.timeout(3e4)
|
|
11142
|
+
});
|
|
11143
|
+
const body = await response.json().catch(() => ({}));
|
|
11144
|
+
if (!response.ok || typeof body.token !== "string")
|
|
11145
|
+
throw new Error(`The join code was refused (${typeof body.error === "string" ? body.error : response.status}).`);
|
|
11146
|
+
return body.token;
|
|
10245
11147
|
}
|
|
10246
11148
|
async function invite(hostId2, name) {
|
|
10247
11149
|
await requireRemoteHosts();
|
|
@@ -10250,10 +11152,10 @@ async function invite(hostId2, name) {
|
|
|
10250
11152
|
try {
|
|
10251
11153
|
const { code, expiresAt } = await server.call("tokens.machineInvite", name ? { name } : {});
|
|
10252
11154
|
const { formatJoinString } = await import("zidane/ipc/browser");
|
|
10253
|
-
|
|
11155
|
+
const address = server.server.client?.hello?.clientUrl ?? server.server.url;
|
|
11156
|
+
return { ok: true, invite: { code, expiresAt, join: formatJoinString(address, code) } };
|
|
10254
11157
|
} catch (err) {
|
|
10255
|
-
|
|
10256
|
-
return { ok: false, message: message(err), ...forbidden ? { forbidden } : {} };
|
|
11158
|
+
return { ok: false, message: message(err) };
|
|
10257
11159
|
}
|
|
10258
11160
|
}
|
|
10259
11161
|
async function answer(task, token) {
|
|
@@ -10418,9 +11320,9 @@ function registerInvalidationChannels({ ipc }) {
|
|
|
10418
11320
|
function registerKeybindingChannels({ ipc }) {
|
|
10419
11321
|
ipc.handle("keybindings:load", () => loadKeybindings());
|
|
10420
11322
|
ipc.handle("keybindings:save", (_e, map) => {
|
|
10421
|
-
const
|
|
11323
|
+
const saved2 = saveKeybindings(map);
|
|
10422
11324
|
desktopExtensionsHost()?.keybindingsChanged();
|
|
10423
|
-
return
|
|
11325
|
+
return saved2;
|
|
10424
11326
|
});
|
|
10425
11327
|
ipc.handle("keybindings:path", () => keybindingsFilePath());
|
|
10426
11328
|
ipc.handle("keybindings:openInEditor", () => openKeybindingsInEditor());
|
|
@@ -10477,9 +11379,9 @@ function registerLogChannels({ ipc }) {
|
|
|
10477
11379
|
const existing = logSubscribers.get(e.sender.id);
|
|
10478
11380
|
if (existing && --existing.count <= 0) logSubscribers.delete(e.sender.id);
|
|
10479
11381
|
});
|
|
10480
|
-
installLogBroadcast((
|
|
11382
|
+
installLogBroadcast((record2) => {
|
|
10481
11383
|
for (const { contents } of logSubscribers.values()) {
|
|
10482
|
-
if (!contents.isDestroyed()) contents.send("logs:record",
|
|
11384
|
+
if (!contents.isDestroyed()) contents.send("logs:record", record2);
|
|
10483
11385
|
}
|
|
10484
11386
|
});
|
|
10485
11387
|
}
|
|
@@ -11065,12 +11967,14 @@ function registerQueueChannels({ ipc }) {
|
|
|
11065
11967
|
ipc.handle("queue:list", (_e, sessionId) => sessionRequest("queue.list", sessionId, {}));
|
|
11066
11968
|
ipc.handle(
|
|
11067
11969
|
"queue:add",
|
|
11068
|
-
(_e, sessionId, text2, activatedSkills, attachments, delivery) => sessionRequest("queue.add", sessionId, {
|
|
11970
|
+
(_e, sessionId, text2, activatedSkills, attachments, delivery, clientMessageId) => sessionRequest("queue.add", sessionId, {
|
|
11069
11971
|
text: text2,
|
|
11070
11972
|
requestId: randomUUID(),
|
|
11071
11973
|
...activatedSkills ? { activatedSkills } : {},
|
|
11072
11974
|
...attachments ? { attachments } : {},
|
|
11073
|
-
...delivery ? { delivery } : {}
|
|
11975
|
+
...delivery ? { delivery } : {},
|
|
11976
|
+
// Kept with the entry until it runs: its echo carries it, so a window binds its row by id.
|
|
11977
|
+
...typeof clientMessageId === "string" && clientMessageId.length > 0 ? { clientMessageId: clientMessageId.slice(0, 128) } : {}
|
|
11074
11978
|
})
|
|
11075
11979
|
);
|
|
11076
11980
|
ipc.handle(
|
|
@@ -11478,7 +12382,8 @@ function startShellRun(opts) {
|
|
|
11478
12382
|
text: typeof text2 === "function" ? text2() : text2,
|
|
11479
12383
|
tool: "shell",
|
|
11480
12384
|
callId,
|
|
11481
|
-
|
|
12385
|
+
// The call's turn, as the replay tags a result (`eventsFromTurns`).
|
|
12386
|
+
turnId: callTurnId,
|
|
11482
12387
|
streaming: !force
|
|
11483
12388
|
});
|
|
11484
12389
|
};
|
|
@@ -11629,7 +12534,7 @@ function onClient(client2, sessionId, request2, options) {
|
|
|
11629
12534
|
options
|
|
11630
12535
|
);
|
|
11631
12536
|
}
|
|
11632
|
-
function runOnHost(key, request2, options) {
|
|
12537
|
+
async function runOnHost(key, request2, options) {
|
|
11633
12538
|
const { host: host2, sessionId } = sessionHost(key);
|
|
11634
12539
|
if (host2.remote) {
|
|
11635
12540
|
const client2 = host2.server.client;
|
|
@@ -11638,6 +12543,11 @@ function runOnHost(key, request2, options) {
|
|
|
11638
12543
|
}
|
|
11639
12544
|
const daemon2 = getDaemonClient();
|
|
11640
12545
|
if (daemon2) return onClient(daemon2, sessionId, request2, options);
|
|
12546
|
+
const held = untilOlderDaemonGone("sessions.runBlock");
|
|
12547
|
+
if (held) {
|
|
12548
|
+
await held;
|
|
12549
|
+
return runOnHost(key, request2, options);
|
|
12550
|
+
}
|
|
11641
12551
|
return getChatHost().runBlock(sessionId, request2, options);
|
|
11642
12552
|
}
|
|
11643
12553
|
function registerBlockRunChannels({ ipc }) {
|
|
@@ -11897,12 +12807,12 @@ function registerPlanChannels({ ipc }) {
|
|
|
11897
12807
|
);
|
|
11898
12808
|
}
|
|
11899
12809
|
const GITHUB_PROBE_MS = 2 * 6e4;
|
|
11900
|
-
function createGithubUsageRead(
|
|
12810
|
+
function createGithubUsageRead(fetch2 = fetchGithubUsage, now = Date.now) {
|
|
11901
12811
|
let lastProbe = -Infinity;
|
|
11902
12812
|
return (opts) => {
|
|
11903
12813
|
const probe2 = opts?.probe === true && now() - lastProbe >= GITHUB_PROBE_MS;
|
|
11904
12814
|
if (probe2) lastProbe = now();
|
|
11905
|
-
return
|
|
12815
|
+
return fetch2({ probe: probe2 }).catch(() => []);
|
|
11906
12816
|
};
|
|
11907
12817
|
}
|
|
11908
12818
|
function registerUsageChannels({ ipc }) {
|
|
@@ -12826,9 +13736,7 @@ function createRemoteBackend(options) {
|
|
|
12826
13736
|
...value !== void 0 ? { value } : {}
|
|
12827
13737
|
}),
|
|
12828
13738
|
settings: async (cwd, sessionId) => {
|
|
12829
|
-
|
|
12830
|
-
const scope = options.clientScope?.();
|
|
12831
|
-
return scope ? { ...wire, clientScope: scope } : wire;
|
|
13739
|
+
return call("extensions.settings", { cwd, ...sessionId ? { sessionId } : {} });
|
|
12832
13740
|
},
|
|
12833
13741
|
settingsSet: (params) => call("extensions.settings.set", params),
|
|
12834
13742
|
commands: (cwd, sessionId) => call("extensions.commands", { cwd, ...sessionId ? { sessionId } : {} }),
|
|
@@ -13847,8 +14755,8 @@ function createWindowClientDirectory(options = {}) {
|
|
|
13847
14755
|
dialogs: r.dialogs
|
|
13848
14756
|
}));
|
|
13849
14757
|
const ask = (windowId, request2, coerce, fallback) => {
|
|
13850
|
-
const
|
|
13851
|
-
if (!
|
|
14758
|
+
const record2 = records.get(windowId);
|
|
14759
|
+
if (!record2 || !record2.ui) return Promise.resolve(fallback);
|
|
13852
14760
|
const requestId = `r${++seq}`;
|
|
13853
14761
|
return new Promise((resolve2) => {
|
|
13854
14762
|
const timer = setTimeout(() => {
|
|
@@ -13864,15 +14772,15 @@ function createWindowClientDirectory(options = {}) {
|
|
|
13864
14772
|
resolve2(coerce(raw) ?? fallback);
|
|
13865
14773
|
}
|
|
13866
14774
|
});
|
|
13867
|
-
|
|
14775
|
+
record2.link.send({ kind: "ui:client", requestId, request: request2 });
|
|
13868
14776
|
});
|
|
13869
14777
|
};
|
|
13870
14778
|
const asBoolean = (raw) => typeof raw === "boolean" ? raw : void 0;
|
|
13871
14779
|
const dialogPort = {
|
|
13872
14780
|
clients: clientList,
|
|
13873
14781
|
show: (clientId, request2, ctx) => {
|
|
13874
|
-
const
|
|
13875
|
-
if (!
|
|
14782
|
+
const record2 = records.get(clientId);
|
|
14783
|
+
if (!record2) return Promise.reject(new NoUiError(request2.kind));
|
|
13876
14784
|
const dialogId = `d${++seq}`;
|
|
13877
14785
|
return new Promise((resolve2, reject) => {
|
|
13878
14786
|
const onAbort = () => {
|
|
@@ -13893,7 +14801,7 @@ function createWindowClientDirectory(options = {}) {
|
|
|
13893
14801
|
...ctx.validate ? { validate: ctx.validate } : {}
|
|
13894
14802
|
});
|
|
13895
14803
|
ctx.signal.addEventListener("abort", onAbort, { once: true });
|
|
13896
|
-
|
|
14804
|
+
record2.link.send({
|
|
13897
14805
|
kind: "ui:dialog",
|
|
13898
14806
|
dialogId,
|
|
13899
14807
|
extensionId: ctx.extensionId,
|
|
@@ -13921,23 +14829,23 @@ function createWindowClientDirectory(options = {}) {
|
|
|
13921
14829
|
// The window presses the chord in its view (`mod` resolved there) and answers whether a binding took it.
|
|
13922
14830
|
keymapDispatch: (clientId, request2) => ask(clientId, { op: "keymap.dispatch", ...request2 }, asBoolean, false),
|
|
13923
14831
|
notify: (clientId, notification) => {
|
|
13924
|
-
const
|
|
13925
|
-
if (
|
|
14832
|
+
const record2 = records.get(clientId);
|
|
14833
|
+
if (record2?.ui) record2.link.send({ kind: "ui:client", request: { op: "notify", ...notification } });
|
|
13926
14834
|
}
|
|
13927
14835
|
};
|
|
13928
14836
|
return {
|
|
13929
14837
|
announce(link, info) {
|
|
13930
|
-
let
|
|
13931
|
-
if (!
|
|
13932
|
-
|
|
13933
|
-
records.set(link.id,
|
|
14838
|
+
let record2 = records.get(link.id);
|
|
14839
|
+
if (!record2) {
|
|
14840
|
+
record2 = { link, viewing: [], lastActiveAt: stamp2(), dialogs: true, ui: true };
|
|
14841
|
+
records.set(link.id, record2);
|
|
13934
14842
|
}
|
|
13935
|
-
|
|
14843
|
+
record2.link = link;
|
|
13936
14844
|
const viewing2 = stringList(info.viewing);
|
|
13937
|
-
if (viewing2)
|
|
13938
|
-
if (info.active === true)
|
|
13939
|
-
if (typeof info.dialogs === "boolean")
|
|
13940
|
-
if (typeof info.ui === "boolean")
|
|
14845
|
+
if (viewing2) record2.viewing = viewing2;
|
|
14846
|
+
if (info.active === true) record2.lastActiveAt = stamp2();
|
|
14847
|
+
if (typeof info.dialogs === "boolean") record2.dialogs = info.dialogs;
|
|
14848
|
+
if (typeof info.ui === "boolean") record2.ui = info.ui;
|
|
13941
14849
|
},
|
|
13942
14850
|
remove(windowId) {
|
|
13943
14851
|
if (!records.delete(windowId)) return;
|
|
@@ -14345,10 +15253,10 @@ function handleExtensionWebviewProtocol() {
|
|
|
14345
15253
|
const host2 = desktopExtensionsHost();
|
|
14346
15254
|
if (host2?.daemonServes()) return daemonBackend?.webviewSource(cwd, extensionId);
|
|
14347
15255
|
const runtime = host2?.runtimeFor(cwd)?.runtime;
|
|
14348
|
-
const
|
|
14349
|
-
if (!runtime || !
|
|
15256
|
+
const record2 = runtime?.get(extensionId);
|
|
15257
|
+
if (!runtime || !record2?.entry.dir || record2.info.status !== "active") return void 0;
|
|
14350
15258
|
const files = runtime.outputs.ui.snapshot().webview.filter((entry) => entry.extension === extensionId).flatMap((entry) => "file" in entry.item.src ? [entry.item.src.file] : []);
|
|
14351
|
-
return { dir:
|
|
15259
|
+
return { dir: record2.entry.dir, files };
|
|
14352
15260
|
})
|
|
14353
15261
|
);
|
|
14354
15262
|
}
|
|
@@ -14449,8 +15357,6 @@ function installExtensions({
|
|
|
14449
15357
|
if (!controller2) throw new Error("Remote hosts are off.");
|
|
14450
15358
|
return controller2.fetchExtensionBundle(hostId2, url);
|
|
14451
15359
|
},
|
|
14452
|
-
// The token's scope: Settings disables the action buttons above it.
|
|
14453
|
-
clientScope: () => getHostDirectory().server(hostId2)?.client?.hello.scope,
|
|
14454
15360
|
mintWebview: async (cwd, webviewId) => {
|
|
14455
15361
|
const controller2 = remoteHosts();
|
|
14456
15362
|
return controller2 ? controller2.mintExtensionWebview(hostId2, cwd, webviewId) : null;
|
|
@@ -14609,8 +15515,8 @@ function isDir(path) {
|
|
|
14609
15515
|
}
|
|
14610
15516
|
}
|
|
14611
15517
|
function defaultParent() {
|
|
14612
|
-
const
|
|
14613
|
-
if (
|
|
15518
|
+
const saved2 = settingsRepo.get(PARENT_KEY);
|
|
15519
|
+
if (saved2 && isDir(saved2)) return saved2;
|
|
14614
15520
|
const last = settingsRepo.get(LAST_FOLDER_KEY);
|
|
14615
15521
|
if (last && isDir(dirname(last)) && dirname(last) !== last) return dirname(last);
|
|
14616
15522
|
const code = join(homedir(), "Code");
|
|
@@ -15179,6 +16085,9 @@ function probe(host2, port) {
|
|
|
15179
16085
|
});
|
|
15180
16086
|
}
|
|
15181
16087
|
const cwdOf = (value) => typeof value === "string" ? value : "";
|
|
16088
|
+
const text = (value, max) => typeof value === "string" && value.length <= max ? value : null;
|
|
16089
|
+
const URL_MAX = 8192;
|
|
16090
|
+
const TITLE_MAX = 1024;
|
|
15182
16091
|
function registerBrowserIpc() {
|
|
15183
16092
|
ipcMain.removeHandler("browser:config");
|
|
15184
16093
|
ipcMain.handle("browser:config", (event, cwd) => {
|
|
@@ -15217,11 +16126,47 @@ function registerBrowserIpc() {
|
|
|
15217
16126
|
"browser:captureAnnotated",
|
|
15218
16127
|
(event, sessionId) => fromAppWindow(event) && typeof sessionId === "string" ? captureAnnotatedBrowserPage(sessionId) : null
|
|
15219
16128
|
);
|
|
15220
|
-
ipcMain.removeHandler("browser:
|
|
15221
|
-
ipcMain.handle(
|
|
15222
|
-
"browser:
|
|
15223
|
-
|
|
15224
|
-
|
|
16129
|
+
ipcMain.removeHandler("browser:state");
|
|
16130
|
+
ipcMain.handle("browser:state", (event, legacy) => {
|
|
16131
|
+
if (!fromAppWindow(event)) throw new Error("browser:state is only available to the app window");
|
|
16132
|
+
if (legacy && typeof legacy === "object") browserState().importLegacy(legacy);
|
|
16133
|
+
return browserState().snapshot();
|
|
16134
|
+
});
|
|
16135
|
+
ipcMain.removeHandler("browser:setEmulation");
|
|
16136
|
+
ipcMain.handle("browser:setEmulation", (event, sessionId, emulation) => {
|
|
16137
|
+
const e = emulation;
|
|
16138
|
+
const colorScheme = asColorScheme(e?.colorScheme);
|
|
16139
|
+
const device = e?.device === null ? null : asBrowserDevice(e?.device);
|
|
16140
|
+
if (!fromAppWindow(event) || typeof sessionId !== "string" || !colorScheme || device === void 0) return;
|
|
16141
|
+
setBrowserEmulation(sessionId, { colorScheme, device });
|
|
16142
|
+
});
|
|
16143
|
+
ipcMain.removeHandler("browser:slotSize");
|
|
16144
|
+
ipcMain.handle("browser:slotSize", (event, sessionId, size) => {
|
|
16145
|
+
const s = size;
|
|
16146
|
+
const side = (n) => typeof n === "number" && Number.isFinite(n) && n > 0 && n <= 1e5;
|
|
16147
|
+
if (!fromAppWindow(event) || typeof sessionId !== "string" || !side(s?.width) || !side(s?.height)) return;
|
|
16148
|
+
setBrowserSlotSize(sessionId, { width: s.width, height: s.height });
|
|
16149
|
+
});
|
|
16150
|
+
ipcMain.removeHandler("browser:rememberUrl");
|
|
16151
|
+
ipcMain.handle("browser:rememberUrl", (event, sessionId, url) => {
|
|
16152
|
+
const u = text(url, URL_MAX);
|
|
16153
|
+
if (fromAppWindow(event) && typeof sessionId === "string" && u !== null) browserState().rememberUrl(sessionId, u);
|
|
16154
|
+
});
|
|
16155
|
+
ipcMain.removeHandler("browser:visit");
|
|
16156
|
+
ipcMain.handle("browser:visit", (event, project, url, title) => {
|
|
16157
|
+
const [p, u, t] = [text(project, URL_MAX), text(url, URL_MAX), text(title, TITLE_MAX)];
|
|
16158
|
+
if (fromAppWindow(event) && p && u && t !== null) browserState().recordVisit(p, u, t);
|
|
16159
|
+
});
|
|
16160
|
+
ipcMain.removeHandler("browser:retitle");
|
|
16161
|
+
ipcMain.handle("browser:retitle", (event, project, url, title) => {
|
|
16162
|
+
const [p, u, t] = [text(project, URL_MAX), text(url, URL_MAX), text(title, TITLE_MAX)];
|
|
16163
|
+
if (fromAppWindow(event) && p && u && t !== null) browserState().retitle(p, u, t);
|
|
16164
|
+
});
|
|
16165
|
+
ipcMain.removeHandler("browser:removeRecent");
|
|
16166
|
+
ipcMain.handle("browser:removeRecent", (event, project, url) => {
|
|
16167
|
+
const [p, u] = [text(project, URL_MAX), text(url, URL_MAX)];
|
|
16168
|
+
if (fromAppWindow(event) && p && u) browserState().removeRecent(p, u);
|
|
16169
|
+
});
|
|
15225
16170
|
ipcMain.removeHandler("browser:screenshot");
|
|
15226
16171
|
ipcMain.handle(
|
|
15227
16172
|
"browser:screenshot",
|
|
@@ -15238,14 +16183,6 @@ function registerBrowserIpc() {
|
|
|
15238
16183
|
await clearBrowserSiteData(browserPartitionFor(cwdOf(cwd)));
|
|
15239
16184
|
});
|
|
15240
16185
|
}
|
|
15241
|
-
function validEmulation(value) {
|
|
15242
|
-
const e = value;
|
|
15243
|
-
if (!e || typeof e !== "object" || !["system", "light", "dark"].includes(e.colorScheme)) return false;
|
|
15244
|
-
if (e.device === null) return true;
|
|
15245
|
-
const d = e.device;
|
|
15246
|
-
const size = (n) => typeof n === "number" && n >= 1 && n <= 1e4;
|
|
15247
|
-
return typeof d === "object" && size(d.width) && size(d.height) && (d.dpr === null || typeof d.dpr === "number" && d.dpr > 0 && d.dpr <= 8) && typeof d.mobile === "boolean" && (d.userAgent === null || typeof d.userAgent === "string" && d.userAgent.length < 512) && typeof d.scale === "number" && d.scale > 0 && d.scale <= 1;
|
|
15248
|
-
}
|
|
15249
16186
|
function validDevToolsRequest(value) {
|
|
15250
16187
|
const r = value;
|
|
15251
16188
|
if (!r || typeof r !== "object") return false;
|
|
@@ -15750,7 +16687,7 @@ function createCollector({ meter: meter2, renderers: renderers2, askRenderers })
|
|
|
15750
16687
|
previous,
|
|
15751
16688
|
now
|
|
15752
16689
|
});
|
|
15753
|
-
const { busy, lag } = meter2.read();
|
|
16690
|
+
const { busy: busy2, lag } = meter2.read();
|
|
15754
16691
|
const totals = originTotals(processes);
|
|
15755
16692
|
return {
|
|
15756
16693
|
at: now,
|
|
@@ -15763,7 +16700,7 @@ function createCollector({ meter: meter2, renderers: renderers2, askRenderers })
|
|
|
15763
16700
|
label: "Main process event loop",
|
|
15764
16701
|
pid: process.pid,
|
|
15765
16702
|
kind: "main",
|
|
15766
|
-
busy,
|
|
16703
|
+
busy: busy2,
|
|
15767
16704
|
heap: process.memoryUsage().heapUsed
|
|
15768
16705
|
},
|
|
15769
16706
|
...workers,
|