@jskit-ai/assistant-core 0.2.2 → 0.2.3

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 (59) hide show
  1. package/examples/conversation/package.json +5 -5
  2. package/fixtures/responsive-assistant/ConversationFixture.vue +2 -2
  3. package/fixtures/responsive-assistant/DeliveryFixture.vue +15 -2
  4. package/locales/en.json +4 -2
  5. package/package.json +5 -5
  6. package/src/client/conversation/AssistantConversationElement.vue +8 -1
  7. package/src/client/conversation/AssistantGoalControl.vue +2 -2
  8. package/src/client/conversation/AssistantTranscript.vue +41 -11
  9. package/src/client/conversation/messageDelivery.js +23 -6
  10. package/src/client/lib/assistantApi.js +5 -0
  11. package/src/server/conversation/claudeProcess.js +105 -58
  12. package/src/server/conversation/claudeTurn.js +179 -59
  13. package/src/server/conversation/codexAuthPreflight.js +3 -0
  14. package/src/server/conversation/codexConfiguration.js +42 -4
  15. package/src/server/conversation/codexConversations.js +256 -114
  16. package/src/server/conversation/codexEvents.js +16 -3
  17. package/src/server/conversation/codexHelperThreadRecovery.js +17 -4
  18. package/src/server/conversation/codexHelperThreads.js +10 -1
  19. package/src/server/conversation/codexHomeStorage.js +69 -0
  20. package/src/server/conversation/codexProcess.js +7 -2
  21. package/src/server/conversation/codexProvider.js +57 -46
  22. package/src/server/conversation/codexProviderOwner.js +234 -29
  23. package/src/server/conversation/codexProviderSelection.js +13 -3
  24. package/src/server/conversation/codexRuntimeLifecycle.js +56 -4
  25. package/src/server/conversation/codexSessionCleanup.js +67 -20
  26. package/src/server/conversation/codexSessionReconciliation.js +18 -4
  27. package/src/server/conversation/codexTurn.js +9 -2
  28. package/src/server/conversation/continuity.js +13 -1
  29. package/src/server/conversation/openCodeClient.js +34 -0
  30. package/src/server/conversation/openCodeProcess.js +37 -5
  31. package/src/server/conversation/openCodeRuntime.js +225 -64
  32. package/src/server/conversation/providers/claudeDriver.js +3 -3
  33. package/src/server/conversation/providers/codexDriver.js +10 -4
  34. package/src/server/conversation/providers/opencodeDriver.js +4 -2
  35. package/src/server/conversation/runtime.js +72 -2
  36. package/src/server/hosts/codexConfiguration.js +4 -0
  37. package/test/assistantScroll.browser.test.js +93 -0
  38. package/test/claudeLifecycle.test.js +293 -0
  39. package/test/claudeProcess.test.js +195 -51
  40. package/test/claudeTurn.test.js +174 -3
  41. package/test/codexAccountChange.test.js +261 -0
  42. package/test/codexConversationsCheckpoint.test.js +3 -0
  43. package/test/codexEvents.test.js +23 -1
  44. package/test/codexHomeStorage.test.js +57 -0
  45. package/test/codexInteractiveArguments.test.js +9 -0
  46. package/test/codexLifecycleIsolation.test.js +441 -0
  47. package/test/codexModelCatalog.test.js +48 -2
  48. package/test/codexProcess.test.js +21 -0
  49. package/test/codexTemporaryProviderRelease.test.js +180 -0
  50. package/test/codexTurn.test.js +21 -1
  51. package/test/conversationNativeStorage.test.js +57 -0
  52. package/test/conversationRuntime.test.js +66 -0
  53. package/test/conversationSession.test.js +4 -8
  54. package/test/messageDelivery.browser.test.js +18 -2
  55. package/test/messageDelivery.test.js +34 -1
  56. package/test/openCodeClient.test.js +31 -0
  57. package/test/openCodeConnectionChange.test.js +166 -0
  58. package/test/openCodeProcess.test.js +36 -0
  59. package/test/openCodeRuntime.test.js +25 -78
@@ -8,14 +8,14 @@
8
8
  "build": "vite build"
9
9
  },
10
10
  "dependencies": {
11
- "@jskit-ai/assistant-core": "0.2.2",
12
- "@jskit-ai/http-runtime": "0.2.0",
13
- "@jskit-ai/kernel": "0.2.0",
11
+ "@jskit-ai/assistant-core": "0.2.3",
12
+ "@jskit-ai/http-runtime": "0.2.1",
13
+ "@jskit-ai/kernel": "0.2.1",
14
14
  "@mdi/js": "^7.4.47",
15
15
  "vue": "^3.5.13",
16
16
  "vuetify": "^4.0.0",
17
- "@jskit-ai/connectors-core": "0.2.0",
18
- "@jskit-ai/connectors-catalog": "0.2.0"
17
+ "@jskit-ai/connectors-core": "0.2.1",
18
+ "@jskit-ai/connectors-catalog": "0.2.1"
19
19
  },
