| 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 | getCompleteStateSnapshot: 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 | getCompleteStateSnapshot: 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 | getCompleteStateSnapshot: 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 getCompleteStateSnapshot = 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 | getCompleteStateSnapshot, |
| 118 | isActive: () => true, |
| 119 | }); |
| 120 | |
| 121 | expect(result).toBe(true); |
| 122 | expect(syncSessionHistory).toHaveBeenCalledTimes(1); |
| 123 | expect(getCompleteStateSnapshot).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 | getCompleteStateSnapshot: 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 | text: async () => "Access denied", |
| 181 | }); |
| 182 | gitDiffMock.mockResolvedValue({ diff: "", repoFound: true }); |
| 183 | |
| 184 | const warnSpy = vi.spyOn(logger, "warn"); |
| 185 | |
| 186 | const result = await service.startFromOptions({ |
| 187 | storageOption: "session-123", |
| 188 | accessToken: "token", |
| 189 | syncSessionHistory: vi.fn(), |
| 190 | getCompleteStateSnapshot: vi.fn().mockReturnValue({}), |
| 191 | }); |
| 192 | |
| 193 | expect(result).toBe(true); |
| 194 | expect(warnSpy).toHaveBeenCalledWith( |
| 195 | expect.stringContaining("Storage sync upload failed"), |
| 196 | ); |
| 197 | const state = service.getState(); |
| 198 | expect(state.isEnabled).toBe(true); |
| 199 | expect(state.lastError).toContain("Storage upload failed"); |
| 200 | |
| 201 | service.stop(); |
| 202 | warnSpy.mockRestore(); |
| 203 | }); |
| 204 | |
| 205 | it("does nothing when markAgentStatusUnread has no storage context", async () => { |
| 206 | await service.markAgentStatusUnread(); |
| 207 | expect(fetchMock).not.toHaveBeenCalled(); |
| 208 | }); |
| 209 | |
| 210 | it("marks the agent session as unread", async () => { |
| 211 | (service as unknown as { options: any }).options = { |
| 212 | storageId: "session-123", |
| 213 | accessToken: "token", |
| 214 | }; |
| 215 | |
| 216 | fetchMock.mockResolvedValueOnce({ ok: true }); |
| 217 | |
| 218 | await service.markAgentStatusUnread(); |
| 219 | |
| 220 | expect(fetchMock).toHaveBeenCalledTimes(1); |
| 221 | const [url, init] = fetchMock.mock.calls[0]; |
| 222 | expect(url).toBeInstanceOf(URL); |
| 223 | expect((url as URL).toString()).toBe( |
| 224 | "https://api.test/agents/session-123/read-status", |
| 225 | ); |
| 226 | expect(init).toMatchObject({ |
| 227 | method: "POST", |
| 228 | body: JSON.stringify({ unread: true }), |
| 229 | headers: { |
| 230 | Authorization: "Bearer token", |
| 231 | "Content-Type": "application/json", |
| 232 | }, |
| 233 | }); |
| 234 | }); |
| 235 | |
| 236 | it("includes server-side encryption header when required by signed headers", async () => { |
| 237 | const syncSessionHistory = vi.fn(); |
| 238 | const getCompleteStateSnapshot = vi.fn().mockReturnValue({ test: "data" }); |
| 239 | |
| 240 | // Mock presign response with server-side encryption in signed headers |
| 241 | const sessionUrlWithSSE = |
| 242 | "https://upload/session?X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption"; |
| 243 | const diffUrl = "https://upload/diff"; |
| 244 | |
| 245 | fetchMock.mockResolvedValueOnce({ |
| 246 | ok: true, |
| 247 | json: async () => ({ |
| 248 | session: { putUrl: sessionUrlWithSSE, key: "session.json" }, |
| 249 | diff: { putUrl: diffUrl, key: "diff.txt" }, |
| 250 | }), |
| 251 | }); |
| 252 | fetchMock.mockResolvedValue({ ok: true }); |
| 253 | gitDiffMock.mockResolvedValue({ diff: "test diff", repoFound: true }); |
| 254 | |
| 255 | const result = await service.startFromOptions({ |
| 256 | storageOption: "session-123", |
| 257 | accessToken: "token", |
| 258 | syncSessionHistory, |
| 259 | getCompleteStateSnapshot, |
| 260 | isActive: () => true, |
| 261 | }); |
| 262 | |
| 263 | expect(result).toBe(true); |
| 264 | expect(fetchMock).toHaveBeenCalledTimes(3); |
| 265 | |
| 266 | // Check session upload includes server-side encryption header |
| 267 | const sessionCall = fetchMock.mock.calls[1]; |
| 268 | expect(sessionCall[0]).toBe(sessionUrlWithSSE); |
| 269 | expect(sessionCall[1]).toMatchObject({ |
| 270 | method: "PUT", |
| 271 | headers: { |
| 272 | "Content-Type": "application/json", |
| 273 | "x-amz-server-side-encryption": "AES256", |
| 274 | }, |
| 275 | }); |
| 276 | |
| 277 | service.stop(); |
| 278 | }); |
| 279 | }); |