@colixsystems/widget-sdk 0.349.0 → 0.351.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -91,7 +91,21 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
91
91
 
92
92
  ## Status
93
93
 
94
- `v0.349.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
94
+ `v0.351.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
95
+
96
+ ### What's new in 0.351.0 (contract 1.288.0)
97
+
98
+ **An agent run lives on the server (`useAgent()`).** Leaving the page, a refresh or a lost connection no longer ends the turn.
99
+
100
+ - **`sending` covers a run found on mount.** The hook reads the thread until the run ends and its answer lands in `messages`, so a widget that gates its composer and Stop control on `sending` needs no change. It spends no credit. A lost connection is followed the same way: `send()` stays pending and resolves with the reply. A send that cannot reach the server again within a minute rejects with its first error.
101
+ - **`cancel()` really stops the run.** `send()` then **resolves** with the stopped row (it used to reject `CANCELLED`). What the agent already changed stays changed. If the stop fails, `error` is set and `sending` stays true. On a host that cannot stop a run, `cancel()` still only ends the wait.
102
+ - **`outcome`** — an assistant message that ended early carries `"stopped"` or `"failed"` with the content `…`. Render its `activity` and a line of your own, not a bubble.
103
+ - **`TURN_IN_PROGRESS`** (409) — the agent is still working on an earlier message, perhaps from another device. Nothing was sent: put the text back.
104
+ - **`AgentError.stored`** — true when the turn failed but the server kept the message. It is in `messages`, so do not put the text back in the composer.
105
+
106
+ ### What's new in 0.350.0 (contract 1.287.0)
107
+
108
+ **A scheduled action script can tell whose account it runs for — `connection` joins `CONTRACT.actionScriptGlobals` (sc-15765).** An Action whose schedule runs once per account app users connected gets that account as `connection`; it is `null` on every other run. The action-sdk README has the details. Nothing changes for widget authors.
95
109
 
96
110
  ### What's new in 0.349.0 (contract 1.286.0)
97
111
 
