@hanzo/app 0.3.66 → 0.3.68

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.
package/dist/bots/Bots.js CHANGED
@@ -1,512 +1,299 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- // The Bots app.
3
+ // The Bots app: make a bot, open it, talk to it.
4
4
  //
5
- // Bots are autonomous workers for your organization: each has a model,
6
- // instructions, tools, and a record of everything it has accomplished.
5
+ // Three columns, as the desktop app draws them: the roster (the bots as a grid
6
+ // of faces, then the rest with their last word, then you), the thread with the
7
+ // open bot, and the panel of what that bot has. Every row, message and switch is
8
+ // a platform record — `/v1/agents` and the runs it records — and a section with
9
+ // nothing behind it is not drawn.
7
10
  //
8
- // In live mode, this connects directly to your organization's bots and sessions.
9
- // When visiting without an account, an interactive Example Workspace lets you
10
- // explore how bots use computers to automate sales, triage inboxes, and review code.
11
+ // The same component is the app on hanzo.bot (hanzo.ai's /bots) and on
12
+ // hanzo.team, so a bot made in one is in the other: one list, one thread, one
13
+ // API, read with the reader's own token.
14
+ //
15
+ // Below a tablet the columns are one at a time: the roster, then the thread a
16
+ // press opens (a step in the history, so Back returns to the roster), with the
17
+ // panel over it.
11
18
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
12
- import { Monitor, Plus, Search, Send, Trash2 } from 'lucide-react';
13
- import { phrase } from '@hanzo/i18n';
14
19
  import { useIam } from '@hanzo/iam/react';
15
- import { useAi, ENSO } from '../lib/ai.js';
16
20
  import { useI18n } from '@hanzo/i18n/react';
21
+ import { XStack, YStack } from '@hanzo/gui';
22
+ import { useAi } from '../lib/ai.js';
23
+ import { useKept } from '../kept.js';
17
24
  import { say } from '../failure.js';
