@sixb/app 0.2.5 → 0.2.7

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 (136) hide show
  1. package/dist/agent/components/agent-threads.d.ts.map +1 -1
  2. package/dist/agent/components/composer-place.d.ts.map +1 -1
  3. package/dist/agent/components/computer-place.d.ts +24 -6
  4. package/dist/agent/components/computer-place.d.ts.map +1 -1
  5. package/dist/agent/components/conversation-panel.d.ts.map +1 -1
  6. package/dist/agent/components/message-view.d.ts +13 -3
  7. package/dist/agent/components/message-view.d.ts.map +1 -1
  8. package/dist/agent/components/pending-messages.d.ts.map +1 -1
  9. package/dist/agent/components/sandbox-recovery.d.ts +8 -2
  10. package/dist/agent/components/sandbox-recovery.d.ts.map +1 -1
  11. package/dist/agent/components/transcript.d.ts +13 -0
  12. package/dist/agent/components/transcript.d.ts.map +1 -1
  13. package/dist/agent/conversation.d.ts +4 -0
  14. package/dist/agent/conversation.d.ts.map +1 -1
  15. package/dist/agent/delegation/use-children.d.ts +5 -5
  16. package/dist/agent/delegation/use-children.d.ts.map +1 -1
  17. package/dist/agent/format.d.ts +7 -0
  18. package/dist/agent/format.d.ts.map +1 -1
  19. package/dist/agent/hooks/thread-queries.d.ts +1548 -0
  20. package/dist/agent/hooks/thread-queries.d.ts.map +1 -0
  21. package/dist/agent/hooks/use-agent-conversation.d.ts +41 -2
  22. package/dist/agent/hooks/use-agent-conversation.d.ts.map +1 -1
  23. package/dist/agent/hooks/use-thread-lists.d.ts +80 -3
  24. package/dist/agent/hooks/use-thread-lists.d.ts.map +1 -1
  25. package/dist/agent/hooks/use-thread-place.d.ts +49 -0
  26. package/dist/agent/hooks/use-thread-place.d.ts.map +1 -0
  27. package/dist/agent/i18n/en.d.ts +44 -6
  28. package/dist/agent/i18n/en.d.ts.map +1 -1
  29. package/dist/agent/i18n/fr.d.ts.map +1 -1
  30. package/dist/agent/i18n/index.d.ts +76 -12
  31. package/dist/agent/i18n/index.d.ts.map +1 -1
  32. package/dist/agent/live-run.d.ts.map +1 -1
  33. package/dist/agent/model-selection.d.ts +3 -2
  34. package/dist/agent/model-selection.d.ts.map +1 -1
  35. package/dist/agent/moves.d.ts +40 -0
  36. package/dist/agent/moves.d.ts.map +1 -0
  37. package/dist/agent/thread-reader-state.d.ts +30 -0
  38. package/dist/agent/thread-reader-state.d.ts.map +1 -0
  39. package/dist/agent/types.d.ts +4 -0
  40. package/dist/agent/types.d.ts.map +1 -1
  41. package/dist/artifacts/live/session.d.ts.map +1 -1
  42. package/dist/artifacts/queries.d.ts.map +1 -1
  43. package/dist/artifacts/renderers/live-frame.d.ts.map +1 -1
  44. package/dist/{chunk-69qgh20f.js → chunk-1f4h75n3.js} +1 -1
  45. package/dist/{chunk-4fex83k2.js → chunk-7v9622qb.js} +2254 -739
  46. package/dist/{chunk-4fex83k2.js.map → chunk-7v9622qb.js.map} +29 -26
  47. package/dist/{chunk-5sgac68y.js → chunk-dntecmwb.js} +1 -1
  48. package/dist/{chunk-4wm09prf.js → chunk-qmka6aea.js} +1 -1
  49. package/dist/createCustomApp.d.ts +8 -1
  50. package/dist/createCustomApp.d.ts.map +1 -1
  51. package/dist/index.d.ts +3 -2
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +4 -2
  54. package/dist/index.js.map +3 -3
  55. package/dist/pages/console/data/accounts.d.ts +94 -0
  56. package/dist/pages/console/data/accounts.d.ts.map +1 -0
  57. package/dist/pages/console/data/connectors.d.ts.map +1 -1
  58. package/dist/pages/console/data/datasets.d.ts.map +1 -1
  59. package/dist/pages/console/data/live-updates.d.ts.map +1 -1
  60. package/dist/pages/console/data/messages.d.ts +46 -0
  61. package/dist/pages/console/data/messages.d.ts.map +1 -1
  62. package/dist/pages/console/data/pipelines.d.ts.map +1 -1
  63. package/dist/pages/console/data/projections.d.ts.map +1 -1
  64. package/dist/pages/console/data/sync-button.d.ts.map +1 -1
  65. package/dist/pages/console/data/syncs.d.ts.map +1 -1
  66. package/dist/pages/console/ontology/actions.d.ts.map +1 -1
  67. package/dist/pages/console/ontology/object-type.d.ts.map +1 -1
  68. package/dist/pages/console/ontology/object-types.d.ts.map +1 -1
  69. package/dist/pages/console/ontology/rules.d.ts.map +1 -1
  70. package/dist/pages/console/ontology/workflow.d.ts.map +1 -1
  71. package/dist/pages/console/ontology/workflows.d.ts.map +1 -1
  72. package/dist/pages/folders.d.ts +106 -0
  73. package/dist/pages/folders.d.ts.map +1 -0
  74. package/dist/pages/settings/usage/breakdown.d.ts.map +1 -1
  75. package/dist/pages/settings/usage/page.d.ts +4 -1
  76. package/dist/pages/settings/usage/page.d.ts.map +1 -1
  77. package/dist/pages/settings/usage/spend-model.d.ts +43 -19
  78. package/dist/pages/settings/usage/spend-model.d.ts.map +1 -1
  79. package/dist/pages.js +23453 -22656
  80. package/dist/pages.js.map +23 -21
  81. package/dist/server.d.ts +1 -1
  82. package/dist/server.d.ts.map +1 -1
  83. package/dist/server.js +40 -3
  84. package/dist/server.js.map +3 -3
  85. package/package.json +3 -3
  86. package/src/agent/agent-chat.tsx +2 -2
  87. package/src/agent/components/agent-threads.tsx +42 -2
  88. package/src/agent/components/composer-place.tsx +2 -7
  89. package/src/agent/components/computer-place.tsx +415 -70
  90. package/src/agent/components/conversation-panel.tsx +31 -26
  91. package/src/agent/components/message-view.tsx +418 -9
  92. package/src/agent/components/pending-messages.tsx +5 -1
  93. package/src/agent/components/sandbox-recovery.tsx +24 -6
  94. package/src/agent/components/transcript.tsx +136 -5
  95. package/src/agent/conversation.ts +16 -1
  96. package/src/agent/format.ts +52 -0
  97. package/src/agent/hooks/thread-queries.ts +75 -0
  98. package/src/agent/hooks/use-agent-conversation.ts +461 -112
  99. package/src/agent/hooks/use-thread-lists.ts +72 -7
  100. package/src/agent/hooks/use-thread-place.ts +239 -0
  101. package/src/agent/i18n/en.ts +69 -16
  102. package/src/agent/i18n/fr.ts +71 -19
  103. package/src/agent/live-run.ts +38 -0
  104. package/src/agent/model-selection.ts +3 -2
  105. package/src/agent/moves.ts +174 -0
  106. package/src/agent/thread-reader-state.ts +75 -0
  107. package/src/agent/types.ts +6 -0
  108. package/src/artifacts/live/session.ts +5 -0
  109. package/src/createCustomApp.ts +57 -3
  110. package/src/index.ts +4 -0
  111. package/src/pages/console/data/accounts.tsx +509 -0
  112. package/src/pages/console/data/connectors.tsx +67 -64
  113. package/src/pages/console/data/datasets.tsx +79 -68
  114. package/src/pages/console/data/live-updates.ts +2 -0
  115. package/src/pages/console/data/messages.ts +73 -0
  116. package/src/pages/console/data/pipelines.tsx +80 -69
  117. package/src/pages/console/data/projections.tsx +111 -82
  118. package/src/pages/console/data/sync-button.tsx +56 -16
  119. package/src/pages/console/data/syncs.tsx +121 -86
  120. package/src/pages/console/ontology/actions.tsx +51 -24
  121. package/src/pages/console/ontology/object-type.tsx +5 -1
  122. package/src/pages/console/ontology/object-types.tsx +41 -32
  123. package/src/pages/console/ontology/rules.tsx +48 -38
  124. package/src/pages/console/ontology/workflow.tsx +9 -3
  125. package/src/pages/console/ontology/workflows.tsx +55 -67
  126. package/src/pages/folders.tsx +335 -0
  127. package/src/pages/section-ui.tsx +1 -1
  128. package/src/pages/settings/usage/breakdown.tsx +5 -2
  129. package/src/pages/settings/usage/filter-menu.tsx +1 -1
  130. package/src/pages/settings/usage/page.tsx +32 -13
  131. package/src/pages/settings/usage/spend-chart.tsx +2 -2
  132. package/src/pages/settings/usage/spend-model.ts +118 -50
  133. package/src/server.ts +1 -0
  134. /package/dist/{chunk-69qgh20f.js.map → chunk-1f4h75n3.js.map} +0 -0
  135. /package/dist/{chunk-5sgac68y.js.map → chunk-dntecmwb.js.map} +0 -0
  136. /package/dist/{chunk-4wm09prf.js.map → chunk-qmka6aea.js.map} +0 -0
