@nexface/chat 0.1.20 → 0.1.21-alpha.1

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 (44) hide show
  1. package/dist/assistant-components.d.ts +2 -1
  2. package/dist/assistant-components.js +22 -10
  3. package/dist/assistant-runtime.js +15 -4
  4. package/dist/client.d.ts +3 -1
  5. package/dist/client.js +136 -42
  6. package/dist/config.d.ts +1 -1
  7. package/dist/default-chat.d.ts +1 -1
  8. package/dist/default-chat.js +26411 -26047
  9. package/dist/fonts/Inter-OFL.txt +93 -0
  10. package/dist/fonts/inter-medium.ttf +0 -0
  11. package/dist/protocol-messages.js +15 -16
  12. package/dist/protocol-response.js +10 -3
  13. package/dist/react.d.ts +13 -1
  14. package/dist/react.js +609 -99
  15. package/dist/session-coordinator.d.ts +23 -0
  16. package/dist/session-coordinator.js +139 -0
  17. package/dist/session-history.d.ts +29 -0
  18. package/dist/session-history.js +282 -0
  19. package/dist/shared/errors.d.ts +1 -1
  20. package/dist/shared/errors.js +2 -0
  21. package/dist/shared/tool-presentation.d.ts +17 -0
  22. package/dist/shared/tool-presentation.js +5 -0
  23. package/dist/shared/tool-proxy.d.ts +6 -0
  24. package/dist/shared/tool-proxy.js +25 -0
  25. package/dist/storage.d.ts +4 -6
  26. package/dist/storage.js +52 -43
  27. package/dist/styles.css +1491 -676
  28. package/dist/tool-confirmation-card.d.ts +5 -0
  29. package/dist/tool-confirmation-card.js +33 -0
  30. package/dist/tool-confirmation.d.ts +23 -0
  31. package/dist/tool-confirmation.js +25 -0
  32. package/dist/tool-presentation.d.ts +6 -0
  33. package/dist/tool-presentation.js +132 -0
  34. package/dist/tool-result.d.ts +5 -0
  35. package/dist/tool-result.js +31 -0
  36. package/dist/types.d.ts +3 -1
  37. package/dist/ui/home-demo/greeting.d.ts +3 -1
  38. package/dist/ui/home-demo/greeting.js +2 -2
  39. package/dist/ui/home-demo/suggestions.d.ts +2 -4
  40. package/dist/ui/home-demo/suggestions.js +5 -4
  41. package/dist/ui/home-demo/trace.js +2 -3
  42. package/dist/ui/thread-list.aui.d.ts +2 -1
  43. package/dist/ui/thread-list.aui.js +2 -2
  44. package/package.json +3 -3
@@ -5,13 +5,14 @@ export declare function AttachmentTile({ binding, savedPreview, }: {
5
5
  binding?: AssistantBinding;
6
6
  savedPreview?: string | undefined;
7
7
  }): import("react").JSX.Element;
8
- export declare function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, cancel, }: {
8
+ export declare function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, recoveryUnavailable, cancel, }: {
9
9
  binding: AssistantBinding;
10
10
  options: ChatProps["attachments"];
11
11
  placeholder: string;
12
12
  suggestion?: string | undefined;
13
13
  busy: boolean;
14
14
  cancelling: boolean;
15
+ recoveryUnavailable: boolean;
15
16
  cancel(): void;
16
17
  }): import("react").JSX.Element;
