Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions website/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import UpdateModal from './components/UpdateModal'
import ComputerUseLiveView from './components/ComputerUseLiveView'
import BottomTerminalPanel, { TerminalDetachedBar } from './components/BottomTerminalPanel'
import { toggleBottomTerminal } from './hooks/useBottomTerminal'
import { RunInTerminalShellNotice, useRunInTerminalShellBridge } from './shell/runInTerminalShellBridge'
import { TerminalHostContext } from './hooks/useTerminalCommand'
// Side effect: closes a terminal tab when its shell exits (main window and popout).
import './utils/terminalExitClose'
Expand Down Expand Up @@ -312,6 +313,8 @@ export default function App() {
setUpdateError, startupVideo, reportProblemOpen, setReportProblemOpen, effectiveCollapsed, activePath,
libraryNavActive, discoverNavActive, isChat, needsFixedHeight, navRowActive, membersRoute, mobileSingle,
} = shell
// "Run in terminal" from a code block outside every chat, on any route.
const runInTerminal = useRunInTerminalShellBridge(activeSlotProject, !isPopout && !isEmbed)

/**
* Phone chat page: the main navigation as a 72px icon rail.
Expand Down Expand Up @@ -888,6 +891,7 @@ export default function App() {
<KiroAccountModal open={kiroUsageOpen} onClose={() => setKiroUsageOpen(false)} usage={kiroUsageState} />
<Lightbox />
<ImportSessionOutcomeNotice />
<RunInTerminalShellNotice error={runInTerminal.error} onDismiss={runInTerminal.dismiss} />
</LocalOverlayRoot>
</div>{/* /Local pane */}
{/* Remote instance panes — embedded dashboards kept warm (mounted, hidden)
Expand Down
25 changes: 21 additions & 4 deletions website/src/hooks/useRunInTerminalBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,18 @@ export interface RunInTerminalBridgeOptions extends RunInTerminalRefs {
* RunInTerminalScope). Only the chat page does: it is where every request
* went before scopes existed. */
acceptUnscoped?: boolean
/** Answer unscoped requests only while no `acceptUnscoped` host is mounted.
* The app shell sets it, so a code block on a page with no chat (an app,
* a knowledge doc) still gets an answer, while the chat page keeps its own
* unscoped requests and one click never opens two terminals. */
unscopedFallback?: boolean
}

/** How many mounted hosts answer unscoped requests (`acceptUnscoped`). A
* fallback host stands down while this is above zero. Read at event time, so
* the order the listeners were added in does not matter. */
let unscopedHosts = 0