@@ -3,25 +3,24 @@ import {
3
3
  cancelAgentRunMutation,
4
4
  createAgentThreadMutation,
5
5
  decideAgentApprovalMutation,
6
+ editAgentThreadMessageMutation,
6
7
  getAgentOptions,
7
8
  getAgentPreferencesOptions,
8
9
  getAgentPreferencesQueryKey,
9
10
  getAgentThreadContextOptions,
10
11
  getAgentThreadContextQueryKey,
11
- getAgentThreadOptions,
12
12
  getAgentThreadQueryKey,
13
13
  listAgentApprovalsQueryKey,
14
+ listAgentComputersOptions,
14
15
  listAgentComputersQueryKey,
15
16
  listAgentThreadApprovalsOptions,
16
17
  listAgentThreadApprovalsQueryKey,
18
+ listAgentThreadInboxOptions,
17
19
  listAgentThreadInboxQueryKey,
18
- listAgentThreadMessagesOptions,
19
20
  listAgentThreadMessagesQueryKey,
20
- listAgentThreadRunsOptions,
21
21
  listAgentThreadRunsQueryKey,
22
22
  listAgentThreadsQueryKey,
23
23
  listModelsOptions,
24
- moveAgentThreadToCloudMutation,
25
24
  postAgentThreadMessageMutation,
26
25
  recreateAgentThreadSandboxMutation,
27
26
  restoreAgentThreadSandboxMutation,
@@ -31,6 +30,7 @@ import {
31
30
  updateAgentPreferencesMutation,
32
31
  useAgentActivityStream,
33
32
  useDesktop,
33
+ withdrawAgentThreadInboxItemMutation,
34
34
  } from "@sixb/client/hooks"
35
35
  import { MODEL_REASONING_LEVELS, type ModelReasoningLevel } from "@sixb/core/models"
36
36
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
@@ -49,7 +49,7 @@ import {
49
49
  } from "../approvals"
50
50
  import type { TranscriptBackground } from "../background/context"
51
51
  import type { ComposerProps } from "../components/composer"
52
- import { type ComputerOfflineNoticeProps, shownFolder } from "../components/computer-place"
52
+ import { type ComputerOfflineNoticeProps, folderName } from "../components/computer-place"
53
53
  import type { PendingMessagesProps } from "../components/pending-messages"
54
54
  import type { SandboxRecoveryProps } from "../components/sandbox-recovery"
55
55
  import type { TranscriptProps } from "../components/transcript"
@@ -70,6 +70,7 @@ import {
70
70
  preferenceWithReasoning,
71
71
  resolveModelSelection,
72
72
  } from "../model-selection"
73
+ import { transcriptMoves } from "../moves"
73
74
  import { openQuestion } from "../questions/interpret"
74
75
  import type { QuestionComposerProps } from "../questions/question-composer"
75
76
  import { type RequesterSettings, sendWithRequesterSettings } from "../requester-settings"
@@ -96,18 +97,22 @@ import {
96
97
  } from "../sharing"
97
98
  import type {
98
99
  AgentContextEntryInput,
100
+ AgentContextInput,
99
101
  AgentFileRef,
102
+ AgentInboxItem,
100
103
  AgentMessageDelivery,
101
104
  AgentRun,
102
105
  AgentThreadSandboxParams,
103
106
  LanguageModel,
104
107
  } from "../types"
108
+ import { markThreadReadsStale, threadQueryOptions } from "./thread-queries"
105
109
  import {
106
110
  ComputerUnavailableError,
107
111
  type NewThreadPlaceBody,
108
112
  useNewThreadPlace,
109
113
  } from "./use-new-thread-place"
110
114
  import { useAgentThreadLists } from "./use-thread-lists"
115
+ import { useThreadPlace } from "./use-thread-place"
111
116
  import { useThreadStream } from "./use-thread-stream"
112
117
 
113
118
  interface PendingSend {
@@ -183,9 +188,21 @@ export type ConversationComposerProps = Pick<
183
188
  | "contextMeter"
184
189
  >
185
190
 
191
+ /** Draft state for an earlier user message open in the inline editor. */
192
+ export interface AgentMessageEditDraft {
193
+ readonly messageId: string
194
+ readonly text: string
195
+ readonly attachments: readonly AgentFileRef[]
196
+ readonly context: readonly AgentContextEntryInput[]
197
+ /** Incremented when a failed edit restores this draft, so the editor reseeds. */
198
+ readonly nonce: number
199
+ /** Why the last save did not go through, said under the editor. */
200
+ readonly error?: string
201
+ }
202
+
186
203
  export type AgentConversation = ReturnType<typeof useAgentConversation>
187
204
 
188
- /** Why a message, a retry or a stop did not go through, or the approval mode did not change. */
205
+ /** Why a message, an edit, a retry or a stop did not go through, or the approval mode did not change. */
189
206
  export type AgentConversationSendError =
190
207
  /** Another answer holds the conversation; `someoneElse` when another person asked for it. */
191
208
  | { readonly code: "busy"; readonly someoneElse: boolean }
@@ -193,7 +210,7 @@ export type AgentConversationSendError =
193
210
  | { readonly code: "sandbox" }
194
211
  /** It's to run on this computer, and what runs it there can't start. */
195
212
  | { readonly code: "computer" }
196
- | { readonly code: "send" | "retry" | "stop" | "approvalMode" }
213
+ | { readonly code: "send" | "edit" | "retry" | "stop" | "approvalMode" }
197
214
 
198
215
  /** The conversation's messages could not be read. */
199
216
  export interface AgentConversationMessagesError {
@@ -202,6 +219,9 @@ export interface AgentConversationMessagesError {
202
219
 
203
220
  const MESSAGES_LOAD_ERROR: AgentConversationMessagesError = { code: "load" }
204
221
 
222
+ /** How often an open thread's messages are read again while the activity feed is away. */
223
+ const MESSAGES_RECOVERY_POLL_MS = 30_000
224
+
205
225
  /**
206
226
  * Everything one conversation with the project's agent needs: its threads, messages, turn and
207
227
  * model choice, and the actions on them. Route-independent; the built-in chat and custom chats
@@ -246,6 +266,8 @@ export function useAgentConversation({
246
266
  return
247
267
  }
248
268
 
269
+ // Another thread may hold reads a prefetch or an earlier visit left: opening it reads again.
270
+ if (event.threadId !== threadId) markThreadReadsStale(queryClient, event.threadId)
249
271
  void refreshThreads()
250
272
  },
251
273
  // A held call changed: its card, and the thread list's count of what waits for the reader. Its
@@ -266,6 +288,7 @@ export function useAgentConversation({
266
288
  },
267
289
  // On every (re)subscription: catch up with what changed while the socket was away.
268
290
  onSubscribed: () => {
291
+ markThreadReadsStale(queryClient)
269
292
  void queryClient.invalidateQueries({ queryKey: listAgentApprovalsQueryKey() })
270
293
  void queryClient.invalidateQueries({ queryKey: listAgentComputersQueryKey() })
271
294
  void (threadId === null ? refreshThreads() : refreshThread(threadId))
@@ -275,32 +298,37 @@ export function useAgentConversation({
275
298
  // The project activity feed is primary. Poll only as a focus-aware recovery path while the
276
299
  // socket is unavailable, rather than opening one connection per background thread.
277
300
  const recoveryPollMs = !activityStream.connected || activityStream.error ? 10_000 : false
301
+ // A thread's messages are its heaviest read, so they follow less often while the feed is away;
302
+ // its runs and the thread still poll at the faster rate.
303
+ const messagesRecoveryPollMs = recoveryPollMs === false ? false : MESSAGES_RECOVERY_POLL_MS
278
304
  const { threads, sharedThreads, waitingThreadIds } = useAgentThreadLists({
279
305
  refetchInterval: recoveryPollMs,
280
306
  })
281
307
  const currentAgent = agentQuery.data
282
308
  const models = useMemo(() => modelsQuery.data?.language ?? [], [modelsQuery.data])
283
- // With a list, the browser remembers one choice for every conversation. With tiers, each
284
- // conversation starts on Auto and keeps the model pinned in it; a new one keeps its pin in
285
- // memory until its first message creates the thread.
309
+ // The browser remembers one choice: a new conversation starts on it, and with tiers each
310
+ // conversation keeps the model pinned in it. Without tiers, that one choice serves every
311
+ // conversation.
286
312
  const tiered = hasTiers(models)
287
313
  const [modelPreference, setModelPreference] = useState(readModelPreference)
288
314
  const [modelPins, setModelPins] = useState(() => readModelPins() ?? {})
289
- const [newThreadPin, setNewThreadPin] = useState<ModelPreference | null>(null)
290
315
  const modelSelection = resolveModelSelection(
291
316
  models,
292
- tiered ? (threadId === null ? newThreadPin : (modelPins[threadId] ?? null)) : modelPreference
317
+ tiered ? (threadId === null ? modelPreference : (modelPins[threadId] ?? null)) : modelPreference
293
318
  )
294
319
  const selectedModel = modelSelection.model
295
320
  const selectedReasoning = modelSelection.reasoning
321
+ const reads = threadQueryOptions(threadId ?? "")
296
322
  const threadQuery = useQuery({
297
- ...getAgentThreadOptions({ path: { threadId: threadId ?? "" } }),
323
+ ...reads.thread,
298
324
  enabled: threadId !== null,
299
325
  refetchInterval: recoveryPollMs,
300
326
  // A shared thread can lose its reader without an event, and a computer's sixb can stop
301
- // without saying so: read it again when they come back.
327
+ // without saying so: read it again when they come back, however recent the last read.
302
328
  refetchOnWindowFocus: (query) =>
303
- isShared(query.state.data ?? null) || query.state.data?.computer !== undefined,
329
+ isShared(query.state.data ?? null) || query.state.data?.computer !== undefined
330
+ ? "always"
331
+ : false,
304
332
  })
305
333
  // A 404 after a read means the reader no longer reads it, such as a participant someone removed:
306
334
  // the last copy the query keeps must not stand in for it.
@@ -322,27 +350,39 @@ export function useAgentConversation({
322
350
  access === "owner" && thread?.runsOn === "computer" && thread.computer?.online !== true
323
351
 
324
352
  const messagesQuery = useQuery({
325
- ...listAgentThreadMessagesOptions({
326
- path: { threadId: threadId ?? "" },
327
- query: { order: "asc" },
328
- }),
353
+ ...reads.messages,
329
354
  enabled: threadId !== null,
330
- refetchInterval: recoveryPollMs,
355
+ refetchInterval: messagesRecoveryPollMs,
331
356
  })
332
357
  const savedMessages = useMemo(() => messagesQuery.data?.messages ?? [], [messagesQuery.data])
333
358
  const approvalOutcomes = useMemo(() => reportedApprovalOutcomes(savedMessages), [savedMessages])
334
359
  const authors = messagesQuery.data?.authors
360
+ // Every run, as every message is read: the transcript marks each move from the runs either side.
335
361
  const runsQuery = useQuery({
336
- ...listAgentThreadRunsOptions({
337
- path: { threadId: threadId ?? "" },
338
- query: { limit: "50", order: "desc" },
339
- }),
362
+ ...reads.runs,
340
363
  enabled: threadId !== null,
341
364
  refetchInterval: recoveryPollMs,
342
365
  })
343
366
  const runs = useMemo(() => runsQuery.data?.runs ?? [], [runsQuery.data])
344
367
  const latestRun = runs[0] ?? null
345
368
 
369
+ // An edit the reader saved while a turn answered waits in the thread's inbox until that turn
370
+ // ends: read from there, it stands in place after a reload, and on another device.
371
+ const inboxQuery = useQuery({
372
+ ...listAgentThreadInboxOptions({ path: { threadId: threadId ?? "" } }),
373
+ enabled: threadId !== null,
374
+ refetchInterval: (query) => ((query.state.data?.items.length ?? 0) > 0 ? 5_000 : false),
375
+ })
376
+ const waitingEdit = useMemo(
377
+ () =>
378
+ inboxQuery.data?.items.find(
379
+ (item) =>
380
+ item.replacesMessageId !== undefined &&
381
+ (!user || (item.authorPrincipal.type === "user" && item.authorPrincipal.id === user.id))
382
+ ) ?? null,
383
+ [inboxQuery.data, user]
384
+ )
385
+
346
386
  // Measured against the model the next message goes to; on Auto, the latest turn's.
347
387
  const meteredModel = modelSelection.auto ? undefined : selectedModel
348
388
  const contextQuery = useQuery({
@@ -390,6 +430,7 @@ export function useAgentConversation({
390
430
 
391
431
  const [pendingSend, setPendingSend] = useState<PendingSend | null>(null)
392
432
  const [pendingUser, setPendingUser] = useState<PendingUserMessage | null>(null)
433
+ const [editingMessage, setEditingMessage] = useState<AgentMessageEditDraft | null>(null)
393
434
  const [sentKeys, setSentKeys] = useState<ReadonlyMap<string, string>>(() => new Map())
394
435
  const [sendError, setSendError] = useState<{
395
436
  threadId: string | null
@@ -474,25 +515,60 @@ export function useAgentConversation({
474
515
  setPendingUser(null)
475
516
  return
476
517
  }
518
+ const replacedGone =
519
+ pendingUser.replacesMessageId === undefined ||
520
+ !savedMessages.some((message) => message.id === pendingUser.replacesMessageId)
477
521
  if (
478
522
  pendingUser.messageId &&
523
+ replacedGone &&
479
524
  savedMessages.some((message) => message.id === pendingUser.messageId)
480
525
  ) {
481
526
  setPendingUser(null)
482
527
  }
483
528
  }, [pendingUser, threadId, savedMessages])
484
529
 
530
+ useEffect(() => {
531
+ if (threadId === null || !waitingEdit) return
532
+ setPendingUser((current) =>
533
+ current?.threadId === threadId ? current : waitingEditPending(threadId, waitingEdit)
534
+ )
535
+ }, [threadId, waitingEdit])
536
+
537
+ // An edit that waited and never became a message was set aside: withdrawn, or dropped once the
538
+ // message it replaced was gone. The conversation shows what the thread holds again.
539
+ useEffect(() => {
540
+ if (!pendingUser?.replacesMessageId || pendingUser.messageId === null) return
541
+ if (pendingUser.threadId !== threadId || pendingSend !== null) return
542
+ if (!inboxQuery.isSuccess || inboxQuery.isFetching || messagesQuery.isFetching) return
543
+
544
+ const waiting = inboxQuery.data.items.some((item) => item.messageId === pendingUser.messageId)
545
+ const saved = savedMessages.some((message) => message.id === pendingUser.messageId)
546
+ if (!waiting && !saved && activeRunId === null) setPendingUser(null)
547
+ }, [
548
+ pendingUser,
549
+ threadId,
550
+ pendingSend,
551
+ inboxQuery.isSuccess,
552
+ inboxQuery.isFetching,
553
+ inboxQuery.data,
554
+ messagesQuery.isFetching,
555
+ savedMessages,
556
+ activeRunId,
557
+ ])
558
+
485
559
  useEffect(() => {
486
560
  setSendError((current) => (current && current.threadId === threadId ? current : null))
561
+ setEditingMessage(null)
487
562
  }, [threadId])
488
563
 
489
564
  const createThread = useMutation(createAgentThreadMutation())
490
565
  const postMessage = useMutation(postAgentThreadMessageMutation())
566
+ const editThreadMessage = useMutation(editAgentThreadMessageMutation())
567
+ const withdrawInboxItem = useMutation(withdrawAgentThreadInboxItemMutation())
491
568
  const cancelRun = useMutation(cancelAgentRunMutation())
492
569
  const retryRun = useMutation(retryAgentRunMutation())
493
570
  const recreateSandbox = useMutation(recreateAgentThreadSandboxMutation())
494
571
  const restoreSandbox = useMutation(restoreAgentThreadSandboxMutation())
495
- const moveToCloud = useMutation(moveAgentThreadToCloudMutation())
496
572
  const stopBackgroundCommand = useMutation(stopAgentBackgroundCommandMutation())
497
573
  const decideApproval = useMutation(decideAgentApprovalMutation())
498
574
  // Each runs after the one before, so the last choice is the one the server keeps.
@@ -515,15 +591,28 @@ export function useAgentConversation({
515
591
  const approvalMode: AgentApprovalMode | undefined =
516
592
  chosenHere ?? (threadId !== null ? threadQuery.data?.approvalMode : defaultApprovalMode)
517
593
 
518
- const presentation = presentActiveTurn({
519
- activeRunId,
594
+ const activePending = pendingUser && pendingUser.threadId === threadId ? pendingUser : null
595
+ const visibleSavedMessages = useMemo(() => {
596
+ if (!activePending?.replacesMessageId) return savedMessages
597
+ const cut = savedMessages.findIndex((entry) => entry.id === activePending.replacesMessageId)
598
+ return cut === -1 ? savedMessages : savedMessages.slice(0, cut)
599
+ }, [activePending?.replacesMessageId, savedMessages])
600
+
601
+ // From Save until the thread holds the edited message: the turns it replaces, and any turn it
602
+ // stopped, are gone from the transcript.
603
+ const editInFlight = activePending?.replacesMessageId !== undefined
604
+ const basePresentation = presentActiveTurn({
605
+ activeRunId: editInFlight ? null : activeRunId,
520
606
  pendingRun,
521
- streamRun,
607
+ streamRun: editInFlight ? null : streamRun,
522
608
  live,
523
609
  runs,
524
- messages: savedMessages,
610
+ messages: visibleSavedMessages,
525
611
  messagesLoading: messagesQuery.isFetching,
526
612
  })
613
+ const presentation = editInFlight
614
+ ? ({ kind: "responding", queuedRun: null } as const)
615
+ : basePresentation
527
616
  const isRunning = presentation.kind === "responding"
528
617
  const waitingLonger = useExtendedWaitingStatus(
529
618
  presentation.kind === "responding" ? presentation.queuedRun : null
@@ -538,7 +627,13 @@ export function useAgentConversation({
538
627
  [pendingRun, streamRun, ...runs].find((run) => run !== null && run.id === activeRunId) ?? null
539
628
 
540
629
  const stop = () => {
541
- if (threadId === null || activeRunId === null || !canStop) return
630
+ if (threadId === null) return
631
+ // While an edit waits for the turn it stopped, Stop takes the edit back, to the editor.
632
+ if (waitingEdit && pendingUser?.messageId === waitingEdit.messageId) {
633
+ withdrawEdit(threadId, waitingEdit)
634
+ return
635
+ }
636
+ if (activeRunId === null || !canStop) return
542
637
  setStoppingRunId(activeRunId)
543
638
  cancelRun.mutate(
544
639
  { path: { threadId }, body: { runId: activeRunId } },
@@ -552,6 +647,31 @@ export function useAgentConversation({
552
647
  )
553
648
  }
554
649
 
650
+ const withdrawEdit = (targetThreadId: string, item: AgentInboxItem) => {
651
+ const edit = pendingUser
652
+ withdrawInboxItem.mutate(
653
+ { path: { threadId: targetThreadId, itemId: item.id } },
654
+ {
655
+ onSuccess: () => {
656
+ setPendingUser(null)
657
+ // The turn the edit stopped is still winding down: it shows as stopping.
658
+ if (activeRunId !== null) setStoppingRunId(activeRunId)
659
+ if (edit?.replacesMessageId) {
660
+ setEditingMessage((current) => ({
661
+ messageId: edit.replacesMessageId as string,
662
+ text: edit.text,
663
+ attachments: edit.attachments,
664
+ context: edit.context,
665
+ nonce: (current?.nonce ?? 0) + 1,
666
+ }))
667
+ }
668
+ },
669
+ // A turn already started from it: Stop again stops that turn.
670
+ onSettled: () => void refreshThread(targetThreadId),
671
+ }
672
+ )
673
+ }
674
+
555
675
  // The turn runs in the mode the chip shows, whatever another device chose since.
556
676
  const turnApprovalMode = approvalMode === undefined ? {} : { approvalMode }
557
677
 
@@ -573,6 +693,8 @@ export function useAgentConversation({
573
693
  : delivery
574
694
  setSendError(null)
575
695
  const targetThreadId = threadId
696
+ // What this message asks for, and what the thread it creates keeps pinned.
697
+ const selection = modelSelection.request
576
698
  const key = `sent:${++sentMessageCount}`
577
699
  let createdThreadId: string | null = null
578
700
  try {
@@ -593,7 +715,7 @@ export function useAgentConversation({
593
715
  postMessage.mutateAsync({
594
716
  path: { threadId: targetThreadId },
595
717
  body: {
596
- ...messageBody(text, attachments, context, modelSelection.request, settings),
718
+ ...messageBody(text, attachments, context, selection, settings),
597
719
  ...turnApprovalMode,
598
720
  ...(where === "auto" ? {} : { delivery: where }),
599
721
  },
@@ -657,7 +779,7 @@ export function useAgentConversation({
657
779
  postMessage.mutateAsync({
658
780
  path: { threadId: newThreadId },
659
781
  body: {
660
- ...messageBody(text, attachments, context, modelSelection.request, settings),
782
+ ...messageBody(text, attachments, context, selection, settings),
661
783
  ...turnApprovalMode,
662
784
  },
663
785
  })
@@ -666,7 +788,7 @@ export function useAgentConversation({
666
788
  // The next new conversation starts from the default again.
667
789
  setChosenApprovalMode((current) => (current?.threadId === null ? null : current))
668
790
  await queryClient.invalidateQueries({ queryKey: listAgentThreadsQueryKey() })
669
- showCreatedThread(createdThreadId)
791
+ showCreatedThread(createdThreadId, selection)
670
792
  } catch (error) {
671
793
  // Restore the exact submitted snapshot. In particular, do not re-read ambient page context:
672
794
  // navigation may have changed it while the request was in flight.
@@ -682,7 +804,7 @@ export function useAgentConversation({
682
804
  threadId: createdThreadId ?? targetThreadId,
683
805
  failure: sendFailure(error),
684
806
  })
685
- if (createdThreadId) showCreatedThread(createdThreadId)
807
+ if (createdThreadId) showCreatedThread(createdThreadId, selection)
686
808
 
687
809
  // A refusal can mean another turn holds the thread: read who asked for it, too.
688
810
  if (targetThreadId !== null) void refreshThread(targetThreadId)
@@ -690,9 +812,9 @@ export function useAgentConversation({
690
812
  }
691
813
  }
692
814
 
693
- // A model pinned before the thread existed stays pinned in it, from the moment it shows.
694
- const showCreatedThread = (createdThreadId: string) => {
695
- if (tiered && newThreadPin) pinModel(createdThreadId, newThreadPin)
815
+ // The model the first message ran on is pinned in the thread it created, from the moment it shows.
816
+ const showCreatedThread = (createdThreadId: string, pin: ModelPreference | undefined) => {
817
+ if (tiered && pin) pinModel(createdThreadId, pin)
696
818
  onThreadCreated(createdThreadId)
697
819
  }
698
820
 
@@ -872,22 +994,6 @@ export function useAgentConversation({
872
994
  }
873
995
  }
874
996
 
875
- const handleContinueInCloud = () => {
876
- if (!thread || thread.runsOn !== "computer" || access !== "owner") return
877
- moveToCloud.mutate(
878
- { path: { threadId: thread.id } },
879
- {
880
- onSuccess: (moved) => {
881
- queryClient.setQueryData(getAgentThreadQueryKey({ path: { threadId: moved.id } }), moved)
882
- void queryClient.invalidateQueries({
883
- queryKey: listAgentThreadRunsQueryKey({ path: { threadId: moved.id } }),
884
- })
885
- void refreshThreads()
886
- },
887
- }
888
- )
889
- }
890
-
891
997
  /** Recover the thread's sandbox as its owner chose: fresh, or as the failed save left it. */
892
998
  const recoverSandbox = (recovery: typeof recreateSandbox | typeof restoreSandbox) => {
893
999
  if (!thread?.sandboxState || isRunning || access !== "owner") return
@@ -924,15 +1030,11 @@ export function useAgentConversation({
924
1030
  /** Follow the project defaults again, including later changes to them; with tiers, Auto. */
925
1031
  const resetModelSelection = () => updateModelPreference(null)
926
1032
 
1033
+ /** The reader's choice: what a new conversation starts on, and the model pinned in this thread. */
927
1034
  const updateModelPreference = (preference: ModelPreference | null) => {
928
- if (!tiered) {
929
- setModelPreference(preference)
930
- writeModelPreference(preference)
931
- return
932
- }
933
-
934
- if (threadId === null) setNewThreadPin(preference)
935
- else pinModel(threadId, preference)
1035
+ setModelPreference(preference)
1036
+ writeModelPreference(preference)
1037
+ if (tiered && threadId !== null) pinModel(threadId, preference)
936
1038
  }
937
1039
 
938
1040
  // Start from the stored pins, so the ones another tab wrote since are kept.
@@ -942,21 +1044,18 @@ export function useAgentConversation({
942
1044
  writeModelPins(pins)
943
1045
  }
944
1046
 
945
- // Leaving a new conversation, or its first message creating the thread, ends its own pin.
946
- useEffect(() => {
947
- if (threadId !== null) setNewThreadPin(null)
948
- }, [threadId])
949
-
950
- // Another tab pinned a model, or went back to Auto.
1047
+ // Another tab chose a model, pinned one, or went back to Auto.
951
1048
  useEffect(() => {
952
1049
  const follow = (event: StorageEvent) => {
953
1050
  if (event.key === MODEL_PINS_KEY) setModelPins(readModelPins() ?? {})
1051
+ if (event.key === MODEL_PREFERENCE_KEY) setModelPreference(readModelPreference())
954
1052
  }
955
1053
  window.addEventListener("storage", follow)
956
1054
  return () => window.removeEventListener("storage", follow)
957
1055
  }, [])
958
1056
 
959
1057
  const sandboxRecovery =
1058
+ thread?.runsOn !== "computer" &&
960
1059
  thread?.sandboxState &&
961
1060
  !isRunning &&
962
1061
  ["busy", "blocked", "unavailable"].includes(thread.sandboxState.status)
@@ -974,7 +1073,8 @@ export function useAgentConversation({
974
1073
  const anchorCurrentTurn = Boolean(
975
1074
  (pendingUser && pendingUser.threadId === threadId) || (pendingRun && pendingSend?.anchor)
976
1075
  )
977
- const composerPending = postMessage.isPending || createThread.isPending || resolvingPlace
1076
+ const composerPending =
1077
+ postMessage.isPending || editThreadMessage.isPending || createThread.isPending || resolvingPlace
978
1078
  const currentSendError: AgentConversationSendError | null =
979
1079
  sendError && sendError.threadId === threadId
980
1080
  ? sendError.failure === "busy"
@@ -995,6 +1095,7 @@ export function useAgentConversation({
995
1095
  // A turn that never answered can run again, by whoever asked for it, once the sandbox works,
996
1096
  // unless it would fail the same way: a conversation too long for its model.
997
1097
  const canRetry =
1098
+ !(access === "participant" && thread?.runsOn === "computer") &&
998
1099
  !sandboxRecovery &&
999
1100
  ((presentation.kind === "failed" && presentation.run.error?.code !== CONTEXT_LIMIT_EXCEEDED) ||
1000
1101
  ((presentation.kind === "timeout" || presentation.kind === "interrupted") &&
@@ -1032,13 +1133,162 @@ export function useAgentConversation({
1032
1133
  authors,
1033
1134
  thread,
1034
1135
  reader,
1035
- pending: pendingUser && pendingUser.threadId === threadId ? pendingUser : null,
1136
+ pending: activePending,
1036
1137
  sentKeys,
1037
1138
  runs,
1038
1139
  live,
1039
1140
  presentation,
1040
1141
  })
1041
1142
 
1143
+ const editableMessageIds = useMemo((): ReadonlySet<string> => {
1144
+ if (
1145
+ threadId === null ||
1146
+ sandboxRecovery ||
1147
+ editInFlight ||
1148
+ (thread?.runsOn === "computer" && access !== "owner") ||
1149
+ (isRunning && !canStop)
1150
+ ) {
1151
+ return new Set()
1152
+ }
1153
+ // An edit takes back whole turns: a message a turn read while it answered, as a steer, sits
1154
+ // inside that turn, which started at an earlier message.
1155
+ const indexOf = new Map(messages.map((entry, index) => [entry.id, index]))
1156
+ const turnStart = new Map(runs.map((run) => [run.id, indexOf.get(run.triggerMessageId)]))
1157
+ let earliestTurnAfter = Number.POSITIVE_INFINITY
1158
+
1159
+ const allowed = new Set<string>()
1160
+ let seenOtherUser = false
1161
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
1162
+ const entry = messages[index]
1163
+ if (!entry) continue
1164
+
1165
+ if (entry.role === "assistant" && entry.runId !== null) {
1166
+ const start = turnStart.get(entry.runId)
1167
+ if (start !== undefined) earliestTurnAfter = Math.min(earliestTurnAfter, start)
1168
+ }
1169
+ if (entry.role !== "user") continue
1170
+
1171
+ const ownMessage = !user || !entry.author || entry.author.isReader
1172
+ const insideTurn = earliestTurnAfter < index
1173
+ if (
1174
+ entry.id !== null &&
1175
+ entry.status === "complete" &&
1176
+ ownMessage &&
1177
+ !insideTurn &&
1178
+ (access === "owner" || !seenOtherUser)
1179
+ ) {
1180
+ allowed.add(entry.id)
1181
+ }
1182
+ if (!ownMessage) seenOtherUser = true
1183
+ }
1184
+ return allowed
1185
+ }, [
1186
+ threadId,
1187
+ sandboxRecovery,
1188
+ editInFlight,
1189
+ thread?.runsOn,
1190
+ access,
1191
+ isRunning,
1192
+ canStop,
1193
+ messages,
1194
+ runs,
1195
+ user,
1196
+ ])
1197
+
1198
+ const startEditMessage = useCallback(
1199
+ (messageId: string) => {
1200
+ if (!editableMessageIds.has(messageId)) return
1201
+ const target = messages.find((entry) => entry.id === messageId && entry.role === "user")
1202
+ if (!target) return
1203
+ const text = target.parts
1204
+ .map((part) => (part.type === "text" ? part.text : ""))
1205
+ .join("")
1206
+ .trim()
1207
+ const attachments = target.parts.flatMap((part) =>
1208
+ part.type === "file" ? [part.fileRef] : []
1209
+ )
1210
+ setEditingMessage((current) => ({
1211
+ messageId,
1212
+ text,
1213
+ attachments,
1214
+ context: target.context,
1215
+ nonce: (current?.nonce ?? 0) + 1,
1216
+ }))
1217
+ },
1218
+ [editableMessageIds, messages]
1219
+ )
1220
+
1221
+ const cancelEditMessage = useCallback(() => {
1222
+ setEditingMessage(null)
1223
+ }, [])
1224
+
1225
+ /**
1226
+ * Replace an earlier message and take the conversation back to it. A turn still answering stops
1227
+ * first: the server holds the edit until that turn ends, then rewinds. Meanwhile the transcript
1228
+ * shows the edit in place of the message, with the turns after it gone.
1229
+ */
1230
+ const editMessage = async (
1231
+ messageId: string,
1232
+ text: string,
1233
+ attachments: readonly AgentFileRef[],
1234
+ context: readonly AgentContextEntryInput[]
1235
+ ) => {
1236
+ const targetThreadId = threadId
1237
+ if (targetThreadId === null || !editableMessageIds.has(messageId)) return
1238
+
1239
+ setSendError(null)
1240
+ setEditingMessage(null)
1241
+ const key =
1242
+ messages.find((entry) => entry.id === messageId)?.key ?? `sent:${++sentMessageCount}`
1243
+ setPendingUser({
1244
+ key,
1245
+ threadId: targetThreadId,
1246
+ text,
1247
+ attachments,
1248
+ context,
1249
+ messageId: null,
1250
+ replacesMessageId: messageId,
1251
+ })
1252
+
1253
+ try {
1254
+ const response = await sendWithRequesterSettings((settings) =>
1255
+ editThreadMessage.mutateAsync({
1256
+ path: { threadId: targetThreadId, messageId },
1257
+ body: {
1258
+ ...messageBody(text, attachments, context, modelSelection.request, settings),
1259
+ ...turnApprovalMode,
1260
+ },
1261
+ })
1262
+ )
1263
+
1264
+ if (response.run) {
1265
+ recordAcceptedSend(response.run, key)
1266
+ } else if (response.item) {
1267
+ // It waits for the turn it stopped: its message takes this id once that turn ends.
1268
+ const waitingId = response.item.messageId
1269
+ setPendingUser((current) =>
1270
+ current && current.key === key ? { ...current, messageId: waitingId } : current
1271
+ )
1272
+ }
1273
+ await refreshThread(targetThreadId)
1274
+ } catch (error) {
1275
+ setPendingUser(null)
1276
+ setEditingMessage((current) => ({
1277
+ messageId,
1278
+ text,
1279
+ attachments,
1280
+ context,
1281
+ nonce: (current?.nonce ?? 0) + 1,
1282
+ error: editFailureMessage(
1283
+ editFailure(error),
1284
+ requestedBySomeoneElse(activeRun, user),
1285
+ labels
1286
+ ),
1287
+ }))
1288
+ void refreshThread(targetThreadId)
1289
+ }
1290
+ }
1291
+
1042
1292
  const answeringAuthor = useMemo(
1043
1293
  () =>
1044
1294
  answeringFor
@@ -1052,7 +1302,10 @@ export function useAgentConversation({
1052
1302
  [answeringFor, answeringForName]
1053
1303
  )
1054
1304
  const continuingHere = continuingThreadId !== null && continuingThreadId === threadId
1055
- const waitingForComputer = computerOffline ? (thread?.computer?.name ?? null) : null
1305
+ const waitingForComputer =
1306
+ computerOffline && thread?.computer
1307
+ ? agentMessages.computer.placeOn(folderName(thread.computer.folder), thread.computer.name)
1308
+ : null
1056
1309
  const streamReconnecting = live.active && reconnecting
1057
1310
  const nextTurn = conversationTurn({
1058
1311
  presentation,
@@ -1138,27 +1391,40 @@ export function useAgentConversation({
1138
1391
  [runs, access, user]
1139
1392
  )
1140
1393
 
1141
- // Where the conversation moved, after the last message saved before then: the files earlier
1142
- // turns worked on stayed behind.
1143
- const movedAt = thread?.movedAt
1144
- const savedBefore = movedAt
1145
- ? new Set(savedMessages.filter((saved) => saved.createdAt <= movedAt).map(({ id }) => id))
1146
- : null
1147
- // The last one the transcript shows: not every saved message is drawn.
1148
- const movedAfterId =
1149
- savedBefore && messages.filter(({ id }) => id !== null && savedBefore.has(id)).at(-1)?.id
1150
- const moved =
1151
- thread && movedAfterId
1152
- ? {
1153
- afterMessageId: movedAfterId,
1154
- label:
1155
- thread.runsOn !== "computer"
1156
- ? agentMessages.computer.movedToCloud
1157
- : thread.computer
1158
- ? agentMessages.computer.movedToFolder(shownFolder(thread.computer.folder))
1159
- : agentMessages.computer.movedElsewhere,
1160
- }
1161
- : null
1394
+ // The names of the reader's computers, where they're already known: a run keeps only the id.
1395
+ const listedComputers = useQuery({ ...listAgentComputersOptions(), enabled: false }).data
1396
+ const computerNames = useMemo(() => {
1397
+ const names = new Map(
1398
+ (listedComputers?.computers ?? []).map((computer) => [computer.id, computer.name])
1399
+ )
1400
+ if (thread?.computer) names.set(thread.computer.id, thread.computer.name)
1401
+ return names
1402
+ }, [listedComputers, thread?.computer])
1403
+
1404
+ // Where the conversation moved, at every turn that ran elsewhere than the one before and where it
1405
+ // runs now: the files earlier turns worked on stayed behind.
1406
+ const { moved, moves } = useMemo(
1407
+ () =>
1408
+ transcriptMoves({
1409
+ thread,
1410
+ savedMessages,
1411
+ shownIds: new Set(messages.flatMap((message) => (message.id !== null ? [message.id] : []))),
1412
+ runs,
1413
+ messages: agentMessages.computer,
1414
+ computerNames,
1415
+ ownerName: thread && access === "participant" ? personName(threadOwner(thread)) : null,
1416
+ }),
1417
+ [access, agentMessages.computer, computerNames, messages, runs, savedMessages, thread]
1418
+ )
1419
+
1420
+ const hasPendingApprovals =
1421
+ isAwaitingApproval(latestRun) &&
1422
+ approvals.some((approval) => approval.status === "pending" && approval.runId === latestRun?.id)
1423
+ // A computer's conversation moves with a turn still queued for it; the cloud's, once none is.
1424
+ const replyRunning = thread?.runsOn === "computer" ? activeRun?.status === "running" : isRunning
1425
+ const placeBusy = hasPendingApprovals ? "approval" : replyRunning ? "running" : null
1426
+ const messageWaiting = thread?.runsOn === "computer" && activeRun?.status === "queued"
1427
+ const place = useThreadPlace({ thread, access, busy: placeBusy, waiting: messageWaiting })
1162
1428
 
1163
1429
  // Its background commands: what its owner's sixb reports of them, and their Stop, to its owner
1164
1430
  // alone, as the computer is theirs. A command started in a folder runs on there once the thread
@@ -1201,6 +1467,7 @@ export function useAgentConversation({
1201
1467
  resetReasoning,
1202
1468
  resetModelSelection,
1203
1469
  setApprovalMode,
1470
+ editMessage,
1204
1471
  })
1205
1472
  actionsRef.current = {
1206
1473
  send,
@@ -1212,6 +1479,7 @@ export function useAgentConversation({
1212
1479
  resetReasoning,
1213
1480
  resetModelSelection,
1214
1481
  setApprovalMode,
1482
+ editMessage,
1215
1483
  }
1216
1484
  const stableSend = useCallback<ComposerProps["onSend"]>(
1217
1485
  (text, attachments, context, delivery) =>
@@ -1235,6 +1503,11 @@ export function useAgentConversation({
1235
1503
  (mode: AgentApprovalMode) => actionsRef.current.setApprovalMode(mode),
1236
1504
  []
1237
1505
  )
1506
+ const stableSubmitEdit = useCallback<NonNullable<TranscriptProps["onSubmitEditMessage"]>>(
1507
+ (messageId, text, attachments, context) =>
1508
+ void actionsRef.current.editMessage(messageId, text, attachments, context),
1509
+ []
1510
+ )
1238
1511
  const stableAnswerQuestion = useCallback(
1239
1512
  (text: string) => void actionsRef.current.send(text, [], []),
1240
1513
  []
@@ -1272,10 +1545,16 @@ export function useAgentConversation({
1272
1545
  threadId,
1273
1546
  messages,
1274
1547
  moved: stableMoved,
1548
+ moves,
1275
1549
  turn,
1276
1550
  anchorCurrentTurn,
1277
1551
  onRetry: canRetry ? stableRetry : undefined,
1278
1552
  onContinue: canContinue ? stableContinue : undefined,
1553
+ editableMessageIds,
1554
+ editingMessage,
1555
+ onStartEditMessage: startEditMessage,
1556
+ onCancelEditMessage: cancelEditMessage,
1557
+ onSubmitEditMessage: stableSubmitEdit,
1279
1558
  approvals: transcriptApprovals,
1280
1559
  approvalOutcomes,
1281
1560
  delegation: transcriptDelegation,
@@ -1285,12 +1564,18 @@ export function useAgentConversation({
1285
1564
  threadId,
1286
1565
  messages,
1287
1566
  stableMoved,
1567
+ moves,
1288
1568
  turn,
1289
1569
  anchorCurrentTurn,
1290
1570
  canRetry,
1291
1571
  stableRetry,
1292
1572
  canContinue,
1293
1573
  stableContinue,
1574
+ editableMessageIds,
1575
+ editingMessage,
1576
+ startEditMessage,
1577
+ cancelEditMessage,
1578
+ stableSubmitEdit,
1294
1579
  transcriptApprovals,
1295
1580
  approvalOutcomes,
1296
1581
  transcriptDelegation,
@@ -1402,27 +1687,25 @@ export function useAgentConversation({
1402
1687
  [threadId, steerable, readMessageIds]
1403
1688
  )
1404
1689
 
1405
- const movingThisThread = moveToCloud.variables?.path.threadId === thread?.id
1406
- const computerNoticeProps: ComputerOfflineNoticeProps | null = computerOffline
1407
- ? {
1408
- computer: thread?.computer ?? null,
1409
- // One mutation serves every conversation this view opens: only this one's state shows.
1410
- pending: movingThisThread && moveToCloud.isPending,
1411
- error:
1412
- !movingThisThread || !moveToCloud.isError
1413
- ? null
1414
- : isSixbApiError(moveToCloud.error) && moveToCloud.error.code === "active_run_exists"
1415
- ? "busy"
1416
- : "failed",
1417
- onContinueInCloud: handleContinueInCloud,
1418
- ...(desktopComputer && thread?.computer && thread.computer.id === desktopComputerId
1419
- ? {
1420
- onRunHere: () =>
1421
- void desktopComputer.allowFolder(thread.computer?.folder ?? "").catch(() => {}),
1422
- }
1423
- : {}),
1424
- }
1425
- : null
1690
+ // The header's move to the cloud, from the notice: one move, one state, wherever it's asked.
1691
+ const computerNoticeProps: ComputerOfflineNoticeProps | null =
1692
+ computerOffline && place
1693
+ ? {
1694
+ computer: thread?.computer ?? null,
1695
+ waiting: messageWaiting,
1696
+ pending: place.movingTo === "cloud",
1697
+ moving: place.pending,
1698
+ busy: place.busy,
1699
+ error: place.cloudError,
1700
+ onContinueInCloud: place.moveToCloud,
1701
+ ...(desktopComputer && thread?.computer && thread.computer.id === desktopComputerId
1702
+ ? {
1703
+ onRunHere: () =>
1704
+ void desktopComputer.allowFolder(thread.computer?.folder ?? "").catch(() => {}),
1705
+ }
1706
+ : {}),
1707
+ }
1708
+ : null
1426
1709
 
1427
1710
  const sandboxRecoveryProps: SandboxRecoveryProps | null = sandboxRecovery
1428
1711
  ? {
@@ -1439,6 +1722,13 @@ export function useAgentConversation({
1439
1722
  },
1440
1723
  }
1441
1724
  : {}),
1725
+ // A turn paused for an approval, or cut short by a limit, also succeeds: it has no answer.
1726
+ answered:
1727
+ latestRun?.status === "succeeded" &&
1728
+ latestRun.finishReason === "stop" &&
1729
+ (latestRun.diagnostics ?? []).some(
1730
+ (diagnostic) => diagnostic.code === "workspace_not_saved"
1731
+ ),
1442
1732
  canRecreate: access === "owner",
1443
1733
  owner: thread ? personName(threadOwner(thread)) : "",
1444
1734
  }
@@ -1488,6 +1778,14 @@ export function useAgentConversation({
1488
1778
  draftReseed,
1489
1779
  composerPending,
1490
1780
  send,
1781
+ /** Saved user message ids the reader may edit in place. */
1782
+ editableMessageIds,
1783
+ /** The message currently open in the inline editor, or null. */
1784
+ editingMessage,
1785
+ startEditMessage,
1786
+ cancelEditMessage,
1787
+ /** Edit an earlier user message in place and restart the thread from there. */
1788
+ editMessage,
1491
1789
  /** Stop the answer in flight, when `turn.canStop`. */
1492
1790
  stop,
1493
1791
  /** Run again the turn that never answered, when `turn.canRetry`. */
@@ -1521,6 +1819,8 @@ export function useAgentConversation({
1521
1819
  pendingProps,
1522
1820
  /** Spread into `<SandboxRecovery>` while set: the composer stays disabled until it is resolved. */
1523
1821
  sandboxRecoveryProps,
1822
+ /** Where the reader's own conversation runs, and how to switch it between cloud and computer. */
1823
+ place,
1524
1824
  /** Where the reader's own conversation runs on their computer, for its badge. */
1525
1825
  computer: access === "owner" ? (thread?.computer ?? null) : null,
1526
1826
  /** Spread into `<ComputerOfflineNotice>` while its computer is offline. */
@@ -1560,6 +1860,53 @@ function sendFailure(error: unknown): TurnFailure {
1560
1860
  return "send"
1561
1861
  }
1562
1862
 
1863
+ function editFailure(error: unknown): TurnFailure {
1864
+ if (error instanceof ComputerUnavailableError) return "computer"
1865
+ if (!isSixbApiError(error)) return "edit"
1866
+ // Someone else's answer runs, which only they or the thread's owner may stop.
1867
+ if (error.status === 403 && error.code === "not_run_requester") return "busy"
1868
+ if (error.status !== 409) return "edit"
1869
+ if (error.code === "active_run_exists") return "busy"
1870
+ if (error.code === "sandbox_execution_unavailable") return "sandbox"
1871
+
1872
+ return "edit"
1873
+ }
1874
+
1875
+ /** Why an edit did not go through, in words about the edit, said under the editor. */
1876
+ function editFailureMessage(
1877
+ failure: TurnFailure,
1878
+ someoneElse: boolean,
1879
+ labels: ReturnType<typeof useAgentMessages>["chat"]
1880
+ ): string {
1881
+ switch (failure) {
1882
+ case "busy":
1883
+ return someoneElse ? labels.editBusyOther : labels.editBusy
1884
+ case "sandbox":
1885
+ return labels.sandboxUnavailable
1886
+ case "computer":
1887
+ return labels.computerUnavailable
1888
+ default:
1889
+ return labels.editFailed
1890
+ }
1891
+ }
1892
+
1893
+ /** The edit a waiting inbox item holds, as the transcript shows one just saved. */
1894
+ function waitingEditPending(threadId: string, item: AgentInboxItem): PendingUserMessage {
1895
+ return {
1896
+ key: `edit:${item.id}`,
1897
+ threadId,
1898
+ text: item.parts.map((part) => (part.type === "text" ? part.text : "")).join(""),
1899
+ attachments: item.parts.flatMap((part) => (part.type === "file" ? [part.fileRef] : [])),
1900
+ context: item.parts.flatMap((part) =>
1901
+ part.type === "context"
1902
+ ? [{ context: part.context as AgentContextInput, origin: part.origin }]
1903
+ : []
1904
+ ),
1905
+ messageId: item.messageId,
1906
+ ...(item.replacesMessageId === undefined ? {} : { replacesMessageId: item.replacesMessageId }),
1907
+ }
1908
+ }
1909
+
1563
1910
  /**
1564
1911
  * Said once the thread is read again, so a busy thread names whose answer holds it when the reader
1565
1912
  * can tell.
@@ -1576,6 +1923,8 @@ function failureMessage(
1576
1923
  return labels.sandboxUnavailable
1577
1924
  case "computer":
1578
1925
  return labels.computerUnavailable
1926
+ case "edit":
1927
+ return labels.editFailed
1579
1928
  case "retry":
1580
1929
  return labels.retryFailed
1581
1930
  case "stop":