@theoremjs/studio 0.3.4-next.649.gf83cea1 → 0.3.4-next.673.ga492632

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 (92) hide show
  1. package/README.md +8 -5
  2. package/cookbooks/catalog.js +18 -5
  3. package/cookbooks/tools.js +3 -3
  4. package/mod.d.ts +3 -3
  5. package/mod.js +3 -3
  6. package/package.json +4 -4
  7. package/page/assets/Banner-BxvBuYgz.js +4 -0
  8. package/page/assets/{ConsoleFrame-B7ruuMVo.js → ConsoleFrame-_YA1HkXX.js} +1 -1
  9. package/page/assets/{MenuBottomSheet-Bso4osRe.js → MenuBottomSheet-BbniF3mM.js} +1 -1
  10. package/page/assets/{SchemaFields-DEqlS2cS.js → SchemaFields-Bg4OxBw3.js} +1 -1
  11. package/page/assets/{ToolResultCharts-DV0Cds5H.js → ToolResultCharts-PhjAbSXq.js} +1 -1
  12. package/page/assets/{TraceInspector-CBybmNzh.js → TraceInspector-fiuM6pWK.js} +1 -1
  13. package/page/assets/{TraceOverview-CO9Oh2_v.js → TraceOverview-BzerB7QI.js} +1 -1
  14. package/page/assets/{_virtual_studio-type-sources-hU0nQlME.js → _virtual_studio-type-sources-BwSqfSwd.js} +17 -3
  15. package/page/assets/{browser-connection-Dim6ghw7.js → browser-connection-DSUHVCT5.js} +2 -2
  16. package/page/assets/browser-engine-SBozuru0.js +11 -0
  17. package/page/assets/browser-transport-BHWgtIIH.js +45 -0
  18. package/page/assets/{crypto-CgKfdKF3.js → crypto-CD14HeXH.js} +1 -1
  19. package/page/assets/{encode-files-mmy8V0Ya.js → encode-files-DhoC5hWG.js} +1 -1
  20. package/page/assets/{export-agent-CuUh1bR8.js → export-agent-GKC4g6Ei.js} +1 -1
  21. package/page/assets/{guardrail-tester-Bi8kF5JO.js → guardrail-tester-HDwGIn2U.js} +1 -1
  22. package/page/assets/index-Xice1eg1.js +145 -0
  23. package/page/assets/{live-messages-MuPbOsZr.js → live-messages-CiLmR89m.js} +1 -1
  24. package/page/assets/reader-DrOfMM8I.js +5 -0
  25. package/page/assets/{shaped-data-BIkh6Bis.js → shaped-data-H1miOZm2.js} +1 -1
  26. package/page/assets/{stub-fr8Q8_U3.js → stub-nxRsh1jo.js} +4 -4
  27. package/page/assets/{studio-code-pane-DnKDFRIG.js → studio-code-pane-DPxkcxON.js} +3 -3
  28. package/page/assets/{studio-console-C8I1MOzW.js → studio-console-CdUQW84-.js} +1 -1
  29. package/page/assets/{studio-decision-wzSt60HL.js → studio-decision-B9Zvbyst.js} +1 -1
  30. package/page/assets/{studio-embedding-DOOXOgyT.js → studio-embedding-Ds3gGEie.js} +1 -1
  31. package/page/assets/{studio-host-console-Dz8tEAST.js → studio-host-console-Bqya7q0s.js} +2 -2
  32. package/page/assets/{studio-labels-C5heV8lN.js → studio-labels-D1VY2Jy8.js} +1 -1
  33. package/page/assets/studio-live-Ccx0NJuI.js +5 -0
  34. package/page/assets/{studio-map-DzrF-FCH.js → studio-map-B4_FRhhr.js} +1 -1
  35. package/page/assets/studio-session-CjUQSXx0.js +1 -0
  36. package/page/assets/studio-trace-replay-DXW5DXpK.js +3 -0
  37. package/page/assets/{studio-type-checker-DCAG9kT0.js → studio-type-checker-BbUSqqOS.js} +1 -1
  38. package/page/assets/tool-schema-BmRYaywn.js +17 -0
  39. package/page/assets/{trace-record-CGww68wU.js → trace-record-DxgSKmYY.js} +1 -1
  40. package/page/assets/tree-3N-1RPZz.js +3 -0
  41. package/page/assets/{turn-client-Bn130DZC.js → turn-client-DN8PawJr.js} +2 -2
  42. package/page/assets/{use-one-call-B_dBxZ07.js → use-one-call-mxMqUe5Q.js} +1 -1
  43. package/page/assets/{use-second-ticker-DtnVtLQo.js → use-second-ticker-CEwOSS-d.js} +1 -1
  44. package/page/assets/{workspace-Cy2likdd.js → workspace-CTSW941G.js} +1 -1
  45. package/page/index.html +16 -16
  46. package/replay.d.ts +13 -8
  47. package/replay.js +33 -31
  48. package/run-payload.d.ts +20 -6
  49. package/run-payload.js +85 -13
  50. package/runtime-scope.js +1 -0
  51. package/runtime.js +1 -0
  52. package/server/project.js +5 -32
  53. package/transport.d.ts +1 -3
  54. package/transport.js +0 -9
  55. package/ui/lib/acting-as.js +1 -6
  56. package/ui/lib/run-keys.d.ts +15 -5
  57. package/ui/lib/run-keys.js +80 -16
  58. package/ui/lib/studio-conversation.d.ts +2 -3
  59. package/ui/lib/studio-conversation.js +28 -65
  60. package/ui/lib/studio-keep.d.ts +34 -0
  61. package/ui/lib/studio-keep.js +202 -0
  62. package/ui/lib/studio-map-kept.d.ts +2 -2
  63. package/ui/lib/studio-map-kept.js +5 -10
  64. package/ui/lib/studio-open.d.ts +1 -1
  65. package/ui/lib/studio-open.js +5 -5
  66. package/ui/lib/studio-page.js +1 -7
  67. package/ui/lib/studio-restore.d.ts +2 -3
  68. package/ui/lib/studio-restore.js +8 -48
  69. package/ui/lib/studio-run-open.d.ts +10 -5
  70. package/ui/lib/studio-run-open.js +18 -9
  71. package/ui/lib/studio-session.d.ts +38 -5
  72. package/ui/lib/studio-session.js +133 -3
  73. package/ui/lib/studio-store.js +8 -30
  74. package/ui/profile-editor.js +3 -6
  75. package/ui/studio-compare.js +266 -49
  76. package/ui/studio-run.js +29 -15
  77. package/ui/studio-screen.d.ts +1 -1
  78. package/ui/studio-screen.js +8 -9
  79. package/ui/studio-trace-replay.js +39 -14
  80. package/vite.mjs +1 -1
  81. package/page/assets/Banner-DnfOgQq4.js +0 -4
  82. package/page/assets/browser-engine-BQs_4RXH.js +0 -11
  83. package/page/assets/browser-transport-K6LWGuCA.js +0 -45
  84. package/page/assets/index-8zuMVtQh.js +0 -145
  85. package/page/assets/reader-YWCb-VWE.js +0 -5
  86. package/page/assets/studio-live-ed1SR-Py.js +0 -5
  87. package/page/assets/studio-session-yEqFQo5o.js +0 -1
  88. package/page/assets/studio-trace-replay-WLO52a22.js +0 -3
  89. package/page/assets/tool-schema-BJnLgvo3.js +0 -17
  90. package/page/assets/tree-CvHjrQ-G.js +0 -3
  91. package/run-payload-core.d.ts +0 -28
  92. package/run-payload-core.js +0 -117