/**
* The reuse-current setting and the PTY-delete mutation, mirrored onto refs for
* useRunInTerminalBridge, for a host other than the chat page (which keeps its
Expand Down Expand Up @@ -82,21 +92,28 @@ export function useRunInTerminalBridge({
cwdRef,
readyRef,
acceptUnscoped = false,
unscopedFallback = false,
deleteTerminalSessionRef,
terminalReuseRef,
terminalCfgUnsettledRef,
terminalCfgReadFailedRef,
}: RunInTerminalBridgeOptions): string {
const scope = useId()
useEffect(() => {
if (!acceptUnscoped) return
unscopedHosts += 1
return () => { unscopedHosts -= 1 }
}, [acceptUnscoped])
useEffect(() => {
const answersUnscoped = () => acceptUnscoped || (unscopedFallback && unscopedHosts === 0)
const handler = (e: Event) => {
const detail = (e as CustomEvent).detail || {}
const code: string = detail.code
const reqId: string = detail.reqId
const lang: string | undefined = typeof detail.lang === 'string' ? detail.lang : undefined
// Another host's chat (or, without acceptUnscoped, an emitter outside
// every scope): not ours to answer.
if (typeof detail.scope === 'string' ? detail.scope !== scope : !acceptUnscoped) return
// Another host's chat (or an emitter outside every scope that another
// host answers, or that this host never answers): not ours to answer.
if (typeof detail.scope === 'string' ? detail.scope !== scope : !answersUnscoped()) return
if (typeof code !== 'string' || !code) return
// Opt-in reuse focuses the terminal tab the user selected and copies the
// command for a manual paste. Sending raw bytes into a live terminal is
Expand Down Expand Up @@ -327,6 +344,6 @@ export function useRunInTerminalBridge({
return () => window.removeEventListener('mc:run-in-terminal', handler)
// All are stable for the host's lifetime (a context client, a []-dep
// useCallback, refs and a useId), so the listener still installs once.
}, [scope, acceptUnscoped, queryClient, showActionError, cwdRef, readyRef, deleteTerminalSessionRef, terminalReuseRef, terminalCfgUnsettledRef, terminalCfgReadFailedRef])
}, [scope, acceptUnscoped, unscopedFallback, queryClient, showActionError, cwdRef, readyRef, deleteTerminalSessionRef, terminalReuseRef, terminalCfgUnsettledRef, terminalCfgReadFailedRef])
return scope
}
75 changes: 75 additions & 0 deletions website/src/shell/runInTerminalShellBridge.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'

import ErrorNotice from '../components/ErrorNotice'
import { useRunInTerminalBridge, useRunInTerminalRefs } from '../hooks/useRunInTerminalBridge'
import { i18nT } from '../i18n/t'

/**
* The shell's "Run in terminal" receiver. A code block outside every chat (an
* app page, a knowledge doc) sends its request with no scope, and before this
* only the chat page answered those, so off /chat the button timed out. The
* dock terminal is app-wide, so the shell answers them on every route, in the
* selected session's project. It stands down while the chat page is mounted,
* which still answers them itself (`unscopedFallback`).
*
* A hook, called from App's own body after useAppShell, so its config read
* joins the shell's ['kirocrewConfig'] read at the same place in boot order.
* `hasDock` is false in popout and embed windows, which render no dock panel:
* there the shell answers nothing rather than open a tab no one can see.
* Returns the failure to show and its dismiss.
*/
export function useRunInTerminalShellBridge(cwd: string | undefined, hasDock: boolean): { error: string; dismiss: () => void } {
const queryClient = useQueryClient()
const [error, setError] = useState('')
const showActionError = useCallback((message: string) => setError(message), [])
const dismiss = useCallback(() => setError(''), [])
// A run that succeeds after a failure proves the old notice wrong: clear it,
// so "Couldn't run in terminal" never sits over a terminal that just ran.
// Except the config-read failure: that run still succeeds (in a fresh tab),
// and the notice is about the ignored reuse setting, which success does not fix.
useEffect(() => {
const configReadFailed = i18nT('pages.chatPage.run_in_terminal_config_read_failed_error')
const onResult = (e: Event) => {
if ((e as CustomEvent).detail?.ok !== true) return
setError(prev => (prev === configReadFailed ? prev : ''))
}
window.addEventListener('mc:run-in-terminal-result', onResult)
return () => window.removeEventListener('mc:run-in-terminal-result', onResult)
}, [])
const cwdRef = useRef(cwd)
cwdRef.current = cwd
const refs = useRunInTerminalRefs()
useRunInTerminalBridge({
queryClient,
showActionError,
cwdRef,
unscopedFallback: hasDock,
...refs,
})
return { error, dismiss }
}

/**
* The shell receiver's failures, fixed over the page, because the page under
* it may be any route. Dismiss-only: an Ask Agent hand-off navigates to chat,
* and that would drop an unsaved edit on the page the user is on.
*/
export function RunInTerminalShellNotice({ error, onDismiss }: { error: string; onDismiss: () => void }) {
if (!error) return null
return (
<div className="fixed left-1/2 top-safe-offset-3 z-[80] w-[min(640px,calc(100vw-1.5rem))] -translate-x-1/2 rounded-lg bg-card shadow-xl">
{/* No hand-off: Ask Agent navigates to /chat, and this notice can sit
over /artifacts/<slug> while its document editor holds unsaved edits
(ArtifactDetailPage's `dirty` edit buffer, which navigating away
destroys). The hand-off would discard that draft. */}
<ErrorNotice
title={i18nT('components.runInTerminalBtn.couldn_t_run_in_terminal')}
message={error}
onDismiss={onDismiss}
askAgent={false}
testId="run-in-terminal-error"
/>
</div>
)
}
20 changes: 20 additions & 0 deletions website/src/test/App.terminalNavActive.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { http, HttpResponse } from 'msw'
import { server } from '../../integration/mocks/server'
import { renderWithProviders } from './helpers'
import App from '../App'
import { api } from '../api/client'
import { setTerminalEnabledFlag } from '../utils/terminalRegistry'
import { __resetBottomTerminal, openBottomTerminal } from '../hooks/useBottomTerminal'

