@theoremjs/studio 0.3.4-next.647.g436b659 → 0.3.4-next.671.gfa09ab2

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.
Files changed (97) hide show
  1. package/README.md +8 -5
  2. package/cookbooks/catalog.js +18 -5
  3. package/cookbooks/tools.js +3 -3
  4. package/label-areas.d.ts +133 -0
  5. package/label-areas.js +154 -0
  6. package/mod.d.ts +4 -3
  7. package/mod.js +4 -3
  8. package/package.json +4 -4
  9. package/page/assets/Banner-DEVAsFER.js +4 -0
  10. package/page/assets/{ConsoleFrame-B7rArrs0.js → ConsoleFrame-CqUUcrR4.js} +1 -1
  11. package/page/assets/{MenuBottomSheet-CRiCEOWg.js → MenuBottomSheet-DOa09vl1.js} +1 -1
  12. package/page/assets/{SchemaFields-BoySuRuC.js → SchemaFields-CMwMU1Px.js} +1 -1
  13. package/page/assets/{ToolResultCharts-C_qojgbn.js → ToolResultCharts-CW23-D1x.js} +1 -1
  14. package/page/assets/{TraceInspector-DSLg92wY.js → TraceInspector-h030OQ82.js} +1 -1
  15. package/page/assets/{TraceOverview-TDZ4GUIz.js → TraceOverview-BsON_uZj.js} +1 -1
  16. package/page/assets/{_virtual_studio-type-sources-B0cSCDug.js → _virtual_studio-type-sources-BwSqfSwd.js} +23 -4
  17. package/page/assets/browser-connection-DSUHVCT5.js +3 -0
  18. package/page/assets/browser-engine-Cf6d-zNH.js +11 -0
  19. package/page/assets/browser-transport-BK4cbTE_.js +45 -0
  20. package/page/assets/{crypto-B6qD6nxk.js → crypto-CD14HeXH.js} +1 -1
  21. package/page/assets/{encode-files-CM9H0Lq5.js → encode-files-DhoC5hWG.js} +1 -1
  22. package/page/assets/{export-agent-BuZ4GIKx.js → export-agent-CaHsJPsM.js} +1 -1
  23. package/page/assets/{guardrail-tester-bc9lxU9X.js → guardrail-tester-BDhFLvT5.js} +1 -1
  24. package/page/assets/index-CqwmMJ4C.js +145 -0
  25. package/page/assets/{live-messages-CHHEtxno.js → live-messages-CiLmR89m.js} +1 -1
  26. package/page/assets/reader-DrOfMM8I.js +5 -0
  27. package/page/assets/shaped-data-H1miOZm2.js +20 -0
  28. package/page/assets/{stub-CWjTbSMX.js → stub-nxRsh1jo.js} +4 -4
  29. package/page/assets/{studio-code-pane-DevKnszl.js → studio-code-pane-C1wH63Y2.js} +3 -3
  30. package/page/assets/{studio-console-kpYOJazO.js → studio-console-DRzo4yTy.js} +1 -1
  31. package/page/assets/{studio-decision-Dq5LDTrl.js → studio-decision-C7QWMm7Q.js} +1 -1
  32. package/page/assets/{studio-embedding-Cebwv5_l.js → studio-embedding-D8KroBXY.js} +1 -1
  33. package/page/assets/{studio-host-console-CaaVHxrN.js → studio-host-console-HkX8BerX.js} +2 -2
  34. package/page/assets/{studio-labels-BQOD-taS.js → studio-labels-6w1SKC2D.js} +1 -1
  35. package/page/assets/studio-live-BmVeXAu4.js +5 -0
  36. package/page/assets/{studio-map-BOaPPVXK.js → studio-map-5ZU1nicW.js} +1 -1
  37. package/page/assets/studio-session-CjUQSXx0.js +1 -0
  38. package/page/assets/studio-trace-replay-CSbJSN5e.js +3 -0
  39. package/page/assets/{studio-type-checker-BQmVytwu.js → studio-type-checker-BbUSqqOS.js} +1 -1
  40. package/page/assets/tool-schema-BmRYaywn.js +17 -0
  41. package/page/assets/{trace-record-CtL5_CIg.js → trace-record-DxgSKmYY.js} +1 -1
  42. package/page/assets/tree-3N-1RPZz.js +3 -0
  43. package/page/assets/{turn-client-yriGS51g.js → turn-client-DN8PawJr.js} +2 -2
  44. package/page/assets/{use-one-call-8QTXCYlp.js → use-one-call-Br2IVJLU.js} +1 -1
  45. package/page/assets/{use-second-ticker-rObooyH6.js → use-second-ticker-CEwOSS-d.js} +1 -1
  46. package/page/assets/{workspace-WKa0_gWg.js → workspace-CTSW941G.js} +1 -1
  47. package/page/index.html +16 -16
  48. package/replay.d.ts +13 -8
  49. package/replay.js +33 -31
  50. package/run-payload.d.ts +20 -6
  51. package/run-payload.js +85 -13
  52. package/runtime-scope.js +1 -0
  53. package/runtime.js +1 -0
  54. package/server/project.js +5 -32
  55. package/transport.d.ts +1 -3
  56. package/transport.js +0 -9
  57. package/ui/inspector.js +11 -5
  58. package/ui/lib/acting-as.js +1 -6
  59. package/ui/lib/run-keys.d.ts +15 -5
  60. package/ui/lib/run-keys.js +80 -16
  61. package/ui/lib/studio-conversation.d.ts +2 -3
  62. package/ui/lib/studio-conversation.js +28 -65
  63. package/ui/lib/studio-keep.d.ts +34 -0
  64. package/ui/lib/studio-keep.js +202 -0
  65. package/ui/lib/studio-map-kept.d.ts +2 -2
  66. package/ui/lib/studio-map-kept.js +5 -10
  67. package/ui/lib/studio-open.d.ts +1 -1
  68. package/ui/lib/studio-open.js +5 -5
  69. package/ui/lib/studio-page.js +1 -7
  70. package/ui/lib/studio-restore.d.ts +2 -3
  71. package/ui/lib/studio-restore.js +8 -48
  72. package/ui/lib/studio-run-open.d.ts +10 -5
  73. package/ui/lib/studio-run-open.js +18 -9
  74. package/ui/lib/studio-session.d.ts +38 -5
  75. package/ui/lib/studio-session.js +133 -3
  76. package/ui/lib/studio-store.js +8 -30
  77. package/ui/profile-editor.js +37 -185
  78. package/ui/studio-compare.js +239 -46
  79. package/ui/studio-run.js +29 -15
  80. package/ui/studio-screen.d.ts +1 -1
  81. package/ui/studio-screen.js +8 -9
  82. package/ui/studio-trace-replay.js +39 -14
  83. package/vite.mjs +1 -1
  84. package/page/assets/Banner-CzP7eU2F.js +0 -4
  85. package/page/assets/browser-connection-QNf4S7Ff.js +0 -3
  86. package/page/assets/browser-engine-DpEz1HOI.js +0 -11
  87. package/page/assets/browser-transport-sRqTLzGF.js +0 -45
  88. package/page/assets/index-CVYQrx1w.js +0 -145
  89. package/page/assets/reader-DlrsIIkn.js +0 -5
  90. package/page/assets/shaped-data-DAdn_XvU.js +0 -20
  91. package/page/assets/studio-live-Bz8YuQcb.js +0 -5
  92. package/page/assets/studio-session-yEqFQo5o.js +0 -1
  93. package/page/assets/studio-trace-replay-Ck0X9hTR.js +0 -3
  94. package/page/assets/tool-schema-B_EOjDjg.js +0 -17
  95. package/page/assets/tree-DM7jRXMx.js +0 -3
  96. package/run-payload-core.d.ts +0 -28
  97. package/run-payload-core.js +0 -117