@@ -2147,7 +2161,7 @@ Additive: `isNarrowWidth` and `NARROW_WIDTH_PX` are unchanged, and `widthTier(w)
2147
2161
 
2148
2162
  **`useAgent()` returns `cancel()` — and two error codes that tell the truth about a slow turn (sc-8519).** A turn can legitimately run for minutes; the client used to give up after 10 seconds and report it as `NETWORK`, so a widget showed "you appear to be offline" to a user whose connection was fine, while the server finished the turn and the workspace paid for a reply nobody saw.
2149
2163
 
2150
- - **`cancel()`** stops WAITING for the turn in flight. The abort never reaches the server, which finishes and bills the turn either way — so label the control **stop**, not *cancel*, and never imply the work was called off.
2164
+ - **`cancel()`** stops waiting for the turn in flight. (Since 0.351.0 it stops the run itself.)
2151
2165
  - **`TIMEOUT`** — the client stopped waiting. Still running, still billed: say it is taking longer than usual, never that it failed.
2152
2166
  - **`CANCELLED`** — the user pressed your stop control. Render no error at all.
2153
2167
 
package/dist/contract.cjs CHANGED
@@ -2264,9 +2264,21 @@ const HOOKS = [
2264
2264
  "it off, so hide the affordance rather than retrying; TIMEOUT means the " +
2265
2265
  "client stopped waiting and the turn is STILL running and billed, so " +
2266
2266
  "say it is taking longer, never that it failed or that they are " +
2267
- "offline; CANCELLED is the user pressing your stop control, so render " +
2268
- "no error at all. Call cancel() to stop waiting -- it ends the WAIT, " +
2269
- "not the turn. NEVER surface a " +
2267
+ "offline; TURN_IN_PROGRESS (409) means the agent is still working on an " +
2268
+ "earlier message, so nothing was sent: put the text back and say they can " +
2269
+ "send it when that one is done; CANCELLED is the user's own choice, so " +
2270
+ "render no error at all. A RUN LIVES ON THE SERVER (sc-18562): leaving the " +
2271
+ "page, a refresh or a lost connection does not end it. `sending` is true " +
2272
+ "while one is in progress, on a later mount too, and its answer lands in " +
2273
+ "`messages` by itself, so gate the composer on `sending` and never resend. " +
2274
+ "cancel() really stops the run (label it 'Stop'): send() then RESOLVES with " +
2275
+ "the stopped row, and changes already made stay made. If the stop fails, " +
2276
+ "`error` is set while `sending` stays true. On an older host cancel() only " +
2277
+ "ends the wait and send() rejects CANCELLED. An assistant message that " +
2278
+ "ended early carries `outcome` ('stopped' | 'failed') and the content '…': " +
2279
+ "render its `activity` and your own line instead of a bubble. A rejection " +
2280
+ "with `stored: true` kept the message in `messages`, so do not put the text " +
2281
+ "back. NEVER surface a " +
2270
2282
  "raw error or the workspace's billing state to an app user. " +
2271
2283
  "RENDER AN ASSISTANT REPLY WITH <RichText value={msg.content} />, " +
2272
2284
  "not <Text>: a model answers in MARKDOWN by default — **bold**, " +
@@ -2310,9 +2322,10 @@ const HOOKS = [
2310
2322
  "Reads ctx.agents.",
2311
2323
  returnShape: {
2312
2324
  send: "(text, { files }?) => Promise<{ id, role, content, created_at } | null>",
2325
+ cancel: "() => void // stops the run; send() resolves with the stopped row",
2313
2326
  reset: "() => void",
2314
- messages: "Array<{ id, conversation_id, role, content, created_at }>",
2315
- sending: "boolean",
2327
+ messages: "Array<{ id, conversation_id, role, content, activity?, outcome?, created_at }>",
2328
+ sending: "boolean // true while a run is in progress, also one found on mount",
2316
2329
  resuming:
2317
2330
  "boolean // true only while the stored transcript is being reopened on mount; show a loading state, not an empty thread",
2318
2331
  error: "AgentError | null",
@@ -4173,6 +4186,8 @@ const ACTION_SCRIPT_GLOBALS = [
4173
4186
  "triggerTableId",
4174
4187
  // sc-7885 — who initiated the run; null on `schedule` / `record_*`.
4175
4188
  "triggeredBy",
4189
+ // sc-15765 — the account a per-connection scheduled run is for; null otherwise.
4190
+ "connection",
4176
4191
  // sc-9031 — a Run action event's parameters; null on every other trigger.
4177
4192
  "input",
4178
4193
  // sc-13843 — hands the app run its one JSON result.
@@ -4531,6 +4546,7 @@ const WIDGET_CONTEXT_SHAPE = {
4531
4546
  description:
4532
4547
  "sc-7991 — injected @colixsystems/agents-client instance. " +
4533
4548
  "{ conversations(agentId) -> { create(), list(query), remove(conversationId), " +
4549
+ "stop(conversationId) -> Promise<{ conversation_id, stopping }> (sc-18562; optional on older hosts), " +
4534
4550
  "messages(conversationId) -> { list(query), send({ content, file_ids? }) } }, " +
4535
4551
  "capabilities(agentId) -> Promise<{ accepts_files, accepted_file_types, max_files, max_pdfs, max_file_bytes, max_total_bytes }>, " +
4536
4552
  "connections(agentId) -> { list(), create({ name, server_url, token }), test(id), remove(id), " +
@@ -7170,7 +7186,13 @@ const CONTRACT = deepFreeze({
7170
7186
  // 1.286.0: guidance (sc-16714) — when an Overlay goes `full`, and that a
7171
7187
  // full one draws its own close control; the `full-overlay-no-close`
7172
7188
  // lint warning flags one that does not.
7173
- version: "1.286.0",
7189
+ // 1.287.0: additive (sc-15765) — `connection` joins `actionScriptGlobals`:
7190
+ // the account a per-connection scheduled run is for, null otherwise.
7191
+ // 1.288.0: behaviour (sc-18562) — an agent run lives on the server: `sending`
7192
+ // covers a run found on mount, cancel() really stops it and send() resolves
7193
+ // with the stopped row, messages carry `outcome`, and a send during a run
7194
+ // rejects TURN_IN_PROGRESS. A rejection says `stored` when the message was kept.
7195
+ version: "1.288.0",
7174
7196
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7175
7197
  hooks: HOOKS,
7176
7198
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -2259,9 +2259,21 @@ const HOOKS = [
2259
2259
  "it off, so hide the affordance rather than retrying; TIMEOUT means the " +
2260
2260
  "client stopped waiting and the turn is STILL running and billed, so " +
2261
2261
  "say it is taking longer, never that it failed or that they are " +
2262
- "offline; CANCELLED is the user pressing your stop control, so render " +
2263
- "no error at all. Call cancel() to stop waiting -- it ends the WAIT, " +
2264
- "not the turn. NEVER surface a " +
2262
+ "offline; TURN_IN_PROGRESS (409) means the agent is still working on an " +
2263
+ "earlier message, so nothing was sent: put the text back and say they can " +
2264
+ "send it when that one is done; CANCELLED is the user's own choice, so " +
2265
+ "render no error at all. A RUN LIVES ON THE SERVER (sc-18562): leaving the " +
2266
+ "page, a refresh or a lost connection does not end it. `sending` is true " +
2267
+ "while one is in progress, on a later mount too, and its answer lands in " +
2268
+ "`messages` by itself, so gate the composer on `sending` and never resend. " +
2269
+ "cancel() really stops the run (label it 'Stop'): send() then RESOLVES with " +
2270
+ "the stopped row, and changes already made stay made. If the stop fails, " +
2271
+ "`error` is set while `sending` stays true. On an older host cancel() only " +
2272
+ "ends the wait and send() rejects CANCELLED. An assistant message that " +
2273
+ "ended early carries `outcome` ('stopped' | 'failed') and the content '…': " +
2274
+ "render its `activity` and your own line instead of a bubble. A rejection " +
2275
+ "with `stored: true` kept the message in `messages`, so do not put the text " +
2276
+ "back. NEVER surface a " +
2265
2277
  "raw error or the workspace's billing state to an app user. " +
2266
2278
  "RENDER AN ASSISTANT REPLY WITH <RichText value={msg.content} />, " +
2267
2279
  "not <Text>: a model answers in MARKDOWN by default — **bold**, " +
@@ -2305,9 +2317,10 @@ const HOOKS = [
2305
2317
  "Reads ctx.agents.",
2306
2318
  returnShape: {
2307
2319
  send: "(text, { files }?) => Promise<{ id, role, content, created_at } | null>",
2320
+ cancel: "() => void // stops the run; send() resolves with the stopped row",
2308
2321
  reset: "() => void",
2309
- messages: "Array<{ id, conversation_id, role, content, created_at }>",
2310
- sending: "boolean",
2322
+ messages: "Array<{ id, conversation_id, role, content, activity?, outcome?, created_at }>",
2323
+ sending: "boolean // true while a run is in progress, also one found on mount",
2311
2324
  resuming:
2312
2325
  "boolean // true only while the stored transcript is being reopened on mount; show a loading state, not an empty thread",
2313
2326
  error: "AgentError | null",
@@ -4168,6 +4181,8 @@ const ACTION_SCRIPT_GLOBALS = [
4168
4181
  "triggerTableId",
4169
4182
  // sc-7885 — who initiated the run; null on `schedule` / `record_*`.
4170
4183
  "triggeredBy",
4184
+ // sc-15765 — the account a per-connection scheduled run is for; null otherwise.
4185
+ "connection",
4171
4186
  // sc-9031 — a Run action event's parameters; null on every other trigger.
4172
4187
  "input",
4173
4188
  // sc-13843 — hands the app run its one JSON result.
@@ -4526,6 +4541,7 @@ const WIDGET_CONTEXT_SHAPE = {
4526
4541
  description:
4527
4542
  "sc-7991 — injected @colixsystems/agents-client instance. " +
4528
4543
  "{ conversations(agentId) -> { create(), list(query), remove(conversationId), " +
4544
+ "stop(conversationId) -> Promise<{ conversation_id, stopping }> (sc-18562; optional on older hosts), " +
4529
4545
  "messages(conversationId) -> { list(query), send({ content, file_ids? }) } }, " +
4530
4546
  "capabilities(agentId) -> Promise<{ accepts_files, accepted_file_types, max_files, max_pdfs, max_file_bytes, max_total_bytes }>, " +
4531
4547
  "connections(agentId) -> { list(), create({ name, server_url, token }), test(id), remove(id), " +
@@ -7165,7 +7181,13 @@ const CONTRACT = deepFreeze({
7165
7181
  // 1.286.0: guidance (sc-16714) — when an Overlay goes `full`, and that a
7166
7182
  // full one draws its own close control; the `full-overlay-no-close`
7167
7183
  // lint warning flags one that does not.
7168
- version: "1.286.0",
7184
+ // 1.287.0: additive (sc-15765) — `connection` joins `actionScriptGlobals`:
7185
+ // the account a per-connection scheduled run is for, null otherwise.
7186
+ // 1.288.0: behaviour (sc-18562) — an agent run lives on the server: `sending`
7187
+ // covers a run found on mount, cancel() really stops it and send() resolves
7188
+ // with the stopped row, messages carry `outcome`, and a send during a run
7189
+ // rejects TURN_IN_PROGRESS. A rejection says `stored` when the message was kept.
7190
+ version: "1.288.0",
7169
7191
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7170
7192
  hooks: HOOKS,
7171
7193
  primitives: PRIMITIVES,
package/dist/hooks.js CHANGED
@@ -3645,6 +3645,10 @@ export function useInterpretDraft(tableId) {
3645
3645
  * control rather than retrying)
3646
3646
  * - "AGENT_FILES_BUSY" — 503 (the server could not take the files on
3647
3647
  * right now; retry shortly)
3648
+ * - "TURN_IN_PROGRESS" — 409 (the agent is still working on an earlier
3649
+ * message, maybe from another device; nothing
3650
+ * was sent. Give the text back; `sending` stays
3651
+ * true until that run ends)
3648
3652
  * - "AI_QUOTA_EXCEEDED" — 429 (the WORKSPACE is out of AI credit; this
3649
3653
  * does NOT clear by retrying — say so)
3650
3654
  * - "RATE_LIMITED" — 429 (too many turns — retry shortly)
@@ -3656,10 +3660,13 @@ export function useInterpretDraft(tableId) {
3656
3660
  * turn: the server finishes it and the
3657
3661
  * workspace is billed, so say "still
3658
3662
  * working", never "failed"
3659
- * - "CANCELLED" — `cancel()` was called. The user chose it,
3660
- * so render no error at all (the turn is
3661
- * still billed — never imply it stopped)
3663
+ * - "CANCELLED" — `cancel()` ended the send before it reached
3664
+ * the server, or on a host that cannot stop a
3665
+ * run. The user chose it, so render no error
3662
3666
  * - "INTERNAL" — anything else (a 5xx carrying no code)
3667
+ *
3668
+ * `stored` is true when the server kept the message although the turn failed:
3669
+ * it is in `messages`, so do not put the text back in the composer.
3663
3670
  */
3664
3671
  export class AgentError extends Error {
3665
3672
  constructor(code, message, opts) {
@@ -3675,6 +3682,43 @@ function statusOfAgentFailure(err) {
3675
3682
  return err && typeof err.status === "number" ? err.status : null;
3676
3683
  }
3677
3684
 
3685
+ // The server's page size; a thread is read from its END.
3686
+ const AGENT_TAIL_ROWS = 50;
3687
+ // Re-read beside the newest known row, so a long thread costs one read a check.
3688
+ const AGENT_TAIL_SLACK = 25;
3689
+ // Past the server's own limit on a run.
3690
+ const AGENT_WATCH_MS = 6 * 60 * 1000;
3691
+ // How long a lost send waits for the connection before it is given back.
3692
+ const AGENT_LOST_MS = 60 * 1000;
3693
+ const AGENT_LOST_CODES = ["NETWORK", "TIMEOUT", "GATEWAY_TIMEOUT"];
3694
+
3695
+ const agentPause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3696
+ const agentBackoff = (failures) => Math.min(15000, 2000 * 2 ** failures);
3697
+ // A refusal a later try cannot change.
3698
+ const agentRefused = (status) => status >= 400 && status < 500 && status !== 429;
3699
+
3700
+ /** The newest rows of a thread and whether a run is in progress. */
3701
+ async function readAgentTail(channel, knownTotal) {
3702
+ let offset = Math.max(0, knownTotal - AGENT_TAIL_SLACK);
3703
+ for (let attempt = 0; ; attempt += 1) {
3704
+ const page = await channel.list({ limit: AGENT_TAIL_ROWS, offset });
3705
+ const rows = page && Array.isArray(page.data) ? page.data : [];
3706
+ const meta = (page && page.meta) || {};
3707
+ const total = typeof meta.total === "number" ? meta.total : 0;
3708
+ if (offset + rows.length >= total || attempt === 2) {
3709
+ return { rows, total, running: meta.turn_running === true };
3710
+ }
3711
+ offset = Math.max(0, total - AGENT_TAIL_ROWS);
3712
+ }
3713
+ }
3714
+
3715
+ /** `prior` with the server's rows in their own order; the same array when it lacks none. */
3716
+ function mergeAgentRows(prior, rows) {
3717
+ const has = (list, row) => Boolean(row.id) && list.some((other) => other.id === row.id);
3718
+ if (rows.every((row) => has(prior, row))) return prior;
3719
+ return prior.filter((row) => !has(rows, row)).concat(rows);
3720
+ }
3721
+
3678
3722
  const NO_CONNECTIONS = Object.freeze({
3679
3723
  agentId: null,
3680
3724
  supported: false,
@@ -3717,6 +3761,12 @@ function toAgentError(err) {
3717
3761
  *
3718
3762
  * send(text) → Promise<{ role, content }> the agent's reply
3719
3763
  *
3764
+ * A run lives on the server: leaving, a refresh or a lost connection does not
3765
+ * end it. `sending` is true while one is in progress, on a later mount too, and
3766
+ * its ending lands in `messages` by itself. `cancel()` really stops it where
3767
+ * the host can: `send` then resolves with the stopped row, and what the agent
3768
+ * already changed stays changed.
3769
+ *
3720
3770
  * Sending is IMPERATIVE — no PAID call is ever made on mount; the widget calls
3721
3771
  * `send` from an event handler, and the first `send` opens the conversation, so
3722
3772
  * an author who places the widget and never types costs the workspace nothing.
@@ -3731,6 +3781,8 @@ function toAgentError(err) {
3731
3781
  * each `{ id, role, content, created_at }` with `role` of "user" | "assistant".
3732
3782
  * An assistant message that used a tool also carries `activity` — what the
3733
3783
  * agent DID with the user's data. Render the writes: "done!" is not evidence.
3784
+ * One that ended early carries `outcome` ("stopped" | "failed"): render that and
3785
+ * its `activity`, not its "…" content.
3734
3786
  * The SERVER owns the real transcript and the system prompt: the widget sends
3735
3787
  * one message and can neither read nor set the prompt.
3736
3788
  *
@@ -3801,6 +3853,9 @@ export function useAgent(agentRef, options) {
3801
3853
  // is a different agent and therefore a different decision.
3802
3854
  const suppressResumeRef = useRef(false);
3803
3855
 
3856
+ // The run `sending` reports: this hook's own send, or one found on the server.
3857
+ const runRef = useRef(null);
3858
+
3804
3859
  // A changed binding is a different agent, so neither the open thread nor the
3805
3860
  // transcript carries — leaving the messages would render agent A's
3806
3861
  // conversation underneath agent B.
@@ -3816,25 +3871,138 @@ export function useAgent(agentRef, options) {
3816
3871
  // A different agent is a different decision: leaving the old agent's
3817
3872
  // "new conversation" set would stop this one from ever resuming.
3818
3873
  suppressResumeRef.current = false;
3874
+ // The previous agent's run goes on in its own thread, unwatched.
3875
+ runRef.current = null;
3819
3876
  }
3820
3877
 
3821
- const abortRef = useRef(null);
3878
+ const messagesRef = useRef(messages);
3879
+ messagesRef.current = messages;
3880
+
3881
+ const startRun = useCallback((fields) => {
3882
+ const run = { thread: null, conversationId: null, controller: null, cancelled: false, stopping: false, stored: false, ...fields };
3883
+ runRef.current = run;
3884
+ setSending(true);
3885
+ return run;
3886
+ }, []);
3887
+
3888
+ // A run that is no longer this hook's own changes nothing on screen.
3889
+ const endRun = useCallback((run, failure) => {
3890
+ if (runRef.current !== run) return;
3891
+ runRef.current = null;
3892
+ // A stale thread is recoverable on the next send rather than permanently
3893
+ // broken: drop it so the widget opens a fresh one.
3894
+ if (failure && failure.code === "CONVERSATION_NOT_FOUND") conversationRef.current = null;
3895
+ // A cancel is the user's own choice, so it is not a failure to report.
3896
+ setError(failure && failure.code !== "CANCELLED" ? failure : null);
3897
+ setSending(false);
3898
+ }, []);
3899
+
3900
+ // Reads the thread until the run ends; resolves with the row it ended on, or
3901
+ // null once this hook has left the run.
3902
+ const followRun = useCallback(async (run, channel, firstPage) => {
3903
+ const deadline = Date.now() + AGENT_WATCH_MS;
3904
+ let page = firstPage;
3905
+ let total = page ? page.total : 0;
3906
+ let failures = 0;
3907
+ let lastFailure = null;
3908
+ for (let polls = 0; ; polls += 1) {
3909
+ if (page) {
3910
+ const rows = page.rows;
3911
+ setMessages((prior) => mergeAgentRows(prior, rows));
3912
+ if (run.asked && rows.some(run.asked)) run.stored = true;
3913
+ if (!page.running) {
3914
+ const last = rows[rows.length - 1];
3915
+ if (last && last.role === "user") {
3916
+ throw new AgentError("AI_GENERATION_FAILED", "The agent did not finish");
3917
+ }
3918
+ return last || null;
3919
+ }
3920
+ }
3921
+ if (polls > 0 || page) {
3922
+ if (Date.now() > deadline) throw lastFailure || new AgentError("TIMEOUT", "The agent did not answer in time");
3923
+ await agentPause(failures > 0 ? agentBackoff(failures) : polls < 5 ? 2000 : 4000);
3924
+ if (runRef.current !== run) return null;
3925
+ }
3926
+ page = null;
3927
+ try {
3928
+ page = await readAgentTail(channel, total);
3929
+ total = page.total;
3930
+ failures = 0;
3931
+ lastFailure = null;
3932
+ } catch (err) {
3933
+ if (agentRefused(statusOfAgentFailure(err))) throw toAgentError(err);
3934
+ failures += 1;
3935
+ lastFailure = toAgentError(err);
3936
+ }
3937
+ if (runRef.current !== run) return null;
3938
+ }
3939
+ }, []);
3940
+
3941
+ // A lost send: what became of it can only be told once the thread is readable.
3942
+ const readWhenBack = useCallback(async (run, channel) => {
3943
+ const deadline = Date.now() + AGENT_LOST_MS;
3944
+ for (let failures = 1; ; failures += 1) {
3945
+ try {
3946
+ return await readAgentTail(channel, 0);
3947
+ } catch (err) {
3948
+ if (agentRefused(statusOfAgentFailure(err)) || Date.now() > deadline) throw err;
3949
+ }
3950
+ await agentPause(agentBackoff(failures));
3951
+ if (runRef.current !== run) return null;
3952
+ }
3953
+ }, []);
3954
+
3955
+ const watchRun = useCallback(
3956
+ (run, channel, firstPage) => {
3957
+ followRun(run, channel, firstPage).then(
3958
+ () => endRun(run),
3959
+ (failure) => endRun(run, failure),
3960
+ );
3961
+ },
3962
+ [followRun, endRun],
3963
+ );
3822
3964
 
3823
3965
  const reset = useCallback(() => {
3824
3966
  // Outdates any resume in flight, so its transcript is discarded on arrival.
3825
3967
  resumeGenerationRef.current += 1;
3826
3968
  suppressResumeRef.current = true;
3827
3969
  conversationRef.current = null;
3970
+ // The run goes on in the thread that was left; this is another one.
3971
+ runRef.current = null;
3828
3972
  setMessages([]);
3829
3973
  setError(null);
3830
3974
  setResuming(false);
3975
+ setSending(false);
3831
3976
  }, []);
3832
3977
 
3833
- // Ends the WAIT, not the turn: the abort never reaches the server, which
3834
- // finishes and bills it either way. Never imply the work was stopped.
3835
- const cancel = useCallback(() => {
3836
- const controller = abortRef.current;
3837
- if (controller) controller.abort();
3978
+ const cancel = useCallback(async () => {
3979
+ const run = runRef.current;
3980
+ if (!run || run.stopping) return;
3981
+ setError(null);
3982
+ if (!run.conversationId) {
3983
+ run.cancelled = true;
3984
+ return;
3985
+ }
3986
+ if (typeof run.thread.stop !== "function") {
3987
+ // An older client can only end the wait; the server finishes the turn.
3988
+ if (run.controller) run.controller.abort();
3989
+ return;
3990
+ }
3991
+ run.stopping = true;
3992
+ try {
3993
+ // The message may still be on its way, so an idle answer is asked again.
3994
+ for (const wait of [1000, 2000, 4000, 4000, 4000]) {
3995
+ const answer = await run.thread.stop(run.conversationId);
3996
+ if (!answer || answer.stopping !== false) return;
3997
+ await agentPause(wait);
3998
+ if (runRef.current !== run) return;
3999
+ }
4000
+ setError(new AgentError("INTERNAL", "The run could not be stopped"));
4001
+ } catch (err) {
4002
+ if (runRef.current === run) setError(toAgentError(err));
4003
+ } finally {
4004
+ run.stopping = false;
4005
+ }
3838
4006
  }, []);
3839
4007
 
3840
4008
  // sc-8867 — reopen the caller's most recent thread with this agent.
@@ -3897,7 +4065,7 @@ export function useAgent(agentRef, options) {
3897
4065
  if (!conversationId) return;
3898
4066
  const transcript = thread.messages(conversationId);
3899
4067
  if (!transcript || typeof transcript.list !== "function") return;
3900
- const history = await transcript.list();
4068
+ const history = await readAgentTail(transcript, 0);
3901
4069
  // Re-checked AFTER the awaits: a rebind, an unmount or a reset during
3902
4070
  // the round trip must not adopt this agent's thread under another.
3903
4071
  if (
@@ -3913,10 +4081,10 @@ export function useAgent(agentRef, options) {
3913
4081
  return;
3914
4082
  }
3915
4083
  conversationRef.current = Promise.resolve(conversationId);
3916
- const rows =
3917
- history && Array.isArray(history.data) ? history.data : [];
4084
+ const rows = history.rows;
3918
4085
  // Never clobber a turn a concurrent send already appended.
3919
4086
  if (rows.length > 0) setMessages((prior) => (prior.length > 0 ? prior : rows));
4087
+ if (history.running) watchRun(startRun({ thread, conversationId }), transcript, history);
3920
4088
  } catch {
3921
4089
  // A transcript that will not load is not a failed turn, and the widget
3922
4090
  // is fully usable without it: a visible error here would report a
@@ -3928,12 +4096,15 @@ export function useAgent(agentRef, options) {
3928
4096
 
3929
4097
  return () => {
3930
4098
  cancelled = true;
4099
+ // Left: the run goes on at the server and a later mount finds it again.
4100
+ runRef.current = null;
4101
+ setSending(false);
3931
4102
  // A hung `list()` never settles, so the `finally` above may never run.
3932
4103
  // Without this the next render stays latched on a spinner with the
3933
4104
  // composer disabled — the wedge this whole path exists to avoid.
3934
4105
  setResuming(false);
3935
4106
  };
3936
- }, [available, agentRef]);
4107
+ }, [available, agentRef, startRun, watchRun]);
3937
4108
 
3938
4109
  // sc-16546 — what this agent reads; null until known, or when it reads none.
3939
4110
  const wantsFiles = Boolean(options && options.files === true);
@@ -3976,8 +4147,16 @@ export function useAgent(agentRef, options) {
3976
4147
  .map((file) => (typeof file === "string" ? file : file && file.id))
3977
4148
  .filter((id) => typeof id === "string" && id.length > 0);
3978
4149
 
3979
- setSending(true);
4150
+ // The server would refuse it too: one run at a time in a thread.
4151
+ if (runRef.current) {
4152
+ throw new AgentError("TURN_IN_PROGRESS", "The agent is still working on an earlier message");
4153
+ }
4154
+ const known = new Set(messagesRef.current.map((row) => row.id));
4155
+ const run = startRun({
4156
+ asked: (row) => row.role === "user" && row.content === content && !known.has(row.id),
4157
+ });
3980
4158
  setError(null);
4159
+ let channel = null;
3981
4160
  try {
3982
4161
  const thread = client.conversations(agentId);
3983
4162
  if (!conversationRef.current) {
@@ -3991,49 +4170,73 @@ export function useAgent(agentRef, options) {
3991
4170
  });
3992
4171
  }
3993
4172
  let conversationId;
4173
+ const opening = conversationRef.current;
3994
4174
  try {
3995
4175
  conversationId = await conversationRef.current;
3996
4176
  } catch (err) {
3997
4177
  // A failed open must not wedge the widget on a rejected promise.
3998
- conversationRef.current = null;
4178
+ if (conversationRef.current === opening) conversationRef.current = null;
3999
4179
  throw err;
4000
4180
  }
4001
- const controller =
4002
- typeof AbortController === "function" ? new AbortController() : null;
4003
- abortRef.current = controller;
4004
- const turn = await thread
4005
- .messages(conversationId)
4181
+ if (run.cancelled) throw new AgentError("CANCELLED", "The request was cancelled");
4182
+ run.thread = thread;
4183
+ run.conversationId = conversationId;
4184
+ run.controller = typeof AbortController === "function" ? new AbortController() : null;
4185
+ channel = thread.messages(conversationId);
4186
+ const turn = await channel
4006
4187
  .send(
4007
4188
  fileIds.length > 0 ? { content, file_ids: fileIds } : { content },
4008
- controller ? { signal: controller.signal } : undefined,
4189
+ run.controller ? { signal: run.controller.signal } : undefined,
4009
4190
  );
4010
- abortRef.current = null;
4011
- // A rebind during the round trip makes this the PREVIOUS agent's reply;
4012
- // writing it now would render it under the new one.
4013
- if (agentIdRef.current !== agentId) {
4014
- setSending(false);
4015
- return turn && turn.reply ? turn.reply : null;
4016
- }
4017
- const userMessage = turn && turn.user_message ? turn.user_message : null;
4018
4191
  const reply = turn && turn.reply ? turn.reply : null;
4019
- setMessages((prior) =>
4020
- prior.concat(userMessage ? [userMessage] : [], reply ? [reply] : []),
4021
- );
4022
- setSending(false);
4192
+ // Left meanwhile (reset, rebind): the reply belongs to the other thread.
4193
+ if (runRef.current === run) {
4194
+ setMessages((prior) =>
4195
+ mergeAgentRows(prior, [turn && turn.user_message, reply].filter(Boolean)),
4196
+ );
4197
+ }
4198
+ endRun(run);
4023
4199
  return reply;
4024
4200
  } catch (err) {
4025
4201
  const e = toAgentError(err);
4026
- // A stale thread is recoverable on the next send rather than permanently
4027
- // broken: drop it so the widget opens a fresh one.
4028
- if (e.code === "CONVERSATION_NOT_FOUND") conversationRef.current = null;
4029
- abortRef.current = null;
4030
- // Same rebind guard: a new agent must not inherit the old one's error.
4031
- // A cancel is the user's own choice, so it is not a failure to report.
4032
- if (e.code !== "CANCELLED" && agentIdRef.current === agentId) setError(e);
4033
- setSending(false);
4034
- throw e;
4202
+ const readable = channel && typeof channel.list === "function" && runRef.current === run;
4203
+ if (e.code === "TURN_IN_PROGRESS" && readable) {
4204
+ setError(e);
4205
+ watchRun(run, channel);
4206
+ throw e;
4207
+ }
4208
+ const lost = AGENT_LOST_CODES.includes(e.code) || statusOfAgentFailure(err) === 504;
4209
+ const reread = () => (lost ? readWhenBack(run, channel) : readAgentTail(channel, 0));
4210
+ const page = readable && e.code !== "CANCELLED" ? await reread().catch(() => null) : null;
4211
+ if (!page || runRef.current !== run) {
4212
+ endRun(run, e);
4213
+ throw e;
4214
+ }
4215
+ run.stored = page.rows.some(run.asked);
4216
+ const last = page.rows[page.rows.length - 1];
4217
+ const answered = run.stored && last.role === "assistant" && last.outcome !== "failed";
4218
+ let failure = e;
4219
+ // The server claims a run before it keeps the message, so a lost send may
4220
+ // be the one running without its row being there yet.
4221
+ if (page.running ? lost || run.stored : answered || (lost && run.stored)) {
4222
+ try {
4223
+ const reply = await followRun(run, channel, page);
4224
+ if (run.stored) {
4225
+ endRun(run);
4226
+ return reply;
4227
+ }
4228
+ } catch (ended) {
4229
+ if (run.stored) failure = ended;
4230
+ }
4231
+ } else if (run.stored) {
4232
+ // It failed after keeping the message, and perhaps some steps: show them.
4233
+ setMessages((prior) => mergeAgentRows(prior, page.rows));
4234
+ }
4235
+ if (run.stored) failure.stored = true;
4236
+ endRun(run, failure);
4237
+ throw failure;
4035
4238
  }
4036
- }, []);
4239
+ }, [startRun, endRun, followRun, readWhenBack, watchRun]);
4037
4240
 
4038
4241
  // sc-17588 — the caller's own MCP servers for this agent. Asked only with
4039
4242
  // `{ connections: true }`, so a widget without the control sends nothing.
@@ -4183,6 +4386,7 @@ export function useAgent(agentRef, options) {
4183
4386
  let visibleMessages = messages;
4184
4387
  let visibleError = error;
4185
4388
  let visibleResuming = resuming;
4389
+ let visibleSending = sending;
4186
4390
  if (pendingResetRef.current) {
4187
4391
  pendingResetRef.current = false;
4188
4392
  visibleMessages = [];
@@ -4195,6 +4399,8 @@ export function useAgent(agentRef, options) {
4195
4399
  // loading now rather than showing an empty thread for one frame.
4196
4400
  visibleResuming = available;
4197
4401
  if (resuming !== available) setResuming(available);
4402
+ visibleSending = false;
4403
+ if (sending) setSending(false);
4198
4404
  }
4199
4405
 
4200
4406
  return {
@@ -4202,7 +4408,8 @@ export function useAgent(agentRef, options) {
4202
4408
  cancel,
4203
4409
  reset,
4204
4410
  messages: visibleMessages,
4205
- sending,
4411
+ // This hook's own send, or a run found still in progress on the server.
4412
+ sending: visibleSending,
4206
4413
  // sc-8867 — true only while the stored transcript is being reopened, so a
4207
4414
  // widget shows a loading state instead of an empty thread that is about to
4208
4415
  // fill. Never true for a turn in flight; that is `sending`.
package/dist/index.d.ts CHANGED
@@ -2192,6 +2192,11 @@ export interface AgentMessage {
2192
2192
  activity?: AgentActivity[];
2193
2193
  /** sc-16546 — the files a user message carried, by reference. Absent when none. */
2194
2194
  attachments?: Array<{ file_id: string; name: string; mime_type: string; size_bytes: number }>;
2195
+ /**
2196
+ * sc-18562 — set on an assistant message whose run ended early. `content` is
2197
+ * then "…": render `activity` and a line of your own instead of a bubble.
2198
+ */
2199
+ outcome?: "stopped" | "failed";
2195
2200
  created_at: string;
2196
2201
  }
2197
2202
 
@@ -2239,9 +2244,10 @@ export interface AgentApi {
2239
2244
  */
2240
2245
  send(text: string, options?: { files?: Array<string | { id: string }> }): Promise<AgentMessage | null>;
2241
2246
  /**
2242
- * Stop WAITING for the turn in flight. The abort never reaches the server,
2243
- * which finishes and bills it either way — label the control "stop", not
2244
- * "cancel", and show no error when the user presses it.
2247
+ * Stop the run in progress. `send` then resolves with the stopped row; what
2248
+ * the agent already changed stays changed. A stop that fails sets `error`
2249
+ * while `sending` stays true. On an older host it only ends the wait, and
2250
+ * `send` rejects CANCELLED: show no error for that.
2245
2251
  */
2246
2252
  cancel(): void;
2247
2253
  /**
@@ -2251,6 +2257,7 @@ export interface AgentApi {
2251
2257
  reset(): void;
2252
2258
  /** Oldest first. The SERVER owns the real transcript. */
2253
2259
  messages: AgentMessage[];
2260
+ /** True while a run is in progress, also one this mount found on the server. */
2254
2261
  sending: boolean;
2255
2262
  /**
2256
2263
  * sc-8867 — true only while the caller's most recent thread is being
@@ -3791,6 +3798,7 @@ export class AgentError extends Error {
3791
3798
  | "AGENT_DISABLED"
3792
3799
  | "CONVERSATION_NOT_FOUND"
3793
3800
  | "INVALID_MESSAGE"
3801
+ | "TURN_IN_PROGRESS"
3794
3802
  | "AI_QUOTA_EXCEEDED"
3795
3803
  | "RATE_LIMITED"
3796
3804
  | "AI_UNAVAILABLE"
@@ -3801,6 +3809,8 @@ export class AgentError extends Error {
3801
3809
  | "CANCELLED"
3802
3810
  | "INTERNAL"
3803
3811
  | (string & {});
3812
+ /** True when the server kept the message although the turn failed. */
3813
+ stored?: boolean;
3804
3814
  constructor(code: string, message: string, opts?: { cause?: unknown });
3805
3815
  }
3806
3816
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.349.0",
3
+ "version": "0.351.0",
4
4
  "description": "Common widget interface for AppStudio. Implements WidgetManifest, WidgetContext, property schema, and helper hooks.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/contract.js CHANGED
@@ -2259,9 +2259,21 @@ const HOOKS = [
2259
2259
  "it off, so hide the affordance rather than retrying; TIMEOUT means the " +
2260
2260
  "client stopped waiting and the turn is STILL running and billed, so " +
2261
2261
  "say it is taking longer, never that it failed or that they are " +
2262
- "offline; CANCELLED is the user pressing your stop control, so render " +
2263
- "no error at all. Call cancel() to stop waiting -- it ends the WAIT, " +
2264
- "not the turn. NEVER surface a " +
2262
+ "offline; TURN_IN_PROGRESS (409) means the agent is still working on an " +
2263
+ "earlier message, so nothing was sent: put the text back and say they can " +
2264
+ "send it when that one is done; CANCELLED is the user's own choice, so " +
2265
+ "render no error at all. A RUN LIVES ON THE SERVER (sc-18562): leaving the " +
2266
+ "page, a refresh or a lost connection does not end it. `sending` is true " +
2267
+ "while one is in progress, on a later mount too, and its answer lands in " +
2268
+ "`messages` by itself, so gate the composer on `sending` and never resend. " +
2269
+ "cancel() really stops the run (label it 'Stop'): send() then RESOLVES with " +
2270
+ "the stopped row, and changes already made stay made. If the stop fails, " +
2271
+ "`error` is set while `sending` stays true. On an older host cancel() only " +
2272
+ "ends the wait and send() rejects CANCELLED. An assistant message that " +
2273
+ "ended early carries `outcome` ('stopped' | 'failed') and the content '…': " +
2274
+ "render its `activity` and your own line instead of a bubble. A rejection " +
2275
+ "with `stored: true` kept the message in `messages`, so do not put the text " +
2276
+ "back. NEVER surface a " +
2265
2277
  "raw error or the workspace's billing state to an app user. " +
2266
2278
  "RENDER AN ASSISTANT REPLY WITH <RichText value={msg.content} />, " +
2267
2279
  "not <Text>: a model answers in MARKDOWN by default — **bold**, " +
@@ -2305,9 +2317,10 @@ const HOOKS = [
2305
2317
  "Reads ctx.agents.",
2306
2318
  returnShape: {
2307
2319
  send: "(text, { files }?) => Promise<{ id, role, content, created_at } | null>",
2320
+ cancel: "() => void // stops the run; send() resolves with the stopped row",
2308
2321
  reset: "() => void",
2309
- messages: "Array<{ id, conversation_id, role, content, created_at }>",
2310
- sending: "boolean",
2322
+ messages: "Array<{ id, conversation_id, role, content, activity?, outcome?, created_at }>",
2323
+ sending: "boolean // true while a run is in progress, also one found on mount",
2311
2324
  resuming:
2312
2325
  "boolean // true only while the stored transcript is being reopened on mount; show a loading state, not an empty thread",
2313
2326
  error: "AgentError | null",
@@ -4168,6 +4181,8 @@ const ACTION_SCRIPT_GLOBALS = [
4168
4181
  "triggerTableId",
4169
4182
  // sc-7885 — who initiated the run; null on `schedule` / `record_*`.
4170
4183
  "triggeredBy",
4184
+ // sc-15765 — the account a per-connection scheduled run is for; null otherwise.
4185
+ "connection",
4171
4186
  // sc-9031 — a Run action event's parameters; null on every other trigger.
4172
4187
  "input",
4173
4188
  // sc-13843 — hands the app run its one JSON result.
@@ -4526,6 +4541,7 @@ const WIDGET_CONTEXT_SHAPE = {
4526
4541
  description:
4527
4542
  "sc-7991 — injected @colixsystems/agents-client instance. " +
4528
4543
  "{ conversations(agentId) -> { create(), list(query), remove(conversationId), " +
4544
+ "stop(conversationId) -> Promise<{ conversation_id, stopping }> (sc-18562; optional on older hosts), " +
4529
4545
  "messages(conversationId) -> { list(query), send({ content, file_ids? }) } }, " +
4530
4546
  "capabilities(agentId) -> Promise<{ accepts_files, accepted_file_types, max_files, max_pdfs, max_file_bytes, max_total_bytes }>, " +
4531
4547
  "connections(agentId) -> { list(), create({ name, server_url, token }), test(id), remove(id), " +
@@ -7165,7 +7181,13 @@ const CONTRACT = deepFreeze({
7165
7181
  // 1.286.0: guidance (sc-16714) — when an Overlay goes `full`, and that a
7166
7182
  // full one draws its own close control; the `full-overlay-no-close`
7167
7183
  // lint warning flags one that does not.
7168
- version: "1.286.0",
7184
+ // 1.287.0: additive (sc-15765) — `connection` joins `actionScriptGlobals`:
7185
+ // the account a per-connection scheduled run is for, null otherwise.
7186
+ // 1.288.0: behaviour (sc-18562) — an agent run lives on the server: `sending`
7187
+ // covers a run found on mount, cancel() really stops it and send() resolves
7188
+ // with the stopped row, messages carry `outcome`, and a send during a run
7189
+ // rejects TURN_IN_PROGRESS. A rejection says `stored` when the message was kept.
7190
+ version: "1.288.0",
7169
7191
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7170
7192
  hooks: HOOKS,
7171
7193
  primitives: PRIMITIVES,