17
18
  export declare function AssistantParts({ showDetails, tools, }: {
@@ -11,10 +11,12 @@ import { TooltipIconButton } from "./ui/tooltip-icon-button.js";
11
11
  import { Button } from "./ui/button.js";
12
12
  import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip.js";
13
13
  import { ToolGroupRoot, ToolGroupContent } from "./ui/tool-group.aui.js";
14
- import { DisclosureTrigger, ToolCall, disclosureContentClass } from "./ui/home-demo/trace.js";
14
+ import { DisclosureTrigger, disclosureContentClass } from "./ui/home-demo/trace.js";
15
15
  import { Reasoning, ReasoningRoot, ReasoningContent, ReasoningText } from "./ui/reasoning.aui.js";
16
16
  import { TraceLine } from "./ui/home-demo/trace-line.js";
17
17
  import { attachmentAccept } from "./attachments.js";
18
+ import { useToolPresentations } from "./react.js";
19
+ import { ToolPresentationUI } from "./tool-presentation.js";
18
20
  export function AttachmentTile({ binding, savedPreview, }) {
19
21
  const attachment = useAuiState((s) => s.attachment);
20
22
  const preview = binding?.attachments.preview(attachment.id) ??
@@ -22,7 +24,7 @@ export function AttachmentTile({ binding, savedPreview, }) {
22
24
  attachment.content?.find((part) => part.type === "image")?.image;
23
25
  return (_jsx(AttachmentUI, { preview: preview, children: _jsxs("div", { className: cn("flex max-w-40 flex-col text-xs wrap-anywhere"), children: [_jsx(AttachmentPrimitive.Name, {}), binding && attachment.status.type === "requires-action" ? (_jsx("small", { className: cn("text-muted-foreground"), children: "\u5DF2\u5C31\u7EEA" })) : null, attachment.status.type === "running" ? (_jsx("small", { className: cn("text-muted-foreground"), children: "\u6B63\u5728\u5904\u7406\u2026" })) : null, attachment.status.type === "incomplete" ? (_jsx("small", { className: cn("text-destructive"), role: "alert", children: attachment.status.message ?? "Attachment processing failed" })) : null] }) }));
24
26
  }
25
- export function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, cancel, }) {
27
+ export function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, recoveryUnavailable, cancel, }) {
26
28
  const input = useRef(null);
27
29
  const sending = binding.sending;
28
30
  const voiceBusy = binding.voice.status !== "idle";
@@ -35,6 +37,14 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
35
37
  const empty = useAuiState((state) => state.composer.text.length === 0);
36
38
  const nextMessage = !busy && !inputDisabled && empty ? suggestion : undefined;
37
39
  const showCancel = useAuiState((state) => busy && (state.thread.isRunning || state.composer.isEmpty));
40
+ const recoveryReason = recoveryUnavailable
41
+ ? "This chat cannot continue because its recovery state is unavailable."
42
+ : undefined;
43
+ const sendButton = (_jsx(ComposerPrimitive.Send, { asChild: true, disabled: inputDisabled || recoveryUnavailable, children: _jsx("button", { type: "button", onClick: (event) => {
44
+ event.preventDefault();
45
+ if (!recoveryUnavailable)
46
+ void binding.send();
47
+ }, "aria-label": "\u53D1\u9001\u4EFB\u52A1", "aria-description": recoveryReason, className: cn("bg-primary text-primary-foreground rounded-control grid size-7 place-items-center transition-opacity disabled:pointer-events-none disabled:opacity-40"), children: _jsx(ArrowUpIcon, { className: cn("size-4") }) }) }));
38
48
  const addFiles = (files) => {
39
49
  for (const file of files)
40
50
  void binding.runtime.thread.composer
@@ -43,7 +53,8 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
43
53
  };
44
54
  return (_jsxs(Composer, { onSubmit: (event) => {
45
55
  event.preventDefault();
46
- void binding.send();
56
+ if (!recoveryUnavailable)
57
+ void binding.send();
47
58
  }, inputProps: {
48
59
  "aria-label": "输入 Agent 任务",
49
60
  placeholder: nextMessage ?? placeholder,
@@ -66,7 +77,8 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
66
77
  }
67
78
  else if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
68
79
  event.preventDefault();
69
- void binding.send();
80
+ if (!recoveryUnavailable)
81
+ void binding.send();
70
82
  }
71
83
  },
72
84
  }, actions: _jsxs(_Fragment, { children: [voiceBusy ? (_jsx("span", { role: "status", className: cn("sr-only"), children: binding.voice.status === "starting"
@@ -76,10 +88,7 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
76
88
  : "正在录音" })) : null, voiceBusy ? (_jsx(TooltipIconButton, { tooltip: "\u53D6\u6D88\u5F55\u97F3", "aria-label": "\u53D6\u6D88\u8BED\u97F3\u8F93\u5165", className: cn("size-7 shrink-0"), onClick: binding.voice.cancel, children: _jsx(XIcon, { className: cn("size-4") }) })) : options !== false ? (_jsxs(_Fragment, { children: [_jsx("input", { ref: input, type: "file", multiple: true, disabled: inputDisabled, accept: options?.accept ?? attachmentAccept, hidden: true, onChange: (event) => {
77
89
  addFiles(Array.from(event.target.files ?? []));
78
90
  event.target.value = "";
79
- } }), _jsx("button", { type: "button", className: cn("text-muted-foreground hover:text-foreground rounded-control grid size-7 shrink-0 place-items-center transition-colors"), "aria-label": "\u6DFB\u52A0\u9644\u4EF6", disabled: inputDisabled, onClick: () => input.current?.click(), children: _jsx(PlusIcon, { className: cn("size-4") }) })] })) : (_jsx("span", {})), voiceBusy ? _jsx(ComposerVoice, { recording: binding.voice.status === "recording" }) : null, _jsxs("div", { className: cn("flex shrink-0 items-center gap-1"), children: [_jsxs(AuiIf, { condition: (state) => state.thread.capabilities.dictation, children: [_jsx(AuiIf, { condition: (state) => state.composer.dictation == null, children: _jsx(TooltipProvider, { delayDuration: 0, children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: cn("inline-flex"), tabIndex: voiceDisabledReason ? 0 : undefined, "aria-label": voiceDisabledReason, children: _jsx(ComposerPrimitive.Dictate, { asChild: true, disabled: busy || sending, children: _jsx(Button, { variant: "ghost", size: "icon", "aria-label": "\u5F00\u59CB\u8BED\u97F3\u8F93\u5165", "aria-description": voiceDisabledReason, className: cn("size-7 p-1"), children: _jsx(MicIcon, { className: cn("size-4") }) }) }) }) }), _jsx(TooltipContent, { children: voiceDisabledReason ?? "语音输入" })] }) }) }), _jsx(AuiIf, { condition: (state) => state.composer.dictation != null, children: _jsx(ComposerPrimitive.StopDictation, { asChild: true, disabled: binding.voice.status !== "recording", children: _jsx("button", { type: "button", "aria-label": "\u7ED3\u675F\u8BED\u97F3\u8F93\u5165", title: "\u7ED3\u675F\u5F55\u97F3", className: cn("text-destructive rounded-control grid size-7 place-items-center transition-colors disabled:opacity-50"), children: _jsx(SquareIcon, { className: cn("size-3 animate-pulse fill-current") }) }) }) })] }), showCancel ? (_jsx("button", { type: "button", "aria-label": "\u53D6\u6D88\u4EFB\u52A1", className: cn("bg-primary text-primary-foreground rounded-control grid size-7 place-items-center"), disabled: cancelling, onClick: cancel, children: _jsx(SquareIcon, { className: cn("size-3 fill-current") }) })) : (_jsx(ComposerPrimitive.Send, { asChild: true, disabled: inputDisabled, children: _jsx("button", { type: "button", onClick: (event) => {
80
- event.preventDefault();
81
- void binding.send();
82
- }, "aria-label": "\u53D1\u9001\u4EFB\u52A1", className: cn("bg-primary text-primary-foreground rounded-control grid size-7 place-items-center transition-opacity disabled:opacity-40"), children: _jsx(ArrowUpIcon, { className: cn("size-4") }) }) }))] })] }), children: [_jsx("div", { ref: (element) => {
91
+ } }), _jsx("button", { type: "button", className: cn("text-muted-foreground hover:text-foreground rounded-control grid size-7 shrink-0 place-items-center transition-colors"), "aria-label": "\u6DFB\u52A0\u9644\u4EF6", disabled: inputDisabled, onClick: () => input.current?.click(), children: _jsx(PlusIcon, { className: cn("size-4") }) })] })) : (_jsx("span", {})), voiceBusy ? _jsx(ComposerVoice, { recording: binding.voice.status === "recording" }) : null, _jsxs("div", { className: cn("flex shrink-0 items-center gap-1"), children: [_jsxs(AuiIf, { condition: (state) => state.thread.capabilities.dictation, children: [_jsx(AuiIf, { condition: (state) => state.composer.dictation == null, children: _jsx(TooltipProvider, { delayDuration: 0, children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: cn("inline-flex"), tabIndex: voiceDisabledReason ? 0 : undefined, "aria-label": voiceDisabledReason, children: _jsx(ComposerPrimitive.Dictate, { asChild: true, disabled: busy || sending, children: _jsx(Button, { variant: "ghost", size: "icon", "aria-label": "\u5F00\u59CB\u8BED\u97F3\u8F93\u5165", "aria-description": voiceDisabledReason, className: cn("size-7 p-1"), children: _jsx(MicIcon, { className: cn("size-4") }) }) }) }) }), _jsx(TooltipContent, { children: voiceDisabledReason ?? "语音输入" })] }) }) }), _jsx(AuiIf, { condition: (state) => state.composer.dictation != null, children: _jsx(ComposerPrimitive.StopDictation, { asChild: true, disabled: binding.voice.status !== "recording", children: _jsx("button", { type: "button", "aria-label": "\u7ED3\u675F\u8BED\u97F3\u8F93\u5165", title: "\u7ED3\u675F\u5F55\u97F3", className: cn("text-destructive rounded-control grid size-7 place-items-center transition-colors disabled:opacity-50"), children: _jsx(SquareIcon, { className: cn("size-3 animate-pulse fill-current") }) }) }) })] }), showCancel ? (_jsx("button", { type: "button", "aria-label": "\u53D6\u6D88\u4EFB\u52A1", className: cn("bg-primary text-primary-foreground rounded-control grid size-7 place-items-center"), disabled: cancelling, onClick: cancel, children: _jsx(SquareIcon, { className: cn("size-3 fill-current") }) })) : recoveryReason ? (_jsx(TooltipProvider, { delayDuration: 0, children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx("span", { className: cn("inline-flex"), tabIndex: 0, "aria-label": recoveryReason, children: sendButton }) }), _jsx(TooltipContent, { children: recoveryReason })] }) })) : (sendButton)] })] }), children: [_jsx("div", { ref: (element) => {
83
92
  element?.toggleAttribute("inert", inputDisabled);
84
93
  }, className: cn("aui-composer-attachments flex w-full flex-row items-center gap-2 overflow-x-auto empty:hidden"), children: _jsx(ComposerPrimitive.Attachments, { children: () => _jsx(AttachmentTile, { binding: binding }) }) }), sending ? _jsx("small", { role: "status", children: "\u6B63\u5728\u5904\u7406\u9644\u4EF6\u2026" }) : null] }));
