Scope goal reads to the session directory and stabilize the background activity tests

This commit is contained in:
Chris Scott committed 2026-11-13 19:47:13 +00:00
1 parent fc00273645
commit 80e013ec81
14 files changed
+257 -22

No files matched your search

+3
View File
@@ -114,6 +114,9 @@ DEBUG=false
# so set true explicitly for HTTPS.
# AUTH_SECURE_COOKIES=true
# Auth rate limit: maximum auth requests per client per 60 seconds (production only)
# AUTH_RATE_LIMIT_MAX=100
# OAuth Providers (optional - enable by providing client ID and secret)
# GITHUB_CLIENT_ID=
# GITHUB_CLIENT_SECRET=
+3
View File
@@ -59,6 +59,9 @@ export function createAuth(
database: db,
secret: env.SECRET,
trustedOrigins,
rateLimit: {
max: env.RATE_LIMIT_MAX,
},
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
+31 -1
View File
@@ -1,5 +1,8 @@
import { Hono } from 'hono'
import type { MiddlewareHandler } from 'hono'
import { cloneRawRequest } from 'hono/request'
import { parseJsonText } from '@opencode-manager/shared/utils'
import { z } from 'zod'
import { opencodeServerManager } from '../services/opencode-single-server'
import type { OpenCodeClient } from '../services/opencode/client'
@@ -7,6 +10,25 @@ export type OpenCodeProxyClient = Pick<OpenCodeClient, 'forwardRaw'>
export type OpenCodeLifecycleGate = Pick<typeof opencodeServerManager, 'isLifecycleInitialized'>
const RPC_PATH_SEGMENT = '/rpc/'
const RPC_UNAVAILABLE_TYPE = 'rpc.unavailable'
const RPC_WARMUP_RETRY_DELAY_MS = 300
const rpcErrorSchema = z.object({ type: z.string() })
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
async function isWarmingRpcUnavailable(response: Response): Promise<boolean> {
if (response.status !== 400) return false
const body = await response.clone().text()
const parsed = rpcErrorSchema.safeParse(parseJsonText(body))
return parsed.success && parsed.data.type === RPC_UNAVAILABLE_TYPE
}
export function createAuthenticatedOpenCodeProxyRoutes(
openCodeClient: OpenCodeProxyClient,
requireAuth: MiddlewareHandler,
@@ -19,7 +41,15 @@ export function createAuthenticatedOpenCodeProxyRoutes(
return c.json({ error: 'OpenCode lifecycle initialization is incomplete; refusing to proxy to an unmanaged server' }, 503)
}
return openCodeClient.forwardRaw(c.req.raw)
if (!c.req.path.includes(RPC_PATH_SEGMENT)) {
return openCodeClient.forwardRaw(c.req.raw)
}
const retryRequest = await cloneRawRequest(c.req)
const response = await openCodeClient.forwardRaw(c.req.raw)
if (!(await isWarmingRpcUnavailable(response))) return response
await delay(RPC_WARMUP_RETRY_DELAY_MS)
return openCodeClient.forwardRaw(retryRequest)
})
return app
@@ -211,6 +211,62 @@ describe('authenticated opencode proxy routes', () => {
expect(forwardRaw).toHaveBeenCalledTimes(1)
expect(await forwardedJson(forwardRaw)).toEqual(body)
})
function rpcUnavailable(): Response {
return new Response(
JSON.stringify({ _tag: 'RpcError', type: 'rpc.unavailable', message: 'RPC is unavailable: opencode.goal' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } },
)
}
async function rpcCall(path: string): Promise<Response> {
return buildApp(forwardRaw).request(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: { sessionID: 'ses_1' } }),
})
}
it('retries an RPC call once while the directory instance loads its RPCs', async () => {
forwardRaw
.mockResolvedValueOnce(rpcUnavailable())
.mockResolvedValueOnce(new Response(JSON.stringify({ output: null }), { status: 200 }))
vi.useFakeTimers()
try {
const pending = rpcCall('/api/opencode/rpc/opencode.goal/get')
await vi.advanceTimersByTimeAsync(0)
await vi.advanceTimersByTimeAsync(1_000)
const res = await pending
expect(res.status).toBe(200)
} finally {
vi.useRealTimers()
}
expect(forwardRaw).toHaveBeenCalledTimes(2)
expect(forwardRaw.mock.calls[1]?.[0].url).toContain('/rpc/opencode.goal/get')
})
it('does not retry an unavailable RPC outside an RPC path', async () => {
forwardRaw.mockResolvedValueOnce(rpcUnavailable())
const res = await buildApp(forwardRaw).request('/api/opencode/session/ses_1/message', { method: 'POST' })
expect(res.status).toBe(400)
expect(forwardRaw).toHaveBeenCalledTimes(1)
})
it('does not retry a different RPC failure', async () => {
forwardRaw.mockResolvedValueOnce(new Response(
JSON.stringify({ _tag: 'RpcError', type: 'rpc.failed', message: 'RPC failed' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } },
))
const res = await rpcCall('/api/opencode/rpc/opencode.goal/get')
expect(res.status).toBe(400)
expect(forwardRaw).toHaveBeenCalledTimes(1)
})
})
describe('authenticated opencode proxy streaming', () => {
+14 -2
View File
@@ -100,7 +100,15 @@ async function navigateWithinApp(page: Page, url: string): Promise<void> {
}, url)
}
test.afterEach(async ({ request }) => {
async function settleRequestDispatch(page: Page): Promise<void> {
await page.evaluate(async () => {
await fetch('/api/health')
})
}
test.afterEach(async ({ page, request }) => {
await page.close()
const shells = createdShells.splice(0)
const results = await Promise.allSettled(shells.map(({ directory, id }) => removeShell(request, directory, id)))
const failures = results.flatMap((result) => (result.status === 'rejected' ? [String(result.reason)] : []))
@@ -232,12 +240,16 @@ test.describe('session background activity', () => {
})
await navigateWithinApp(page, '/')
await expect(page.getByPlaceholder('Send a message...')).toBeHidden()
await settleRequestDispatch(page)
expect(unsubscribes).toEqual([])
await removeShell(request, directory, shellId)
await navigateWithinApp(page, `/repos/${repo.id}/sessions/${sessionId}`)
await expect(page.getByPlaceholder('Send a message...')).toBeVisible()
await expect(backgroundIndicator(page)).toBeHidden({ timeout: 20_000 })
expect(unsubscribes).toEqual([])
expect(unsubscribes.length).toBeLessThanOrEqual(1)
})
test('follows a session moved to another directory without a reload', async ({ page, request, repo }) => {
+1
View File
@@ -43,6 +43,7 @@ export function createServerEnv() {
WORKSPACE_PATH: path.join(E2E_TMP, 'workspace'),
REPO_BROWSE_ROOT: path.join(E2E_TMP, 'workspace'),
AUTH_SECRET,
AUTH_RATE_LIMIT_MAX: '500',
AUTH_TRUSTED_ORIGINS: `${BASE_URL},http://localhost:${SERVER_PORT}`,
AUTH_SECURE_COOKIES: 'false',
PASSKEY_ORIGIN: BASE_URL,
@@ -127,6 +127,7 @@ export interface PromptInputHandle {
interface PromptInputProps {
directory?: string
goalDirectory: string | undefined
sessionID: string
onVoiceConversationActiveChange?: (active: boolean) => void
onSuggestionsOpenChange?: (open: boolean) => void
@@ -140,6 +141,7 @@ interface PromptInputProps {
export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
directory,
goalDirectory,
sessionID,
onVoiceConversationActiveChange,
onSuggestionsOpenChange,
@@ -259,7 +261,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const goalCommand = useSessionGoalCommand(directory)
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending || goalCommand.isPending
const interruptSession = useInterruptSession()
const { data: goalRead } = useSessionGoal(sessionID, directory)
const { data: goalRead } = useSessionGoal(sessionID, goalDirectory)
const { searchCommands, findCommand, recentNames } = useCommands({ directory })
const recordCommand = useRecentCommandsStore((state) => state.recordCommand)
const isExactCommandPrompt = (value: string) => {
+3 -3
View File
@@ -1190,16 +1190,16 @@ describe('EventProvider permissions and forms', () => {
}
const updatedGoal: GoalState = { ...initialGoal, rounds: 1, updatedAt: 2000 }
const queryClient = createTestQueryClient()
queryClient.setQueryData(['session-goal', 'session-1'], { supported: true, goal: initialGoal })
queryClient.setQueryData(['session-goal', 'session-1', '/repo'], { supported: true, goal: initialGoal })
const harness = await renderProvider({ queryClient })
harness.push(goalChanged('session-1', updatedGoal, { directory: '/repo' }))
expect(queryClient.getQueryData(['session-goal', 'session-1'])).toEqual({ supported: true, goal: updatedGoal })
expect(queryClient.getQueryData(['session-goal', 'session-1', '/repo'])).toEqual({ supported: true, goal: updatedGoal })
harness.push(sessionIdle('other', { directory: '/repo' }))
expect(queryClient.getQueryData(['session-goal', 'session-1'])).toEqual({ supported: true, goal: updatedGoal })
expect(queryClient.getQueryData(['session-goal', 'session-1', '/repo'])).toEqual({ supported: true, goal: updatedGoal })
})
it('invalidates the sibling caches when a branch changes outside a repo row', async () => {
+60 -5
View File
@@ -52,7 +52,7 @@ function deferred() {
describe('useSessionGoal', () => {
it('reads the goal from the local server', async () => {
const { result, fetchFake } = renderHookWithProviders(() => useSessionGoal('ses_1', '/repo'), {
const { result, fetchFake, queryClient } = renderHookWithProviders(() => useSessionGoal('ses_1', '/repo'), {
...hookProviders,
fetchRoutes: [goalRoute()],
})
@@ -62,6 +62,8 @@ describe('useSessionGoal', () => {
const request = fetchFake.lastRequest('POST', goalReadPath)
expect(request?.body).toEqual({ input: { sessionID: 'ses_1' } })
expect(request?.searchParams.get('location[directory]')).toBe('/repo')
expect(queryClient.getQueryData(['session-goal', 'ses_1', '/repo'])).toEqual(supportedGoal)
expect(queryClient.getQueryCache().find({ queryKey: ['session-goal', 'ses_1', '/other'] })).toBeUndefined()
})
it('reads the goal from the current remote server and scopes its cache key', async () => {
@@ -80,7 +82,7 @@ describe('useSessionGoal', () => {
await waitFor(() => expect(result.current.data).toEqual(supportedGoal))
expect(queryClient.getQueryCache().find({ queryKey: ['session-goal', 'ses_1', 'srv_remote'] })).toBeDefined()
expect(queryClient.getQueryCache().find({ queryKey: ['session-goal', 'ses_1', '/repo', 'srv_remote'] })).toBeDefined()
})
it('does not poll for goal updates', async () => {
@@ -147,12 +149,43 @@ describe('applySessionGoalEvent', () => {
expect(result.current.data).toEqual(supportedGoal)
})
it('updates every cached goal for the session directory on the event server only', async () => {
const { result, queryClient } = renderHookWithProviders(() => useSessionGoal('ses_1', '/repo'), {
...hookProviders,
fetchRoutes: [goalRoute()],
})
await waitFor(() => expect(result.current.data).toEqual(supportedGoal))
queryClient.setQueryData(['session-goal', 'ses_1', '/elsewhere'], supportedGoal)
queryClient.setQueryData(['session-goal', 'ses_2', '/repo'], supportedGoal)
queryClient.setQueryData(['session-goal', 'ses_1', '/repo', 'srv_remote'], supportedGoal)
await act(async () => {
applySessionGoalEvent(
queryClient,
{ type: 'rpc.opencode.goal.changed', data: { sessionID: 'ses_1', goal: updatedGoal } },
'local',
)
})
const nextGoal = { supported: true, goal: updatedGoal }
expect(queryClient.getQueryData(['session-goal', 'ses_1', '/repo'])).toEqual(nextGoal)
expect(queryClient.getQueryData(['session-goal', 'ses_1', '/elsewhere'])).toEqual(nextGoal)
expect(queryClient.getQueryData(['session-goal', 'ses_2', '/repo'])).toEqual(supportedGoal)
expect(queryClient.getQueryData(['session-goal', 'ses_1', '/repo', 'srv_remote'])).toEqual(supportedGoal)
})
it('writes the change under the event server scoped key', async () => {
const { queryClient } = renderHookWithProviders(() => useSessionGoal('ses_1', '/repo'), {
...hookProviders,
fetchRoutes: [goalRoute()],
})
queryClient.setQueryData(['session-goal', 'ses_1', '/repo', 'srv_remote'], supportedGoal)
queryClient.setQueryData(['session-goal', 'ses_2', '/repo', 'srv_remote'], supportedGoal)
queryClient.setQueryData(['session-goal', 'ses_1', 'other', 'srv_other'], supportedGoal)
await act(async () => {
applySessionGoalEvent(
queryClient,
@@ -161,11 +194,13 @@ describe('applySessionGoalEvent', () => {
)
})
expect(queryClient.getQueryData(['session-goal', 'ses_1', 'srv_remote'])).toEqual({
expect(queryClient.getQueryData(['session-goal', 'ses_1', '/repo', 'srv_remote'])).toEqual({
supported: true,
goal: updatedGoal,
})
expect(queryClient.getQueryData(['session-goal', 'ses_1'])).toEqual(supportedGoal)
expect(queryClient.getQueryData(['session-goal', 'ses_2', '/repo', 'srv_remote'])).toEqual(supportedGoal)
expect(queryClient.getQueryData(['session-goal', 'ses_1', 'other', 'srv_other'])).toEqual(supportedGoal)
expect(queryClient.getQueryData(['session-goal', 'ses_1', '/repo'])).toEqual(supportedGoal)
})
it('keeps the event goal when an in-flight read resolves afterwards', async () => {
@@ -175,7 +210,9 @@ describe('applySessionGoalEvent', () => {
fetchRoutes: [goalRoute(() => pending.promise)],
})
await waitFor(() => expect(queryClient.getQueryState(['session-goal', 'ses_1'])?.fetchStatus).toBe('fetching'))
await waitFor(() =>
expect(queryClient.getQueryState(['session-goal', 'ses_1', '/repo'])?.fetchStatus).toBe('fetching'),
)
act(() => {
applySessionGoalEvent(
@@ -240,6 +277,24 @@ describe('useSessionGoalCommand', () => {
)
})
it('refetches the goal queries for the session after the command succeeds', async () => {
const { result, fetchFake } = renderHookWithProviders(
() => ({ goal: useSessionGoal('ses_1', '/repo'), command: useSessionGoalCommand('/repo') }),
{
...hookProviders,
fetchRoutes: [goalRoute(), commandRoute, ...switchRoutes],
},
)
await waitFor(() => expect(fetchFake.findRequests('POST', goalReadPath)).toHaveLength(1))
await act(async () => {
await result.current.command.mutateAsync({ sessionID: 'ses_1', text: 'pause' })
})
await waitFor(() => expect(fetchFake.findRequests('POST', goalReadPath)).toHaveLength(2))
})
it('reports the command failure message', async () => {
const failingCommand: FetchRoute = {
method: 'POST',
+25 -9
View File
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'
import { useMutation, useQuery, useQueryClient, type Query, type QueryClient } from '@tanstack/react-query'
import { getSessionGoal, runCommand, type RunCommandInput } from '@/api/opencode'
import { useOpenCodeServerId } from '@/contexts/opencode-server-context'
import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/opencode-server-context'
import { useSyncSessionSelection } from '@/hooks/useOpenCode'
import { serverScopedKey } from '@/lib/serverScope'
import { showToast } from '@/lib/toast'
@@ -13,14 +13,30 @@ import {
export const SESSION_GOAL_QUERY_ROOT = 'session-goal'
function sessionGoalQueryKey(sessionID: string, serverId: string) {
return serverScopedKey([SESSION_GOAL_QUERY_ROOT, sessionID], serverId)
const SESSION_GOAL_KEY_BASE_LENGTH = 3
function sessionGoalQueryKey(sessionID: string, directory: string | undefined, serverId: string) {
return serverScopedKey([SESSION_GOAL_QUERY_ROOT, sessionID, directory], serverId)
}
function isSessionGoalQueryFor(query: Query, sessionID: string, serverId: string): boolean {
const { queryKey } = query
if (queryKey[0] !== SESSION_GOAL_QUERY_ROOT || queryKey[1] !== sessionID) return false
if (isLocalOpenCodeServer(serverId)) return queryKey.length === SESSION_GOAL_KEY_BASE_LENGTH
return (
queryKey.length === SESSION_GOAL_KEY_BASE_LENGTH + 1
&& queryKey[SESSION_GOAL_KEY_BASE_LENGTH] === serverId
)
}
function sessionGoalQueryPredicate(sessionID: string, serverId: string) {
return (query: Query) => isSessionGoalQueryFor(query, sessionID, serverId)
}
export function useSessionGoal(sessionID: string, directory: string | undefined) {
const serverId = useOpenCodeServerId()
return useQuery<SessionGoalRead>({
queryKey: sessionGoalQueryKey(sessionID, serverId),
queryKey: sessionGoalQueryKey(sessionID, directory, serverId),
queryFn: () => getSessionGoal(sessionID, directory, serverId),
enabled: Boolean(directory),
})
@@ -34,9 +50,9 @@ export function applySessionGoalEvent(
const change = goalChangeFromEvent(event)
if (!change) return false
const nextGoal: SessionGoalRead = { supported: true, goal: change.goal }
const queryKey = sessionGoalQueryKey(change.sessionID, serverId)
void queryClient.cancelQueries({ queryKey })
queryClient.setQueryData<SessionGoalRead>(queryKey, nextGoal)
const predicate = sessionGoalQueryPredicate(change.sessionID, serverId)
void queryClient.cancelQueries({ predicate })
queryClient.setQueriesData<SessionGoalRead>({ predicate }, nextGoal)
return true
}
@@ -55,7 +71,7 @@ export function useSessionGoalCommand(directory: string | undefined) {
await runCommand({ ...command, name: GOAL_COMMAND_NAME }, serverId)
},
onSuccess: (_result, input) => {
void queryClient.invalidateQueries({ queryKey: sessionGoalQueryKey(input.sessionID, serverId) })
void queryClient.invalidateQueries({ predicate: sessionGoalQueryPredicate(input.sessionID, serverId) })
},
onError: (error: Error) => {
showToast.error(error.message ?? 'Goal command failed')
+2 -1
View File
@@ -980,7 +980,7 @@ export function SessionDetail() {
<div className={cn(isFormSheetOpen && "shrink-0 bg-background px-[3%]")}>
<div className={cn(!isFormSheetOpen && "px-[3%] md:px-0")}>
<SessionSendErrorBanner sessionId={sessionId} isConnected={streamConnected} isReconnecting={streamReconnecting} />
<SessionGoalBar sessionID={sessionId} directory={sessionDirectory} />
<SessionGoalBar sessionID={sessionId} directory={resolvedDirectory} />
<BackgroundWorkBar
sessionID={sessionId}
directory={sessionDirectory}
@@ -994,6 +994,7 @@ export function SessionDetail() {
key={sessionId}
ref={promptInputRef}
directory={sessionDirectory}
goalDirectory={resolvedDirectory}
sessionID={sessionId}
onVoiceConversationActiveChange={setIsVoiceConversationActive}
onSuggestionsOpenChange={setHasComposerSuggestions}
@@ -0,0 +1,54 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { waitFor } from '@testing-library/react'
import { installMatchMedia, installWindowSize } from '@/test/browserFakes'
import { makeRepo, makeSession } from '@/test/fixtures/api'
import { renderSessionPage } from '@/test/sessionPage'
import type { FetchFake, FetchRouteResult } from '@/test/fetchFake'
const SESSION_ID = 'session-1'
const REPO_DIRECTORY = '/test/repo'
const SESSION_DIRECTORY = '/test/elsewhere'
const GOAL_PATH = '/api/opencode/api/rpc/opencode.goal/get'
function deferred() {
let resolve: (result: FetchRouteResult) => void = () => undefined
const promise = new Promise<FetchRouteResult>((resolveResult) => {
resolve = resolveResult
})
return { promise, resolve }
}
function goalDirectories(fetchFake: FetchFake): Array<string | null> {
return fetchFake
.findRequests('POST', GOAL_PATH)
.map((request) => request.searchParams.get('location[directory]'))
}
describe('SessionDetail goal reads', () => {
beforeEach(() => {
installMatchMedia(false)
installWindowSize(900)
})
it('reads the goal with the session directory once it resolves instead of the repo directory', async () => {
const sessionResponse = deferred()
const session = makeSession({
id: SESSION_ID,
title: 'Elsewhere',
location: { directory: SESSION_DIRECTORY },
})
const { fetchFake } = renderSessionPage({
repo: makeRepo({ id: 1, fullPath: REPO_DIRECTORY }),
session,
sessionRespond: () => sessionResponse.promise,
})
await waitFor(() => expect(document.querySelector('[data-prompt-input]')).not.toBeNull())
expect(goalDirectories(fetchFake)).toEqual([])
sessionResponse.resolve({ json: { data: session } })
await waitFor(() => expect(goalDirectories(fetchFake).length).toBeGreaterThan(0))
expect(new Set(goalDirectories(fetchFake))).toEqual(new Set([SESSION_DIRECTORY]))
})
})
+1
View File
@@ -141,6 +141,7 @@ export async function renderPromptInput(fixture: PromptInputFixture = {}) {
key={active.sessionID ?? 'test-session'}
sessionID={active.sessionID ?? 'test-session'}
directory={active.directory ?? '/test'}
goalDirectory={active.directory ?? '/test'}
isSessionActive={active.isSessionActive ?? false}
isStreamingResponse={active.isStreamingResponse ?? false}
onScrollToBottom={() => {}}
+1
View File
@@ -140,6 +140,7 @@ export const ENV = {
PASSKEY_RP_ID: getEnvString('PASSKEY_RP_ID', 'localhost'),
PASSKEY_RP_NAME: getEnvString('PASSKEY_RP_NAME', 'OpenCode Manager'),
PASSKEY_ORIGIN: getEnvString('PASSKEY_ORIGIN', 'http://localhost:5003'),
RATE_LIMIT_MAX: getEnvNumber('AUTH_RATE_LIMIT_MAX', 100),
},
} as const