@@ -1,15 +1,18 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Button } from '@astryxdesign/core/Button';
2
+ import { Center } from '@astryxdesign/core/Center';
3
+ import { ComplexSelector } from '@astryxdesign/core/ComplexSelector';
3
4
  import { Divider } from '@astryxdesign/core/Divider';
4
5
  import { HStack } from '@astryxdesign/core/HStack';
5
6
  import { Icon } from '@astryxdesign/core/Icon';
6
7
  import { IconButton } from '@astryxdesign/core/IconButton';
8
+ import { RadioList, RadioListItem } from '@astryxdesign/core/RadioList';
7
9
  import { StackItem } from '@astryxdesign/core/Stack';
8
10
  import { Text } from '@astryxdesign/core/Text';
9
11
  import { VStack } from '@astryxdesign/core/VStack';
10
- import { IconLayoutSidebarLeftCollapse, IconLayoutSidebarLeftExpand } from '@tabler/icons-react';
11
- import { ChatComposerBar, InPlace, PaneFailure, PaneLoading, TheoremChat, } from '@theoremjs/react/ui';
12
- import { createHttpTransport, createTraceFeed } from '@theoremjs/web/client';
12
+ import { IconInputAi, IconLayoutSidebarLeftCollapse, IconLayoutSidebarLeftExpand, } from '@tabler/icons-react';
13
+ import { createComposerPendingMessage, orderComposerPendingMessages, removeComposerPendingMessage, } from '@theoremjs/agents/interface';
14
+ import { ChatComposerBar, DEFAULT_CHAT_MAX_WIDTH, generationOptions, InPlace, PaneFailure, PaneLoading, TheoremChat, } from '@theoremjs/react/ui';
15
+ import { clientFailure, composerFieldsFromDraft, composerHasPayload, createHttpTransport, createTraceFeed, encodeComposerDraft, } from '@theoremjs/web/client';
13
16
  import { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, useSyncExternalStore, } from 'react';
14
17
  import { atStart } from "../mod.js";
15
18
  import { useActingAs } from "./lib/acting-as.js";
@@ -72,40 +75,45 @@ export function useLoadedStamp(answer) {
72
75
  setLoaded(now);
73
76
  return now;
74
77
  }
78
+ /** A side's chat as it stands, and as it changes. Null until the side is mounted. */
79
+ function useSideState(chat) {
80
+ const subscribe = useCallback((listener) => (chat ? chat.subscribe(listener) : () => { }), [chat]);
81
+ return useSyncExternalStore(subscribe, () => chat?.getState() ?? null);
82
+ }
75
83
  /**
76
- * One message sent to both sides, and which of them still answers it. A side rests when its turn
77
- * is done: the reply ended, and any question it stopped on was answered.
84
+ * The two sides' chats, and which of them still answers. A side rests when its turn is done: the
85
+ * reply ended, and any question it stopped on was answered.
78
86
  */