20
20
  "devDependencies": {
21
21
  "@vitejs/plugin-vue": "^6.0.7",
@@ -111,12 +111,12 @@ const adapter = reactive({
111
111
  discard(id) {
112
112
  if (id !== "temporary" || !previewCanTake.value) return;
113
113
  temporaryPresent.value = false;
114
- if (previewDelivery.find(id)?.status === "failed") previewDelivery.cancel(id);
114
+ if (previewDelivery.find(id)?.status === "failed") previewDelivery.remove(id);
115
115
  },
116
116
  edit(id) {
117
117
  if (id !== "temporary" || !previewCanTake.value) return;
118
118
  temporaryEditing.value = true;
119
- if (previewDelivery.find(id)?.status === "failed") previewDelivery.cancel(id);
119
+ if (previewDelivery.find(id)?.status === "failed") previewDelivery.remove(id);
120
120
  },
121
121
  update(id, text) {
122
122
  if (id === "temporary" && previewCanTake.value) temporaryWords.value = text;
@@ -25,6 +25,16 @@ const delivery = createAssistantMessageDelivery({ deliver(payload) {
25
25
  pendingRequest = Promise.withResolvers();
26
26
  return pendingRequest.promise;
27
27
  } });
28
+ // A stand-in for the application's server cancel: the recovery fixture answers
29
+ // from its buttons, the others agree at once.
30
+ let cancelAnswer;
31
+ function cancelMessage(id) {
32
+ if (!delivery.cancel(id)) return false;
33
+ cancelAnswer = Promise.withResolvers();
34
+ cancelAnswer.promise.then(agreed => agreed ? delivery.remove(id) : delivery.cancelFailed(id));
35
+ if (!recoveryFixture) cancelAnswer.resolve(true);
36
+ return true;
37
+ }
28
38
  function accept() {
29
39
  const payload = requests.value.at(-1);
30
40
  const at = new Date().toISOString();
@@ -56,8 +66,8 @@ const adapter = reactive({
56
66
  conversation: { cancellableDelivery: recoveryFixture, turns, visible: true, scrollKey: "delivery", welcomeMessage: "Start a conversation." },
57
67
  composer: { draft, canSend: true, submitOnEnter: true, queueWhileSending },
58
68
  actions: {
59
- ...(recoveryFixture ? { cancel: id => delivery.remove(id) } : {}),
60
- setDraft(value) { draft.value = value; }
69
+ setDraft(value) { draft.value = value; },
70
+ cancel: cancelMessage
61
71
  }
62
72
  });
63
73
  </script>
@@ -66,6 +76,9 @@ const adapter = reactive({
66
76
  <main class="fixture">
67
77
  <nav>
68
78
  <button v-if="acceptedFixture" @click="turns.unshift({ turnId: 'earlier', user: { messageId: 'accepted-old', text: 'Earlier accepted message', at: '2026-10-16T11:05:00.000Z' } })">Load accepted history</button>
79
+ <button v-if="recoveryFixture" @click="delivery.find('uncertain').checking = true">Start delivery check</button>
80
+ <button v-if="recoveryFixture" @click="cancelAnswer?.resolve(false)">Server unreachable</button>
81
+ <button v-if="recoveryFixture" @click="cancelAnswer?.resolve(true)">Server agrees to cancel</button>
69
82
  <button @click="pendingRequest.reject(new Error('Delivery unavailable.'))">Fail request</button>
70
83
  <button @click="accept">Accept request</button>
71
84
  <button @click="attachments.attachments.push({ attachmentId: 'new-file', fileName: 'next.txt' }); configuration = { tone: 'detailed' }">Prepare newer input</button>
package/locales/en.json CHANGED
@@ -87,6 +87,8 @@
87
87
  "useSuggestion": "Use suggestion: {prompt}"
88
88
  },
89
89
  "delivery": {
90
+ "cancelling": "Cancelling…",
91
+ "cancelUnreachable": "Couldn't reach the server — Cancel again",
90
92
  "checkBeforeResend": "Check delivery before resending.",
91
93
  "checkPrevious": "Check the previous message's delivery before sending again.",
92
94
  "checking": "Checking…",
@@ -213,6 +215,8 @@
213
215
  "liveSettingsUnsupported": "This provider does not support live native settings.",
214
216
  "completedEnvelopesNeedStorage": "Completed envelopes require runtime-owned canonical storage.",
215
217
  "originalReadOnly": "This conversation uses its original read and subscription operations.",
218
+ "messageCancelUnsupported": "This conversation cannot cancel one message.",
219
+ "messageCancelled": "This message was cancelled. Send it again as a new message.",
216
220
  "authorizedSelectionRequired": "Use the conversation's authorized selection operation.",
217
221
  "eventDeliveryRetained": "This scoped conversation retains its original event delivery.",
218
222
  "engineChanged": "The selected native engine changed.",
@@ -371,8 +375,6 @@
371
375
  "conversation_receipt_unavailable": "The native receipt has no stored authored message.",
372
376
  "conversation_goal_unavailable": "The native goal is unavailable. Try reading its status again.",
373
377
  "assistant_provider_invalid_response": "Assistant provider returned an invalid response payload.",
374
- "assistant_opencode_connection_changing": "OpenCode is changing a connection. Retry after the connection change finishes.",
375
- "assistant_opencode_connection_in_use": "Close the other OpenCode conversations that use this connection, then retry this connection change. The saved connection has not changed.",
376
378
  "assistant_opencode_conversation_busy": "This conversation is still working.",
377
379
  "assistant_opencode_key_verification_failed": "OpenCode rejected the API-key verification request.",
378
380
  "assistant_opencode_turn_thread_mismatch": "The OpenCode predecessor history changed before handover generation.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/assistant-core",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1"
@@ -48,8 +48,8 @@
48
48
  "@ai-sdk/perplexity": "^4.0.43",
49
49
  "@ai-sdk/togetherai": "^3.0.49",
50
50
  "@ai-sdk/xai": "^4.0.58",
51
- "@jskit-ai/resource-core": "0.1.191",
52
- "@jskit-ai/resource-crud-core": "0.1.191",
51
+ "@jskit-ai/resource-core": "0.1.192",
52
+ "@jskit-ai/resource-crud-core": "0.1.192",
53
53
  "@mdi/js": "^7.4.47",
54
54
  "@openrouter/ai-sdk-provider": "^3.0.0",
55
55
  "ai": "^7.0.101",
@@ -58,8 +58,8 @@
58
58
  "ws": "^8.20.1"
59
59
  },
60
60
  "peerDependencies": {
61
- "@jskit-ai/http-runtime": "0.2.0",
62
- "@jskit-ai/kernel": "0.2.0",
61
+ "@jskit-ai/http-runtime": "0.2.1",
62
+ "@jskit-ai/kernel": "0.2.1",
63
63
  "vue": "^3.5.13",
64
64
  "vuetify": "^4.0.0"
65
65
  },
@@ -327,8 +327,15 @@ async function resend(id) {
327
327
  }
328
328
  catch { /* The delivery controller retains the error beside the failed message. */ }
329
329
  }
330
+ // The application's cancel asks its server and removes the message only once
331
+ // the server agrees. Without one, only a message the server already refused
332
+ // (failed) is removed.
330
333
  function cancel(id) {
331
- return props.adapter.actions?.cancel ? props.adapter.actions.cancel(id) : props.adapter.delivery?.cancel(id);
334
+ if (props.adapter.actions?.cancel) return props.adapter.actions.cancel(id);
335
+ const message = props.adapter.delivery?.find(id);
336
+ if (message?.status !== "failed") return false;
337
+ props.adapter.delivery.remove(id);
338
+ return true;
332
339
  }
333
340
  function edit(id) {
334
341
  if (props.adapter.actions?.edit) return props.adapter.actions.edit(id);
@@ -70,9 +70,9 @@ async function setGoal() {
70
70
  </template>
71
71
  <v-card class="assistant-goal__details pa-3" max-width="360">
72
72
  <strong role="status">{{ label }}</strong>
73
- <v-btn v-if="(running || (state.pauseBlocked && goal?.status === 'blocked')) && state.pause" size="small" :disabled="state.pending" @click="state.pause()">{{ state.action === 'pause' ? t('jskit.assistant.goal.pausing') : t('jskit.assistant.goal.pause') }}</v-btn>
73
+ <v-btn v-if="(running || (state.pauseBlocked && goal?.status === 'blocked')) && state.pause" size="small" :disabled="state.stopPending" @click="state.pause()">{{ state.action === 'pause' ? t('jskit.assistant.goal.pausing') : t('jskit.assistant.goal.pause') }}</v-btn>
74
74
  <v-btn v-if="['paused', 'blocked', 'usageLimited'].includes(goal?.status) && state.resume" size="small" :disabled="state.pending" @click="state.resume()">{{ state.action === 'resume' ? t('jskit.assistant.goal.resuming') : t('jskit.assistant.goal.resume') }}</v-btn>
75
- <v-btn v-if="goal && goal.status !== 'complete' && state.cancel" color="error" size="small" variant="text" :disabled="state.pending" @click="state.cancel()">{{ state.action === 'cancel' ? t('jskit.assistant.goal.cancelling') : t('jskit.assistant.goal.cancel') }}</v-btn>
75
+ <v-btn v-if="goal && goal.status !== 'complete' && state.cancel" color="error" size="small" variant="text" :disabled="state.stopPending" @click="state.cancel()">{{ state.action === 'cancel' ? t('jskit.assistant.goal.cancelling') : t('jskit.assistant.goal.cancel') }}</v-btn>
76
76
  <p v-if="goal" class="my-2">{{ goal.objective }}</p>
77
77
  <p v-if="goal?.reason" class="text-body-small my-2">{{ goal.reason }}</p>
78
78
  <p v-if="elapsed" class="text-body-small my-2">{{ elapsedText }}</p>
@@ -65,10 +65,11 @@
65
65
  :class="{ 'assistant-transcript__body--settling': initialScrollPending }"
66
66
  tabindex="0"
67
67
  @keydown.capture="markKeyboardScrollIntent"
68
- @pointerdown.self="markUserScrollIntent"
68
+ @pointerdown.self="markUserScrollIntent()"
69
69
  @scroll.passive="updateLatestFollowFromScroll"
70
- @touchmove.passive="markUserScrollIntent"
71
- @wheel.passive="markUserScrollIntent"
70
+ @touchstart.passive="rememberTouch"
71
+ @touchmove.passive="markTouchScrollIntent"
72
+ @wheel.passive="markUserScrollIntent({ upward: $event.deltaY < 0 })"
72
73
  >
73
74
  <div
74
75
  v-if="welcomeMessage"
@@ -179,12 +180,15 @@
179
180
  </div>
180
181
  <slot name="user-message-actions" :message="entry.message" :turn="entry.turn" />
181
182
  <div
182
- v-if="entry.delivery || entry.turn.optimistic?.status === 'failed'"
183
+ v-if="entry.delivery || entry.turn.optimistic?.status === 'failed' || entry.turn.optimistic?.cancelling || entry.turn.optimistic?.cancelError"
183
184
  class="assistant-transcript__optimistic-failure"
184
185
  >
185
- <span role="status">{{ entry.delivery ? entry.delivery.delivery.error || t('jskit.assistant.delivery.unconfirmedShort') : t('jskit.assistant.transcript.failed', { error: entry.turn.optimistic.error || t('jskit.assistant.delivery.notSent') }) }}</span>
186
+ <span role="status">{{ entry.turn.optimistic?.cancelling ? t('jskit.assistant.delivery.cancelling')
187
+ : entry.turn.optimistic?.cancelError ? entry.turn.optimistic.cancelError
188
+ : entry.delivery ? entry.delivery.delivery.error || t('jskit.assistant.delivery.unconfirmedShort') : t('jskit.assistant.transcript.failed', { error: entry.turn.optimistic.error || t('jskit.assistant.delivery.notSent') }) }}</span>
186
189
  <div v-if="!entry.turn.preview" class="assistant-transcript__optimistic-actions">
187
190
  <v-btn
191
+ v-if="!entry.turn.optimistic?.cancelling && !entry.turn.optimistic?.cancelError && (entry.delivery || entry.turn.optimistic?.status === 'failed')"
188
192
  class="assistant-transcript__delivery-action"
189
193
  color="error"
190
194
  size="x-small"
@@ -198,7 +202,7 @@
198
202
  {{ entry.delivery?.delivery.checking ? t('jskit.assistant.delivery.checking') : t('jskit.assistant.delivery.retry') }}
199
203
  </v-btn>
200
204
  <v-btn
201
- v-if="!entry.delivery || cancellableDelivery"
205
+ v-if="!entry.delivery || cancellableDelivery || entry.turn.optimistic?.cancelling || entry.turn.optimistic?.cancelError"
202
206
  class="assistant-transcript__delivery-action"
203
207
  size="x-small"
204
208
  type="button"
@@ -208,7 +212,7 @@
208
212
  {{ t("jskit.assistant.transcript.cancel") }}
209
213
  </v-btn>
210
214
  <v-btn
211
- v-if="!entry.delivery"
215
+ v-if="!entry.delivery && entry.turn.optimistic?.status === 'failed' && !entry.turn.optimistic.cancelling && !entry.turn.optimistic.cancelError"
212
216
  class="assistant-transcript__delivery-action"
213
217
  size="x-small"
214
218
  type="button"
@@ -328,6 +332,7 @@ import AssistantProgress from "./AssistantProgress.vue";
328
332
  import { parseNumberedQuestionPrompt } from "../../shared/conversation/numberedQuestionSugar.js";
329
333
  import { parseLongTextReviewBlocks } from "../../shared/conversation/longTextBlocks.js";
330
334
  import {
335
+ scrollDistanceFromBottom,
331
336
  scrollElementNearBottom
332
337
  } from "../../shared/conversation/scrollFollowState.js";
333
338
  import {
@@ -442,6 +447,8 @@ let retainedReaderScrollSnapshot = null;
442
447
  let loadMoreRequestVersion = 0;
443
448
  let pendingTailFollow = false;
444
449
  let previousScrollTop = 0;
450
+ let userScrollIntentUpward = false;
451
+ let lastTouchY = null;
445
452
  const USER_SCROLL_INTENT_RESET_MS = 600;
446
453
  const LOAD_MORE_THRESHOLD_PX = 160;
447
454
  const KEYBOARD_SCROLL_KEYS = new Set([
@@ -454,6 +461,7 @@ const KEYBOARD_SCROLL_KEYS = new Set([
454
461
  "PageUp",
455
462
  "Spacebar"
456
463
  ]);
464
+ const UPWARD_SCROLL_KEYS = new Set(["ArrowUp", "Home", "PageUp"]);
457
465
  const TIME_FORMAT = Object.freeze({
458
466
  year: "numeric",
459
467
  month: "short",
@@ -747,9 +755,10 @@ function resumePendingTailFollow() {
747
755
  }
748
756
  }
749
757
 
750
- function markUserScrollIntent() {
758
+ function markUserScrollIntent({ upward = false } = {}) {
751
759
  retainedReaderScrollSnapshot = null;
752
760
  userScrollIntent.value = true;
761
+ userScrollIntentUpward = upward;
753
762
  clearLiveBottomScroll();
754
763
  clearScheduledScrolls();
755
764
  if (userScrollIntentTimer && typeof window !== "undefined" && typeof window.clearTimeout === "function") {
@@ -778,7 +787,20 @@ function markKeyboardScrollIntent(event = {}) {
778
787
  ) {
779
788
  return;
780
789
  }
781
- markUserScrollIntent();
790
+ markUserScrollIntent({
791
+ upward: UPWARD_SCROLL_KEYS.has(event.key) || (event.shiftKey && [" ", "Spacebar"].includes(event.key))
792
+ });
793
+ }
794
+
795
+ function rememberTouch(event = {}) {
796
+ lastTouchY = event.touches?.[0]?.clientY ?? null;
797
+ }
798
+
799
+ function markTouchScrollIntent(event = {}) {
800
+ const touchY = event.touches?.[0]?.clientY ?? null;
801
+ // A finger moving down the screen scrolls the transcript up.
802
+ markUserScrollIntent({ upward: touchY !== null && lastTouchY !== null && touchY > lastTouchY });
803
+ lastTouchY = touchY;
782
804
  }
783
805
 
784
806
  function scrollToLatestMessageAfterLayout({
@@ -870,13 +892,21 @@ function updateLatestFollowFromScroll(event = {}) {
870
892
  loadMoreScrollSnapshot.anchor = visibleHistoryAnchor(target);
871
893
  loadMoreScrollSnapshot.scrollHeight = target.scrollHeight;
872
894
  }
873
- const shouldFollow = scrollElementNearBottom(target);
895
+ // The reader's own upward scrolling leaves the latest message from its first
896
+ // frame, even within the follow threshold.
897
+ const userScrollsUp = userScrollIntent.value && userScrollIntentUpward;
898
+ const shouldFollow = scrollElementNearBottom(target) &&
899
+ !(userScrollsUp && scrollDistanceFromBottom(target) > 1);
874
900
  if (!shouldFollow && !userScrollIntent.value && followingLatest.value) {
875
901
  return;
876
902
  }
877
903
  followingLatest.value = shouldFollow;
878
904
  if (shouldFollow) {
879
- clearUserScrollIntent();
905
+ // A scroll event still at the end, queued before upward input, must not
906
+ // end that input's intent.
907
+ if (!userScrollsUp) {
908
+ clearUserScrollIntent();
909
+ }
880
910
  resumePendingTailFollow();
881
911
  return;
882
912
  }
@@ -100,7 +100,8 @@ function createAssistantMessageDelivery({ deliver: defaultDeliver } = {}) {
100
100
  } : null;
101
101
  return {
102
102
  optimistic: { error: message.error, id: message.id, status: message.status,
103
- ...(message.status === "pending" && message.waiting ? { waiting: message.waiting } : {}) },
103
+ ...(message.status === "pending" && message.waiting ? { waiting: message.waiting } : {}),
104
+ ...(message.cancelling ? { cancelling: true } : {}), ...(message.cancelError ? { cancelError: message.cancelError } : {}) },
104
105
  turnId: message.id,
105
106
  [role]: authored,
106
107
  ...(status ? { system: role === "system" ? { ...authored, ...status, text: `${authored.text}\n\n${status.text}` } : status } : {})
@@ -117,7 +118,7 @@ function createAssistantMessageDelivery({ deliver: defaultDeliver } = {}) {
117
118
  queue = false
118
119
  } = {}) {
119
120
  if ((state.sending && !queue) || pendingSends.has(messageId) || find(messageId)?.status === "uncertain" ||
120
- (!messageText(payload?.message) && !payload?.displayAttachments?.length)) return false;
121
+ find(messageId)?.cancelling || (!messageText(payload?.message) && !payload?.displayAttachments?.length)) return false;
121
122
  if (typeof deliver !== "function") throw new TypeError("Message delivery requires a deliver function.");
122
123
  const snapshot = JSON.parse(JSON.stringify(payload));
123
124
  const previous = find(messageId);
@@ -147,6 +148,8 @@ function createAssistantMessageDelivery({ deliver: defaultDeliver } = {}) {
147
148
  try {
148
149
  if (predecessor) await predecessor;
149
150
  if (!current()) return false;
151
+ // A queued message cancelled while it waited is never delivered.
152
+ if (find(messageId)?.cancelling) return false;
150
153
  if (uncertainOnError && state.messages.some(entry => entry.id !== messageId && entry.status === "uncertain" && !knownUncertain.has(entry.id))) {
151
154
  fail(messageId, t("jskit.assistant.delivery.checkPrevious"));
152
155
  return false;
@@ -240,15 +243,29 @@ function createAssistantMessageDelivery({ deliver: defaultDeliver } = {}) {
240
243
  return true;
241
244
  }
242
245
 
246
+ // Cancel of a pending, uncertain or failed message waits for the server: the
247
+ // message stays, shown as cancelling, until the caller removes it on the
248
+ // server's agreement or reports that the server could not be reached.
243
249
  function cancel(messageId) {
244
- if (find(messageId)?.status !== "failed") return false;
245
- remove(messageId);
250
+ const message = find(messageId);
251
+ if (!message || message.status === "accepted" || message.cancelling) return false;
252
+ message.cancelling = true;
253
+ message.cancelError = "";
246
254
  return true;
247
255
  }
248
256
 
257
+ function cancelFailed(messageId, error = "") {
258
+ const message = find(messageId);
259
+ if (!message) return;
260
+ message.cancelling = false;
261
+ message.cancelError = String(error || t("jskit.assistant.delivery.cancelUnreachable")).trim();
262
+ }
263
+
264
+ // Only a message that never reached the conversation returns to the draft.
249
265
  function edit(messageId, draft = "") {
250
266
  const message = find(messageId);
251
- if (!message || !cancel(messageId)) return null;
267
+ if (message?.status !== "failed" || message.cancelling) return null;
268
+ remove(messageId);
252
269
  return draftWithRestoredMessage(message.text, draft);
253
270
  }
254
271
 
@@ -269,7 +286,7 @@ function createAssistantMessageDelivery({ deliver: defaultDeliver } = {}) {
269
286
  state.sending = false;
270
287
  }
271
288
 
272
- return { accept, cancel, edit, find, reconcile, remove, resend, reset, restoreUncertain, rejectUnsent, send, state, turns, wait };
289
+ return { accept, cancel, cancelFailed, edit, find, reconcile, remove, resend, reset, restoreUncertain, rejectUnsent, send, state, turns, wait };
273
290
  }
274
291
 
275
292
  // The composer text after a failed or cancelled message returns to it: the
@@ -133,6 +133,11 @@ function createAssistantApi({ request, requestStream, resolveBasePath, resolveSu
133
133
  return requestConversation(conversationId, `/deliveries/${encodedMessageId}/inspect`, { method: "POST", signal });
134
134
  },
135
135
 
136
+ cancelConversationDelivery(conversationId, messageId, { signal } = {}) {
137
+ const encodedMessageId = encodeURIComponent(String(messageId || "").trim());
138
+ return requestConversation(conversationId, `/deliveries/${encodedMessageId}/cancel`, { method: "POST", signal });
139
+ },
140
+
136
141
  readConversationGoal(conversationId, { signal } = {}) {
137
142
  return requestConversation(conversationId, "/goal", { method: "GET", signal });
138
143
  },
@@ -9,9 +9,8 @@ import { createLocalConversationExecution } from "./localExecution.js";
9
9
  import { CLAUDE_APPLICATION_TOOL_SERVER } from "./claudeTools.js";
10
10
  import { nativeCommandHook, validateCommandWrapper } from "./commandWrapper.js";
11
11
 
12
- const statusReads = new WeakMap();
13
- const STATUS_REUSE_MS = 30_000;
14
- const STATUS_UNFINISHED_GRACE_MS = 5 * 60_000;
12
+ const statusReads = new Map();
13
+ const STATUS_RETRY_MS = 30_000;
15
14
  const CLAUDE_EXIT_WAIT_MS = 5_000;
16
15
 
17
16
  /** Person-facing cause for a Claude process that ended without being stopped. */
@@ -28,6 +27,17 @@ export function claudeUnexpectedExitMessage(processExit = {}) {
28
27
  return `Claude stopped unexpectedly. ${resume}`;
29
28
  }
30
29
 
30
+ // A file's metadata, following links, or null when it is absent.
31
+ async function fileRevision(file) {
32
+ try {
33
+ const value = await stat(file, { bigint: true });
34
+ return [value.dev, value.ino, value.size, value.mtimeNs].join(":");
35
+ } catch (error) {
36
+ if (error.code === "ENOENT") return null;
37
+ throw error;
38
+ }
39
+ }
40
+
31
41
  export async function readClaudeCodeAuthStatus({
32
42
  env = process.env, credentialHome = { home: env.HOME || homedir() }, command = "claude", commandRunner, signal
33
43
  } = {}) {
@@ -35,39 +45,28 @@ export async function readClaudeCodeAuthStatus({
35
45
  if (typeof commandRunner !== "function") throw new TypeError("Claude account status requires its host capture runner.");
36
46
  const configRoot = env.CLAUDE_CONFIG_DIR || path.join(credentialHome.home, ".claude");
37
47
  // Inspect file metadata only. Claude still owns reading and validating credentials.
38
- const revisions = await Promise.all([
39
- path.join(configRoot, ".credentials.json"), path.join(configRoot, ".claude.json"),
40
- path.join(credentialHome.home, ".claude.json")
41
- ].map(async (file) => {
42
- try {
43
- const value = await stat(file, { bigint: true });
44
- return [value.dev, value.ino, value.size, value.mtimeNs, value.ctimeNs].map(String);
45
- } catch (error) {
46
- if (error.code === "ENOENT") return null;
47
- throw error;
48
- }
49
- }));
50
- let reads = statusReads.get(commandRunner);
51
- if (!reads) statusReads.set(commandRunner, reads = new Map());
52
- const key = JSON.stringify([command, env, credentialHome]);
53
- const revision = JSON.stringify(revisions);
54
- const previous = reads.get(key);
48
+ // Sign-in writes .credentials.json and sign-out removes it. Claude Code also
49
+ // rewrites .claude.json during turns and after every status read, so that
50
+ // file is not watched.
51
+ const revision = await fileRevision(path.join(configRoot, ".credentials.json"));
52
+ // One entry per account, whichever command path or host runner reads it: only
53
+ // the account's location and its identity variables count.
54
+ const key = jsonHash([configRoot, credentialHome.home, Object.entries(env).filter(([name, value]) =>
55
+ value && (name === "CLAUDE_CODE_OAUTH_TOKEN" || name.startsWith("ANTHROPIC_"))).sort()]);
56
+ const previous = statusReads.get(key);
55
57
  if (previous?.revision === revision && (previous.pending || previous.expiresAt > Date.now())) return previous.value;
56
- // Claude's last answer for these exact account files.
57
- const answered = previous?.revision === revision ? previous.answered : null;
58
- const entry = { revision, pending: true, expiresAt: 0, answered };
59
- reads.set(key, entry);
58
+ const entry = { revision, pending: true, expiresAt: 0 };
59
+ statusReads.set(key, entry);
60
60
  entry.value = readNativeClaudeCodeAuthStatus({ env, credentialHome, command, commandRunner, signal }).then(({ status, unfinished }) => {
61
- // A read the host timed out or refused for now says nothing about the account.
62
- const value = unfinished && answered && Date.now() - answered.at < STATUS_UNFINISHED_GRACE_MS
63
- ? answered.status : Object.freeze(status);
64
61
  // Keychain changes cannot be observed with file metadata on macOS.
65
62
  if (process.platform !== "darwin") {
66
- // Unfinished reads back off too, so a busy host is not probed again by every caller.
67
- if (!status.error || unfinished) entry.expiresAt = Date.now() + STATUS_REUSE_MS;
68
- if (!status.error) entry.answered = { status: value, at: Date.now() };
63
+ // Claude's answer holds until its credentials change. A read the host timed
64
+ // out or refused for now backs off, so a busy host is not probed again by
65
+ // every caller; a read that ran and failed is asked again next time.
66
+ if (!status.error) entry.expiresAt = Infinity;
67
+ else if (unfinished) entry.expiresAt = Date.now() + STATUS_RETRY_MS;
69
68
  }
70
- return value;
69
+ return Object.freeze(status);
71
70
  }).finally(() => { entry.pending = false; });
72
71
  return entry.value;
73
72
  }
@@ -250,6 +249,11 @@ const PLAN_USAGE_IDLE_READ_MS = 300_000;
250
249
  // A verified reading stays current until the next idle read, one client poll and
251
250
  // its read deadline could have replaced it.
252
251
  const PLAN_USAGE_CURRENT_MS = 420_000;
252
+ // One plan-usage reading per Claude account in this server process, with its read
253
+ // times and the read in flight. Every account-query owner, page and session asking
254
+ // for the account shares it, so however many ask, the account's one-shot Claude
255
+ // starts at most once per idle interval.
256
+ const planUsageReads = new Map();
253
257
 
254
258
  /**
255
259
  * Claude Code answers `get_usage` from the usage endpoint, or from its saved copy
@@ -278,15 +282,21 @@ export function claudeCatalogueModels(initialization) {
278
282
  }));
279
283
  }
280
284
 
281
- /** Native account queries share process reuse, caches and retryable cleanup. */
282
- export function createClaudeAccountQueries({ createProcess, accountIdentity, processes = () => [], isClosing = () => false }) {
285
+ /**
286
+ * Native account queries share process reuse, caches and retryable cleanup. Plan
287
+ * usage is shared by `accountIdentity` with every other owner in the process, so
288
+ * that identity names exactly one Claude account. `configRoot` is the account's
289
+ * Claude configuration directory, whose credentials the model list follows.
290
+ */
291
+ export function createClaudeAccountQueries({ createProcess, accountIdentity, configRoot, processes = () => [], isClosing = () => false }) {
283
292
  const error = message => Object.assign(new Error(message), { code: "claude_account_query_failed" });
284
293
  const accountProcessStops = new Set();
285
294
  const accountReads = new Set();
286
295
  let catalog;
287
296
  const catalogStarts = new Map();
288
- const planUsage = new Map();
289
- const planUsagePending = new Map();
297
+ // Accounts whose shared plan-usage reading this owner used, and the reads it started.
298
+ const usageAccounts = new Set();
299
+ const usageReads = new Set();
290
300
  let revision = 0;
291
301
 
292
302
  function assertCurrent(expectedRevision) {
@@ -305,7 +315,7 @@ export function createClaudeAccountQueries({ createProcess, accountIdentity, pro
305
315
  entry.process && !entry.stopping && entry.accountIdentity === identity);
306
316
  }
307
317
 
308
- async function readAccountProcess(identity, expectedRevision, purpose, read, { borrow = true } = {}) {
318
+ async function readAccountProcess(identity, expectedRevision, purpose, read, { borrow = false } = {}) {
309
319
  assertCurrent(expectedRevision);
310
320
  for (const native of accountProcessStops) await stopAccountProcess(native);
311
321
  assertCurrent(expectedRevision);
@@ -330,36 +340,60 @@ export function createClaudeAccountQueries({ createProcess, accountIdentity, pro
330
340
  }
331
341
  }
332
342
 
343
+ // The model list belongs to the account and the Claude Code version that gave
344
+ // it: the account's credentials file changes with sign-in, sign-out and each
345
+ // token refresh (which carries a plan change), and the executable with each
346
+ // Claude Code update. An executable given as a bare name has no metadata.
347
+ async function catalogueRevision(command) {
348
+ return JSON.stringify(await Promise.all([fileRevision(path.join(configRoot, ".credentials.json")),
349
+ fileRevision(command)]));
350
+ }
351
+
333
352
  return Object.freeze({
334
353
  async readCatalogue(context) {
335
354
  const expectedRevision = revision;
336
355
  assertCurrent(expectedRevision);
337
356
  const identity = await accountIdentity(context);
338
357
  assertCurrent(expectedRevision);
339
- if (!catalog || catalog.identity !== identity || Date.now() - catalog.at > 600_000) {
340
- if (!catalogStarts.has(identity)) catalogStarts.set(identity, (async () => {
341
- const value = await readAccountProcess(identity, expectedRevision, "catalogue", (native) => native.initialization);
342
- if (identity !== await accountIdentity(context)) throw error("The signed-in Claude account changed. Refresh the model list.");
343
- assertCurrent(expectedRevision);
344
- catalog = { at: Date.now(), identity, value };
345
- return value;
346
- })().finally(() => { catalogStarts.delete(identity); }));
347
- return catalogStarts.get(identity);
358
+ // An answer is kept until its account, credentials or executable change, so
359
+ // reading it again starts no Claude.
360
+ const kept = catalog?.identity === identity ? catalog : null;
361
+ if (kept && kept.revision === await catalogueRevision(kept.command)) {
362
+ assertCurrent(expectedRevision);
363
+ return kept.value;
348
364
  }
349
- return catalog.value;
365
+ if (!catalogStarts.has(identity)) catalogStarts.set(identity, (async () => {
366
+ // A conversation's process answers with what it knew when it started, so
367
+ // the list comes from a Claude started for this read.
368
+ const { value, command } = await readAccountProcess(identity, expectedRevision, "catalogue",
369
+ async (native) => ({ value: await native.initialization, command: native.command }));
370
+ const answered = await catalogueRevision(command);
371
+ if (identity !== await accountIdentity(context)) throw error("The signed-in Claude account changed. Refresh the model list.");
372
+ assertCurrent(expectedRevision);
373
+ catalog = { identity, command, revision: answered, value };
374
+ return value;
375
+ })().finally(() => { catalogStarts.delete(identity); }));
376
+ return catalogStarts.get(identity);
350
377
  },
351
378
  async readPlanUsage(context) {
352
379
  const expectedRevision = revision;
353
380
  assertCurrent(expectedRevision);
354
381
  const identity = await accountIdentity(context);
355
382
  assertCurrent(expectedRevision);
356
- if (planUsagePending.has(identity)) return planUsagePending.get(identity);
357
- // One reading per account; a started process is stopped after its read.
358
- const usage = planUsage.get(identity) || { liveReadAt: -Infinity, temporaryReadAt: -Infinity, reading: null };
359
- planUsage.set(identity, usage);
383
+ // One reading per account, whichever owner asks; a started process is stopped after its read.
384
+ let usage = planUsageReads.get(identity);
385
+ if (!usage) {
386
+ usage = { liveReadAt: -Infinity, temporaryReadAt: -Infinity, reading: null, pending: null };
387
+ planUsageReads.set(identity, usage);
388
+ }
389
+ usageAccounts.add(identity);
390
+ if (usage.pending) return usage.pending;
360
391
  const live = Boolean(ownedProcess(identity));
361
392
  const liveDue = live && Date.now() - usage.liveReadAt >= PLAN_USAGE_LIVE_READ_MS;
362
- const temporaryDue = () => Date.now() - usage.temporaryReadAt >= PLAN_USAGE_IDLE_READ_MS;
393
+ // A one-shot Claude starts only when neither a verified reading nor a one-shot
394
+ // read is from the last idle interval.
395
+ const temporaryDue = () => Date.now() - Math.max(usage.temporaryReadAt, usage.reading?.checkedAt ?? -Infinity) >=
396
+ PLAN_USAGE_IDLE_READ_MS;
363
397
  if (!liveDue && (live || !temporaryDue())) return presentPlanUsage(usage.reading);
364
398
  const pending = (async () => {
365
399
  // A live process's held endpoint read is its own, so a fresh one-shot Claude
@@ -385,18 +419,31 @@ export function createClaudeAccountQueries({ createProcess, accountIdentity, pro
385
419
  }
386
420
  }
387
421
  return presentPlanUsage(usage.reading);
388
- })().finally(() => { planUsagePending.delete(identity); });
389
- planUsagePending.set(identity, pending);
422
+ })().finally(() => {
423
+ usageReads.delete(pending);
424
+ if (usage.pending === pending) usage.pending = null;
425
+ });
426
+ // Requests that arrive while the account is read share that read.
427
+ usage.pending = pending;
428
+ usageReads.add(pending);
390
429
  return pending;
391
430
  },
392
431
  // A native usage change lets the next request read again without hiding the last reading.
393
- invalidateUsage() { for (const usage of planUsage.values()) usage.liveReadAt = -Infinity; },
432
+ invalidateUsage() {
433
+ for (const identity of usageAccounts) {
434
+ const usage = planUsageReads.get(identity);
435
+ if (usage) usage.liveReadAt = -Infinity;
436
+ }
437
+ },
394
438
  async invalidate() {
395
439
  revision++;
396
- for (const controller of accountReads) controller.abort(error("Claude account query was cancelled for reconnection."));
397
- await Promise.allSettled([...catalogStarts.values(), ...planUsagePending.values()]);
440
+ // Dropped at once: a read started before this cannot store its answer.
398
441
  catalog = null;
399
- planUsage.clear();
442
+ for (const controller of accountReads) controller.abort(error("Claude account query was cancelled for reconnection."));
443
+ await Promise.allSettled([...catalogStarts.values(), ...usageReads]);
444
+ // The account changed: the next request for an account this owner used reads again.
445
+ for (const identity of usageAccounts) planUsageReads.delete(identity);
446
+ usageAccounts.clear();
400
447
  for (const native of accountProcessStops) await stopAccountProcess(native);
401
448
  }
402
449
  });
@@ -478,7 +525,7 @@ export async function createClaudeCodeProcess({
478
525
  }, error => {
479
526
  if (!stopped && !stopping) stream.destroy(error);
480
527
  });
481
- return { client, initialization, executionId: native.id, stop };
528
+ return { client, initialization, executionId: native.id, command, stop };
482
529
  } catch (error) {
483
530
  // A rejected start may already own an execution and its cleanup proof.
484
531
  // Only a returned native handle transfers that cleanup to this owner.