Expand Down Expand Up @@ -56,6 +57,7 @@ vi.mock('../api/client', () => ({
chatSlotModel: vi.fn().mockResolvedValue({}),
chatMode: vi.fn().mockResolvedValue({}),
listInstances: vi.fn().mockResolvedValue({ instances: [], warm_set_cap: 5 }),
kirocrewConfig: vi.fn().mockResolvedValue({}),
},
isAuthBannerShown: vi.fn(() => false),
ApiError: class ApiError extends Error {
Expand Down Expand Up @@ -146,4 +148,22 @@ describe('App nav rail — Terminal row reflects the docked panel state', () =>

await waitFor(() => expect(terminalRow()).toHaveAttribute('aria-pressed', 'true'))
})

it('answers "Run in terminal" on a route with no chat page (#10708)', async () => {
// Before the shell answered unscoped requests, only the chat page did, so
// a code block on any other route got no terminal at all.
renderWithProviders(<App />, { route: '/logs' })
await waitFor(() => expect(terminalRow()).toBeInTheDocument())
expect(screen.queryByTestId('chat-page')).not.toBeInTheDocument()
// Let the reuse-setting read settle: while it is pending the run copies.
await waitFor(() => expect(api.kirocrewConfig).toHaveBeenCalled())
await act(async () => {})

act(() => {
window.dispatchEvent(new CustomEvent('mc:run-in-terminal', { detail: { code: 'npm test', reqId: 'r1' } }))
})

await waitFor(() => expect(terminalRow()).toHaveAttribute('aria-pressed', 'true'))
expect(screen.getAllByTestId('cli-panel')).toHaveLength(1)
})
})
159 changes: 159 additions & 0 deletions website/src/test/RunInTerminalShellBridge.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/**
* The shell's Run-in-terminal receiver (shell/runInTerminalShellBridge.tsx).
*
* Pins the behavior #10708 adds: a request with no scope (a code block outside
* every chat, on any route) opens ONE dock terminal in the selected session's
* project, the shell stands down while a host that answers unscoped requests
* itself (the chat page) is mounted, it never answers another host's scope,
* and a failed run shows a dismiss-only notice.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { render, renderHook, act, screen, within, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useRef, type ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const term = vi.hoisted(() => ({ unsub: vi.fn() }))
const cfg = vi.hoisted(() => ({ fail: false }))
vi.mock('../api/client', async (importOriginal) => {
const actual = await importOriginal<typeof import('../api/client')>()
return {
...actual,
api: { ...actual.api, kirocrewConfig: () => (cfg.fail ? Promise.reject(new Error('down')) : Promise.resolve({})) },
}
})
vi.mock('../utils/terminalRegistry', async (importOriginal) => ({
...(await importOriginal<typeof import('../utils/terminalRegistry')>()),
onTerminalReady: () => term.unsub,
}))

import { RunInTerminalShellNotice, useRunInTerminalShellBridge } from '../shell/runInTerminalShellBridge'

function RunInTerminalShellBridge({ cwd, hasDock = true }: { cwd: string | undefined; hasDock?: boolean }) {
const { error, dismiss } = useRunInTerminalShellBridge(cwd, hasDock)
return <RunInTerminalShellNotice error={error} onDismiss={dismiss} />
}
import { useRunInTerminalBridge, useRunInTerminalRefs } from '../hooks/useRunInTerminalBridge'
import { __resetBottomTerminal, addTab, MAX_TERMINALS, useBottomTerminal } from '../hooks/useBottomTerminal'

function client() {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
// A settled config read with reuse off: the run path, not the copy path.
qc.setQueryData(['kirocrewConfig'], {})
return qc
}

const run = (detail: Record<string, unknown>) => act(() => {
window.dispatchEvent(new CustomEvent('mc:run-in-terminal', { detail }))
})

/** A stand-in for the chat page: a host that answers unscoped requests. */
function UnscopedHost({ qc }: { qc: QueryClient }) {
const cwdRef = useRef<string | undefined>('/chat-project')
useRunInTerminalBridge({ queryClient: qc, showActionError: () => {}, cwdRef, acceptUnscoped: true, ...useRunInTerminalRefs() })
return null
}