18
- import { Input, Text, XStack, YStack } from '@hanzo/gui';
19
- import { Button } from '@hanzo/ui';
20
- import { Lights } from './Lights.js';
21
- import { Face } from './face.js';
22
- import { Runtime } from './runtime.js';
23
- import { DIM, FAINT, GROUND, INK, LINE, RAISED, SURFACE } from './ink.js';
24
- import { BARE, BOXED, CARD, CLIP, GHOST, LABEL, NOTE, TAB } from './kit.js';
25
- import { ALWAYS, ONCE, launch, sessions, steer } from './api.js';
26
- /** How long ago, in the words a roster row has space for. */
27
- function when(iso, t, locale) {
28
- if (!iso)
29
- return '';
30
- const date = new Date(iso);
31
- if (Number.isNaN(date.getTime()))
32
- return '';
33
- const days = Math.floor((Date.now() - date.getTime()) / 86_400_000);
34
- if (days === 0)
35
- return date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' });
36
- if (days === 1)
37
- return t('Yesterday');
38
- if (days < 7)
39
- return date.toLocaleDateString(locale, { weekday: 'short' });
40
- return date.toLocaleDateString(locale, { month: 'short', day: 'numeric' });
41
- }
42
- /** What a run cost, from the fields the run actually recorded. */
43
- function cost(r, t) {
44
- const tokens = (r.promptTokens ?? 0) + (r.completionTokens ?? 0);
45
- return [
46
- r.model,
47
- r.durationMs ? t('{seconds}s', { seconds: (r.durationMs / 1000).toFixed(1) }) : '',
48
- tokens ? t('{count} tokens', { count: tokens }) : '',
49
- ]
50
- .filter(Boolean)
51
- .join(' · ');
25
+ import { Roster } from './Roster.js';
26
+ import { Thread } from './Thread.js';
27
+ import { recordedRun, refusal } from './refusal.js';
28
+ import { Panel } from './Panel.js';
29
+ import { Make } from './Make.js';
30
+ import { ALWAYS, ONCE, PARAM } from './api.js';
31
+ import { instant } from './time.js';
32
+ import { FLOOR, GROUND, LINE } from './ink.js';
33
+ const named = () => typeof window === 'undefined' ? null : new URLSearchParams(window.location.search).get(PARAM);
34
+ /** Writes the open bot into the address: a new step when a phone enters a thread, else in place. */
35
+ function address(name, step) {
36
+ const url = new URL(window.location.href);
37
+ if (name)
38
+ url.searchParams.set(PARAM, name);
39
+ else
40
+ url.searchParams.delete(PARAM);
41
+ const to = `${url.pathname}${url.search}${url.hash}`;
42
+ // Null, not the current state: Next's router stamps its own entries and syncs
43
+ // only a write that does not carry its stamp.
44
+ if (step)
45
+ window.history.pushState(null, '', to);
46
+ else
47
+ window.history.replaceState(null, '', to);
52
48
  }
53
- /** The platform's word for how a bot runs, as a person reads it. An unknown mode stays a token. */
54
- function modeName(mode, t) {
55
- if (mode === ALWAYS)
56
- return t('long-running');
57
- if (!mode || mode === ONCE)
58
- return t('one-shot');
59
- return mode;
49
+ /** The newest run of each bot, from the org's feed (newest first). */
50
+ function lastOf(feed) {
51
+ const out = new Map();
52
+ for (const r of feed)
53
+ if (r.agent && !out.has(r.agent))
54
+ out.set(r.agent, r);
55
+ return out;
60
56
  }
61
- /** A session's status, in the reader's words. An unrecognized status stays a token. */
62
- function sessionStatus(status, t) {
63
- switch (status) {
64
- case 'running':
65
- return t('running');
66
- case 'paused':
67
- return t('paused');
68
- default:
69
- return status;
70
- }
57
+ /** Runs by id, oldest first: a late read never drops a run this page already drew. */
58
+ function merged(a, b) {
59
+ const by = new Map();
60
+ for (const r of [...a, ...b])
61
+ by.set(r.id, r);
62
+ return [...by.values()].sort((x, y) => (instant(x.createdAt) ?? 0) - (instant(y.createdAt) ?? 0));
71
63
  }
72
- /** When something happened, as a number to sort by. */
73
- const at = (iso) => {
74
- const t = iso ? new Date(iso).getTime() : NaN;
75
- return Number.isNaN(t) ? 0 : t;
76
- };
77
- /** A session the platform still considers open. Only these can be steered:
78
- * the route takes a command for a finished session and records it against a
79
- * log nothing is reading, so a control on one is a control over nothing. */
80
- const open = (s) => s.status === 'running' || s.status === 'paused';
81
- /** A Bot's recorded runs as the turns they were. */
82
- function turns(detail, t) {
83
- return (detail?.recentRuns ?? []).flatMap((r) => {
84
- const when = at(r.createdAt);
85
- const out = [];
86
- if (r.input)
87
- out.push({ id: `${r.id}-in`, at: when, who: 'you', text: r.input });
88
- out.push({
89
- id: `${r.id}-out`,
90
- at: when + 1,
91
- who: 'bot',
92
- text: r.error || r.output || t('This run recorded no output.'),
93
- note: cost(r, t),
94
- failed: Boolean(r.error),
95
- });
96
- return out;
97
- });
64
+ /** Whether a media query holds, kept current. False until mounted. */
65
+ function useWide(query) {
66
+ const [on, setOn] = useState(false);
67
+ useEffect(() => {
68
+ const q = window.matchMedia(query);
69
+ const set = () => setOn(q.matches);
70
+ set();
71
+ q.addEventListener('change', set);
72
+ return () => q.removeEventListener('change', set);
73
+ }, [query]);
74
+ return on;
98
75
  }
99
- const EXAMPLE_BOTS = [
100
- {
101
- id: 'bot-sales-outbound',
102
- avatar: '/bots/sales-outbound.png',
103
- name: 'Sales Outbound',
104
- description: phrase('Prospecting, lead qualification, and cold outreach'),
105
- model: 'claude-3-5-sonnet',
106
- executionMode: ALWAYS,
107
- schedule: '0 9 * * 1-5',
108
- updatedAt: new Date(Date.now() - 1000 * 60 * 12).toISOString(),
109
- },
110
- {
111
- id: 'bot-chief',
112
- avatar: '/bots/chief.png',
113
- name: 'Chief',
114
- description: phrase('Executive briefing, team updates, and orchestration'),
115
- model: 'claude-3-5-sonnet',
116
- executionMode: ALWAYS,
117
- schedule: '0 8 * * *',
118
- updatedAt: new Date(Date.now() - 1000 * 60 * 45).toISOString(),
119
- },
120
- {
121
- id: 'bot-inbox-manager',
122
- avatar: '/bots/inbox-manager.png',
123
- name: 'Inbox Manager',
124
- description: phrase('Triage email, draft responses, and surface urgent items'),
125
- model: 'claude-3-5-sonnet',
126
- executionMode: ALWAYS,
127
- schedule: '*/15 * * * *',
128
- updatedAt: new Date(Date.now() - 1000 * 60 * 90).toISOString(),
129
- },
130
- {
131
- id: 'bot-code-reviewer',
132
- name: 'Code Reviewer',
133
- description: phrase('Analyze pull requests, check test suites, and style'),
134
- model: 'claude-3-5-sonnet',
135
- executionMode: ONCE,
136
- updatedAt: new Date(Date.now() - 1000 * 60 * 180).toISOString(),
137
- },
138
- {
139
- id: 'bot-research-analyst',
140
- name: 'Research Analyst',
141
- description: phrase('Track industry trends, competitive moves, and filings'),
142
- model: 'claude-3-5-sonnet',
143
- executionMode: ONCE,
144
- updatedAt: new Date(Date.now() - 1000 * 60 * 300).toISOString(),
145
- },
146
- ];
147
- const EXAMPLE_ACTIONS = {
148
- 'Sales Outbound': {
149
- title: phrase('Computer'),
150
- status: phrase('Done'),
151
- summary: phrase('Reviewed 52 new outbound leads across target accounts. Qualified 18 high-fit profiles and prepared tailored email drafts.'),
152
- tasks: [
153
- phrase('Verified domain deliverability and prospect contact records'),
154
- phrase('Extracted buyer intent signals from company milestones'),
155
- phrase('Queued 18 personalized emails for Armand’s review'),
156
- ],
157
- },
158
- 'Chief': {
159
- title: phrase('Computer'),
160
- status: phrase('Done'),
161
- summary: phrase('Compiled morning briefing, synced calendar events, and highlighted team priorities.'),
162
- tasks: [
163
- phrase('Aggregated GitHub pull requests and release milestones'),
164
- phrase('Organized 3 priority decisions for today'),
165
- phrase('Synchronized executive calendar and shared prep notes'),
166
- ],
167
- },
168
- 'Inbox Manager': {
169
- title: phrase('Computer'),
170
- status: phrase('Done'),
171
- summary: phrase('Triaged 34 unread messages, flagged 4 urgent requests, and drafted replies for approval.'),
172
- tasks: [
173
- phrase('Categorized incoming inquiries by priority and topic'),
174
- phrase('Drafted context-aware responses citing knowledge base docs'),
175
- phrase('Scheduled followup reminders for unresolved partner threads'),
176
- ],
177
- },
178
- 'Code Reviewer': {
179
- title: phrase('Computer'),
180
- status: phrase('Done'),
181
- summary: phrase('Analyzed pull request 142 for architectural consistency, security considerations, and edge cases.'),
182
- tasks: [
183
- phrase('Verified zero memory leaks and confirmed strict typing'),
184
- phrase('Validated test suite passes across all target environments'),
185
- phrase('Posted inline review suggestions for error handling'),
186
- ],
187
- },
188
- 'Research Analyst': {
189
- title: phrase('Computer'),
190
- status: phrase('Done'),
191
- summary: phrase('Indexed frontier model benchmarks, competitive releases, and performance telemetry.'),
192
- tasks: [
193
- phrase('Indexed latest release notes and technical benchmarks'),
194
- phrase('Created comparative capability matrix'),
195
- phrase('Generated summary digest for the engineering team'),
196
- ],
197
- },
198
- };
199
- export function Bots() {
200
- const { t, locale } = useI18n();
76
+ export function Bots({ foot = true, bot: held, onBot, } = {}) {
77
+ const { t } = useI18n();
201
78
  const { client, ready } = useAi();
202
79
  const { user, isAuthenticated } = useIam();
203
- // A client EXISTS signed out — `useAi` hands back an anonymous one so the
204
- // free chat lane works — so holding one is not proof of a reader. Every read
205
- // below is org-scoped and answers 403 without a session, so this is the gate.
206
80
  const live = Boolean(client && isAuthenticated && ready);
207
- const [roster, setRoster] = useState([]);
208
- const [rosterFailed, setRosterFailed] = useState(null);
209
- const [loading, setLoading] = useState(false);
210
- const [query, setQuery] = useState('');
211
- const [picked, setPicked] = useState('');
212
- const [detail, setDetail] = useState(null);
213
- const [own, setOwn] = useState([]);
214
- const [draft, setDraft] = useState('');
215
- const [trialTurns, setTrialTurns] = useState([]);
216
- const [running, setRunning] = useState(false);
217
- const [failed, setFailed] = useState(null);
218
- const [pane, setPane] = useState(false);
81
+ const hosted = held !== undefined;
82
+ const [bots, setBots] = useState(null);
83
+ // The roster has been read once, so a name it lacks is not this org's.
84
+ const [listed, setListed] = useState(false);
85
+ const [feed, setFeed] = useState([]);
86
+ const [unread, setUnread] = useState(null);
87
+ const [own, setOwn] = useState(null);
219
88
  const [making, setMaking] = useState(false);
220
- const [cron, setCron] = useState('');
89
+ // The panel beside the thread, kept per browser; over the thread below a laptop.
90
+ const [side, setSide] = useKept('hanzo.bots.side', true);
91
+ const [over, setOver] = useState(false);
92
+ const wide = useWide('(min-width: 768px)');
93
+ const laptop = useWide('(min-width: 1280px)');
94
+ // The address, read on arrival and on every Back and Forward.
95
+ useEffect(() => {
96
+ if (hosted)
97
+ return;
98
+ const read = () => setOwn(named());
99
+ read();
100
+ window.addEventListener('popstate', read);
101
+ return () => window.removeEventListener('popstate', read);
102
+ }, [hosted]);
103
+ const name = hosted ? (held ?? null) : own;
104
+ const move = useCallback((next, step) => {
105
+ if (hosted)
106
+ return onBot?.(next, step);
107
+ setOwn(next);
108
+ address(next, step);
109
+ }, [hosted, onBot]);
110
+ const reading = useRef(0);
221
111
  const read = useCallback(async () => {
222
112
  if (!client)
223
113
  return;
224
- setLoading(true);
225
- try {
226
- setRoster(await client.agents.list());
227
- setRosterFailed(null);
228
- }
229
- catch (e) {
230
- setRosterFailed(say(e, t('this org’s bots'), 'read', t));
114
+ const turn = ++reading.current;
115
+ const [list, runs] = await Promise.allSettled([client.agents.list(), client.agents.runs({ limit: 200 })]);
116
+ if (turn !== reading.current)
117
+ return;
118
+ if (list.status === 'fulfilled') {
119
+ setBots(list.value);
120
+ setListed(true);
121
+ setUnread(null);
231
122
  }
232
- finally {
233
- setLoading(false);
123
+ else {
124
+ setBots((b) => b ?? []);
125
+ setUnread(say(list.reason, t('your bots'), 'read', t));
234
126
  }
127
+ if (runs.status === 'fulfilled')
128
+ setFeed(runs.value);
235
129
  }, [client, t]);
236
130
  useEffect(() => {
237
131
  if (live)
238
132
  void read();
239
133
  }, [live, read]);
240
- // In live mode, use platform roster. When exploring as a visitor, show example workspace bots.
241
- const activeRoster = useMemo(() => {
242
- if (live && roster.length > 0)
243
- return roster;
244
- if (!live)
245
- return EXAMPLE_BOTS;
246
- return roster;
247
- }, [live, roster]);
248
- const shown = useMemo(() => {
249
- const q = query.trim().toLowerCase();
250
- if (!q)
251
- return activeRoster;
252
- return activeRoster.filter((b) => {
253
- const about = b.description ? (live ? b.description : t(b.description)) : '';
254
- return b.name.toLowerCase().includes(q) || about.toLowerCase().includes(q);
255
- });
256
- }, [activeRoster, query, live, t]);
257
- const bot = useMemo(() => activeRoster.find((b) => b.name === picked) ?? shown[0] ?? activeRoster[0] ?? null, [activeRoster, shown, picked]);
258
- // Its record and its work, re-read after anything this app does to it —
259
- // the platform's answer is the only account of what happened.
260
- const refresh = useCallback(async () => {
261
- if (!client || !bot)
262
- return;
263
- const [d, s] = await Promise.allSettled([client.agents.get(bot.name), sessions(client, bot.name)]);
264
- if (d.status === 'fulfilled')
265
- setDetail(d.value);
266
- setOwn(s.status === 'fulfilled' ? s.value : []);
267
- }, [client, bot]);
134
+ const last = useMemo(() => lastOf(feed), [feed]);
135
+ // The open bot is the one the address names. With none — or one this org does
136
+ // not keep — a laptop opens the one last spoken to (else the first) and writes
137
+ // it into the address, so it stays open while the feed moves; a phone stays on
138
+ // the roster.
139
+ const bot = useMemo(() => (name && bots?.find((b) => b.name === name)) || null, [bots, name]);
268
140
  useEffect(() => {
269
- if (!client || !bot) {
270
- setDetail(null);
271
- setOwn([]);
141
+ if (!bots || bot)
272
142
  return;
273
- }
274
- const stop = new AbortController();
275
- setCron(bot.schedule ?? '');
276
- client.agents
277
- .get(bot.name, { signal: stop.signal })
278
- .then(setDetail)
279
- .catch(() => {
280
- if (!stop.signal.aborted)
281
- setDetail(null);
282
- });
283
- // No limit of its own. The route has no per-agent filter, so the page it
284
- // answers is the ORG's and the narrowing happens after — ask for twenty
285
- // and a bot whose work is older than the org's twenty newest sessions
286
- // reads as having none.
287
- sessions(client, bot.name, undefined, stop.signal)
288
- .then(setOwn)
289
- .catch(() => setOwn([]));
290
- return () => stop.abort();
291
- }, [client, bot]);
292
- // ONE STREAM, IN THE ORDER IT HAPPENED. A run and a session are two records
293
- // of the same Bot working, so they are read together and sorted by the clock
294
- // the platform put on them — newest at the bottom, where a reader who has
295
- // just asked for something is looking.
296
- const computerAction = bot ? EXAMPLE_ACTIONS[bot.name] ?? null : null;
297
- const stream = useMemo(() => {
298
- if (!live) {
299
- return trialTurns.map((turn) => ({ at: turn.at, key: turn.id, turn, session: null }));
300
- }
301
- return [
302
- ...turns(detail, t).map((turn) => ({ at: turn.at, key: turn.id, turn, session: null })),
303
- ...own.map((s) => ({ at: at(s.updatedAt || s.startedAt || s.createdAt), key: s.id, turn: null, session: s })),
304
- ].sort((a, b) => a.at - b.at);
305
- }, [live, detail, own, trialTurns, t]);
306
- const always = bot?.executionMode === ALWAYS;
307
- // Newest last means the newest is off-screen on a Bot with any history, so
308
- // the stream opens where a reader is looking rather than at its oldest run.
309
- const foot = useRef(null);
310
- useEffect(() => {
311
- foot.current?.scrollIntoView({ block: 'end' });
312
- }, [stream]);
313
- /** One task, run now. */
314
- const run = useCallback(async (e) => {
315
- if (e)
316
- e.preventDefault();
317
- const input = draft.trim();
318
- if (!bot || !input || running)
143
+ if (name) {
144
+ if (listed && !bots.some((b) => b.name === name))
145
+ move(null, false);
319
146
  return;
320
- if (!live) {
321
- setDraft('');
322
- const userTurn = { id: `trial-${Date.now()}-in`, at: Date.now(), who: 'you', text: input };
323
- setTrialTurns((prev) => [...prev, userTurn]);
324
- setTimeout(() => {
325
- const botTurn = {
326
- id: `trial-${Date.now()}-out`,
327
- at: Date.now(),
328
- who: 'bot',
329
- text: t('Received: "{input}". Running on {model} with computer tools enabled. Sign in to your organization to deploy bots into production.', {
330
- input,
331
- model: bot.model,
332
- }),
333
- note: t('{model} · {seconds}s · {count} tokens', { model: bot.model, seconds: '0.8', count: 142 }),
334
- };
335
- setTrialTurns((prev) => [...prev, botTurn]);
336
- }, 400);
147
+ }
148
+ if (!wide || !bots.length)
337
149
  return;
150
+ const recent = feed.find((r) => r.agent && bots.some((b) => b.name === r.agent))?.agent;
151
+ move(recent ?? bots[0].name, false);
152
+ }, [bots, bot, name, listed, wide, feed, move]);
153
+ // Whether this page stepped into the thread, so Back can step out of it.
154
+ const stepped = useRef(false);
155
+ const pick = useCallback((next) => {
156
+ setOver(false);
157
+ // A phone steps into the thread, so Back returns to the roster.
158
+ const step = !wide && !name;
159
+ if (step)
160
+ stepped.current = true;
161
+ move(next, step);
162
+ }, [move, wide, name]);
163
+ const back = useCallback(() => {
164
+ setOver(false);
165
+ if (stepped.current) {
166
+ stepped.current = false;
167
+ window.history.back();
338
168
  }
169
+ else
170
+ move(null, false);
171
+ }, [move]);
172
+ // ── the open bot's thread ────────────────────────────────────────────────
173
+ const [runs, setRuns] = useState(null);
174
+ const [pending, setPending] = useState(null);
175
+ const [notice, setNotice] = useState(null);
176
+ const [wrong, setWrong] = useState(null);
177
+ const open = bot?.name ?? null;
178
+ const asking = useRef(0);
179
+ const history = useCallback(async (who, signal) => {
339
180
  if (!client)
340
181
  return;
341
- setRunning(true);
342
- setFailed(null);
182
+ const rows = await client.agents.runs({ agent: who, limit: 200 }, signal ? { signal } : undefined);
183
+ if (!signal?.aborted)
184
+ setRuns((drawn) => merged(drawn ?? [], rows));
185
+ }, [client]);
186
+ useEffect(() => {
187
+ // Another bot is open: whatever the last one's run answers, it is not this thread's.
188
+ asking.current += 1;
189
+ setRuns(null);
190
+ setPending(null);
191
+ setNotice(null);
192
+ setWrong(null);
193
+ if (!client || !open)
194
+ return;
195
+ const stop = new AbortController();
196
+ history(open, stop.signal).catch((e) => {
197
+ if (stop.signal.aborted)
198
+ return;
199
+ setRuns([]);
200
+ setWrong(say(e, t('this conversation'), 'read', t));
201
+ });
202
+ return () => stop.abort();
203
+ }, [client, open, history, t]);
204
+ /**
205
+ * Says `input` to the open bot. Answers whether the platform recorded it: a
206
+ * message it refused, or never received, is handed back to the composer so
207
+ * the thread holds only what was said.
208
+ */
209
+ const send = useCallback(async (input) => {
210
+ if (!client || !bot)
211
+ return false;
212
+ const who = bot.name;
213
+ const turn = ++asking.current;
214
+ const now = () => turn === asking.current;
215
+ setNotice(null);
216
+ setWrong(null);
217
+ setPending({ input, at: Date.now() });
343
218
  try {
344
- await client.agents.run(bot.name, input);
345
- setDraft('');
346
- await refresh();
219
+ const ran = await client.agents.run(who, input);
220
+ if (now())
221
+ setRuns((rs) => merged(rs ?? [], [ran]));
222
+ return true;
347
223
  }
348
- catch (err) {
349
- setFailed(err instanceof Error ? err.message : String(err));
224
+ catch (e) {
225
+ // A thread since left: its words are not handed to the one now open.
226
+ if (!now())
227
+ return true;
228
+ const no = refusal(e, who, Date.now(), t, bot.period);
229
+ if (no) {
230
+ setNotice(no);
231
+ return false;
232
+ }
233
+ // A run that reached its model and failed is recorded and comes back as
234
+ // the body; it is drawn with its own error. Anything else never arrived.
235
+ const ran = recordedRun(e);
236
+ if (ran) {
237
+ setRuns((rs) => merged(rs ?? [], [ran]));
238
+ return true;
239
+ }
240
+ setWrong(say(e, t('your message to {name}', { name: who }), 'save', t));
241
+ return false;
350
242
  }
351
243
  finally {
352
- setRunning(false);
244
+ if (now())
245
+ setPending(null);
246
+ void read();
353
247
  }
354
- }, [live, client, bot, draft, running, refresh, t]);
355
- /** Stays up, or runs when asked. The platform REFUSES long-running without a
356
- * cron — measured, 400 naming the field — so the cron is asked for beside
357
- * the switch rather than guessed at here. */
358
- const keepUp = useCallback(async () => {
248
+ }, [client, bot, read, t]);
249
+ /**
250
+ * Runs on its schedule, or only when asked. The platform keeps no schedule for
251
+ * a bot that runs only when asked, so turning it back on states the schedule.
252
+ */
253
+ // The schedule each bot last had on this page. The platform keeps none for a bot
254
+ // that runs only when asked, so a schedule turned off is held here to turn back on.
255
+ const [kept, setKept] = useState({});
256
+ const schedule = useCallback(async (on, cron) => {
359
257
  if (!client || !bot)
360
258
  return;
361
- setFailed(null);
362
- try {
363
- const saved = always
364
- ? await client.agents.update(bot.name, { executionMode: ONCE })
365
- : await client.agents.update(bot.name, { executionMode: ALWAYS, schedule: cron.trim() });
366
- setRoster((r) => r.map((b) => (b.name === saved.name ? saved : b)));
367
- }
368
- catch (e) {
369
- setFailed(e instanceof Error ? e.message : String(e));
370
- }
371
- }, [client, bot, always, cron]);
372
- const retire = useCallback(async () => {
259
+ setKept((k) => ({ ...k, [bot.name]: cron }));
260
+ const saved = await client.agents.update(bot.name, on ? { executionMode: ALWAYS, schedule: cron } : { executionMode: ONCE });
261
+ setBots((all) => (all ?? []).map((b) => (b.name === saved.name ? { ...b, ...saved, schedule: saved.schedule } : b)));
262
+ }, [client, bot]);
263
+ /** Deletes the open bot and every run recorded against it. */
264
+ const remove = useCallback(async () => {
373
265
  if (!client || !bot)
374
266
  return;
375
- setFailed(null);
376
- try {
377
- await client.agents.delete(bot.name);
378
- setPicked('');
379
- await read();
380
- }
381
- catch (e) {
382
- setFailed(say(e, t('this bot'), 'save', t));
383
- }
384
- }, [client, bot, read, t]);
385
- return (_jsxs(XStack, { width: "100%", height: "100%", overflow: "hidden", bg: GROUND, "$max-lg": { overflowX: 'auto', overflowY: 'hidden' }, "$platform-web": { scrollSnapType: 'x mandatory' }, children: [_jsxs(YStack, { width: 280, minW: 280, height: "100%", bg: GROUND, borderRightWidth: 1, borderColor: LINE, "$max-lg": { width: '85%', maxW: 320 }, "$platform-web": { scrollSnapAlign: 'start' }, children: [_jsxs(XStack, { pt: 16, px: 18, pb: 12, items: "center", justify: "space-between", children: [_jsx(Lights, {}), _jsx(XStack, { ...GHOST, title: t(live ? 'New bot' : 'Sign in to keep a bot'), onClick: () => setMaking((m) => !m), "aria-label": t('New bot'), "aria-expanded": making, disabled: !live, opacity: live ? 1 : 0.4, children: _jsx(Plus, { size: 18, color: DIM }) })] }), making && live ? (_jsx(Hire, { onDone: async (made) => {
386
- setMaking(false);
387
- setPicked(made.name);
388
- await read();
389
- }, onCancel: () => setMaking(false) })) : null, _jsx(YStack, { px: 14, pb: 12, children: _jsxs(XStack, { items: "center", gap: 8, bg: SURFACE, borderWidth: 1, borderColor: LINE, rounded: 8, px: 12, py: 8, children: [_jsx(Search, { size: 14, color: DIM, "aria-hidden": true }), _jsx(Input, { ...BARE, value: query, onChange: (e) => setQuery(e.target.value), placeholder: t('Search'), "aria-label": t('Search bots'), fontSize: "$2", flex: 1, minW: 0 })] }) }), _jsxs(YStack, { "data-hz": "roster", flex: 1, overflowY: "auto", px: 10, gap: 2, children: [live && rosterFailed ? (_jsx(Text, { ...NOTE, children: rosterFailed })) : live && loading && roster.length === 0 ? (_jsx(Text, { ...NOTE, children: t('Reading the roster…') })) : live && shown.length === 0 ? (_jsx(Text, { ...NOTE, children: t(roster.length === 0 ? 'This org keeps no bots yet.' : 'No bot matches that.') })) : null, shown.map((b) => {
390
- const on = bot?.name === b.name;
391
- return (_jsxs(XStack, { render: "button", type: 'button', "data-hz": "bot", "data-name": b.name, "aria-current": on, onClick: () => setPicked(b.name), items: "center", gap: 12, px: 12, py: 10, rounded: 10, bg: on ? SURFACE : 'transparent', borderWidth: 0, cursor: "pointer", width: "100%", children: [_jsx(Face, { bot: b, size: 36 }), _jsxs(YStack, { flex: 1, minW: 0, children: [_jsxs(XStack, { items: "center", justify: "space-between", gap: 8, children: [_jsx(Text, { fontSize: "$2", fontWeight: "600", color: on ? INK : DIM, children: b.name }), _jsx(Text, { fontSize: "$1", color: FAINT, whiteSpace: "nowrap", children: when(b.updatedAt, t, locale) })] }), _jsx(Text, { ...CLIP, fontSize: "$2", color: DIM, text: "left", children: b.description
392
- ? live
393
- ? b.description
394
- : t(b.description)
395
- : t(b.runs ? '{model} · {count} runs' : '{model}', {
396
- model: b.model,
397
- count: b.runs ?? 0,
398
- }) })] })] }, b.id || b.name));
399
- })] }), _jsxs(XStack, { px: 16, py: 14, borderTopWidth: 1, borderColor: LINE, items: "center", gap: 12, children: [_jsx(Text, { "aria-hidden": true, display: "flex", width: 32, height: 32, shrink: 0, rounded: 9999, bg: SURFACE, borderWidth: 1, borderColor: LINE, items: "center", justify: "center", fontSize: "$2", fontWeight: "600", color: DIM, children: (user?.name || (live ? '·' : 'Armand Segall')).trim().charAt(0).toUpperCase() }), _jsxs(YStack, { flex: 1, minW: 0, children: [_jsx(Text, { fontSize: "$2", fontWeight: "600", color: INK, children: user?.name || (live ? t('Signed in') : 'Armand Segall') }), _jsx(Text, { ...CLIP, fontSize: "$1", color: FAINT, children: user?.email || (live ? t('Active Workspace') : t('{email} · Example Workspace', { email: 'armand@example.com' })) })] })] })] }), _jsxs(YStack, { flex: 1, minW: 0, height: "100%", position: "relative", bg: GROUND, "$max-lg": { width: '100%', minW: '100%', shrink: 0, overflowX: 'hidden' }, "$platform-web": { scrollSnapAlign: 'start' }, children: [_jsxs(XStack, { height: 60, borderBottomWidth: 1, borderColor: LINE, items: "center", justify: "space-between", px: 16, gap: 12, children: [_jsxs(XStack, { items: "center", gap: 10, minW: 0, shrink: 1, children: [bot ? _jsx(Face, { bot: bot, size: 28 }) : null, _jsxs(YStack, { minW: 0, shrink: 1, children: [_jsx(Text, { ...CLIP, "data-hz": "head", fontSize: "$3", fontWeight: "600", color: INK, children: bot?.name || t('No bot') }), _jsx(Text, { ...CLIP, "data-hz": "mode", fontSize: "$1", color: FAINT, children: bot
400
- ? t(bot.schedule ? '{model} · {mode} · {schedule}' : '{model} · {mode}', {
401
- model: bot.model,
402
- mode: modeName(bot.executionMode, t),
403
- schedule: bot.schedule ?? '',
404
- })
405
- : '' })] })] }), bot ? (_jsxs(XStack, { items: "center", gap: 8, shrink: 0, children: [!always ? (_jsx(Input, { ...BOXED, "data-hz": "cron", value: cron, onChange: (e) => setCron(e.target.value), placeholder: t('0 * * * *'), "aria-label": t('Schedule, as a 5-field cron'), width: 104, fontSize: "$1" })) : null, _jsx(Button, { size: "sm", variant: always ? undefined : 'default', bg: always ? 'var(--primary)' : undefined, color: always ? 'var(--primary-foreground)' : undefined, borderColor: always ? 'var(--primary)' : undefined, hoverStyle: always ? { bg: 'var(--primary-hover)', borderColor: 'var(--primary-hover)' } : undefined, rounded: 999, title: t(always ? 'Run only when asked' : 'Keep this bot up on a schedule'), "data-hz": "always", onClick: keepUp, "aria-pressed": always, children: t('24/7') }), _jsx(Button, { size: "sm", bg: "var(--primary)", color: "var(--primary-foreground)", borderColor: "var(--primary)", hoverStyle: { bg: 'var(--primary-hover)', borderColor: 'var(--primary-hover)' }, title: t('Open a session for this bot'), "data-hz": "open", onClick: async () => {
406
- if (!client || !bot)
407
- return;
408
- setFailed(null);
409
- try {
410
- await launch(client, bot.name, t('{name} session', { name: bot.name }));
411
- await refresh();
412
- }
413
- catch (e) {
414
- setFailed(e instanceof Error ? e.message : String(e));
415
- }
416
- }, children: t('Open a session') }), _jsx(XStack, { ...GHOST, title: t('What this bot has'), "data-hz": "runtime", onClick: () => setPane((p) => !p), "aria-label": t('Runtime'), "aria-pressed": pane, bg: pane ? SURFACE : 'transparent', children: _jsx(Monitor, { size: 18, color: pane ? INK : DIM }) }), _jsx(XStack, { ...GHOST, title: t('Retire'), "data-hz": "retire", onClick: retire, "aria-label": t('Retire {name}', { name: bot.name }), children: _jsx(Trash2, { size: 16, color: DIM }) })] })) : null] }), _jsxs(XStack, { flex: 1, minH: 0, children: [_jsxs(YStack, { flex: 1, minW: 0, overflow: "hidden", children: [_jsxs(YStack, { "data-hz": "stream", flex: 1, overflowY: "auto", px: 32, py: 24, gap: 16, children: [!bot ? (_jsx(Text, { ...NOTE, children: t(live
417
- ? 'Nothing is kept yet. A bot is a model, a standing instruction and a record of what it has done — press + to keep one.'
418
- : 'Select a bot to begin.') })) : null, bot && detail?.instructions ? (_jsxs(YStack, { ...CARD, children: [_jsx(Text, { ...LABEL, children: t('Standing instruction') }), _jsx(Text, { render: "p", fontSize: "$2", lineHeight: "1.3rem", color: DIM, whiteSpace: "pre-wrap", children: detail.instructions })] })) : null, computerAction ? (_jsxs(YStack, { ...CARD, "data-hz": "computer-card", children: [_jsxs(XStack, { items: "center", justify: "space-between", children: [_jsxs(XStack, { items: "center", gap: 8, children: [_jsx(Monitor, { size: 15, color: INK }), _jsx(Text, { fontSize: "$2", fontWeight: "600", color: INK, children: t(computerAction.title) })] }), _jsx(Text, { display: "inline-flex", items: "center", px: 8, py: 2, rounded: 999, fontSize: "$1", fontWeight: "600", bg: SURFACE, color: DIM, borderWidth: 1, borderColor: LINE, children: t(computerAction.status) })] }), _jsx(Text, { render: "p", fontSize: "$2", lineHeight: "1.26rem", color: INK, children: t(computerAction.summary) }), _jsx(YStack, { gap: 5, mt: 4, children: computerAction.tasks.map((task, idx) => (_jsxs(XStack, { items: "center", gap: 8, children: [_jsx(YStack, { width: 4, height: 4, shrink: 0, rounded: 9999, bg: FAINT }), _jsx(Text, { fontSize: "$2", color: DIM, children: t(task) })] }, idx))) })] })) : null, bot && stream.length === 0 && !computerAction ? (_jsx(Text, { ...NOTE, children: t('Nothing has been run yet. Ask for something below and the run is recorded here.') })) : null, stream.map(({ key, turn, session }) => session ? (_jsx(Live, { session: session, onChange: refresh }, key)) : turn ? (_jsxs(Text, { render: "div", "data-hz": turn.who === 'you' ? 'asked' : 'answered', self: turn.who === 'you' ? 'flex-end' : 'flex-start', maxW: 620, rounded: 14, px: 16, py: 12, fontSize: "$3", lineHeight: "1.35625rem", whiteSpace: "pre-wrap", bg: turn.who === 'you' ? SURFACE : RAISED, borderWidth: 1, borderColor: LINE, color: turn.failed ? DIM : INK, children: [turn.text, turn.note ? (_jsx(Text, { display: "block", mt: 6, fontSize: "$1", lineHeight: "1.0656rem", color: FAINT, children: turn.failed ? t('failed · {note}', { note: turn.note ?? '' }) : turn.note })) : null] }, key)) : null), _jsx("div", { ref: foot })] }), _jsxs(YStack, { pt: 16, px: 32, pb: 24, children: [failed ? _jsx(Text, { ...NOTE, px: 0, pt: 0, pb: 8, children: failed }) : null, _jsxs(XStack, { render: "form", onSubmit: run, items: "center", gap: 12, bg: SURFACE, borderWidth: 1, borderColor: LINE, rounded: 26, pt: 6, pr: 8, pb: 6, pl: 16, children: [_jsx(Input, { ...BARE, "data-hz": "ask", value: draft, onChange: (e) => setDraft(e.target.value), placeholder: bot ? t('Message {name}', { name: bot.name }) : t('Message bot...'), "aria-label": t('Task'), disabled: !bot || running, flex: 1, fontSize: "$3" }), _jsx(Button, { type: "submit", size: "icon", rounded: 9999, bg: !bot || running || !draft.trim() ? SURFACE : 'var(--primary)', color: !bot || running || !draft.trim() ? FAINT : 'var(--primary-foreground)', borderColor: "transparent", hoverStyle: !bot || running || !draft.trim() ? undefined : { bg: 'var(--primary-hover)' }, title: t('Run this task'), "data-hz": "run", disabled: !bot || running || !draft.trim(), "aria-label": t('Run this task'), children: _jsx(Send, { size: 16, color: !bot || running || !draft.trim() ? 'var(--text-tertiary)' : 'var(--primary-foreground)' }) })] }), _jsx(Text, { render: "p", mt: 8, fontSize: "$1", color: FAINT, children: running
419
- ? t('Running. The recorded run appears above when the platform answers.')
420
- : bot
421
- ? t('Runs on {model}, recorded against {name}.', { model: bot.model, name: bot.name })
422
- : '' })] })] }), pane && bot ? _jsx(Runtime, { bot: bot }) : null] })] })] }));
423
- }
424
- /**
425
- * One session of this Bot's, and — while it is still open — the three things
426
- * the route lets you say to it.
427
- *
428
- * A FINISHED SESSION HAS NO CONTROLS. The route accepts a command for one and
429
- * records it against a log nothing is reading, so drawing Pause beside a run
430
- * that ended an hour ago is a control over nothing.
431
- *
432
- * `forwarded` is the platform's own word for whether a runner was listening: a
433
- * command is always RECORDED, and only sometimes delivered. Saying which is the
434
- * difference between a control and a button that appears to work.
435
- */
436
- function Live({ session, onChange }) {
437
- const { t, locale } = useI18n();
438
- const { client } = useAi();
439
- const [said, setSaid] = useState(null);
440
- const command = async (verb) => {
441
- if (!client)
442
- return;
443
- try {
444
- const r = await steer(client, session.id, verb);
445
- const delivered = verb === 'pause' ? t('pause delivered') : verb === 'resume' ? t('resume delivered') : t('stop delivered');
446
- const recorded = verb === 'pause'
447
- ? t('pause recorded — no runner is attached to this session')
448
- : verb === 'resume'
449
- ? t('resume recorded — no runner is attached to this session')
450
- : t('stop recorded — no runner is attached to this session');
451
- setSaid(r.forwarded ? delivered : recorded);
452
- await onChange();
453
- }
454
- catch (e) {
455
- setSaid(say(e, t('this session'), 'save', t));
456
- }
457
- };
458
- return (_jsxs(YStack, { ...CARD, "data-hz": "session", "data-status": session.status, children: [_jsxs(XStack, { items: "baseline", justify: "space-between", gap: 8, children: [_jsx(Text, { fontSize: "$2", fontWeight: "600", color: INK, children: session.title || t('Session') }), _jsx(Text, { fontSize: "$1", color: FAINT, children: t('{status} · {count} turns', {
459
- status: sessionStatus(session.status, t),
460
- count: session.events ?? 0,
461
- }) })] }), session.lastEvent?.preview ? (_jsx(Text, { ...CLIP, render: "p", fontSize: "$1", lineHeight: "1.03125rem", fontFamily: "$mono", color: FAINT, children: session.lastEvent.preview })) : null, open(session) ? (_jsxs(XStack, { gap: 6, children: [_jsx(Text, { ...TAB, "data-hz": "pause", onClick: () => command('pause'), children: t('Pause') }), _jsx(Text, { ...TAB, "data-hz": "resume", onClick: () => command('resume'), children: t('Resume') }), _jsx(Text, { ...TAB, "data-hz": "stop", onClick: () => command('stop'), children: t('Stop') })] })) : null, said ? _jsx(Text, { render: "p", fontSize: "$1", color: FAINT, children: said }) : null] }));
462
- }
463
- /**
464
- * Keeping a Bot.
465
- *
466
- * The model is checked against the gateway's served catalogue at create time,
467
- * so the field OFFERS that catalogue rather than a name this file invented: a
468
- * model this deployment cannot serve is refused with a 400 naming it, and the
469
- * platform's own sentence is what a reader is shown.
470
- */
471
- function Hire({ onDone, onCancel }) {
472
- const { t, locale } = useI18n();
473
- const { client } = useAi();
474
- const [name, setName] = useState('');
475
- const [model, setModel] = useState(ENSO);
476
- const [about, setAbout] = useState('');
477
- const [orders, setOrders] = useState('');
478
- const [busy, setBusy] = useState(false);
479
- const [failed, setFailed] = useState(null);
480
- const [served, setServed] = useState([]);
267
+ await client.agents.delete(bot.name);
268
+ setBots((all) => (all ?? []).filter((b) => b.name !== bot.name));
269
+ setOver(false);
270
+ stepped.current = false;
271
+ move(null, false);
272
+ await read();
273
+ }, [client, bot, move, read]);
274
+ const made = useCallback(async (agent) => {
275
+ setMaking(false);
276
+ setBots((all) => [...(all ?? []).filter((b) => b.name !== agent.name), agent]);
277
+ const step = !wide && !name;
278
+ if (step)
279
+ stepped.current = true;
280
+ move(agent.name, step);
281
+ await read();
282
+ }, [move, read, wide, name]);
283
+ // Escape closes the panel over the thread, as it closes any dialog.
481
284
  useEffect(() => {
482
- if (!client)
285
+ if (!over)
483
286
  return;
484
- const stop = new AbortController();
485
- client.models
486
- .list({ signal: stop.signal })
487
- .then(setServed)
488
- .catch(() => setServed([]));
489
- return () => stop.abort();
490
- }, [client]);
491
- return (_jsxs(YStack, { render: "form", onSubmit: async (e) => {
492
- e.preventDefault();
493
- if (!client || busy || !name.trim())
494
- return;
495
- setBusy(true);
496
- setFailed(null);
497
- try {
498
- await onDone(await client.agents.create({
499
- name: name.trim(),
500
- model: model.trim() || ENSO,
501
- description: about.trim(),
502
- instructions: orders.trim(),
503
- }));
504
- }
505
- catch (err) {
506
- setFailed(err instanceof Error ? err.message : String(err));
507
- }
508
- finally {
509
- setBusy(false);
510
- }
511
- }, "data-hz": "hire", mx: 10, mb: 10, p: 12, gap: 8, bg: RAISED, borderWidth: 1, borderColor: LINE, rounded: 10, children: [_jsx(Input, { ...BOXED, "data-hz": "name", value: name, onChange: (e) => setName(e.target.value), placeholder: t('Name'), "aria-label": t('Bot name'), autoFocus: true }), _jsx(Input, { ...BOXED, "data-hz": "model", list: "bot-models", value: model, onChange: (e) => setModel(e.target.value), placeholder: t('Model'), "aria-label": t('Model') }), _jsx("datalist", { id: "bot-models", children: served.map((m) => (_jsx("option", { value: m.id }, m.id))) }), _jsx(Input, { ...BOXED, value: about, onChange: (e) => setAbout(e.target.value), placeholder: t('What it is for'), "aria-label": t('Description') }), _jsx(Input, { ...BOXED, render: "textarea", rows: 2, value: orders, onChange: (e) => setOrders(e.target.value), placeholder: t('Standing instruction'), "aria-label": t('Standing instruction') }), failed ? _jsx(Text, { "data-hz": "hire-failed", fontSize: "$1", color: DIM, children: failed }) : null, _jsxs(XStack, { gap: 6, children: [_jsx(Button, { type: "submit", size: "sm", bg: "var(--primary)", color: "var(--primary-foreground)", borderColor: "var(--primary)", hoverStyle: { bg: 'var(--primary-hover)', borderColor: 'var(--primary-hover)' }, "data-hz": "keep", disabled: busy || !name.trim(), flex: 1, children: t(busy ? 'Keeping…' : 'Keep') }), _jsx(Button, { size: "sm", onClick: onCancel, flex: 1, children: t('Cancel') })] })] }));
287
+ const key = (e) => e.key === 'Escape' && setOver(false);
288
+ window.addEventListener('keydown', key);
289
+ return () => window.removeEventListener('keydown', key);
290
+ }, [over]);
291
+ const close = () => {
292
+ if (laptop)
293
+ setSide(false);
294
+ setOver(false);
295
+ };
296
+ const panel = bot ? (_jsx(Panel, { bot: bot, kept: kept[bot.name] ?? '', onClose: close, onSchedule: schedule, onDelete: remove, focus: over && !laptop }, bot.name)) : null;
297
+ const shown = laptop ? side : over;
298
+ return (_jsxs(XStack, { "data-parity-key": "bots.window", width: "100%", height: "100%", overflow: "hidden", bg: FLOOR, position: "relative", children: [_jsx(YStack, { "data-parity-key": "bots.roster", width: 279, shrink: 0, height: "100%", bg: FLOOR, borderRightWidth: 1, borderColor: LINE, "$max-md": { width: '100%', borderRightWidth: 0, display: bot ? 'none' : 'flex' }, children: _jsx(Roster, { bots: bots, last: last, open: open, unread: unread, me: foot ? user : null, onPick: pick, onMake: () => setMaking(true), disabled: !live }) }), _jsx(YStack, { "data-parity-key": "bots.center", flex: 1, minW: 0, height: "100%", bg: GROUND, "$max-md": { display: bot ? 'flex' : 'none' }, children: _jsx(Thread, { bot: bot, bots: bots ?? [], runs: runs, pending: pending, notice: notice, wrong: wrong, side: shown, live: live, loaded: bots !== null, onSend: send, onDismiss: () => setNotice(null), onSide: () => (laptop ? setSide(!side) : setOver(!over)), onBack: back, onMake: () => setMaking(true) }) }), laptop && side && panel ? (_jsx(YStack, { "data-parity-key": "bots.panel", width: 319, shrink: 0, height: "100%", bg: GROUND, borderLeftWidth: 1, borderColor: LINE, "$max-xl": { display: 'none' }, children: panel })) : null, over && panel && !laptop ? (_jsx(YStack, { "data-parity-key": "bots.panel.over", role: "dialog", "aria-modal": true, "aria-label": bot?.name, position: "absolute", t: 0, r: 0, b: 0, width: 319, maxW: "100%", z: 10, bg: GROUND, borderLeftWidth: 1, borderColor: LINE, boxShadow: "var(--shadow-floating)", children: panel })) : null, making ? _jsx(Make, { onDone: made, onCancel: () => setMaking(false) }) : null] }));
512
299
  }