Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
c920082
fix(mothership): bound replay frames and end refused turns instead of…
waleedlatif1 Sep 30, 2026
38cc7f9
fix(mothership): render stream-omitted tool values honestly
waleedlatif1 Sep 30, 2026
a0fe73f
refactor(mothership): replace replay compaction with one string-trunc…
waleedlatif1 Sep 30, 2026
9b4f7c8
fix(mothership): stop stale approval cards, raw backend bodies, and e…
waleedlatif1 Sep 30, 2026
9491b14
fix(mothership): never forward an approval stamp on a frame that cann…
waleedlatif1 Sep 30, 2026
bafd6aa
fix(mothership): keep retrying an unreachable worker through a task r…
waleedlatif1 Sep 30, 2026
61388bf
fix(mothership): settle runs whose terminal events fail, and tighten …
waleedlatif1 Sep 30, 2026
7fc6db9
fix(mothership): settle tool rows left unfinished by any finished turn
waleedlatif1 Sep 30, 2026
177ac84
fix(mothership): harden replay compaction, stream retries, teardown, …
waleedlatif1 Sep 30, 2026
89977d0
fix(mothership): separate retry budgets, cap preview totals, and clea…
waleedlatif1 Sep 30, 2026
55386c0
fix(mothership): clean up turns whose terminal publish failed and cap…
waleedlatif1 Sep 30, 2026
a4debbf
fix(mothership): bound preview frames per write and per turn, and nar…
waleedlatif1 Sep 30, 2026
77e7e4a
fix(mothership): omit the largest field of an event no cut can bound,…
waleedlatif1 Sep 30, 2026
7989cdf
fix(mothership): keep sibling fields when omitting bulk, and never ca…
waleedlatif1 Sep 30, 2026
fc2149c
fix(mothership): keep omitting bulk until an event fits one replay write
waleedlatif1 Sep 30, 2026
7aa6002
fix(mothership): shed oversized replay events in one pass and retry m…
waleedlatif1 Sep 30, 2026
aea7ed0
refactor(mothership): tidy replay compaction and stream retry after r…
waleedlatif1 Sep 30, 2026
77dedc2
fix(mothership): bound preview metadata frames and settle stopped row…
waleedlatif1 Sep 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/sim/app/api/copilot/confirm/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ import {
retainSealedClientToolContext,
sealClientToolCompletion,
} from '@/lib/mothership/request/tools/client-completion-seal.server'
import { isWorkflowToolName } from '@/lib/mothership/tools/client-executed-tools'
import {
createStructuralWorkflowToolCompletionData,
getWorkflowToolCompletionExecutionId,
getWorkflowToolCompletionMessage,
getWorkflowToolConfirmationStatus,
getWorkflowToolLaunchError,
isWorkflowToolName,
resolveWorkflowToolTargetId,
WORKFLOW_EXECUTION_BUSY,
type WorkflowToolLaunchError,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest'
import type { PersistedMessage } from '@/lib/mothership/chat/persisted-message'
import { markMessageStopped } from '@/app/workspace/[workspaceId]/home/hooks/message-reconcile'

describe('markMessageStopped', () => {
it.each(['executing', 'pending', 'awaiting_approval'] as const)(
'settles a %s tool row as stopped',
(state) => {
const message: PersistedMessage = {
id: 'assistant-1',
role: 'assistant',
content: '',
timestamp: '2026-09-29T00:00:00.000Z',
contentBlocks: [
{
type: 'tool',
endedAt: 1,
toolCall: { id: 'call-1', name: 'gmail_read_v2', state },
},
],
}

const stopped = markMessageStopped(message)

expect(stopped.contentBlocks?.[0].toolCall?.state).toBe('cancelled')
}
)
})
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
import { isBrowserToolName } from '@sim/browser-protocol'
import type { PersistedContentBlock } from '@/lib/api/contracts/copilot-messages'
import type { PersistedMessage } from '@/lib/mothership/chat/persisted-message'
import { normalizeMessage, withBlockTiming } from '@/lib/mothership/chat/persisted-message'
import {
isUnsettledToolState,
normalizeMessage,
withBlockTiming,
} from '@/lib/mothership/chat/persisted-message'
import {
MothershipStreamV1CompletionStatus,
MothershipStreamV1EventType,
Expand All @@ -18,7 +22,7 @@ import {
MothershipStreamV1ToolPhase,
} from '@/lib/mothership/generated/mothership-stream-v1'
import type { StreamBatchEvent } from '@/lib/mothership/request/session/types'
import { isWorkflowToolName } from '@/lib/mothership/tools/workflow-tools'
import { isWorkflowToolName } from '@/lib/mothership/tools/client-executed-tools'
import type { ContentBlock } from '@/app/workspace/[workspaceId]/home/types'
import type { MothershipChatHistory } from '@/hooks/queries/mothership-chats'
import { isZeroStreamCursor } from './stream-protocol'
Expand Down Expand Up @@ -142,18 +146,18 @@ export function buildAssistantSnapshotMessage(params: {
}

export function markMessageStopped(message: PersistedMessage): PersistedMessage {
const hasExecutingTool = message.contentBlocks?.some(
(block) => block.toolCall?.state === 'executing'
const hasUnsettledTool = message.contentBlocks?.some((block) =>
isUnsettledToolState(block.toolCall?.state)
)
const hasOpenBlock = message.contentBlocks?.some((block) => block.endedAt === undefined)
if (!hasExecutingTool && !hasOpenBlock) {
if (!hasUnsettledTool && !hasOpenBlock) {
return message
}

const stopTs = Date.now()
const nextBlocks = (message.contentBlocks ?? []).map((block) => {
const stamped = block.endedAt === undefined ? { ...block, endedAt: stopTs } : block
if (stamped.toolCall?.state !== 'executing') {
if (!stamped.toolCall || !isUnsettledToolState(stamped.toolCall.state)) {
return stamped
}
return {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest'
import type { FilePreviewSession } from '@/lib/mothership/request/session'
import { deriveFilePreviewSession } from './apply-file-preview-phase'
import {
deriveFilePreviewSession,
previewHoldsFinalContent,
} from '@/app/workspace/[workspaceId]/home/hooks/preview/apply-file-preview-phase'

const NOW = '2026-06-08T00:00:00.000Z'

Expand Down Expand Up @@ -94,3 +97,40 @@ describe('deriveFilePreviewSession', () => {
expect(third?.previewText).toBe('ABC')
})
})

describe('previewHoldsFinalContent', () => {
const complete = (previewVersion?: number) => ({
previewPhase: 'file_preview_complete' as const,
toolCallId: 'tool-1',
toolName: 'prepare_file_edit' as const,
...(previewVersion !== undefined ? { previewVersion } : {}),
})

it('holds the final content when the last content received is the completed version', () => {
const prev = session({ previewText: 'final text', previewVersion: 7 })

expect(previewHoldsFinalContent(prev, complete(7))).toBe(true)
})

it('does not hold it when later versions were never received, so the stored file must load', () => {
const prev = session({ previewText: 'an earlier draft', previewVersion: 5 })

expect(previewHoldsFinalContent(prev, complete(7))).toBe(false)
})

it('does not hold it when no content was received at all', () => {
expect(previewHoldsFinalContent(undefined, complete(7))).toBe(false)
})

it('does not hold it when the session exists but received no text', () => {
const prev = session({ previewText: '', previewVersion: 7 })

expect(previewHoldsFinalContent(prev, complete(7))).toBe(false)
})

it('holds the received text when the completion carries no version to compare', () => {
const prev = session({ previewText: 'final text', previewVersion: 3 })

expect(previewHoldsFinalContent(prev, complete())).toBe(true)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,17 @@ export function deriveFilePreviewSession(
}
}
}

/**
* Whether the preview text the client holds is the edit's final content. The
* server skips a content frame too large for the stream, so a completion whose
* version is newer than the last content received means the text is an earlier
* draft, and only the stored file is the saved result.
*/
export function previewHoldsFinalContent(
prev: FilePreviewSession | undefined,
completion: Extract<SyntheticFilePreviewPayload, { previewPhase: 'file_preview_complete' }>
): boolean {
if (!prev || prev.previewText.length === 0) return false
return completion.previewVersion === undefined || prev.previewVersion >= completion.previewVersion
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ import { useQueryClient } from '@tanstack/react-query'
import type { SyntheticFilePreviewPayload } from '@/lib/mothership/request/session'
import type { FilePreviewSession } from '@/lib/mothership/request/session/file-preview-session-contract'
import { invalidateResourceQueries } from '@/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-registry'
import { deriveFilePreviewSession } from '@/app/workspace/[workspaceId]/home/hooks/preview/apply-file-preview-phase'
import {
deriveFilePreviewSession,
previewHoldsFinalContent,
} from '@/app/workspace/[workspaceId]/home/hooks/preview/apply-file-preview-phase'
import {
buildCompletedPreviewSessions,
type FilePreviewSessionsState,
Expand Down Expand Up @@ -381,7 +384,7 @@ export function useFilePreviewController({
sessionId: nextSession.id,
suppressActivation: !shouldActivateOnComplete,
})
if (hasRenderableFilePreviewContent(nextSession)) {
if (previewHoldsFinalContent(prevSession, payload)) {
seedCompletedPreviewContentCache(fileId, nextSession.previewText)
}
if (workspaceId) invalidateResourceQueries(queryClient, workspaceId, 'file', fileId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ vi.mock('@/lib/mothership/resources/extraction', () => ({
isResourceToolName: vi.fn(() => false),
extractResourcesFromToolResult: vi.fn(() => []),
}))
vi.mock('@/lib/mothership/tools/workflow-tools', () => ({
isWorkflowToolName: vi.fn(() => false),
}))
vi.mock(
'@/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-registry',
() => ({ invalidateResourceQueries: vi.fn() })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ import {
extractResourcesFromToolResult,
isResourceToolName,
} from '@/lib/mothership/resources/extraction'
import { isNativeFileTool, isUserLocalVfsToolCall } from '@/lib/mothership/tools/local-filesystem'
import { isWorkflowToolName } from '@/lib/mothership/tools/workflow-tools'
import {
isClientExecutedToolCall,
isWorkflowToolName,
} from '@/lib/mothership/tools/client-executed-tools'
import { invalidateResourceQueries } from '@/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-registry'
import type { StreamLoopContext } from '@/app/workspace/[workspaceId]/home/hooks/stream/stream-context'
import {
Expand Down Expand Up @@ -188,56 +190,23 @@ export function handleToolEvent(ctx: StreamLoopContext, parsed: ToolEvent): void
const name = payload.toolName
const isPartial =
payload.partial === true || payload.status === MothershipStreamV1ToolStatus.generating
if (isWorkflowToolName(name) && !isPartial) {
const shouldStartWorkflowTool =
!deps.options.suppressedWorkflowToolStartIds?.has(rawId) &&
node?.kind === 'tool' &&
node.status === 'running' &&
!node.result
if (shouldStartWorkflowTool) {
const args = payload.arguments as Record<string, unknown> | undefined
const args = payload.arguments as Record<string, unknown> | undefined
const shouldStartClientTool =
isClientExecutedToolCall(name, args) &&
!isPartial &&
!deps.options.suppressedWorkflowToolStartIds?.has(rawId) &&
node?.kind === 'tool' &&
node.status === 'running' &&
!node.result
if (shouldStartClientTool) {
if (isWorkflowToolName(name)) {
deps.startClientWorkflowTool(rawId, name, args ?? {})
}
}
const localFilesystemArgs = payload.arguments as Record<string, unknown> | undefined
if ((isNativeFileTool(name) || isUserLocalVfsToolCall(name, localFilesystemArgs)) && !isPartial) {
const shouldStartLocalFilesystemTool =
!deps.options.suppressedWorkflowToolStartIds?.has(rawId) &&
node?.kind === 'tool' &&
node.status === 'running' &&
!node.result
if (shouldStartLocalFilesystemTool) {
deps.startClientLocalFilesystemTool(rawId, name, localFilesystemArgs ?? {})
}
}
if (isCurrentBrowserToolName(name) && !isPartial) {
const shouldStartBrowserTool =
!deps.options.suppressedWorkflowToolStartIds?.has(rawId) &&
node?.kind === 'tool' &&
node.status === 'running' &&
!node.result
if (shouldStartBrowserTool) {
deps.startClientBrowserTool(
rawId,
name,
(payload.arguments as Record<string, unknown> | undefined) ?? {},
parsed.ts
)
}
}
if (isTerminalToolName(name) && !isPartial) {
const shouldStartTerminalTool =
!deps.options.suppressedWorkflowToolStartIds?.has(rawId) &&
node?.kind === 'tool' &&
node.status === 'running' &&
!node.result
if (shouldStartTerminalTool) {
deps.startClientTerminalTool(
rawId,
name,
(payload.arguments as Record<string, unknown> | undefined) ?? {},
parsed.ts
)
} else if (isCurrentBrowserToolName(name)) {
deps.startClientBrowserTool(rawId, name, args ?? {}, parsed.ts)
} else if (isTerminalToolName(name)) {
deps.startClientTerminalTool(rawId, name, args ?? {}, parsed.ts)
} else {
deps.startClientLocalFilesystemTool(rawId, name, args ?? {})
}
}
ops.flush()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest'
import { finalizeResidualToolCalls } from '@/app/workspace/[workspaceId]/home/hooks/stream/stream-helpers'
import type { ContentBlock } from '@/app/workspace/[workspaceId]/home/types'

describe('finalizeResidualToolCalls', () => {
it.each(['executing', 'awaiting_approval'] as const)(
'settles a %s tool row with the turn outcome on Stop',
(status) => {
const blocks: ContentBlock[] = [
{ type: 'tool_call', toolCall: { id: 'call-1', name: 'gmail_read_v2', status } },
]

finalizeResidualToolCalls(blocks, 'cancelled')

expect(blocks[0].toolCall?.status).toBe('cancelled')
}
)

it('reports whether any tool row was left to settle', () => {
const open: ContentBlock[] = [
{ type: 'tool_call', toolCall: { id: 'call-1', name: 'read', status: 'awaiting_approval' } },
]
const settled: ContentBlock[] = [
{ type: 'tool_call', toolCall: { id: 'call-2', name: 'read', status: 'success' } },
]

expect(finalizeResidualToolCalls(open, 'error')).toBe(true)
expect(finalizeResidualToolCalls(settled, 'error')).toBe(false)
})

it('reports closing an open subagent lane as a change to persist', () => {
const blocks: ContentBlock[] = [{ type: 'subagent', content: 'research' }]

expect(finalizeResidualToolCalls(blocks, 'error')).toBe(true)
expect(blocks[0].endedAt).toEqual(expect.any(Number))
})
})
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createLogger } from '@sim/logger'
import { isRecordLike } from '@sim/utils/object'
import { isUnsettledToolState } from '@/lib/mothership/chat/persisted-message'
import {
CallIntegrationTool,
CreateEmptyFile,
Expand Down Expand Up @@ -68,17 +69,17 @@ export function asPayloadRecord(value: unknown): StreamPayload | undefined {
}

/**
* Settles any tool row still `executing` at a turn terminal by propagating the
* turn's outcome — the deterministic replacement for the old `interrupted`
* invention. A clean `complete` means the turn succeeded, so a straggler is
* settled `success` (with explicit tool/span terminals from the backend there
* are normally none); a stop settles `cancelled`; an error settles `error`.
* Settles every unfinished tool row (running, pending, or awaiting approval) at
* a turn terminal by propagating the turn's outcome: a clean `complete` settles
* a straggler `success`, a stop `cancelled`, an error `error`. Also closes any
* open subagent lane. Returns whether it settled a row or closed a lane.
*/
export function finalizeResidualToolCalls(
blocks: ContentBlock[],
turnTerminal: 'complete' | 'cancelled' | 'error'
): void {
): boolean {
const endedAt = Date.now()
let settled = false
const propagated =
turnTerminal === 'cancelled'
? ToolCallStatus.cancelled
Expand All @@ -93,10 +94,12 @@ export function finalizeResidualToolCalls(
// transport-based gating.
if (block.type === 'subagent' && block.endedAt === undefined) {
block.endedAt = endedAt
settled = true
continue
}
const tc = block.toolCall
if (!tc || tc.status !== ToolCallStatus.executing) continue
if (!tc || !isUnsettledToolState(tc.status)) continue
settled = true
Comment thread
waleedlatif1 marked this conversation as resolved.
tc.status = propagated
if (propagated === ToolCallStatus.cancelled) {
tc.displayTitle = 'Stopped by user'
Expand All @@ -105,6 +108,7 @@ export function finalizeResidualToolCalls(
block.endedAt = endedAt
}
}
return settled
}

function stringParam(value: unknown): string | undefined {
Expand Down
Loading
Loading