fix: key auth rate limiting on the socket address only and clear sent drafts after unmount

- auth: drop the AUTH_TRUSTED_PROXY_HEADERS opt-in. Configured headers were
  trusted from any peer, so direct access to the published port could still
  rotate them. Better Auth now reads only the Manager-set socket address
  header; the env, compose forwarding, docs and tests are removed.
- composer: a send that completes after the composer unmounted (session
  switched mid-send) left the submitted text in the per-session draft store.
  Sends now complete through mutateAsync and clear the stored draft only if
  it still matches what was submitted, so newer edits are kept.
This commit is contained in:
ioplex committed 2026-10-23 12:49:53 -04:00
1 parent 4ec62cd4e7
commit dabe750920
17 files changed
+268 -233

No files matched your search

-8
View File
@@ -114,14 +114,6 @@ DEBUG=false
# so set true explicitly for HTTPS.
# AUTH_SECURE_COOKIES=true
# Trusted proxy headers for the client IP used by auth rate limiting and session records
# (comma-separated header names, for example x-forwarded-for or cf-connecting-ip).
# Unset by default: the Manager uses the real TCP socket address and ignores any
# client-supplied forwarding header, so a header cannot be rotated to bypass the
# login rate limit. Set this only when the Manager sits behind a reverse proxy or
# tunnel that overwrites the header, and list only headers that proxy sets.
# AUTH_TRUSTED_PROXY_HEADERS=x-forwarded-for
# OAuth Providers (optional - enable by providing client ID and secret)
# GITHUB_CLIENT_ID=
# GITHUB_CLIENT_SECRET=
-23
View File
@@ -1,23 +1,8 @@
import type { Context } from 'hono'
import { getConnInfo } from '@hono/node-server/conninfo'
import { ENV } from '@opencode-manager/shared/config/env'
export const AUTH_SOCKET_IP_HEADER = 'x-ocm-auth-socket-ip'
const DEFAULT_PROXY_HEADERS = ['x-forwarded-for']
const HEADER_NAME_PATTERN = /^[a-z0-9!#$%&'*+.^_`|~-]+$/
export function getTrustedProxyHeaders(): string[] {
return ENV.AUTH.TRUSTED_PROXY_HEADERS
.split(',')
.map((header) => header.trim().toLowerCase())
.filter((header) => HEADER_NAME_PATTERN.test(header))
}
export function getClientIpHeaders(): string[] {
return [...getTrustedProxyHeaders(), AUTH_SOCKET_IP_HEADER]
}
export function resolveSocketIp(c: Context): string | undefined {
try {
return getConnInfo(c).remote.address ?? undefined
@@ -27,14 +12,6 @@ export function resolveSocketIp(c: Context): string | undefined {
}
export function applyClientIpHeaders(headers: Headers, socketIp: string | undefined): Headers {
const trustedProxyHeaders = getTrustedProxyHeaders()
for (const header of DEFAULT_PROXY_HEADERS) {
if (!trustedProxyHeaders.includes(header)) {
headers.delete(header)
}
}
headers.delete(AUTH_SOCKET_IP_HEADER)
if (socketIp) {
headers.set(AUTH_SOCKET_IP_HEADER, socketIp)
+2 -2
View File
@@ -4,7 +4,7 @@ import { passkey } from '@better-auth/passkey'
import { Database } from 'bun:sqlite'
import { ENV, getTrustedOrigins } from '@opencode-manager/shared/config/env'
import { AUTH_COOKIE_PREFIX } from './cookies'
import { getClientIpHeaders } from './client-ip'
import { AUTH_SOCKET_IP_HEADER } from './client-ip'
export type AuthInstance = ReturnType<typeof createAuth>
@@ -92,7 +92,7 @@ export function createAuth(db: Database) {
cookiePrefix: AUTH_COOKIE_PREFIX,
useSecureCookies: ENV.AUTH.SECURE_COOKIES,
ipAddress: {
ipAddressHeaders: getClientIpHeaders(),
ipAddressHeaders: [AUTH_SOCKET_IP_HEADER],
},
},
})
+18 -99
View File
@@ -1,10 +1,9 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi } from 'vitest'
import { Hono } from 'hono'
import { DatabaseSync } from 'node:sqlite'
import type { Database } from 'bun:sqlite'
import { createAuth } from '../../src/auth'
import { AUTH_SOCKET_IP_HEADER } from '../../src/auth/client-ip'
import { applyClientIpHeaders, getClientIpHeaders, getTrustedProxyHeaders } from '../../src/auth/client-ip'
import { AUTH_SOCKET_IP_HEADER, applyClientIpHeaders } from '../../src/auth/client-ip'
import { createAuthRoutes } from '../../src/routes/auth'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
@@ -16,7 +15,6 @@ const { ENV } = vi.hoisted(() => ({
SECRET: 'test-secret-for-encryption-key-32c',
TRUSTED_ORIGINS: 'http://localhost:5173,http://localhost:5003',
SECURE_COOKIES: false,
TRUSTED_PROXY_HEADERS: '',
ADMIN_EMAIL: undefined as string | undefined,
ADMIN_PASSWORD: undefined as string | undefined,
ADMIN_PASSWORD_RESET: false,
@@ -80,45 +78,21 @@ function readSessionIpAddress(db: Database): string {
return row.ipAddress
}
function createCapturingHandler() {
const received: Request[] = []
const handler = vi.fn(async (request: Request) => {
received.push(request)
return new Response('ok')
})
return { received, handler }
}
describe('auth client ip headers', () => {
beforeEach(() => {
ENV.AUTH.TRUSTED_PROXY_HEADERS = ''
})
it('trusts no proxy headers by default and resolves the socket address', () => {
expect(getTrustedProxyHeaders()).toEqual([])
expect(getClientIpHeaders()).toEqual([AUTH_SOCKET_IP_HEADER])
})
it('reads configured proxy headers in order before the socket address', () => {
ENV.AUTH.TRUSTED_PROXY_HEADERS = ' CF-Connecting-IP , X-Forwarded-For '
expect(getTrustedProxyHeaders()).toEqual(['cf-connecting-ip', 'x-forwarded-for'])
expect(getClientIpHeaders()).toEqual(['cf-connecting-ip', 'x-forwarded-for', AUTH_SOCKET_IP_HEADER])
})
it('ignores empty, malformed and duplicate header names', () => {
ENV.AUTH.TRUSTED_PROXY_HEADERS = 'x-real-ip,,X-Real-IP,not a header'
expect(getTrustedProxyHeaders()).toEqual(['x-real-ip', 'x-real-ip'])
})
it('drops a client-supplied forwarded header and uses the socket address by default', () => {
const headers = new Headers({ 'x-forwarded-for': '198.51.100.9', [AUTH_SOCKET_IP_HEADER]: '6.6.6.6' })
it('overrides a client-supplied socket header with the socket address', () => {
const headers = new Headers({ [AUTH_SOCKET_IP_HEADER]: '6.6.6.6' })
const result = applyClientIpHeaders(headers, '203.0.113.7')
expect(result.get('x-forwarded-for')).toBeNull()
expect(result.get(AUTH_SOCKET_IP_HEADER)).toBe('203.0.113.7')
})
it('keeps the configured proxy header and still forwards the socket address', () => {
ENV.AUTH.TRUSTED_PROXY_HEADERS = 'x-forwarded-for'
const headers = new Headers({ 'x-forwarded-for': '198.51.100.9' })
const result = applyClientIpHeaders(headers, '203.0.113.7')
expect(result.get('x-forwarded-for')).toBe('198.51.100.9')
expect(result.get(AUTH_SOCKET_IP_HEADER)).toBe('203.0.113.7')
})
@@ -132,55 +106,22 @@ describe('auth client ip headers', () => {
})
describe('createAuthRoutes client ip forwarding', () => {
beforeEach(() => {
ENV.AUTH.TRUSTED_PROXY_HEADERS = ''
})
it('passes the socket address to the auth handler and strips a spoofed forwarded header', async () => {
const received: Request[] = []
const handler = vi.fn(async (request: Request) => {
received.push(request)
return new Response('ok')
})
it('sets the socket address on the auth request and ignores a spoofed socket header', async () => {
const { received, handler } = createCapturingHandler()
const app: Hono = createAuthRoutes({ handler } as unknown as ReturnType<typeof createAuth>)
await app.fetch(
new Request('http://localhost:5003/api/auth/get-session', {
headers: { 'x-forwarded-for': '198.51.100.9' },
headers: { [AUTH_SOCKET_IP_HEADER]: '6.6.6.6', 'x-forwarded-for': '198.51.100.9' },
}),
socketEnv('203.0.113.7')
)
expect(received[0]?.headers.get(AUTH_SOCKET_IP_HEADER)).toBe('203.0.113.7')
expect(received[0]?.headers.get('x-forwarded-for')).toBeNull()
})
it('forwards the configured proxy header when trusted', async () => {
ENV.AUTH.TRUSTED_PROXY_HEADERS = 'x-forwarded-for'
const received: Request[] = []
const handler = vi.fn(async (request: Request) => {
received.push(request)
return new Response('ok')
})
const app: Hono = createAuthRoutes({ handler } as unknown as ReturnType<typeof createAuth>)
await app.fetch(
new Request('http://localhost:5003/api/auth/get-session', {
headers: { 'x-forwarded-for': '198.51.100.9' },
}),
socketEnv('203.0.113.7')
)
expect(received[0]?.headers.get('x-forwarded-for')).toBe('198.51.100.9')
expect(received[0]?.headers.get(AUTH_SOCKET_IP_HEADER)).toBe('203.0.113.7')
})
it('omits the socket header when the connection info is unavailable', async () => {
const received: Request[] = []
const handler = vi.fn(async (request: Request) => {
received.push(request)
return new Response('ok')
})
const { received, handler } = createCapturingHandler()
const app: Hono = createAuthRoutes({ handler } as unknown as ReturnType<typeof createAuth>)
await app.fetch(new Request('http://localhost:5003/api/auth/get-session', {
@@ -192,17 +133,13 @@ describe('createAuthRoutes client ip forwarding', () => {
})
describe('createAuth client ip resolution', () => {
beforeEach(() => {
ENV.AUTH.TRUSTED_PROXY_HEADERS = ''
})
it('records the socket address on a new session and ignores a spoofed forwarded header', async () => {
const db = createAuthDatabase()
const app: Hono = createAuthRoutes(createAuth(db))
try {
const response = await app.fetch(
signUpRequest({ 'x-forwarded-for': '198.51.100.9' }),
signUpRequest({ 'x-forwarded-for': '198.51.100.9', [AUTH_SOCKET_IP_HEADER]: '6.6.6.6' }),
socketEnv('203.0.113.7')
)
@@ -212,22 +149,4 @@ describe('createAuth client ip resolution', () => {
db.close()
}
}, 30000)
it('records the trusted forwarded address when proxy headers are configured', async () => {
ENV.AUTH.TRUSTED_PROXY_HEADERS = 'x-forwarded-for'
const db = createAuthDatabase()
const app: Hono = createAuthRoutes(createAuth(db))
try {
const response = await app.fetch(
signUpRequest({ 'x-forwarded-for': '198.51.100.9' }),
socketEnv('203.0.113.7')
)
expect(response.status).toBe(200)
expect(readSessionIpAddress(db)).toBe('198.51.100.9')
} finally {
db.close()
}
}, 30000)
})
-2
View File
@@ -13,7 +13,6 @@ const { ENV } = vi.hoisted(() => ({
SECRET: 'test-secret-for-encryption-key-32c',
TRUSTED_ORIGINS: 'http://localhost:5173,http://localhost:5003',
SECURE_COOKIES: false,
TRUSTED_PROXY_HEADERS: '',
ADMIN_EMAIL: undefined as string | undefined,
ADMIN_PASSWORD: undefined as string | undefined,
ADMIN_PASSWORD_RESET: false,
@@ -47,7 +46,6 @@ function resetEnv(): void {
ENV.SERVER.PORT = 5003
ENV.AUTH.TRUSTED_ORIGINS = 'http://localhost:5173,http://localhost:5003'
ENV.AUTH.SECURE_COOKIES = false
ENV.AUTH.TRUSTED_PROXY_HEADERS = ''
ENV.AUTH.ADMIN_EMAIL = undefined
ENV.AUTH.ADMIN_PASSWORD = undefined
ENV.AUTH.GITHUB_CLIENT_ID = undefined
-2
View File
@@ -10,7 +10,6 @@ const { ENV } = vi.hoisted(() => ({
SECRET: 'test-secret-for-encryption-key-32c',
TRUSTED_ORIGINS: 'http://localhost:5173,http://localhost:5003',
SECURE_COOKIES: false,
TRUSTED_PROXY_HEADERS: '',
ADMIN_EMAIL: undefined as string | undefined,
ADMIN_PASSWORD: undefined as string | undefined,
ADMIN_PASSWORD_RESET: false,
@@ -50,7 +49,6 @@ const mockLoggerDebug = vi.mocked(logger.debug)
function resetEnv(): void {
ENV.AUTH.TRUSTED_ORIGINS = 'http://localhost:5173,http://localhost:5003'
ENV.AUTH.SECURE_COOKIES = false
ENV.AUTH.TRUSTED_PROXY_HEADERS = ''
ENV.AUTH.ADMIN_EMAIL = undefined
ENV.AUTH.ADMIN_PASSWORD = undefined
ENV.AUTH.ADMIN_PASSWORD_RESET = false
@@ -244,13 +244,6 @@ describe('workspace ownership configuration', () => {
expect(envExample).toContain('# PUID=1000')
expect(envExample).toContain('# PGID=1000')
})
it('forwards the auth trusted proxy header opt-in and documents it', () => {
expect(read(composePath)).toContain('- AUTH_TRUSTED_PROXY_HEADERS=${AUTH_TRUSTED_PROXY_HEADERS:-}')
expect(read(join(repoRoot, 'docker-compose.release.yml')))
.toContain('- AUTH_TRUSTED_PROXY_HEADERS=${AUTH_TRUSTED_PROXY_HEADERS:-}')
expect(read(envExamplePath)).toContain('# AUTH_TRUSTED_PROXY_HEADERS=x-forwarded-for')
})
})
describe('compose image source', () => {
-1
View File
@@ -43,7 +43,6 @@ services:
- DISCORD_CLIENT_ID=${DISCORD_CLIENT_ID:-}
- DISCORD_CLIENT_SECRET=${DISCORD_CLIENT_SECRET:-}
- AUTH_SECURE_COOKIES=${AUTH_SECURE_COOKIES:-false}
- AUTH_TRUSTED_PROXY_HEADERS=${AUTH_TRUSTED_PROXY_HEADERS:-}
- PASSKEY_RP_ID=${PASSKEY_RP_ID:-localhost}
- PASSKEY_RP_NAME=${PASSKEY_RP_NAME:-OpenCode Manager}
- PASSKEY_ORIGIN=${PASSKEY_ORIGIN:-http://localhost:5003}
-1
View File
@@ -41,7 +41,6 @@ services:
- DISCORD_CLIENT_ID=${DISCORD_CLIENT_ID:-}
- DISCORD_CLIENT_SECRET=${DISCORD_CLIENT_SECRET:-}
- AUTH_SECURE_COOKIES=${AUTH_SECURE_COOKIES:-false}
- AUTH_TRUSTED_PROXY_HEADERS=${AUTH_TRUSTED_PROXY_HEADERS:-}
- PASSKEY_RP_ID=${PASSKEY_RP_ID:-localhost}
- PASSKEY_RP_NAME=${PASSKEY_RP_NAME:-OpenCode Manager}
- PASSKEY_ORIGIN=${PASSKEY_ORIGIN:-http://localhost:5003}
@@ -49,9 +49,9 @@ vi.mock('@/lib/toast', () => ({
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSendPrompt: () => ({ mutate: mocks.useSendPrompt, isPending: false }),
useSendPrompt: () => ({ mutate: mocks.useSendPrompt, mutateAsync: mocks.useSendPrompt, isPending: false }),
useInterruptSession: () => ({ mutate: vi.fn() }),
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
useSendShell: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(() => Promise.resolve()), isPending: false }),
useAgents: () => ({ data: [] }),
useSkills: () => ({ data: [] }),
}))
@@ -118,6 +118,7 @@ describe('PromptInput composer layout', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useSendPrompt.mockResolvedValue({ id: 'inbox_1' })
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.hasPendingPermission.mockReturnValue(false)
mocks.useMobile.mockReturnValue(false)
@@ -193,12 +194,13 @@ describe('PromptInput composer layout', () => {
expect(button.parentElement?.contains(controlsRow())).toBe(false)
})
it('sends the typed prompt from the row button', () => {
it('sends the typed prompt from the row button', async () => {
renderComponent()
fireEvent.change(promptInput(), { target: { value: 'row send' } })
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(promptInput()).toHaveValue(''))
const [variables] = mocks.useSendPrompt.mock.calls[0] as [{ text: string }]
expect(variables.text).toBe('row send')
})
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useComposerDraftStore } from '@/stores/composerDraftStore'
@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({
useSendErrorStore: vi.fn(),
useHasBackgroundActivity: vi.fn(),
useSendPrompt: vi.fn(),
useSendShell: vi.fn(),
hasPendingPermission: vi.fn(() => false),
setShowDialog: vi.fn(),
}))
@@ -48,9 +49,9 @@ vi.mock('@/lib/toast', () => ({
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSendPrompt: () => ({ mutate: mocks.useSendPrompt, isPending: false }),
useSendPrompt: () => ({ mutate: mocks.useSendPrompt, mutateAsync: mocks.useSendPrompt, isPending: false }),
useInterruptSession: () => ({ mutate: vi.fn() }),
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
useSendShell: () => ({ mutate: mocks.useSendShell, mutateAsync: mocks.useSendShell, isPending: false }),
useAgents: () => ({ data: [] }),
useSkills: () => ({ data: [] }),
}))
@@ -120,9 +121,8 @@ describe('PromptInput per-session composer draft', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useSendPrompt.mockImplementation((_variables, options) => {
options?.onSuccess?.()
})
mocks.useSendPrompt.mockResolvedValue({ id: 'inbox_1' })
mocks.useSendShell.mockResolvedValue({ id: 'shell_1' })
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.hasPendingPermission.mockReturnValue(false)
mocks.useMobile.mockReturnValue(false)
@@ -196,7 +196,7 @@ describe('PromptInput per-session composer draft', () => {
expect(screen.getByText('pic.png')).toBeInTheDocument()
})
it('sends the restored draft to the session that owns it and clears only that draft', () => {
it('sends the restored draft to the session that owns it and clears only that draft', async () => {
const { rerender } = renderSession('session-a')
fireEvent.change(promptInput(), { target: { value: 'draft for A' } })
@@ -209,14 +209,76 @@ describe('PromptInput per-session composer draft', () => {
expect(mocks.useSendPrompt).toHaveBeenCalledWith(
expect.objectContaining({ sessionID: 'session-a', text: 'draft for A' }),
expect.anything(),
)
expect(promptInput()).toHaveValue('')
await waitFor(() => expect(promptInput()).toHaveValue(''))
rerender(harness('session-b'))
expect(promptInput()).toHaveValue('draft for B')
})
it('clears a submitted draft after its session unmounted before the send resolved', async () => {
let resolveSend: (value: { id: string }) => void = () => {}
mocks.useSendPrompt.mockImplementation(() => new Promise((resolve) => {
resolveSend = resolve
}))
const { rerender } = renderSession('session-a')
fireEvent.change(promptInput(), { target: { value: 'sent while leaving' } })
fireEvent.click(screen.getByTitle('Send'))
expect(useComposerDraftStore.getState().getDraft('session-a').prompt).toBe('sent while leaving')
rerender(harness('session-b'))
await act(async () => {
resolveSend({ id: 'inbox_1' })
})
rerender(harness('session-a'))
expect(promptInput()).toHaveValue('')
})
it('clears a submitted bash command after its session unmounted before the send resolved', async () => {
let resolveShell: (value: { id: string }) => void = () => {}
mocks.useSendShell.mockImplementation(() => new Promise((resolve) => {
resolveShell = resolve
}))
const { rerender } = renderSession('session-a')
fireEvent.change(promptInput(), { target: { value: '!' } })
fireEvent.change(screen.getByPlaceholderText('Enter bash command...'), { target: { value: '!ls' } })
fireEvent.click(screen.getByTitle('Send'))
rerender(harness('session-b'))
await act(async () => {
resolveShell({ id: 'shell_1' })
})
rerender(harness('session-a'))
expect(promptInput()).toHaveValue('')
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
})
it('keeps text typed after the submit when the send resolves', async () => {
let resolveSend: (value: { id: string }) => void = () => {}
mocks.useSendPrompt.mockImplementation(() => new Promise((resolve) => {
resolveSend = resolve
}))
renderSession('session-a')
fireEvent.change(promptInput(), { target: { value: 'sent message' } })
fireEvent.click(screen.getByTitle('Send'))
fireEvent.change(promptInput(), { target: { value: 'sent message plus an edit' } })
await act(async () => {
resolveSend({ id: 'inbox_1' })
})
expect(promptInput()).toHaveValue('sent message plus an edit')
expect(useComposerDraftStore.getState().getDraft('session-a').prompt).toBe('sent message plus an edit')
})
it('keeps the draft when Escape is pressed while the session is idle', () => {
renderSession('session-a')
@@ -42,8 +42,8 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
return {
...actual,
useSendPrompt: () => ({ mutate: mocks.sendPrompt, isPending: false }),
useSendShell: () => ({ mutate: mocks.sendShell, isPending: false }),
useSendPrompt: () => ({ mutate: mocks.sendPrompt, mutateAsync: mocks.sendPrompt, isPending: false }),
useSendShell: () => ({ mutate: mocks.sendShell, mutateAsync: mocks.sendShell, isPending: false }),
useInterruptSession: () => ({ mutate: mocks.interrupt }),
useAgents: () => ({ data: mocks.agents }),
useSkills: () => ({ data: mocks.skills }),
@@ -170,6 +170,8 @@ describe('PromptInput goal mode', () => {
mocks.useSessionGoal.mockReturnValue({ data: null })
mocks.useSessionPermissionMode.mockReturnValue({ data: undefined })
mocks.startGoal.mockResolvedValue({ id: 1 })
mocks.sendPrompt.mockResolvedValue({ id: 'inbox_1' })
mocks.sendShell.mockResolvedValue({ id: 'shell_1' })
mocks.agents = []
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
@@ -267,7 +269,6 @@ describe('PromptInput goal mode', () => {
}))
await waitFor(() => expect(mocks.sendPrompt).toHaveBeenCalledWith(
expect.objectContaining({ delivery: 'queue' }),
expect.anything(),
))
expect(mocks.startGoal.mock.invocationCallOrder[0]).toBeLessThan(mocks.sendPrompt.mock.invocationCallOrder[0])
})
@@ -56,7 +56,7 @@ vi.mock('@/hooks/useOpenCode', () => ({
isPending: mocks.sendPromptPending(),
}),
useInterruptSession: () => ({ mutate: vi.fn(), mutateAsync: vi.fn() }),
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
useSendShell: () => ({ mutate: vi.fn(), mutateAsync: vi.fn(() => Promise.resolve()), isPending: false }),
useAgents: () => ({ data: [] }),
useSkills: () => ({ data: [] }),
}))
@@ -222,9 +222,6 @@ describe('PromptInput voice conversation', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useSendPromptMutate.mockImplementation((_variables, options) => {
options?.onSuccess?.()
})
mocks.useSendPromptMutateAsync.mockResolvedValue({ id: 'inbox_1' })
mocks.sendPromptPending.mockReturnValue(false)
mocks.useMobile.mockReturnValue(true)
@@ -426,9 +423,7 @@ describe('PromptInput submission', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useSendPromptMutate.mockImplementation((_variables, options) => {
options?.onSuccess?.()
})
mocks.useSendPromptMutateAsync.mockResolvedValue({ id: 'inbox_1' })
mocks.sendPromptPending.mockReturnValue(false)
mocks.useMobile.mockReturnValue(true)
mocks.useSttAvailability.mockReturnValue({ isEnabled: true, isSupported: true })
@@ -439,7 +434,7 @@ describe('PromptInput submission', () => {
})
it('keeps submitted text until send succeeds', () => {
mocks.useSendPromptMutate.mockImplementation(() => undefined)
mocks.useSendPromptMutateAsync.mockImplementation(() => new Promise(() => {}))
renderComponent()
const input = screen.getByPlaceholderText('Send a message...')
@@ -462,7 +457,7 @@ describe('PromptInput submission', () => {
})
it('clears submitted text once the server confirms it is processing', async () => {
mocks.useSendPromptMutate.mockImplementation(() => undefined)
mocks.useSendPromptMutateAsync.mockImplementation(() => new Promise(() => {}))
const view = renderComponent()
const input = screen.getByPlaceholderText('Send a message...')
@@ -478,7 +473,7 @@ describe('PromptInput submission', () => {
})
})
it('allows queuing a follow-up while a non-queued send is pending', () => {
it('allows queuing a follow-up while a non-queued send is pending', async () => {
mocks.sendPromptPending.mockReturnValue(true)
renderComponent({ isStreamingResponse: true })
@@ -490,7 +485,8 @@ describe('PromptInput submission', () => {
fireEvent.click(queueButton)
const [callArgs] = mocks.useSendPromptMutate.mock.calls[0] as [{ text: string }, unknown]
await waitFor(() => expect(input).toHaveValue(''))
const [callArgs] = mocks.useSendPromptMutateAsync.mock.calls[0] as [{ text: string }]
expect(callArgs.text).toBe('follow-up')
})
@@ -501,7 +497,7 @@ describe('PromptInput submission', () => {
fireEvent.change(input, { target: { value: 'queued message' } })
fireEvent.click(screen.getByTitle('Queue message'))
const [callArgs] = mocks.useSendPromptMutate.mock.calls[0] as [{ text: string }, unknown]
const [callArgs] = mocks.useSendPromptMutateAsync.mock.calls[0] as [{ text: string }]
expect(callArgs.text).toBe('queued message')
await waitFor(() => {
+54 -60
View File
@@ -11,7 +11,7 @@ import { useSttAvailability } from '@/hooks/useSTT'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { useSendErrorStore } from '@/stores/sendErrorStore'
import { useComposerDraftStore } from '@/stores/composerDraftStore'
import { useComposerDraftStore, type ComposerDraft } from '@/stores/composerDraftStore'
import { useRecentCommandsStore } from '@/stores/recentCommandsStore'
import { useHasBackgroundActivity } from '@/stores/sessionStatusStore'
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
@@ -189,6 +189,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const saveDraft = useComposerDraftStore((state) => state.saveDraft)
const clearDraft = useComposerDraftStore((state) => state.clearDraft)
const clearDraftIfUnchanged = useComposerDraftStore((state) => state.clearDraftIfUnchanged)
useEffect(() => {
if (prompt === '' && !isBashMode && attachedFiles.size === 0 && imageAttachments.length === 0) {
@@ -215,6 +216,11 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}
}, [])
const completeSubmittedDraft = useCallback((submitted: ComposerDraft, options?: { keepAttachments?: boolean }) => {
clearDraftIfUnchanged(sessionID, submitted, options)
clearSubmittedPrompt(submitted.prompt, submitted.attachedFiles, submitted.imageAttachments, options)
}, [sessionID, clearDraftIfUnchanged, clearSubmittedPrompt])
const pendingConfirmClearRef = useRef<{
prompt: string
files: Map<string, FileAttachmentInfo>
@@ -376,27 +382,23 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (isStreamingResponse) {
onScrollToBottom()
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, skillIds, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
const submitted: ComposerDraft = { prompt, isBashMode, attachedFiles, imageAttachments }
if (isGoalArmed && !isBashMode && !isExactCommandPrompt(prompt)) {
const goalStarted = await startArmedGoal(parsed.text)
if (!goalStarted) return
}
sendPrompt.mutate(
{
sessionID,
text: parsed.text,
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef ?? undefined,
agent: currentMode,
delivery: 'queue',
},
{
onSuccess: () => clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments)
}
void sendPrompt.mutateAsync({
sessionID,
text: parsed.text,
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef ?? undefined,
agent: currentMode,
delivery: 'queue',
}).then(
() => completeSubmittedDraft(submitted),
() => undefined,
)
setStoredAgent(sessionID, currentMode)
return
@@ -407,19 +409,18 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (isBashMode) {
const command = prompt.startsWith('!') ? prompt.slice(1) : prompt
addUserBashCommand(command)
const submittedPrompt = prompt
sendShell.mutate(
{
sessionID,
command,
const submitted: ComposerDraft = { prompt, isBashMode, attachedFiles, imageAttachments }
void sendShell.mutateAsync({
sessionID,
command,
}).then(
() => {
clearDraftIfUnchanged(sessionID, submitted, { keepAttachments: true })
if (promptRef.current !== submitted.prompt) return
setPrompt('')
setIsBashMode(false)
},
{
onSuccess: () => {
if (promptRef.current !== submittedPrompt) return
setPrompt('')
setIsBashMode(false)
}
}
() => undefined,
)
setStoredAgent(sessionID, currentMode)
return
@@ -434,9 +435,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
if (command) {
recordCommand(command.name)
const parsed = parsePromptToInput(commandPrompt.args?.trim() || '', attachedFiles, agentNames, skillIds, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
const submitted: ComposerDraft = { prompt, isBashMode, attachedFiles, imageAttachments }
void executeCommand(command, {
text: parsed.text,
@@ -445,22 +444,20 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
skills: parsed.skills,
}).then((shouldClear) => {
if (!shouldClear) return
const keepAttachments = isBuiltinCommand(command) && (submittedAttachedFiles.size > 0 || submittedImageAttachments.length > 0)
const keepAttachments = isBuiltinCommand(command) && (submitted.attachedFiles.size > 0 || submitted.imageAttachments.length > 0)
if (keepAttachments) {
clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments, { keepAttachments: true })
completeSubmittedDraft(submitted, { keepAttachments: true })
showToast.info('Built-in commands do not use attachments; they were kept')
return
}
clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments)
completeSubmittedDraft(submitted)
})
return
}
}
const parsed = parsePromptToInput(prompt, attachedFiles, agentNames, skillIds, imageAttachments)
const submittedPrompt = prompt
const submittedAttachedFiles = attachedFiles
const submittedImageAttachments = imageAttachments
const submitted: ComposerDraft = { prompt, isBashMode, attachedFiles, imageAttachments }
if (isGoalArmed) {
const goalStarted = await startArmedGoal(parsed.text)
@@ -468,30 +465,27 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}
pendingConfirmClearRef.current = {
prompt: submittedPrompt,
files: submittedAttachedFiles,
images: submittedImageAttachments
prompt: submitted.prompt,
files: submitted.attachedFiles,
images: submitted.imageAttachments
}
sendPrompt.mutate(
{
sessionID,
text: parsed.text,
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef ?? undefined,
agent: currentMode,
void sendPrompt.mutateAsync({
sessionID,
text: parsed.text,
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef ?? undefined,
agent: currentMode,
}).then(
() => {
pendingConfirmClearRef.current = null
completeSubmittedDraft(submitted)
},
() => {
pendingConfirmClearRef.current = null
},
{
onSuccess: () => {
pendingConfirmClearRef.current = null
clearSubmittedPrompt(submittedPrompt, submittedAttachedFiles, submittedImageAttachments)
},
onError: () => {
pendingConfirmClearRef.current = null
}
}
)
onScrollToBottom()
@@ -0,0 +1,74 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useComposerDraftStore, type ComposerDraft } from './composerDraftStore'
const createDraft = (prompt: string): ComposerDraft => ({
prompt,
isBashMode: false,
attachedFiles: new Map(),
imageAttachments: [],
})
describe('useComposerDraftStore', () => {
beforeEach(() => {
useComposerDraftStore.setState({ drafts: {} })
})
it('clears the stored draft when it still holds the submitted content', () => {
const submitted = createDraft('sent message')
useComposerDraftStore.getState().saveDraft('session-1', submitted)
useComposerDraftStore.getState().clearDraftIfUnchanged('session-1', submitted)
expect(useComposerDraftStore.getState().drafts['session-1']).toBeUndefined()
})
it('keeps text typed after the submit', () => {
const submitted = createDraft('sent message')
useComposerDraftStore.getState().saveDraft('session-1', submitted)
const edited = createDraft('sent message and more')
useComposerDraftStore.getState().saveDraft('session-1', edited)
useComposerDraftStore.getState().clearDraftIfUnchanged('session-1', submitted)
expect(useComposerDraftStore.getState().getDraft('session-1')).toBe(edited)
})
it('keeps attachments replaced after the submit', () => {
const submitted = createDraft('sent message')
useComposerDraftStore.getState().saveDraft('session-1', submitted)
const edited = { ...submitted, attachedFiles: new Map([['file', { path: '/tmp/file', name: 'file' }]]) }
useComposerDraftStore.getState().saveDraft('session-1', edited)
useComposerDraftStore.getState().clearDraftIfUnchanged('session-1', submitted)
expect(useComposerDraftStore.getState().getDraft('session-1')).toBe(edited)
})
it('keeps the draft of another session', () => {
const submitted = createDraft('sent from session 1')
const other = createDraft('draft for session 2')
useComposerDraftStore.getState().saveDraft('session-1', submitted)
useComposerDraftStore.getState().saveDraft('session-2', other)
useComposerDraftStore.getState().clearDraftIfUnchanged('session-1', submitted)
expect(useComposerDraftStore.getState().getDraft('session-2')).toBe(other)
})
it('keeps the submitted attachments when asked to', () => {
const submitted: ComposerDraft = {
prompt: '!ls',
isBashMode: true,
attachedFiles: new Map([['file', { path: '/tmp/file', name: 'file' }]]),
imageAttachments: [],
}
useComposerDraftStore.getState().saveDraft('session-1', submitted)
useComposerDraftStore.getState().clearDraftIfUnchanged('session-1', submitted, { keepAttachments: true })
const draft = useComposerDraftStore.getState().getDraft('session-1')
expect(draft.prompt).toBe('')
expect(draft.isBashMode).toBe(false)
expect(draft.attachedFiles).toBe(submitted.attachedFiles)
})
})
+32
View File
@@ -8,13 +8,23 @@ export interface ComposerDraft {
imageAttachments: ImageAttachment[]
}
export interface ComposerDraftClearOptions {
keepAttachments?: boolean
}
interface ComposerDraftStore {
drafts: Record<string, ComposerDraft>
getDraft: (sessionID: string) => ComposerDraft
saveDraft: (sessionID: string, draft: ComposerDraft) => void
clearDraft: (sessionID: string) => void
clearDraftIfUnchanged: (sessionID: string, submitted: ComposerDraft, options?: ComposerDraftClearOptions) => void
}
const matchesSubmittedDraft = (draft: ComposerDraft, submitted: ComposerDraft): boolean =>
draft.prompt === submitted.prompt &&
draft.attachedFiles === submitted.attachedFiles &&
draft.imageAttachments === submitted.imageAttachments
const createEmptyDraft = (): ComposerDraft => ({
prompt: '',
isBashMode: false,
@@ -36,4 +46,26 @@ export const useComposerDraftStore = create<ComposerDraftStore>((set, get) => ({
return { drafts }
})
},
clearDraftIfUnchanged: (sessionID, submitted, options) => {
set((state) => {
const draft = state.drafts[sessionID]
if (!draft || !matchesSubmittedDraft(draft, submitted)) return state
if (options?.keepAttachments && (submitted.attachedFiles.size > 0 || submitted.imageAttachments.length > 0)) {
return {
drafts: {
...state.drafts,
[sessionID]: {
prompt: '',
isBashMode: false,
attachedFiles: submitted.attachedFiles,
imageAttachments: submitted.imageAttachments,
},
},
}
}
const drafts = { ...state.drafts }
delete drafts[sessionID]
return { drafts }
})
},
}))
-1
View File
@@ -129,7 +129,6 @@ export const ENV = {
SECRET: getEnvString('AUTH_SECRET', process.env.NODE_ENV === 'production' ? '' : generateDefaultSecret()),
TRUSTED_ORIGINS: getEnvString('AUTH_TRUSTED_ORIGINS', 'http://localhost:5173,http://localhost:5003,http://127.0.0.1:5173,http://127.0.0.1:5003'),
SECURE_COOKIES: getEnvBoolean('AUTH_SECURE_COOKIES', getEnvString('NODE_ENV', 'development') === 'production'),
TRUSTED_PROXY_HEADERS: getEnvString('AUTH_TRUSTED_PROXY_HEADERS', ''),
ADMIN_EMAIL: process.env.ADMIN_EMAIL,
ADMIN_PASSWORD: process.env.ADMIN_PASSWORD,
ADMIN_PASSWORD_RESET: getEnvBoolean('ADMIN_PASSWORD_RESET', false),