@@ -29,12 +29,7 @@ function keptPick(project) {
29
29
  }
30
30
  }
31
31
  function keepPick(project, pick) {
32
- try {
33
- session()?.setItem(pickKey(project), JSON.stringify(pick));
34
- }
35
- catch {
36
- // Storage refused: the pick lasts as long as the page.
37
- }
32
+ session()?.setItem(pickKey(project), JSON.stringify(pick));
38
33
  }
39
34
  /**
40
35
  * The pick for a project: the builder's last one in this tab, else the one the setup file starts
@@ -1,12 +1,22 @@
1
+ import { type StudioRunCredentials, type StudioRunPayload } from '../../mod.ts';
1
2
  /** A run tab's keys: the studio's vault, by slot. */
2
3
  export type RunKeys = Readonly<Record<string, string>>;
4
+ /** A run as the browser keeps it, and whether keeping it masked credentials the run tab must ask for. */
5
+ export interface KeptRun {
6
+ payload: StudioRunPayload;
7
+ masked: boolean;
8
+ }
3
9
  /**
4
- * Answers each run tab this studio tab opened with the keys it holds now.
5
- * invariant: keys go only to a same-origin window this tab opened, for a run id this browser saved.
10
+ * Hands `payload` to a new run tab through the browser's keep, its tools' credentials masked;
11
+ * the run tab asks this tab for them. Resolves to the run's id, for the run tab's address, once
12
+ * this tab holds the run's lock.
6
13
  */
14
+ export declare function handOffStudioRun(payload: StudioRunPayload): Promise<string>;
15
+ /** Lends the screen's keys to the run tabs this page opened, until the returned cleanup. */
7
16
  export declare function answerRunKeys(keys: () => RunKeys): () => void;
