@frockbot/plugin-provider-ollama-cloud 0.0.0 → 0.1.0

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.
@@ -0,0 +1,2230 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ createCredentialUserBackendContribution,
4
+ type CredentialStorage,
5
+ type CredentialTransaction,
6
+ } from "@frockbot/plugin-credentials/user";
7
+ import {
8
+ createUserSettingsBackendContribution,
9
+ type UserSettingsStorage,
10
+ type UserSettingsTransaction,
11
+ } from "@frockbot/plugin-settings/user";
12
+ import { OllamaCloudClient, type OllamaFetch } from "./client.js";
13
+ import {
14
+ createOllamaCloudUserBackendContribution,
15
+ selectAutomaticOllamaModelV1,
16
+ type OllamaUserBackendHost,
17
+ } from "./user.js";
18
+
19
+ class MemoryStorage implements UserSettingsStorage, CredentialStorage {
20
+ readonly values = new Map<string, unknown>();
21
+ alarm?: number;
22
+ failNextKey?: string;
23
+ failNextEntriesContaining?: string;
24
+ failNextGetKey?: string;
25
+ armGetFailureAfterEntriesContaining?: string;
26
+ armEntriesFailureAfterKey?: {
27
+ key: string;
28
+ entry: string;
29
+ };
30
+
31
+ get<T>(key: string): Promise<T | undefined> {
32
+ if (this.failNextGetKey === key) {
33
+ this.failNextGetKey = undefined;
34
+ return Promise.reject(new Error("injected storage read failure"));
35
+ }
36
+ return Promise.resolve(this.values.get(key) as T | undefined);
37
+ }
38
+
39
+ put<T>(key: string, value: T): Promise<void>;
40
+ put(entries: Record<string, unknown>): Promise<void>;
41
+ put<T>(
42
+ keyOrEntries: string | Record<string, unknown>,
43
+ value?: T,
44
+ ): Promise<void> {
45
+ if (typeof keyOrEntries === "string") {
46
+ if (this.failNextKey === keyOrEntries) {
47
+ this.failNextKey = undefined;
48
+ return Promise.reject(new Error("injected storage failure"));
49
+ }
50
+ this.values.set(keyOrEntries, value);
51
+ if (this.armEntriesFailureAfterKey?.key === keyOrEntries) {
52
+ this.failNextEntriesContaining = this.armEntriesFailureAfterKey.entry;
53
+ this.armEntriesFailureAfterKey = undefined;
54
+ }
55
+ } else {
56
+ if (
57
+ this.failNextEntriesContaining &&
58
+ Object.hasOwn(keyOrEntries, this.failNextEntriesContaining)
59
+ ) {
60
+ this.failNextEntriesContaining = undefined;
61
+ return Promise.reject(new Error("injected storage failure"));
62
+ }
63
+ for (const [key, entry] of Object.entries(keyOrEntries))
64
+ this.values.set(key, entry);
65
+ if (
66
+ this.armGetFailureAfterEntriesContaining &&
67
+ Object.hasOwn(keyOrEntries, this.armGetFailureAfterEntriesContaining)
68
+ ) {
69
+ this.armGetFailureAfterEntriesContaining = undefined;
70
+ this.failNextGetKey = "user-configuration";
71
+ }
72
+ }
73
+ return Promise.resolve();
74
+ }
75
+
76
+ delete(key: string): Promise<boolean> {
77
+ return Promise.resolve(this.values.delete(key));
78
+ }
79
+
80
+ async transaction<T>(
81
+ callback: (
82
+ storage: UserSettingsTransaction & CredentialTransaction,
83
+ ) => Promise<T>,
84
+ ): Promise<T> {
85
+ const before = new Map(this.values);
86
+ try {
87
+ return await callback(this);
88
+ } catch (error) {
89
+ this.values.clear();
90
+ for (const [key, value] of before) this.values.set(key, value);
91
+ throw error;
92
+ }
93
+ }
94
+
95
+ getAlarm(): Promise<number | null> {
96
+ return Promise.resolve(this.alarm ?? null);
97
+ }
98
+
99
+ setAlarm(scheduledTime: number | Date): Promise<void> {
100
+ this.alarm = Number(scheduledTime);
101
+ return Promise.resolve();
102
+ }
103
+ }
104
+
105
+ function keyring(): string {
106
+ const bytes = Uint8Array.from({ length: 32 }, (_, index) => index + 3);
107
+ let binary = "";
108
+ for (const byte of bytes) binary += String.fromCharCode(byte);
109
+ const key = btoa(binary)
110
+ .replaceAll("+", "-")
111
+ .replaceAll("/", "_")
112
+ .replace(/=+$/, "");
113
+ return JSON.stringify({
114
+ schemaVersion: 1,
115
+ currentKeyId: "primary",
116
+ keys: { primary: key },
117
+ });
118
+ }
119
+
120
+ async function fixture(
121
+ fetchOverride?: OllamaFetch,
122
+ now: () => number = () => Date.parse("2026-08-30T00:00:00.000Z"),
123
+ ) {
124
+ const storage = new MemoryStorage();
125
+ const settings = createUserSettingsBackendContribution({
126
+ storage,
127
+ availablePackages: [
128
+ { packageId: "provider-ollama-cloud", version: "0.0.1" },
129
+ ],
130
+ });
131
+ await settings.executeConfiguration({
132
+ schemaVersion: 1,
133
+ userId: "account-1",
134
+ command: {
135
+ schemaVersion: 1,
136
+ type: "user/install-package",
137
+ commandId: "install-1",
138
+ expectedRevision: 0,
139
+ packageId: "provider-ollama-cloud",
140
+ version: "0.0.1",
141
+ },
142
+ });
143
+ const credentials = createCredentialUserBackendContribution({
144
+ storage,
145
+ keyring: keyring(),
146
+ now,
147
+ });
148
+ let rejectCatalog = false;
149
+ const client = new OllamaCloudClient({
150
+ fetch:
151
+ fetchOverride ??
152
+ (async (input) => {
153
+ if (rejectCatalog) return new Response("invalid", { status: 401 });
154
+ const url = String(input);
155
+ return url.endsWith("/tags")
156
+ ? Response.json({ models: [{ model: "glm-5.3-flash:cloud" }] })
157
+ : Response.json({ capabilities: ["tools", "thinking"] });
158
+ }),
159
+ });
160
+ let id = 0;
161
+ const ollama = createOllamaCloudUserBackendContribution({
162
+ storage,
163
+ settings,
164
+ credentials: credentials as unknown as OllamaUserBackendHost["credentials"],
165
+ client,
166
+ now,
167
+ randomId: () => `id-${++id}`,
168
+ });
169
+ return {
170
+ storage,
171
+ settings,
172
+ credentials,
173
+ ollama,
174
+ rejectCatalog: () => {
175
+ rejectCatalog = true;
176
+ },
177
+ };
178
+ }
179
+
180
+ describe("Ollama Cloud User Contribution", () => {
181
+ test("rejects malformed durable account, command, and pending records", async () => {
182
+ const accountFixture = await fixture();
183
+ accountFixture.storage.values.set("ollama-connection-account", {
184
+ accountId: "account-1",
185
+ });
186
+ await expect(
187
+ accountFixture.ollama.executeConnection("account-1", {
188
+ schemaVersion: 1,
189
+ type: "connection/create-api-key",
190
+ commandId: "connect-malformed-account",
191
+ packageId: "provider-ollama-cloud",
192
+ connectionTypeId: "ollama-cloud-account",
193
+ label: "Work",
194
+ apiKey: "secret",
195
+ }),
196
+ ).rejects.toThrow("Stored Ollama account is invalid");
197
+
198
+ const commandFixture = await fixture();
199
+ const command = {
200
+ schemaVersion: 1,
201
+ type: "connection/create-api-key",
202
+ commandId: "connect-malformed-command",
203
+ packageId: "provider-ollama-cloud",
204
+ connectionTypeId: "ollama-cloud-account",
205
+ label: "Work",
206
+ apiKey: "secret",
207
+ } as const;
208
+ await commandFixture.ollama.executeConnection("account-1", command);
209
+ const commandKey = `ollama-connection-command:${command.commandId}`;
210
+ commandFixture.storage.values.set(commandKey, {
211
+ ...(commandFixture.storage.values.get(commandKey) as Record<
212
+ string,
213
+ unknown
214
+ >),
215
+ unexpected: true,
216
+ });
217
+ await expect(
218
+ commandFixture.ollama.executeConnection("account-1", command),
219
+ ).rejects.toThrow("Stored Ollama command is invalid");
220
+
221
+ const pendingFixture = await fixture();
222
+ pendingFixture.storage.values.set("ollama-pending-connection-commands", [
223
+ { commandId: "invalid" },
224
+ ]);
225
+ await expect(pendingFixture.ollama.alarm()).rejects.toThrow(
226
+ "commandId is invalid",
227
+ );
228
+ });
229
+
230
+ test("creates multiple account-scoped Connections with write-only credentials", async () => {
231
+ const { storage, settings, ollama } = await fixture();
232
+
233
+ const result = await ollama.executeConnection("account-1", {
234
+ schemaVersion: 1,
235
+ type: "connection/create-api-key",
236
+ commandId: "connect-1",
237
+ packageId: "provider-ollama-cloud",
238
+ connectionTypeId: "ollama-cloud-account",
239
+ label: "Work",
240
+ apiKey: "ollama-secret",
241
+ });
242
+
243
+ expect(result.status).toBe("applied");
244
+ const connection = (await settings.read("account-1")).connections[0];
245
+ expect(connection).toMatchObject({
246
+ connectionId: result.connectionId,
247
+ displayName: "Work",
248
+ state: "ready",
249
+ providerType: "ollama-cloud",
250
+ safeMetadata: { creationCommandId: "connect-1" },
251
+ authorization: { credential: { configured: true, writable: true } },
252
+ modelCatalog: {
253
+ state: "fresh",
254
+ models: [{ providerModelId: "glm-5.3-flash:cloud" }],
255
+ },
256
+ });
257
+ expect(await settings.read("account-1")).toMatchObject({
258
+ newBotModelTemplate: {
259
+ connectionId: result.connectionId,
260
+ providerModelId: "glm-5.3-flash:cloud",
261
+ },
262
+ newBotModelTemplateSource: "auto",
263
+ });
264
+ expect(JSON.stringify([...storage.values.values()])).not.toContain(
265
+ "ollama-secret",
266
+ );
267
+ });
268
+
269
+ test("never replaces a User-chosen default when a Connection succeeds", async () => {
270
+ const { settings, ollama } = await fixture();
271
+ const before = await settings.read("account-1");
272
+ await settings.executeConfiguration({
273
+ schemaVersion: 1,
274
+ userId: "account-1",
275
+ command: {
276
+ schemaVersion: 1,
277
+ type: "user/set-new-bot-model",
278
+ commandId: "choose-model",
279
+ expectedRevision: before.revision,
280
+ model: {
281
+ connectionId: "chosen-connection",
282
+ providerModelId: "chosen-model",
283
+ },
284
+ source: "user",
285
+ },
286
+ });
287
+
288
+ await ollama.executeConnection("account-1", {
289
+ schemaVersion: 1,
290
+ type: "connection/create-api-key",
291
+ commandId: "connect-after-choice",
292
+ packageId: "provider-ollama-cloud",
293
+ connectionTypeId: "ollama-cloud-account",
294
+ label: "Work",
295
+ apiKey: "ollama-secret",
296
+ });
297
+
298
+ expect(await settings.read("account-1")).toMatchObject({
299
+ newBotModelTemplate: {
300
+ connectionId: "chosen-connection",
301
+ providerModelId: "chosen-model",
302
+ },
303
+ newBotModelTemplateSource: "user",
304
+ });
305
+ });
306
+
307
+ test("prefers gpt-oss, then GLM, then the first catalog model", () => {
308
+ const model = (providerModelId: string) => ({
309
+ providerModelId,
310
+ displayName: providerModelId,
311
+ capabilities: { tools: true, vision: false, reasoning: true },
312
+ source: "discovered" as const,
313
+ });
314
+ const catalog = (ids: string[]) => ({
315
+ schemaVersion: 1 as const,
316
+ generation: "catalog-1",
317
+ state: "fresh" as const,
318
+ models: ids.map(model),
319
+ });
320
+ expect(
321
+ selectAutomaticOllamaModelV1(
322
+ catalog(["other", "glm-5.3-flash:cloud", "gpt-oss:20b"]),
323
+ )?.providerModelId,
324
+ ).toBe("gpt-oss:20b");
325
+ expect(
326
+ selectAutomaticOllamaModelV1(catalog(["other", "glm-5.3-flash:cloud"]))
327
+ ?.providerModelId,
328
+ ).toBe("glm-5.3-flash:cloud");
329
+ expect(
330
+ selectAutomaticOllamaModelV1(catalog(["other", "second"]))
331
+ ?.providerModelId,
332
+ ).toBe("other");
333
+ });
334
+
335
+ test("atomically admits the command, Connection, and encrypted credential", async () => {
336
+ const { storage, settings, ollama } = await fixture();
337
+ storage.failNextEntriesContaining =
338
+ "ollama-connection-command:connect-atomic";
339
+ const command = {
340
+ schemaVersion: 1,
341
+ type: "connection/create-api-key",
342
+ commandId: "connect-atomic",
343
+ packageId: "provider-ollama-cloud",
344
+ connectionTypeId: "ollama-cloud-account",
345
+ label: "Atomic",
346
+ apiKey: "valid-key",
347
+ } as const;
348
+
349
+ await expect(
350
+ ollama.executeConnection("account-1", command),
351
+ ).rejects.toThrow("injected storage failure");
352
+ expect((await settings.read("account-1")).connections).toEqual([]);
353
+
354
+ await expect(
355
+ ollama.executeConnection("account-1", command),
356
+ ).resolves.toMatchObject({
357
+ status: "applied",
358
+ });
359
+ });
360
+
361
+ test("projects durable Connection command receipts for hosted recovery", async () => {
362
+ const { ollama } = await fixture();
363
+ const receipt = await ollama.executeConnection("account-1", {
364
+ schemaVersion: 1,
365
+ type: "connection/create-api-key",
366
+ commandId: "connect-receipt-lookup",
367
+ packageId: "provider-ollama-cloud",
368
+ connectionTypeId: "ollama-cloud-account",
369
+ label: "Personal",
370
+ apiKey: "valid-key",
371
+ });
372
+
373
+ await expect(
374
+ ollama.lookupConnectionCommand("account-1", "connect-receipt-lookup"),
375
+ ).resolves.toEqual(receipt);
376
+ await expect(
377
+ ollama.lookupConnectionCommand("account-1", "unknown-command"),
378
+ ).resolves.toBeUndefined();
379
+ });
380
+
381
+ test("compacts command history without expiring idempotency", async () => {
382
+ const { settings, storage, ollama } = await fixture();
383
+ const created = await ollama.executeConnection("account-1", {
384
+ schemaVersion: 1,
385
+ type: "connection/create-api-key",
386
+ commandId: "connect-receipt-retention",
387
+ packageId: "provider-ollama-cloud",
388
+ connectionTypeId: "ollama-cloud-account",
389
+ label: "Original",
390
+ apiKey: "valid-key",
391
+ });
392
+ for (let index = 0; index < 257; index += 1) {
393
+ await ollama.executeConnection("account-1", {
394
+ schemaVersion: 1,
395
+ type: "connection/update-label",
396
+ commandId: `label-retention-${index}`,
397
+ connectionId: created.connectionId,
398
+ label: `Label ${index}`,
399
+ });
400
+ }
401
+
402
+ for (let index = 257; index < 383; index += 1) {
403
+ await ollama.executeConnection("account-1", {
404
+ schemaVersion: 1,
405
+ type: "connection/update-label",
406
+ commandId: `label-retention-${index}`,
407
+ connectionId: created.connectionId,
408
+ label: `Label ${index}`,
409
+ });
410
+ }
411
+
412
+ await expect(
413
+ ollama.lookupConnectionCommand("account-1", "connect-receipt-retention"),
414
+ ).resolves.toEqual(created);
415
+ await expect(
416
+ ollama.executeConnection("account-1", {
417
+ schemaVersion: 1,
418
+ type: "connection/create-api-key",
419
+ commandId: "connect-receipt-retention",
420
+ packageId: "provider-ollama-cloud",
421
+ connectionTypeId: "ollama-cloud-account",
422
+ label: "Original",
423
+ apiKey: "valid-key",
424
+ }),
425
+ ).resolves.toEqual(created);
426
+ expect((await settings.read("account-1")).connections).toHaveLength(1);
427
+ expect(
428
+ storage.values.has("ollama-connection-command:connect-receipt-retention"),
429
+ ).toBe(false);
430
+ expect(
431
+ storage.values.get("ollama-connection-command-tombstones"),
432
+ ).toHaveLength(128);
433
+ expect(
434
+ [...storage.values.keys()].filter((key) =>
435
+ key.startsWith("ollama-connection-command:"),
436
+ ),
437
+ ).toHaveLength(256);
438
+ await expect(
439
+ ollama.executeConnection("account-1", {
440
+ schemaVersion: 1,
441
+ type: "connection/update-label",
442
+ commandId: "label-history-over-capacity",
443
+ connectionId: created.connectionId,
444
+ label: "Over capacity",
445
+ }),
446
+ ).rejects.toThrow("Ollama Connection command history capacity reached");
447
+ });
448
+
449
+ test("bounds pending command admission before durable recovery grows", async () => {
450
+ const { storage, settings, ollama } = await fixture();
451
+ const created = await ollama.executeConnection("account-1", {
452
+ schemaVersion: 1,
453
+ type: "connection/create-api-key",
454
+ commandId: "connect-pending-limit",
455
+ packageId: "provider-ollama-cloud",
456
+ connectionTypeId: "ollama-cloud-account",
457
+ label: "Original",
458
+ apiKey: "valid-key",
459
+ });
460
+ storage.values.set(
461
+ "ollama-pending-connection-commands",
462
+ Array.from({ length: 64 }, (_, index) => `pending-${index}`),
463
+ );
464
+
465
+ await expect(
466
+ ollama.executeConnection("account-1", {
467
+ schemaVersion: 1,
468
+ type: "connection/update-label",
469
+ commandId: "label-over-capacity",
470
+ connectionId: created.connectionId,
471
+ label: "Changed",
472
+ }),
473
+ ).rejects.toThrow("Ollama Connection command capacity reached");
474
+ expect(
475
+ await settings.getConnection("account-1", created.connectionId),
476
+ ).toMatchObject({ displayName: "Original" });
477
+ expect(
478
+ storage.values.has("ollama-connection-command:label-over-capacity"),
479
+ ).toBe(false);
480
+ });
481
+
482
+ test("recovers one pending command per alarm", async () => {
483
+ const { storage, settings, ollama } = await fixture();
484
+ const created = await ollama.executeConnection("account-1", {
485
+ schemaVersion: 1,
486
+ type: "connection/create-api-key",
487
+ commandId: "connect-pending-recovery",
488
+ packageId: "provider-ollama-cloud",
489
+ connectionTypeId: "ollama-cloud-account",
490
+ label: "Original",
491
+ apiKey: "valid-key",
492
+ });
493
+ const connection = await settings.getConnection(
494
+ "account-1",
495
+ created.connectionId,
496
+ );
497
+ if (!connection?.generation) throw new Error("generation is missing");
498
+ storage.values.set("ollama-pending-connection-commands", [
499
+ "pending-label-1",
500
+ "pending-label-2",
501
+ ]);
502
+ for (const [index, commandId] of [
503
+ "pending-label-1",
504
+ "pending-label-2",
505
+ ].entries()) {
506
+ storage.values.set(`ollama-connection-command:${commandId}`, {
507
+ schemaVersion: 1,
508
+ commandId,
509
+ fingerprint: `fingerprint-${index}`,
510
+ accountId: "account-1",
511
+ connectionId: created.connectionId,
512
+ expectedGeneration: connection.generation,
513
+ operation: "connection/update-label",
514
+ label: `Recovered ${index + 1}`,
515
+ });
516
+ }
517
+
518
+ await ollama.alarm();
519
+ await expect(
520
+ ollama.lookupConnectionCommand("account-1", "pending-label-1"),
521
+ ).resolves.toMatchObject({ status: "applied" });
522
+ await expect(
523
+ ollama.lookupConnectionCommand("account-1", "pending-label-2"),
524
+ ).resolves.toBeUndefined();
525
+ expect(
526
+ await settings.getConnection("account-1", created.connectionId),
527
+ ).toMatchObject({ displayName: "Recovered 1" });
528
+
529
+ await ollama.alarm();
530
+ await expect(
531
+ ollama.lookupConnectionCommand("account-1", "pending-label-2"),
532
+ ).resolves.toMatchObject({ status: "applied" });
533
+ expect(
534
+ await settings.getConnection("account-1", created.connectionId),
535
+ ).toMatchObject({ displayName: "Recovered 2" });
536
+ });
537
+
538
+ test("keeps the active generation when rotation validation fails", async () => {
539
+ const { settings, ollama, rejectCatalog } = await fixture();
540
+ const created = await ollama.executeConnection("account-1", {
541
+ schemaVersion: 1,
542
+ type: "connection/create-api-key",
543
+ commandId: "connect-1",
544
+ packageId: "provider-ollama-cloud",
545
+ connectionTypeId: "ollama-cloud-account",
546
+ label: "Personal",
547
+ apiKey: "valid-key",
548
+ });
549
+ const before = (await settings.read("account-1")).connections[0];
550
+ rejectCatalog();
551
+
552
+ const rotated = await ollama.executeConnection("account-1", {
553
+ schemaVersion: 1,
554
+ type: "connection/rotate-api-key",
555
+ commandId: "rotate-1",
556
+ connectionId: created.connectionId,
557
+ apiKey: "invalid-key",
558
+ });
559
+
560
+ expect(rotated.status).toBe("failed");
561
+ expect((await settings.read("account-1")).connections[0]).toMatchObject({
562
+ state: "ready",
563
+ generation: before?.generation,
564
+ });
565
+ });
566
+
567
+ test("atomically promotes credentials with their Connection generation", async () => {
568
+ const { storage, settings, credentials, ollama } = await fixture();
569
+ const created = await ollama.executeConnection("account-1", {
570
+ schemaVersion: 1,
571
+ type: "connection/create-api-key",
572
+ commandId: "connect-1",
573
+ packageId: "provider-ollama-cloud",
574
+ connectionTypeId: "ollama-cloud-account",
575
+ label: "Personal",
576
+ apiKey: "old-key",
577
+ });
578
+ const before = (await settings.read("account-1")).connections[0];
579
+ if (!before?.generation) throw new Error("active generation is missing");
580
+ storage.failNextKey = "user-configuration";
581
+
582
+ const rotated = await ollama.executeConnection("account-1", {
583
+ schemaVersion: 1,
584
+ type: "connection/rotate-api-key",
585
+ commandId: "rotate-atomic",
586
+ connectionId: created.connectionId,
587
+ apiKey: "new-key",
588
+ });
589
+ const lease = await credentials.lease({
590
+ accountId: "account-1",
591
+ connectionId: created.connectionId,
592
+ packageId: "provider-ollama-cloud",
593
+ expectedGeneration: before.generation,
594
+ effectId: "effect-after-failure",
595
+ expiresAt: "2026-08-30T01:00:00.000Z",
596
+ });
597
+
598
+ expect(rotated.status).toBe("failed");
599
+ expect(lease.credentialGeneration).toBe(before.generation);
600
+ expect((await settings.read("account-1")).connections[0]?.generation).toBe(
601
+ before.generation,
602
+ );
603
+ });
604
+
605
+ test("retries staged validation settlement without repeating validation", async () => {
606
+ let catalogRequests = 0;
607
+ const { settings, credentials, ollama } = await fixture((input) => {
608
+ if (String(input).endsWith("/tags")) {
609
+ catalogRequests += 1;
610
+ return Promise.resolve(
611
+ Response.json({ models: [{ model: "glm-5.3-flash:cloud" }] }),
612
+ );
613
+ }
614
+ return Promise.resolve(Response.json({ capabilities: ["tools"] }));
615
+ });
616
+ const settle = credentials.settle.bind(credentials);
617
+ let settlementFailures = 1;
618
+ credentials.settle = (input) => {
619
+ if (
620
+ input.effectId === "validation:connect-validation-settlement" &&
621
+ settlementFailures > 0
622
+ ) {
623
+ settlementFailures -= 1;
624
+ return Promise.reject(new Error("settlement unavailable"));
625
+ }
626
+ return settle(input);
627
+ };
628
+ const command = {
629
+ schemaVersion: 1,
630
+ type: "connection/create-api-key",
631
+ commandId: "connect-validation-settlement",
632
+ packageId: "provider-ollama-cloud",
633
+ connectionTypeId: "ollama-cloud-account",
634
+ label: "Personal",
635
+ apiKey: "key",
636
+ } as const;
637
+
638
+ await expect(
639
+ ollama.executeConnection("account-1", command),
640
+ ).rejects.toThrow("settlement unavailable");
641
+ expect(catalogRequests).toBe(1);
642
+ expect((await settings.read("account-1")).connections[0]).toMatchObject({
643
+ state: "ready",
644
+ });
645
+
646
+ await expect(
647
+ ollama.executeConnection("account-1", command),
648
+ ).resolves.toMatchObject({ status: "applied" });
649
+ expect(catalogRequests).toBe(1);
650
+ await expect(
651
+ credentials.replayLease({
652
+ accountId: "account-1",
653
+ connectionId: (await settings.read("account-1")).connections[0]!
654
+ .connectionId,
655
+ packageId: "provider-ollama-cloud",
656
+ effectId: "validation:connect-validation-settlement",
657
+ }),
658
+ ).resolves.toBeUndefined();
659
+ });
660
+
661
+ test("replays successful activation when receipt finalization fails", async () => {
662
+ let storage: MemoryStorage | undefined;
663
+ const fixtureValue = await fixture(async (input, init) => {
664
+ const authorization = new Headers(init?.headers).get("authorization");
665
+ if (
666
+ authorization === "Bearer new-key" &&
667
+ String(input).endsWith("/tags")
668
+ ) {
669
+ storage!.failNextEntriesContaining =
670
+ "ollama-connection-command:rotate-finalize";
671
+ }
672
+ return String(input).endsWith("/tags")
673
+ ? Response.json({ models: [{ model: "glm-5.3-flash:cloud" }] })
674
+ : Response.json({ capabilities: ["tools"] });
675
+ });
676
+ storage = fixtureValue.storage;
677
+ const { settings, ollama } = fixtureValue;
678
+ const created = await ollama.executeConnection("account-1", {
679
+ schemaVersion: 1,
680
+ type: "connection/create-api-key",
681
+ commandId: "connect-1",
682
+ packageId: "provider-ollama-cloud",
683
+ connectionTypeId: "ollama-cloud-account",
684
+ label: "Personal",
685
+ apiKey: "old-key",
686
+ });
687
+ const command = {
688
+ schemaVersion: 1,
689
+ type: "connection/rotate-api-key",
690
+ commandId: "rotate-finalize",
691
+ connectionId: created.connectionId,
692
+ apiKey: "new-key",
693
+ } as const;
694
+
695
+ await expect(
696
+ ollama.executeConnection("account-1", command),
697
+ ).rejects.toThrow("injected storage failure");
698
+ const promoted = await settings.getConnection(
699
+ "account-1",
700
+ created.connectionId,
701
+ );
702
+ expect(promoted?.state).toBe("ready");
703
+ await expect(
704
+ ollama.executeConnection("account-1", command),
705
+ ).resolves.toMatchObject({ status: "applied" });
706
+ });
707
+
708
+ test("single-flights concurrent delivery through one validation effect", async () => {
709
+ const catalogStarted = Promise.withResolvers<void>();
710
+ const catalogResponse = Promise.withResolvers<Response>();
711
+ let catalogRequests = 0;
712
+ const { storage, ollama } = await fixture((input) => {
713
+ if (!String(input).endsWith("/tags")) {
714
+ return Promise.resolve(Response.json({ capabilities: ["tools"] }));
715
+ }
716
+ catalogRequests += 1;
717
+ catalogStarted.resolve();
718
+ return catalogResponse.promise;
719
+ });
720
+ const command = {
721
+ schemaVersion: 1,
722
+ type: "connection/create-api-key",
723
+ commandId: "connect-concurrent",
724
+ packageId: "provider-ollama-cloud",
725
+ connectionTypeId: "ollama-cloud-account",
726
+ label: "Personal",
727
+ apiKey: "secret",
728
+ } as const;
729
+
730
+ const first = ollama.executeConnection("account-1", command);
731
+ await catalogStarted.promise;
732
+ expect(
733
+ storage.values.get("ollama-connection-command:connect-concurrent"),
734
+ ).toMatchObject({ providerRetryPolicy: "safe-metadata-read" });
735
+ const second = ollama.executeConnection("account-1", command);
736
+ await new Promise((resolve) => setTimeout(resolve, 5));
737
+ expect(catalogRequests).toBe(1);
738
+ catalogResponse.resolve(
739
+ Response.json({ models: [{ model: "glm-5.3-flash:cloud" }] }),
740
+ );
741
+ const [firstReceipt, secondReceipt] = await Promise.all([first, second]);
742
+
743
+ expect(catalogRequests).toBe(1);
744
+ expect(firstReceipt.status).toBe("applied");
745
+ expect(secondReceipt).toEqual(firstReceipt);
746
+ });
747
+
748
+ test("does not let recovered mutations reverse newer commands", async () => {
749
+ const { storage, settings, ollama } = await fixture();
750
+ const created = await ollama.executeConnection("account-1", {
751
+ schemaVersion: 1,
752
+ type: "connection/create-api-key",
753
+ commandId: "connect-sequenced",
754
+ packageId: "provider-ollama-cloud",
755
+ connectionTypeId: "ollama-cloud-account",
756
+ label: "Original",
757
+ apiKey: "key",
758
+ });
759
+ storage.failNextKey = "user-configuration";
760
+ await expect(
761
+ ollama.executeConnection("account-1", {
762
+ schemaVersion: 1,
763
+ type: "connection/update-label",
764
+ commandId: "label-older",
765
+ connectionId: created.connectionId,
766
+ label: "Older",
767
+ }),
768
+ ).rejects.toThrow("injected storage failure");
769
+
770
+ await expect(
771
+ ollama.executeConnection("account-1", {
772
+ schemaVersion: 1,
773
+ type: "connection/update-label",
774
+ commandId: "label-newer",
775
+ connectionId: created.connectionId,
776
+ label: "Newer",
777
+ }),
778
+ ).resolves.toMatchObject({ status: "applied" });
779
+ await ollama.alarm();
780
+
781
+ expect(
782
+ await settings.getConnection("account-1", created.connectionId),
783
+ ).toMatchObject({ displayName: "Newer" });
784
+ expect(
785
+ storage.values.get("ollama-connection-command:label-older"),
786
+ ).toMatchObject({ receipt: { status: "failed" } });
787
+ });
788
+
789
+ test("recovers a committed sequenced mutation as applied", async () => {
790
+ const { storage, settings, ollama } = await fixture();
791
+ const created = await ollama.executeConnection("account-1", {
792
+ schemaVersion: 1,
793
+ type: "connection/create-api-key",
794
+ commandId: "connect-committed-label",
795
+ packageId: "provider-ollama-cloud",
796
+ connectionTypeId: "ollama-cloud-account",
797
+ label: "Original",
798
+ apiKey: "key",
799
+ });
800
+ storage.armEntriesFailureAfterKey = {
801
+ key: "user-configuration",
802
+ entry: "ollama-connection-command:label-committed",
803
+ };
804
+
805
+ await expect(
806
+ ollama.executeConnection("account-1", {
807
+ schemaVersion: 1,
808
+ type: "connection/update-label",
809
+ commandId: "label-committed",
810
+ connectionId: created.connectionId,
811
+ label: "Committed",
812
+ }),
813
+ ).rejects.toThrow("injected storage failure");
814
+ expect(
815
+ await settings.getConnection("account-1", created.connectionId),
816
+ ).toMatchObject({ displayName: "Committed" });
817
+
818
+ await ollama.alarm();
819
+
820
+ expect(
821
+ storage.values.get("ollama-connection-command:label-committed"),
822
+ ).toMatchObject({ receipt: { status: "applied" } });
823
+ });
824
+
825
+ test("recovers independent mutations with per-field ordering", async () => {
826
+ const { storage, settings, ollama } = await fixture();
827
+ const created = await ollama.executeConnection("account-1", {
828
+ schemaVersion: 1,
829
+ type: "connection/create-api-key",
830
+ commandId: "connect-independent-sequences",
831
+ packageId: "provider-ollama-cloud",
832
+ connectionTypeId: "ollama-cloud-account",
833
+ label: "Original",
834
+ apiKey: "key",
835
+ });
836
+ storage.failNextKey = "user-configuration";
837
+ await expect(
838
+ ollama.executeConnection("account-1", {
839
+ schemaVersion: 1,
840
+ type: "connection/set-enabled",
841
+ commandId: "disable-older",
842
+ connectionId: created.connectionId,
843
+ enabled: false,
844
+ }),
845
+ ).rejects.toThrow("injected storage failure");
846
+ await ollama.executeConnection("account-1", {
847
+ schemaVersion: 1,
848
+ type: "connection/update-label",
849
+ commandId: "label-independent",
850
+ connectionId: created.connectionId,
851
+ label: "Renamed",
852
+ });
853
+
854
+ await ollama.alarm();
855
+
856
+ expect(
857
+ await settings.getConnection("account-1", created.connectionId),
858
+ ).toMatchObject({ displayName: "Renamed", state: "disabled" });
859
+ });
860
+
861
+ test("preserves disabled state across credential rotation", async () => {
862
+ const { settings, ollama } = await fixture();
863
+ const created = await ollama.executeConnection("account-1", {
864
+ schemaVersion: 1,
865
+ type: "connection/create-api-key",
866
+ commandId: "connect-1",
867
+ packageId: "provider-ollama-cloud",
868
+ connectionTypeId: "ollama-cloud-account",
869
+ label: "Personal",
870
+ apiKey: "old-key",
871
+ });
872
+ await ollama.executeConnection("account-1", {
873
+ schemaVersion: 1,
874
+ type: "connection/set-enabled",
875
+ commandId: "disable-1",
876
+ connectionId: created.connectionId,
877
+ enabled: false,
878
+ });
879
+
880
+ const rotated = await ollama.executeConnection("account-1", {
881
+ schemaVersion: 1,
882
+ type: "connection/rotate-api-key",
883
+ commandId: "rotate-disabled",
884
+ connectionId: created.connectionId,
885
+ apiKey: "new-key",
886
+ });
887
+
888
+ expect(rotated.status).toBe("applied");
889
+ expect((await settings.read("account-1")).connections[0]?.state).toBe(
890
+ "disabled",
891
+ );
892
+ });
893
+
894
+ test("rejects disconnect while a Bot assignment depends on the Connection", async () => {
895
+ const { settings, ollama } = await fixture();
896
+ const created = await ollama.executeConnection("account-1", {
897
+ schemaVersion: 1,
898
+ type: "connection/create-api-key",
899
+ commandId: "connect-dependent",
900
+ packageId: "provider-ollama-cloud",
901
+ connectionTypeId: "ollama-cloud-account",
902
+ label: "Work",
903
+ apiKey: "key",
904
+ });
905
+ await settings.claimConnectionDependency(
906
+ "account-1",
907
+ created.connectionId,
908
+ "bot-1",
909
+ "assignment-1",
910
+ {
911
+ schemaVersion: 1,
912
+ packageId: "provider-ollama-cloud",
913
+ packageVersion: "0.0.1",
914
+ capabilityId: "ollama-cloud-models",
915
+ connectionTypeIds: ["ollama-cloud-account"],
916
+ },
917
+ );
918
+
919
+ await expect(
920
+ ollama.executeConnection("account-1", {
921
+ schemaVersion: 1,
922
+ type: "connection/disconnect",
923
+ commandId: "disconnect-dependent",
924
+ connectionId: created.connectionId,
925
+ revokeUpstream: false,
926
+ }),
927
+ ).resolves.toMatchObject({ status: "failed" });
928
+ expect(
929
+ await settings.getConnection("account-1", created.connectionId),
930
+ ).toMatchObject({ state: "ready" });
931
+ });
932
+
933
+ test("does not downgrade concurrent upstream revocation reconciliation", async () => {
934
+ const { settings, credentials, ollama } = await fixture();
935
+ const created = await ollama.executeConnection("account-1", {
936
+ schemaVersion: 1,
937
+ type: "connection/create-api-key",
938
+ commandId: "connect-disconnect-race",
939
+ packageId: "provider-ollama-cloud",
940
+ connectionTypeId: "ollama-cloud-account",
941
+ label: "Work",
942
+ apiKey: "key",
943
+ });
944
+ const firstStarted = Promise.withResolvers<void>();
945
+ const secondStarted = Promise.withResolvers<void>();
946
+ const releaseFirst = Promise.withResolvers<void>();
947
+ const releaseSecond = Promise.withResolvers<void>();
948
+ const disconnect = credentials.disconnect.bind(credentials);
949
+ let disconnectCalls = 0;
950
+ credentials.disconnect = async (connectionId) => {
951
+ disconnectCalls += 1;
952
+ const call = disconnectCalls;
953
+ if (call === 1) {
954
+ firstStarted.resolve();
955
+ await releaseFirst.promise;
956
+ } else {
957
+ secondStarted.resolve();
958
+ await releaseSecond.promise;
959
+ }
960
+ await disconnect(connectionId);
961
+ };
962
+
963
+ const upstream = ollama.executeConnection("account-1", {
964
+ schemaVersion: 1,
965
+ type: "connection/disconnect",
966
+ commandId: "disconnect-upstream",
967
+ connectionId: created.connectionId,
968
+ revokeUpstream: true,
969
+ });
970
+ await firstStarted.promise;
971
+ const local = ollama.executeConnection("account-1", {
972
+ schemaVersion: 1,
973
+ type: "connection/disconnect",
974
+ commandId: "disconnect-local",
975
+ connectionId: created.connectionId,
976
+ revokeUpstream: false,
977
+ });
978
+ await secondStarted.promise;
979
+ releaseFirst.resolve();
980
+ expect((await upstream).status).toBe("reconciliation-required");
981
+ releaseSecond.resolve();
982
+ expect((await local).status).toBe("reconciliation-required");
983
+ expect(
984
+ await settings.getConnection("account-1", created.connectionId),
985
+ ).toMatchObject({ state: "reconciliation-required" });
986
+ });
987
+
988
+ test("does not reactivate a Connection disconnected during authorization", async () => {
989
+ const catalogStarted = Promise.withResolvers<void>();
990
+ const catalogResponse = Promise.withResolvers<Response>();
991
+ let catalogRequests = 0;
992
+ const { settings, credentials, ollama } = await fixture(async (input) => {
993
+ if (String(input).endsWith("/tags")) {
994
+ catalogRequests += 1;
995
+ if (catalogRequests === 1) {
996
+ catalogStarted.resolve();
997
+ return catalogResponse.promise;
998
+ }
999
+ return Response.json({
1000
+ models: [{ model: "glm-5.3-flash:cloud" }],
1001
+ });
1002
+ }
1003
+ return Response.json({ capabilities: ["tools"] });
1004
+ });
1005
+ const creating = ollama.executeConnection("account-1", {
1006
+ schemaVersion: 1,
1007
+ type: "connection/create-api-key",
1008
+ commandId: "connect-race",
1009
+ packageId: "provider-ollama-cloud",
1010
+ connectionTypeId: "ollama-cloud-account",
1011
+ label: "Race",
1012
+ apiKey: "valid-key",
1013
+ });
1014
+ await catalogStarted.promise;
1015
+
1016
+ const disconnected = await ollama.executeConnection("account-1", {
1017
+ schemaVersion: 1,
1018
+ type: "connection/disconnect",
1019
+ commandId: "disconnect-race",
1020
+ connectionId: "connection-id-1",
1021
+ revokeUpstream: false,
1022
+ });
1023
+ const replacement = await ollama.executeConnection("account-1", {
1024
+ schemaVersion: 1,
1025
+ type: "connection/create-api-key",
1026
+ commandId: "connect-replacement",
1027
+ packageId: "provider-ollama-cloud",
1028
+ connectionTypeId: "ollama-cloud-account",
1029
+ label: "Replacement",
1030
+ apiKey: "replacement-key",
1031
+ });
1032
+ catalogResponse.resolve(
1033
+ Response.json({ models: [{ model: "glm-5.3-flash:cloud" }] }),
1034
+ );
1035
+
1036
+ expect(disconnected.status).toBe("applied");
1037
+ expect(replacement.status).toBe("applied");
1038
+ expect((await creating).status).toBe("failed");
1039
+ await expect(
1040
+ ollama.executeConnection("account-1", {
1041
+ schemaVersion: 1,
1042
+ type: "connection/create-api-key",
1043
+ commandId: "connect-race",
1044
+ packageId: "provider-ollama-cloud",
1045
+ connectionTypeId: "ollama-cloud-account",
1046
+ label: "Race",
1047
+ apiKey: "valid-key",
1048
+ }),
1049
+ ).resolves.toMatchObject({ status: "failed" });
1050
+ expect((await settings.read("account-1")).connections).toMatchObject([
1051
+ { connectionId: replacement.connectionId, state: "ready" },
1052
+ ]);
1053
+ await expect(
1054
+ credentials.readStagedApiKey({
1055
+ accountId: "account-1",
1056
+ connectionId: "connection-id-1",
1057
+ packageId: "provider-ollama-cloud",
1058
+ generation: "id-2",
1059
+ }),
1060
+ ).rejects.toThrow("Credential generation is unavailable");
1061
+ });
1062
+
1063
+ test("cancels pending credential rotation before revocation", async () => {
1064
+ const rotationStarted = Promise.withResolvers<void>();
1065
+ const rotationResponse = Promise.withResolvers<Response>();
1066
+ let catalogRequests = 0;
1067
+ const { settings, credentials, ollama } = await fixture(async (input) => {
1068
+ if (String(input).endsWith("/tags")) {
1069
+ catalogRequests += 1;
1070
+ if (catalogRequests === 2) {
1071
+ rotationStarted.resolve();
1072
+ return rotationResponse.promise;
1073
+ }
1074
+ return Response.json({
1075
+ models: [{ model: "glm-5.3-flash:cloud" }],
1076
+ });
1077
+ }
1078
+ return Response.json({ capabilities: ["tools"] });
1079
+ });
1080
+ const created = await ollama.executeConnection("account-1", {
1081
+ schemaVersion: 1,
1082
+ type: "connection/create-api-key",
1083
+ commandId: "connect-before-pending-rotation",
1084
+ packageId: "provider-ollama-cloud",
1085
+ connectionTypeId: "ollama-cloud-account",
1086
+ label: "Original",
1087
+ apiKey: "original-key",
1088
+ });
1089
+ const rotating = ollama.executeConnection("account-1", {
1090
+ schemaVersion: 1,
1091
+ type: "connection/rotate-api-key",
1092
+ commandId: "pending-rotation",
1093
+ connectionId: created.connectionId,
1094
+ apiKey: "pending-key",
1095
+ });
1096
+ await rotationStarted.promise;
1097
+
1098
+ const disconnected = await ollama.executeConnection("account-1", {
1099
+ schemaVersion: 1,
1100
+ type: "connection/disconnect",
1101
+ commandId: "disconnect-pending-rotation",
1102
+ connectionId: created.connectionId,
1103
+ revokeUpstream: false,
1104
+ });
1105
+ rotationResponse.resolve(
1106
+ Response.json({ models: [{ model: "glm-5.3-flash:cloud" }] }),
1107
+ );
1108
+
1109
+ expect(disconnected.status).toBe("applied");
1110
+ expect((await rotating).status).toBe("failed");
1111
+ const revoked = await settings.getConnection(
1112
+ "account-1",
1113
+ created.connectionId,
1114
+ );
1115
+ expect(revoked).toMatchObject({
1116
+ state: "revoked",
1117
+ authorization: {
1118
+ credential: { configured: false },
1119
+ },
1120
+ });
1121
+ expect(
1122
+ Object.hasOwn(revoked?.authorization?.credential ?? {}, "generation"),
1123
+ ).toBe(false);
1124
+ await expect(
1125
+ credentials.readStagedApiKey({
1126
+ accountId: "account-1",
1127
+ connectionId: created.connectionId,
1128
+ packageId: "provider-ollama-cloud",
1129
+ generation: "id-3",
1130
+ }),
1131
+ ).rejects.toThrow("Credential generation is unavailable");
1132
+ });
1133
+
1134
+ test("fails an interrupted disconnect after credential rotation", async () => {
1135
+ const { storage, settings, ollama } = await fixture();
1136
+ const created = await ollama.executeConnection("account-1", {
1137
+ schemaVersion: 1,
1138
+ type: "connection/create-api-key",
1139
+ commandId: "connect-1",
1140
+ packageId: "provider-ollama-cloud",
1141
+ connectionTypeId: "ollama-cloud-account",
1142
+ label: "Personal",
1143
+ apiKey: "old-key",
1144
+ });
1145
+ storage.armGetFailureAfterEntriesContaining =
1146
+ "ollama-connection-command:disconnect-stale";
1147
+ await expect(
1148
+ ollama.executeConnection("account-1", {
1149
+ schemaVersion: 1,
1150
+ type: "connection/disconnect",
1151
+ commandId: "disconnect-stale",
1152
+ connectionId: created.connectionId,
1153
+ revokeUpstream: false,
1154
+ }),
1155
+ ).rejects.toThrow("injected storage read failure");
1156
+
1157
+ const rotated = await ollama.executeConnection("account-1", {
1158
+ schemaVersion: 1,
1159
+ type: "connection/rotate-api-key",
1160
+ commandId: "rotate-after-disconnect",
1161
+ connectionId: created.connectionId,
1162
+ apiKey: "new-key",
1163
+ });
1164
+ const afterRotation = await settings.getConnection(
1165
+ "account-1",
1166
+ created.connectionId,
1167
+ );
1168
+ if (!afterRotation?.generation) {
1169
+ throw new Error("rotated generation is missing");
1170
+ }
1171
+ await ollama.alarm();
1172
+
1173
+ expect(rotated.status).toBe("applied");
1174
+ expect(
1175
+ await settings.getConnection("account-1", created.connectionId),
1176
+ ).toMatchObject({
1177
+ state: "ready",
1178
+ generation: afterRotation.generation,
1179
+ });
1180
+ });
1181
+
1182
+ test("does not project a stale catalog across credential rotation", async () => {
1183
+ const refreshStarted = Promise.withResolvers<void>();
1184
+ const refreshResponse = Promise.withResolvers<Response>();
1185
+ let oldTagRequests = 0;
1186
+ const { settings, ollama } = await fixture(async (input, init) => {
1187
+ if (!String(input).endsWith("/tags")) {
1188
+ return Response.json({ capabilities: ["tools"] });
1189
+ }
1190
+ const authorization = new Headers(init?.headers).get("authorization");
1191
+ if (authorization === "Bearer old-key") {
1192
+ oldTagRequests += 1;
1193
+ if (oldTagRequests === 2) {
1194
+ refreshStarted.resolve();
1195
+ return refreshResponse.promise;
1196
+ }
1197
+ return Response.json({ models: [{ model: "old-model:cloud" }] });
1198
+ }
1199
+ return Response.json({ models: [{ model: "new-model:cloud" }] });
1200
+ });
1201
+ const created = await ollama.executeConnection("account-1", {
1202
+ schemaVersion: 1,
1203
+ type: "connection/create-api-key",
1204
+ commandId: "connect-1",
1205
+ packageId: "provider-ollama-cloud",
1206
+ connectionTypeId: "ollama-cloud-account",
1207
+ label: "Personal",
1208
+ apiKey: "old-key",
1209
+ });
1210
+ const refreshing = ollama.executeConnection("account-1", {
1211
+ schemaVersion: 1,
1212
+ type: "connection/refresh-models",
1213
+ commandId: "refresh-stale",
1214
+ connectionId: created.connectionId,
1215
+ });
1216
+ await refreshStarted.promise;
1217
+ await ollama.executeConnection("account-1", {
1218
+ schemaVersion: 1,
1219
+ type: "connection/rotate-api-key",
1220
+ commandId: "rotate-during-refresh",
1221
+ connectionId: created.connectionId,
1222
+ apiKey: "new-key",
1223
+ });
1224
+ refreshResponse.resolve(
1225
+ Response.json({ models: [{ model: "stale-model:cloud" }] }),
1226
+ );
1227
+
1228
+ expect((await refreshing).status).toBe("failed");
1229
+ expect(
1230
+ (await settings.getConnection("account-1", created.connectionId))
1231
+ ?.modelCatalog?.models,
1232
+ ).toContainEqual(
1233
+ expect.objectContaining({ providerModelId: "new-model:cloud" }),
1234
+ );
1235
+ });
1236
+
1237
+ test("rejects catalog refresh before provider access without authority", async () => {
1238
+ let currentTime = Date.parse("2026-08-30T00:00:00.000Z");
1239
+ let providerRequests = 0;
1240
+ const { settings, ollama } = await fixture(
1241
+ (input) => {
1242
+ providerRequests += 1;
1243
+ return Promise.resolve(
1244
+ String(input).endsWith("/tags")
1245
+ ? Response.json({ models: [{ model: "glm-5.3-flash:cloud" }] })
1246
+ : Response.json({ capabilities: ["tools"] }),
1247
+ );
1248
+ },
1249
+ () => currentTime,
1250
+ );
1251
+ const created = await ollama.executeConnection("account-1", {
1252
+ schemaVersion: 1,
1253
+ type: "connection/create-api-key",
1254
+ commandId: "connect-refresh-authority",
1255
+ packageId: "provider-ollama-cloud",
1256
+ connectionTypeId: "ollama-cloud-account",
1257
+ label: "Personal",
1258
+ apiKey: "key",
1259
+ });
1260
+ await ollama.executeConnection("account-1", {
1261
+ schemaVersion: 1,
1262
+ type: "connection/set-enabled",
1263
+ commandId: "disable-connection",
1264
+ connectionId: created.connectionId,
1265
+ enabled: false,
1266
+ });
1267
+ const beforeDisabledRefresh = providerRequests;
1268
+
1269
+ await expect(
1270
+ ollama.executeConnection("account-1", {
1271
+ schemaVersion: 1,
1272
+ type: "connection/refresh-models",
1273
+ commandId: "refresh-disabled-connection",
1274
+ connectionId: created.connectionId,
1275
+ }),
1276
+ ).resolves.toMatchObject({ status: "failed" });
1277
+ expect(providerRequests).toBe(beforeDisabledRefresh);
1278
+
1279
+ await ollama.executeConnection("account-1", {
1280
+ schemaVersion: 1,
1281
+ type: "connection/set-enabled",
1282
+ commandId: "enable-connection",
1283
+ connectionId: created.connectionId,
1284
+ enabled: true,
1285
+ });
1286
+ const current = await settings.read("account-1");
1287
+ await settings.executeConfiguration({
1288
+ schemaVersion: 1,
1289
+ userId: "account-1",
1290
+ command: {
1291
+ schemaVersion: 1,
1292
+ type: "user/set-package-enabled",
1293
+ commandId: "disable-package-before-refresh",
1294
+ expectedRevision: current.revision,
1295
+ packageId: "provider-ollama-cloud",
1296
+ enabled: false,
1297
+ },
1298
+ });
1299
+ const beforePackageRefresh = providerRequests;
1300
+ const refreshAfter = (
1301
+ await settings.getConnection("account-1", created.connectionId)
1302
+ )?.modelCatalog?.refreshAfter;
1303
+ if (!refreshAfter) throw new Error("refresh deadline is missing");
1304
+ currentTime = Date.parse(refreshAfter);
1305
+ await ollama.alarm();
1306
+ expect(providerRequests).toBe(beforePackageRefresh);
1307
+
1308
+ await expect(
1309
+ ollama.executeConnection("account-1", {
1310
+ schemaVersion: 1,
1311
+ type: "connection/refresh-models",
1312
+ commandId: "refresh-disabled-package",
1313
+ connectionId: created.connectionId,
1314
+ }),
1315
+ ).resolves.toMatchObject({ status: "failed" });
1316
+ expect(providerRequests).toBe(beforePackageRefresh);
1317
+ });
1318
+
1319
+ test("does not let an older refresh overwrite a newer catalog", async () => {
1320
+ const older = Promise.withResolvers<Response>();
1321
+ const newer = Promise.withResolvers<Response>();
1322
+ const olderStarted = Promise.withResolvers<void>();
1323
+ const newerStarted = Promise.withResolvers<void>();
1324
+ let catalogRequests = 0;
1325
+ const { settings, ollama } = await fixture((input) => {
1326
+ if (!String(input).endsWith("/tags")) {
1327
+ return Promise.resolve(Response.json({ capabilities: ["tools"] }));
1328
+ }
1329
+ catalogRequests += 1;
1330
+ if (catalogRequests === 1) {
1331
+ return Promise.resolve(
1332
+ Response.json({ models: [{ model: "initial:cloud" }] }),
1333
+ );
1334
+ }
1335
+ if (catalogRequests === 2) {
1336
+ olderStarted.resolve();
1337
+ return older.promise;
1338
+ }
1339
+ newerStarted.resolve();
1340
+ return newer.promise;
1341
+ });
1342
+ const created = await ollama.executeConnection("account-1", {
1343
+ schemaVersion: 1,
1344
+ type: "connection/create-api-key",
1345
+ commandId: "connect-refresh-order",
1346
+ packageId: "provider-ollama-cloud",
1347
+ connectionTypeId: "ollama-cloud-account",
1348
+ label: "Personal",
1349
+ apiKey: "key",
1350
+ });
1351
+ const olderRefresh = ollama.executeConnection("account-1", {
1352
+ schemaVersion: 1,
1353
+ type: "connection/refresh-models",
1354
+ commandId: "refresh-older",
1355
+ connectionId: created.connectionId,
1356
+ });
1357
+ await olderStarted.promise;
1358
+ const newerRefresh = ollama.executeConnection("account-1", {
1359
+ schemaVersion: 1,
1360
+ type: "connection/refresh-models",
1361
+ commandId: "refresh-newer",
1362
+ connectionId: created.connectionId,
1363
+ });
1364
+ await newerStarted.promise;
1365
+ newer.resolve(Response.json({ models: [{ model: "newer:cloud" }] }));
1366
+ const newerReceipt = await newerRefresh;
1367
+ older.resolve(Response.json({ models: [{ model: "older:cloud" }] }));
1368
+ const olderReceipt = await olderRefresh;
1369
+
1370
+ expect(newerReceipt.status).toBe("applied");
1371
+ expect(olderReceipt.status).toBe("failed");
1372
+ const catalog = (
1373
+ await settings.getConnection("account-1", created.connectionId)
1374
+ )?.modelCatalog;
1375
+ expect(catalog?.models).toContainEqual(
1376
+ expect.objectContaining({ providerModelId: "newer:cloud" }),
1377
+ );
1378
+ expect(catalog?.models).not.toContainEqual(
1379
+ expect.objectContaining({ providerModelId: "older:cloud" }),
1380
+ );
1381
+ });
1382
+
1383
+ test("retries catalog lease settlement without repeating the catalog read", async () => {
1384
+ let catalogRequests = 0;
1385
+ const { credentials, ollama } = await fixture(async (input) => {
1386
+ if (String(input).endsWith("/tags")) {
1387
+ catalogRequests += 1;
1388
+ return Response.json({
1389
+ models: [{ model: "glm-5.3-flash:cloud" }],
1390
+ });
1391
+ }
1392
+ return Response.json({ capabilities: ["tools"] });
1393
+ });
1394
+ const created = await ollama.executeConnection("account-1", {
1395
+ schemaVersion: 1,
1396
+ type: "connection/create-api-key",
1397
+ commandId: "connect-settlement-retry",
1398
+ packageId: "provider-ollama-cloud",
1399
+ connectionTypeId: "ollama-cloud-account",
1400
+ label: "Personal",
1401
+ apiKey: "key",
1402
+ });
1403
+ const beforeRefresh = catalogRequests;
1404
+ const settle = credentials.settle.bind(credentials);
1405
+ let settlementFailures = 1;
1406
+ credentials.settle = (input) => {
1407
+ if (settlementFailures > 0) {
1408
+ settlementFailures -= 1;
1409
+ return Promise.reject(new Error("settlement unavailable"));
1410
+ }
1411
+ return settle(input);
1412
+ };
1413
+
1414
+ await expect(
1415
+ ollama.executeConnection("account-1", {
1416
+ schemaVersion: 1,
1417
+ type: "connection/refresh-models",
1418
+ commandId: "refresh-settlement-retry",
1419
+ connectionId: created.connectionId,
1420
+ }),
1421
+ ).rejects.toThrow("settlement unavailable");
1422
+ expect(catalogRequests).toBe(beforeRefresh + 1);
1423
+ await expect(
1424
+ ollama.lookupConnectionCommand("account-1", "refresh-settlement-retry"),
1425
+ ).resolves.toBeUndefined();
1426
+
1427
+ await ollama.alarm();
1428
+
1429
+ expect(catalogRequests).toBe(beforeRefresh + 1);
1430
+ await expect(
1431
+ ollama.lookupConnectionCommand("account-1", "refresh-settlement-retry"),
1432
+ ).resolves.toMatchObject({ status: "applied" });
1433
+ });
1434
+
1435
+ test("commits catalog outcomes atomically with settlement recovery", async () => {
1436
+ let storageRef: MemoryStorage | undefined;
1437
+ let failOutcomeCommit = false;
1438
+ let catalogRequests = 0;
1439
+ const fixtureValue = await fixture(async (input) => {
1440
+ if (String(input).endsWith("/tags")) {
1441
+ catalogRequests += 1;
1442
+ if (failOutcomeCommit) {
1443
+ storageRef!.failNextKey =
1444
+ "ollama-connection-command:refresh-atomic-outcome";
1445
+ failOutcomeCommit = false;
1446
+ }
1447
+ return Response.json({
1448
+ models: [{ model: `model-${catalogRequests}:cloud` }],
1449
+ });
1450
+ }
1451
+ return Response.json({ capabilities: ["tools"] });
1452
+ });
1453
+ const { storage, settings, ollama } = fixtureValue;
1454
+ storageRef = storage;
1455
+ const created = await ollama.executeConnection("account-1", {
1456
+ schemaVersion: 1,
1457
+ type: "connection/create-api-key",
1458
+ commandId: "connect-atomic-outcome",
1459
+ packageId: "provider-ollama-cloud",
1460
+ connectionTypeId: "ollama-cloud-account",
1461
+ label: "Personal",
1462
+ apiKey: "key",
1463
+ });
1464
+ const before = await settings.getConnection(
1465
+ "account-1",
1466
+ created.connectionId,
1467
+ );
1468
+ failOutcomeCommit = true;
1469
+
1470
+ await expect(
1471
+ ollama.executeConnection("account-1", {
1472
+ schemaVersion: 1,
1473
+ type: "connection/refresh-models",
1474
+ commandId: "refresh-atomic-outcome",
1475
+ connectionId: created.connectionId,
1476
+ }),
1477
+ ).rejects.toThrow("injected storage failure");
1478
+
1479
+ expect(
1480
+ (await settings.getConnection("account-1", created.connectionId))
1481
+ ?.modelCatalog?.generation,
1482
+ ).toBe(before?.modelCatalog?.generation);
1483
+ await ollama.alarm();
1484
+ expect(catalogRequests).toBe(3);
1485
+ await expect(
1486
+ ollama.lookupConnectionCommand("account-1", "refresh-atomic-outcome"),
1487
+ ).resolves.toMatchObject({ status: "applied" });
1488
+ });
1489
+
1490
+ test("compacts automatic refresh commands into one durable receipt", async () => {
1491
+ let currentTime = Date.parse("2026-08-30T00:00:00.000Z");
1492
+ const { storage, settings, ollama } = await fixture(
1493
+ undefined,
1494
+ () => currentTime,
1495
+ );
1496
+ const created = await ollama.executeConnection("account-1", {
1497
+ schemaVersion: 1,
1498
+ type: "connection/create-api-key",
1499
+ commandId: "connect-refresh-compaction",
1500
+ packageId: "provider-ollama-cloud",
1501
+ connectionTypeId: "ollama-cloud-account",
1502
+ label: "Personal",
1503
+ apiKey: "key",
1504
+ });
1505
+ const firstDeadline = (
1506
+ await settings.getConnection("account-1", created.connectionId)
1507
+ )?.modelCatalog?.refreshAfter;
1508
+ if (!firstDeadline) throw new Error("refresh deadline is missing");
1509
+ currentTime = Date.parse(firstDeadline);
1510
+
1511
+ await ollama.alarm();
1512
+ const receiptKey = `ollama-refresh-receipt:${created.connectionId}`;
1513
+ const firstReceipt = storage.values.get(receiptKey) as
1514
+ { commandId: string; status: string } | undefined;
1515
+ expect(firstReceipt?.status).toBe("applied");
1516
+ expect(
1517
+ [...storage.values.keys()].filter((key) =>
1518
+ key.startsWith("ollama-connection-command:refresh-"),
1519
+ ),
1520
+ ).toEqual([]);
1521
+
1522
+ const secondDeadline = (
1523
+ await settings.getConnection("account-1", created.connectionId)
1524
+ )?.modelCatalog?.refreshAfter;
1525
+ if (!secondDeadline) throw new Error("refresh deadline is missing");
1526
+ currentTime = Date.parse(secondDeadline);
1527
+ await ollama.alarm();
1528
+ const secondReceipt = storage.values.get(receiptKey) as
1529
+ { commandId: string; status: string } | undefined;
1530
+
1531
+ expect(secondReceipt?.status).toBe("applied");
1532
+ expect(secondReceipt?.commandId).not.toBe(firstReceipt?.commandId);
1533
+ expect(
1534
+ [...storage.values.keys()].filter((key) =>
1535
+ key.startsWith("ollama-refresh-receipt:"),
1536
+ ),
1537
+ ).toEqual([receiptKey]);
1538
+ });
1539
+
1540
+ test("refreshes one due Connection per recovery alarm", async () => {
1541
+ let currentTime = Date.parse("2026-08-30T00:00:00.000Z");
1542
+ let catalogRequests = 0;
1543
+ const { settings, ollama } = await fixture(
1544
+ async (input) => {
1545
+ if (String(input).endsWith("/tags")) {
1546
+ catalogRequests += 1;
1547
+ return Response.json({
1548
+ models: [{ model: "glm-5.3-flash:cloud" }],
1549
+ });
1550
+ }
1551
+ return Response.json({ capabilities: ["tools"] });
1552
+ },
1553
+ () => currentTime,
1554
+ );
1555
+ for (const suffix of ["one", "two"]) {
1556
+ await ollama.executeConnection("account-1", {
1557
+ schemaVersion: 1,
1558
+ type: "connection/create-api-key",
1559
+ commandId: `connect-alarm-${suffix}`,
1560
+ packageId: "provider-ollama-cloud",
1561
+ connectionTypeId: "ollama-cloud-account",
1562
+ label: suffix,
1563
+ apiKey: `${suffix}-key`,
1564
+ });
1565
+ }
1566
+ const refreshAfter = (await settings.read("account-1")).connections[0]
1567
+ ?.modelCatalog?.refreshAfter;
1568
+ if (!refreshAfter) throw new Error("refresh deadline is missing");
1569
+ currentTime = Date.parse(refreshAfter);
1570
+
1571
+ await ollama.alarm();
1572
+ expect(catalogRequests).toBe(3);
1573
+ await ollama.alarm();
1574
+ expect(catalogRequests).toBe(4);
1575
+ });
1576
+
1577
+ test("terminally fails an admitted create whose credential was never sealed", async () => {
1578
+ const { storage, settings, ollama } = await fixture();
1579
+ storage.values.set("ollama-connection-account", "account-1");
1580
+ storage.values.set("ollama-pending-connection-commands", [
1581
+ "connect-crashed",
1582
+ ]);
1583
+ storage.values.set("ollama-connection-command:connect-crashed", {
1584
+ schemaVersion: 1,
1585
+ commandId: "connect-crashed",
1586
+ fingerprint: "admitted",
1587
+ accountId: "account-1",
1588
+ connectionId: "connection-crashed",
1589
+ credentialGeneration: "generation-crashed",
1590
+ operation: "connection/create-api-key",
1591
+ label: "Recovered",
1592
+ });
1593
+
1594
+ await ollama.alarm();
1595
+
1596
+ expect(
1597
+ await settings.getConnection("account-1", "connection-crashed"),
1598
+ ).toMatchObject({ state: "failed", displayName: "Recovered" });
1599
+ expect(storage.values.get("ollama-pending-connection-commands")).toEqual(
1600
+ [],
1601
+ );
1602
+ });
1603
+
1604
+ test("rejects exact model authorization when Connection state changes", async () => {
1605
+ const resolutionStarted = Promise.withResolvers<void>();
1606
+ const resolutionResponse = Promise.withResolvers<Response>();
1607
+ const { settings, ollama } = await fixture(async (input, init) => {
1608
+ if (String(input).endsWith("/tags")) {
1609
+ return Response.json({
1610
+ models: [{ model: "glm-5.3-flash:cloud" }],
1611
+ });
1612
+ }
1613
+ const body = JSON.parse(String(init?.body)) as { model: string };
1614
+ if (body.model === "new-model:cloud") {
1615
+ resolutionStarted.resolve();
1616
+ return resolutionResponse.promise;
1617
+ }
1618
+ return Response.json({ capabilities: ["tools"] });
1619
+ });
1620
+ const created = await ollama.executeConnection("account-1", {
1621
+ schemaVersion: 1,
1622
+ type: "connection/create-api-key",
1623
+ commandId: "connect-1",
1624
+ packageId: "provider-ollama-cloud",
1625
+ connectionTypeId: "ollama-cloud-account",
1626
+ label: "Personal",
1627
+ apiKey: "valid-key",
1628
+ });
1629
+ const connection = await settings.getConnection(
1630
+ "account-1",
1631
+ created.connectionId,
1632
+ );
1633
+ if (!connection?.generation) throw new Error("generation is missing");
1634
+ const authorization = ollama.leaseModelCredential({
1635
+ accountId: "account-1",
1636
+ connectionId: created.connectionId,
1637
+ providerModelId: "new-model:cloud",
1638
+ effectId: "effect-race",
1639
+ connectionGeneration: connection.generation,
1640
+ });
1641
+ await resolutionStarted.promise;
1642
+ await ollama.executeConnection("account-1", {
1643
+ schemaVersion: 1,
1644
+ type: "connection/set-enabled",
1645
+ commandId: "disable-race",
1646
+ connectionId: created.connectionId,
1647
+ enabled: false,
1648
+ });
1649
+ resolutionResponse.resolve(Response.json({ capabilities: ["tools"] }));
1650
+
1651
+ await expect(authorization).rejects.toThrow(
1652
+ "Connection changed before model authorization",
1653
+ );
1654
+ });
1655
+
1656
+ test("journals safe exact-resolution retry before provider metadata", async () => {
1657
+ let storage: MemoryStorage | undefined;
1658
+ let resolutionRequests = 0;
1659
+ let failOutcomeWrite = true;
1660
+ const fixtureValue = await fixture((input, init) => {
1661
+ if (String(input).endsWith("/tags")) {
1662
+ return Promise.resolve(
1663
+ Response.json({ models: [{ model: "known:cloud" }] }),
1664
+ );
1665
+ }
1666
+ const body = JSON.parse(String(init?.body)) as { model: string };
1667
+ if (body.model === "new-model:cloud") {
1668
+ resolutionRequests += 1;
1669
+ if (failOutcomeWrite) {
1670
+ failOutcomeWrite = false;
1671
+ storage!.failNextKey =
1672
+ "ollama-model-resolution:effect-safe-resolution";
1673
+ }
1674
+ }
1675
+ return Promise.resolve(Response.json({ capabilities: ["tools"] }));
1676
+ });
1677
+ storage = fixtureValue.storage;
1678
+ const { settings, ollama } = fixtureValue;
1679
+ const created = await ollama.executeConnection("account-1", {
1680
+ schemaVersion: 1,
1681
+ type: "connection/create-api-key",
1682
+ commandId: "connect-safe-resolution",
1683
+ packageId: "provider-ollama-cloud",
1684
+ connectionTypeId: "ollama-cloud-account",
1685
+ label: "Personal",
1686
+ apiKey: "valid-key",
1687
+ });
1688
+ const connection = await settings.getConnection(
1689
+ "account-1",
1690
+ created.connectionId,
1691
+ );
1692
+ if (!connection?.generation) throw new Error("generation is missing");
1693
+ const input = {
1694
+ accountId: "account-1",
1695
+ connectionId: created.connectionId,
1696
+ providerModelId: "new-model:cloud",
1697
+ effectId: "effect-safe-resolution",
1698
+ connectionGeneration: connection.generation,
1699
+ };
1700
+
1701
+ await expect(ollama.leaseModelCredential(input)).rejects.toThrow(
1702
+ "injected storage failure",
1703
+ );
1704
+ expect(
1705
+ storage.values.get("ollama-model-resolution:effect-safe-resolution"),
1706
+ ).toMatchObject({
1707
+ retryPolicy: "safe-metadata-read",
1708
+ status: "pending",
1709
+ });
1710
+ await expect(ollama.leaseModelCredential(input)).resolves.toMatchObject({
1711
+ effectId: "effect-safe-resolution",
1712
+ });
1713
+ expect(resolutionRequests).toBe(2);
1714
+ expect(
1715
+ storage.values.has("ollama-model-resolution:effect-safe-resolution"),
1716
+ ).toBe(false);
1717
+ });
1718
+
1719
+ test("advances catalog generation after exact model resolution", async () => {
1720
+ const { settings, ollama } = await fixture();
1721
+ const created = await ollama.executeConnection("account-1", {
1722
+ schemaVersion: 1,
1723
+ type: "connection/create-api-key",
1724
+ commandId: "connect-1",
1725
+ packageId: "provider-ollama-cloud",
1726
+ connectionTypeId: "ollama-cloud-account",
1727
+ label: "Personal",
1728
+ apiKey: "valid-key",
1729
+ });
1730
+ const before = await settings.getConnection(
1731
+ "account-1",
1732
+ created.connectionId,
1733
+ );
1734
+
1735
+ if (!before?.generation) throw new Error("generation is missing");
1736
+ await ollama.leaseModelCredential({
1737
+ accountId: "account-1",
1738
+ connectionId: created.connectionId,
1739
+ providerModelId: "new-model:cloud",
1740
+ effectId: "effect-resolution",
1741
+ connectionGeneration: before.generation,
1742
+ });
1743
+ const after = await settings.getConnection(
1744
+ "account-1",
1745
+ created.connectionId,
1746
+ );
1747
+
1748
+ expect(after?.modelCatalog?.generation).not.toBe(
1749
+ before?.modelCatalog?.generation,
1750
+ );
1751
+ expect(after?.modelCatalog?.models).toContainEqual(
1752
+ expect.objectContaining({ providerModelId: "new-model:cloud" }),
1753
+ );
1754
+ });
1755
+
1756
+ test("settles a failed exact-resolution lease from model outcome recovery", async () => {
1757
+ const { settings, credentials, ollama } = await fixture();
1758
+ const created = await ollama.executeConnection("account-1", {
1759
+ schemaVersion: 1,
1760
+ type: "connection/create-api-key",
1761
+ commandId: "connect-resolution-settlement",
1762
+ packageId: "provider-ollama-cloud",
1763
+ connectionTypeId: "ollama-cloud-account",
1764
+ label: "Work",
1765
+ apiKey: "valid-key",
1766
+ });
1767
+ const connection = await settings.getConnection(
1768
+ "account-1",
1769
+ created.connectionId,
1770
+ );
1771
+ if (!connection?.generation) throw new Error("generation is missing");
1772
+ const settle = credentials.settle.bind(credentials);
1773
+ let failResolutionSettlement = true;
1774
+ credentials.settle = (input) => {
1775
+ if (
1776
+ failResolutionSettlement &&
1777
+ input.effectId === "resolve:resolution-outcome"
1778
+ ) {
1779
+ failResolutionSettlement = false;
1780
+ return Promise.reject(new Error("settlement unavailable"));
1781
+ }
1782
+ return settle(input);
1783
+ };
1784
+
1785
+ await expect(
1786
+ ollama.leaseModelCredential({
1787
+ accountId: "account-1",
1788
+ connectionId: created.connectionId,
1789
+ providerModelId: "uncatalogued:cloud",
1790
+ effectId: "resolution-outcome",
1791
+ connectionGeneration: connection.generation,
1792
+ }),
1793
+ ).rejects.toThrow("settlement unavailable");
1794
+ await expect(
1795
+ credentials.replayLease({
1796
+ accountId: "account-1",
1797
+ connectionId: created.connectionId,
1798
+ packageId: "provider-ollama-cloud",
1799
+ effectId: "resolve:resolution-outcome",
1800
+ }),
1801
+ ).resolves.toBeDefined();
1802
+
1803
+ await ollama.settleModelCredential({
1804
+ accountId: "account-1",
1805
+ connectionId: created.connectionId,
1806
+ effectId: "resolution-outcome",
1807
+ });
1808
+
1809
+ await expect(
1810
+ credentials.replayLease({
1811
+ accountId: "account-1",
1812
+ connectionId: created.connectionId,
1813
+ packageId: "provider-ollama-cloud",
1814
+ effectId: "resolve:resolution-outcome",
1815
+ }),
1816
+ ).resolves.toBeUndefined();
1817
+ });
1818
+
1819
+ test("bounds retained exact models while preserving discovered models", async () => {
1820
+ const { settings, ollama } = await fixture();
1821
+ const created = await ollama.executeConnection("account-1", {
1822
+ schemaVersion: 1,
1823
+ type: "connection/create-api-key",
1824
+ commandId: "connect-model-retention",
1825
+ packageId: "provider-ollama-cloud",
1826
+ connectionTypeId: "ollama-cloud-account",
1827
+ label: "Work",
1828
+ apiKey: "valid-key",
1829
+ });
1830
+ const connection = await settings.getConnection(
1831
+ "account-1",
1832
+ created.connectionId,
1833
+ );
1834
+ if (!connection?.generation) throw new Error("generation is missing");
1835
+
1836
+ for (let index = 0; index < 105; index += 1) {
1837
+ const effectId = `exact-retention-${index}`;
1838
+ await ollama.leaseModelCredential({
1839
+ accountId: "account-1",
1840
+ connectionId: created.connectionId,
1841
+ providerModelId: `exact-${index}:cloud`,
1842
+ effectId,
1843
+ connectionGeneration: connection.generation,
1844
+ });
1845
+ await ollama.settleModelCredential({
1846
+ accountId: "account-1",
1847
+ connectionId: created.connectionId,
1848
+ effectId,
1849
+ });
1850
+ }
1851
+ const models = (
1852
+ await settings.getConnection("account-1", created.connectionId)
1853
+ )?.modelCatalog?.models;
1854
+
1855
+ expect(models).toHaveLength(100);
1856
+ expect(models).toContainEqual(
1857
+ expect.objectContaining({ providerModelId: "glm-5.3-flash:cloud" }),
1858
+ );
1859
+ expect(models).toContainEqual(
1860
+ expect.objectContaining({ providerModelId: "exact-104:cloud" }),
1861
+ );
1862
+ expect(models).not.toContainEqual(
1863
+ expect.objectContaining({ providerModelId: "exact-0:cloud" }),
1864
+ );
1865
+ });
1866
+
1867
+ test("reserves exact-model capacity in a full discovered catalog", async () => {
1868
+ let showRequests = 0;
1869
+ const { settings, ollama } = await fixture((input) => {
1870
+ if (String(input).endsWith("/tags")) {
1871
+ return Promise.resolve(
1872
+ Response.json({
1873
+ models: Array.from({ length: 100 }, (_, index) => ({
1874
+ model: `discovered-${index}:cloud`,
1875
+ })),
1876
+ }),
1877
+ );
1878
+ }
1879
+ showRequests += 1;
1880
+ return Promise.resolve(Response.json({ capabilities: ["tools"] }));
1881
+ });
1882
+ const created = await ollama.executeConnection("account-1", {
1883
+ schemaVersion: 1,
1884
+ type: "connection/create-api-key",
1885
+ commandId: "connect-full-catalog",
1886
+ packageId: "provider-ollama-cloud",
1887
+ connectionTypeId: "ollama-cloud-account",
1888
+ label: "Work",
1889
+ apiKey: "valid-key",
1890
+ });
1891
+ const connection = await settings.getConnection(
1892
+ "account-1",
1893
+ created.connectionId,
1894
+ );
1895
+ if (!connection?.generation) throw new Error("generation is missing");
1896
+ const baselineShowRequests = showRequests;
1897
+
1898
+ for (const effectId of ["full-exact-1", "full-exact-2"]) {
1899
+ await ollama.leaseModelCredential({
1900
+ accountId: "account-1",
1901
+ connectionId: created.connectionId,
1902
+ providerModelId: "uncatalogued:cloud",
1903
+ effectId,
1904
+ connectionGeneration: connection.generation,
1905
+ });
1906
+ await ollama.settleModelCredential({
1907
+ accountId: "account-1",
1908
+ connectionId: created.connectionId,
1909
+ effectId,
1910
+ });
1911
+ }
1912
+ const models = (
1913
+ await settings.getConnection("account-1", created.connectionId)
1914
+ )?.modelCatalog?.models;
1915
+
1916
+ expect(showRequests - baselineShowRequests).toBe(1);
1917
+ expect(models).toHaveLength(91);
1918
+ expect(models).toContainEqual(
1919
+ expect.objectContaining({ providerModelId: "uncatalogued:cloud" }),
1920
+ );
1921
+ });
1922
+
1923
+ test("rejects a journaled credential generation after rotation", async () => {
1924
+ const { settings, ollama } = await fixture();
1925
+ const created = await ollama.executeConnection("account-1", {
1926
+ schemaVersion: 1,
1927
+ type: "connection/create-api-key",
1928
+ commandId: "connect-1",
1929
+ packageId: "provider-ollama-cloud",
1930
+ connectionTypeId: "ollama-cloud-account",
1931
+ label: "Work",
1932
+ apiKey: "old-key",
1933
+ });
1934
+ const before = await settings.getConnection(
1935
+ "account-1",
1936
+ created.connectionId,
1937
+ );
1938
+ if (!before?.generation) throw new Error("generation is missing");
1939
+ await ollama.executeConnection("account-1", {
1940
+ schemaVersion: 1,
1941
+ type: "connection/rotate-api-key",
1942
+ commandId: "rotate-before-lease",
1943
+ connectionId: created.connectionId,
1944
+ apiKey: "new-key",
1945
+ });
1946
+
1947
+ await expect(
1948
+ ollama.leaseModelCredential({
1949
+ accountId: "account-1",
1950
+ connectionId: created.connectionId,
1951
+ providerModelId: "glm-5.3-flash:cloud",
1952
+ effectId: "journaled-effect",
1953
+ connectionGeneration: before.generation,
1954
+ }),
1955
+ ).rejects.toThrow("Connection changed before model authorization");
1956
+ });
1957
+
1958
+ test("blocks new leases after Package disable while preserving replay", async () => {
1959
+ let providerRequests = 0;
1960
+ const { settings, ollama } = await fixture((input) => {
1961
+ providerRequests += 1;
1962
+ return Promise.resolve(
1963
+ String(input).endsWith("/tags")
1964
+ ? Response.json({ models: [{ model: "glm-5.3-flash:cloud" }] })
1965
+ : Response.json({ capabilities: ["tools"] }),
1966
+ );
1967
+ });
1968
+ const created = await ollama.executeConnection("account-1", {
1969
+ schemaVersion: 1,
1970
+ type: "connection/create-api-key",
1971
+ commandId: "connect-1",
1972
+ packageId: "provider-ollama-cloud",
1973
+ connectionTypeId: "ollama-cloud-account",
1974
+ label: "Work",
1975
+ apiKey: "valid-key",
1976
+ });
1977
+ const connection = await settings.getConnection(
1978
+ "account-1",
1979
+ created.connectionId,
1980
+ );
1981
+ if (!connection?.generation) throw new Error("generation is missing");
1982
+ const first = await ollama.leaseModelCredential({
1983
+ accountId: "account-1",
1984
+ connectionId: created.connectionId,
1985
+ providerModelId: "glm-5.3-flash:cloud",
1986
+ effectId: "effect-before-disable",
1987
+ connectionGeneration: connection.generation,
1988
+ });
1989
+ const current = await settings.read("account-1");
1990
+ await settings.executeConfiguration({
1991
+ schemaVersion: 1,
1992
+ userId: "account-1",
1993
+ command: {
1994
+ schemaVersion: 1,
1995
+ type: "user/set-package-enabled",
1996
+ commandId: "disable-package",
1997
+ expectedRevision: current.revision,
1998
+ packageId: "provider-ollama-cloud",
1999
+ enabled: false,
2000
+ },
2001
+ });
2002
+ const requestsBeforeAuthorization = providerRequests;
2003
+
2004
+ await expect(
2005
+ ollama.executeConnection("account-1", {
2006
+ schemaVersion: 1,
2007
+ type: "connection/rotate-api-key",
2008
+ commandId: "rotate-disabled-package",
2009
+ connectionId: created.connectionId,
2010
+ apiKey: "replacement-key",
2011
+ }),
2012
+ ).rejects.toThrow("Connection changed before credential rotation");
2013
+ expect(
2014
+ (await settings.getConnection("account-1", created.connectionId))
2015
+ ?.generation,
2016
+ ).toBe(connection.generation);
2017
+ await expect(
2018
+ ollama.leaseModelCredential({
2019
+ accountId: "account-1",
2020
+ connectionId: created.connectionId,
2021
+ providerModelId: "glm-5.3-flash:cloud",
2022
+ effectId: "effect-before-disable",
2023
+ connectionGeneration: connection.generation,
2024
+ }),
2025
+ ).resolves.toEqual(first);
2026
+ await expect(
2027
+ ollama.leaseModelCredential({
2028
+ accountId: "account-1",
2029
+ connectionId: created.connectionId,
2030
+ providerModelId: "glm-5.3-flash:cloud",
2031
+ effectId: "effect-after-disable",
2032
+ connectionGeneration: connection.generation,
2033
+ }),
2034
+ ).rejects.toThrow("Ollama Cloud Package is not installed and enabled");
2035
+ await expect(
2036
+ ollama.leaseModelCredential({
2037
+ accountId: "account-1",
2038
+ connectionId: created.connectionId,
2039
+ providerModelId: "uncatalogued:cloud",
2040
+ effectId: "exact-after-disable",
2041
+ connectionGeneration: connection.generation,
2042
+ }),
2043
+ ).rejects.toThrow("Ollama Cloud Package is not installed and enabled");
2044
+ expect(providerRequests).toBe(requestsBeforeAuthorization);
2045
+ });
2046
+
2047
+ test("pins one credential lease to the exact model effect", async () => {
2048
+ const { settings, ollama } = await fixture();
2049
+ const created = await ollama.executeConnection("account-1", {
2050
+ schemaVersion: 1,
2051
+ type: "connection/create-api-key",
2052
+ commandId: "connect-1",
2053
+ packageId: "provider-ollama-cloud",
2054
+ connectionTypeId: "ollama-cloud-account",
2055
+ label: "Work",
2056
+ apiKey: "valid-key",
2057
+ });
2058
+
2059
+ const connection = await settings.getConnection(
2060
+ "account-1",
2061
+ created.connectionId,
2062
+ );
2063
+ if (!connection?.generation) throw new Error("generation is missing");
2064
+ const first = await ollama.leaseModelCredential({
2065
+ accountId: "account-1",
2066
+ connectionId: created.connectionId,
2067
+ providerModelId: "glm-5.3-flash:cloud",
2068
+ effectId: "effect-1",
2069
+ connectionGeneration: connection.generation,
2070
+ });
2071
+ const replay = await ollama.leaseModelCredential({
2072
+ accountId: "account-1",
2073
+ connectionId: created.connectionId,
2074
+ providerModelId: "glm-5.3-flash:cloud",
2075
+ effectId: "effect-1",
2076
+ connectionGeneration: connection.generation,
2077
+ });
2078
+
2079
+ expect(replay).toEqual(first);
2080
+ });
2081
+
2082
+ test("fails a key that lists models but is unauthorized for inference", async () => {
2083
+ const { settings, ollama } = await fixture(async (input) => {
2084
+ const url = String(input);
2085
+ if (url.endsWith("/tags")) {
2086
+ return Response.json({ models: [{ model: "gpt-oss:20b" }] });
2087
+ }
2088
+ if (url.endsWith("/chat")) {
2089
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
2090
+ }
2091
+ return Response.json({ capabilities: ["tools"] });
2092
+ });
2093
+
2094
+ const created = await ollama.executeConnection("account-1", {
2095
+ schemaVersion: 1,
2096
+ type: "connection/create-api-key",
2097
+ commandId: "connect-unauthorized-inference",
2098
+ packageId: "provider-ollama-cloud",
2099
+ connectionTypeId: "ollama-cloud-account",
2100
+ label: "Bad key",
2101
+ apiKey: "listable-but-unauthorized",
2102
+ });
2103
+
2104
+ expect(created.status).toBe("failed");
2105
+ const connection = await settings.getConnection(
2106
+ "account-1",
2107
+ created.connectionId,
2108
+ );
2109
+ expect(connection).toMatchObject({
2110
+ state: "failed",
2111
+ failure: "Ollama Cloud rejected the key for inference: Unauthorized",
2112
+ });
2113
+ expect(connection?.state).not.toBe("ready");
2114
+ });
2115
+
2116
+ test("activates a key that passes the catalog read and the inference probe", async () => {
2117
+ let probes = 0;
2118
+ const { settings, ollama } = await fixture(async (input) => {
2119
+ const url = String(input);
2120
+ if (url.endsWith("/tags")) {
2121
+ return Response.json({ models: [{ model: "gpt-oss:20b" }] });
2122
+ }
2123
+ if (url.endsWith("/chat")) {
2124
+ probes += 1;
2125
+ return Response.json({
2126
+ model: "gpt-oss:20b",
2127
+ message: { role: "assistant", content: "H" },
2128
+ done: true,
2129
+ done_reason: "length",
2130
+ prompt_eval_count: 68,
2131
+ eval_count: 1,
2132
+ });
2133
+ }
2134
+ return Response.json({ capabilities: ["tools"] });
2135
+ });
2136
+
2137
+ const created = await ollama.executeConnection("account-1", {
2138
+ schemaVersion: 1,
2139
+ type: "connection/create-api-key",
2140
+ commandId: "connect-authorized-inference",
2141
+ packageId: "provider-ollama-cloud",
2142
+ connectionTypeId: "ollama-cloud-account",
2143
+ label: "Good key",
2144
+ apiKey: "authorized",
2145
+ });
2146
+
2147
+ expect(created.status).toBe("applied");
2148
+ expect(probes).toBe(1);
2149
+ expect(
2150
+ await settings.getConnection("account-1", created.connectionId),
2151
+ ).toMatchObject({ state: "ready" });
2152
+ });
2153
+
2154
+ test("probes one predicted token on the smallest discovered model", async () => {
2155
+ const probes: unknown[] = [];
2156
+ const { ollama } = await fixture(async (input, init) => {
2157
+ const url = String(input);
2158
+ if (url.endsWith("/tags")) {
2159
+ return Response.json({
2160
+ models: [{ model: "glm-5.1" }, { model: "gpt-oss:20b" }],
2161
+ });
2162
+ }
2163
+ if (url.endsWith("/chat")) {
2164
+ probes.push(JSON.parse(await new Request(input, init).text()));
2165
+ return Response.json({ done: true, done_reason: "length" });
2166
+ }
2167
+ return Response.json({ capabilities: ["tools"] });
2168
+ });
2169
+
2170
+ await ollama.executeConnection("account-1", {
2171
+ schemaVersion: 1,
2172
+ type: "connection/create-api-key",
2173
+ commandId: "connect-probe-body",
2174
+ packageId: "provider-ollama-cloud",
2175
+ connectionTypeId: "ollama-cloud-account",
2176
+ label: "Probe",
2177
+ apiKey: "authorized",
2178
+ });
2179
+
2180
+ expect(probes).toEqual([
2181
+ {
2182
+ model: "gpt-oss:20b",
2183
+ messages: [{ role: "user", content: "hi" }],
2184
+ stream: false,
2185
+ options: { num_predict: 1 },
2186
+ },
2187
+ ]);
2188
+ });
2189
+
2190
+ test("keeps the active generation when rotation fails the inference probe", async () => {
2191
+ let rejectInference = false;
2192
+ const { settings, ollama } = await fixture(async (input) => {
2193
+ const url = String(input);
2194
+ if (url.endsWith("/tags")) {
2195
+ return Response.json({ models: [{ model: "gpt-oss:20b" }] });
2196
+ }
2197
+ if (url.endsWith("/chat")) {
2198
+ return rejectInference
2199
+ ? Response.json({ error: "Unauthorized" }, { status: 401 })
2200
+ : Response.json({ done: true, done_reason: "length" });
2201
+ }
2202
+ return Response.json({ capabilities: ["tools"] });
2203
+ });
2204
+ const created = await ollama.executeConnection("account-1", {
2205
+ schemaVersion: 1,
2206
+ type: "connection/create-api-key",
2207
+ commandId: "connect-before-rotate-probe",
2208
+ packageId: "provider-ollama-cloud",
2209
+ connectionTypeId: "ollama-cloud-account",
2210
+ label: "Personal",
2211
+ apiKey: "authorized",
2212
+ });
2213
+ const before = (await settings.read("account-1")).connections[0];
2214
+ rejectInference = true;
2215
+
2216
+ const rotated = await ollama.executeConnection("account-1", {
2217
+ schemaVersion: 1,
2218
+ type: "connection/rotate-api-key",
2219
+ commandId: "rotate-unauthorized-inference",
2220
+ connectionId: created.connectionId,
2221
+ apiKey: "listable-but-unauthorized",
2222
+ });
2223
+
2224
+ expect(rotated.status).toBe("failed");
2225
+ expect((await settings.read("account-1")).connections[0]).toMatchObject({
2226
+ state: "ready",
2227
+ generation: before?.generation,
2228
+ });
2229
+ });
2230
+ });