85
94
  }
@@ -103,7 +112,10 @@ const groupAssistantParts = groupPartByType({
103
112
  "standalone-tool-call": [],
104
113
  });
105
114
  export function AssistantParts({ showDetails, tools = [], }) {
106
- return (_jsx(_Fragment, { children: _jsx(GroupedParts, { groupBy: groupAssistantParts, children: ({ part, children }) => {
115
+ const registry = useToolPresentations();
116
+ return (_jsx(_Fragment, { children: _jsx(GroupedParts, { groupBy: (part, context) => part.type === "tool-call" && registry?.controller?.get(part.toolName)
117
+ ? []
118
+ : groupAssistantParts(part, context), children: ({ part, children }) => {
107
119
  switch (part.type) {
108
120
  case "group-chainOfThought":
109
121
  return _jsx("div", { className: cn("mb-3"), children: children });
@@ -121,7 +133,7 @@ export function AssistantParts({ showDetails, tools = [], }) {
121
133
  case "text":
122
134
  return part.text === "" && part.status?.type === "running" ? (_jsx(TraceLine, { live: true, label: "thinking" })) : (_jsx(MarkdownText, {}));
123
135
  case "tool-call":
124
- return (part.toolUI ?? (_jsx(ToolCall, { ...part, showDetails: showDetails, presentation: tools.find((tool) => tool.type === "tool" && tool.toolCallId === part.toolCallId) })));
136
+ return (part.toolUI ?? (_jsx(ToolPresentationUI, { ...part, showDetails: showDetails, presentation: tools.find((tool) => tool.type === "tool" && tool.toolCallId === part.toolCallId) })));
125
137
  case "indicator":
126
138
  return _jsx(TraceLine, { live: true, label: "thinking" });
127
139
  default:
@@ -2,7 +2,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "react";
3
3
  import { AssistantRuntimeProvider, MessageNotSentError, useExternalStoreRuntime, } from "@assistant-ui/react";
4
4
  import { AssistantAttachments, toAssistantAttachment } from "./assistant-attachments.js";
5
- import { assertChatSendable } from "./react.js";
5
+ import { assertChatSendable, sessionCommandResult } from "./react.js";
6
6
  import { useVoiceInput } from "./voice/use-voice.js";
7
7
  function parseToolArgs(text) {
8
8
  try {
@@ -155,10 +155,20 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
155
155
  })),
156
156
  onSwitchToNewThread: () => {
157
157
  latest.current.createSession();
158
+ return sessionCommandResult(latest.current);
159
+ },
160
+ onSwitchToThread: (next) => {
161
+ latest.current.switchSession(next);
162
+ return sessionCommandResult(latest.current);
163
+ },
164
+ onRename: (target, title) => {
165
+ latest.current.renameSession(target, title);
166
+ return sessionCommandResult(latest.current);
167
+ },
168
+ onDelete: (target) => {
169
+ latest.current.deleteSession(target);
170
+ return sessionCommandResult(latest.current);
158
171
  },
159
- onSwitchToThread: (next) => latest.current.switchSession(next),
160
- onRename: (target, title) => latest.current.renameSession(target, title),
161
- onDelete: (target) => latest.current.deleteSession(target),
162
172
  },
163
173
  },
164
174
  });
@@ -175,6 +185,7 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
175
185
  setSending(true);
176
186
  setNotice("");
177
187
  try {
188
+ assertChatSendable(latest.current, id);
178
189
  // Prepare before dispatch: the upstream void send API cannot report upload
179
190
  // rejections to its caller. Keep the draft intact until every file settles.
180
191
  const results = await Promise.allSettled(draft.attachments.map((attachment) => attachments.send(attachment)));
package/dist/client.d.ts CHANGED
@@ -62,13 +62,15 @@ declare class ChatClientImplementation implements ChatClient {
62
62
  getStatus: () => ChatClientStatus;
63
63
  getApproval: () => ToolApprovalInterruptDescriptor | undefined;
64
64
  getError: () => Error | undefined;
65
+ get recoveryUnavailable(): boolean;
65
66
  assertRecoveryAvailable(): void;
66
67
  subscribe: (listener: () => void) => (() => void);
67
68
  subscribeEvents: (listener: (event: ProtocolEvent) => void) => (() => void);
68
69
  get cancelling(): boolean;
69
70
  get busy(): boolean;
71
+ get appendOnly(): boolean;
70
72
  setPageResolver(resolver: (name: string) => boolean): void;
71
- restore(messages: UIMessage[]): void;
73
+ restore(messages: UIMessage[], appendOnly?: boolean): void;
72
74
  recreateBefore(messageId: string): ChatClient;
73
75
  switchModel(model: AgentModelConfig): Promise<void>;
74
76
  sendMessage: (content: string | readonly AgentInputContent[]) => Promise<{
package/dist/client.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { decodeToolProxy } from "./shared/tool-proxy.js";
1
2
  import { pageDecisionSymbol } from "./shared/runtime-execution.js";
2
3
  import { createAgent, } from "@nexface/agent";
3
4
  import { decodeAgentResponse, } from "./protocol-response.js";
@@ -52,15 +53,16 @@ class ChatClientImplementation {
52
53
  #error;
53
54
  #listeners = new Set();
54
55
  #controller;
56
+ #stopRemote;
55
57
  #activeRun;
56
58
  #operation;
57
59
  #disposed = false;
58
60
  #state;
61
+ #appendOnly = false;
59
62
  #stateBeforeLastMessage;
60
- #resumeBeforeLastMessage;
63
+ #interruptBeforeLastMessage;
61
64
  #recoveryUnavailable = false;
62
- #remoteInterruptId;
63
- #cancelledResume;
65
+ #cancelledInterrupt;
64
66
  #task;
65
67
  #replacement;
66
68
  #approval;
@@ -89,6 +91,9 @@ class ChatClientImplementation {
89
91
  getStatus = () => this.#status;
90
92
  getApproval = () => this.#approval;
91
93
  getError = () => this.#error;
94
+ get recoveryUnavailable() {
95
+ return this.#recoveryUnavailable;
96
+ }
92
97
  assertRecoveryAvailable() {
93
98
  if (this.#recoveryUnavailable)
94
99
  throw new ClientError("CHAT_RECOVERY_UNAVAILABLE", "This chat cannot continue. Check the action results, then start a new chat.");
@@ -117,19 +122,23 @@ class ChatClientImplementation {
117
122
  }
118
123
  }
119
124
  get cancelling() {
120
- return Boolean(this.#controller?.signal.aborted);
125
+ return Boolean(this.#controller && this.#cancelled);
121
126
  }
122
127
  get busy() {
123
128
  return Boolean(this.#controller);
124
129
  }
130
+ get appendOnly() {
131
+ return this.#appendOnly;
132
+ }
125
133
  setPageResolver(resolver) {
126
134
  this.#hasPageHook = resolver;
127
135
  if (this.agent)
128
136
  agentController(this.agent).setPageConfirmationResolver(resolver);
129
137
  }
130
- restore(messages) {
138
+ restore(messages, appendOnly = false) {
131
139
  if (this.busy || this.#messages.length)
132
140
  throw new Error("Restore requires a new Client.");
141
+ this.#appendOnly = appendOnly;
133
142
  const restored = structuredClone(messages);
134
143
  const conversation = conversationFromMessages(restored);
135
144
  this.#messages = restoreMessages(restored, conversation);
@@ -137,6 +146,8 @@ class ChatClientImplementation {
137
146
  agentController(this.agent).restoreConversation(conversation);
138
147
  }
139
148
  recreateBefore(messageId) {
149
+ if (this.#appendOnly)
150
+ throw new ClientError("INVALID_INPUT", "Messages in this chat cannot be edited. Start a new chat.");
140
151
  if (this.busy || this.#disposed)
141
152
  throw new ClientError("CHAT_RUN_ACTIVE", "Wait for the active task to finish.");
142
153
  const index = this.#messages.findIndex((message) => message.role === "user" && message.id === messageId);
@@ -147,7 +158,7 @@ class ChatClientImplementation {
147
158
  client.setPageResolver(this.#hasPageHook);
148
159
  client.#messages = structuredClone(this.#messages.slice(0, index));
149
160
  client.#state = this.#stateBeforeLastMessage;
150
- client.#cancelledResume = this.#resumeBeforeLastMessage;
161
+ client.#cancelledInterrupt = this.#interruptBeforeLastMessage;
151
162
  if (this.agent) {
152
163
  const retained = agentController(this.agent).conversationBefore(messageId);
153
164
  agentController(client.agent).restoreConversation(retained.messages, retained.replay);
@@ -187,7 +198,7 @@ class ChatClientImplementation {
187
198
  let name = call?.function.name;
188
199
  if (name === "nxf_callAppTool")
189
200
  try {
190
- name = JSON.parse(call.function.arguments).name;
201
+ name = decodeToolProxy(JSON.parse(call.function.arguments)).name;
191
202
  }
192
203
  catch {
193
204
  /* Incomplete calls have no local diagnostic. */
@@ -284,6 +295,8 @@ class ChatClientImplementation {
284
295
  catch (error) {
285
296
  throw new ClientError("INVALID_INPUT", error instanceof Error ? error.message : "Invalid chat message.");
286
297
  }
298
+ if (this.#replacement)
299
+ throw new ClientError("CHAT_RUN_ACTIVE", "The Client is already running.");
287
300
  if (this.busy) {
288
301
  if (this.#status !== "waiting" || !this.#pending || !this.#task)
289
302
  throw new ClientError("CHAT_RUN_ACTIVE", "The Client is already running.");
@@ -347,7 +360,7 @@ class ChatClientImplementation {
347
360
  });
348
361
  }
349
362
  this.#stateBeforeLastMessage = this.#state;
350
- this.#resumeBeforeLastMessage = this.#cancelledResume;
363
+ this.#interruptBeforeLastMessage = this.#cancelledInterrupt;
351
364
  this.#controller = controller;
352
365
  this.#cancelled = false;
353
366
  this.#executingBrowserCall = undefined;
@@ -397,11 +410,14 @@ class ChatClientImplementation {
397
410
  this.#runtimeCauses.set(event.name, causes);
398
411
  });
399
412
  let succeeded = false;
413
+ const wasCancelled = () => controller.signal.aborted && !(controller.signal.reason instanceof ClientError);
400
414
  try {
401
415
  this.#publish();
402
416
  const result = initialRun
403
417
  ? await this.#local(initialRun, controller.signal)
404
418
  : await this.#remote(controller.signal);
419
+ if (this.#cancelled)
420
+ controller.abort(abortError());
405
421
  controller.signal.throwIfAborted();
406
422
  succeeded = true;
407
423
  return result;
@@ -423,7 +439,7 @@ class ChatClientImplementation {
423
439
  name: typeof record?.name === "string" ? record.name : "Error",
424
440
  ...(typeof record?.code === "string" ? { code: record.code } : {}),
425
441
  });
426
- const cancelled = controller.signal.aborted;
442
+ const cancelled = wasCancelled();
427
443
  const lastUser = this.#messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
428
444
  const current = this.#messages.slice(lastUser + 1);
429
445
  const unknownTools = projectMessages(current).some((message) => message.parts.some((part) => part.type === "tool" && part.toolState === "unknown"));
@@ -471,7 +487,7 @@ class ChatClientImplementation {
471
487
  this.#approval = undefined;
472
488
  if (this.#operation)
473
489
  await this.#operation.end({
474
- outcome: succeeded ? "completed" : controller.signal.aborted ? "cancelled" : "failed",
490
+ outcome: succeeded ? "completed" : wasCancelled() ? "cancelled" : "failed",
475
491
  });
476
492
  this.#operation = undefined;
477
493
  this.#activeRun = undefined;
@@ -479,7 +495,7 @@ class ChatClientImplementation {
479
495
  for (const settle of this.#settled.values())
480
496
  settle();
481
497
  this.#settled.clear();
482
- this.#status = succeeded || controller.signal.aborted ? "idle" : "error";
498
+ this.#status = succeeded || wasCancelled() ? "idle" : "error";
483
499
  this.#publish();
484
500
  }
485
501
  }
@@ -606,7 +622,6 @@ class ChatClientImplementation {
606
622
  if (this.agent) {
607
623
  agentController(this.agent).settle(approval.id, { type: "invalidate", message, reason: "binding_changed" }, this.#messages);
608
624
  }
609
- this.#queueRemoteCancellation();
610
625
  const pending = this.#pending;
611
626
  pending?.cleanup();
612
627
  this.#pending = undefined;
@@ -622,19 +637,19 @@ class ChatClientImplementation {
622
637
  this.#replacement.cancelled = true;
623
638
  this.#cancelCurrent();
624
639
  };
625
- #queueRemoteCancellation() {
626
- if (this.#remoteInterruptId)
627
- this.#cancelledResume = [{ interruptId: this.#remoteInterruptId, status: "cancelled" }];
628
- }
629
640
  #cancelCurrent() {
630
641
  if (!this.#controller || this.#cancelled)
631
642
  return;
632
643
  this.#cancelled = true;
644
+ if (this.#stopRemote && !this.#disposed) {
645
+ this.#stopRemote();
646
+ this.#publish();
647
+ return;
648
+ }
633
649
  if (this.#approval) {
634
650
  this.#messages = settleApproval(this.#messages, this.#approval, "TOOL_CANCELLED", "The pending Tool confirmation was cancelled.", "interrupt_cancelled");
635
651
  if (this.agent)
636
652
  agentController(this.agent).settle(this.#approval.id, { type: "cancel" }, this.#messages);
637
- this.#queueRemoteCancellation();
638
653
  }
639
654
  const pending = this.#pending;
640
655
  pending?.cleanup();
@@ -649,16 +664,23 @@ class ChatClientImplementation {
649
664
  if (this.#disposed)
650
665
  return;
651
666
  this.#disposed = true;
667
+ if (this.#stopRemote && this.#cancelled)
668
+ this.#controller?.abort(abortError());
652
669
  this.cancel();
653
670
  this.#listeners.clear();
654
671
  this.#eventListeners.clear();
655
672
  };
656
673
  async #remote(signal) {
657
- let resume = this.#cancelledResume;
674
+ const cancelled = this.#cancelledInterrupt;
675
+ let state = cancelled ? cancelled.state : this.#state;
676
+ let resume = cancelled
677
+ ? [{ interruptId: cancelled.id, status: "cancelled" }]
678
+ : undefined;
679
+ let interruptId;
658
680
  let inFlight = false;
659
681
  let completedBrowserCall = false;
660
- let uncommittedToolCall = false;
661
- let clientToolExecutionOnly = false;
682
+ let serverCannotWrite = false;
683
+ let stopTimeout;
662
684
  try {
663
685
  for (;;) {
664
686
  signal.throwIfAborted();
@@ -670,7 +692,7 @@ class ChatClientImplementation {
670
692
  threadId: this.id,
671
693
  runId,
672
694
  messages: this.#messages.filter((message) => !message.metadata?.nexface?.displayOnly),
673
- state: this.#state ?? null,
695
+ state: state ?? null,
674
696
  ...(resume ? { resume } : {}),
675
697
  tools: catalog.map(({ definition }) => ({
676
698
  name: definition.name,
@@ -692,9 +714,9 @@ class ChatClientImplementation {
692
714
  },
693
715
  };
694
716
  RunAgentInputSchema.parse(input);
695
- clientToolExecutionOnly = false;
717
+ serverCannotWrite = false;
696
718
  inFlight = true;
697
- this.#remoteInterruptId = undefined;
719
+ interruptId = undefined;
698
720
  const response = await abortable(this.#runHandler(input, { signal }), signal);
699
721
  if (!response.ok || !response.body)
700
722
  throw new ClientError("CHAT_REQUEST_FAILED", `Agent request failed (${response.status}).`);
@@ -704,12 +726,6 @@ class ChatClientImplementation {
704
726
  let stateSnapshot;
705
727
  let started = false;
706
728
  for await (const event of readEvents(response, signal)) {
707
- // A tool event may precede a server-side effect; text alone does not.
708
- if (event.type === EventType.TOOL_CALL_START ||
709
- event.type === EventType.TOOL_CALL_CHUNK ||
710
- event.type === EventType.TOOL_CALL_RESULT ||
711
- (event.type === EventType.CUSTOM && event.name === "nexface.tool-execution"))
712
- uncommittedToolCall = true;
713
729
  if (event.type === EventType.RUN_ERROR) {
714
730
  this.#event(event);
715
731
  throw new ClientError(event.code ?? "CHAT_RUN_ERROR", event.message);
@@ -722,7 +738,41 @@ class ChatClientImplementation {
722
738
  if (started)
723
739
  throw new Error("Duplicate Agent start event.");
724
740
  started = true;
725
- clientToolExecutionOnly = event.metadata?.nexface?.clientToolExecutionOnly === true;
741
+ if (event.metadata?.nexface?.appendOnly === true)
742
+ this.#appendOnly = true;
743
+ const capabilities = event.metadata?.nexface;
744
+ serverCannotWrite =
745
+ capabilities?.clientToolExecutionOnly === true ||
746
+ capabilities?.serverToolExecutionReadOnly === true;
747
+ if (capabilities?.cooperativeStop === true) {
748
+ const stop = () => {
749
+ const controller = this.#controller;
750
+ const fail = () => {
751
+ if (this.#stopRemote !== stop)
752
+ return;
753
+ controller.abort(new ClientError("CHAT_RECOVERY_UNAVAILABLE", "The remote stop could not be confirmed."));
754
+ };
755
+ stopTimeout = setTimeout(fail, 10_000);
756
+ void Promise.resolve()
757
+ .then(() => this.#runHandler({
758
+ threadId: input.threadId,
759
+ runId,
760
+ messages: [],
761
+ tools: [],
762
+ context: [],
763
+ state: null,
764
+ forwardedProps: { nexface: { stop: true } },
765
+ }, { signal }))
766
+ .then((response) => {
767
+ void response.body?.cancel().catch(() => undefined);
768
+ if (response.status >= 400 &&
769
+ response.status < 500 &&
770
+ response.status !== 404)
771
+ fail();
772
+ }, () => undefined);
773
+ };
774
+ this.#stopRemote = stop;
775
+ }
726
776
  }
727
777
  if (event.type === EventType.MESSAGES_SNAPSHOT) {
728
778
  if (messageSnapshot || stateSnapshot)
@@ -745,7 +795,8 @@ class ChatClientImplementation {
745
795
  }
746
796
  if (messageSnapshot)
747
797
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Unexpected event between recovery snapshots and terminal.");
748
- this.#event(event);
798
+ if (!this.#cancelled || !this.#stopRemote)
799
+ this.#event(event);
749
800
  }
750
801
  if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot)
751
802
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent stream ended without complete recovery snapshots.");
@@ -756,14 +807,40 @@ class ChatClientImplementation {
756
807
  catch (error) {
757
808
  throw new ClientError("CHAT_STREAM_INCOMPLETE", error instanceof Error ? error.message : "Invalid Agent recovery response.");
758
809
  }
810
+ const wireSnapshot = messageSnapshot;
759
811
  const commit = () => {
760
812
  // Only a complete terminal commits the matching messages and state.
761
- this.#state = structuredClone(stateSnapshot.snapshot);
762
- this.#cancelledResume = undefined;
813
+ state = structuredClone(stateSnapshot.snapshot);
814
+ if (decoded.type === "success")
815
+ this.#state = state;
816
+ this.#cancelledInterrupt = undefined;
763
817
  inFlight = false;
764
818
  completedBrowserCall = false;
765
- uncommittedToolCall = false;
766
- this.#event(messageSnapshot);
819
+ const stopping = this.#cancelled && this.#stopRemote;
820
+ this.#stopRemote = undefined;
821
+ let snapshot = wireSnapshot;
822
+ if (stopping && decoded.type === "success") {
823
+ // Keep the signed wire content while preserving the text shown before Stop.
824
+ const visible = new Map(this.#messages.map((message) => [message.id, message.content]));
825
+ snapshot = {
826
+ ...wireSnapshot,
827
+ messages: wireSnapshot.messages.map((message) => {
828
+ if (message.role !== "assistant" || visible.get(message.id) === message.content)
829
+ return message;
830
+ return {
831
+ ...message,
832
+ metadata: {
833
+ ...message.metadata,
834
+ nexface: {
835
+ ...message.metadata?.nexface,
836
+ stoppedText: visible.get(message.id) ?? "",
837
+ },
838
+ },
839
+ };
840
+ }),
841
+ };
842
+ }
843
+ this.#event(snapshot);
767
844
  this.#event(stateSnapshot);
768
845
  this.#event(terminalEvent);
769
846
  };
@@ -771,8 +848,10 @@ class ChatClientImplementation {
771
848
  commit();
772
849
  return decoded.result;
773
850
  }
774
- this.#remoteInterruptId = decoded.interruptId;
851
+ interruptId = decoded.interruptId;
775
852
  commit();
853
+ if (this.#cancelled && !signal.aborted)
854
+ throw new ClientError("CHAT_RECOVERY_UNAVAILABLE", "The remote run stopped at a pending tool call.");
776
855
  const toolResult = await this.#browserAction(decoded.action, catalog, signal);
777
856
  completedBrowserCall = true;
778
857
  const messageId = id();
@@ -796,15 +875,18 @@ class ChatClientImplementation {
796
875
  }
797
876
  }
798
877
  catch (error) {
799
- // Keep the last committed state and partial text for a new instruction.
800
- // Never resume a call whose effects have not reached a complete terminal.
801
- const unknown = (inFlight && (!signal.aborted || !clientToolExecutionOnly || uncommittedToolCall)) ||
878
+ const unknown = (inFlight && (!signal.aborted || !serverCannotWrite)) ||
802
879
  completedBrowserCall ||
803
880
  this.#executingBrowserCall !== undefined;
804
- if (unknown)
881
+ if (this.#appendOnly ? unknown || this.#cancelled : unknown && !signal.aborted) {
805
882
  this.#recoveryUnavailable = true;
806
- else
807
- this.#queueRemoteCancellation();
883
+ }
884
+ else if (unknown) {
885
+ this.#cancelledInterrupt = undefined;
886
+ }
887
+ else if (interruptId) {
888
+ this.#cancelledInterrupt = { state, id: interruptId };
889
+ }
808
890
  const lastUser = this.#messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
809
891
  const current = this.#messages.slice(lastUser);
810
892
  for (const [index, message] of current.entries())
@@ -833,8 +915,20 @@ class ChatClientImplementation {
833
915
  });
834
916
  }
835
917
  }
918
+ if (signal.aborted && unknown && !this.#appendOnly) {
919
+ this.#messages.push({
920
+ id: id(),
921
+ role: "assistant",
922
+ content: "The previous run was stopped and its execution outcome is unknown. Check the result before repeating any action.",
923
+ metadata: { nexface: { state: "cancelled" } },
924
+ });
925
+ }
836
926
  throw error;
837
927
  }
928
+ finally {
929
+ clearTimeout(stopTimeout);
930
+ this.#stopRemote = undefined;
931
+ }
838
932
  }
839
933
  async #browserAction(action, catalog, signal) {
840
934
  let confirmed = false;
package/dist/config.d.ts CHANGED
@@ -12,7 +12,7 @@ export type NexfaceModelConfig = (CompletionsOptions & {
12
12
  }) | (GoogleOptions & {
13
13
  protocol: "google-generative-ai";
14
14
  });
15
- export type NexfaceAgentConfig = Pick<Parameters<typeof createAgent>[0], "tools" | "skills" | "maxSteps" | "maxRetries" | "applicationContext"> & {
15
+ export type NexfaceAgentConfig = Pick<Parameters<typeof createAgent>[0], "tools" | "useToolProxy" | "skills" | "maxSteps" | "maxRetries" | "applicationContext"> & {
16
16
  model: NexfaceModelConfig;
17
17
  /**
18
18
  * @experimental Page decisions may change in future releases.
@@ -1,3 +1,3 @@
1
1
  import { type ReactElement } from "react";
2
2
  import type { ChatProps } from "./types.js";
3
- export declare function Chat({ title, avatar, welcomeMessage, welcomeDescription, open, onOpenChange, placeholder, layout, side, className, style, suggestions, suggestNextMessage, attachments, dictation, sessionSidebar, showToolDetails, onFullscreenChange, onRunResult, }: ChatProps): ReactElement | null;
3
+ export declare function Chat({ title, avatar, welcomeMessage, welcomeDescription, welcomeIcon, open, onOpenChange, placeholder, layout, side, className, style, suggestions, suggestNextMessage, attachments, dictation, sessionSidebar, showToolDetails, onFullscreenChange, onRunResult, }: ChatProps): ReactElement | null;