8
17
  /**
9
- * Asks the studio tab that opened this run for its keys. Returns null when no studio tab is
10
- * there to ask; otherwise the cleanup.
18
+ * Asks the studio tab that opened this run for its keys and its tools' credentials. `onGone` when
19
+ * that tab no longer holds them: it was closed, reloaded or left the studio. Returns null when
20
+ * no studio tab opened this one; otherwise the cleanup.
11
21
  */
12
- export declare function askRunKeys(run: string, onKeys: (keys: RunKeys) => void): (() => void) | null;
22
+ export declare function askRunKeys(run: string, onKeys: (keys: RunKeys, tools: StudioRunCredentials) => void, onGone: () => void): (() => void) | null;
@@ -1,6 +1,10 @@
1
- import { loadStudioRunPayload } from "../../mod.js";
1
+ import { createStudioRunId, maskedStudioRun, studioRunCredentials, studioRunIsMasked, } from "../../mod.js";
2
+ import { handOffRun } from "./studio-session.js";
2
3
  const ASK = 'theorem.studio.run-keys.ask';
3
4
  const KEYS = 'theorem.studio.run-keys';
5
+ const GONE = 'theorem.studio.run-keys.gone';
6
+ /** Held by the studio page that handed a run off, for as long as it holds the run's credentials. */
7
+ const RUN_LOCK = 'theorem.studio.run-keys:';
4
8
  const isAsk = (data) => typeof data === 'object' &&
5
9
  data !== null &&
6
10
  data.type === ASK &&
@@ -9,7 +13,44 @@ const isReply = (data) => typeof data === 'object' &&
9
13
  data !== null &&
10
14
  data.type === KEYS &&
11
15
  typeof data.run === 'string' &&
12
- typeof data.keys === 'object';
16
+ typeof data.keys === 'object' &&
17
+ typeof data.tools === 'object';
18
+ const isGone = (data) => typeof data === 'object' &&
19
+ data !== null &&
20
+ data.type === GONE &&
21
+ typeof data.run === 'string';
22
+ /** The runs this tab handed off, with the credentials their kept copies mask. They last as long as the page. */
23
+ const handed = new Map();
24
+ /** The keys the studio holds now, while its screen is open. */
25
+ let heldKeys;
26
+ let answering = false;
27
+ /**
28
+ * Hands `payload` to a new run tab through the browser's keep, its tools' credentials masked;
29
+ * the run tab asks this tab for them. Resolves to the run's id, for the run tab's address, once
30
+ * this tab holds the run's lock.
31
+ */
32
+ export async function handOffStudioRun(payload) {
33
+ const run = createStudioRunId();
34
+ const kept = { payload: maskedStudioRun(payload), masked: studioRunIsMasked(payload) };
35
+ handed.set(run, studioRunCredentials(payload));
36
+ answerAsks();
37
+ handOffRun(run, JSON.stringify(kept));
38
+ const locks = navigator.locks;
39
+ // invariant: the run tab opens after the lock is held, so its query finds it.
40
+ // why: Chrome refuses a lock granted while `window.open` runs, and drops the request.
41
+ if (locks)
42
+ await new Promise((held) => {
43
+ locks
44
+ .request(`${RUN_LOCK}${run}`, () => {
45
+ held();
46
+ return new Promise(() => { });
47
+ })
48
+ .catch(() => {
49
+ held();
50
+ });
51
+ });
52
+ return run;
53
+ }
13
54
  /** Whether `source` is a window this tab opened. A window from another origin throws on `opener`. */