describe('RunInTerminalShellBridge', () => {
let qc: QueryClient
let results: Array<{ reqId: string; ok: boolean }>
const onResult = (e: Event) => { results.push((e as CustomEvent).detail) }
const wrap = (node: ReactNode) => <QueryClientProvider client={qc}>{node}</QueryClientProvider>

beforeEach(() => {
__resetBottomTerminal()
qc = client()
results = []
cfg.fail = false
window.addEventListener('mc:run-in-terminal-result', onResult)
})
afterEach(() => {
window.removeEventListener('mc:run-in-terminal-result', onResult)
act(() => { __resetBottomTerminal() })
})

it('opens one dock terminal in the selected project for an unscoped request', () => {
const dock = renderHook(() => useBottomTerminal())
render(wrap(<RunInTerminalShellBridge cwd="/proj" />))
run({ code: 'npm test', reqId: 'r1' })
expect(dock.result.current.tabs).toEqual([expect.objectContaining({ cwd: '/proj' })])
})

it('starts in the server default when no project is selected', () => {
const dock = renderHook(() => useBottomTerminal())
render(wrap(<RunInTerminalShellBridge cwd={undefined} />))
run({ code: 'ls', reqId: 'r1' })
expect(dock.result.current.tabs).toHaveLength(1)
expect(dock.result.current.tabs[0].cwd).toBeUndefined()
})

it('ignores a request scoped to another host and an empty command', () => {
const dock = renderHook(() => useBottomTerminal())
render(wrap(<RunInTerminalShellBridge cwd="/proj" />))
run({ code: 'ls', reqId: 'r1', scope: 'some-chat' })
run({ code: '', reqId: 'r2' })
run({ reqId: 'r3' })
expect(dock.result.current.tabs).toHaveLength(0)
expect(results).toEqual([])
})

it('answers nothing in a window with no dock (popout, embed)', () => {
const dock = renderHook(() => useBottomTerminal())
render(wrap(<RunInTerminalShellBridge cwd="/proj" hasDock={false} />))
run({ code: 'ls', reqId: 'r1' })
expect(dock.result.current.tabs).toHaveLength(0)
expect(results).toEqual([])
})

it('stands down while the chat page answers unscoped requests, and resumes when it unmounts', () => {
const dock = renderHook(() => useBottomTerminal())
render(wrap(<RunInTerminalShellBridge cwd="/proj" />))
const chat = render(wrap(<UnscopedHost qc={qc} />))
run({ code: 'ls', reqId: 'r1' })
// Exactly one terminal for one click, and it is the chat page's.
expect(dock.result.current.tabs).toEqual([expect.objectContaining({ cwd: '/chat-project' })])
chat.unmount()
run({ code: 'ls', reqId: 'r2' })
expect(dock.result.current.tabs).toHaveLength(2)
expect(dock.result.current.tabs[1].cwd).toBe('/proj')
})

it('answers ok:false and shows a dismiss-only notice when the terminal cap is full', async () => {
const user = userEvent.setup()
act(() => { for (let i = 0; i < MAX_TERMINALS; i++) addTab() })
render(wrap(<RunInTerminalShellBridge cwd="/proj" />))
expect(screen.queryByTestId('run-in-terminal-error')).not.toBeInTheDocument()
run({ code: 'ls', reqId: 'r1' })
expect(results).toEqual([{ reqId: 'r1', ok: false }])
const notice = screen.getByTestId('run-in-terminal-error')
expect(notice).toHaveTextContent("Couldn't run in terminal")
expect(within(notice).queryByRole('button', { name: /ask.*agent/i })).not.toBeInTheDocument()
await user.click(within(notice).getByRole('button', { name: /dismiss/i }))
expect(screen.queryByTestId('run-in-terminal-error')).not.toBeInTheDocument()
})

it('clears the failure notice once a later run succeeds, and keeps it on another failure', () => {
act(() => { for (let i = 0; i < MAX_TERMINALS; i++) addTab() })
render(wrap(<RunInTerminalShellBridge cwd="/proj" />))
run({ code: 'ls', reqId: 'r1' })
expect(screen.getByTestId('run-in-terminal-error')).toBeInTheDocument()
act(() => { window.dispatchEvent(new CustomEvent('mc:run-in-terminal-result', { detail: { reqId: 'x', ok: false } })) })
expect(screen.getByTestId('run-in-terminal-error')).toBeInTheDocument()
act(() => { window.dispatchEvent(new CustomEvent('mc:run-in-terminal-result', { detail: { reqId: 'r2', ok: true } })) })
expect(screen.queryByTestId('run-in-terminal-error')).not.toBeInTheDocument()
})

it('keeps the config-read failure notice when that same run succeeds', async () => {
// A failed reuse-setting read: the run still goes to a fresh tab.
cfg.fail = true
qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const dock = renderHook(() => useBottomTerminal())
render(wrap(<RunInTerminalShellBridge cwd="/proj" />))
await waitFor(() => expect(qc.getQueryState(['kirocrewConfig'])?.status).toBe('error'))
run({ code: 'ls', reqId: 'r1' })
expect(dock.result.current.tabs).toHaveLength(1)
expect(screen.getByTestId('run-in-terminal-error')).toBeInTheDocument()
act(() => { window.dispatchEvent(new CustomEvent('mc:run-in-terminal-result', { detail: { reqId: 'r1', ok: true } })) })
expect(screen.getByTestId('run-in-terminal-error')).toBeInTheDocument()
})
})
Loading