79
87
  function usePair() {
80
- const chats = useRef({ saved: null, edited: null });
81
- const [busy, setBusy] = useState([]);
82
- const done = useCallback((side) => {
83
- setBusy((sides) => sides.filter((other) => other !== side));
84
- }, []);
85
- const send = useCallback(async (text) => {
86
- const sent = SIDES.filter((side) => chats.current[side]);
87
- setBusy(sent);
88
- const answers = sent.map(async (side) => {
89
- // A side's send resolves once its reply is done, or at once when it could not take it.
90
- const added = await chats.current[side]?.send(text).catch(() => null);
91
- done(side);
92
- return [side, added ?? null];
88
+ const handles = useRef({ saved: null, edited: null });
89
+ const [chats, setChats] = useState({
90
+ saved: null,
91
+ edited: null,
92
+ });
93
+ const [refs] = useState(() => {
94
+ const ref = (side) => (handle) => {
95
+ handles.current[side] = handle;
96
+ const chat = handle?.controller ?? null;
97
+ setChats((now) => (now[side] === chat ? now : { ...now, [side]: chat }));
98
+ };
99
+ return { saved: ref('saved'), edited: ref('edited') };
100
+ });
101
+ const states = { saved: useSideState(chats.saved), edited: useSideState(chats.edited) };
102
+ const busy = SIDES.filter((side) => states[side] && states[side].phase !== 'idle');
103
+ const send = useCallback(async (text, options) => {
104
+ const sent = SIDES.flatMap((side) => {
105
+ const chat = handles.current[side]?.controller;
106
+ return chat ? [[side, chat]] : [];
93
107
  });
108
+ // A side's send resolves once its reply is done, or at once when it could not take it.
109
+ const answers = sent.map(async ([side, chat]) => [side, await chat.sendText(text, options).catch(() => null)]);
94
110
  return new Map(await Promise.all(answers));
95
- }, [done]);
111
+ }, []);
96
112
  const stop = useCallback(() => {
97
113
  for (const side of SIDES)
98
- chats.current[side]?.stop();
114
+ handles.current[side]?.stop();
99
115
  }, []);
100
- const [refs] = useState(() => ({
101
- saved: (handle) => {
102
- chats.current.saved = handle;
103
- },
104
- edited: (handle) => {
105
- chats.current.edited = handle;
106
- },
107
- }));
108
- return useMemo(() => ({ busy, send, stop, refs, chats }), [busy, send, stop, refs]);
116
+ return { busy, send, stop, refs, handles, chats, states };
109
117
  }
110
118
  /** Whether the files' side is put away, for every comparison in this tab. */
111
119
  const savedSide = { isHidden: false, listeners: new Set() };
@@ -172,10 +180,206 @@ export function SavedSide({ isCompared = true, children, }) {
172
180
  function NotRunning({ refusal, actions }) {
173
181
  return (_jsx(PaneFailure, { title: NOT_RUNNING[refusal.reason] ?? 'Your edits are not running.', actions: actions, children: _jsx(RefusalDetail, { refusal: refusal }) }));
174
182
  }
175
- /** The message both sides get, and the stop for both while either answers. */
176
- function SharedComposer({ handle, why, isBusy, onSend, onStop, }) {
177
- const [text, setText] = useState('');
178
- return (_jsxs(HStack, { gap: 2, vAlign: "end", padding: 3, children: [_jsx(StackItem, { size: "fill", children: _jsx(ChatComposerBar, { handle: handle, draftText: text, onDraftTextChange: setText, onSubmit: onSend, isDisabled: isBusy || why !== undefined, placeholder: why ?? 'Message both' }) }), isBusy && _jsx(Button, { label: "Stop", variant: "ghost", onClick: onStop })] }));
183
+ /** The phase the shared composer shows: streaming while either side streams, else gated while either waits. */
184
+ function pairPhase(states) {
185
+ if (states.some((state) => state.phase === 'streaming'))
186
+ return 'streaming';
187
+ return states.some((state) => state.phase === 'gated') ? 'gated' : 'idle';
188
+ }
189
+ function allowsSteering(state) {
190
+ return state.iface != null && 'allowSteering' in state.iface && state.iface.allowSteering;
191
+ }
192
+ /** Each side's pending messages, once each: both sides hold a shared message under one id. */
193
+ function pairPending(states) {
194
+ const byId = new Map(states.flatMap((state) => state.pendingMessages.map((message) => [message.id, message])));
195
+ return orderComposerPendingMessages([...byId.values()]);
196
+ }
197
+ /** Whether a side's running turn would take a steer now. */
198
+ const takesSteer = (state) => state.phase === 'streaming' && allowsSteering(state);
199
+ /** A side's name where the two are named in a line. */
200
+ const SIDE_NAMES = { saved: 'Saved', edited: 'Edited' };
201
+ /** One column of the model control: what this side's own composer offers, and it alone. */
202
+ function SideGeneration({ side, chat, state }) {
203
+ const { selectedModel, selectedEffort } = state.session;
204
+ if (!state.iface)
205
+ return null;
206
+ const { models, efforts } = generationOptions(state.iface, selectedModel);
207
+ const isDisabled = state.phase === 'streaming';
208
+ return (_jsxs(VStack, { gap: 3, style: { flex: '1 1 12rem', minWidth: 0 }, children: [models.length > 0 ? (_jsx(RadioList, { label: SIDE_NAMES[side], size: "sm", isDisabled: isDisabled, value: selectedModel ?? '', onChange: (modelId) => {
209
+ chat.setGeneration({ modelId });
210
+ }, children: models.map((model) => (_jsx(RadioListItem, { value: model.id, label: model.id, description: model.label === model.id ? undefined : model.label }, model.id))) })) : (_jsxs(VStack, { gap: 1, children: [_jsx(Text, { type: "supporting", weight: "semibold", children: SIDE_NAMES[side] }), _jsx(Text, { type: "supporting", color: "secondary", children: selectedModel })] })), selectedModel && efforts.length > 0 && (_jsx(RadioList, { label: "Effort", size: "sm", isDisabled: isDisabled, value: selectedEffort ?? '', onChange: (effort) => {
211
+ chat.setGeneration({ modelId: selectedModel, effort });
212
+ }, children: efforts.map((option) => (_jsx(RadioListItem, { value: option.alias, label: option.alias, description: option.level }, option.alias))) }))] }));
213
+ }
214
+ /**
215
+ * The composer's model control when two chats share it: each side's choices, side by side. A pick
216
+ * is that side's, held by its chat, as its own composer would hold it.
217
+ */
218
+ function PairGeneration({ sides }) {
219
+ const offered = sides.filter(({ state }) => {
220
+ const { models, efforts } = state.iface
221
+ ? generationOptions(state.iface, state.session.selectedModel)
222
+ : { models: [], efforts: [] };
223
+ return models.length + efforts.length > 0;
224
+ });
225
+ if (offered.length === 0)
226
+ return null;
227
+ const running = sides.flatMap(({ side, state }) => {
228
+ const model = state.session.selectedModel;
229
+ return model ? [{ side, model }] : [];
230
+ });
231
+ const label = new Set(running.map(({ model }) => model)).size === 1
232
+ ? running[0].model
233
+ : running.map(({ side, model }) => `${SIDE_NAMES[side]} ${model}`).join(' · ');
234
+ return (_jsx(ComplexSelector, { label: "Model", size: "sm", variant: "ghost", placement: "above", startIcon: _jsx(IconInputAi, { size: 14 }), value: label, triggerLabel: label, children: () => (_jsx(HStack, { gap: 4, padding: 3, wrap: "wrap", style: {
235
+ width: 'min(32rem, calc(100vw - 2rem))',
236
+ maxHeight: 'min(60vh, 28rem)',
237
+ overflowY: 'auto',
238
+ }, children: sides.map((side) => (_jsx(SideGeneration, { ...side }, side.side))) })) }));
239
+ }
240
+ /**
241
+ * The one composer of both sides. It only types for them: each side does with what is sent what
242
+ * its own composer would. An idle side sends it, a busy one queues it; a steer goes to each side
243
+ * whose running turn takes one; and each side refuses a file its profile does not take. The model
244
+ * is each side's own.
245
+ */
246
+ function SharedComposer({ sides, edited, inputRef, }) {
247
+ const iface = edited.iface ?? undefined;
248
+ const [draftText, setDraftText] = useState('');
249
+ const [pendingFiles, setPendingFiles] = useState([]);
250
+ const [pendingVoice, setPendingVoice] = useState([]);
251
+ const [failure, setFailure] = useState(null);
252
+ const states = sides.map((side) => side.state);
253
+ const phase = pairPhase(states);
254
+ if (!iface)
255
+ return null;
256
+ const options = () => ({ files: pendingFiles, voice: pendingVoice });
257
+ const message = async (kind) => createComposerPendingMessage({
258
+ kind,
259
+ draft: await encodeComposerDraft({ text: draftText, pendingFiles, pendingVoice }),
260
+ });
261
+ const clear = () => {
262
+ setDraftText('');
263
+ setPendingFiles([]);
264
+ setPendingVoice([]);
265
+ };
266
+ /** Each side as its own composer would: an idle side sends, a busy one takes `kind`. */
267
+ const deliver = async (kind) => {
268
+ const text = draftText;
269
+ const sent = options();
270
+ let shared;
271
+ try {
272
+ shared = await message(kind === 'send_now' ? 'queue' : kind);
273
+ }
274
+ catch (error) {
275
+ // The draft stays in the composer, with why it could not go.
276
+ setFailure(clientFailure(error, iface.labels));
277
+ return;
278
+ }
279
+ setFailure(null);
280
+ clear();
281
+ for (const { chat, state } of sides) {
282
+ if (kind === 'steer') {
283
+ if (takesSteer(state))
284
+ void chat.pend(shared);
285
+ continue;
286
+ }
287
+ if (kind === 'stash') {
288
+ void chat.pend(shared);
289
+ continue;
290
+ }
291
+ // why: reading the attachments took time, and a side may have finished or started since.
292
+ if (chat.getState().phase === 'idle') {
293
+ void chat.sendText(text, sent);
294
+ continue;
295
+ }
296
+ void (kind === 'send_now' ? chat.sendNow(shared) : chat.pend(shared));
297
+ }
298
+ };
299
+ const each = (act) => {
300
+ for (const { chat } of sides)
301
+ act(chat);
302
+ };
303
+ const pending = pairPending(states);
304
+ return (_jsx(SharedDock, { children: _jsx(ChatComposerBar
305
+ // why: a steer goes only to a running turn, so one that no side would take is not offered.
306
+ , {
307
+ // why: a steer goes only to a running turn, so one that no side would take is not offered.
308
+ iface: {
309
+ ...iface,
310
+ ...('allowSteering' in iface
311
+ ? { allowSteering: sides.some(({ state }) => takesSteer(state)) }
312
+ : {}),
313
+ }, draftText: draftText, pendingFiles: pendingFiles, pendingVoice: pendingVoice, pendingMessages: pending, issues: [], phase: phase, failure: failure, placeholder: "Message both", inputRef: inputRef, onDraftTextChange: setDraftText, onFilesSelected: (files) => {
314
+ setPendingFiles((prev) => [...prev, ...files]);
315
+ }, onAttachmentRemove: (index) => {
316
+ setPendingFiles((prev) => prev.filter((_, at) => at !== index));
317
+ }, onVoiceStaged: (file) => {
318
+ setPendingVoice([file]);
319
+ }, onVoiceClear: () => {
320
+ setPendingVoice([]);
321
+ }, onSubmit: () => {
322
+ void deliver('queue');
323
+ }, onStop: () => {
324
+ each((chat) => {
325
+ chat.stop();
326
+ });
327
+ }, onMenuAction: (action) => {
328
+ void deliver(action);
329
+ }, generationSelect: _jsx(PairGeneration, { sides: sides }), slotChoices: edited.slots && {
330
+ ...edited.slots,
331
+ onChange: (name, value) => {
332
+ each((chat) => {
333
+ chat.pickSlot(name, value);
334
+ });
335
+ },
336
+ }, onPendingMove: (id, direction) => {
337
+ each((chat) => {
338
+ chat.movePending(id, direction);
339
+ });
340
+ }, onPendingRemove: (id) => {
341
+ each((chat) => {
342
+ chat.setPendingMessages((prev) => removeComposerPendingMessage(prev, id));
343
+ });
344
+ }, onPendingQueue: (id) => {
345
+ each((chat) => {
346
+ chat.queuePending(id);
347
+ });
348
+ }, onPendingRestore: (id) => {
349
+ void (async () => {
350
+ const restored = pending.find((held) => held.id === id);
351
+ if (!restored)
352
+ return;
353
+ // As a chat restores: what the composer holds is stashed first.
354
+ if (composerHasPayload(draftText, pendingFiles, pendingVoice))
355
+ await deliver('stash');
356
+ each((chat) => {
357
+ chat.setPendingMessages((prev) => removeComposerPendingMessage(prev, id));
358
+ });
359
+ const fields = composerFieldsFromDraft(restored.draft);
360
+ setDraftText(fields.text);
361
+ setPendingFiles(fields.files);
362
+ setPendingVoice(fields.voice);
363
+ })();
364
+ }, onPendingSendNow: (id) => {
365
+ for (const { chat, state } of sides) {
366
+ const held = state.pendingMessages.find((m) => m.id === id);
367
+ if (!held)
368
+ continue;
369
+ void chat.sendNow(held);
370
+ }
371
+ } }) }));
372
+ }
373
+ /**
374
+ * Where the shared composer sits: the width and inset of a chat's own dock.
375
+ * why: it sits outside both chats' layouts, so it brings the 12px sides and 24px below they give.
376
+ */
377
+ function SharedDock({ children }) {
378
+ return (_jsx(VStack, { paddingInline: 3, paddingBlockEnd: 6, children: _jsx(Center, { axis: "horizontal", width: "100%", children: _jsx(VStack, { width: "100%", maxWidth: DEFAULT_CHAT_MAX_WIDTH, children: children }) }) }));
379
+ }
380
+ /** The composer while the edits cannot take a message: it says why. */
381
+ function WaitingComposer({ handle, why }) {
382
+ return (_jsx(SharedDock, { children: _jsx(ChatComposerBar, { handle: handle, draftText: "", onDraftTextChange: () => { }, onSubmit: () => { }, isDisabled: true, placeholder: why }) }));
179
383
  }
180
384
  /** The agent as the files hold it: an edit may have renamed it, or made it another type. */
181
385
  function savedOf(tested, profileId) {
@@ -275,24 +479,32 @@ function useComparison({ project, profileId, tested, note, traces }) {
275
479
  }
276
480
  /**
277
481
  * The chat the page holds: a message goes to both sides while both are there and can take it, and
278
- * to the one side otherwise. It answers with what the edits said.
482
+ * to the one side otherwise. It answers with what the edits said, and its controller is theirs.
279
483
  */
280
- function useChatHandle(chatRef, pair, only, canSendBoth) {
281
- const { send, stop, chats } = pair;
282
- const sendBoth = useCallback(async (text) => (await send(text)).get('edited') ?? null, [send]);
484
+ function useChatHandle(chatRef, pair, only, canSendBoth, sharedInput) {
485
+ const { send, stop, handles } = pair;
283
486
  useImperativeHandle(chatRef, () => ({
284
- send: (text) => {
487
+ send: (text, options) => {
285
488
  if (only)
286
- return chats.current[only]?.send(text) ?? Promise.resolve(null);
287
- return canSendBoth ? sendBoth(text) : Promise.resolve(null);
489
+ return handles.current[only]?.send(text, options) ?? Promise.resolve(null);
490
+ if (!canSendBoth)
491
+ return Promise.resolve(null);
492
+ return send(text, options).then((answers) => answers.get('edited') ?? null);
288
493
  },
289
494
  stop,
290
- // With both sides shown, the edited side answers `send`, so its composer takes the focus.
291
495
  focus: () => {
292
- chats.current[only ?? 'edited']?.focus();
496
+ if (only)
497
+ handles.current[only]?.focus();
498
+ else
499
+ sharedInput.current?.focus();
293
500
  },
294
- }), [only, canSendBoth, sendBoth, stop, chats]);
295
- return sendBoth;
501
+ get controller() {
502
+ const chat = handles.current[only ?? 'edited']?.controller;
503
+ if (!chat)
504
+ throw new Error('The chat is not open yet.');
505
+ return chat;
506
+ },
507
+ }), [only, canSendBoth, send, stop, handles, sharedInput]);
296
508
  }
297
509
  /**
298
510
  * A project's text or image profile, run by the studio's local server. While the builder has
@@ -307,7 +519,13 @@ export function ProjectChat(props) {
307
519
  const showsSaved = view.inFiles && !(view.isEditing && isSavedHidden);
308
520
  const isShared = view.isShared && showsSaved;
309
521
  const only = isShared ? undefined : showsSaved ? 'saved' : 'edited';
310
- const sendBoth = useChatHandle(chatRef, pair, only, !isBusy && isReady);
522
+ const sharedInput = useRef(null);
523
+ useChatHandle(chatRef, pair, only, !isBusy && isReady, sharedInput);
524
+ const shared = SIDES.flatMap((side) => {
525
+ const chat = pair.chats[side];
526
+ const state = pair.states[side];
527
+ return chat && state ? [{ side, chat, state }] : [];
528
+ });
311
529
  const common = {
312
530
  detectCodeLanguage: true,
313
531
  labels: STUDIO_LABELS,
@@ -323,7 +541,6 @@ export function ProjectChat(props) {
323
541
  // A new load is a new transport: the chat reads it in place and keeps its transcript.
324
542
  transport: transports.edited, conversation: view.conversations.current.edited ?? view.conversations.current.saved, onConversationChange: view.onChange.edited,
325
543
  // Under a refusal nothing reaches it: the edits it ran are not loaded.
326
- chatRef: refused ? undefined : pair.refs.edited })) }) }, "edited"))] }) }), isShared && (_jsx(SharedComposer, { handle: profileId, why: whyNot(refused !== undefined, isReady), isBusy: isBusy, onSend: (text) => {
327
- void sendBoth(text);
328
- }, onStop: pair.stop }))] }));
544
+ chatRef: refused ? undefined : pair.refs.edited })) }) }, "edited"))] }) }), isShared &&
545
+ (isReady && pair.states.edited ? (_jsx(SharedComposer, { sides: shared, edited: pair.states.edited, inputRef: sharedInput })) : (_jsx(WaitingComposer, { handle: profileId, why: whyNot(refused !== undefined, isReady) ?? 'Loading your edits' })))] }));
329
546
  }
package/ui/studio-run.js CHANGED
@@ -2,9 +2,9 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Icon } from '@astryxdesign/core/Icon';
3
3
  import { IconKey } from '@tabler/icons-react';
4
4
  import { PaneState, TheoremThemeProvider, TracePlacement } from '@theoremjs/react/ui';
5
- import { useEffect, useState } from 'react';
5
+ import { useEffect, useMemo, useState } from 'react';
6
6
  import { studioKeySlots } from "../browser.js";
7
- import { modelRoute, modelSlots, onStudioLocal, readStudioRunIdFromUrl, STUDIO_PROVIDERS, } from "../mod.js";
7
+ import { modelRoute, modelSlots, onStudioLocal, readStudioRunIdFromUrl, STUDIO_PROVIDERS, withStudioRunCredentials, } from "../mod.js";
8
8
  import { recordsTraces } from "./lib/project-traces.js";
9
9
  import { askRunKeys } from "./lib/run-keys.js";
10
10
  import { ProjectContext } from "./lib/studio-project.js";
@@ -27,7 +27,10 @@ function providersOf(payload) {
27
27
  * `opened` is what `openStudioRun` returned for this tab.
28
28
  */
29
29
  export function StudioRunScreen({ opened, supplies, }) {
30
- const { payload } = opened;
30
+ const fromStudio = useFromStudio(opened.masked);
31
+ const payload = useMemo(() => fromStudio.tools
32
+ ? withStudioRunCredentials(opened.payload, fromStudio.tools)
33
+ : opened.payload, [opened.payload, fromStudio.tools]);
31
34
  // The agent and the agents it calls each read their own key slots.
32
35
  const profiles = [
33
36
  payload.profile,
@@ -46,7 +49,15 @@ export function StudioRunScreen({ opened, supplies, }) {
46
49
  ? []
47
50
  : Object.values(profile.models).flatMap((binding) => Object.values(modelSlots(providersOf(payload), binding)))),
48
51
  ], supplies);
49
- const keysFromStudio = useStudioKeys(!opened.project && payload.connectionMode === 'byok', connection.setVault);
52
+ const needsKeys = !opened.project && payload.connectionMode === 'byok';
53
+ const { setVault } = connection;
54
+ useEffect(() => {
55
+ if (needsKeys && fromStudio.keys)
56
+ setVault(fromStudio.keys);
57
+ }, [needsKeys, fromStudio.keys, setVault]);
58
+ const isGone = fromStudio.gone && (needsKeys || opened.masked);
59
+ // why: a tool called before its credentials arrive would go out with them masked.
60
+ const isWaiting = opened.masked && !fromStudio.tools && !fromStudio.gone;
50
61
  const traced = recordsTraces(payload);
51
62
  const [traceOpen, setTraceOpen] = useState(false);
52
63
  const phone = usePhone();
@@ -54,26 +65,29 @@ export function StudioRunScreen({ opened, supplies, }) {
54
65
  const title = studioRunTitle(payload);
55
66
  return (_jsxs(TheoremThemeProvider, { mode: "dark", children: [_jsx("title", { children: `${title} · theorem studio` }), _jsx(TracePlacement, { value: "panel", children: _jsxs("div", { className: "run-page", children: [_jsx("div", { className: "run-controls", children: traced ? (_jsx(TraceButton, { open: traceOpen, isIconOnly: phone, onToggle: () => {
56
67
  setTraceOpen((open) => !open);
57
- } })) : null }), keysFromStudio === 'gone' ? (_jsx(PaneState, { icon: _jsx(Icon, { icon: IconKey, size: "lg", color: "secondary" }), title: "Set your keys in the studio", description: "This tab takes its keys from the studio tab that opened it, and that tab is closed. Open the agent in a new tab from the studio again." })) : (_jsx(ProjectContext.Provider, { value: opened.project, children: _jsx(StudioRunner, { payload: payload, runtime: runtime, trace: traced ? traceOpen : undefined, flush: true, columns: true, className: "run-chat" }, mode) }))] }) })] }));
68
+ } })) : null }), isGone ? (_jsx(PaneState, { icon: _jsx(Icon, { icon: IconKey, size: "lg", color: "secondary" }), title: "Open the agent from the studio again", description: "This tab takes its keys and its tools' credentials from the studio tab that opened it, and that tab no longer holds them: it was closed, reloaded, or left the studio. Open the agent in a new tab from the studio again." })) : isWaiting ? null : (_jsx(ProjectContext.Provider, { value: opened.project, children: _jsx(StudioRunner, { payload: payload, runtime: runtime, trace: traced ? traceOpen : undefined, flush: true, columns: true, className: "run-chat" }, mode) }))] }) })] }));
58
69
  }