14
55
  function openedHere(source) {
15
56
  try {
@@ -20,28 +61,39 @@ function openedHere(source) {
20
61
  }
21
62
  }
22
63
  /**
23
- * Answers each run tab this studio tab opened with the keys it holds now.
24
- * invariant: keys go only to a same-origin window this tab opened, for a run id this browser saved.
64
+ * Answers each run tab this page opened, for the life of the page: with the keys the screen holds
65
+ * now and the run's tools' credentials, or that it holds them no longer.
66
+ * invariant: keys go only to a same-origin window this tab opened, for a run id this tab handed off.
25
67
  */
26
- export function answerRunKeys(keys) {
27
- const answer = (event) => {
68
+ function answerAsks() {
69
+ if (answering)
70
+ return;
71
+ answering = true;
72
+ globalThis.addEventListener('message', (event) => {
28
73
  if (event.origin !== globalThis.location.origin || !isAsk(event.data))
29
74
  return;
30
- if (!openedHere(event.source) || !loadStudioRunPayload(event.data.run))
75
+ if (!openedHere(event.source))
31
76
  return;
32
- const reply = { type: KEYS, run: event.data.run, keys: keys() };
77
+ const { run } = event.data;
78
+ const tools = handed.get(run);
79
+ const reply = tools && heldKeys ? { type: KEYS, run, keys: heldKeys(), tools } : { type: GONE, run };
33
80
  event.source.postMessage(reply, globalThis.location.origin);
34
- };
35
- globalThis.addEventListener('message', answer);
81
+ });
82
+ }
83
+ /** Lends the screen's keys to the run tabs this page opened, until the returned cleanup. */
84
+ export function answerRunKeys(keys) {
85
+ heldKeys = keys;
36
86
  return () => {
37
- globalThis.removeEventListener('message', answer);
87
+ if (heldKeys === keys)
88
+ heldKeys = undefined;
38
89
  };
39
90
  }
40
91
  /**
41
- * Asks the studio tab that opened this run for its keys. Returns null when no studio tab is
42
- * there to ask; otherwise the cleanup.
92
+ * Asks the studio tab that opened this run for its keys and its tools' credentials. `onGone` when
93
+ * that tab no longer holds them: it was closed, reloaded or left the studio. Returns null when
94
+ * no studio tab opened this one; otherwise the cleanup.
43
95
  */
44
- export function askRunKeys(run, onKeys) {
96
+ export function askRunKeys(run, onKeys, onGone) {
45
97
  const studio = globalThis.window.opener;
46
98
  if (!studio)
47
99
  return null;
@@ -49,11 +101,23 @@ export function askRunKeys(run, onKeys) {
49
101
  if (event.origin !== globalThis.location.origin || event.source !== studio)
50
102
  return;
51
103
  if (isReply(event.data) && event.data.run === run)
52
- onKeys(event.data.keys);
104
+ onKeys(event.data.keys, event.data.tools);
105
+ if (isGone(event.data) && event.data.run === run)
106
+ onGone();
53
107
  };
54
108
  globalThis.addEventListener('message', receive);
109
+ // why: a page that left or closed answers nothing; its lock on the run is gone with it.
110
+ void navigator.locks?.query().then(({ held = [], pending = [] }) => {
111
+ if (![...held, ...pending].some((lock) => lock.name === `${RUN_LOCK}${run}`))
112
+ onGone();
113
+ });
55
114
  const ask = { type: ASK, run };
56
- studio.postMessage(ask, globalThis.location.origin);
115
+ try {
116
+ studio.postMessage(ask, globalThis.location.origin);
117
+ }
118
+ catch {
119
+ onGone();
120
+ }
57
121
  return () => {
58
122
  globalThis.removeEventListener('message', receive);
59
123
  };
@@ -6,9 +6,8 @@ export type ChatSealer = 'page' | 'demo';
6
6
  */
7
7
  export declare function pageConversationKey(): string;
8
8
  /**
9
- * Keeps an agent's conversation ref. The ref holds the whole conversation, its media too: one too
10
- * big for the tab's storage is not kept, and the agent's last kept ref is forgotten with it.
11
- * Never throws.
9
+ * Keeps an agent's conversation ref. The ref holds the whole conversation, its media too: one the
10
+ * browser refuses to keep is forgotten, with the agent's last kept ref. Never throws.
12
11
  */
13
12
  export declare function saveConversation(agentKey: string, sealer: ChatSealer, ref: string): void;
14
13
  /**
@@ -1,11 +1,11 @@
1
1
  /**
2
- * Each agent's preview conversation, kept in this tab's sessionStorage beside the workspace so a
3
- * reload resumes it. What is kept is the conversation's ref: the conversation sealed with a key,
4
- * which opens only where that key is. A run in the page seals with the tab's own key; the hosted
5
- * demo seals on its server.
2
+ * Each agent's preview conversation, kept in this tab's records beside the workspace so a reload
3
+ * resumes it. What is kept is the conversation's ref: the conversation sealed with a key, which
4
+ * opens only where that key is. A run in the page seals with the tab's own key, which stays in the
5
+ * tab's sessionStorage and never reaches the browser's keep; the hosted demo seals on its server.
6
6
  */
7
7
  import { newConversationKey } from "../../conversation-key.js";
8
- import { CHAT_PREFIX, isRecord, session } from "./studio-session.js";
8
+ import { CHAT_PREFIX, isRecord, session, tabSession } from "./studio-session.js";
9
9
  /** The tab's key for the conversations its page runs seal. */
10
10
  const PAGE_KEY = 'theorem.studio.chat-key';
11
11
  /** The key, while the tab keeps none: it lasts as long as the page. */
@@ -15,7 +15,7 @@ let pageKeyHeld;
15
15
  * refs it opens, so both go when the tab does. A new key forgets the refs the last one sealed.
16
16
  */
17
17
  export function pageConversationKey() {
18
- const store = session();
18
+ const store = tabSession();
19
19
  try {
20
20
  const kept = store?.getItem(PAGE_KEY);
21
21
  if (kept)
@@ -52,79 +52,42 @@ function keptRef(raw) {
52
52
  }
53
53
  /** Forgets every ref `sealer` sealed: none of them opens any more. */
54
54
  function forgetSealedBy(sealer) {
55
- try {
56
- const store = session();
57
- if (!store)
58
- return;
59
- for (const key of Object.keys(store)) {
60
- if (!key.startsWith(CHAT_PREFIX))
61
- continue;
62
- const raw = store.getItem(key);
63
- if (raw && keptRef(raw)?.sealer === sealer)
64
- store.removeItem(key);
65
- }
66
- }
67
- catch {
68
- // Nothing to forget.
55
+ const store = session();
56
+ for (const key of store?.keys() ?? []) {
57
+ if (!key.startsWith(CHAT_PREFIX))
58
+ continue;
59
+ const raw = store?.getItem(key);
60
+ if (raw && keptRef(raw)?.sealer === sealer)
61
+ store?.removeItem(key);
69
62
  }
70
63
  }
71
64
  /**
72
- * Keeps an agent's conversation ref. The ref holds the whole conversation, its media too: one too
73
- * big for the tab's storage is not kept, and the agent's last kept ref is forgotten with it.
74
- * Never throws.
65
+ * Keeps an agent's conversation ref. The ref holds the whole conversation, its media too: one the
66
+ * browser refuses to keep is forgotten, with the agent's last kept ref. Never throws.
75
67
  */
76
68
  export function saveConversation(agentKey, sealer, ref) {
77
- const store = session();
78
- if (!store)
79
- return;
80
- const key = `${CHAT_PREFIX}${agentKey}`;
81
- try {
82
- store.setItem(key, JSON.stringify({ sealer, ref }));
83
- return;
84
- }
85
- catch {
86
- // Over quota: an older ref is a conversation that already moved on, so none is kept.
87
- }
88
- try {
89
- store.removeItem(key);
90
- }
91
- catch {
92
- // Nothing more to do.
93
- }
69
+ session()?.setItem(`${CHAT_PREFIX}${agentKey}`, JSON.stringify({ sealer, ref }));
94
70
  }
95
71
  /**
96
72
  * An agent's kept ref, when `sealer` sealed it. Anything else kept under the agent (a
97
73
  * conversation kept before refs) is forgotten, so it holds no room.
98
74
  */
99
75
  export function restoreConversation(agentKey, sealer) {
100
- try {
101
- const store = session();
102
- const key = `${CHAT_PREFIX}${agentKey}`;
103
- const raw = store?.getItem(key);
104
- if (!raw)
105
- return undefined;
106
- const kept = keptRef(raw);
107
- if (!kept)
108
- store?.removeItem(key);
109
- return kept?.sealer === sealer ? kept.ref : undefined;
110
- }
111
- catch {
76
+ const store = session();
77
+ const key = `${CHAT_PREFIX}${agentKey}`;
78
+ const raw = store?.getItem(key);
79
+ if (!raw)
112
80
  return undefined;
113
- }
81
+ const kept = keptRef(raw);
82
+ if (!kept)
83
+ store?.removeItem(key);
84
+ return kept?.sealer === sealer ? kept.ref : undefined;
114
85
  }
115
86
  /** Forgets one agent's conversation, or every agent's. */
116
87
  export function clearConversation(agentKey) {
117
- try {
118
- const store = session();
119
- if (!store)
120
- return;
121
- for (const key of Object.keys(store)) {
122
- if (agentKey === undefined ? key.startsWith(CHAT_PREFIX) : key === `${CHAT_PREFIX}${agentKey}`) {
123
- store.removeItem(key);
124
- }
125
- }
126
- }
127
- catch {
128
- // Nothing to clear.
88
+ const store = session();
89
+ for (const key of store?.keys() ?? []) {
90
+ if (agentKey === undefined ? key.startsWith(CHAT_PREFIX) : key === `${CHAT_PREFIX}${agentKey}`)
91
+ store?.removeItem(key);
129
92
  }
130
93
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Where the studio keeps itself in this browser: IndexedDB, each record under the id of the tab
3
+ * that wrote it, and each run handed to a new tab under the run's id until that tab takes it.
4
+ * Keys never come here: the vault stays in memory, and a run tab asks the studio tab for its keys.
5
+ */
6
+ /** A tab gone this long has closed, not reloaded: another studio tab that opens clears its records. */
7
+ export declare const GONE_MS = 60000;
8
+ /** The studio's records, by the tab that wrote them. */
9
+ export interface Keep {
10
+ /**
11
+ * Takes the tab's records: says the tab is here, and returns what it kept. With `from`, the
12
+ * tab is a copy of that one (a duplicated tab), so it starts with a copy of its records.
13
+ */
14
+ claim(tab: string, from: string | undefined): Promise<Array<[string, string]>>;
15
+ /** Keeps a record. One the browser refuses to keep is forgotten, so an older one does not come back. */
16
+ put(tab: string, name: string, value: string): void;
17
+ remove(tab: string, name: string): void;
18
+ /** Keeps a run for the tab it opens in, beside the records of the tab that opened it. */
19
+ handOff(run: string, opener: string, value: string): void;
20
+ /** Moves a handed-off run into `tab`'s records under `name`; undefined when no tab handed it off. */
21
+ takeRun(run: string, tab: string, name: string): Promise<string | undefined>;
22
+ /** Clears the records of each tab that has been gone `GONE_MS`. `alive` names the tabs open now. */
23
+ sweep(alive: ReadonlySet<string>, now: number): Promise<void>;
24
+ }
25
+ /** What a sweep does with each tab it knows of, from when each was first seen gone. */
26
+ export declare function sweepPlan(tabs: Iterable<string>, gone: ReadonlyMap<string, number>, alive: ReadonlySet<string>, now: number): {
27
+ seen: string[];
28
+ back: string[];
29
+ clear: string[];
30
+ };
31
+ /** A keep that lasts as long as the page: where the browser has no IndexedDB or no Web Locks, and in tests. */
32
+ export declare function memoryKeep(): Keep;
33
+ /** The keep in this browser's IndexedDB. Rejects where IndexedDB is missing or refuses to open. */
34
+ export declare function indexedDbKeep(): Promise<Keep>;
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Where the studio keeps itself in this browser: IndexedDB, each record under the id of the tab
3
+ * that wrote it, and each run handed to a new tab under the run's id until that tab takes it.
4
+ * Keys never come here: the vault stays in memory, and a run tab asks the studio tab for its keys.
5
+ */
6
+ /** A tab gone this long has closed, not reloaded: another studio tab that opens clears its records. */
7
+ export const GONE_MS = 60_000;
8
+ /** What a sweep does with each tab it knows of, from when each was first seen gone. */
9
+ export function sweepPlan(tabs, gone, alive, now) {
10
+ const plan = { seen: [], back: [], clear: [] };
11
+ for (const tab of new Set([...tabs, ...gone.keys()])) {
12
+ const since = gone.get(tab);
13
+ if (alive.has(tab)) {
14
+ if (since !== undefined)
15
+ plan.back.push(tab);
16
+ }
17
+ else if (since === undefined)
18
+ plan.seen.push(tab);
19
+ else if (now - since >= GONE_MS)
20
+ plan.clear.push(tab);
21
+ }
22
+ return plan;
23
+ }
24
+ /** A keep that lasts as long as the page: where the browser has no IndexedDB or no Web Locks, and in tests. */
25
+ export function memoryKeep() {
26
+ const tabs = new Map();
27
+ const runs = new Map();
28
+ const gone = new Map();
29
+ const records = (tab) => {
30
+ const kept = tabs.get(tab) ?? new Map();
31
+ tabs.set(tab, kept);
32
+ return kept;
33
+ };
34
+ return {
35
+ claim(tab, from) {
36
+ gone.delete(tab);
37
+ if (from !== undefined)
38
+ for (const [name, value] of tabs.get(from) ?? [])
39
+ records(tab).set(name, value);
40
+ return Promise.resolve([...records(tab)]);
41
+ },
42
+ put(tab, name, value) {
43
+ records(tab).set(name, value);
44
+ },
45
+ remove(tab, name) {
46
+ tabs.get(tab)?.delete(name);
47
+ },
48
+ handOff(run, opener, value) {
49
+ runs.set(run, { opener, value });
50
+ },
51
+ takeRun(run, tab, name) {
52
+ const handed = runs.get(run);
53
+ if (!handed)
54
+ return Promise.resolve(undefined);
55
+ runs.delete(run);
56
+ records(tab).set(name, handed.value);
57
+ return Promise.resolve(handed.value);
58
+ },
59
+ sweep(alive, now) {
60
+ const openers = [...runs.values()].map((run) => run.opener);
61
+ const plan = sweepPlan([...tabs.keys(), ...openers], gone, alive, now);
62
+ for (const tab of plan.seen)
63
+ gone.set(tab, now);
64
+ for (const tab of plan.back)
65
+ gone.delete(tab);
66
+ for (const tab of plan.clear) {
67
+ tabs.delete(tab);
68
+ gone.delete(tab);
69
+ for (const [run, handed] of runs)
70
+ if (handed.opener === tab)
71
+ runs.delete(run);
72
+ }
73
+ return Promise.resolve();
74
+ },
75
+ };
76
+ }
77
+ const DATABASE = 'theorem.studio';
78
+ const TABS = 'tabs';
79
+ const RUNS = 'runs';
80
+ const GONE = 'gone';
81
+ function result(request) {
82
+ return new Promise((resolve, reject) => {
83
+ request.onsuccess = () => {
84
+ resolve(request.result);
85
+ };
86
+ request.onerror = () => {
87
+ reject(request.error ?? new Error('IndexedDB refused the request.'));
88
+ };
89
+ });
90
+ }
91
+ function finished(transaction) {
92
+ return new Promise((resolve, reject) => {
93
+ transaction.oncomplete = () => {
94
+ resolve();
95
+ };
96
+ transaction.onerror = transaction.onabort = () => {
97
+ reject(transaction.error ?? new Error('IndexedDB did not keep the change.'));
98
+ };
99
+ });
100
+ }
101
+ /** Every record of `tab`: its names sort under it, and a list sorts after every name. */
102
+ const ofTab = (tab) => IDBKeyRange.bound([tab], [tab, []]);
103
+ /** The keep in this browser's IndexedDB. Rejects where IndexedDB is missing or refuses to open. */
104
+ export async function indexedDbKeep() {
105
+ const opening = indexedDB.open(DATABASE, 1);
106
+ opening.onupgradeneeded = () => {
107
+ const db = opening.result;
108
+ db.createObjectStore(TABS);
109
+ db.createObjectStore(RUNS);
110
+ db.createObjectStore(GONE);
111
+ };
112
+ const db = await result(opening);
113
+ const write = (stores, change, undo) => {
114
+ const transaction = db.transaction(stores, 'readwrite');
115
+ change(transaction);
116
+ finished(transaction).catch(() => undo?.());
117
+ };
118
+ const forget = (tab, name) => {
119
+ write([TABS], (transaction) => transaction.objectStore(TABS).delete([tab, name]));
120
+ };
121
+ return {
122
+ async claim(tab, from) {
123
+ const transaction = db.transaction([TABS, GONE], 'readwrite');
124
+ const done = finished(transaction);
125
+ const kept = transaction.objectStore(TABS);
126
+ transaction.objectStore(GONE).delete(tab);
127
+ if (from !== undefined) {
128
+ const [names, values] = await Promise.all([
129
+ result(kept.getAllKeys(ofTab(from))),
130
+ result(kept.getAll(ofTab(from))),
131
+ ]);
132
+ names.forEach((key, at) => {
133
+ kept.put(values[at], [tab, key[1]]);
134
+ });
135
+ }
136
+ const [names, values] = await Promise.all([
137
+ result(kept.getAllKeys(ofTab(tab))),
138
+ result(kept.getAll(ofTab(tab))),
139
+ ]);
140
+ await done;
141
+ return names.map((key, at) => [
142
+ key[1],
143
+ String(values[at]),
144
+ ]);
145
+ },
146
+ put(tab, name, value) {
147
+ write([TABS], (transaction) => transaction.objectStore(TABS).put(value, [tab, name]), () => {
148
+ forget(tab, name);
149
+ });
150
+ },
151
+ remove(tab, name) {
152
+ forget(tab, name);
153
+ },
154
+ handOff(run, opener, value) {
155
+ // invariant: the write is queued before the run tab opens, so its read comes after it.
156
+ write([RUNS], (transaction) => transaction.objectStore(RUNS).put({ opener, value }, run));
157
+ },
158
+ async takeRun(run, tab, name) {
159
+ const transaction = db.transaction([RUNS, TABS], 'readwrite');
160
+ const done = finished(transaction);
161
+ const handed = (await result(transaction.objectStore(RUNS).get(run)));
162
+ if (handed) {
163
+ transaction.objectStore(RUNS).delete(run);
164
+ transaction.objectStore(TABS).put(handed.value, [tab, name]);
165
+ }
166
+ await done;
167
+ return handed?.value;
168
+ },
169
+ async sweep(alive, now) {
170
+ const transaction = db.transaction([TABS, RUNS, GONE], 'readwrite');
171
+ const done = finished(transaction);
172
+ const tabs = transaction.objectStore(TABS);
173
+ const runs = transaction.objectStore(RUNS);
174
+ const goneStore = transaction.objectStore(GONE);
175
+ const [names, runIds, handed, goneIds, goneSince] = await Promise.all([
176
+ result(tabs.getAllKeys()),
177
+ result(runs.getAllKeys()),
178
+ result(runs.getAll()),
179
+ result(goneStore.getAllKeys()),
180
+ result(goneStore.getAll()),
181
+ ]);
182
+ const openers = handed.map((run) => run.opener);
183
+ const gone = new Map(goneIds.map((tab, at) => [String(tab), Number(goneSince[at])]));
184
+ const plan = sweepPlan([...names.map((key) => key[0]), ...openers], gone, alive, now);
185
+ for (const tab of plan.seen)
186
+ goneStore.put(now, tab);
187
+ for (const tab of plan.back)
188
+ goneStore.delete(tab);
189
+ const clear = new Set(plan.clear);
190
+ for (const tab of clear) {
191
+ tabs.delete(ofTab(tab));
192
+ goneStore.delete(tab);
193
+ }
194
+ openers.forEach((opener, at) => {
195
+ const run = runIds[at];
196
+ if (clear.has(opener) && run !== undefined)
197
+ runs.delete(run);
198
+ });
199
+ await done;
200
+ },
201
+ };
202
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * How someone left the map, kept in this tab's sessionStorage beside the workspace, a project's
2
+ * How someone left the map, kept in this tab's records beside the workspace, a project's
3
3
  * under its own name: where they dragged its nodes, with and without detail, whether it shows
4
4
  * detail, and the node whose family alone it shows.
5
5
  */
@@ -13,5 +13,5 @@ export interface KeptMap {
13
13
  }
14
14
  /** What was kept; the map as it first opens when nothing was or it cannot be read. */
15
15
  export declare function readKeptMap(project: string | undefined): KeptMap;
16
- /** Keeps `kept`, or forgets it when it is the map as it first opens. Storage that is full or blocked keeps nothing. */
16
+ /** Keeps `kept`, or forgets it when it is the map as it first opens. */
17
17
  export declare function writeKeptMap(project: string | undefined, kept: KeptMap): void;
@@ -29,20 +29,15 @@ export function readKeptMap(project) {
29
29
  return NOTHING_KEPT;
30
30
  }
31
31
  }
32
- /** Keeps `kept`, or forgets it when it is the map as it first opens. Storage that is full or blocked keeps nothing. */
32
+ /** Keeps `kept`, or forgets it when it is the map as it first opens. */
33
33
  export function writeKeptMap(project, kept) {
34
34
  const { tokens, detail, expanded, family } = kept;
35
35
  const untouched = Object.keys(tokens).length === 0 &&
36
36
  Object.keys(detail).length === 0 &&
37
37
  !expanded &&
38
38
  family === undefined;
39
- try {
40
- if (untouched)
41
- session()?.removeItem(keptKey(project));
42
- else
43
- session()?.setItem(keptKey(project), JSON.stringify(kept));
44
- }
45
- catch {
46
- // Nothing to do: it lasts until the page goes.
47
- }
39
+ if (untouched)
40
+ session()?.removeItem(keptKey(project));
41
+ else
42
+ session()?.setItem(keptKey(project), JSON.stringify(kept));
48
43
  }
@@ -12,7 +12,7 @@ export declare function openStudio(seed?: {
12
12
  } | {
13
13
  workspace: StudioWorkspace;
14
14
  question: string | undefined;
15
- }): StudioOpened;
15
+ }): Promise<StudioOpened>;
16
16
  /**
17
17
  * What the studio opens on when a local server holds a project: the project's workspace, with the
18
18
  * edits this tab kept for it. The studio merges into them what the files changed since; edits
@@ -1,13 +1,13 @@
1
- import { clearStaleStudioRuns, createResearchWorkspace, workspaceFromDraft, } from "../../mod.js";
1
+ import { createResearchWorkspace, workspaceFromDraft, } from "../../mod.js";
2
2
  import { openProject } from "./studio-project.js";
3
3
  import { editsAside, restoreProject, restoreStudio } from "./studio-restore.js";
4
- import { projectKey } from "./studio-session.js";
4
+ import { projectKey, tabStorage } from "./studio-session.js";
5
5
  /**
6
6
  * What the studio opens on in this tab. Draft keys are random, so this runs in the browser. The
7
7
  * tab's kept workspace comes back unless a `seed` asks for another; then it waits behind Undo.
8
8
  */
9
- export function openStudio(seed) {
10
- clearStaleStudioRuns();
9
+ export async function openStudio(seed) {
10
+ await tabStorage();
11
11
  const kept = restoreStudio();
12
12
  const freshWorkspace = (workspace) => ({
13
13
  workspace,
@@ -39,7 +39,7 @@ export function openStudio(seed) {
39
39
  * files. Throws when no server answers.
40
40
  */
41
41
  export async function openStudioProject(said) {
42
- const { project, workspace } = await openProject(said);
42
+ const [{ project, workspace }] = await Promise.all([openProject(said), tabStorage()]);
43
43
  const key = projectKey(project.name);
44
44
  const kept = restoreProject(key, workspace, project.print);
45
45
  return {
@@ -105,14 +105,8 @@ function loadPageValues(agentKey) {
105
105
  return NO_PAGE_VALUES;
106
106
  }
107
107
  }
108
- /** Never throws: a full or blocked store keeps nothing. */
109
108
  function savePageValues(agentKey, values) {
110
- try {
111
- session()?.setItem(`${PAGE_PREFIX}${agentKey}`, JSON.stringify(values));
112
- }
113
- catch {
114
- // Nothing is kept.
115
- }
109
+ session()?.setItem(`${PAGE_PREFIX}${agentKey}`, JSON.stringify(values));
116
110
  }
117
111
  /** Each agent's values as last read or set, so the editor and the preview show the same ones. */
118
112
  const held = new Map();
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Reading the studio's workspace back from this tab's sessionStorage. A kept workspace that no
3
- * longer fits the current shape is set aside, and a draft kept by the one-agent studio opens as
4
- * a workspace holding it.
2
+ * Reading the studio's workspace back from this tab's records. A kept workspace that no longer
3
+ * fits the current shape is set aside.
5
4
  */
6
5
  import { type StudioWorkspace } from '../../mod.ts';
7
6
  import { type RestoredStudio } from './studio-session.ts';