Changesets · Branches · Tags · Compare
| Changeset | 6f33b7b66d9daf319e4c90859c113d60924ae2ad670f1ff9fb63fb5fe12a7428 |
|---|---|
| Author | Nate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-09-21 13:24 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-21 13:24 -07:00 |
| Parents | 21a32b8e3b8e |
9 files changed
added extensions/cli/docs/storage-sync.md +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +# Storage Sync Flow for `cn serve` | |
| 2 | + | |
| 3 | +## Overview | |
| 4 | + | |
| 5 | +The `--id <storageId>` flag enables the `cn serve` command to periodically persist session state to an external Continue-managed storage bucket. On startup, the CLI exchanges the provided `storageId` for two pre-signed S3 URLs - one for `session.json` and one for `diff.txt` - and then pushes fresh copies of those files every 30 seconds. | |
| 6 | + | |
| 7 | +This document captures the responsibilities for both the CLI and backend components so we can iterate on the feature together. | |
| 8 | + | |
| 9 | +## CLI Responsibilities | |
| 10 | + | |
| 11 | +- **Flag plumbing**: When `cn serve` is invoked with `--id <storageId>`, the CLI treats that value as an opaque identifier. | |
| 12 | +- **API key auth**: The CLI attaches the user-level Continue API key (same mechanism we already use for other authenticated requests) to backend calls. | |
| 13 | +- **Presign handshake**: | |
| 14 | + 1. On startup, issue `POST https://api.continue.dev/agents/storage/presigned-url` with JSON payload `{ "storageId": "<storageId>" }`. | |
| 15 | + 2. Expect a response payload containing two pre-signed `PUT` URLs and their target object keys: | |
| 16 | + ```json | |
| 17 | + { | |
| 18 | + "session": { | |
| 19 | + "key": "sessions/<sessionId>/session.json", | |
| 20 | + "putUrl": "https://<s3-host>/..." | |
| 21 | + }, | |
| 22 | + "diff": { | |
| 23 | + "key": "sessions/<sessionId>/diff.txt", | |
| 24 | + "putUrl": "https://<s3-host>/..." | |
| 25 | + } | |
| 26 | + } | |
| 27 | + ``` | |
| 28 | + 3. If the call fails, log and continue without remote storage (no retries yet). | |
| 29 | +- **Periodic uploads**: | |
| 30 | + - Every 30 seconds (configurable later), serialize the in-memory session to `session.json` and fetch the `/diff` payload to produce `diff.txt`. | |
| 31 | + - Upload both artifacts using their respective `PUT` URLs. For now we overwrite the same objects each cycle. | |
| 32 | + - Errors should be logged but non-fatal; the server keeps running. | |
| 33 | + - If the repo check fails (no git repo or missing `main`), `diff.txt` uploads an empty string and we log the condition once for debugging. | |
| 34 | + | |
| 35 | +## Backend Responsibilities | |
| 36 | + | |
| 37 | +- **Endpoint surface**: `POST /agents/storage/presigned-url` accepts a JSON body `{ "storageId": string }`. | |
| 38 | +- **Authentication**: Leverage the caller's Continue API key (the request arrives with the standard `Authorization: Bearer <apiKey>` header). Apply normal auth/tenant validation so users can only request URLs tied to their account/org. | |
| 39 | +- **URL issuance**: | |
| 40 | + - Resolve `storageId` into the desired S3 prefix (e.g., `sessions/<org>/<storageId>/`). | |
| 41 | + - Generate two short-lived pre-signed `PUT` URLs: one for `session.json`, one for `diff.txt`. | |
| 42 | + - Return both URLs and their keys in the response payload described above. | |
| 43 | +- **Expiration**: The initial implementation can hand out URLs with a generous TTL (e.g., 60 minutes). Later we will add CLI-side refresh logic before expiry. | |
| 44 | + | |
| 45 | +## Open Questions & Future Enhancements | |
| 46 | + | |
| 47 | +- **URL refresh**: When the presigned URLs expire we currently have no refresh cycle. We'd need either a renewal endpoint or to re-call the existing endpoint on failure. | |
| 48 | +- **Upload cadence**: The 30-second interval is hard-coded for now. Consider making it configurable in both CLI and backend policies. | |
| 49 | +- **Error telemetry**: Decide if repeated upload failures should trip analytics or circuit breakers. | |
| 50 | +- **Diff source**: `diff.txt` currently mirrors the `/diff` endpoint response. Confirm backend expectations for format and size limits. | |
| 51 | +- **Security**: We might want to sign responses or enforce stricter scope on `storageId` mapping (e.g., require both org + storageId and validate ownership). | |
| 52 | + | |
| 53 | +--- | |
| 54 | + | |
| 55 | +This document should evolve alongside implementation details; update it whenever the API contract or client behavior changes. |
modified extensions/cli/src/commands/serve.ts +49 −37
| @@ -1,11 +1,8 @@ | ||
| 1 | -import { exec } from "child_process"; | |
| 2 | -import { promisify } from "util"; | |
| 3 | - | |
| 4 | 1 | import chalk from "chalk"; |
| 5 | 2 | import type { ChatHistoryItem } from "core/index.js"; |
| 6 | 3 | import express, { Request, Response } from "express"; |
| 7 | 4 | |
| 8 | -import { getAssistantSlug } from "../auth/workos.js"; | |
| 5 | +import { getAccessToken, getAssistantSlug } from "../auth/workos.js"; | |
| 9 | 6 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 10 | 7 | import { toolPermissionManager } from "../permissions/permissionManager.js"; |
| 11 | 8 | import { |
| @@ -19,11 +16,12 @@ | ||
| 19 | 16 | ConfigServiceState, |
| 20 | 17 | ModelServiceState, |
| 21 | 18 | } from "../services/types.js"; |
| 22 | -import { createSession } from "../session.js"; | |
| 19 | +import { createSession, getSessionPersistenceSnapshot } from "../session.js"; | |
| 23 | 20 | import { constructSystemMessage } from "../systemMessage.js"; |
| 24 | 21 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 25 | 22 | import { gracefulExit } from "../util/exit.js"; |
| 26 | 23 | import { formatError } from "../util/formatError.js"; |
| 24 | +import { getGitDiffSnapshot } from "../util/git.js"; | |
| 27 | 25 | import { logger } from "../util/logger.js"; |
| 28 | 26 | import { readStdinSync } from "../util/stdin.js"; |
| 29 | 27 | |
| @@ -33,11 +31,11 @@ | ||
| 33 | 31 | type ServerState, |
| 34 | 32 | } from "./serve.helpers.js"; |
| 35 | 33 | |
| 36 | -const execAsync = promisify(exec); | |
| 37 | - | |
| 38 | 34 | interface ServeOptions extends ExtendedCommandOptions { |
| 39 | 35 | timeout?: string; |
| 40 | 36 | port?: string; |
| 37 | + /** Storage identifier for remote sync */ | |
| 38 | + id?: string; | |
| 41 | 39 | } |
| 42 | 40 | |
| 43 | 41 | // eslint-disable-next-line max-statements |
| @@ -86,6 +84,7 @@ | ||
| 86 | 84 | if (authState.organizationId) { |
| 87 | 85 | telemetryService.updateOrganization(authState.organizationId); |
| 88 | 86 | } |
| 87 | + const accessToken = getAccessToken(authState.authConfig); | |
| 89 | 88 | |
| 90 | 89 | // Log configuration information |
| 91 | 90 | const organizationId = authState.organizationId || "personal"; |
| @@ -146,6 +145,32 @@ | ||
| 146 | 145 | pendingPermission: null, |
| 147 | 146 | }; |
| 148 | 147 | |
| 148 | + const syncSessionHistory = () => { | |
| 149 | + try { | |
| 150 | + state.session.history = services.chatHistory.getHistory(); | |
| 151 | + } catch (e) { | |
| 152 | + logger.debug( | |
| 153 | + `Failed to sync session history from ChatHistoryService: ${formatError(e)}`, | |
| 154 | + ); | |
| 155 | + } | |
| 156 | + }; | |
| 157 | + | |
| 158 | + const storageSyncService = services.storageSync; | |
| 159 | + let storageSyncActive = await storageSyncService.startFromOptions({ | |
| 160 | + storageOption: options.id, | |
| 161 | + accessToken, | |
| 162 | + syncSessionHistory, | |
| 163 | + getSessionSnapshot: () => getSessionPersistenceSnapshot(state.session), | |
| 164 | + isActive: () => state.serverRunning, | |
| 165 | + }); | |
| 166 | + | |
| 167 | + const stopStorageSync = () => { | |
| 168 | + if (storageSyncActive) { | |
| 169 | + storageSyncService.stop(); | |
| 170 | + storageSyncActive = false; | |
| 171 | + } | |
| 172 | + }; | |
| 173 | + | |
| 149 | 174 | // Record session start |
| 150 | 175 | telemetryService.recordSessionStart(); |
| 151 | 176 | telemetryService.startActiveTime(); |
| @@ -156,14 +181,7 @@ | ||
| 156 | 181 | // GET /state - Return the current state |
| 157 | 182 | app.get("/state", (_req: Request, res: Response) => { |
| 158 | 183 | state.lastActivity = Date.now(); |
| 159 | - // Ensure session history reflects ChatHistoryService state | |
| 160 | - try { | |
| 161 | - state.session.history = services.chatHistory.getHistory(); | |
| 162 | - } catch (e) { | |
| 163 | - logger.debug( | |
| 164 | - `Failed to sync session history from ChatHistoryService: ${formatError(e)}`, | |
| 165 | - ); | |
| 166 | - } | |
| 184 | + syncSessionHistory(); | |
| 167 | 185 | res.json({ |
| 168 | 186 | session: state.session, // Return session directly instead of converting |
| 169 | 187 | isProcessing: state.isProcessing, |
| @@ -239,34 +257,25 @@ | ||
| 239 | 257 | state.lastActivity = Date.now(); |
| 240 | 258 | |
| 241 | 259 | try { |
| 242 | - // First check if we're in a git repository | |
| 243 | - await execAsync("git rev-parse --git-dir"); | |
| 244 | - | |
| 245 | - // Get the diff against main branch | |
| 246 | - const { stdout } = await execAsync("git diff main"); | |
| 260 | + const diffResult = await getGitDiffSnapshot(); | |
| 247 | 261 | |
| 248 | - res.json({ | |
| 249 | - diff: stdout, | |
| 250 | - }); | |
| 251 | - } catch (error: any) { | |
| 252 | - // Git diff returns exit code 1 when there are differences, which is normal | |
| 253 | - if (error.code === 1 && error.stdout) { | |
| 254 | - res.json({ | |
| 255 | - diff: error.stdout, | |
| 256 | - }); | |
| 257 | - } else if (error.code === 128) { | |
| 258 | - // Handle case where we're not in a git repo or main branch doesn't exist | |
| 262 | + if (!diffResult.repoFound) { | |
| 259 | 263 | res.status(404).json({ |
| 260 | 264 | error: "Not in a git repository or main branch doesn't exist", |
| 261 | 265 | diff: "", |
| 262 | 266 | }); |
| 263 | - } else { | |
| 264 | - logger.error(`Git diff error: ${formatError(error)}`); | |
| 265 | - res.status(500).json({ | |
| 266 | - error: `Failed to get git diff: ${formatError(error)}`, | |
| 267 | - diff: "", | |
| 268 | - }); | |
| 267 | + return; | |
| 269 | 268 | } |
| 269 | + | |
| 270 | + res.json({ | |
| 271 | + diff: diffResult.diff, | |
| 272 | + }); | |
| 273 | + } catch (error) { | |
| 274 | + logger.error(`Git diff error: ${formatError(error)}`); | |
| 275 | + res.status(500).json({ | |
| 276 | + error: `Failed to get git diff: ${formatError(error)}`, | |
| 277 | + diff: "", | |
| 278 | + }); | |
| 270 | 279 | } |
| 271 | 280 | }); |
| 272 | 281 | |
| @@ -287,6 +296,7 @@ | ||
| 287 | 296 | |
| 288 | 297 | // Set server running flag to false to stop processing |
| 289 | 298 | state.serverRunning = false; |
| 299 | + stopStorageSync(); | |
| 290 | 300 | |
| 291 | 301 | // Abort any current processing |
| 292 | 302 | if (state.currentAbortController) { |
| @@ -438,6 +448,7 @@ | ||
| 438 | 448 | ), |
| 439 | 449 | ); |
| 440 | 450 | state.serverRunning = false; |
| 451 | + stopStorageSync(); | |
| 441 | 452 | server.close(() => { |
| 442 | 453 | telemetryService.stopActiveTime(); |
| 443 | 454 | gracefulExit(0).catch((err) => { |
| @@ -456,6 +467,7 @@ | ||
| 456 | 467 | process.on("SIGINT", () => { |
| 457 | 468 | console.log(chalk.yellow("\nShutting down server...")); |
| 458 | 469 | state.serverRunning = false; |
| 470 | + stopStorageSync(); | |
| 459 | 471 | if (inactivityChecker) { |
| 460 | 472 | clearInterval(inactivityChecker); |
| 461 | 473 | inactivityChecker = null; |
modified extensions/cli/src/index.ts +4 −0
| @@ -312,6 +312,10 @@ | ||
| 312 | 312 | "300", |
| 313 | 313 | ) |
| 314 | 314 | .option("--port <port>", "Port to run the server on (default: 8000)", "8000") |
| 315 | + .option( | |
| 316 | + "--id <storageId>", | |
| 317 | + "Upload session snapshots to Continue-managed storage using the provided identifier", | |
| 318 | + ) | |
| 315 | 319 | .action(async (prompt, options) => { |
| 316 | 320 | // Telemetry: record command invocation |
| 317 | 321 | await posthogService.capture("cliCommand", { command: "serve" }); |
added extensions/cli/src/services/StorageSyncService.test.ts +203 −0
| @@ -0,0 +1,203 @@ | ||
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import { getGitDiffSnapshot } from "../util/git.js"; | |
| 4 | +import { logger } from "../util/logger.js"; | |
| 5 | + | |
| 6 | +import { StorageSyncService } from "./StorageSyncService.js"; | |
| 7 | + | |
| 8 | +vi.mock("../util/logger.js", () => ({ | |
| 9 | + logger: { | |
| 10 | + debug: vi.fn(), | |
| 11 | + info: vi.fn(), | |
| 12 | + warn: vi.fn(), | |
| 13 | + error: vi.fn(), | |
| 14 | + }, | |
| 15 | +})); | |
| 16 | + | |
| 17 | +vi.mock("../env.js", () => ({ | |
| 18 | + env: { apiBase: "https://api.test/" }, | |
| 19 | +})); | |
| 20 | + | |
| 21 | +vi.mock("../util/git.js", () => ({ | |
| 22 | + getGitDiffSnapshot: vi.fn(), | |
| 23 | +})); | |
| 24 | + | |
| 25 | +describe("StorageSyncService", () => { | |
| 26 | + const fetchMock = vi.fn(); | |
| 27 | + const gitDiffMock = vi.mocked(getGitDiffSnapshot); | |
| 28 | + let service: StorageSyncService; | |
| 29 | + let originalFetch: typeof fetch | undefined; | |
| 30 | + let hadFetch = false; | |
| 31 | + | |
| 32 | + beforeEach(async () => { | |
| 33 | + vi.clearAllMocks(); | |
| 34 | + fetchMock.mockReset(); | |
| 35 | + hadFetch = "fetch" in globalThis; | |
| 36 | + originalFetch = globalThis.fetch; | |
| 37 | + globalThis.fetch = fetchMock as unknown as typeof fetch; | |
| 38 | + gitDiffMock.mockReset(); | |
| 39 | + | |
| 40 | + service = new StorageSyncService(); | |
| 41 | + await service.initialize(); | |
| 42 | + }); | |
| 43 | + | |
| 44 | + afterEach(() => { | |
| 45 | + service.stop(); | |
| 46 | + if (hadFetch) { | |
| 47 | + globalThis.fetch = originalFetch!; | |
| 48 | + } else { | |
| 49 | + delete (globalThis as { fetch?: typeof fetch }).fetch; | |
| 50 | + } | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("returns false when no storage option provided", async () => { | |
| 54 | + const result = await service.startFromOptions({ | |
| 55 | + storageOption: undefined, | |
| 56 | + accessToken: "token", | |
| 57 | + syncSessionHistory: vi.fn(), | |
| 58 | + getSessionSnapshot: vi.fn(), | |
| 59 | + }); | |
| 60 | + | |
| 61 | + expect(result).toBe(false); | |
| 62 | + expect(fetchMock).not.toHaveBeenCalled(); | |
| 63 | + }); | |
| 64 | + | |
| 65 | + it("warns when storage identifier trims to empty", async () => { | |
| 66 | + const warnSpy = vi.spyOn(logger, "warn"); | |
| 67 | + | |
| 68 | + const result = await service.startFromOptions({ | |
| 69 | + storageOption: " ", | |
| 70 | + accessToken: "token", | |
| 71 | + syncSessionHistory: vi.fn(), | |
| 72 | + getSessionSnapshot: vi.fn(), | |
| 73 | + }); | |
| 74 | + | |
| 75 | + expect(result).toBe(false); | |
| 76 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 77 | + expect.stringContaining("storage identifier was empty"), | |
| 78 | + ); | |
| 79 | + warnSpy.mockRestore(); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + it("warns when storage requested without access token", async () => { | |
| 83 | + const warnSpy = vi.spyOn(logger, "warn"); | |
| 84 | + | |
| 85 | + const result = await service.startFromOptions({ | |
| 86 | + storageOption: "session-123", | |
| 87 | + accessToken: null, | |
| 88 | + syncSessionHistory: vi.fn(), | |
| 89 | + getSessionSnapshot: vi.fn(), | |
| 90 | + }); | |
| 91 | + | |
| 92 | + expect(result).toBe(false); | |
| 93 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 94 | + expect.stringContaining("no Continue API key"), | |
| 95 | + ); | |
| 96 | + warnSpy.mockRestore(); | |
| 97 | + }); | |
| 98 | + | |
| 99 | + it("starts syncing when presign succeeds", async () => { | |
| 100 | + const syncSessionHistory = vi.fn(); | |
| 101 | + const getSessionSnapshot = vi.fn().mockReturnValue({ foo: "bar" }); | |
| 102 | + | |
| 103 | + fetchMock.mockResolvedValueOnce({ | |
| 104 | + ok: true, | |
| 105 | + json: async () => ({ | |
| 106 | + session: { putUrl: "https://upload/session", key: "session.json" }, | |
| 107 | + diff: { putUrl: "https://upload/diff", key: "diff.txt" }, | |
| 108 | + }), | |
| 109 | + }); | |
| 110 | + fetchMock.mockResolvedValue({ ok: true }); | |
| 111 | + gitDiffMock.mockResolvedValue({ diff: "diff", repoFound: true }); | |
| 112 | + | |
| 113 | + const result = await service.startFromOptions({ | |
| 114 | + storageOption: "session-123", | |
| 115 | + accessToken: "token", | |
| 116 | + syncSessionHistory, | |
| 117 | + getSessionSnapshot, | |
| 118 | + isActive: () => true, | |
| 119 | + }); | |
| 120 | + | |
| 121 | + expect(result).toBe(true); | |
| 122 | + expect(syncSessionHistory).toHaveBeenCalledTimes(1); | |
| 123 | + expect(getSessionSnapshot).toHaveBeenCalledTimes(1); | |
| 124 | + expect(fetchMock).toHaveBeenCalledTimes(3); | |
| 125 | + const [presignUrl, presignOptions] = fetchMock.mock.calls[0]; | |
| 126 | + expect(presignUrl).toBeInstanceOf(URL); | |
| 127 | + expect((presignUrl as URL).toString()).toBe( | |
| 128 | + "https://api.test/agents/storage/presigned-url", | |
| 129 | + ); | |
| 130 | + expect(presignOptions).toMatchObject({ method: "POST" }); | |
| 131 | + | |
| 132 | + const [sessionUrl, sessionOptions] = fetchMock.mock.calls[1]; | |
| 133 | + expect(sessionUrl).toBe("https://upload/session"); | |
| 134 | + expect(sessionOptions).toMatchObject({ | |
| 135 | + method: "PUT", | |
| 136 | + body: expect.any(String), | |
| 137 | + }); | |
| 138 | + | |
| 139 | + service.stop(); | |
| 140 | + expect(service.getState().isEnabled).toBe(false); | |
| 141 | + }); | |
| 142 | + | |
| 143 | + it("returns false when presign request fails", async () => { | |
| 144 | + fetchMock.mockResolvedValueOnce({ | |
| 145 | + ok: false, | |
| 146 | + status: 500, | |
| 147 | + statusText: "Server Error", | |
| 148 | + }); | |
| 149 | + | |
| 150 | + const warnSpy = vi.spyOn(logger, "warn"); | |
| 151 | + const result = await service.startFromOptions({ | |
| 152 | + storageOption: "session-123", | |
| 153 | + accessToken: "token", | |
| 154 | + syncSessionHistory: vi.fn(), | |
| 155 | + getSessionSnapshot: vi.fn(), | |
| 156 | + }); | |
| 157 | + | |
| 158 | + expect(result).toBe(false); | |
| 159 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 160 | + expect.stringContaining("presign request failed"), | |
| 161 | + ); | |
| 162 | + expect(service.getState().lastError).toBe( | |
| 163 | + "Failed to obtain presigned URLs", | |
| 164 | + ); | |
| 165 | + warnSpy.mockRestore(); | |
| 166 | + }); | |
| 167 | + | |
| 168 | + it("records upload error details when PUT fails", async () => { | |
| 169 | + fetchMock.mockResolvedValueOnce({ | |
| 170 | + ok: true, | |
| 171 | + json: async () => ({ | |
| 172 | + session: { putUrl: "https://upload/session", key: "session.json" }, | |
| 173 | + diff: { putUrl: "https://upload/diff", key: "diff.txt" }, | |
| 174 | + }), | |
| 175 | + }); | |
| 176 | + fetchMock.mockResolvedValueOnce({ | |
| 177 | + ok: false, | |
| 178 | + status: 403, | |
| 179 | + statusText: "Forbidden", | |
| 180 | + }); | |
| 181 | + gitDiffMock.mockResolvedValue({ diff: "", repoFound: true }); | |
| 182 | + | |
| 183 | + const warnSpy = vi.spyOn(logger, "warn"); | |
| 184 | + | |
| 185 | + const result = await service.startFromOptions({ | |
| 186 | + storageOption: "session-123", | |
| 187 | + accessToken: "token", | |
| 188 | + syncSessionHistory: vi.fn(), | |
| 189 | + getSessionSnapshot: vi.fn().mockReturnValue({}), | |
| 190 | + }); | |
| 191 | + | |
| 192 | + expect(result).toBe(true); | |
| 193 | + expect(warnSpy).toHaveBeenCalledWith( | |
| 194 | + expect.stringContaining("Storage upload failed"), | |
| 195 | + ); | |
| 196 | + const state = service.getState(); | |
| 197 | + expect(state.isEnabled).toBe(true); | |
| 198 | + expect(state.lastError).toContain("Storage upload failed"); | |
| 199 | + | |
| 200 | + service.stop(); | |
| 201 | + warnSpy.mockRestore(); | |
| 202 | + }); | |
| 203 | +}); |
added extensions/cli/src/services/StorageSyncService.ts +283 −0
| @@ -0,0 +1,283 @@ | ||
| 1 | +import chalk from "chalk"; | |
| 2 | + | |
| 3 | +import { env } from "../env.js"; | |
| 4 | +import { formatError } from "../util/formatError.js"; | |
| 5 | +import { getGitDiffSnapshot } from "../util/git.js"; | |
| 6 | +import { logger } from "../util/logger.js"; | |
| 7 | + | |
| 8 | +import type { StorageSyncServiceState } from "./types.js"; | |
| 9 | + | |
| 10 | +const DEFAULT_UPLOAD_INTERVAL_MS = 30_000; | |
| 11 | + | |
| 12 | +type StoragePresignedLocation = { | |
| 13 | + key: string; | |
| 14 | + putUrl: string; | |
| 15 | +}; | |
| 16 | + | |
| 17 | +type StoragePresignResponse = { | |
| 18 | + session?: StoragePresignedLocation; | |
| 19 | + diff?: StoragePresignedLocation; | |
| 20 | +}; | |
| 21 | + | |
| 22 | +type StorageTargets = { | |
| 23 | + sessionUrl: string; | |
| 24 | + diffUrl: string; | |
| 25 | +}; | |
| 26 | + | |
| 27 | +export interface StorageSyncStartOptions { | |
| 28 | + storageId: string; | |
| 29 | + accessToken: string; | |
| 30 | + intervalMs?: number; | |
| 31 | + syncSessionHistory: () => void; | |
| 32 | + getSessionSnapshot: () => unknown; | |
| 33 | + isActive?: () => boolean; | |
| 34 | +} | |
| 35 | + | |
| 36 | +export class StorageSyncService { | |
| 37 | + private state: StorageSyncServiceState = { | |
| 38 | + isEnabled: false, | |
| 39 | + lastError: null, | |
| 40 | + }; | |
| 41 | + | |
| 42 | + private intervalHandle: NodeJS.Timeout | null = null; | |
| 43 | + private stopped = true; | |
| 44 | + private uploadInFlight = false; | |
| 45 | + private missingRepoLogged = false; | |
| 46 | + private targets: StorageTargets | null = null; | |
| 47 | + private options: StorageSyncStartOptions | null = null; | |
| 48 | + | |
| 49 | + async initialize(): Promise<StorageSyncServiceState> { | |
| 50 | + this.stop(); | |
| 51 | + return this.getState(); | |
| 52 | + } | |
| 53 | + | |
| 54 | + getState(): StorageSyncServiceState { | |
| 55 | + return { ...this.state }; | |
| 56 | + } | |
| 57 | + | |
| 58 | + getDefaultInterval(): number { | |
| 59 | + return DEFAULT_UPLOAD_INTERVAL_MS; | |
| 60 | + } | |
| 61 | + | |
| 62 | + async startFromOptions( | |
| 63 | + options: { | |
| 64 | + storageOption?: string; | |
| 65 | + accessToken?: string | null; | |
| 66 | + } & Omit<StorageSyncStartOptions, "storageId" | "accessToken">, | |
| 67 | + ): Promise<boolean> { | |
| 68 | + const { storageOption, accessToken, ...rest } = options; | |
| 69 | + | |
| 70 | + if (!storageOption) { | |
| 71 | + return false; | |
| 72 | + } | |
| 73 | + | |
| 74 | + const storageId = storageOption.trim(); | |
| 75 | + if (!storageId) { | |
| 76 | + logger.warn( | |
| 77 | + "Storage sync requested but the provided storage identifier was empty; skipping uploads.", | |
| 78 | + ); | |
| 79 | + return false; | |
| 80 | + } | |
| 81 | + | |
| 82 | + if (!accessToken) { | |
| 83 | + logger.warn( | |
| 84 | + "Storage sync requested but no Continue API key is available; skipping uploads.", | |
| 85 | + ); | |
| 86 | + return false; | |
| 87 | + } | |
| 88 | + | |
| 89 | + return this.start({ | |
| 90 | + storageId, | |
| 91 | + accessToken, | |
| 92 | + ...rest, | |
| 93 | + }); | |
| 94 | + } | |
| 95 | + | |
| 96 | + async start(options: StorageSyncStartOptions): Promise<boolean> { | |
| 97 | + // Ensure any existing sync loop is stopped before starting a new one | |
| 98 | + this.stop(); | |
| 99 | + | |
| 100 | + const targets = await this.requestStorageTargets( | |
| 101 | + options.storageId, | |
| 102 | + options.accessToken, | |
| 103 | + ); | |
| 104 | + | |
| 105 | + if (!targets) { | |
| 106 | + this.setState({ | |
| 107 | + isEnabled: false, | |
| 108 | + storageId: options.storageId, | |
| 109 | + lastError: "Failed to obtain presigned URLs", | |
| 110 | + }); | |
| 111 | + return false; | |
| 112 | + } | |
| 113 | + | |
| 114 | + this.targets = targets; | |
| 115 | + this.options = options; | |
| 116 | + this.stopped = false; | |
| 117 | + this.uploadInFlight = false; | |
| 118 | + this.missingRepoLogged = false; | |
| 119 | + this.setState({ | |
| 120 | + isEnabled: true, | |
| 121 | + storageId: options.storageId, | |
| 122 | + lastError: null, | |
| 123 | + lastUploadAt: undefined, | |
| 124 | + }); | |
| 125 | + | |
| 126 | + const intervalMs = options.intervalMs ?? DEFAULT_UPLOAD_INTERVAL_MS; | |
| 127 | + logger.info( | |
| 128 | + chalk.dim( | |
| 129 | + `Storage sync enabled (uploading every ${Math.round(intervalMs / 1000)}s)`, | |
| 130 | + ), | |
| 131 | + ); | |
| 132 | + | |
| 133 | + await this.performUpload(); | |
| 134 | + | |
| 135 | + this.intervalHandle = setInterval(() => { | |
| 136 | + void this.performUpload(); | |
| 137 | + }, intervalMs); | |
| 138 | + | |
| 139 | + return true; | |
| 140 | + } | |
| 141 | + | |
| 142 | + stop(): void { | |
| 143 | + this.stopped = true; | |
| 144 | + this.targets = null; | |
| 145 | + this.options = null; | |
| 146 | + this.uploadInFlight = false; | |
| 147 | + | |
| 148 | + if (this.intervalHandle) { | |
| 149 | + clearInterval(this.intervalHandle); | |
| 150 | + this.intervalHandle = null; | |
| 151 | + } | |
| 152 | + | |
| 153 | + if (this.state.isEnabled) { | |
| 154 | + this.setState({ | |
| 155 | + isEnabled: false, | |
| 156 | + storageId: this.state.storageId, | |
| 157 | + lastError: null, | |
| 158 | + lastUploadAt: this.state.lastUploadAt, | |
| 159 | + }); | |
| 160 | + } | |
| 161 | + } | |
| 162 | + | |
| 163 | + private setState(next: StorageSyncServiceState): void { | |
| 164 | + this.state = { ...next }; | |
| 165 | + } | |
| 166 | + | |
| 167 | + private async requestStorageTargets( | |
| 168 | + storageId: string, | |
| 169 | + accessToken: string, | |
| 170 | + ): Promise<StorageTargets | null> { | |
| 171 | + const url = new URL("agents/storage/presigned-url", env.apiBase); | |
| 172 | + | |
| 173 | + try { | |
| 174 | + const response = await fetch(url, { | |
| 175 | + method: "POST", | |
| 176 | + headers: { | |
| 177 | + "Content-Type": "application/json", | |
| 178 | + Authorization: `Bearer ${accessToken}`, | |
| 179 | + }, | |
| 180 | + body: JSON.stringify({ storageId }), | |
| 181 | + }); | |
| 182 | + | |
| 183 | + if (!response.ok) { | |
| 184 | + const statusText = `${response.status} ${response.statusText}`.trim(); | |
| 185 | + logger.warn( | |
| 186 | + `Storage sync presign request failed (${statusText}). Storage uploads disabled for this session.`, | |
| 187 | + ); | |
| 188 | + return null; | |
| 189 | + } | |
| 190 | + | |
| 191 | + const body = (await response.json()) as StoragePresignResponse; | |
| 192 | + | |
| 193 | + if (!body.session?.putUrl || !body.diff?.putUrl) { | |
| 194 | + logger.warn( | |
| 195 | + "Storage sync presign response missing required URLs. Storage uploads disabled for this session.", | |
| 196 | + ); | |
| 197 | + return null; | |
| 198 | + } | |
| 199 | + | |
| 200 | + return { | |
| 201 | + sessionUrl: body.session.putUrl, | |
| 202 | + diffUrl: body.diff.putUrl, | |
| 203 | + }; | |
| 204 | + } catch (error) { | |
| 205 | + logger.warn( | |
| 206 | + `Storage sync presign request failed: ${formatError(error)}. Storage uploads disabled for this session.`, | |
| 207 | + ); | |
| 208 | + return null; | |
| 209 | + } | |
| 210 | + } | |
| 211 | + | |
| 212 | + private async uploadToPresignedUrl( | |
| 213 | + url: string, | |
| 214 | + body: string, | |
| 215 | + contentType: string, | |
| 216 | + ): Promise<void> { | |
| 217 | + const response = await fetch(url, { | |
| 218 | + method: "PUT", | |
| 219 | + headers: { | |
| 220 | + "Content-Type": contentType, | |
| 221 | + }, | |
| 222 | + body, | |
| 223 | + }); | |
| 224 | + | |
| 225 | + if (!response.ok) { | |
| 226 | + const statusText = `${response.status} ${response.statusText}`.trim(); | |
| 227 | + throw new Error(`Storage upload failed (${statusText})`); | |
| 228 | + } | |
| 229 | + } | |
| 230 | + | |
| 231 | + private async performUpload(): Promise<void> { | |
| 232 | + if (this.stopped || this.uploadInFlight || !this.targets || !this.options) { | |
| 233 | + return; | |
| 234 | + } | |
| 235 | + | |
| 236 | + if (this.options.isActive && !this.options.isActive()) { | |
| 237 | + return; | |
| 238 | + } | |
| 239 | + | |
| 240 | + this.uploadInFlight = true; | |
| 241 | + | |
| 242 | + try { | |
| 243 | + this.options.syncSessionHistory(); | |
| 244 | + const snapshot = this.options.getSessionSnapshot(); | |
| 245 | + const sessionPayload = JSON.stringify(snapshot, null, 2); | |
| 246 | + await this.uploadToPresignedUrl( | |
| 247 | + this.targets.sessionUrl, | |
| 248 | + sessionPayload, | |
| 249 | + "application/json", | |
| 250 | + ); | |
| 251 | + | |
| 252 | + const diffResult = await getGitDiffSnapshot(); | |
| 253 | + if (!diffResult.repoFound && !this.missingRepoLogged) { | |
| 254 | + logger.debug( | |
| 255 | + "Storage sync diff upload skipped: not in a git repository or main branch missing.", | |
| 256 | + ); | |
| 257 | + this.missingRepoLogged = true; | |
| 258 | + } | |
| 259 | + await this.uploadToPresignedUrl( | |
| 260 | + this.targets.diffUrl, | |
| 261 | + diffResult.diff, | |
| 262 | + "text/plain", | |
| 263 | + ); | |
| 264 | + | |
| 265 | + this.setState({ | |
| 266 | + isEnabled: true, | |
| 267 | + storageId: this.state.storageId, | |
| 268 | + lastUploadAt: Date.now(), | |
| 269 | + lastError: null, | |
| 270 | + }); | |
| 271 | + } catch (error) { | |
| 272 | + this.setState({ | |
| 273 | + isEnabled: true, | |
| 274 | + storageId: this.state.storageId, | |
| 275 | + lastUploadAt: this.state.lastUploadAt, | |
| 276 | + lastError: formatError(error), | |
| 277 | + }); | |
| 278 | + logger.warn(`Storage sync upload failed: ${formatError(error)}`); | |
| 279 | + } finally { | |
| 280 | + this.uploadInFlight = false; | |
| 281 | + } | |
| 282 | + } | |
| 283 | +} |
modified extensions/cli/src/services/index.ts +9 −0
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | import { modeService } from "./ModeService.js"; |
| 13 | 13 | import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; |
| 14 | 14 | import { serviceContainer } from "./ServiceContainer.js"; |
| 15 | +import { StorageSyncService } from "./StorageSyncService.js"; | |
| 15 | 16 | import { systemMessageService } from "./SystemMessageService.js"; |
| 16 | 17 | import { |
| 17 | 18 | ApiClientServiceState, |
| @@ -33,6 +34,7 @@ | ||
| 33 | 34 | const resourceMonitoringService = new ResourceMonitoringService(); |
| 34 | 35 | const chatHistoryService = new ChatHistoryService(); |
| 35 | 36 | const updateService = new UpdateService(); |
| 37 | +const storageSyncService = new StorageSyncService(); | |
| 36 | 38 | |
| 37 | 39 | /** |
| 38 | 40 | * Initialize all services and register them with the service container |
| @@ -251,6 +253,12 @@ | ||
| 251 | 253 | [], |
| 252 | 254 | ); |
| 253 | 255 | |
| 256 | + serviceContainer.register( | |
| 257 | + SERVICE_NAMES.STORAGE_SYNC, | |
| 258 | + () => storageSyncService.initialize(), | |
| 259 | + [], | |
| 260 | + ); | |
| 261 | + | |
| 254 | 262 | serviceContainer.register( |
| 255 | 263 | SERVICE_NAMES.CHAT_HISTORY, |
| 256 | 264 | () => chatHistoryService.initialize(undefined, initOptions.headless), |
| @@ -318,6 +326,7 @@ | ||
| 318 | 326 | systemMessage: systemMessageService, |
| 319 | 327 | chatHistory: chatHistoryService, |
| 320 | 328 | updateService: updateService, |
| 329 | + storageSync: storageSyncService, | |
| 321 | 330 | } as const; |
| 322 | 331 | |
| 323 | 332 | // Export the service container for advanced usage |
modified extensions/cli/src/services/types.ts +8 −0
| @@ -111,6 +111,13 @@ | ||
| 111 | 111 | originalPolicies?: ToolPermissions; |
| 112 | 112 | } |
| 113 | 113 | |
| 114 | +export interface StorageSyncServiceState { | |
| 115 | + isEnabled: boolean; | |
| 116 | + storageId?: string; | |
| 117 | + lastUploadAt?: number; | |
| 118 | + lastError?: string | null; | |
| 119 | +} | |
| 120 | + | |
| 114 | 121 | export type { ChatHistoryState } from "./ChatHistoryService.js"; |
| 115 | 122 | export type { FileIndexServiceState } from "./FileIndexService.js"; |
| 116 | 123 | |
| @@ -129,6 +136,7 @@ | ||
| 129 | 136 | SYSTEM_MESSAGE: "systemMessage", |
| 130 | 137 | CHAT_HISTORY: "chatHistory", |
| 131 | 138 | UPDATE: "update", |
| 139 | + STORAGE_SYNC: "storageSync", | |
| 132 | 140 | } as const; |
| 133 | 141 | |
| 134 | 142 | /** |
modified extensions/cli/src/session.ts +5 −1
| @@ -157,13 +157,17 @@ | ||
| 157 | 157 | }; |
| 158 | 158 | } |
| 159 | 159 | |
| 160 | +export function getSessionPersistenceSnapshot(session: Session): Session { | |
| 161 | + return modifySessionBeforeSave(session); | |
| 162 | +} | |
| 163 | + | |
| 160 | 164 | /** |
| 161 | 165 | * Save the current session to file |
| 162 | 166 | */ |
| 163 | 167 | export function saveSession(): void { |
| 164 | 168 | try { |
| 165 | 169 | const session = SessionManager.getInstance().getCurrentSession(); |
| 166 | - const sessionToSave = modifySessionBeforeSave(session); | |
| 170 | + const sessionToSave = getSessionPersistenceSnapshot(session); | |
| 167 | 171 | historyManager.save(sessionToSave); |
| 168 | 172 | } catch (error) { |
| 169 | 173 | logger.error("Error saving session:", error); |
modified extensions/cli/src/util/git.ts +51 −1
| @@ -1,4 +1,8 @@ | ||
| 1 | -import { execSync } from "child_process"; | |
| 1 | +import { exec, execSync } from "child_process"; | |
| 2 | +import { promisify } from "util"; | |
| 3 | + | |
| 4 | +const execAsync = promisify(exec); | |
| 5 | +const LARGE_STDIO_BUFFER_BYTES = 10 * 1024 * 1024; // bump buffer for large git output | |
| 2 | 6 | |
| 3 | 7 | /** |
| 4 | 8 | * Get the git remote URL for the current repository |
| @@ -110,3 +114,49 @@ | ||
| 110 | 114 | const url = remoteUrl || process.cwd(); |
| 111 | 115 | return url.endsWith(".git") ? url.slice(0, -4) : url; |
| 112 | 116 | } |
| 117 | + | |
| 118 | +export interface GitDiffSnapshot { | |
| 119 | + diff: string; | |
| 120 | + repoFound: boolean; | |
| 121 | +} | |
| 122 | + | |
| 123 | +function isExecError( | |
| 124 | + error: unknown, | |
| 125 | +): error is { code?: number; stdout?: string } { | |
| 126 | + return ( | |
| 127 | + typeof error === "object" && | |
| 128 | + error !== null && | |
| 129 | + ("code" in error || "stdout" in error) | |
| 130 | + ); | |
| 131 | +} | |
| 132 | + | |
| 133 | +export async function getGitDiffSnapshot(): Promise<GitDiffSnapshot> { | |
| 134 | + try { | |
| 135 | + await execAsync("git rev-parse --git-dir", { | |
| 136 | + maxBuffer: LARGE_STDIO_BUFFER_BYTES, | |
| 137 | + }); | |
| 138 | + } catch (error) { | |
| 139 | + if (isExecError(error) && error.code === 128) { | |
| 140 | + return { diff: "", repoFound: false }; | |
| 141 | + } | |
| 142 | + throw error; | |
| 143 | + } | |
| 144 | + | |
| 145 | + try { | |
| 146 | + const { stdout } = await execAsync("git diff main", { | |
| 147 | + maxBuffer: LARGE_STDIO_BUFFER_BYTES, | |
| 148 | + }); | |
| 149 | + return { diff: stdout, repoFound: true }; | |
| 150 | + } catch (error) { | |
| 151 | + if (isExecError(error)) { | |
| 152 | + if (error.code === 1 && error.stdout) { | |
| 153 | + return { diff: error.stdout, repoFound: true }; | |
| 154 | + } | |
| 155 | + | |
| 156 | + if (error.code === 128) { | |
| 157 | + return { diff: "", repoFound: false }; | |
| 158 | + } | |
| 159 | + } | |
| 160 | + throw error; | |
| 161 | + } | |
| 162 | +} |