59
70
  /**
60
- * Fills the vault from the studio tab that opened this one, when the run reads this browser's
61
- * keys. `gone` when there is no studio tab left to ask.
71
+ * What the studio tab that opened this one answers: its keys, and the credentials the kept copy of
72
+ * this run masked. `gone` when no studio tab holds them for it.
62
73
  */
63
- function useStudioKeys(needed, setVault) {
74
+ function useFromStudio(masked) {
75
+ const [answer, setAnswer] = useState();
64
76
  const [gone, setGone] = useState(false);
65
77
  useEffect(() => {
66
- if (!needed)
67
- return;
68
78
  const run = readStudioRunIdFromUrl();
69
- const stop = run ? askRunKeys(run, setVault) : null;
79
+ const stop = run
80
+ ? askRunKeys(run, (keys, tools) => {
81
+ setAnswer({ keys, tools });
82
+ }, () => {
83
+ setGone(true);
84
+ })
85
+ : null;
70
86
  if (!stop) {
71
87
  setGone(true);
72
88
  return;
73
89
  }
74
90
  return stop;
75
- }, [needed, setVault]);
76
- if (!needed)
77
- return 'unneeded';
78
- return gone ? 'gone' : 'asked';
91
+ }, []);
92
+ return { ...answer, tools: masked ? answer?.tools : undefined, gone };
79
93
  }
