@nexface/chat 0.1.20-alpha.3 → 0.1.21-alpha.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.
@@ -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, }: {
@@ -24,7 +24,7 @@ export function AttachmentTile({ binding, savedPreview, }) {
24
24
  attachment.content?.find((part) => part.type === "image")?.image;
25
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] }) }));
26
26
  }
27
- export function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, cancel, }) {
27
+ export function AssistantComposer({ binding, options, placeholder, suggestion, busy, cancelling, recoveryUnavailable, cancel, }) {
28
28
  const input = useRef(null);
29
29
  const sending = binding.sending;
30
30
  const voiceBusy = binding.voice.status !== "idle";
@@ -37,6 +37,14 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
37
37
  const empty = useAuiState((state) => state.composer.text.length === 0);
38
38
  const nextMessage = !busy && !inputDisabled && empty ? suggestion : undefined;
39
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") }) }) }));
40
48
  const addFiles = (files) => {
41
49
  for (const file of files)
42
50
  void binding.runtime.thread.composer
@@ -45,7 +53,8 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
45
53
  };
46
54
  return (_jsxs(Composer, { onSubmit: (event) => {
47
55
  event.preventDefault();
48
- void binding.send();
56
+ if (!recoveryUnavailable)
57
+ void binding.send();
49
58
  }, inputProps: {
50
59
  "aria-label": "输入 Agent 任务",
51
60
  placeholder: nextMessage ?? placeholder,
@@ -68,7 +77,8 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
68
77
  }
69
78
  else if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
70
79
  event.preventDefault();
71
- void binding.send();
80
+ if (!recoveryUnavailable)
81
+ void binding.send();
72
82
  }
73
83
  },
74
84
  }, actions: _jsxs(_Fragment, { children: [voiceBusy ? (_jsx("span", { role: "status", className: cn("sr-only"), children: binding.voice.status === "starting"
@@ -78,10 +88,7 @@ export function AssistantComposer({ binding, options, placeholder, suggestion, b
78
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) => {
79
89
  addFiles(Array.from(event.target.files ?? []));
80
90
  event.target.value = "";
81
- } }), _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) => {
82
- event.preventDefault();
83
- void binding.send();
84
- }, "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) => {
85
92
  element?.toggleAttribute("inert", inputDisabled);
86
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] }));
87
94
  }
@@ -175,6 +175,7 @@ export function SessionRuntime({ id, chat, options, dictation, open = true, bloc
175
175
  setSending(true);
176
176
  setNotice("");
177
177
  try {
178
+ assertChatSendable(latest.current, id);
178
179
  // Prepare before dispatch: the upstream void send API cannot report upload
179
180
  // rejections to its caller. Keep the draft intact until every file settles.
180
181
  const results = await Promise.allSettled(draft.attachments.map((attachment) => attachments.send(attachment)));
package/dist/client.d.ts CHANGED
@@ -62,6 +62,7 @@ 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);
package/dist/client.js CHANGED
@@ -53,16 +53,16 @@ class ChatClientImplementation {
53
53
  #error;
54
54
  #listeners = new Set();
55
55
  #controller;
56
+ #stopRemote;
56
57
  #activeRun;
57
58
  #operation;
58
59
  #disposed = false;
59
60
  #state;
60
61
  #appendOnly = false;
61
62
  #stateBeforeLastMessage;
62
- #resumeBeforeLastMessage;
63
+ #interruptBeforeLastMessage;
63
64
  #recoveryUnavailable = false;
64
- #remoteInterruptId;
65
- #cancelledResume;
65
+ #cancelledInterrupt;
66
66
  #task;
67
67
  #replacement;
68
68
  #approval;
@@ -91,6 +91,9 @@ class ChatClientImplementation {
91
91
  getStatus = () => this.#status;
92
92
  getApproval = () => this.#approval;
93
93
  getError = () => this.#error;
94
+ get recoveryUnavailable() {
95
+ return this.#recoveryUnavailable;
96
+ }
94
97
  assertRecoveryAvailable() {
95
98
  if (this.#recoveryUnavailable)
96
99
  throw new ClientError("CHAT_RECOVERY_UNAVAILABLE", "This chat cannot continue. Check the action results, then start a new chat.");
@@ -119,7 +122,7 @@ class ChatClientImplementation {
119
122
  }
120
123
  }
121
124
  get cancelling() {
122
- return Boolean(this.#controller?.signal.aborted);
125
+ return Boolean(this.#controller && this.#cancelled);
123
126
  }
124
127
  get busy() {
125
128
  return Boolean(this.#controller);
@@ -155,7 +158,7 @@ class ChatClientImplementation {
155
158
  client.setPageResolver(this.#hasPageHook);
156
159
  client.#messages = structuredClone(this.#messages.slice(0, index));
157
160
  client.#state = this.#stateBeforeLastMessage;
158
- client.#cancelledResume = this.#resumeBeforeLastMessage;
161
+ client.#cancelledInterrupt = this.#interruptBeforeLastMessage;
159
162
  if (this.agent) {
160
163
  const retained = agentController(this.agent).conversationBefore(messageId);
161
164
  agentController(client.agent).restoreConversation(retained.messages, retained.replay);
@@ -357,7 +360,7 @@ class ChatClientImplementation {
357
360
  });
358
361
  }
359
362
  this.#stateBeforeLastMessage = this.#state;
360
- this.#resumeBeforeLastMessage = this.#cancelledResume;
363
+ this.#interruptBeforeLastMessage = this.#cancelledInterrupt;
361
364
  this.#controller = controller;
362
365
  this.#cancelled = false;
363
366
  this.#executingBrowserCall = undefined;
@@ -407,11 +410,14 @@ class ChatClientImplementation {
407
410
  this.#runtimeCauses.set(event.name, causes);
408
411
  });
409
412
  let succeeded = false;
413
+ const wasCancelled = () => controller.signal.aborted && !(controller.signal.reason instanceof ClientError);
410
414
  try {
411
415
  this.#publish();
412
416
  const result = initialRun
413
417
  ? await this.#local(initialRun, controller.signal)
414
418
  : await this.#remote(controller.signal);
419
+ if (this.#cancelled)
420
+ controller.abort(abortError());
415
421
  controller.signal.throwIfAborted();
416
422
  succeeded = true;
417
423
  return result;
@@ -433,7 +439,7 @@ class ChatClientImplementation {
433
439
  name: typeof record?.name === "string" ? record.name : "Error",
434
440
  ...(typeof record?.code === "string" ? { code: record.code } : {}),
435
441
  });
436
- const cancelled = controller.signal.aborted;
442
+ const cancelled = wasCancelled();
437
443
  const lastUser = this.#messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
438
444
  const current = this.#messages.slice(lastUser + 1);
439
445
  const unknownTools = projectMessages(current).some((message) => message.parts.some((part) => part.type === "tool" && part.toolState === "unknown"));
@@ -481,7 +487,7 @@ class ChatClientImplementation {
481
487
  this.#approval = undefined;
482
488
  if (this.#operation)
483
489
  await this.#operation.end({
484
- outcome: succeeded ? "completed" : controller.signal.aborted ? "cancelled" : "failed",
490
+ outcome: succeeded ? "completed" : wasCancelled() ? "cancelled" : "failed",
485
491
  });
486
492
  this.#operation = undefined;
487
493
  this.#activeRun = undefined;
@@ -489,7 +495,7 @@ class ChatClientImplementation {
489
495
  for (const settle of this.#settled.values())
490
496
  settle();
491
497
  this.#settled.clear();
492
- this.#status = succeeded || controller.signal.aborted ? "idle" : "error";
498
+ this.#status = succeeded || wasCancelled() ? "idle" : "error";
493
499
  this.#publish();
494
500
  }
495
501
  }
@@ -616,7 +622,6 @@ class ChatClientImplementation {
616
622
  if (this.agent) {
617
623
  agentController(this.agent).settle(approval.id, { type: "invalidate", message, reason: "binding_changed" }, this.#messages);
618
624
  }
619
- this.#queueRemoteCancellation();
620
625
  const pending = this.#pending;
621
626
  pending?.cleanup();
622
627
  this.#pending = undefined;
@@ -632,19 +637,19 @@ class ChatClientImplementation {
632
637
  this.#replacement.cancelled = true;
633
638
  this.#cancelCurrent();
634
639
  };
635
- #queueRemoteCancellation() {
636
- if (this.#remoteInterruptId)
637
- this.#cancelledResume = [{ interruptId: this.#remoteInterruptId, status: "cancelled" }];
638
- }
639
640
  #cancelCurrent() {
640
641
  if (!this.#controller || this.#cancelled)
641
642
  return;
642
643
  this.#cancelled = true;
644
+ if (this.#stopRemote && !this.#disposed) {
645
+ this.#stopRemote();
646
+ this.#publish();
647
+ return;
648
+ }
643
649
  if (this.#approval) {
644
650
  this.#messages = settleApproval(this.#messages, this.#approval, "TOOL_CANCELLED", "The pending Tool confirmation was cancelled.", "interrupt_cancelled");
645
651
  if (this.agent)
646
652
  agentController(this.agent).settle(this.#approval.id, { type: "cancel" }, this.#messages);
647
- this.#queueRemoteCancellation();
648
653
  }
649
654
  const pending = this.#pending;
650
655
  pending?.cleanup();
@@ -659,16 +664,23 @@ class ChatClientImplementation {
659
664
  if (this.#disposed)
660
665
  return;
661
666
  this.#disposed = true;
667
+ if (this.#stopRemote && this.#cancelled)
668
+ this.#controller?.abort(abortError());
662
669
  this.cancel();
663
670
  this.#listeners.clear();
664
671
  this.#eventListeners.clear();
665
672
  };
666
673
  async #remote(signal) {
667
- 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;
668
680
  let inFlight = false;
669
681
  let completedBrowserCall = false;
670
- let uncommittedToolCall = false;
671
- let clientToolExecutionOnly = false;
682
+ let serverCannotWrite = false;
683
+ let stopTimeout;
672
684
  try {
673
685
  for (;;) {
674
686
  signal.throwIfAborted();
@@ -680,7 +692,7 @@ class ChatClientImplementation {
680
692
  threadId: this.id,
681
693
  runId,
682
694
  messages: this.#messages.filter((message) => !message.metadata?.nexface?.displayOnly),
683
- state: this.#state ?? null,
695
+ state: state ?? null,
684
696
  ...(resume ? { resume } : {}),
685
697
  tools: catalog.map(({ definition }) => ({
686
698
  name: definition.name,
@@ -702,9 +714,9 @@ class ChatClientImplementation {
702
714
  },
703
715
  };
704
716
  RunAgentInputSchema.parse(input);
705
- clientToolExecutionOnly = false;
717
+ serverCannotWrite = false;
706
718
  inFlight = true;
707
- this.#remoteInterruptId = undefined;
719
+ interruptId = undefined;
708
720
  const response = await abortable(this.#runHandler(input, { signal }), signal);
709
721
  if (!response.ok || !response.body)
710
722
  throw new ClientError("CHAT_REQUEST_FAILED", `Agent request failed (${response.status}).`);
@@ -714,12 +726,6 @@ class ChatClientImplementation {
714
726
  let stateSnapshot;
715
727
  let started = false;
716
728
  for await (const event of readEvents(response, signal)) {
717
- // A tool event may precede a server-side effect; text alone does not.
718
- if (event.type === EventType.TOOL_CALL_START ||
719
- event.type === EventType.TOOL_CALL_CHUNK ||
720
- event.type === EventType.TOOL_CALL_RESULT ||
721
- (event.type === EventType.CUSTOM && event.name === "nexface.tool-execution"))
722
- uncommittedToolCall = true;
723
729
  if (event.type === EventType.RUN_ERROR) {
724
730
  this.#event(event);
725
731
  throw new ClientError(event.code ?? "CHAT_RUN_ERROR", event.message);
@@ -734,7 +740,39 @@ class ChatClientImplementation {
734
740
  started = true;
735
741
  if (event.metadata?.nexface?.appendOnly === true)
736
742
  this.#appendOnly = true;
737
- clientToolExecutionOnly = event.metadata?.nexface?.clientToolExecutionOnly === 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
+ }
738
776
  }
739
777
  if (event.type === EventType.MESSAGES_SNAPSHOT) {
740
778
  if (messageSnapshot || stateSnapshot)
@@ -757,7 +795,8 @@ class ChatClientImplementation {
757
795
  }
758
796
  if (messageSnapshot)
759
797
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Unexpected event between recovery snapshots and terminal.");
760
- this.#event(event);
798
+ if (!this.#cancelled || !this.#stopRemote)
799
+ this.#event(event);
761
800
  }
762
801
  if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot)
763
802
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent stream ended without complete recovery snapshots.");
@@ -768,14 +807,40 @@ class ChatClientImplementation {
768
807
  catch (error) {
769
808
  throw new ClientError("CHAT_STREAM_INCOMPLETE", error instanceof Error ? error.message : "Invalid Agent recovery response.");
770
809
  }
810
+ const wireSnapshot = messageSnapshot;
771
811
  const commit = () => {
772
812
  // Only a complete terminal commits the matching messages and state.
773
- this.#state = structuredClone(stateSnapshot.snapshot);
774
- this.#cancelledResume = undefined;
813
+ state = structuredClone(stateSnapshot.snapshot);
814
+ if (decoded.type === "success")
815
+ this.#state = state;
816
+ this.#cancelledInterrupt = undefined;
775
817
  inFlight = false;
776
818
  completedBrowserCall = false;
777
- uncommittedToolCall = false;
778
- 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);
779
844
  this.#event(stateSnapshot);
780
845
  this.#event(terminalEvent);
781
846
  };
@@ -783,8 +848,10 @@ class ChatClientImplementation {
783
848
  commit();
784
849
  return decoded.result;
785
850
  }
786
- this.#remoteInterruptId = decoded.interruptId;
851
+ interruptId = decoded.interruptId;
787
852
  commit();
853
+ if (this.#cancelled && !signal.aborted)
854
+ throw new ClientError("CHAT_RECOVERY_UNAVAILABLE", "The remote run stopped at a pending tool call.");
788
855
  const toolResult = await this.#browserAction(decoded.action, catalog, signal);
789
856
  completedBrowserCall = true;
790
857
  const messageId = id();
@@ -808,15 +875,18 @@ class ChatClientImplementation {
808
875
  }
809
876
  }
810
877
  catch (error) {
811
- // Keep the last committed state and partial text for a new instruction.
812
- // Never resume a call whose effects have not reached a complete terminal.
813
- const unknown = (inFlight && (!signal.aborted || !clientToolExecutionOnly || uncommittedToolCall)) ||
878
+ const unknown = (inFlight && (!signal.aborted || !serverCannotWrite)) ||
814
879
  completedBrowserCall ||
815
880
  this.#executingBrowserCall !== undefined;
816
- if (unknown || (this.#appendOnly && signal.aborted))
881
+ if (this.#appendOnly ? unknown || this.#cancelled : unknown && !signal.aborted) {
817
882
  this.#recoveryUnavailable = true;
818
- else
819
- this.#queueRemoteCancellation();
883
+ }
884
+ else if (unknown) {
885
+ this.#cancelledInterrupt = undefined;
886
+ }
887
+ else if (interruptId) {
888
+ this.#cancelledInterrupt = { state, id: interruptId };
889
+ }
820
890
  const lastUser = this.#messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
821
891
  const current = this.#messages.slice(lastUser);
822
892
  for (const [index, message] of current.entries())
@@ -845,8 +915,20 @@ class ChatClientImplementation {
845
915
  });
846
916
  }
847
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
+ }
848
926
  throw error;
849
927
  }
928
+ finally {
929
+ clearTimeout(stopTimeout);
930
+ this.#stopRemote = undefined;
931
+ }
850
932
  }
851
933
  async #browserAction(action, catalog, signal) {
852
934
  let confirmed = false;
@@ -29280,7 +29280,7 @@ function Greeting({
29280
29280
 
29281
29281
  // src/ui/home-demo/suggestions.tsx
29282
29282
  import { jsx as jsx72, jsxs as jsxs15 } from "react/jsx-runtime";
29283
- var suggestionChipClass = "bg-background text-suggestion hover:text-foreground font-suggestion inset-ring inset-ring-foreground/8 hover:inset-ring-foreground/25 rounded-xl inline-flex min-h-[46px] min-w-0 max-w-full items-center gap-2 px-4 py-3 text-sm font-medium leading-[1.57143] transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
29283
+ var suggestionChipClass = "bg-background text-suggestion hover:text-foreground font-suggestion inset-ring inset-ring-black/8 dark:inset-ring-foreground/8 hover:inset-ring-foreground/25 rounded-lg inline-flex min-h-[32px] min-w-0 max-w-full items-center gap-2 px-3 py-[5px] text-sm font-medium leading-[1.57143] transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
29284
29284
  function Suggestions2({
29285
29285
  suggestions,
29286
29286
  disabled,
@@ -30233,6 +30233,7 @@ function SessionRuntime({
30233
30233
  setSending(true);
30234
30234
  setNotice("");
30235
30235
  try {
30236
+ assertChatSendable(latest.current, id);
30236
30237
  const results = await Promise.allSettled(
30237
30238
  draft.attachments.map((attachment) => attachments.send(attachment))
30238
30239
  );
@@ -46732,6 +46733,7 @@ function AssistantComposer({
46732
46733
  suggestion,
46733
46734
  busy,
46734
46735
  cancelling,
46736
+ recoveryUnavailable,
46735
46737
  cancel
46736
46738
  }) {
46737
46739
  const input = useRef38(null);
@@ -46744,6 +46746,23 @@ function AssistantComposer({
46744
46746
  const showCancel = useAuiState(
46745
46747
  (state) => busy && (state.thread.isRunning || state.composer.isEmpty)
46746
46748
  );
46749
+ const recoveryReason = recoveryUnavailable ? "This chat cannot continue because its recovery state is unavailable." : void 0;
46750
+ const sendButton = /* @__PURE__ */ jsx99(ComposerPrimitiveSend, { asChild: true, disabled: inputDisabled || recoveryUnavailable, children: /* @__PURE__ */ jsx99(
46751
+ "button",
46752
+ {
46753
+ type: "button",
46754
+ onClick: (event) => {
46755
+ event.preventDefault();
46756
+ if (!recoveryUnavailable) void binding.send();
46757
+ },
46758
+ "aria-label": "\u53D1\u9001\u4EFB\u52A1",
46759
+ "aria-description": recoveryReason,
46760
+ className: cn(
46761
+ "bg-primary text-primary-foreground rounded-control grid size-7 place-items-center transition-opacity disabled:pointer-events-none disabled:opacity-40"
46762
+ ),
46763
+ children: /* @__PURE__ */ jsx99(ArrowUp, { className: cn("size-4") })
46764
+ }
46765
+ ) });
46747
46766
  const addFiles = (files) => {
46748
46767
  for (const file of files)
46749
46768
  void binding.runtime.thread.composer.addAttachment(file).catch(
@@ -46755,7 +46774,7 @@ function AssistantComposer({
46755
46774
  {
46756
46775
  onSubmit: (event) => {
46757
46776
  event.preventDefault();
46758
- void binding.send();
46777
+ if (!recoveryUnavailable) void binding.send();
46759
46778
  },
46760
46779
  inputProps: {
46761
46780
  "aria-label": "\u8F93\u5165 Agent \u4EFB\u52A1",
@@ -46770,7 +46789,7 @@ function AssistantComposer({
46770
46789
  binding.runtime.thread.composer.setText(nextMessage);
46771
46790
  } else if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
46772
46791
  event.preventDefault();
46773
- void binding.send();
46792
+ if (!recoveryUnavailable) void binding.send();
46774
46793
  }
46775
46794
  }
46776
46795
  },
@@ -46872,21 +46891,10 @@ function AssistantComposer({
46872
46891
  onClick: cancel,
46873
46892
  children: /* @__PURE__ */ jsx99(Square, { className: cn("size-3 fill-current") })
46874
46893
  }
46875
- ) : /* @__PURE__ */ jsx99(ComposerPrimitiveSend, { asChild: true, disabled: inputDisabled, children: /* @__PURE__ */ jsx99(
46876
- "button",
46877
- {
46878
- type: "button",
46879
- onClick: (event) => {
46880
- event.preventDefault();
46881
- void binding.send();
46882
- },
46883
- "aria-label": "\u53D1\u9001\u4EFB\u52A1",
46884
- className: cn(
46885
- "bg-primary text-primary-foreground rounded-control grid size-7 place-items-center transition-opacity disabled:opacity-40"
46886
- ),
46887
- children: /* @__PURE__ */ jsx99(ArrowUp, { className: cn("size-4") })
46888
- }
46889
- ) })
46894
+ ) : recoveryReason ? /* @__PURE__ */ jsx99(TooltipProvider2, { delayDuration: 0, children: /* @__PURE__ */ jsxs31(Tooltip2, { children: [
46895
+ /* @__PURE__ */ jsx99(TooltipTrigger3, { asChild: true, children: /* @__PURE__ */ jsx99("span", { className: cn("inline-flex"), tabIndex: 0, "aria-label": recoveryReason, children: sendButton }) }),
46896
+ /* @__PURE__ */ jsx99(TooltipContent3, { children: recoveryReason })
46897
+ ] }) }) : sendButton
46890
46898
  ] })
46891
46899
  ] }),
46892
46900
  children: [
@@ -47020,7 +47028,7 @@ function AssistantParts({
47020
47028
  }
47021
47029
 
47022
47030
  // src/default-chat.tsx
47023
- import { canEditChatSession, useChat as useChat3 } from "./react.js";
47031
+ import { canEditChatSession, isChatRecoveryUnavailable, useChat as useChat3 } from "./react.js";
47024
47032
  import { sendErrorNotice } from "./errors.js";
47025
47033
  import { Fragment as Fragment18, jsx as jsx100, jsxs as jsxs32 } from "react/jsx-runtime";
47026
47034
  var textOf = (message) => message.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
@@ -47580,6 +47588,7 @@ function Chat({
47580
47588
  suggestion: nextMessage,
47581
47589
  busy: busy || Boolean(interrupt),
47582
47590
  cancelling: status === "cancelling",
47591
+ recoveryUnavailable: isChatRecoveryUnavailable(chat),
47583
47592
  cancel: chat.cancel
47584
47593
  }
47585
47594
  ),
@@ -350,14 +350,16 @@ export function projectMessages(messages) {
350
350
  if (message.role === "reasoning" && assistantIds.has(metadata?.reasoningOwnerId))
351
351
  return [];
352
352
  const parts = [];
353
- const text = typeof metadata?.reasoningText === "string"
354
- ? metadata.reasoningText
355
- : typeof message.content === "string"
356
- ? message.content
357
- : (message.content ?? [])
358
- .filter((part) => part.type === "text")
359
- .map((part) => part.text)
360
- .join("");
353
+ const text = typeof metadata?.stoppedText === "string"
354
+ ? metadata.stoppedText
355
+ : typeof metadata?.reasoningText === "string"
356
+ ? metadata.reasoningText
357
+ : typeof message.content === "string"
358
+ ? message.content
359
+ : (message.content ?? [])
360
+ .filter((part) => part.type === "text")
361
+ .map((part) => part.text)
362
+ .join("");
361
363
  const reasoning = ownedReasoning.get(message.id) ?? [];
362
364
  let offset = 0;
363
365
  for (const entry of reasoning) {
@@ -377,6 +379,7 @@ export function projectMessages(messages) {
377
379
  if (message.role === "reasoning" && !text)
378
380
  return [];
379
381
  if (typeof metadata?.reasoningText === "string" &&
382
+ typeof metadata?.stoppedText !== "string" &&
380
383
  typeof message.content === "string" &&
381
384
  message.content !== text) {
382
385
  parts.push({ type: "text", text: message.content });
package/dist/react.d.ts CHANGED
@@ -60,6 +60,7 @@ export type NexfaceProviderProps = {
60
60
  }) => Promise<Response>;
61
61
  agent?: never;
62
62
  });
63
+ export declare function isChatRecoveryUnavailable(chat: UseChatResult): boolean;
63
64
  export declare function canEditChatSession(chat: UseChatResult, sessionId: string): boolean;
64
65
  export declare function assertChatSendable(chat: UseChatResult, sessionId: string): void;
65
66
  export declare function useToolPresentations(): {
package/dist/react.js CHANGED
@@ -18,6 +18,10 @@ export function isChatError(error) {
18
18
  }
19
19
  const sendGuards = new WeakMap();
20
20
  const appendOnlySessions = new WeakMap();
21
+ const chatsWithoutRecovery = new WeakSet();
22
+ export function isChatRecoveryUnavailable(chat) {
23
+ return chatsWithoutRecovery.has(chat);
24
+ }
21
25
  export function canEditChatSession(chat, sessionId) {
22
26
  return !appendOnlySessions.get(chat)?.has(sessionId);
23
27
  }
@@ -454,6 +458,8 @@ export function NexfaceProvider(props) {
454
458
  }
455
459
  },
456
460
  };
461
+ if (controller.recoveryUnavailable)
462
+ chatsWithoutRecovery.add(value);
457
463
  appendOnlySessions.set(value, new Set(store.sessions
458
464
  .filter(({ client }) => getClientController(client).appendOnly)
459
465
  .map(({ id }) => id)));
package/dist/styles.css CHANGED
@@ -887,8 +887,8 @@
887
887
  min-height: calc(var(--nxf-spacing) * 12);
888
888
  }
889
889
 
890
- .nexface-ui .nxf-min-h-\[46px\] {
891
- min-height: 46px;
890
+ .nexface-ui .nxf-min-h-\[32px\] {
891
+ min-height: 32px;
892
892
  }
893
893
 
894
894
  .nexface-ui .nxf-w-0\.5 {
@@ -1200,10 +1200,6 @@
1200
1200
  border-radius: 1rem;
1201
1201
  }
1202
1202
 
1203
- .nexface-ui .nxf-rounded-xl {
1204
- border-radius: var(--nxf-radius-xl);
1205
- }
1206
-
1207
1203
  .nexface-ui .nxf-rounded-xs {
1208
1204
  border-radius: var(--nxf-radius-xs);
1209
1205
  }
@@ -1561,6 +1557,10 @@
1561
1557
  padding-block: calc(var(--nxf-spacing) * 4);
1562
1558
  }
1563
1559
 
1560
+ .nexface-ui .nxf-py-\[5px\] {
1561
+ padding-block: 5px;
1562
+ }
1563
+
1564
1564
  .nexface-ui .nxf-ps-0 {
1565
1565
  padding-inline-start: 0;
1566
1566
  }
@@ -1892,13 +1892,13 @@
1892
1892
  box-shadow: var(--nxf-tw-inset-shadow), var(--nxf-tw-inset-ring-shadow), var(--nxf-tw-ring-offset-shadow), var(--nxf-tw-ring-shadow), var(--nxf-tw-shadow);
1893
1893
  }
1894
1894
 
1895
- .nexface-ui .nxf-inset-ring-foreground\/8 {
1896
- --nxf-tw-inset-ring-color: var(--nxf-foreground);
1895
+ .nexface-ui .nxf-inset-ring-black\/8 {
1896
+ --nxf-tw-inset-ring-color: #00000014;
1897
1897
  }
1898
1898
 
1899
1899
  @supports (color: color-mix(in lab, red, red)) {
1900
- .nexface-ui .nxf-inset-ring-foreground\/8 {
1901
- --nxf-tw-inset-ring-color: color-mix(in oklab, var(--nxf-foreground) 8%, transparent);
1900
+ .nexface-ui .nxf-inset-ring-black\/8 {
1901
+ --nxf-tw-inset-ring-color: color-mix(in oklab, var(--nxf-color-black) 8%, transparent);
1902
1902
  }
1903
1903
  }
1904
1904
 
@@ -2848,6 +2848,16 @@
2848
2848
  }
2849
2849
  }
2850
2850
 
2851
+ .nexface-ui .nxf-dark\:inset-ring-foreground\/8:where(.nexface-dark, .nexface-dark *) {
2852
+ --nxf-tw-inset-ring-color: var(--nxf-foreground);
2853
+ }
2854
+
2855
+ @supports (color: color-mix(in lab, red, red)) {
2856
+ .nexface-ui .nxf-dark\:inset-ring-foreground\/8:where(.nexface-dark, .nexface-dark *) {
2857
+ --nxf-tw-inset-ring-color: color-mix(in oklab, var(--nxf-foreground) 8%, transparent);
2858
+ }
2859
+ }
2860
+
2851
2861
  .nexface-ui .nxf-dark\:after\:ring-destructive\/60:where(.nexface-dark, .nexface-dark *):after {
2852
2862
  content: var(--nxf-tw-content);
2853
2863
  --nxf-tw-ring-color: oklab(57.7% .217662 .112464 / .6);
@@ -3,7 +3,8 @@
3
3
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
4
4
  import { ThreadPrimitive, useAuiState } from "@assistant-ui/react";
5
5
  import { cn } from "../utils.js";
6
- const suggestionChipClass = "bg-background text-suggestion hover:text-foreground font-suggestion inset-ring inset-ring-foreground/8 hover:inset-ring-foreground/25 rounded-xl inline-flex min-h-[46px] min-w-0 max-w-full items-center gap-2 px-4 py-3 text-sm font-medium leading-[1.57143] transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
6
+ // Keep the 32px design height without trimming CJK glyphs; wrapped or enlarged labels can grow.
7
+ const suggestionChipClass = "bg-background text-suggestion hover:text-foreground font-suggestion inset-ring inset-ring-black/8 dark:inset-ring-foreground/8 hover:inset-ring-foreground/25 rounded-lg inline-flex min-h-[32px] min-w-0 max-w-full items-center gap-2 px-3 py-[5px] text-sm font-medium leading-[1.57143] transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
7
8
  export function Suggestions({ suggestions, disabled, onSend, }) {
8
9
  const isComposerEmpty = useAuiState((s) => s.composer.isEmpty);
9
10
  const hidden = !isComposerEmpty || disabled;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexface/chat",
3
- "version": "0.1.20-alpha.3",
3
+ "version": "0.1.21-alpha.0",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "sideEffects": [
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@ag-ui/core": "0.0.59",
22
- "@nexface/agent": "0.1.20-alpha.3",
22
+ "@nexface/agent": "0.1.21-alpha.0",
23
23
  "class-variance-authority": "0.7.1",
24
24
  "clsx": "2.1.1",
25
25
  "fast-json-patch": "3.1.1",
@@ -28,7 +28,7 @@
28
28
  "use-sync-external-store": "1.7.0"
29
29
  },
30
30
  "peerDependencies": {
31
- "@nexface/tools": "0.1.20-alpha.3",
31
+ "@nexface/tools": "0.1.21-alpha.0",
32
32
  "react": ">=17",
33
33
  "react-dom": ">=17"
34
34
  },