The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | ConnectionTransientError, |
| 3 | PrimaryConnectionTarget, |
| 4 | } from "@t3tools/client-runtime/connection"; |
| 5 | import { EnvironmentId, ThreadId } from "@t3tools/contracts"; |
| 6 | import { ConnectionCatalogDocument, Persistence } from "@t3tools/client-runtime/platform"; |
| 7 | import { describe, expect, it } from "@effect/vitest"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Deferred from "effect/Deferred"; |
| 10 | import * as Option from "effect/Option"; |
| 11 | import * as Schema from "effect/Schema"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import { afterEach, vi } from "vite-plus/test"; |
| 14 | |
| 15 | import * as ConnectionStorage from "./storage"; |
| 16 | |
| 17 | const emptyCatalog = { |
| 18 | schemaVersion: 1, |
| 19 | targets: [], |
| 20 | profiles: [], |
| 21 | credentials: [], |
| 22 | remoteDpopTokens: [], |
| 23 | disabledEnvironmentIds: [], |
| 24 | } as const; |
| 25 | const decodeCatalog = Schema.decodeUnknownSync(Schema.fromJsonString(ConnectionCatalogDocument)); |
| 26 | const encodeCatalog = Schema.encodeSync(Schema.fromJsonString(ConnectionCatalogDocument)); |
| 27 | |
| 28 | afterEach(() => { |
| 29 | vi.unstubAllGlobals(); |
| 30 | vi.restoreAllMocks(); |
| 31 | }); |
| 32 | |
| 33 | describe("ConnectionStorage.makeCatalogStore", () => { |
| 34 | it.effect("quarantines malformed catalogs and starts from an empty document", () => |
| 35 | Effect.gen(function* () { |
| 36 | const writes: string[] = []; |
| 37 | const quarantined: string[] = []; |
| 38 | const store = yield* ConnectionStorage.makeCatalogStore({ |
| 39 | read: Effect.succeed("{not-json"), |
| 40 | write: (raw) => Effect.sync(() => writes.push(raw)), |
| 41 | quarantine: (raw) => Effect.sync(() => quarantined.push(raw)), |
| 42 | }); |
| 43 | |
| 44 | expect(yield* store.read).toEqual(emptyCatalog); |
| 45 | expect(quarantined).toEqual(["{not-json"]); |
| 46 | expect(writes).toHaveLength(1); |
| 47 | expect(decodeCatalog(writes[0]!)).toEqual(emptyCatalog); |
| 48 | }), |
| 49 | ); |
| 50 | |
| 51 | it.effect("does not hide catalog read failures", () => |
| 52 | Effect.gen(function* () { |
| 53 | const failure = new ConnectionTransientError({ |
| 54 | reason: "remote-unavailable", |
| 55 | detail: "permission denied", |
| 56 | }); |
| 57 | const store = yield* ConnectionStorage.makeCatalogStore({ |
| 58 | read: Effect.fail(failure), |
| 59 | write: () => Effect.void, |
| 60 | }); |
| 61 | |
| 62 | expect(yield* Effect.flip(store.read)).toBe(failure); |
| 63 | }), |
| 64 | ); |
| 65 | }); |
| 66 | |
| 67 | const fixedHandle = (database: IDBDatabase) => ({ |
| 68 | get: Effect.succeed(database), |
| 69 | invalidate: () => Effect.void, |
| 70 | }); |
| 71 | |
| 72 | describe("ConnectionStorage.makeCatalogBackend", () => { |
| 73 | it.effect("fails IndexedDB writes whose commit aborts", () => |
| 74 | Effect.gen(function* () { |
| 75 | vi.stubGlobal("window", {}); |
| 76 | const transaction = Object.assign(new EventTarget(), { |
| 77 | error: null as DOMException | null, |
| 78 | objectStore: () => ({ |
| 79 | put: () => { |
| 80 | // A failed commit aborts the transaction without an "error" event. |
| 81 | queueMicrotask(() => { |
| 82 | transaction.error = new DOMException("Quota exceeded", "QuotaExceededError"); |
| 83 | transaction.dispatchEvent(new Event("abort")); |
| 84 | }); |
| 85 | }, |
| 86 | }), |
| 87 | }); |
| 88 | const backend = ConnectionStorage.makeCatalogBackend( |
| 89 | fixedHandle({ transaction: () => transaction } as unknown as IDBDatabase), |
| 90 | ); |
| 91 | |
| 92 | const error = yield* backend.write("{}").pipe(Effect.flip); |
| 93 | |
| 94 | expect(error.message).toContain("QuotaExceededError"); |
| 95 | }), |
| 96 | ); |
| 97 | }); |
| 98 | |
| 99 | describe("IndexedDB connection recovery", () => { |
| 100 | it.effect("reopens after a forced close and finalizes the current connection", () => |
| 101 | Effect.gen(function* () { |
| 102 | vi.stubGlobal("window", {}); |
| 103 | const makeDatabase = () => |
| 104 | Object.assign(new EventTarget(), { |
| 105 | close: vi.fn(), |
| 106 | transaction: () => ({ |
| 107 | objectStore: () => ({ |
| 108 | get: () => { |
| 109 | const request = Object.assign(new EventTarget(), { |
| 110 | result: undefined, |
| 111 | error: null, |
| 112 | }); |
| 113 | queueMicrotask(() => request.dispatchEvent(new Event("success"))); |
| 114 | return request; |
| 115 | }, |
| 116 | }), |
| 117 | }), |
| 118 | }) as unknown as IDBDatabase; |
| 119 | const first = makeDatabase(); |
| 120 | const second = makeDatabase(); |
| 121 | const databases = [first, second]; |
| 122 | let openCount = 0; |
| 123 | const open = vi.fn(() => { |
| 124 | const request = Object.assign(new EventTarget(), { |
| 125 | result: databases[openCount++], |
| 126 | error: null, |
| 127 | }); |
| 128 | queueMicrotask(() => request.dispatchEvent(new Event("success"))); |
| 129 | return request; |
| 130 | }); |
| 131 | vi.stubGlobal("indexedDB", { open }); |
| 132 | |
| 133 | yield* Effect.gen(function* () { |
| 134 | const cache = yield* Persistence.EnvironmentCacheStore; |
| 135 | const environmentId = EnvironmentId.make("env"); |
| 136 | const threadId = ThreadId.make("thread"); |
| 137 | expect(Option.isNone(yield* cache.loadThread(environmentId, threadId))).toBe(true); |
| 138 | expect(open).toHaveBeenCalledTimes(1); |
| 139 | |
| 140 | first.dispatchEvent(new Event("close")); |
| 141 | const recovered = yield* Effect.all( |
| 142 | [cache.loadThread(environmentId, threadId), cache.loadThread(environmentId, threadId)], |
| 143 | { concurrency: 2 }, |
| 144 | ); |
| 145 | expect(recovered.every(Option.isNone)).toBe(true); |
| 146 | expect(open).toHaveBeenCalledTimes(2); |
| 147 | }).pipe(Effect.provide(ConnectionStorage.layer)); |
| 148 | |
| 149 | expect(first.close).not.toHaveBeenCalled(); |
| 150 | expect(second.close).toHaveBeenCalledOnce(); |
| 151 | }), |
| 152 | ); |
| 153 | }); |
| 154 | |
| 155 | describe("IndexedDB connection closed without a close event", () => { |
| 156 | it.effect("reopens and retries the failing operation once", () => |
| 157 | Effect.gen(function* () { |
| 158 | vi.stubGlobal("window", {}); |
| 159 | const closing = Object.assign(new EventTarget(), { |
| 160 | close: vi.fn(), |
| 161 | transaction: () => { |
| 162 | // Chromium force-closed this connection; this tab never saw "close". |
| 163 | throw new DOMException("The database connection is closing.", "InvalidStateError"); |
| 164 | }, |
| 165 | }) as unknown as IDBDatabase; |
| 166 | const fresh = Object.assign(new EventTarget(), { |
| 167 | close: vi.fn(), |
| 168 | transaction: () => ({ |
| 169 | objectStore: () => ({ |
| 170 | get: () => { |
| 171 | const request = Object.assign(new EventTarget(), { result: undefined, error: null }); |
| 172 | queueMicrotask(() => request.dispatchEvent(new Event("success"))); |
| 173 | return request; |
| 174 | }, |
| 175 | }), |
| 176 | }), |
| 177 | }) as unknown as IDBDatabase; |
| 178 | const databases = [closing, fresh]; |
| 179 | let openCount = 0; |
| 180 | const open = vi.fn(() => { |
| 181 | const request = Object.assign(new EventTarget(), { |
| 182 | result: databases[openCount++], |
| 183 | error: null, |
| 184 | }); |
| 185 | queueMicrotask(() => request.dispatchEvent(new Event("success"))); |
| 186 | return request; |
| 187 | }); |
| 188 | vi.stubGlobal("indexedDB", { open }); |
| 189 | |
| 190 | yield* Effect.gen(function* () { |
| 191 | const cache = yield* Persistence.EnvironmentCacheStore; |
| 192 | const loaded = yield* cache.loadThread(EnvironmentId.make("env"), ThreadId.make("thread")); |
| 193 | expect(Option.isNone(loaded)).toBe(true); |
| 194 | expect(open).toHaveBeenCalledTimes(2); |
| 195 | }).pipe(Effect.provide(ConnectionStorage.layer)); |
| 196 | }), |
| 197 | ); |
| 198 | }); |
| 199 | |
| 200 | describe("browser GitHub routing permissions", () => { |
| 201 | it.effect("revokes across runtimes before storage events and resists stale catalog writes", () => |
| 202 | Effect.gen(function* () { |
| 203 | const values = new Map<string, string>(); |
| 204 | const localStorage: Storage = { |
| 205 | get length() { |
| 206 | return values.size; |
| 207 | }, |
| 208 | key: (index) => [...values.keys()][index] ?? null, |
| 209 | getItem: (key) => values.get(key) ?? null, |
| 210 | setItem: (key, value) => { |
| 211 | values.set(key, value); |
| 212 | }, |
| 213 | removeItem: (key) => { |
| 214 | values.delete(key); |
| 215 | }, |
| 216 | clear: () => { |
| 217 | values.clear(); |
| 218 | }, |
| 219 | }; |
| 220 | const firstBrowser = Object.assign(new EventTarget(), { localStorage }); |
| 221 | const secondBrowser = Object.assign(new EventTarget(), { localStorage }); |
| 222 | const first = ConnectionStorage.makeBrowserPullRequestRoutingPermissions(firstBrowser); |
| 223 | const second = ConnectionStorage.makeBrowserPullRequestRoutingPermissions(secondBrowser); |
| 224 | const entry = { |
| 225 | target: new PrimaryConnectionTarget({ |
| 226 | environmentId: EnvironmentId.make("first"), |
| 227 | label: "First", |
| 228 | httpBaseUrl: "http://localhost:3000", |
| 229 | wsBaseUrl: "ws://localhost:3000", |
| 230 | }), |
| 231 | profile: Option.none(), |
| 232 | enabled: true, |
| 233 | }; |
| 234 | const other = { |
| 235 | ...entry, |
| 236 | target: new PrimaryConnectionTarget({ |
| 237 | ...entry.target, |
| 238 | environmentId: EnvironmentId.make("second"), |
| 239 | }), |
| 240 | }; |
| 241 | expect(yield* first.get(entry)).toBe("off"); |
| 242 | yield* first.set(entry, "read-write"); |
| 243 | expect(yield* second.get(entry)).toBe("read-write"); |
| 244 | const oldPermissions = Option.getOrThrow(yield* Stream.runHead(first.changes)); |
| 245 | const staleCatalog = yield* ConnectionStorage.makeCatalogStore({ |
| 246 | read: Effect.succeed( |
| 247 | encodeCatalog({ ...emptyCatalog, githubRoutingPermissions: oldPermissions }), |
| 248 | ), |
| 249 | write: () => Effect.void, |
| 250 | }); |
| 251 | yield* staleCatalog.read; |
| 252 | const listening = yield* Deferred.make<void>(); |
| 253 | const revoked = yield* Deferred.make<void>(); |
| 254 | yield* second.changes.pipe( |
| 255 | Stream.runForEach((permissions) => |
| 256 | Deferred.succeed(permissions.length > 0 ? listening : revoked, undefined), |
| 257 | ), |
| 258 | Effect.forkChild, |
| 259 | ); |
| 260 | yield* Deferred.await(listening); |
| 261 | |
| 262 | yield* first.set(entry, "off"); |
| 263 | expect(yield* second.get(entry)).toBe("off"); |
| 264 | secondBrowser.dispatchEvent(Object.assign(new Event("storage"), { key: null })); |
| 265 | yield* Deferred.await(revoked); |
| 266 | yield* second.set(other, "read"); |
| 267 | yield* staleCatalog.update((document) => ({ ...document, accountId: "updated" })); |
| 268 | expect(yield* second.get(entry)).toBe("off"); |
| 269 | expect(yield* first.get(other)).toBe("read"); |
| 270 | expect( |
| 271 | yield* ConnectionStorage.makeBrowserPullRequestRoutingPermissions(firstBrowser).get(entry), |
| 272 | ).toBe("off"); |
| 273 | |
| 274 | yield* first.set(entry, "read-write"); |
| 275 | yield* second.forget(entry.target.environmentId); |
| 276 | expect(yield* first.get(entry)).toBe("off"); |
| 277 | expect(yield* first.get(other)).toBe("read"); |
| 278 | vi.spyOn(localStorage, "setItem").mockImplementation(() => { |
| 279 | throw new Error("Storage unavailable"); |
| 280 | }); |
| 281 | expect(yield* first.set(entry, "read-write").pipe(Effect.flip)).toBeInstanceOf( |
| 282 | ConnectionTransientError, |
| 283 | ); |
| 284 | expect(yield* second.get(entry)).toBe("off"); |
| 285 | }), |
| 286 | ); |
| 287 | }); |