{
diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx
index 9af89d8fddb..28a4114c078 100644
--- a/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx
+++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx
@@ -52,6 +52,7 @@ export function NativeChatAssistantMessageRow({
trailingRun,
continuesTurn = false,
endsResponse,
+ actionsHang = false,
inSubagentSection = false,
runtimeContext,
fork
@@ -122,8 +123,9 @@ export function NativeChatAssistantMessageRow({
}
className={cn(
'mt-1 w-fit select-none',
- // They hang into the gap below; a section keeps them inside its border instead.
- !inSubagentSection && '-mb-5'
+ // They hang into the gap below only when nothing left-side starts there. Never in a
+ // section, which keeps them inside its border.
+ actionsHang && '-mb-5'
)}
/>
) : null}
diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx
index 11c9bbda907..543dcb7f6be 100644
--- a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx
+++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx
@@ -59,6 +59,8 @@ export type MessageRowProps = {
continuesTurn?: boolean
/** In a turn: whether this row holds the response's actions (its last words, else its last images). */
endsResponse?: boolean
+ /** Response controls may hang into the gap below; otherwise they keep their own height. */
+ actionsHang?: boolean
/** Align this message's top to the top of the scroll viewport. */
onScrollMessageToTop: (el: HTMLElement) => void
deliveryNotice?: NativeChatDeliveryNotice
diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.fixture.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.fixture.tsx
new file mode 100644
index 00000000000..f2c4f9c04bc
--- /dev/null
+++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.fixture.tsx
@@ -0,0 +1,69 @@
+import { defineFixture } from '../../../../component-fixtures/component-fixture'
+import { NativeChatMessageList } from '../../NativeChatMessageList'
+import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract'
+import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
+import { orchestrationMailFixture } from '../../../../../../shared/agent-session/orchestration-mail.test-fixture'
+
+const STARTED_AT = 1_800_000_000_000
+let sent = 0
+function at(): number {
+ sent += 1
+ return STARTED_AT + sent * 60_000
+}
+function text(id: string, role: NativeChatMessage['role'], body: string): NativeChatMessage {
+ return { id, role, source: 'transcript', timestamp: at(), blocks: [{ type: 'text', text: body }] }
+}
+
+// What follows a response's copy / fork / scroll-up row: a worker's card, the person's own bubble,
+// and the turn's changed-files rollup.
+const messages: NativeChatMessage[] = [
+ text('ask', 'user', 'Have a worker review the parser.'),
+ text('dispatched', 'assistant', 'A review worker is on it. I will report when it answers.'),
+ {
+ ...orchestrationMailFixture({ body: 'The parser review found nothing blocking.' }),
+ timestamp: at()
+ },
+ text('reported', 'assistant', 'The worker found nothing blocking.'),
+ text('follow-up', 'user', 'Good. Update the greeting too.'),
+ {
+ id: 'edit',
+ role: 'assistant',
+ source: 'transcript',
+ timestamp: at(),
+ blocks: [
+ {
+ type: 'tool-call',
+ name: 'Edit',
+ state: 'completed',
+ input: {
+ file_path: '/Users/alice/orca/workspaces/orca/feature-x/src/components/greeting.ts',
+ old_string: 'return "Hello"',
+ new_string: 'return `Hello, ${name}`'
+ }
+ },
+ { type: 'tool-result', output: 'The file was updated successfully.' }
+ ]
+ },
+ text('answer', 'assistant', 'The greeting now includes the name.')
+]
+
+const session: NativeChatLiveSession = {
+ messages,
+ agent: 'claude',
+ sessionId: 'fixture',
+ status: 'ready',
+ readPhase: 'ready',
+ hasMore: false,
+ loadingEarlier: false,
+ olderHistoryGeneration: 0,
+ loadEarlier: async () => 'applied'
+}
+
+export const responseActionsGap = defineFixture({
+ width: 560,
+ render: () => (
+
+
+
+ )
+})
diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx
index 3bfadce54b5..70ecc3a1ff6 100644
--- a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx
+++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx
@@ -48,12 +48,15 @@ export type NativeChatTranscriptRowContext = {
export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({
slot,
context,
- newRowsMarker
+ newRowsMarker,
+ newRowsMarkerBelow = false
}: {
slot: NativeChatTranscriptSlot
context: NativeChatTranscriptRowContext
/** The "New" marker, when it draws in this row. */
newRowsMarker?: NativeChatNewRowsMarkerState
+ /** The "New" marker opens the next row: left-side, so this row's actions keep their own height. */
+ newRowsMarkerBelow?: boolean
}): React.JSX.Element {
// Offered only on the conversation's own turn-opening prompts (`nativeChatRowOffersRewind`).
const rewind = useContext(NativeChatRewindContext)
@@ -105,7 +108,8 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({
) : null
return (
// The negative margin shortens the measured row, which is what moves the next one up.
- // A row whose actions hang into the gap keeps it whole, so they never cover the next row.
+ // A row that holds its response's actions keeps the gap whole: they stay in flow above the
+ // agent's next step (`actionsHang` is unset there), which then sits a full gap below them.
{
- const original = await importOriginal()
- return {
- ...original,
- agentSessionVisibleFailureFacts: vi.fn(original.agentSessionVisibleFailureFacts)
- }
- }
-)
const { mocks, moduleFactories, resetStructuredSessionMocks, launchModule } = await vi.hoisted(
async () => {
@@ -46,7 +28,6 @@ vi.mock(
async (importOriginal) => ({
...(await importOriginal()),
getStructuredAgentSessionLaunchLifecycle: launchModule.getStructuredAgentSessionLaunchLifecycle,
- getStructuredAgentSessionLaunchResumes: launchModule.getStructuredAgentSessionLaunchResumes,
useStructuredAgentSessionLaunchLifecycle: launchModule.useStructuredAgentSessionLaunchLifecycle,
useStructuredAgentSessionLaunchFailure: launchModule.useStructuredAgentSessionLaunchFailure
})
@@ -93,7 +74,6 @@ afterEach(() => {
localStorage.clear()
resetStructuredSessionMocks()
mocks.queuedCards = []
- vi.mocked(agentSessionVisibleFailureFacts).mockClear()
})
function pane(agent: 'claude' | 'codex' = 'codex'): React.JSX.Element {
@@ -111,35 +91,6 @@ function pane(agent: 'claude' | 'codex' = 'codex'): React.JSX.Element {
)
}
-function startFailureRow(fact: AgentSessionFailureFact): AgentJournalRenderItem {
- return {
- itemId: agentJournalItemKey(structuredAgentSessionStartFailureRowIdentity('generation-1')),
- revision: 1,
- sequence: 1,
- observedAt: 1,
- body: {
- kind: 'status',
- tone: 'error',
- ...agentSessionFailureWords(fact, { agentName: 'Codex', surface: 'row' })
- }
- }
-}
-
-function turnRow(): AgentJournalRenderItem {
- return {
- itemId: agentJournalItemKey({
- provider: 'codex',
- threadId: 'thread-1',
- turnId: 'turn-1',
- ordinal: 0
- }),
- revision: 1,
- sequence: 2,
- observedAt: 2,
- body: { kind: 'turn', turnId: 'turn-1', state: 'completed', startedAt: 2, completedAt: 3 }
- }
-}
-
it('stays dismissed for the same verdict, and shows again when it changes or comes back', () => {
mocks.unavailable = { reason: 'notSignedIn', account: 'system' }
const view = render(pane())
@@ -165,21 +116,3 @@ it('stays dismissed for the same verdict, and shows again when it changes or com
view.rerender(pane())
expect(screen.getByText(CODEX_SIGNED_OUT)).toBeTruthy()
})
-
-it("leaves the reason to the transcript's start-failure row, but not a different one", () => {
- mocks.journalItems = [startFailureRow({ kind: 'notSignedIn' })]
- mocks.unavailable = { reason: 'notSignedIn', account: 'system' }
- const view = render(pane())
- expect(screen.queryByText(CODEX_SIGNED_OUT)).toBeNull()
-
- mocks.unavailable = { reason: 'cliMissing' }
- view.rerender(pane())
- expect(screen.getByText(CODEX_MISSING)).toBeTruthy()
-})
-
-it('ignores a failed start that a turn has run since', () => {
- mocks.journalItems = [startFailureRow({ kind: 'notSignedIn' }), turnRow()]
- mocks.unavailable = { reason: 'notSignedIn', account: 'system' }
- render(pane())
- expect(screen.getByText(CODEX_SIGNED_OUT)).toBeTruthy()
-})
diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.history-read-state.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.history-read-state.test.tsx
deleted file mode 100644
index 78bc942b434..00000000000
--- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.history-read-state.test.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-// @vitest-environment happy-dom
-
-import type * as LaunchRegistry from '@/lib/agent-session/launch/structured-agent-session-launch-registry'
-import type * as LaunchOptions from '@/lib/agent-session/launch/structured-agent-session-launch-options'
-import { cleanup, render, screen } from '@testing-library/react'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-
-import { NativeChatStructuredSession } from '../../NativeChatStructuredSession'
-
-const { mocks, moduleFactories, resetStructuredSessionMocks, launchModule } = await vi.hoisted(
- async () => {
- const setup = (
- await import('./NativeChatStructuredSession.test-harness')
- ).createStructuredSessionMocks()
- return {
- ...setup,
- launchModule: setup.moduleFactories.structuredAgentSessionLaunch()
- }
- }
-)
-
-vi.mock('@/lib/agent-session/launch/structured-agent-session-launch', () => ({
- retryStructuredAgentSessionLaunch: launchModule.retryStructuredAgentSessionLaunch,
- relaunchFailedStructuredAgentSessionForMessage:
- launchModule.relaunchFailedStructuredAgentSessionForMessage
-}))
-vi.mock(
- '@/lib/agent-session/launch/structured-agent-session-launch-registry',
- async (importOriginal) => ({
- ...(await importOriginal()),
- getStructuredAgentSessionLaunchLifecycle: launchModule.getStructuredAgentSessionLaunchLifecycle,
- getStructuredAgentSessionLaunchResumes: launchModule.getStructuredAgentSessionLaunchResumes,
- useStructuredAgentSessionLaunchLifecycle: launchModule.useStructuredAgentSessionLaunchLifecycle,
- useStructuredAgentSessionLaunchFailure: launchModule.useStructuredAgentSessionLaunchFailure
- })
-)
-vi.mock(
- '@/lib/agent-session/launch/structured-agent-session-launch-options',
- async (importOriginal) => ({
- ...(await importOriginal()),
- useStructuredAgentSessionLaunchSelection: launchModule.useStructuredAgentSessionLaunchSelection
- })
-)
-vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () =>
- moduleFactories.structuredAgentSessionCall()
-)
-vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () =>
- moduleFactories.structuredAgentSessionSubscriptions()
-)
-vi.mock('../../session/structured/use-structured-agent-session', () =>
- moduleFactories.useStructuredAgentSession()
-)
-vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize())
-vi.mock('../../links/actions/use-native-chat-file-link-context', () =>
- moduleFactories.useNativeChatFileLinkContext()
-)
-vi.mock('../../links/actions/use-native-chat-file-link-click', () =>
- moduleFactories.useNativeChatFileLinkClick()
-)
-vi.mock('../../NativeChatMessageList', () => moduleFactories.nativeChatMessageList())
-vi.mock('../../composer/NativeChatComposer', () => moduleFactories.nativeChatComposer())
-vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard())
-vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard())
-
-afterEach(() => {
- cleanup()
- localStorage.clear()
- resetStructuredSessionMocks()
-})
-
-{
- const START_A_CHAT = 'Start a chat with Codex'
- const LOADING_TEXT = /Loading conversation|Reading the agent transcript/
-
- function loadingCue(): HTMLElement | null {
- return document.querySelector('[data-native-chat-loading-cue="true"]')
- }
-
- function sessionView(): React.JSX.Element {
- return (
-
- )
- }
-
- describe('NativeChatStructuredSession before its first read settles', () => {
- it('keeps a chat this view started on its empty state through publish and the first read', () => {
- mocks.messages = []
- mocks.launchLifecycle = 'pending'
- // The real controller reports `ready` while the launch has not published.
- mocks.status = 'ready'
- const { rerender } = render(sessionView())
- expect(screen.getByText(START_A_CHAT)).toBeTruthy()
-
- mocks.launchLifecycle = null
- for (const status of ['idle', 'loading', 'ready'] as const) {
- mocks.status = status
- rerender(sessionView())
- expect(screen.getByText(START_A_CHAT)).toBeTruthy()
- expect(screen.queryAllByText(LOADING_TEXT)).toHaveLength(0)
- expect(loadingCue()).toBeNull()
- }
- })
- })
-}
diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx
deleted file mode 100644
index 1fc8490b19f..00000000000
--- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-// @vitest-environment happy-dom
-
-import type * as LaunchRegistry from '@/lib/agent-session/launch/structured-agent-session-launch-registry'
-import type * as LaunchOptions from '@/lib/agent-session/launch/structured-agent-session-launch-options'
-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
-import { afterEach, expect, it, vi } from 'vitest'
-
-const { mocks, moduleFactories, resetStructuredSessionMocks, launchModule } = await vi.hoisted(
- async () => {
- const setup = (
- await import('./NativeChatStructuredSession.test-harness')
- ).createStructuredSessionMocks()
- return {
- ...setup,
- launchModule: setup.moduleFactories.structuredAgentSessionLaunch()
- }
- }
-)
-
-vi.mock('@/lib/agent-session/launch/structured-agent-session-launch', () => ({
- retryStructuredAgentSessionLaunch: launchModule.retryStructuredAgentSessionLaunch,
- relaunchFailedStructuredAgentSessionForMessage:
- launchModule.relaunchFailedStructuredAgentSessionForMessage
-}))
-vi.mock(
- '@/lib/agent-session/launch/structured-agent-session-launch-registry',
- async (importOriginal) => ({
- ...(await importOriginal()),
- getStructuredAgentSessionLaunchLifecycle: launchModule.getStructuredAgentSessionLaunchLifecycle,
- getStructuredAgentSessionLaunchResumes: launchModule.getStructuredAgentSessionLaunchResumes,
- useStructuredAgentSessionLaunchLifecycle: launchModule.useStructuredAgentSessionLaunchLifecycle,
- useStructuredAgentSessionLaunchFailure: launchModule.useStructuredAgentSessionLaunchFailure
- })
-)
-vi.mock(
- '@/lib/agent-session/launch/structured-agent-session-launch-options',
- async (importOriginal) => ({
- ...(await importOriginal()),
- useStructuredAgentSessionLaunchSelection: launchModule.useStructuredAgentSessionLaunchSelection
- })
-)
-vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () =>
- moduleFactories.structuredAgentSessionCall()
-)
-vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () =>
- moduleFactories.structuredAgentSessionSubscriptions()
-)
-vi.mock('../../session/structured/use-structured-agent-session', () =>
- moduleFactories.useStructuredAgentSession()
-)
-vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize())
-vi.mock('../../links/actions/use-native-chat-file-link-context', () =>
- moduleFactories.useNativeChatFileLinkContext()
-)
-vi.mock('../../links/actions/use-native-chat-file-link-click', () =>
- moduleFactories.useNativeChatFileLinkClick()
-)
-vi.mock('../../NativeChatMessageList', () => moduleFactories.nativeChatMessageList())
-vi.mock('../../composer/NativeChatComposer', () => moduleFactories.nativeChatComposer())
-vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard())
-vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard())
-
-import { NativeChatStructuredSession } from '../../NativeChatStructuredSession'
-import type { NativeChatStructuredComposerTransport } from '../../composer/submit/native-chat-structured-composer-transport'
-
-const SESSION_ID = 'notice-card-session'
-
-afterEach(() => {
- cleanup()
- resetStructuredSessionMocks()
-})
-
-function renderPane(): void {
- render(
-
- )
-}
-
-function composerOnError(): NativeChatStructuredComposerTransport['onError'] {
- const onError = mocks.composerProps?.structuredTransport?.onError
- if (!onError) {
- throw new Error('composer transport has no onError')
- }
- return onError
-}
-
-it("shows the chat's own error and a composer error together, where one used to hide the other", () => {
- mocks.status = 'error'
- mocks.readRefusal = {
- code: 'agent_session_journal_unreadable',
- details: { reason: 'journalUnavailable' }
- }
- renderPane()
- act(() => {
- composerOnError()('sonnet-9 is not an available model for this chat session.')
- })
- expect(screen.getByText("Orca couldn't open this chat's history right now.")).toBeTruthy()
- expect(screen.getByText('sonnet-9 is not an available model for this chat session.')).toBeTruthy()
- expect(document.querySelectorAll('[data-notice-kind="error"]')).toHaveLength(2)
-})
-
-it('keeps a send failure’s raw error apart and lets the user dismiss it', () => {
- renderPane()
- act(() => {
- composerOnError()('Your message was not sent.', {
- errorText: 'connect ECONNREFUSED /tmp/agent-host.sock'
- })
- })
- expect(screen.getByText('connect ECONNREFUSED /tmp/agent-host.sock').tagName).toBe('PRE')
- fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
- expect(screen.queryByText('Your message was not sent.')).toBeNull()
-})
diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing-test-support.tsx b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing-test-support.tsx
index 9a71f31db2e..b4cb24722e3 100644
--- a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing-test-support.tsx
+++ b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing-test-support.tsx
@@ -8,6 +8,7 @@ import { NativeChatMessageList } from '../../NativeChatMessageList'
import { transcriptRowOffset, transcriptWindowHeight } from './native-chat-window-test-layout'
import {
estimateNativeChatRowHeight,
+ nativeChatRowHeightWithControlsInFlow,
nativeChatRowContentMetrics
} from './native-chat-row-height-estimate'
@@ -35,11 +36,15 @@ export function marker(index: number): NativeChatMessage {
}
}
-const ROW_PX = estimateNativeChatRowHeight(nativeChatRowContentMetrics(marker(0)), {
- hasReceipt: false,
- hasStatus: false,
- hasTurnDiff: false
-})
+// Another agent row follows every marker but the last, so its response controls keep their own
+// height; rows measure at this height wherever they sit.
+const ROW_PX = nativeChatRowHeightWithControlsInFlow(
+ estimateNativeChatRowHeight(nativeChatRowContentMetrics(marker(0)), {
+ hasReceipt: false,
+ hasStatus: false,
+ hasTurnDiff: false
+ })
+)
function overrideLayoutProperty(name: string, descriptor: PropertyDescriptor): () => void {
const original = Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)
diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatTranscriptItems.tsx b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatTranscriptItems.tsx
index 1088f039f66..ba383132503 100644
--- a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatTranscriptItems.tsx
+++ b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatTranscriptItems.tsx
@@ -53,6 +53,10 @@ export function NativeChatTranscriptItems({
newRowsMarker={
rowKeys[item.index] === newRowsMarker?.key ? newRowsMarker : undefined
}
+ newRowsMarkerBelow={
+ newRowsMarker?.place === 'above-row' &&
+ rowKeys[item.index + 1] === newRowsMarker.key
+ }
/>
diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.ts b/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.ts
index d4eeb68147a..c9f535c603e 100644
--- a/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.ts
+++ b/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.ts
@@ -61,7 +61,8 @@ const TURN_DIFF_PX = 28
/** The opened-PR card: its heading, then one row per pull request. */
const OPENED_PULL_REQUEST_ROW_PX = 30
const RECEIPT_PX = 56
-/** How far assistant prose's controls hang below the row (`-mb-5`) outside a section. */
+/** How far assistant prose's controls hang below the row (`-mb-5`) when they may; a row that keeps
+ * them in flow is that much taller. */
const AGENT_CONTROLS_OVERHANG_PX = 20
const ROW_MIN_PX = 24
/** Charge internal gap-5 only; the virtualizer owns inter-row gaps, which would otherwise compound drift. */
@@ -148,6 +149,17 @@ export function nativeChatWorkRunContentMetrics(
}
}
+/** A row estimate with its response controls in flow, for a row estimated with them hanging. */
+export function nativeChatRowHeightWithControlsInFlow(
+ estimatedHeight: number,
+ typography = DEFAULT_ROW_TYPOGRAPHY
+): number {
+ return Math.min(
+ ROW_MAX_PX,
+ estimatedHeight + AGENT_CONTROLS_OVERHANG_PX * typography.spacingScale
+ )
+}
+
export function estimateNativeChatRowHeight(
content: NativeChatRowContentMetrics,
chrome: NativeChatRowChromeMetrics,
diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-windowing-test-harness.tsx b/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-windowing-test-harness.tsx
index dad84678f73..ebefd55ea58 100644
--- a/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-windowing-test-harness.tsx
+++ b/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-windowing-test-harness.tsx
@@ -7,6 +7,7 @@ import { NativeChatMessageList } from '../../NativeChatMessageList'
import { transcriptRowOffset, transcriptWindowHeight } from './native-chat-window-test-layout'
import {
estimateNativeChatRowHeight,
+ nativeChatRowHeightWithControlsInFlow,
NATIVE_CHAT_ROW_GAP_PX,
nativeChatRowContentMetrics
} from './native-chat-row-height-estimate'
@@ -44,11 +45,15 @@ export function marker(index: number): NativeChatMessage {
}
}
-export const ROW_PX = estimateNativeChatRowHeight(nativeChatRowContentMetrics(marker(0)), {
- hasReceipt: false,
- hasStatus: false,
- hasTurnDiff: false
-})
+// Another agent row follows every marker but the last, so its response controls keep their own
+// height; rows measure at this height wherever they sit.
+export const ROW_PX = nativeChatRowHeightWithControlsInFlow(
+ estimateNativeChatRowHeight(nativeChatRowContentMetrics(marker(0)), {
+ hasReceipt: false,
+ hasStatus: false,
+ hasTurnDiff: false
+ })
+)
export const ROW_PITCH_PX = ROW_PX + NATIVE_CHAT_ROW_GAP_PX
export function overrideLayoutProperty(name: string, descriptor: PropertyDescriptor): () => void {
diff --git a/src/renderer/src/components/orchestration-crew/CrewAgentIcons.tsx b/src/renderer/src/components/orchestration-crew/CrewAgentIcons.tsx
index 7c29826bfec..96e29255aa2 100644
--- a/src/renderer/src/components/orchestration-crew/CrewAgentIcons.tsx
+++ b/src/renderer/src/components/orchestration-crew/CrewAgentIcons.tsx
@@ -5,7 +5,8 @@ import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon'
import { cn } from '@/lib/utils'
import { getAgentLabel } from '@/lib/agent-catalog/agent-catalog'
import { mapAgentStatusStateToVisualStatus } from '@/lib/agent-status/aggregation/worktree-agent-status'
-import { getWorktreeStatusLabel, type WorktreeStatus } from '@/lib/worktree-status'
+import { getWorktreeStatusLabel } from '@/lib/worktree-status'
+import type { WorktreeStatus } from '../../../../shared/worktree-status-rollup'
import {
useAgentMessageSenderViews,
type AgentMessageSenderInput
diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx
index 974cb20fec5..6b5d7ef6d01 100644
--- a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx
+++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx
@@ -5,7 +5,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { cn } from '@/lib/utils'
import StatusIndicator from '@/components/sidebar/workspace-card/surface/StatusIndicator'
import { formatStateCount } from '@/components/sidebar/workspace-card/activity/worktree-card-agent-summary'
-import type { WorktreeStatus } from '@/lib/worktree-status'
+import type { WorktreeStatus } from '../../../../shared/worktree-status-rollup'
import type {
OrchestrationCrewRow,
OrchestrationCrewSnapshot
diff --git a/src/renderer/src/components/orchestration-crew/use-orchestration-crew.test.tsx b/src/renderer/src/components/orchestration-crew/use-orchestration-crew.test.tsx
deleted file mode 100644
index e6c6b6fc303..00000000000
--- a/src/renderer/src/components/orchestration-crew/use-orchestration-crew.test.tsx
+++ /dev/null
@@ -1,252 +0,0 @@
-// @vitest-environment happy-dom
-import '@testing-library/jest-dom/vitest'
-import { act, cleanup, render } from '@testing-library/react'
-import { afterEach, beforeEach, expect, it, vi } from 'vitest'
-import type {
- CrewSubscriptionAttemptArgs,
- CrewSubscriptionAttemptCallbacks
-} from '../../../../shared/remote-runtime/host-catalog/runtime-environment-subscription-setup'
-import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target'
-import type { RuntimeRpcSubscriptionHandlers } from '@/runtime/rpc/subscriptions/runtime-rpc-subscribe'
-import { replaceRuntimeEnvironmentRevisions } from '@/runtime/rpc/environment-revisions/runtime-environment-revision'
-import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/host-runtime-capabilities'
-import { useOrchestrationCrew } from './use-orchestration-crew'
-
-const rig = vi.hoisted(() => {
- const streams: {
- target: RuntimeClientTarget
- party: string
- handlers: RuntimeRpcSubscriptionHandlers
- unsubscribe: ReturnType
- }[] = []
- return {
- streams,
- producers: new Map () => void>(),
- cancellations: new Map void>(),
- listeners: new Set<() => void>(),
- state: {
- unusedLocalState: 0,
- runtimeStatusByEnvironmentId: new Map<
- string,
- {
- status: { runtimeId: string; capabilities?: string[] }
- connectionGeneration: number
- hostContactEpoch: number
- snapshot?: {
- environmentId: string
- pairingRevision: number
- sequence: number
- checkedAt: number
- status: { runtimeId: string; capabilities?: string[] }
- verification: string
- transport: string
- }
- }
- >([
- [
- 'crew-host',
- { status: { runtimeId: 'runtime-one' }, connectionGeneration: 1, hostContactEpoch: 1 }
- ]
- ])
- }
- }
-})
-vi.mock('@/runtime/rpc/subscriptions/runtime-rpc-subscribe', () => ({
- subscribeRuntimeRpc: vi.fn(
- async (
- target: RuntimeClientTarget,
- _method: string,
- params: { party: string },
- handlers: RuntimeRpcSubscriptionHandlers
- ) => {
- const key = `${target.kind === 'local' ? 'local' : target.environmentId}:${params.party}`
- const stop = rig.producers.get(key)?.(handlers)
- const stream = { target, party: params.party, handlers, unsubscribe: vi.fn(() => stop?.()) }
- rig.streams.push(stream)
- return { unsubscribe: stream.unsubscribe }
- }
- )
-}))
-vi.mock('@/store/index', () => ({
- useAppStore: {
- getState: () => rig.state,
- subscribe: (wake: () => void) => {
- rig.listeners.add(wake)
- return () => rig.listeners.delete(wake)
- }
- }
-}))
-vi.mock('../native-chat/messages/agent-senders/native-chat-agent-message-sender-view', () => ({
- useAgentMessageSenderViews: () => []
-}))
-vi.mock('@/lib/open-agent-message-sender', () => ({ openOrchestrationCrewAgent: vi.fn() }))
-beforeEach(() => {
- vi.useFakeTimers()
- vi.spyOn(Math, 'random').mockReturnValue(0)
- Object.assign(window, {
- api: {
- runtimeEnvironments: {
- subscribeCrewAttempt: async (
- args: CrewSubscriptionAttemptArgs,
- callbacks: CrewSubscriptionAttemptCallbacks
- ) => {
- const params = args.params
- if (
- !params ||
- typeof params !== 'object' ||
- !('party' in params) ||
- typeof params.party !== 'string'
- ) {
- throw new Error('Expected party')
- }
- const unsubscribe = vi.fn()
- rig.cancellations.set(args.subscriptionId, unsubscribe)
- rig.streams.push({
- target: { kind: 'environment', environmentId: args.selector },
- party: params.party,
- unsubscribe,
- handlers: {
- onEvent: (value) =>
- callbacks.onResponse({
- id: args.subscriptionId,
- ok: true,
- result: value,
- _meta: { runtimeId: args.expectedEnvironmentRuntimeId ?? '' }
- }),
- onError: (error) => {
- if (
- error &&
- typeof error === 'object' &&
- 'code' in error &&
- typeof error.code === 'string'
- ) {
- callbacks.onError?.({ code: error.code, message: '' })
- }
- },
- onClose: () => callbacks.onClose?.()
- }
- })
- return { subscriptionId: args.subscriptionId, ok: true as const }
- },
- cancelSubscription: async ({ subscriptionId }: { subscriptionId: string }) => {
- rig.cancellations.get(subscriptionId)?.()
- rig.cancellations.delete(subscriptionId)
- }
- }
- }
- })
-})
-afterEach(() => {
- cleanup()
- rig.streams.length = 0
- rig.producers.clear()
- rig.cancellations.clear()
- vi.restoreAllMocks()
- vi.useRealTimers()
-})
-const local = { kind: 'local' } as const
-const remote = { kind: 'environment', environmentId: 'crew-host' } as const
-function Pane({ party, target = local }: { party: string; target?: RuntimeClientTarget }) {
- const crew = useOrchestrationCrew(target, party)
- return (
- <>
-
-
-
-
- >
- )
-}
-function publish(index: number, pending = false) {
- const handlers = rig.streams[index].handlers
- handlers.onEvent({ type: 'begin', status: 'ok' })
- handlers.onEvent({
- type: 'rows',
- section: 'managing',
- rows: [
- {
- partyKey: 'host-worker',
- role: 'worker',
- label: 'Worker',
- agentKind: 'codex',
- status: 'working',
- sendAddress: 'term_worker',
- ...(pending
- ? { pendingQuestion: { preview: 'Which option?', at: new Date(0).toISOString() } }
- : {})
- }
- ]
- })
- return () => handlers.onEvent({ type: 'complete' })
-}
-
-it('caches old-host refusal per generation and resubscribes after reconnect or pairing changes', async () => {
- replaceRuntimeEnvironmentRevisions([{ id: 'crew-host', createdAt: 1 }])
- const view = render()
- await act(async () => {
- await vi.advanceTimersByTimeAsync(250)
- })
- act(() => rig.streams[0].handlers.onError({ code: 'method_not_found' }))
- expect(view.getByTestId('term_old').textContent).toBe('unknown')
- view.rerender()
- await act(async () => {
- await vi.advanceTimersByTimeAsync(250)
- })
- expect(rig.streams).toHaveLength(1)
- act(() => {
- rig.state = {
- ...rig.state,
- runtimeStatusByEnvironmentId: new Map([
- [
- 'crew-host',
- {
- status: {
- runtimeId: 'runtime-two',
- capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY]
- },
- connectionGeneration: 2,
- hostContactEpoch: 2,
- snapshot: {
- environmentId: 'crew-host',
- pairingRevision: 1,
- sequence: 1,
- checkedAt: 1,
- status: { runtimeId: 'runtime-two' },
- verification: 'verified',
- transport: 'ready'
- }
- }
- ]
- ])
- }
- rig.listeners.forEach((wake) => wake())
- })
- await act(async () => {
- await vi.advanceTimersByTimeAsync(250)
- })
- expect(rig.streams).toHaveLength(2)
- act(() => publish(1)())
- expect(view.getByTestId('term_plain').textContent).toBe('1')
- act(() => rig.streams[1].handlers.onClose())
- expect(view.getByTestId('term_plain').textContent).toBe('unknown')
- act(() => {
- const entry = rig.state.runtimeStatusByEnvironmentId.get('crew-host')
- if (entry?.snapshot) {
- entry.snapshot.pairingRevision = 2
- }
- replaceRuntimeEnvironmentRevisions([{ id: 'crew-host', createdAt: 1, pairingRevision: 2 }])
- })
- await act(async () => {
- await vi.advanceTimersByTimeAsync(500)
- })
- expect(rig.streams).toHaveLength(3)
- expect(rig.streams[1].unsubscribe).toHaveBeenCalledOnce()
- view.unmount()
- expect(rig.streams[2].unsubscribe).toHaveBeenCalledOnce()
-})
diff --git a/src/renderer/src/components/settings/voice/VoiceSpeechModelSection.test.tsx b/src/renderer/src/components/settings/voice/VoiceSpeechModelSection.test.tsx
deleted file mode 100644
index b019dc293be..00000000000
--- a/src/renderer/src/components/settings/voice/VoiceSpeechModelSection.test.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-// @vitest-environment happy-dom
-
-// @vitest-environment happy-dom
-import { act } from 'react'
-import { createRoot, type Root } from 'react-dom/client'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import type { SpeechModelManifest, SpeechModelState } from '../../../../../shared/speech-types'
-import { getDefaultVoiceSettings } from '../../../../../shared/constants'
-
-const toastErrorMock = vi.hoisted(() => vi.fn())
-
-vi.mock('sonner', () => ({
- toast: {
- error: toastErrorMock
- }
-}))
-
-vi.mock('@/i18n/i18n', () => ({
- getIntlLocale: () => 'en',
- translate: (_key: string, fallback: string, values?: Record) =>
- values ? fallback.replace('{{value0}}', values.value0) : fallback
-}))
-
-import { VoiceSpeechModelSection } from './VoiceSpeechModelSection'
-
-const localModel: SpeechModelManifest = {
- id: 'model-a',
- label: 'Local Model',
- provider: 'local',
- language: 'en',
- languages: ['en'],
- type: 'transducer',
- streaming: true,
- sampleRate: 16000,
- sizeBytes: 123_000_000,
- files: ['encoder.onnx']
-}
-
-const secondLocalModel: SpeechModelManifest = {
- ...localModel,
- id: 'model-b',
- label: 'Second Local Model'
-}
-
-function renderSection(args: {
- deleteModel: (modelId: string) => Promise
- downloadModel?: (modelId: string) => Promise
- catalog?: SpeechModelManifest[]
- modelStates?: SpeechModelState[]
- refreshModelStates?: () => void
-}): { container: HTMLDivElement; root: Root } {
- Object.assign(window, {
- api: {
- speech: {
- deleteModel: vi.fn(args.deleteModel),
- downloadModel: vi.fn(args.downloadModel ?? (() => Promise.resolve()))
- }
- }
- })
-
- const container = document.createElement('div')
- document.body.appendChild(container)
- const root = createRoot(container)
- const voiceSettings = { ...getDefaultVoiceSettings(), enabled: true, sttModel: localModel.id }
- const catalog = args.catalog ?? [localModel]
- const modelStates = args.modelStates ?? [{ id: localModel.id, status: 'ready' }]
- act(() => {
- root.render(
-
- )
- })
-
- return { container, root }
-}
-
-describe('VoiceSpeechModelSection', () => {
- beforeEach(() => {
- toastErrorMock.mockReset()
- })
-
- afterEach(() => {
- document.body.innerHTML = ''
- vi.unstubAllGlobals()
- })
-
- it('keeps another row delete disabled until its own request finishes', async () => {
- const deleteResolvers = new Map void>()
- const refreshModelStates = vi.fn()
- const { container, root } = renderSection({
- refreshModelStates,
- catalog: [localModel, secondLocalModel],
- modelStates: [
- { id: localModel.id, status: 'ready' },
- { id: secondLocalModel.id, status: 'ready' }
- ],
- deleteModel: (modelId) =>
- new Promise((resolve) => {
- deleteResolvers.set(modelId, resolve)
- })
- })
- const firstDeleteButton = container.querySelector(
- 'button[aria-label="Delete Local Model"]'
- )
- const secondDeleteButton = container.querySelector(
- 'button[aria-label="Delete Second Local Model"]'
- )
-
- await act(async () => {
- firstDeleteButton!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
- })
- await act(async () => {
- secondDeleteButton!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
- })
-
- expect(firstDeleteButton!.disabled).toBe(true)
- expect(secondDeleteButton!.disabled).toBe(true)
-
- await act(async () => {
- deleteResolvers.get(localModel.id)!()
- await Promise.resolve()
- })
-
- expect(firstDeleteButton!.disabled).toBe(false)
- expect(secondDeleteButton!.disabled).toBe(true)
-
- await act(async () => {
- deleteResolvers.get(secondLocalModel.id)!()
- await Promise.resolve()
- })
-
- expect(refreshModelStates).toHaveBeenCalledTimes(2)
- root.unmount()
- })
-})
diff --git a/src/renderer/src/components/sidebar/workspace-card/details/WorktreeCardAutomationDetailSection.tsx b/src/renderer/src/components/sidebar/workspace-card/details/WorktreeCardAutomationDetailSection.tsx
index ef9afa4cb17..2d20dbdecae 100644
--- a/src/renderer/src/components/sidebar/workspace-card/details/WorktreeCardAutomationDetailSection.tsx
+++ b/src/renderer/src/components/sidebar/workspace-card/details/WorktreeCardAutomationDetailSection.tsx
@@ -11,7 +11,7 @@ import {
getAutomationTargetFromHostId,
listAutomationRunsForTarget,
listAutomationsForTarget
-} from '@/components/automations/automation-host-client'
+} from '@/components/automations/hosts/automation-host-client'
type WorktreeCardAutomationDetailSectionProps = {
provenance: AutomationWorkspaceProvenance
diff --git a/src/renderer/src/components/skills/sharing/skill-share-package-selection.test.ts b/src/renderer/src/components/skills/sharing/skill-share-package-selection.test.ts
deleted file mode 100644
index 0e55da7549a..00000000000
--- a/src/renderer/src/components/skills/sharing/skill-share-package-selection.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import type { ManagedSkillInstall } from '../../../../../shared/skill-install-contract'
-import type { DiscoveredSkill } from '../../../../../shared/skills'
-import { matchingManagedSkillShareInstall } from './skill-share-package-selection'
-
-function skill(name: string): DiscoveredSkill {
- return {
- id: `skill:${name}`,
- name,
- description: null,
- providers: ['agent-skills'],
- sourceKind: 'home',
- sourceLabel: 'Home',
- rootPath: '/skills',
- directoryPath: `/skills/${name}`,
- skillFilePath: `/skills/${name}/SKILL.md`,
- installed: true,
- updatedAt: null
- }
-}
-
-function install(name: string, destinationIdentity = 'global:local'): ManagedSkillInstall {
- return {
- name,
- packageId: 'pkg_1',
- versionId: 'ver_1',
- packageDigest: 'a'.repeat(64),
- bundleDigest: 'b'.repeat(64),
- scope: 'global',
- destinationIdentity,
- destination: { scope: 'global' },
- installedAt: '2026-08-11T00:00:00.000Z',
- state: 'unchanged'
- }
-}
-
-describe('matchingManagedSkillShareInstall', () => {
- it('matches one complete managed bundle and rejects a partial selection', () => {
- const installs = [install('alpha'), install('beta')]
-
- expect(matchingManagedSkillShareInstall([skill('alpha'), skill('beta')], installs)).toBe(
- installs[0]
- )
- expect(matchingManagedSkillShareInstall([skill('alpha')], installs)).toBeNull()
- })
-
- it('rejects the same bundle installed at multiple destinations', () => {
- const installs = [
- install('alpha'),
- install('beta'),
- install('alpha', 'global:other'),
- install('beta', 'global:other')
- ]
-
- expect(matchingManagedSkillShareInstall([skill('alpha'), skill('beta')], installs)).toBeNull()
- })
-})
diff --git a/src/renderer/src/components/status-bar/AccountSwitchList.tsx b/src/renderer/src/components/status-bar/AccountSwitchList.tsx
index b04f6a6c76f..8affaeccf52 100644
--- a/src/renderer/src/components/status-bar/AccountSwitchList.tsx
+++ b/src/renderer/src/components/status-bar/AccountSwitchList.tsx
@@ -6,6 +6,8 @@ import {
DropdownMenuSeparator
} from '@/components/ui/dropdown-menu'
import { useTranslate } from '@/i18n/use-translate'
+import { useAppStore } from '../../store'
+import { normalizeUsagePercentageDisplay } from '../../../../shared/usage-percentage-display'
export function AccountSwitchList({
heading,
@@ -14,9 +16,28 @@ export function AccountSwitchList({
heading: string
children: React.ReactNode
}): React.JSX.Element {
+ const t = useTranslate()
+ const display = normalizeUsagePercentageDisplay(
+ useAppStore((state) => state.usagePercentageDisplay)
+ )
return (
-
{heading}
+
+
+ {heading}
+
+
+
+ {display === 'used'
+ ? t('auto.components.status.bar.AccountSwitchList.used', 'Used')
+ : t('auto.components.status.bar.AccountSwitchList.left', 'Left')}
+
+
+ {t('auto.components.status.bar.AccountSwitchList.reset', 'Reset')}
+
+
+
+
{children}
)
diff --git a/src/renderer/src/components/status-bar/InlineProviderUsage.tsx b/src/renderer/src/components/status-bar/InlineProviderUsage.tsx
index 758dbff20e0..65d865d91c3 100644
--- a/src/renderer/src/components/status-bar/InlineProviderUsage.tsx
+++ b/src/renderer/src/components/status-bar/InlineProviderUsage.tsx
@@ -12,10 +12,17 @@ import { useResetCountdownClock } from '@/hooks/useResetCountdownClock'
import { barColor, clampUsedPercent } from './tooltip'
import { formatWindowLabel } from '../../../../shared/rate-limit-window-label'
import { formatResetDuration } from '../../../../shared/rate-limit-reset-format'
-import { formatUsageLimitResetClock } from '../../../../shared/agent-session/failures/agent-session-usage-limit'
-import { formatUsagePercentageLabel } from './usage-percentage-label'
+import { formatBareUsagePercentage, formatUsagePercentageLabel } from './usage-percentage-label'
import { getUsageRosterRowState } from './usage-roster-row-state'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
+import { uiNumberFormat } from '@/i18n/ui-intl-formatters'
+import { formatUiNarrowDuration } from '@/i18n/relative-time-format'
+
+const RESET_UNIT_FORMATS: Record<'minute' | 'hour' | 'day', Intl.NumberFormatOptions> = {
+ minute: { style: 'unit', unit: 'minute', unitDisplay: 'short' },
+ hour: { style: 'unit', unit: 'hour', unitDisplay: 'short' },
+ day: { style: 'unit', unit: 'day', unitDisplay: 'short' }
+}
type InlineUsageWindow = { key: string; used: number; label: string; resetsAt: number | null }
@@ -88,31 +95,40 @@ export function InlineUsageBars({
window.resetsAt != null && Number.isFinite(new Date(window.resetsAt).getTime())
? window.resetsAt
: null
+ const resetDuration =
+ resetsAt == null
+ ? null
+ : resetsAt <= now
+ ? t('auto.components.status.bar.InlineUsageBars.now', 'now')
+ : formatResetDuration(resetsAt - now, (value, unit) =>
+ intlLocale.startsWith('en')
+ ? formatUiNarrowDuration(value, unit, intlLocale)
+ : uiNumberFormat(RESET_UNIT_FORMATS[unit], intlLocale).format(value)
+ )
return (
-
-
-
- {/* Why: fill follows the selected percentage; color still signals consumption urgency. */}
-
-
-
- {formatUsagePercentageLabel(window.used, display, t)} {window.label}
-
- {/* Why: fixed width keeps the reset countdowns in one column across account rows. */}
-
- {resetsAt != null ? formatResetDuration(resetsAt - now) : null}
-
+
+
{window.label}
+
- {resetsAt != null ? (
-
- {t('auto.components.status.bar.InlineUsageBars.resetsAt', 'Resets {{when}}', {
- when: formatUsageLimitResetClock(resetsAt, now, intlLocale)
- })}
-
- ) : null}
+
+ {formatBareUsagePercentage(window.used, display, t)}
+
+
{resetDuration}
)
})}
diff --git a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx
deleted file mode 100644
index 38ee13b1e66..00000000000
--- a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-// @vitest-environment happy-dom
-
-import { EVERY_AGENT_CHAT } from '../../../../shared/native-chat/every-agent-chat.test-fixture'
-import { resetLocalStructuredChatsForTests } from '@/runtime/native-chat/local-sessions/local-structured-chats'
-import { act, cleanup, render, screen } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { getDefaultSettings } from '../../../../shared/constants'
-import { useAppStore } from '../../store'
-import { TooltipProvider } from '../ui/tooltip'
-import type { ResumeCandidate } from '../native-chat-recovery/tree/native-chat-resume-on-restart-grouping'
-import {
- consumeNativeChatResumeOnRestartDialogRequest,
- getNativeChatResumeOnRestartDialogRequest
-} from '../native-chat-recovery/dialogs/native-chat-resume-on-restart-dialog'
-import {
- _resetNativeChatRestartOffer,
- localNativeChatRestartStore
-} from '../native-chat-recovery/offers/native-chat-resume-on-restart-store'
-import { NativeChatResumeStatusSegment } from './NativeChatResumeStatusSegment'
-
-const rpc = vi.hoisted(() => vi.fn())
-vi.mock('../../runtime/native-chat/requests/structured-agent-session-call', () => ({
- callStructuredAgentSession: rpc
-}))
-
-vi.mock('../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({
- // A failed row opens the status feed; these cases never drive it.
- subscribeStructuredAgentSessionStatus: () => new Promise(() => {})
-}))
-
-const candidates: ResumeCandidate[] = [
- {
- sessionId: 'a',
- workspaceId: 'workspace',
- agent: 'codex',
- trigger: 'quit',
- latestPrompt: 'Fix it',
- recordedAt: 1
- },
- {
- sessionId: 'b',
- workspaceId: 'workspace',
- agent: 'claude',
- trigger: 'update',
- latestPrompt: 'Review it',
- recordedAt: 2
- }
-]
-
-function stageLocalHost(installed: boolean): void {
- Object.defineProperty(window, 'api', {
- configurable: true,
- value: {
- app: {
- holdsStructuredAgentSessions: async () => installed,
- onStructuredAgentSessionsHeldChanged: () => () => undefined
- }
- }
- })
-}
-
-async function mount(iconOnly = false): Promise
{
- await act(async () => {
- render(
-
-
-
- )
- })
- act(() => consumeNativeChatResumeOnRestartDialogRequest())
-}
-
-describe('NativeChatResumeStatusSegment', () => {
- beforeEach(() => {
- rpc.mockReset()
- _resetNativeChatRestartOffer()
- consumeNativeChatResumeOnRestartDialogRequest()
- useAppStore.setState({
- ...useAppStore.getInitialState(),
- // These cases cover the review flow, which runs while automatic resume is off.
- settings: {
- ...getDefaultSettings(''),
- nativeChatProviders: EVERY_AGENT_CHAT,
- nativeChatResumeWorkOnRestart: false
- }
- })
- })
-
- afterEach(() => {
- cleanup()
- resetLocalStructuredChatsForTests()
- Reflect.deleteProperty(window, 'api')
- _resetNativeChatRestartOffer()
- consumeNativeChatResumeOnRestartDialogRequest()
- useAppStore.setState(useAppStore.getInitialState(), true)
- })
-
- // The count can lag the host — another window may have dismissed the offer. The re-read decides.
- it('does not reopen the dialog when the host no longer offers anything', async () => {
- rpc.mockResolvedValueOnce({ sessions: candidates }).mockResolvedValue({ sessions: [] })
- await mount()
-
- expect(getNativeChatResumeOnRestartDialogRequest()).toBe(false)
- await act(async () => screen.getByRole('button').click())
- expect(getNativeChatResumeOnRestartDialogRequest()).toBe(false)
- expect(screen.queryByRole('button')).toBeNull()
- })
-
- // The setting picks what new agents open as; chats that already exist keep their offer.
- it('offers to continue the chats this machine holds while the setting is off', async () => {
- rpc.mockResolvedValue({ sessions: candidates })
- useAppStore.setState({
- settings: {
- ...getDefaultSettings(''),
- nativeChatProviders: {},
- nativeChatResumeWorkOnRestart: false
- }
- })
- stageLocalHost(true)
- await mount()
-
- expect(rpc).toHaveBeenCalledWith(expect.anything(), 'agentSession.restartResumable')
- expect(screen.getByRole('button')).toBeTruthy()
- })
-
- // The offer is this machine's runtime's; a paired server's chats are no reason to build it.
- it("does not ask this machine for an offer over a paired server's chats", async () => {
- rpc.mockResolvedValue({ sessions: candidates })
- useAppStore.setState({
- settings: { ...getDefaultSettings(''), nativeChatProviders: {} },
- unifiedTabsByWorktree: {
- 'wt-1': [
- {
- id: 'agent-session:claude_1',
- entityId: 'claude_1',
- groupId: 'group-1',
- worktreeId: 'wt-1',
- executionHostId: 'runtime:server-1',
- contentType: 'agent-session',
- agentSessionAgent: 'claude',
- label: 'Claude Chat',
- customLabel: null,
- color: null,
- sortOrder: 0,
- createdAt: 1
- }
- ]
- }
- })
- stageLocalHost(false)
- await mount()
-
- expect(rpc).not.toHaveBeenCalled()
- expect(screen.queryByRole('button')).toBeNull()
- })
-
- it('keeps run-only uncertainty reachable until its viewed summary is closed', async () => {
- rpc.mockResolvedValue({ sessions: [candidates[0]], failed: [] })
- await mount()
- rpc.mockImplementation(async (_target, method) => {
- if (method === 'agentSession.restartContinue') {
- throw new Error('accepted reply lost')
- }
- return { sessions: [], failed: [] }
- })
- await act(async () => localNativeChatRestartStore.continueNativeChatRestartOffer(['a']))
- const entry = screen.getByRole('button', {
- name: '1 chat to check after resuming. Click for details.'
- })
- expect(screen.queryByText(/failed to resume/)).toBeNull()
- await act(async () => entry.click())
- expect(getNativeChatResumeOnRestartDialogRequest()).toBe(true)
- const run = localNativeChatRestartStore.getNativeChatRestartRun()!
- act(() => {
- localNativeChatRestartStore.markFinishedNativeChatRestartRunShown(run)
- localNativeChatRestartStore.releaseFinishedNativeChatRestartRun()
- })
- expect(screen.queryByRole('button')).toBeNull()
- })
-})
diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-close-admission.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-close-admission.ts
index 522ec0b93be..ce230942d68 100644
--- a/src/renderer/src/components/tab-bar/cli-chat-resume-close-admission.ts
+++ b/src/renderer/src/components/tab-bar/cli-chat-resume-close-admission.ts
@@ -23,10 +23,8 @@ import { cliChatResumeClosingPaneKeys } from './cli-chat-resume-close-terminal'
import { cliConversationExitGuidance } from '@/lib/cli-conversation-exit-guidance'
import type { AgentSessionLaunchPlan } from '@/lib/agent-session/launch/routing/agent-session-launch-plan'
import { structuredLaunchesHoldingIdentity } from '@/lib/agent-session/launch/structured-agent-session-launch-holders'
-import {
- structuredLaunchIdentity,
- type StructuredLaunchState
-} from '@/lib/agent-session/launch/structured-agent-session-launch-registry'
+import { structuredLaunchIdentity } from '@/lib/agent-session/launch/structured-agent-session-launch-registry'
+import type { StructuredLaunchState } from '@/lib/agent-session/launch/structured-agent-session-launch-state-store'
import { openStructuredAgentSessionProvisionalTab } from '@/lib/agent-session/launch/structured-agent-session-launch-surface'
/** keep: the agent quit, so the terminal stays; close: continuing stops the pane's agent;
diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts
index 044bacbe8dc..204bd895dc1 100644
--- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts
+++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts
@@ -85,53 +85,18 @@ vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (import
).runtimeLayoutClientWithTestFrames(await importOriginal())
)
-import { adoptAgentSessionLaunchVerdict } from '@/lib/agent-session/launch/routing/agent-session-launch-plan'
-import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id'
-import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/agent-session/structured-agent-session-provisional-tab'
-import {
- getStructuredAgentSessionLaunchLifecycle,
- resetStructuredAgentLaunchRegistryForTests,
- structuredLaunchStates
-} from '@/lib/agent-session/launch/structured-agent-session-launch-registry'
-import { retryStructuredAgentSessionLaunch } from '@/lib/agent-session/launch/structured-agent-session-launch'
-import {
- readStructuredAgentLaunchRecord,
- writeStructuredAgentLaunchRecord,
- resetStructuredAgentLaunchPersistenceForTests
-} from '@/lib/agent-session/launch/structured-agent-session-launch-persistence'
-import {
- reserveStructuredLaunchSlot,
- restoreStructuredLaunchSurfaces,
- stopStructuredLaunchSlotTracking
-} from '@/lib/agent-session/launch/structured-agent-session-launch-surface'
-import { applyStructuredSessionTabSnapshots } from '@/runtime/local-structured-session-tabs-sync/snapshot-apply'
-import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session'
-import { buildHydratedTabState } from '@/store/slices/tabs/tabs-hydration'
-import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
-import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types'
import { useAppStore } from '@/store'
import { runCliChatResume } from './cli-chat-resume-run'
import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/workspace/activation/initial-surface/empty-workspace-default-surface-claims'
-import {
- clearWebSessionFocusIntent,
- peekWebSessionFocusIntent
-} from '@/runtime/web-session-tabs-sync/navigation/web-session-focus-intent'
-import { structuredAgentSessionFocusOwner } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner'
-import { registerSessionTabIpcBridge } from '@/hooks/ipc-events/session-tab-ipc-bridge'
+
import {
drawTabsFromMain,
type TabsDrawnFromMain
} from '@/store/slices/tabs/tabs-drawn-from-main.test-fixture'
-import {
- SOURCE,
- deferred,
- refuse,
- resetCliChatResumeRun,
- tabs
-} from './cli-chat-resume-run.test-fixture'
+import { SOURCE, deferred, resetCliChatResumeRun, tabs } from './cli-chat-resume-run.test-fixture'
let main: TabsDrawnFromMain | undefined
afterEach(() => {
@@ -145,46 +110,6 @@ beforeEach(async () => {
main = await drawTabsFromMain(useAppStore)
})
-// A fixed version: later snapshots in a test count up from it.
-const SNAPSHOT_VERSION = 1_700_000_000_000
-
-function snapshot(sessionId?: string): RuntimeMobileSessionTabsResult {
- return {
- worktree: 'wt-1',
- publicationEpoch: 'publication-test',
- snapshotVersion: SNAPSHOT_VERSION,
- activeGroupId: null,
- activeTabId: null,
- activeTabType: null,
- tabs: sessionId
- ? [
- {
- type: 'agent-session',
- id: `agent-session:${sessionId}`,
- sessionId,
- agent: 'claude',
- title: 'Chat',
- isActive: false
- }
- ]
- : []
- }
-}
-
-/** Main takes the store's current layout, as after a restart; seeding after it is invisible to main. */
-async function redrawFromMain(): Promise {
- main?.close()
- main = await drawTabsFromMain(useAppStore)
-}
-
-async function seedTabs() {
- const seeded = ['E', 'S', 'B'].map((id) =>
- useAppStore.getState().createUnifiedTab('wt-1', 'editor', { id, entityId: id })
- )
- await redrawFromMain()
- return seeded
-}
-
describe('CLI identity resume through the existing launch owner', () => {
it('shares pending, sends only an advertised source, and survives source closure after dispatch', async () => {
const reply = deferred()
@@ -207,256 +132,4 @@ describe('CLI identity resume through the existing launch owner', () => {
expect(tabs()).toHaveLength(1)
expect(isEmptyWorkspaceDefaultSurfacePending('wt-1')).toBe(false)
})
-
- it('retires an unsent click during create capability waiting, even if the same source returns', async () => {
- const capability = deferred()
- mocks.createCapability.mockReturnValue(capability.promise)
- const running = runCliChatResume(SOURCE)
- await vi.waitFor(() => expect(mocks.createCapability).toHaveBeenCalledOnce())
- mocks.source = null
- useAppStore.setState({})
- await running
- mocks.source = SOURCE
- capability.resolve(true)
- await vi.waitFor(() => expect([...structuredLaunchStates()]).toHaveLength(0))
- expect(mocks.call).not.toHaveBeenCalled()
- expect(tabs()).toEqual([])
- expect(mocks.toast).not.toHaveBeenCalled()
- })
-
- it('keeps the eager History joiner failed and retryable after the hidden starter is refused', async () => {
- const reply = deferred()
- mocks.call.mockReturnValue(reply.promise)
- const running = runCliChatResume(SOURCE)
- await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledOnce())
- const sessionId: string = mocks.call.mock.calls[0][2].envelope.sessionId
- const eager = beginStructuredAgentSessionProvisionalLaunch({
- hooks: {},
- plan: adoptAgentSessionLaunchVerdict({
- route: 'structured-native-chat',
- requestId: newAgentLaunchRequestId(),
- agent: 'claude',
- worktreeId: 'wt-1',
- executionHostId: 'local',
- resumeFrom: { providerSessionId: 'provider-1' }
- })
- })
- await vi.waitFor(() => expect(tabs()).toHaveLength(1))
- reply.resolve({ ok: false, refusal: refuse('transcriptUnreadable') })
- await Promise.all([running, eager?.settlement])
- expect(mocks.call).toHaveBeenCalledOnce()
- expect(getStructuredAgentSessionLaunchLifecycle('wt-1', sessionId)).toBe('failed')
- expect(readStructuredAgentLaunchRecord(sessionId)?.lifecycle).toBe('failed')
- mocks.call.mockResolvedValue({ ok: true, value: { sessionId, fence: 1 } })
- expect(retryStructuredAgentSessionLaunch('wt-1', sessionId)).toBe(true)
- await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2))
- expect(mocks.call.mock.calls[1][2].envelope.sessionId).toBe(sessionId)
- await vi.waitFor(() =>
- expect(getStructuredAgentSessionLaunchLifecycle('wt-1', sessionId)).toBeNull()
- )
- expect(tabs()).toHaveLength(1)
- })
-
- it.each([false, true])(
- 'still opens an eager History joiner after the terminal closes before create (frame-drawn: %s)',
- async (frameDrawn) => {
- mocks.frameDrawn = frameDrawn
- const capability = deferred()
- mocks.createCapability.mockReturnValue(capability.promise)
- const running = runCliChatResume(SOURCE)
- await vi.waitFor(() => expect(mocks.createCapability).toHaveBeenCalledOnce())
- const eager = beginStructuredAgentSessionProvisionalLaunch({
- hooks: {},
- plan: adoptAgentSessionLaunchVerdict({
- route: 'structured-native-chat',
- requestId: newAgentLaunchRequestId(),
- agent: 'claude',
- worktreeId: 'wt-1',
- executionHostId: 'local',
- resumeFrom: { providerSessionId: 'provider-1' }
- })
- })
- await vi.waitFor(() =>
- expect(
- [...structuredLaunchStates()][0]?.intent.params.resumeFrom?.cliSource
- ).toBeUndefined()
- )
- mocks.source = null
- useAppStore.setState({})
- capability.resolve(true)
- await Promise.all([running, eager?.settlement])
- expect(mocks.call).toHaveBeenCalledOnce()
- expect(mocks.call.mock.calls[0][2].resumeFrom).toEqual({ providerSessionId: 'provider-1' })
- expect(mocks.call.mock.calls[0][2].tabPlacement).toEqual(
- frameDrawn ? { groupId: 'g-1' } : undefined
- )
- expect(tabs()).toHaveLength(1)
- expect(mocks.toast).not.toHaveBeenCalled()
- }
- )
-
- it.each([
- ['reply', 'B', 'B E S R', 'B E S D R'],
- ['inventory', 'E', 'S B R E', 'S B D R E'],
- ['reply', 'E', 'S B E R', 'S B D E R'],
- ['inventory', 'B', 'R S E B', 'R S E D B']
- ])(
- 'keeps canonical membership through registered IPC (%s first, move %s to %s)',
- async (first, mover, requested, expected) => {
- const [e, source, browser] = await seedTabs()
- let move: Parameters[0] = () => {}
- vi.stubGlobal('api', {
- ...window.api,
- ui: {
- ...window.api?.ui,
- onCloseSessionTab: () => () => {},
- onSessionTabCloseRequest: () => () => {},
- onMoveSessionTab: (callback: typeof move) => {
- move = callback
- return () => {}
- }
- }
- })
- registerSessionTabIpcBridge([])
- const reply = deferred()
- mocks.call.mockReturnValue(reply.promise)
- const running = runCliChatResume(SOURCE)
- await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledOnce())
- const sessionId: string = mocks.call.mock.calls[0][2].envelope.sessionId
- const slotId = `structured-agent-session-${sessionId}`
- const store = useAppStore.getState()
- const order = store.groupsByWorktree['wt-1'][0].tabOrder
- expect(order).toEqual([e.id, source.id, browser.id, slotId])
- const later = useAppStore
- .getState()
- .createUnifiedTab('wt-1', 'editor', { id: 'R', entityId: 'R' })
- await redrawFromMain()
- const beforeNoop = useAppStore.getState()
- move({
- kind: 'reorder',
- worktreeId: 'wt-1',
- targetGroupId: e.groupId,
- tabId: browser.id,
- tabOrder: [e.id, source.id, browser.id, later.id]
- })
- expect(useAppStore.getState()).toBe(beforeNoop)
- move({
- kind: 'reorder',
- worktreeId: 'wt-1',
- targetGroupId: e.groupId,
- tabId: mover,
- tabOrder: requested.split(' ')
- })
- const expectedOrder = expected.split(' ').map((id) => (id === 'D' ? slotId : id))
- expect(useAppStore.getState().groupsByWorktree['wt-1'][0].tabOrder).toEqual(expectedOrder)
- expect(readStructuredAgentLaunchRecord(sessionId)?.surfaceAddress).toEqual({
- worktreeId: 'wt-1',
- targetGroupId: e.groupId,
- precedingTabIds: expectedOrder.slice(0, expectedOrder.indexOf(slotId))
- })
- const other = useAppStore.getState().createUnifiedTab('wt-1', 'editor', {
- entityId: 'other',
- split: { splitDirection: 'right', sourceGroupId: e.groupId }
- })
- await redrawFromMain()
- clearWebSessionFocusIntent(structuredAgentSessionFocusOwner({ kind: 'local' }), 'wt-1')
- if (first === 'inventory') {
- applyStructuredSessionTabSnapshots([snapshot(sessionId)])
- }
- reply.resolve({ ok: true, value: { sessionId, fence: 1 } })
- await running
- expect(
- useAppStore.getState().groupsByWorktree['wt-1'].find((group) => group.id === e.groupId)
- ?.tabOrder
- ).toEqual(expectedOrder)
- expect(useAppStore.getState().activeGroupIdByWorktree['wt-1']).toBe(other.groupId)
- useAppStore.getState().moveUnifiedTabToGroup(slotId, other.groupId)
- applyStructuredSessionTabSnapshots([
- { ...snapshot(sessionId), snapshotVersion: SNAPSHOT_VERSION + 1 }
- ])
- expect(tabs().find((tab) => tab.entityId === sessionId)?.groupId).toBe(other.groupId)
- }
- )
-
- it.each([false, true])(
- 'keeps overlapping requests in their canonical order (second finishes first: %s)',
- async (reverse) => {
- const initial = await seedTabs()
- const replies = [deferred(), deferred()]
- mocks.call
- .mockImplementationOnce(() => replies[0].promise)
- .mockImplementationOnce(() => replies[1].promise)
- const first = runCliChatResume(SOURCE)
- await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(1))
- const secondSource = { ...SOURCE, providerSessionId: 'provider-2' }
- mocks.source = secondSource
- const second = runCliChatResume(secondSource)
- await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2))
- const ids: string[] = mocks.call.mock.calls.map((call) => call[2].envelope.sessionId)
- for (const index of reverse ? [1, 0] : [0, 1]) {
- replies[index].resolve({ ok: true, value: { sessionId: ids[index], fence: 1 } })
- await (index === 0 ? first : second)
- }
- expect(useAppStore.getState().groupsByWorktree['wt-1'][0].tabOrder).toEqual([
- ...initial.map((tab) => tab.id),
- ...ids.map((id) => `structured-agent-session-${id}`)
- ])
- }
- )
-
- it('restores a pending-only group as unknown without sending create or restoring focus', async () => {
- const record = {
- sessionId: 'reload-pending',
- executionHostId: 'local' as const,
- agent: 'claude' as const,
- lifecycle: 'pending' as const,
- clientOperationId: 'original-operation',
- payloadFingerprint: 'fingerprint',
- expectedRuntimeFence: null,
- surfaceAddress: { worktreeId: 'wt-1', precedingTabIds: [] }
- }
- writeStructuredAgentLaunchRecord(record)
- const firstGroup = vi.fn()
- const unsubscribe = useAppStore.subscribe((state) => {
- const group = state.groupsByWorktree['wt-1']?.[0]
- if (group) {
- firstGroup(group)
- }
- })
- reserveStructuredLaunchSlot(record)
- unsubscribe()
- expect(firstGroup).toHaveBeenCalledTimes(1)
- expect(firstGroup.mock.calls[0][0]).toMatchObject({
- tabOrder: ['structured-agent-session-reload-pending'],
- activeTabId: null
- })
- expect(firstGroup.mock.calls[0][0].recentTabIds ?? []).toEqual([])
- expect(tabs()).toHaveLength(0)
- const session = buildWorkspaceSessionPayload(useAppStore.getState())
- stopStructuredLaunchSlotTracking()
- resetStructuredAgentLaunchPersistenceForTests()
- resetStructuredAgentLaunchRegistryForTests()
- useAppStore.setState(useAppStore.getInitialState(), true)
- useAppStore.setState({
- ...buildHydratedTabState(session, new Set(['wt-1'])),
- worktreesByRepo: { repo: [makeWorktree({ id: 'wt-1', repoId: 'repo', hostId: 'local' })] }
- })
- await redrawFromMain()
- restoreStructuredLaunchSurfaces()
- restoreStructuredLaunchSurfaces()
- applyStructuredSessionTabSnapshots([snapshot()])
- await main?.settle()
- expect(mocks.call).not.toHaveBeenCalled()
- expect(
- peekWebSessionFocusIntent(structuredAgentSessionFocusOwner({ kind: 'local' }), 'wt-1')
- ).toBeNull()
- expect(tabs()).toHaveLength(1)
- expect(getStructuredAgentSessionLaunchLifecycle('wt-1', 'reload-pending')).toBe(
- 'visibility-unknown'
- )
- expect(readStructuredAgentLaunchRecord('reload-pending')?.clientOperationId).toBe(
- 'original-operation'
- )
- expect(useAppStore.getState().groupsByWorktree['wt-1'][0].recentTabIds ?? []).toEqual([])
- })
})
diff --git a/src/renderer/src/components/tab-group/SplitPaneLanding.tsx b/src/renderer/src/components/tab-group/SplitPaneLanding.tsx
index b8675b5aefe..e4f3678719e 100644
--- a/src/renderer/src/components/tab-group/SplitPaneLanding.tsx
+++ b/src/renderer/src/components/tab-group/SplitPaneLanding.tsx
@@ -1,16 +1,8 @@
-import { useRef } from 'react'
-import {
- FilePlus,
- Globe,
- History,
- Search,
- Smartphone,
- TerminalSquare,
- type LucideIcon
-} from 'lucide-react'
+import { useRef, useState } from 'react'
+import { FilePlus, Globe, Smartphone, TerminalSquare, type LucideIcon } from 'lucide-react'
import { useShallow } from 'zustand/react/shallow'
import { useAppStore } from '../../store'
-import { useShortcutKeyDetails, type ShortcutKeyComboDetails } from '@/hooks/useShortcutLabel'
+import { useOptionalShortcutLabel } from '@/hooks/useShortcutLabel'
import { useTranslate } from '@/i18n/use-translate'
import {
ensureClientCreationActionAllowed,
@@ -23,12 +15,19 @@ import {
ensureSimulatorTab,
getSimulatorTabForWorktree
} from '@/lib/simulator/tabs/ensure-simulator-tab'
-import { SplitPaneLandingAgentRow } from './SplitPaneLandingAgentRow'
+import { useFileListWorktree } from '@/store/workspaces/selection/use-selected-worktree'
+import { Button } from '@/components/ui/button'
import {
- LANDING_ROW_CLASS,
- LandingRowShortcut,
- moveLandingRowFocus
-} from './split-pane-landing-row'
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList
+} from '@/components/ui/command'
+import { LandingAgentResults, LandingDefaultAgentItem } from './split-pane-landing-agents'
+import { LandingFileResults } from './split-pane-landing-files'
+import { LandingItemShortcut, landingQueryMatches } from './split-pane-landing-item'
/** Fills an empty split pane so the user picks what opens there; each action creates into this group. */
export function SplitPaneLanding({
@@ -45,6 +44,11 @@ export function SplitPaneLanding({
}): React.JSX.Element {
const t = useTranslate()
const listRef = useRef(null)
+ const [selected, setSelected] = useState('')
+ const [agentPickerOpen, setAgentPickerOpen] = useState(false)
+ const inputRef = useRef(null)
+ const [query, setQuery] = useState('')
+ const worktreePath = useFileListWorktree(worktreeId)?.path ?? null
// Why: paired web clients without host streaming hide these, as the tab bar's + menu does.
const [browserEnabled, emulatorEnabled] = useAppStore(
useShallow((state) => {
@@ -56,15 +60,10 @@ export function SplitPaneLanding({
] as const
})
)
- const canReopen = useAppStore(
- (state) => (state.recentlyClosedTabKindsByWorktree[worktreeId]?.length ?? 0) > 0
- )
- const terminalShortcut = useShortcutKeyDetails('tab.newTerminal')
- const browserShortcut = useShortcutKeyDetails('tab.newBrowser')
- const markdownShortcut = useShortcutKeyDetails('tab.newMarkdown')
- const quickOpenShortcut = useShortcutKeyDetails('worktree.quickOpen')
- const emulatorShortcut = useShortcutKeyDetails('tab.newSimulator')
- const reopenShortcut = useShortcutKeyDetails('tab.reopenClosed')
+ const terminalShortcut = useOptionalShortcutLabel('tab.newTerminal')
+ const browserShortcut = useOptionalShortcutLabel('tab.newBrowser')
+ const markdownShortcut = useOptionalShortcutLabel('tab.newMarkdown')
+ const emulatorShortcut = useOptionalShortcutLabel('tab.newSimulator')
const openTerminal = (): void => {
void openNewTerminalTabInWorkspace(useAppStore.getState, worktreeId, groupId).catch(
@@ -97,7 +96,7 @@ export function SplitPaneLanding({
)
}
- const rows: LandingRow[] = [
+ const actions: LandingAction[] = [
{
id: 'terminal',
icon: TerminalSquare,
@@ -121,13 +120,6 @@ export function SplitPaneLanding({
shortcut: markdownShortcut,
onSelect: openMarkdown
},
- {
- id: 'quick-open',
- icon: Search,
- label: t('components.tabGroup.splitPaneLanding.goToFile', 'Go to file'),
- shortcut: quickOpenShortcut,
- onSelect: () => useAppStore.getState().openModal('quick-open')
- },
emulatorEnabled
? {
id: 'emulator',
@@ -137,74 +129,151 @@ export function SplitPaneLanding({
onSelect: openEmulator
}
: null
- ].filter((row): row is LandingRow => row !== null)
+ ].filter(
+ (action): action is LandingAction => action !== null && landingQueryMatches(action.label, query)
+ )
+ const searching = query.trim() !== ''
+
+ // Why: cmdk pulls focus into its input on every selection change, so the list keeps focus
+ // outside the Command root and drives its selection here; / moves into the field.
+ const onKeyDown = (event: React.KeyboardEvent): void => {
+ const input = inputRef.current
+ if (event.target === input) {
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ if (query !== '') {
+ setQuery('')
+ } else {
+ listRef.current?.focus()
+ }
+ }
+ return
+ }
+ if (event.target !== listRef.current) {
+ return
+ }
+ if (event.key === '/') {
+ event.preventDefault()
+ input?.focus()
+ } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault()
+ setSelected(stepLandingSelection(listRef.current, selected, event.key === 'ArrowDown'))
+ } else if (event.key === 'ArrowRight' && selected === 'default-agent') {
+ event.preventDefault()
+ setAgentPickerOpen(true)
+ } else if (event.key === 'Enter') {
+ event.preventDefault()
+ listRef.current.querySelector('[cmdk-item][data-selected="true"]')?.click()
+ }
+ }
return (
-
- {t('components.tabGroup.splitPaneLanding.heading', 'Open in this pane')}
-
moveLandingRowFocus(event, listRef.current)}
+ tabIndex={-1}
+ autoFocus={autoFocus}
+ className="outline-none"
+ onKeyDown={onKeyDown}
>
-