@@ -4,7 +4,7 @@ import { type ProjectFiles, type ProjectSession } from './lib/studio-project.ts'
4
4
  import { type RestoredStudio } from './lib/studio-session.ts';
5
5
  import type { ProbeResult } from './lib/tool-probe.ts';
6
6
  import { type StudioHost, type StudioOpened } from './studio-host.ts';
7
- /** The workspace's store, kept in this tab's sessionStorage, and the open agent's draft from it. */
7
+ /** The workspace's store, kept in this tab's records, and the open agent's draft from it. */
8
8
  declare function useStudioWorkspace(start: RestoredStudio, project: ProjectSession | undefined): {
9
9
  store: {
10
10
  getWorkspace: () => StudioWorkspace;
@@ -25,7 +25,7 @@ import { IconAdjustmentsHorizontal, IconArrowBarToDown, IconArrowLeft, IconBrows
25
25
  import { profileGraphFacet } from '@theoremjs/agents';
26
26
  import { InPlace, PaneFailure, RaisedPane, useDisclosureMotion, } from '@theoremjs/react/ui';
27
27
  import { canonical } from "../canonical.js";
28
- import { addAgent, addArchitectExample, addProvider, addResearchExample, agentNodeId, compileWorkspace, createBlankDraft, createConsoleExampleDraft, createDecisionExampleDraft, createExampleDraft, createGeminiEmbeddingExampleDraft, createLiveExampleDraft, createNarratorExampleDraft, createStudioRunId, draftFacets, duplicateAgent, editedSince, excludeFacet, includableFacets, includeFacet, libraryDraft, localProviderAddress, mergedWithFiles, modelBindingNodeId, modelRoute, modelSharers, modelSlots, nodeOrigins, onStudioLocal, openOutcome, originLabel, originPlace, originWay, providerIdOf, providerNodeId, providerUse, rebased, removeAgent, removeLibraryTool, removeProvider, renameProvider, reopened, resetAgent, resetAgentNode, resetLibraryTool, resetProvider, sampleToolInput, saveStudioRunPayload, scopedNodeId, setToolAllowed, sharedAsk, sharedAt, sharedEntries, studioNodeRef, studioSource, studioTree, toolSpecKeyOf, withAgentDraft, withFilesChosen, withProvider, workspaceNodeRef, workspaceRunAgent, workspaceTree, writeAsk, } from "../mod.js";
28
+ import { addAgent, addArchitectExample, addProvider, addResearchExample, agentNodeId, compileWorkspace, createBlankDraft, createConsoleExampleDraft, createDecisionExampleDraft, createExampleDraft, createGeminiEmbeddingExampleDraft, createLiveExampleDraft, createNarratorExampleDraft, draftFacets, duplicateAgent, editedSince, excludeFacet, includableFacets, includeFacet, libraryDraft, localProviderAddress, mergedWithFiles, modelBindingNodeId, modelRoute, modelSharers, modelSlots, nodeOrigins, onStudioLocal, openOutcome, originLabel, originPlace, originWay, providerIdOf, providerNodeId, providerUse, rebased, removeAgent, removeLibraryTool, removeProvider, renameProvider, reopened, resetAgent, resetAgentNode, resetLibraryTool, resetProvider, sampleToolInput, scopedNodeId, setToolAllowed, sharedAsk, sharedAt, sharedEntries, studioNodeRef, studioSource, studioTree, toolSpecKeyOf, withAgentDraft, withFilesChosen, withProvider, workspaceNodeRef, workspaceRunAgent, workspaceTree, writeAsk, } from "../mod.js";
29
29
  import { slotProviders } from "../requirements.js";
30
30
  import { studioSurface } from "../surface.js";
31
31
  import './studio.css';
@@ -42,7 +42,7 @@ import { FACET_ICON } from "./lib/facet-icons.js";
42
42
  import { movePanel } from "./lib/panel-motion.js";
43
43
  import { screenEndpoint } from "./lib/project-address.js";
44
44
  import { recordsTraces } from "./lib/project-traces.js";
45
- import { answerRunKeys } from "./lib/run-keys.js";
45
+ import { answerRunKeys, handOffStudioRun } from "./lib/run-keys.js";
46
46
  import { sendWhenReady } from "./lib/send-when-ready.js";
47
47
  import { clearConversation, restoreConversation, saveConversation, } from "./lib/studio-conversation.js";
48
48
  import { STUDIO_EXAMPLES } from "./lib/studio-examples.js";
@@ -559,10 +559,9 @@ function innerNodeId(id, focus) {
559
559
  return 'identity';
560
560
  return id.startsWith(`${root}/`) ? id.slice(root.length + 1) : undefined;
561
561
  }
562
- /** Hands the compiled agent to a new tab through this browser's storage; the run route reads it back. */
563
- function openInNewTab(payload, project) {
564
- const runId = createStudioRunId();
565
- saveStudioRunPayload(payload, runId);
562
+ /** Hands the compiled agent to a new tab through the browser's keep; the run route takes it. */
563
+ async function openInNewTab(payload, project) {
564
+ const runId = await handOffStudioRun(payload);
566
565
  // A project's agent runs the project's code on its own page too.
567
566
  const named = project ? `&project=${encodeURIComponent(project.name)}` : '';
568
567
  // why: no `noopener`: the run tab asks this tab for its keys, which never leave memory.
@@ -803,7 +802,7 @@ function runMembers(store, page, chat) {
803
802
  const result = runNow();
804
803
  if (!result)
805
804
  return;
806
- openInNewTab({
805
+ void openInNewTab({
807
806
  ...runPayload(result),
808
807
  connectionMode: page.current.on.mode,
809
808
  localBaseUrl: page.current.connection.local.baseUrl,
@@ -892,7 +891,7 @@ function OpenInNewTabButton({ compiled, chattedId, blocked, connection, isIconOn
892
891
  'Run this agent on a full page of its own, in a new tab, the way a person using it would see it', onClick: () => {
893
892
  const run = compiled && workspaceRunAgent(compiled, chattedId);
894
893
  if (run)
895
- openInNewTab({ ...runPayload(run), ...connection }, project);
894
+ void openInNewTab({ ...runPayload(run), ...connection }, project);
896
895
  } }));
897
896
  }
898
897
  /** Get code: a .zip, Copy, or Copy for LLM, for every agent; off while the workspace has issues. */
@@ -952,7 +951,7 @@ function ExportMenu({ store, compile, copy, }) {
952
951
  },
953
952
  ] }));
954
953
  }
955
- /** The workspace's store, kept in this tab's sessionStorage, and the open agent's draft from it. */
954
+ /** The workspace's store, kept in this tab's records, and the open agent's draft from it. */
956
955
  function useStudioWorkspace(start, project) {
957
956
  // The settings the project's profiles share, on the agents it opened as: a change to one is
958
957
  // made on each of them.