fix: address findings from the full Docker evaluation of main

Critical and high:
- repos: unlinking a local repo removes only the Manager reference and alias,
  never the repository files; confirm button reads "Unlink"
- auth: rate-limit by the socket address; trust proxy headers only when
  AUTH_TRUSTED_PROXY_HEADERS is set (documented and forwarded in compose)
- composer: per-session in-memory drafts (text, bash mode, attachments);
  Escape no longer clears the prompt
- url params: compose same-tick updates so schedule dialogs stay closed after
  create/delete; delete dialog names the job

Medium:
- tool rows show failures (non-zero shell exit, failed exploration members)
- voice conversation shows the specific error and a starting state
- settings: Escape in dropdowns and the shortcut recorder no longer closes
  the dialog; mobile deep links open the requested section; one content tree
  per platform
- closing pushed sheets, settings, tool panels and schedule dialogs goes back
  in history
- login returns to the requested page; signed-out pages make no
  authenticated requests
- action terminals keep their output (Manager-side output capture and replay)
- unpushed-commit detection, commit message kept on failure
- binary files with unknown extensions are detected and not editable
- tool panel resizes when docked and floats as a dismissible sheet when the
  page is too narrow
- Docker image runs tini as PID 1

Low: not-found states, add-repo and branch validation errors (4xx),
search-aware empty states, mobile repo sort/filter/select cues, sidebar
resize affordance and collapse shortcut, mobile unread badge, preview port
filtering, terminal close handling, walkthrough empty state and helper
session filtering, placeholder contrast, permission labels and focus,
TTS task-list sanitizing, git identity email validation, quieter git
logging, hermetic worktree tests, and accessible names for icon-only
controls.
This commit is contained in:
ioplex committed 2026-10-23 11:42:37 -04:00
1 parent 1c22ef6ea1
commit 4ec62cd4e7
191 files changed
+6674 -696

No files matched your search

+8
View File
@@ -114,6 +114,14 @@ 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=
+2 -1
View File
@@ -19,6 +19,7 @@ RUN apt-get update && apt-get install -y \
python3 \
python3-pip \
python3-venv \
tini \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
@@ -155,5 +156,5 @@ EXPOSE 5003 5004 5100 5101 5102 5103
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD curl -f http://localhost:5003/api/health || exit 1
ENTRYPOINT ["/docker-entrypoint.sh"]
ENTRYPOINT ["/usr/bin/tini", "--", "/docker-entrypoint.sh"]
CMD ["bun", "backend/src/index.ts"]
+44
View File
@@ -0,0 +1,44 @@
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
} catch {
return 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)
}
return headers
}
+4
View File
@@ -4,6 +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'
export type AuthInstance = ReturnType<typeof createAuth>
@@ -90,6 +91,9 @@ export function createAuth(db: Database) {
advanced: {
cookiePrefix: AUTH_COOKIE_PREFIX,
useSecureCookies: ENV.AUTH.SECURE_COOKIES,
ipAddress: {
ipAddressHeaders: getClientIpHeaders(),
},
},
})
+7
View File
@@ -222,6 +222,13 @@ export function updateChangeWalkthrough(
return getChangeWalkthrough(db, sessionId, sourceKey)
}
export function listChangeWalkthroughSessionIds(db: Database): string[] {
const rows = db
.prepare('SELECT DISTINCT walkthrough_session_id FROM change_walkthroughs WHERE walkthrough_session_id IS NOT NULL')
.all() as Array<{ walkthrough_session_id: string }>
return rows.map((row) => row.walkthrough_session_id)
}
export function listChangeWalkthroughs(db: Database, sessionId: string): ChangeWalkthrough[] {
const rows = db
.prepare(`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE session_id = ?`)
+5 -1
View File
@@ -1,5 +1,6 @@
import { Hono } from 'hono'
import { isAdminConfigured, type AuthInstance } from '../auth'
import { applyClientIpHeaders, resolveSocketIp } from '../auth/client-ip'
import { Database } from 'bun:sqlite'
import { ENV } from '@opencode-manager/shared/config/env'
import { logger } from '../utils/logger'
@@ -8,7 +9,10 @@ import { hashPassword } from 'better-auth/crypto'
export function createAuthRoutes(auth: AuthInstance): Hono {
const app = new Hono()
app.all('/*', (c) => auth.handler(c.req.raw))
app.all('/*', (c) => {
applyClientIpHeaders(c.req.raw.headers, resolveSocketIp(c))
return auth.handler(c.req.raw)
})
return app
}
@@ -12,6 +12,10 @@ import { ServiceError } from '../utils/service-error'
export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService) {
const app = new Hono()
app.get('/helper-sessions', (c) => {
return c.json({ sessionIds: service.listHelperSessionIds() })
})
app.get('/:sessionId', async (c) => {
const sourceParam = c.req.query('source')
const source = sourceParam === undefined ? DEFAULT_WALKTHROUGH_SOURCE : parseWalkthroughSourceKey(sourceParam)
+1 -1
View File
@@ -498,7 +498,7 @@ app.get('/', async (c) => {
return c.json({ ...updatedRepo, currentBranch })
} catch (error: unknown) {
logger.error('Failed to create branch:', error)
return c.json({ error: getErrorMessage(error) }, 500)
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
}
})
+18 -3
View File
@@ -1,8 +1,23 @@
import { Hono } from 'hono'
import { Hono, type Context } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import { SetSessionSandboxRequestSchema } from '@opencode-manager/shared/schemas'
import { openCodeErrorStatus } from '@opencode-manager/shared/opencode'
import { SessionSandboxError, type SessionSandboxService } from '../services/session-sandbox'
import { getErrorMessage } from '../utils/error-utils'
import { handleServiceError, parseJsonBody } from '../utils/route-helpers'
/**
* Maps both sandbox errors and the OpenCode errors raised while resolving a session (for example
* `SessionNotFoundError` or `InvalidRequestError` for a malformed id) to their real status codes.
*/
function handleSessionSandboxError(c: Context, error: unknown, fallback: string) {
const status = openCodeErrorStatus(error)
if (status !== undefined) {
return c.json({ error: getErrorMessage(error) || fallback }, status as ContentfulStatusCode)
}
return handleServiceError(c, error, fallback, SessionSandboxError)
}
export function createSessionSandboxRoutes(service: SessionSandboxService) {
const app = new Hono()
@@ -11,7 +26,7 @@ export function createSessionSandboxRoutes(service: SessionSandboxService) {
const state = await service.getState(c.req.param('sessionId'))
return c.json(state)
} catch (error) {
return handleServiceError(c, error, 'Failed to read session sandbox state', SessionSandboxError)
return handleSessionSandboxError(c, error, 'Failed to read session sandbox state')
}
})
@@ -25,7 +40,7 @@ export function createSessionSandboxRoutes(service: SessionSandboxService) {
const state = await service.update(c.req.param('sessionId'), parsed.data)
return c.json(state)
} catch (error) {
return handleServiceError(c, error, 'Failed to set session sandbox state', SessionSandboxError)
return handleSessionSandboxError(c, error, 'Failed to set session sandbox state')
}
})
@@ -31,6 +31,7 @@ import {
deleteChangeWalkthroughs,
getChangeWalkthrough,
getChangeWalkthroughByWalkthroughSession,
listChangeWalkthroughSessionIds,
listChangeWalkthroughs,
updateChangeWalkthrough,
type ChangeWalkthroughPatch,
@@ -56,6 +57,7 @@ import type { SettingsService } from './settings'
import type { SSEEvent } from './sse-aggregator'
const WALKTHROUGH_TIMEOUT_MESSAGE = 'The walkthrough session did not publish within 15 minutes'
const EMPTY_CHANGES_HASH = computeChangesHash([])
export interface ChangeWalkthroughServiceOptions {
generationTimeoutMs?: number
@@ -170,6 +172,11 @@ export class ChangeWalkthroughService {
this.walkthroughsRoot = options.walkthroughsRoot ?? getWalkthroughsPath()
}
/** Sessions the walkthrough runs were created in, which are helper sessions rather than user sessions. */
listHelperSessionIds(): string[] {
return listChangeWalkthroughSessionIds(this.db)
}
async getState(
sessionId: string,
source: WalkthroughSource = DEFAULT_WALKTHROUGH_SOURCE,
@@ -187,6 +194,7 @@ export class ChangeWalkthroughService {
return {
walkthrough,
currentDiffHash,
hasChanges: currentDiffHash === null || currentDiffHash !== EMPTY_CHANGES_HASH,
stale: walkthrough !== null && currentDiffHash !== null && walkthrough.diffHash !== currentDiffHash,
generating: walkthrough?.status === 'generating',
running: walkthrough !== null && walkthrough.executionStartedAt !== null,
+38 -9
View File
@@ -40,9 +40,15 @@ interface FileUploadResult {
mimeType: string
}
const BINARY_MIME_TYPE = 'application/octet-stream'
const SNIFF_BYTE_COUNT = 8192
const MAX_INVALID_UTF8_RATIO = 0.1
type DetectedMimeType = AllowedMimeType | typeof BINARY_MIME_TYPE
export interface RawFileMetadata {
size: number
mimeType: AllowedMimeType
mimeType: DetectedMimeType
lastModified: Date
}
@@ -85,7 +91,7 @@ export async function getRawFileMetadata(userPath: string): Promise<RawFileMetad
return {
size: stats.size,
mimeType: getMimeType(validatedPath),
mimeType: await detectMimeType(validatedPath),
lastModified: stats.lastModified,
}
} catch (error) {
@@ -141,12 +147,10 @@ export async function getFile(userPath: string): Promise<FileInfo> {
} else {
// It's a file - get content
let content = ''
const mimeType = getMimeType(validatedPath)
const mimeType = await detectMimeType(validatedPath)
if (stats.size < FILE_LIMITS.MAX_SIZE_BYTES) {
try {
const mimeType = getMimeType(validatedPath)
if (mimeType.startsWith('image/') || !mimeType.startsWith('text/')) {
content = await readFileAsBase64(validatedPath)
} else {
@@ -179,7 +183,7 @@ export async function uploadFile(userPath: string, file: File, relativePath?: st
throw new Error('File too large')
}
const mimeType = (file.type || getMimeType(file.name)) as AllowedMimeType
const mimeType = (file.type || getKnownMimeType(file.name) || 'text/plain') as AllowedMimeType
if (!ALLOWED_MIME_TYPES.includes(mimeType) && !mimeType.startsWith('text/')) {
throw new Error('File type not allowed')
}
@@ -288,7 +292,7 @@ function validatePath(userPath: string): string {
return resolved
}
function getMimeType(filePath: string): AllowedMimeType {
function getKnownMimeType(filePath: string): AllowedMimeType | undefined {
const ext = path.extname(filePath).toLowerCase()
const mimeTypes: Record<string, AllowedMimeType> = {
@@ -315,7 +319,32 @@ function getMimeType(filePath: string): AllowedMimeType {
'.mdx': 'text/markdown',
}
return mimeTypes[ext] || 'text/plain'
return mimeTypes[ext]
}
async function detectMimeType(filePath: string): Promise<DetectedMimeType> {
const known = getKnownMimeType(filePath)
if (known) return known
return isBinaryContent(await readFilePrefix(filePath)) ? BINARY_MIME_TYPE : 'text/plain'
}
async function readFilePrefix(filePath: string): Promise<Buffer> {
const handle = await fs.open(filePath, 'r')
try {
const buffer = Buffer.alloc(SNIFF_BYTE_COUNT)
const { bytesRead } = await handle.read(buffer, 0, SNIFF_BYTE_COUNT, 0)
return buffer.subarray(0, bytesRead)
} finally {
await handle.close()
}
}
function isBinaryContent(buffer: Buffer): boolean {
if (buffer.length === 0) return false
if (buffer.includes(0)) return true
const decoded = buffer.toString('utf8')
const invalidCharacters = decoded.split('\uFFFD').length - 1
return invalidCharacters / decoded.length > MAX_INVALID_UTF8_RATIO
}
async function readFileLinesAndCount(
@@ -356,7 +385,7 @@ export async function getFileRange(userPath: string, startLine: number, endLine:
const { lines, totalLines } = await readFileLinesAndCount(validatedPath, startLine, endLine)
const clampedEnd = Math.min(endLine, totalLines)
const mimeType = getMimeType(validatedPath)
const mimeType = await detectMimeType(validatedPath)
return {
name: path.basename(validatedPath),
+14 -8
View File
@@ -176,12 +176,13 @@ export class GitService {
}
const repoPath = path.resolve(repo.fullPath)
const revision = branch?.trim() || 'HEAD'
const logArgs = [
'git',
'-C',
repoPath,
'log',
branch?.trim() || 'HEAD',
revision,
`-n`,
String(limit),
'--format=%H|%an|%ae|%at|%s'
@@ -210,7 +211,7 @@ export class GitService {
}
}
const unpushedCommits = await this.getUnpushedCommitHashes(repoPath, logEnv)
const unpushedCommits = await this.getUnpushedCommitHashes(repoPath, revision, logEnv, limit)
return commits.map(commit => ({
...commit,
@@ -858,6 +859,9 @@ export class GitService {
return { ahead: ahead || 0, behind: behind || 0 }
} catch (error) {
if (isNoUpstreamError(error as Error)) {
return { ahead: 0, behind: 0 }
}
logger.warn(`Could not get branch status for repo ${repoId}, returning zeros:`, error)
return { ahead: 0, behind: 0 }
}
@@ -1515,16 +1519,18 @@ export class GitService {
}
private async isCommitUnpushed(repoPath: string, commitHash: string, env: Record<string, string>): Promise<boolean> {
const unpushedHashes = await this.getUnpushedCommitHashes(repoPath, env)
const unpushedHashes = await this.getUnpushedCommitHashes(repoPath, 'HEAD', env)
return unpushedHashes.has(commitHash)
}
private async getUnpushedCommitHashes(repoPath: string, env: Record<string, string>): Promise<Set<string>> {
private async getUnpushedCommitHashes(repoPath: string, revision: string, env: Record<string, string>, limit?: number): Promise<Set<string>> {
try {
const output = await executeCommand(
['git', '-C', repoPath, 'log', '--not', '--remotes', '--format=%H'],
{ env, silent: true }
)
const args = ['git', '-C', repoPath, 'log', revision, '--not', '--remotes']
if (limit !== undefined) {
args.push('-n', String(limit))
}
args.push('--format=%H')
const output = await executeCommand(args, { env, silent: true })
const hashes = output.trim().split('\n').filter(Boolean)
return new Set(hashes)
} catch {
+1 -1
View File
@@ -96,7 +96,7 @@ function isAllowedAddress(address: string): boolean {
address === WILDCARD_V4 ||
address === WILDCARD_V6 ||
address === '::1' ||
address.startsWith('127.')
address === '127.0.0.1'
)
}
+80 -30
View File
@@ -27,30 +27,52 @@ const GIT_CLONE_TIMEOUT = 300000
const DEFAULT_DISCOVERY_MAX_DEPTH = 4
const DISCOVERY_SKIP_DIRECTORIES = new Set(['.git', 'node_modules'])
function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: string): Error {
export class RepoInputError extends Error {
readonly statusCode: 400
constructor(message: string) {
super(message)
this.name = 'RepoInputError'
this.statusCode = 400
}
}
function notFoundOrDeniedMessage(repoUrl: string): string {
return `Repository not found or access denied: ${repoUrl}. Check the URL and add credentials in Settings > Git Credentials if it is private.`
}
function enhanceCloneError(repoUrl: string, originalMessage: string): RepoInputError {
const message = originalMessage.toLowerCase()
if (message.includes('authentication failed') || message.includes('could not authenticate') || message.includes('invalid credentials')) {
return new Error(`Authentication failed for ${repoUrl}. Please add your credentials in Settings > Git Credentials.`)
}
if (message.includes('repository not found') || message.includes('404')) {
return new Error(`Repository not found: ${repoUrl}. Check the URL and ensure you have access to it.`)
}
if (isSSHUrl(repoUrl) && message.includes('permission denied')) {
return new Error(`Access denied to ${repoUrl}. Please add your SSH credentials in Settings > Git Credentials and ensure your SSH key has access to this repository.`)
}
if (isGitHubHttpsUrl(repoUrl) && (message.includes('permission denied') || message.includes('fatal'))) {
return new Error(`Access denied to ${repoUrl}. Please add your credentials in Settings > Git Credentials and ensure you have proper access.`)
}
if (message.includes('timed out')) {
return new Error(`Clone timed out for ${repoUrl}. The repository might be too large or there could be network issues. Try again or verify the repository exists.`)
return new RepoInputError(`Clone timed out for ${repoUrl}. The repository might be too large or there could be network issues.`)
}
return error instanceof Error ? error : new Error(originalMessage)
if (message.includes('could not resolve host') || message.includes('network is unreachable')) {
return new RepoInputError(`Repository not reachable: ${repoUrl}. Check the URL and your network connection.`)
}
if (message.includes('repository not found') || message.includes('not found') || message.includes('does not exist') || message.includes('404')) {
return new RepoInputError(notFoundOrDeniedMessage(repoUrl))
}
if (message.includes('permission denied')) {
return isSSHUrl(repoUrl)
? new RepoInputError(`Access denied to ${repoUrl}. Add your SSH credentials in Settings > Git Credentials and ensure your SSH key has access.`)
: new RepoInputError(notFoundOrDeniedMessage(repoUrl))
}
if (message.includes('authentication failed') || message.includes('could not authenticate') || message.includes('invalid credentials') || message.includes('could not read username')) {
return isGitHubHttpsUrl(repoUrl)
? new RepoInputError(notFoundOrDeniedMessage(repoUrl))
: new RepoInputError(`Authentication failed for ${repoUrl}. Check your credentials in Settings > Git Credentials.`)
}
if (message.includes('not a git repository') || message.includes('fatal:')) {
return new RepoInputError(notFoundOrDeniedMessage(repoUrl))
}
return new RepoInputError(`Could not clone ${repoUrl}. Check the URL and your access to it.`)
}
async function hasCommits(repoPath: string, env: Record<string, string>): Promise<boolean> {
@@ -258,12 +280,12 @@ async function registerExistingLocalRepo(
const exists = await pathExists(normalizedSourcePath)
if (!exists) {
throw new Error(`No such file or directory: '${normalizedSourcePath}'`)
throw new RepoInputError(`No such directory: '${normalizedSourcePath}'`)
}
const isGitRepo = await isValidGitRepo(normalizedSourcePath, env)
if (!isGitRepo) {
throw new Error(`Directory exists but is not a valid Git repository. Use folder discovery to scan nested repositories.`)
throw new RepoInputError(`Directory is not a valid Git repository: '${normalizedSourcePath}'.`)
}
if (branch) {
@@ -317,11 +339,11 @@ export async function discoverLocalRepos(
}> {
const normalizedRootPath = normalizeAbsolutePath(rootPath)
const rootStats = await fs.stat(normalizedRootPath).catch((error: unknown) => {
throw new Error(`Failed to access '${normalizedRootPath}': ${getErrorMessage(error)}`)
throw new RepoInputError(`Failed to access '${normalizedRootPath}': ${getErrorMessage(error)}`)
})
if (!rootStats.isDirectory()) {
throw new Error(`Path is not a directory: '${normalizedRootPath}'`)
throw new RepoInputError(`Path is not a directory: '${normalizedRootPath}'`)
}
const repoPaths: string[] = []
@@ -687,7 +709,7 @@ export async function cloneRepo(
try {
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (cloneError: unknown) {
throw enhanceCloneError(cloneError, normalizedRepoUrl, getErrorMessage(cloneError))
throw enhanceCloneError(normalizedRepoUrl, getErrorMessage(cloneError))
}
let localBranchExists = 'missing'
@@ -704,7 +726,7 @@ export async function cloneRepo(
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
}
} else {
throw enhanceCloneError(error, normalizedRepoUrl, getErrorMessage(error))
throw enhanceCloneError(normalizedRepoUrl, getErrorMessage(error))
}
}
} else {
@@ -801,7 +823,7 @@ export async function cloneRepo(
try {
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
} catch (cloneError: unknown) {
throw enhanceCloneError(cloneError, normalizedRepoUrl, getErrorMessage(cloneError))
throw enhanceCloneError(normalizedRepoUrl, getErrorMessage(cloneError))
}
let localBranchExists = 'missing'
@@ -818,7 +840,7 @@ export async function cloneRepo(
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
}
} else {
throw enhanceCloneError(error, normalizedRepoUrl, getErrorMessage(error))
throw enhanceCloneError(normalizedRepoUrl, getErrorMessage(error))
}
}
}
@@ -876,6 +898,14 @@ export async function switchBranch(
}
}
async function assertValidBranchName(branch: string): Promise<void> {
try {
await executeCommand(['git', 'check-ref-format', '--branch', branch], { silent: true })
} catch {
throw new RepoInputError(`Invalid branch name: '${branch}'.`)
}
}
export async function createBranch(database: Database, gitAuthService: GitAuthService, repoId: number, branch: string): Promise<void> {
const repo = getRepoById(database, repoId)
if (!repo) {
@@ -891,6 +921,8 @@ export async function createBranch(database: Database, gitAuthService: GitAuthSe
.replace(/^refs\/remotes\//, '')
.replace(/^origin\//, '')
await assertValidBranchName(sanitizedBranch)
logger.info(`Creating new branch: ${sanitizedBranch} in ${repo.localPath}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch], { env })
logger.info(`Successfully created and switched to branch: ${sanitizedBranch}`)
@@ -944,6 +976,19 @@ export async function resolveMainCheckoutPath(worktreePath: string): Promise<str
}
}
async function removeWorkspaceAlias(aliasPath: string): Promise<void> {
try {
const stats = await fs.lstat(aliasPath)
if (stats.isSymbolicLink()) {
await fs.unlink(aliasPath)
}
} catch (error: unknown) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error
}
}
}
export async function deleteRepoFiles(database: Database, repoId: number): Promise<void> {
const repo = getRepoById(database, repoId)
if (!repo) {
@@ -959,9 +1004,14 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
if (baseRepoPath) {
await removeWorktree(baseRepoPath, fullPath)
}
await executeCommand(['rm', '-rf', repo.localPath], getReposPath())
} else if (repo.isLocal) {
await removeWorkspaceAlias(fullPath)
} else {
await executeCommand(['rm', '-rf', repo.localPath], getReposPath())
}
await executeCommand(['rm', '-rf', repo.localPath], getReposPath())
deleteRepo(database, repoId)
}
+327
View File
@@ -0,0 +1,327 @@
import {
MAX_PEER_BUFFERED_BYTES,
MAX_UPSTREAM_BUFFERED_BYTES,
type WebSocketBridge,
type WebSocketPeer,
} from '../utils/websocket-bridge'
const BUFFER_LIMIT_CHARS = 256 * 1024
const REPLAY_CHUNK_CHARS = 64 * 1024
const MAX_CONNECT_ATTEMPTS = 3
const RETRY_DELAY_MS = 100
const META_FRAME_PREFIX = 0
const MAX_REGISTERED_HUBS = 64
const WEBSOCKET_OPEN = 1
const WEBSOCKET_CLOSING = 2
const WEBSOCKET_CLOSED = 3
type HubState = 'connecting' | 'open' | 'closed' | 'failed'
const META_DECODER = new TextDecoder()
const META_ENCODER = new TextEncoder()
export function encodeTerminalMetaFrame(cursor: number): Uint8Array<ArrayBuffer> {
const payload = META_ENCODER.encode(JSON.stringify({ cursor }))
const frame = new Uint8Array(new ArrayBuffer(payload.length + 1))
frame[0] = META_FRAME_PREFIX
frame.set(payload, 1)
return frame
}
export interface TerminalHubOptions {
openUpstream: () => Promise<WebSocket>
}
export class TerminalHub {
private readonly decoder = new TextDecoder()
private readonly subscribers = new Set<WebSocketPeer>()
private readonly pendingInput: Array<string | Uint8Array<ArrayBuffer>> = []
private socket: WebSocket | null = null
private state: HubState = 'connecting'
private attempts = 0
private retryTimer: ReturnType<typeof setTimeout> | undefined
private pendingInputBytes = 0
private buffer = ''
private bufferStart = 0
private cursor = 0
constructor(private readonly options: TerminalHubOptions) {}
start(): Promise<void> {
return this.connect()
}
isAvailable(): boolean {
return this.state !== 'failed'
}
isEnded(): boolean {
return this.state === 'closed' || this.state === 'failed'
}
attach(peer: WebSocketPeer, cursor: number | undefined): WebSocketBridge {
this.replay(peer, cursor)
if (this.state === 'closed') {
this.closePeer(peer, 1000)
return { send: () => {}, close: () => {} }
}
this.subscribers.add(peer)
return {
send: (data) => this.write(data),
close: () => {
this.subscribers.delete(peer)
},
}
}
dispose(): void {
this.clearRetry()
if (this.state !== 'failed') this.state = 'closed'
const socket = this.socket
this.socket = null
closeSocketQuietly(socket)
const peers = [...this.subscribers]
this.subscribers.clear()
for (const peer of peers) this.closePeer(peer, 1000)
}
private async connect(): Promise<void> {
if (this.state !== 'connecting') return
this.attempts += 1
let socket: WebSocket
try {
socket = await this.options.openUpstream()
} catch {
this.retryOrFail()
return
}
if (this.state !== 'connecting') {
closeSocketQuietly(socket)
return
}
this.socket = socket
socket.binaryType = 'arraybuffer'
socket.addEventListener('open', () => this.handleOpen(socket))
socket.addEventListener('message', (event) => this.handleMessage(event as MessageEvent))
socket.addEventListener('close', () => this.handleUpstreamClosed(socket))
socket.addEventListener('error', () => this.handleUpstreamError(socket))
const readyState = (socket as { readyState?: number }).readyState
if (readyState === WEBSOCKET_OPEN) {
this.handleOpen(socket)
return
}
if (readyState === WEBSOCKET_CLOSING || readyState === WEBSOCKET_CLOSED) {
this.socket = null
this.retryOrFail()
}
}
private handleOpen(socket: WebSocket): void {
if (this.socket !== socket || this.state !== 'connecting') return
this.state = 'open'
while (this.pendingInput.length > 0) {
const item = this.pendingInput.shift()!
this.pendingInputBytes -= byteLengthOf(item)
try {
socket.send(item)
} catch {
this.endStream()
return
}
}
}
private handleMessage(event: MessageEvent): void {
const data: unknown = event.data
if (typeof data === 'string') {
this.appendOutput(data)
return
}
let bytes: Uint8Array
if (data instanceof ArrayBuffer) {
bytes = new Uint8Array(data)
} else if (data instanceof Uint8Array) {
bytes = data
} else {
return
}
if (bytes.length > 0 && bytes[0] === META_FRAME_PREFIX) {
this.alignToCursor(bytes.subarray(1))
return
}
this.appendOutput(this.decoder.decode(bytes, { stream: true }))
}
private handleUpstreamError(socket: WebSocket): void {
if (this.socket !== socket || this.state !== 'connecting') return
this.socket = null
closeSocketQuietly(socket)
this.retryOrFail()
}
private handleUpstreamClosed(socket: WebSocket): void {
if (this.socket !== socket) return
this.socket = null
if (this.state === 'open') {
this.endStream()
return
}
if (this.state === 'connecting') this.retryOrFail()
}
private retryOrFail(): void {
if (this.state !== 'connecting') return
if (this.attempts >= MAX_CONNECT_ATTEMPTS) {
this.state = 'failed'
return
}
this.clearRetry()
this.retryTimer = setTimeout(() => {
this.retryTimer = undefined
void this.connect()
}, RETRY_DELAY_MS)
}
private clearRetry(): void {
if (this.retryTimer === undefined) return
clearTimeout(this.retryTimer)
this.retryTimer = undefined
}
private endStream(): void {
if (this.state === 'closed') return
this.state = 'closed'
const peers = [...this.subscribers]
this.subscribers.clear()
for (const peer of peers) this.closePeer(peer, 1000)
}
private alignToCursor(payload: Uint8Array): void {
try {
const parsed = JSON.parse(META_DECODER.decode(payload)) as { cursor?: unknown }
if (typeof parsed.cursor !== 'number' || !Number.isSafeInteger(parsed.cursor)) return
if (parsed.cursor < this.cursor) return
this.cursor = parsed.cursor
this.bufferStart = Math.max(0, parsed.cursor - this.buffer.length)
} catch {
return
}
}
private appendOutput(chunk: string): void {
if (chunk.length === 0) return
this.cursor += chunk.length
this.buffer += chunk
const excess = this.buffer.length - BUFFER_LIMIT_CHARS
if (excess > 0) {
this.buffer = this.buffer.slice(excess)
this.bufferStart += excess
}
for (const peer of [...this.subscribers]) this.deliver(peer, chunk)
}
private replay(peer: WebSocketPeer, cursor: number | undefined): void {
const from = this.replayStart(cursor)
const offset = Math.max(0, from - this.bufferStart)
const replay = offset < this.buffer.length ? this.buffer.slice(offset) : ''
for (let index = 0; index < replay.length; index += REPLAY_CHUNK_CHARS) {
this.deliver(peer, replay.slice(index, index + REPLAY_CHUNK_CHARS))
}
this.deliver(peer, encodeTerminalMetaFrame(this.cursor))
}
private replayStart(cursor: number | undefined): number {
if (cursor === -1) return this.cursor
if (cursor === undefined) return this.bufferStart
return Math.max(cursor, this.bufferStart)
}
private write(data: string | ArrayBuffer | Uint8Array<ArrayBuffer>): void {
if (this.state === 'closed' || this.state === 'failed') return
const payload: string | Uint8Array<ArrayBuffer> =
typeof data === 'string' ? data : data instanceof Uint8Array ? data : new Uint8Array(data)
if (this.state === 'open' && this.socket) {
try {
this.socket.send(payload)
} catch {
this.endStream()
}
return
}
this.pendingInput.push(payload)
this.pendingInputBytes += byteLengthOf(payload)
while (this.pendingInputBytes > MAX_UPSTREAM_BUFFERED_BYTES && this.pendingInput.length > 0) {
const dropped = this.pendingInput.shift()!
this.pendingInputBytes -= byteLengthOf(dropped)
}
}
private deliver(peer: WebSocketPeer, data: string | Uint8Array<ArrayBuffer>): void {
try {
peer.send(data)
} catch {
this.subscribers.delete(peer)
return
}
if (peer.bufferedAmount() > MAX_PEER_BUFFERED_BYTES) {
this.subscribers.delete(peer)
this.closePeer(peer, 1013, 'Client too slow')
}
}
private closePeer(peer: WebSocketPeer, code: number, reason?: string): void {
try {
peer.close(code, reason)
} catch {
return
}
}
}
function closeSocketQuietly(socket: { close: () => void } | null | undefined): void {
if (!socket) return
try {
socket.close()
} catch {
return
}
}
function byteLengthOf(data: string | Uint8Array<ArrayBuffer>): number {
return typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength
}
export class TerminalHubRegistry {
private readonly hubs = new Map<string, TerminalHub>()
get(key: string): TerminalHub | undefined {
return this.hubs.get(key)
}
register(key: string, hub: TerminalHub): void {
if (this.hubs.has(key)) {
hub.dispose()
return
}
if (this.hubs.size >= MAX_REGISTERED_HUBS && !this.evict()) {
hub.dispose()
return
}
this.hubs.set(key, hub)
}
dispose(key: string): void {
const hub = this.hubs.get(key)
if (!hub) return
this.hubs.delete(key)
hub.dispose()
}
private evict(): boolean {
const target = [...this.hubs.entries()].find(([, hub]) => hub.isEnded())
if (!target) return false
this.hubs.delete(target[0])
target[1].dispose()
return true
}
}
+59 -6
View File
@@ -5,6 +5,7 @@ import type { OpenCodeClient } from './opencode/client'
import type { CredentialProvider } from './credential-provider'
import { toWebSocketUrl } from './opencode/upstream'
import { bridgeWebSocket, type WebSocketBridge, type WebSocketPeer } from '../utils/websocket-bridge'
import { TerminalHub, TerminalHubRegistry } from './terminal-hub'
type OpenCodePty = Awaited<ReturnType<OpenCodeClient['api']['pty']['list']>>['data'][number]
type OpenCodePersistentPty = Awaited<ReturnType<OpenCodeClient['api']['experimental']['persistentPty']['list']>>[number]
@@ -36,15 +37,28 @@ export class TerminalNotFoundError extends Error {
}
}
const DEFERRED_START_SHELL = '/bin/sh'
const DEFERRED_START_SCRIPT = 'sleep 0.3; exec "$@"'
const DEFERRED_START_HANDLE = 'ocm-terminal'
const DEFERRED_START_KINDS: ReadonlySet<TerminalKind> = new Set(['action', 'setup'])
function deferCommandStart(command: string, args: readonly string[]): { command: string; args: string[] } {
return {
command: DEFERRED_START_SHELL,
args: ['-c', DEFERRED_START_SCRIPT, DEFERRED_START_HANDLE, command, ...args],
}
}
export class TerminalService {
constructor(
private readonly target: TerminalTarget,
private readonly credentialProvider: CredentialProvider,
private readonly openSocket: (url: string) => WebSocket = (url) => new WebSocket(url),
private readonly hubs: TerminalHubRegistry = new TerminalHubRegistry(),
) {}
forTarget(target: TerminalTarget): TerminalService {
return new TerminalService(target, this.credentialProvider, this.openSocket)
return new TerminalService(target, this.credentialProvider, this.openSocket, this.hubs)
}
async list(directory: string): Promise<TerminalInfo[]> {
@@ -53,17 +67,39 @@ export class TerminalService {
}
async create(directory: string, input: CreateTerminalInput): Promise<TerminalInfo> {
const deferred =
input.command !== undefined && DEFERRED_START_KINDS.has(input.kind) && process.platform !== 'win32'
? deferCommandStart(input.command, input.args ?? [])
: undefined
const result = await this.target.client.api.pty.create({
location: { directory },
title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }),
...(input.command !== undefined ? { command: input.command } : {}),
...(input.args !== undefined ? { args: input.args } : {}),
...(deferred
? { command: deferred.command, args: deferred.args }
: {
...(input.command !== undefined ? { command: input.command } : {}),
...(input.args !== undefined ? { args: input.args } : {}),
}),
env: {
...(this.target.includeLocalCredentials ? this.credentialProvider.getGhCliEnv({ cwd: directory }) : {}),
...input.env,
},
})
return this.toTerminalInfo(result.data)
const terminal = this.toTerminalInfo(result.data)
this.recordTerminal(directory, terminal.id)
return terminal
}
private recordTerminal(directory: string, ptyID: string): void {
const key = this.hubKey(directory, ptyID)
if (this.hubs.get(key)) return
const hub = new TerminalHub({ openUpstream: () => this.openUpstreamSocket(directory, ptyID, 0) })
this.hubs.register(key, hub)
void hub.start()
}
private hubKey(directory: string, ptyID: string): string {
return `${this.target.baseUrl()}\u0000${directory}\u0000${ptyID}`
}
async requireTerminal(directory: string, ptyID: string): Promise<TerminalInfo> {
@@ -80,7 +116,11 @@ export class TerminalService {
}
async remove(directory: string, ptyID: string): Promise<void> {
await this.target.client.api.pty.remove({ ptyID, location: { directory } })
try {
await this.target.client.api.pty.remove({ ptyID, location: { directory } })
} finally {
this.hubs.dispose(this.hubKey(directory, ptyID))
}
}
async removeAll(directory: string): Promise<void> {
@@ -104,6 +144,19 @@ export class TerminalService {
): Promise<WebSocketBridge> {
await this.requireTerminal(directory, ptyID)
const key = this.hubKey(directory, ptyID)
const hub = this.hubs.get(key)
if (hub?.isAvailable()) return hub.attach(peer, cursor)
if (hub) this.hubs.dispose(key)
return bridgeWebSocket(await this.openUpstreamSocket(directory, ptyID, cursor), peer)
}
private async openUpstreamSocket(
directory: string,
ptyID: string,
cursor: number | undefined,
): Promise<WebSocket> {
const result = await this.target.client.api.pty.connect.token({
ptyID,
location: { directory },
@@ -117,7 +170,7 @@ export class TerminalService {
socketUrl.searchParams.set('location[directory]', directory)
if (cursor !== undefined) socketUrl.searchParams.set('cursor', String(cursor))
return bridgeWebSocket(this.openSocket(toWebSocketUrl(socketUrl.toString())), peer)
return this.openSocket(toWebSocketUrl(socketUrl.toString()))
}
private async removePersistentTerminals(directory: string): Promise<void> {
+3 -7
View File
@@ -32,14 +32,10 @@ export async function executeCommand<O extends ExecuteCommandOptions = ExecuteCo
const effectiveEnv = { ...process.env, ...options.env }
// Log key git-related environment variables
if (command === 'git') {
logger.info(`executeCommand: ${args.join(' ')}`)
logger.info(` GIT_ASKPASS: ${effectiveEnv.GIT_ASKPASS || '(not set)'}`)
logger.info(` VSCODE_GIT_IPC_HANDLE: ${effectiveEnv.VSCODE_GIT_IPC_HANDLE || '(not set)'}`)
logger.info(` GIT_TERMINAL_PROMPT: ${effectiveEnv.GIT_TERMINAL_PROMPT || '(not set)'}`)
logger.info(` GIT_SSH_COMMAND: ${effectiveEnv.GIT_SSH_COMMAND || '(not set)'}`)
logger.info(` VSCODE_GIT_SSH_HOST_KEY: ${effectiveEnv.VSCODE_GIT_SSH_HOST_KEY || '(not set)'}`)
logger.debug(
`executeCommand: ${args.join(' ')} | GIT_ASKPASS=${effectiveEnv.GIT_ASKPASS || '(not set)'} VSCODE_GIT_IPC_HANDLE=${effectiveEnv.VSCODE_GIT_IPC_HANDLE || '(not set)'} GIT_TERMINAL_PROMPT=${effectiveEnv.GIT_TERMINAL_PROMPT || '(not set)'} GIT_SSH_COMMAND=${effectiveEnv.GIT_SSH_COMMAND || '(not set)'} VSCODE_GIT_SSH_HOST_KEY=${effectiveEnv.VSCODE_GIT_SSH_HOST_KEY || '(not set)'}`
)
}
const proc: ChildProcess = spawn(command || '', cmdArgs, {
+233
View File
@@ -0,0 +1,233 @@
import { describe, it, expect, vi, beforeEach } 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 { createAuthRoutes } from '../../src/routes/auth'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
const { ENV } = vi.hoisted(() => ({
ENV: {
SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' },
AUTH: {
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,
GITHUB_CLIENT_ID: undefined as string | undefined,
GITHUB_CLIENT_SECRET: undefined as string | undefined,
GOOGLE_CLIENT_ID: undefined as string | undefined,
GOOGLE_CLIENT_SECRET: undefined as string | undefined,
DISCORD_CLIENT_ID: undefined as string | undefined,
DISCORD_CLIENT_SECRET: undefined as string | undefined,
PASSKEY_RP_ID: 'localhost',
PASSKEY_RP_NAME: 'OpenCode Manager',
PASSKEY_ORIGIN: 'http://localhost:5003',
},
LOGGING: { DEBUG: false, LOG_LEVEL: 'info' },
},
}))
vi.mock('@opencode-manager/shared/config/env', () => ({
ENV,
getTrustedOrigins: () => ENV.AUTH.TRUSTED_ORIGINS
.split(',')
.map((origin: string) => origin.trim())
.filter((origin: string) => origin.length > 0),
}))
vi.mock('../../src/utils/logger', () => ({
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}))
function socketEnv(address: string | undefined) {
return {
incoming: {
socket: {
remoteAddress: address,
remotePort: 54321,
remoteFamily: address?.includes(':') ? 'IPv6' : 'IPv4',
},
},
}
}
function createAuthDatabase(): Database {
const db = new DatabaseSync(':memory:')
const compatible = Object.assign(db, {
run: (sql: string, ...params: (string | number | null)[]) => db.prepare(sql).run(...params),
}) as unknown as Database
migrate(compatible, allMigrations)
return compatible
}
function signUpRequest(headers: Record<string, string>): Request {
return new Request('http://localhost:5003/api/auth/sign-up/email', {
method: 'POST',
headers: { 'content-type': 'application/json', origin: 'http://localhost:5003', ...headers },
body: JSON.stringify({ email: 'spoof@example.com', password: 'test-password', name: 'Spoof' }),
})
}
function readSessionIpAddress(db: Database): string {
const row = db.prepare('SELECT ipAddress FROM "session" LIMIT 1').get() as { ipAddress: string }
return row.ipAddress
}
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' })
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')
})
it('clears the socket header when the address cannot be resolved', () => {
const headers = new Headers({ [AUTH_SOCKET_IP_HEADER]: '6.6.6.6' })
const result = applyClientIpHeaders(headers, undefined)
expect(result.get(AUTH_SOCKET_IP_HEADER)).toBeNull()
})
})
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')
})
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(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 app: Hono = createAuthRoutes({ handler } as unknown as ReturnType<typeof createAuth>)
await app.fetch(new Request('http://localhost:5003/api/auth/get-session', {
headers: { [AUTH_SOCKET_IP_HEADER]: '6.6.6.6' },
}))
expect(received[0]?.headers.get(AUTH_SOCKET_IP_HEADER)).toBeNull()
})
})
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' }),
socketEnv('203.0.113.7')
)
expect(response.status).toBe(200)
expect(readSessionIpAddress(db)).toBe('203.0.113.7')
} finally {
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,6 +13,7 @@ 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,
@@ -46,6 +47,7 @@ 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,6 +10,7 @@ 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,
@@ -49,6 +50,7 @@ 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
@@ -11,6 +11,7 @@ function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthrou
return {
walkthrough: null,
currentDiffHash: 'hash',
hasChanges: true,
stale: false,
generating: false,
running: false,
@@ -24,6 +25,7 @@ describe('change walkthrough routes', () => {
let startGeneration: ReturnType<typeof vi.fn>
let cancelGeneration: ReturnType<typeof vi.fn>
let refine: ReturnType<typeof vi.fn>
let listHelperSessionIds: ReturnType<typeof vi.fn>
let app: Hono
beforeEach(() => {
@@ -31,13 +33,22 @@ describe('change walkthrough routes', () => {
startGeneration = vi.fn(async () => state({ generating: true }))
cancelGeneration = vi.fn(async () => true)
refine = vi.fn(async () => state({ generating: true }))
listHelperSessionIds = vi.fn(() => ['ses_helper'])
app = new Hono()
app.route(
'/change-walkthroughs',
createChangeWalkthroughRoutes({ getState, startGeneration, cancelGeneration, refine } as unknown as ChangeWalkthroughService),
createChangeWalkthroughRoutes({ getState, startGeneration, cancelGeneration, refine, listHelperSessionIds } as unknown as ChangeWalkthroughService),
)
})
it('GET helper-sessions lists walkthrough helper sessions', async () => {
const res = await app.request('/change-walkthroughs/helper-sessions')
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({ sessionIds: ['ses_helper'] })
expect(getState).not.toHaveBeenCalled()
})
it('GET returns the state for the default source', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`)
+37
View File
@@ -494,6 +494,24 @@ describe('Repo Routes', () => {
const body = await res.json() as { error: string }
expect(body.error).toBe('init failed')
})
it('should return the client status for user-input repo failures', async () => {
vi.mocked(repoService.cloneRepo).mockRejectedValue(Object.assign(
new Error('Repository not found or access denied: https://github.com/test/missing.'),
{ statusCode: 400 },
))
const app = createTestRoutes()
const res = await app.request('/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ repoUrl: 'https://github.com/test/missing' }),
})
expect(res.status).toBe(400)
const body = await res.json() as { error: string }
expect(body.error).toBe('Repository not found or access denied: https://github.com/test/missing.')
})
})
describe('POST /:id/workspaces', () => {
@@ -1108,6 +1126,25 @@ describe('Repo Routes', () => {
const body = await res.json() as { error: string }
expect(body.error).toBe('create failed')
})
it('should return 400 when the branch name is invalid', async () => {
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 }))
vi.mocked(repoService.createBranch).mockRejectedValue(Object.assign(
new Error("Invalid branch name: 'bad name..x'."),
{ statusCode: 400 },
))
const app = createTestRoutes()
const res = await app.request('/1/branch/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ branch: 'bad name..x' }),
})
expect(res.status).toBe(400)
const body = await res.json() as { error: string }
expect(body.error).toBe("Invalid branch name: 'bad name..x'.")
})
})
describe('GET /:id/download', () => {
+37 -2
View File
@@ -22,13 +22,20 @@ function createTestDb(): Database {
function createTestApp(
db: Database,
options: { parents?: Record<string, string | null>; sandboxEnabled?: boolean } = {},
options: { parents?: Record<string, string | null>; sandboxEnabled?: boolean; sessionGetError?: Error } = {},
): Hono {
const settingsService = new SettingsService(db)
if (options.sandboxEnabled) {
settingsService.updateSettings({ sandbox: { enabled: true } })
}
const client = createFakeSessionPermissionClient({ parents: options.parents ?? {} })
const client = createFakeSessionPermissionClient({
parents: options.parents ?? {},
getSession: options.sessionGetError
? async () => {
throw options.sessionGetError
}
: undefined,
})
const service = new SessionSandboxService(db, new SessionAncestry(client), settingsService, {
removeSessionSandbox: async () => undefined,
})
@@ -96,6 +103,34 @@ describe('session sandbox routes', () => {
})
})
it('GET returns 404 when the session does not exist on OpenCode', async () => {
const notFound = Object.assign(new Error('Session not found: ses_missing'), { _tag: 'SessionNotFoundError' })
const app = createTestApp(db, { sessionGetError: notFound })
const res = await app.request('/session-sandbox/ses_missing')
expect(res.status).toBe(404)
await expect(res.json()).resolves.toMatchObject({ error: 'Session not found: ses_missing' })
})
it('GET returns 400 when the session id is malformed', async () => {
const invalid = Object.assign(new Error('Expected a string starting with "ses"'), { _tag: 'InvalidRequestError' })
const app = createTestApp(db, { sessionGetError: invalid })
const res = await app.request('/session-sandbox/nope')
expect(res.status).toBe(400)
await expect(res.json()).resolves.toMatchObject({ error: 'Expected a string starting with "ses"' })
})
it('GET keeps returning 500 for unexpected upstream failures', async () => {
const app = createTestApp(db, { sessionGetError: new Error('upstream unavailable') })
const res = await app.request('/session-sandbox/ses_root')
expect(res.status).toBe(500)
})
it('PUT stores a value and GET reads it back', async () => {
const app = createTestApp(db, { sandboxEnabled: true })
+53
View File
@@ -1554,6 +1554,59 @@ describe('Settings Routes - OpenCode Upgrade', () => {
})
})
describe('PATCH / - git identity validation', () => {
it.each(['not-an-email', 'missing@tld', 'two words@example.com'])('rejects the email %s with 400', async (email) => {
const res = await settingsApp.fetch(new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { gitIdentity: { name: 'Agent', email } } }),
}))
const json = await res.json() as { error: string }
expect(res.status).toBe(400)
expect(json.error).toBe('Invalid settings data')
expect(mockUpdateSettings).not.toHaveBeenCalled()
})
it('accepts an empty email and a valid email', async () => {
mockGetSettings.mockReturnValue({
preferences: { gitIdentity: { name: 'Agent', email: '' } },
updatedAt: 1,
})
mockUpdateSettings.mockReturnValue({
preferences: { gitIdentity: { name: 'Agent', email: 'agent@example.com' } },
updatedAt: 2,
})
const emptyRes = await settingsApp.fetch(new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { gitIdentity: { name: 'Agent', email: '' } } }),
}))
expect(emptyRes.status).toBe(200)
const validRes = await settingsApp.fetch(new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { gitIdentity: { name: 'Agent', email: 'agent@example.com' } } }),
}))
expect(validRes.status).toBe(200)
})
it('rejects an invalid email in a saved identity profile', async () => {
const res = await settingsApp.fetch(new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
preferences: { gitIdentities: [{ id: 'a', name: 'Alpha', email: 'not-an-email' }] },
}),
}))
expect(res.status).toBe(400)
expect(mockUpdateSettings).not.toHaveBeenCalled()
})
})
describe('PATCH / - sandbox enable guard', () => {
afterEach(() => {
forceProcessAttestation(null)
@@ -78,6 +78,13 @@ describe('entrypoint library wiring', () => {
const dockerfile = read(dockerfilePath)
expect(dockerfile).not.toMatch(/chmod \+x \/usr\/local\/lib\/ocm\/container-user\.sh/)
})
it('runs the entrypoint under tini so orphaned processes are reaped', () => {
const dockerfile = read(dockerfilePath)
expect(dockerfile).toMatch(/^\s+tini \\$/m)
expect(dockerfile).toContain('ENTRYPOINT ["/usr/bin/tini", "--", "/docker-entrypoint.sh"]')
expect(read(composePath)).not.toContain('init: true')
})
})
describe('microsandbox runtime install', () => {
@@ -237,6 +244,13 @@ 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', () => {
@@ -265,10 +265,26 @@ describe('ChangeWalkthroughService', () => {
expect(state.walkthrough).toBeNull()
expect(state.stale).toBe(false)
expect(state.currentDiffHash).toBe(computeChangesHash(THREE_HUNKS))
expect(state.hasChanges).toBe(true)
expect(state.generating).toBe(false)
expect(state.error).toBeNull()
})
it('reports no changes for a session with an empty diff', async () => {
sessions[SESSION_ID]!.changes = []
const state = await service.getState(SESSION_ID)
expect(state.currentDiffHash).toBe(computeChangesHash([]))
expect(state.hasChanges).toBe(false)
})
it('lists the helper sessions of existing walkthroughs', async () => {
await service.startGeneration(SESSION_ID, {})
expect(service.listHelperSessionIds()).toEqual(['ses_walk_1'])
})
it('creates exactly one walkthrough session and returns generating', async () => {
const state = await service.startGeneration(SESSION_ID, {})
@@ -479,6 +495,7 @@ describe('ChangeWalkthroughService', () => {
const state = await service.getState(SESSION_ID)
expect(state.currentDiffHash).toBeNull()
expect(state.hasChanges).toBe(true)
expect(state.stale).toBe(false)
})
+44
View File
@@ -93,6 +93,15 @@ describe('files service', () => {
expect(await getRawFileMetadata(`${relativeRoot}/meta-dir`)).toBeNull()
})
it('sniffs an unknown extension and reports binary content', async () => {
const bytes = Buffer.from(Array.from({ length: 512 }, (_, index) => (index * 37 + 11) % 256))
await writeFile(resolveTempPath(`${relativeRoot}/payload.unknownext`), bytes)
const metadata = await getRawFileMetadata(`${relativeRoot}/payload.unknownext`)
expect(metadata?.mimeType).toBe('application/octet-stream')
})
it('rejects with 404 when the file is missing', async () => {
await expect(getRawFileMetadata(`${relativeRoot}/missing.htm`)).rejects.toEqual({
message: 'File or directory not found',
@@ -134,6 +143,32 @@ describe('files service', () => {
expect(Buffer.from(result.content ?? '', 'base64').toString('utf8')).toBe('mystery')
})
it('reports an unknown extension with text content as text', async () => {
await writeLines(`${relativeRoot}/plain.foo`, 'still text')
const result = await getFile(`${relativeRoot}/plain.foo`)
expect(result.mimeType).toBe('text/plain')
})
it('reports an unknown extension with binary content as binary', async () => {
const bytes = Buffer.from(Array.from({ length: 2930 }, (_, index) => (index * 37 + 11) % 256))
await writeFile(resolveTempPath(`${relativeRoot}/blob.bin`), bytes)
const result = await getFile(`${relativeRoot}/blob.bin`)
expect(result.mimeType).toBe('application/octet-stream')
expect(result.content).toBe(bytes.toString('base64'))
})
it('reports an empty unknown extension as text', async () => {
await writeLines(`${relativeRoot}/empty.foo`, '')
const result = await getFile(`${relativeRoot}/empty.foo`)
expect(result.mimeType).toBe('text/plain')
})
it('maps .htm files to text/html', async () => {
await writeLines(`${relativeRoot}/page.htm`, '<h1>hi</h1>')
@@ -326,6 +361,15 @@ describe('files service', () => {
expect(result.hasMore).toBe(false)
})
it('reports binary content for an unknown extension', async () => {
const bytes = Buffer.from(Array.from({ length: 512 }, (_, index) => (index * 37 + 11) % 256))
await writeFile(resolveTempPath(`${relativeRoot}/blob.unknownext`), bytes)
const result = await getFileRange(`${relativeRoot}/blob.unknownext`, 0, 5)
expect(result.mimeType).toBe('application/octet-stream')
})
it('rejects with 404 when the file is missing', async () => {
await expect(getFileRange(`${relativeRoot}/missing.txt`, 0, 5)).rejects.toEqual({
message: 'File does not exist',
@@ -1,7 +1,7 @@
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { migrate } from '../../../src/db/migration-runner'
@@ -15,6 +15,7 @@ import { createRepoRoutes } from '../../../src/routes/repos'
import { createStubOpenCodeClient } from '../../helpers/stub-opencode-client'
import { cloneOrigin, createCommittedRepo, createGitAuthService, createOrigin, git, uniqueName } from '../../helpers/git-fixtures'
import { GitOperationError, parseGitError } from '../../../src/utils/git-errors'
import { logger } from '../../../src/utils/logger'
import type { GitAuthService } from '../../../src/services/git-auth'
import type { Repo } from '../../../src/types/repo'
import type { TerminalService } from '../../../src/services/terminal'
@@ -103,6 +104,121 @@ describe('GitService real git', () => {
})
})
describe('getLog unpushed commits', () => {
it('flags only the commits that are not on a remote', async () => {
const origin = path.join(workspaceRoot, uniqueName('unpushed-origin.git'))
const work = path.join(workspaceRoot, uniqueName('unpushed-work'))
createOrigin(origin, work)
const repoPath = path.join(reposPath, uniqueName('unpushed-clone'))
cloneOrigin(origin, repoPath)
const repo = registerClone(origin, repoPath)
writeFileSync(path.join(repoPath, 'pushed.txt'), 'pushed\n')
git(['add', 'pushed.txt'], repoPath)
git(['commit', '-m', 'pushed commit'], repoPath)
git(['push', 'origin', 'main'], repoPath)
writeFileSync(path.join(repoPath, 'local.txt'), 'local\n')
git(['add', 'local.txt'], repoPath)
git(['commit', '-m', 'local commit'], repoPath)
const commits = await service.getLog(repo.id, db, 10)
expect(commits.map((commit) => [commit.message, commit.unpushed])).toEqual([
['local commit', true],
['pushed commit', false],
['init', false],
])
})
it('flags the listed branch rather than HEAD', async () => {
const origin = path.join(workspaceRoot, uniqueName('unpushed-branch-origin.git'))
const work = path.join(workspaceRoot, uniqueName('unpushed-branch-work'))
createOrigin(origin, work)
const repoPath = path.join(reposPath, uniqueName('unpushed-branch-clone'))
cloneOrigin(origin, repoPath)
const repo = registerClone(origin, repoPath)
git(['checkout', '-b', 'feature'], repoPath)
writeFileSync(path.join(repoPath, 'feature.txt'), 'feature\n')
git(['add', 'feature.txt'], repoPath)
git(['commit', '-m', 'feature commit'], repoPath)
git(['checkout', 'main'], repoPath)
const commits = await service.getLog(repo.id, db, 10, 'feature')
expect(commits.map((commit) => [commit.message, commit.unpushed])).toEqual([
['feature commit', true],
['init', false],
])
})
it('flags every commit as unpushed when the repository has no remote', async () => {
const repoPath = path.join(reposPath, uniqueName('unpushed-local'))
createCommittedRepo(repoPath)
git(['commit', '--allow-empty', '-m', 'local only'], repoPath)
const repo = createRepo(db, {
isLocal: true,
localPath: path.basename(repoPath),
sourcePath: repoPath,
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
const commits = await service.getLog(repo.id, db, 10)
expect(commits.map((commit) => commit.message)).toEqual(['local only', 'init'])
expect(commits.every((commit) => commit.unpushed)).toBe(true)
})
})
describe('getBranchStatus', () => {
it('returns zeros without logging when the branch has no upstream', async () => {
const repoPath = path.join(reposPath, uniqueName('status-no-upstream'))
createCommittedRepo(repoPath)
const repo = createRepo(db, {
isLocal: true,
localPath: path.basename(repoPath),
sourcePath: repoPath,
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
try {
await expect(service.getBranchStatus(repo.id, db)).resolves.toEqual({ ahead: 0, behind: 0 })
expect(warnSpy).not.toHaveBeenCalled()
} finally {
warnSpy.mockRestore()
}
})
it('still logs a real failure', async () => {
const notARepoPath = path.join(reposPath, uniqueName('status-not-a-repo'))
mkdirSync(notARepoPath, { recursive: true })
const repo = createRepo(db, {
isLocal: true,
localPath: path.basename(notARepoPath),
sourcePath: notARepoPath,
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
try {
await expect(service.getBranchStatus(repo.id, db)).resolves.toEqual({ ahead: 0, behind: 0 })
expect(warnSpy).toHaveBeenCalledTimes(1)
} finally {
warnSpy.mockRestore()
}
})
})
describe('renameBranch', () => {
it('renames the checked-out branch and updates the repo row', async () => {
const origin = path.join(workspaceRoot, uniqueName('rename-origin.git'))
@@ -21,6 +21,7 @@ const IPV4_FIXTURE = [
procRow('0100007F:1F90', '00000000:0000', '0A', '22222'),
procRow('0501A8C0:1F90', '00000000:0000', '0A', '33333'),
procRow('0100007F:1435', '0100007F:9C40', '01', '44444'),
procRow('0B00007F:8F71', '00000000:0000', '0A', '88888'),
].join('\n')
const IPV6_FIXTURE = [
@@ -70,6 +71,12 @@ describe('parseProcNetTcp', () => {
])
})
it('drops loopback aliases such as Docker embedded DNS', () => {
const sockets = parseProcNetTcp(IPV4_FIXTURE, 4)
expect(sockets.map((socket) => socket.address)).not.toContain('127.0.0.11')
})
it('decodes little-endian IPv6 addresses and keeps loopback and wildcard', () => {
const sockets = parseProcNetTcp(IPV6_FIXTURE, 6)
@@ -252,6 +259,19 @@ describe('listListeningPorts', () => {
expect(cwdCalls).toEqual([[777, 888]])
})
it('drops loopback aliases from lsof listeners', async () => {
const deps = createDeps(
{ files: {}, links: {}, dirs: {} },
{
platform: 'darwin',
runLsof: async () => ['p999', 'cdockerd', 'n127.0.0.11:36721'].join('\n'),
runLsofCwd: async () => '',
},
)
expect(await listListeningPorts(deps)).toEqual([])
})
it('keeps cwd null when the cwd lsof call rejects but still lists the ports', async () => {
const deps = createDeps(
{ files: {}, links: {}, dirs: {} },
+94 -6
View File
@@ -196,9 +196,13 @@ describe('repo service real git', () => {
})
it('rejects a missing absolute path', async () => {
const { initLocalRepo } = await import('../../src/services/repo')
const { initLocalRepo, RepoInputError } = await import('../../src/services/repo')
await expect(initLocalRepo(db, gitAuth, path.join(projectsRoot, 'missing-absolute'))).rejects.toThrow(/No such file or directory/)
const error = await initLocalRepo(db, gitAuth, path.join(projectsRoot, 'missing-absolute')).catch((thrown: unknown) => thrown)
expect(error).toBeInstanceOf(RepoInputError)
expect((error as { statusCode: number }).statusCode).toBe(400)
expect((error as Error).message).toMatch(/No such directory/)
})
it('rejects the repos root itself as a source', async () => {
@@ -397,6 +401,19 @@ describe('repo service real git', () => {
await expect(createBranch(db, gitAuth, 9999, 'main')).rejects.toThrow(/Repo not found/)
})
it('rejects an invalid branch name as a repo input error', async () => {
const { createBranch, RepoInputError } = await import('../../src/services/repo')
const repoPath = path.join(reposPath, uniqueName('create-bad-branch'))
createCommittedRepo(repoPath)
const repo = registerLocalRepo(path.basename(repoPath))
const error = await createBranch(db, gitAuth, repo.id, 'bad name..x').catch((thrown: unknown) => thrown)
expect(error).toBeInstanceOf(RepoInputError)
expect((error as Error).message).toBe("Invalid branch name: 'bad name..x'.")
expect(git(['rev-parse', '--abbrev-ref', 'HEAD'], repoPath)).toBe('main')
})
})
describe('pullRepo', () => {
@@ -458,14 +475,66 @@ describe('repo service real git', () => {
})
describe('deleteRepoFiles', () => {
it('deletes a local repo directory and its row', async () => {
it('keeps the files of a local repo inside the repos directory and deletes the row', async () => {
const { deleteRepoFiles } = await import('../../src/services/repo')
const repoPath = path.join(reposPath, uniqueName('delete-local'))
const repoPath = path.join(reposPath, uniqueName('delete-local-inside'))
createCommittedRepo(repoPath)
writeFileSync(path.join(repoPath, 'important.txt'), 'keep me')
const repo = registerLocalRepo(path.basename(repoPath))
await deleteRepoFiles(db, repo.id)
expect(existsSync(path.join(repoPath, 'important.txt'))).toBe(true)
expect(existsSync(path.join(repoPath, '.git'))).toBe(true)
expect(getRepoById(db, repo.id)).toBeNull()
})
it('removes only the workspace alias of a local repo outside the repos directory', async () => {
const { initLocalRepo, deleteRepoFiles } = await import('../../src/services/repo')
const sourcePath = path.join(projectsRoot, uniqueName('delete-local-outside'))
createCommittedRepo(sourcePath)
writeFileSync(path.join(sourcePath, 'important.txt'), 'keep me')
const repo = await initLocalRepo(db, gitAuth, sourcePath)
const aliasPath = path.join(reposPath, repo.localPath)
expect(lstatSync(aliasPath).isSymbolicLink()).toBe(true)
await deleteRepoFiles(db, repo.id)
expect(existsSync(aliasPath)).toBe(false)
expect(existsSync(path.join(sourcePath, 'important.txt'))).toBe(true)
expect(getRepoById(db, repo.id)).toBeNull()
})
it('keeps local repo files when the alias is missing', async () => {
const { initLocalRepo, deleteRepoFiles } = await import('../../src/services/repo')
const sourcePath = path.join(projectsRoot, uniqueName('delete-local-alias-gone'))
createCommittedRepo(sourcePath)
const repo = await initLocalRepo(db, gitAuth, sourcePath)
rmSync(path.join(reposPath, repo.localPath), { force: true })
await deleteRepoFiles(db, repo.id)
expect(existsSync(path.join(sourcePath, '.git'))).toBe(true)
expect(getRepoById(db, repo.id)).toBeNull()
})
it('deletes a cloned repo directory and its row', async () => {
const { deleteRepoFiles } = await import('../../src/services/repo')
const baseName = uniqueName('delete-clone')
const repoPath = path.join(reposPath, baseName)
createCommittedRepo(repoPath)
const repo = createRepo(db, {
repoUrl: `https://github.com/example/${baseName}.git`,
localPath: baseName,
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
await deleteRepoFiles(db, repo.id)
expect(existsSync(repoPath)).toBe(false)
expect(getRepoById(db, repo.id)).toBeNull()
})
@@ -653,10 +722,29 @@ describe('repo service real git', () => {
})
it('enhances a missing local clone error and rolls back the row', async () => {
const { cloneRepo } = await import('../../src/services/repo')
const { cloneRepo, RepoInputError } = await import('../../src/services/repo')
const name = uniqueName('clone-missing-source')
await expect(cloneRepo(db, gitAuth, path.join(workspaceRoot, 'no-such-origin'), { directoryName: name })).rejects.toThrow(/does not exist/)
const error = await cloneRepo(db, gitAuth, path.join(workspaceRoot, 'no-such-origin'), { directoryName: name })
.catch((thrown: unknown) => thrown)
expect(error).toBeInstanceOf(RepoInputError)
expect((error as Error).message).toMatch(/Repository not found or access denied/)
expect((error as { statusCode: number }).statusCode).toBe(400)
expect(getRepoByLocalPath(db, name)).toBeNull()
})
it('reports an unparseable clone URL as a repo input error', async () => {
const { cloneRepo, RepoInputError } = await import('../../src/services/repo')
const name = uniqueName('clone-bad-url')
const error = await cloneRepo(db, gitAuth, 'not a url !!', { directoryName: name })
.catch((thrown: unknown) => thrown)
expect(error).toBeInstanceOf(RepoInputError)
expect((error as Error).message).not.toMatch(/Command failed/)
expect((error as Error).message).toMatch(/Repository not found or access denied/)
expect((error as { statusCode: number }).statusCode).toBe(400)
expect(getRepoByLocalPath(db, name)).toBeNull()
})
+4 -4
View File
@@ -21,17 +21,17 @@ describe('repo worktree helpers', () => {
worktreePath = path.join(tmpDir, 'feature-x')
// Init bare origin
execSync(`git init --bare "${originRepoPath}"`, { env })
execSync(`git init --bare -b main "${originRepoPath}"`, { env })
// Clone origin to get a working base repo (default branch is "master" in bare repos)
// Clone origin to get a working base repo (default branch is "main")
execSync(`git clone "${originRepoPath}" "${baseRepoPath}"`, { env })
// Set git config for commits
execSync(`git -C "${baseRepoPath}" config user.email test@test.com`, { env })
execSync(`git -C "${baseRepoPath}" config user.name Test`, { env })
// Rename default branch to "main" and push
execSync(`git -C "${baseRepoPath}" branch -m master main`, { env })
// Ensure the branch is "main" and push
execSync(`git -C "${baseRepoPath}" branch -M main`, { env })
execSync(`git -C "${baseRepoPath}" commit --allow-empty -m "Initial commit"`, { env })
execSync(`git -C "${baseRepoPath}" push origin main`, { env })
@@ -72,12 +72,12 @@ describe('ScheduleWorktreeManager', () => {
nonGitDir = path.join(tmpDir, 'non-git-dir')
mkdirSync(nonGitDir, { recursive: true })
// Init bare origin and clone a working base repo
execSync(`git init --bare "${originRepoPath}"`, { env })
// Init bare origin on main and clone a working base repo
execSync(`git init --bare -b main "${originRepoPath}"`, { env })
execSync(`git clone "${originRepoPath}" "${baseRepoPath}"`, { env })
execSync(`git -C "${baseRepoPath}" config user.email test@test.com`, { env })
execSync(`git -C "${baseRepoPath}" config user.name Test`, { env })
execSync(`git -C "${baseRepoPath}" branch -m master main`, { env })
execSync(`git -C "${baseRepoPath}" branch -M main`, { env })
execSync(`git -C "${baseRepoPath}" commit --allow-empty -m "Initial commit"`, { env })
execSync(`git -C "${baseRepoPath}" push origin main`, { env })
execSync(`git -C "${originRepoPath}" symbolic-ref HEAD refs/heads/main`, { env })
+167
View File
@@ -0,0 +1,167 @@
import { describe, expect, it, vi } from 'vitest'
import { TerminalHub } from '../../src/services/terminal-hub'
import type { WebSocketPeer } from '../../src/utils/websocket-bridge'
class FakeSocket {
binaryType: 'blob' | 'arraybuffer' = 'blob'
readyState = 0
readonly sent: Array<string | Uint8Array> = []
close = vi.fn()
private readonly listeners = new Map<string, Set<(event: unknown) => void>>()
addEventListener(type: string, listener: (event: unknown) => void): void {
const set = this.listeners.get(type) ?? new Set<(event: unknown) => void>()
set.add(listener)
this.listeners.set(type, set)
}
send(data: string | Uint8Array): void {
this.sent.push(data)
}
emit(type: string, event: unknown = {}): void {
for (const listener of this.listeners.get(type) ?? []) listener(event)
}
}
interface FakePeer extends WebSocketPeer {
sent: Array<string | Uint8Array>
closeCalls: Array<{ code?: number; reason?: string }>
}
function createPeer(): FakePeer {
const sent: Array<string | Uint8Array> = []
const closeCalls: Array<{ code?: number; reason?: string }> = []
return {
sent,
closeCalls,
send(data) {
sent.push(data)
},
close(code, reason) {
closeCalls.push({ code, reason })
},
bufferedAmount() {
return 0
},
}
}
function decodeMeta(data: string | Uint8Array): number {
expect(data).toBeInstanceOf(Uint8Array)
const bytes = data as Uint8Array
expect(bytes[0]).toBe(0)
return (JSON.parse(new TextDecoder().decode(bytes.subarray(1))) as { cursor: number }).cursor
}
async function createOpenHub(): Promise<{ hub: TerminalHub; socket: FakeSocket }> {
const socket = new FakeSocket()
const hub = new TerminalHub({ openUpstream: async () => socket as unknown as WebSocket })
await hub.start()
socket.readyState = 1
socket.emit('open')
return { hub, socket }
}
describe('TerminalHub', () => {
it('sends retained output, then the cursor, then live output to a late client', async () => {
const { hub, socket } = await createOpenHub()
socket.emit('message', { data: 'hi\r\n' })
const peer = createPeer()
hub.attach(peer, undefined)
socket.emit('message', { data: 'more' })
expect(peer.sent[0]).toBe('hi\r\n')
expect(decodeMeta(peer.sent[1]!)).toBe(4)
expect(peer.sent[2]).toBe('more')
expect(peer.closeCalls).toEqual([])
})
it('replays an exited terminal and then closes the client', async () => {
const { hub, socket } = await createOpenHub()
socket.emit('message', { data: 'hi' })
socket.emit('close', { code: 1000 })
const peer = createPeer()
hub.attach(peer, undefined)
expect(peer.sent[0]).toBe('hi')
expect(decodeMeta(peer.sent[1]!)).toBe(2)
expect(peer.closeCalls).toEqual([{ code: 1000, reason: undefined }])
expect(hub.isEnded()).toBe(true)
})
it('replays only the output after the cursor a reconnecting client sends back', async () => {
const { hub, socket } = await createOpenHub()
socket.emit('message', { data: 'first' })
socket.emit('message', { data: 'second' })
const client = createPeer()
hub.attach(client, undefined)
expect(client.sent[1]).toBeInstanceOf(Uint8Array)
hub.attach(client, decodeMeta(client.sent[1]!))
const reconnected = createPeer()
hub.attach(reconnected, 5)
expect(reconnected.sent[0]).toBe('second')
expect(decodeMeta(reconnected.sent[1]!)).toBe(11)
})
it('tails an exited terminal without replaying its buffer for cursor -1', async () => {
const { hub, socket } = await createOpenHub()
socket.emit('message', { data: 'hello' })
socket.emit('close', {})
const peer = createPeer()
hub.attach(peer, -1)
expect(peer.sent).toHaveLength(1)
expect(decodeMeta(peer.sent[0]!)).toBe(5)
expect(peer.closeCalls).toEqual([{ code: 1000, reason: undefined }])
})
it('keeps the retained buffer bounded while the cursor keeps counting', async () => {
const { hub, socket } = await createOpenHub()
socket.emit('message', { data: 'a'.repeat(300 * 1024) })
const peer = createPeer()
hub.attach(peer, undefined)
const replay = peer.sent
.slice(0, -1)
.map((chunk) => chunk as string)
.join('')
expect(replay).toHaveLength(256 * 1024)
expect(decodeMeta(peer.sent[peer.sent.length - 1]!)).toBe(300 * 1024)
})
it('queues client input until the upstream opens and then forwards it', async () => {
const socket = new FakeSocket()
const hub = new TerminalHub({ openUpstream: async () => socket as unknown as WebSocket })
await hub.start()
const peer = createPeer()
const bridge = hub.attach(peer, undefined)
bridge.send('typed')
expect(socket.sent).toEqual([])
socket.readyState = 1
socket.emit('open')
bridge.send('later')
expect(socket.sent).toEqual(['typed', 'later'])
})
it('stops delivering live output once a client detaches', async () => {
const { hub, socket } = await createOpenHub()
const peer = createPeer()
const bridge = hub.attach(peer, undefined)
bridge.close()
socket.emit('message', { data: 'after close' })
expect(peer.sent.some((chunk) => chunk === 'after close')).toBe(false)
})
})
+153 -3
View File
@@ -19,7 +19,20 @@ function createPty(overrides: Partial<PtyRecord> = {}): PtyRecord {
}
function createClient(pty: Record<string, unknown>, api: Record<string, unknown> = {}): OpenCodeClient {
return { api: { pty, ...api } } as unknown as OpenCodeClient
const hubToken = vi.fn(async () => ({ data: { ticket: 'hub-ticket', expires_in: 60 } }))
return { api: { pty: { connect: { token: hubToken }, ...pty }, ...api } } as unknown as OpenCodeClient
}
function createSocketFactory(): { openSocket: (url: string) => WebSocket; sockets: FakeUpstreamSocket[] } {
const sockets: FakeUpstreamSocket[] = []
return {
sockets,
openSocket: (url) => {
const socket = new FakeUpstreamSocket(url)
sockets.push(socket)
return socket as unknown as WebSocket
},
}
}
function createCredentialProvider(shellEnv: Record<string, string> = {}): CredentialProvider {
@@ -29,7 +42,7 @@ function createCredentialProvider(shellEnv: Record<string, string> = {}): Creden
function createTerminalService(
client: OpenCodeClient,
provider: CredentialProvider,
openSocket?: (url: string) => WebSocket,
openSocket: (url: string) => WebSocket = createSocketFactory().openSocket,
baseUrl = 'http://127.0.0.1:5551',
includeLocalCredentials = true,
): TerminalService {
@@ -139,7 +152,7 @@ describe('TerminalService', () => {
location: { directory: '/repo' },
title: 'ocm:action:dev:Dev server',
command: '/bin/sh',
args: ['-c', 'npm run dev'],
args: ['-c', 'sleep 0.3; exec "$@"', 'ocm-terminal', '/bin/sh', '-c', 'npm run dev'],
env: { GH_TOKEN: 'gh', FOO: 'bar' },
})
expect(result).toEqual({
@@ -170,6 +183,143 @@ describe('TerminalService', () => {
expect(captured).not.toHaveProperty('args')
expect(captured?.env).toEqual({})
})
it('defers a setup command until the manager has attached to the new PTY', async () => {
const create = vi.fn(async () => ({
location: { directory: '/repo' },
data: createPty({ id: 'pty-setup', title: 'ocm:setup:Worktree setup' }),
}))
const service = createTerminalService(createClient({ create }), createCredentialProvider())
await service.create('/repo', {
kind: 'setup',
name: 'Worktree setup',
command: '/bin/sh',
args: ['-c', 'set -e\npnpm install'],
})
expect(create).toHaveBeenCalledWith(
expect.objectContaining({
command: '/bin/sh',
args: ['-c', 'sleep 0.3; exec "$@"', 'ocm-terminal', '/bin/sh', '-c', 'set -e\npnpm install'],
}),
)
})
it('keeps a plain shell command without deferring it', async () => {
let captured: Record<string, unknown> | undefined
const create = vi.fn(async (input: Record<string, unknown>) => {
captured = input
return { location: { directory: '/repo' }, data: createPty({ id: 'pty-1', title: 'Terminal' }) }
})
const service = createTerminalService(createClient({ create }), createCredentialProvider())
await service.create('/repo', { kind: 'shell', name: 'Terminal', command: '/bin/zsh', args: ['-l'] })
expect(captured).toMatchObject({ command: '/bin/zsh', args: ['-l'] })
})
})
describe('output capture', () => {
function createCapturingService(actionTerminal = createPty({ id: 'pty-action', title: 'ocm:action:say:Say hi' })) {
const create = vi.fn(async () => ({ location: { directory: '/repo' }, data: actionTerminal }))
const list = vi.fn(async () => ({ location: { directory: '/repo' }, data: [actionTerminal] }))
const factory = createSocketFactory()
const service = createTerminalService(
createClient({ create, list }),
createCredentialProvider(),
factory.openSocket,
)
return { service, sockets: factory.sockets }
}
async function openHub(sockets: FakeUpstreamSocket[]): Promise<FakeUpstreamSocket> {
await vi.waitFor(() => expect(sockets).toHaveLength(1))
sockets[0]!.emit('open', {})
return sockets[0]!
}
it('opens the upstream at creation so output is captured before the first client attaches', async () => {
const { service, sockets } = createCapturingService()
await service.create('/repo', { kind: 'shell', name: 'Terminal' })
const socket = await openHub(sockets)
const url = new URL(socket.url)
expect(url.pathname).toBe('/api/pty/pty-action/connect')
expect(url.searchParams.get('cursor')).toBe('0')
})
it('replays captured output and the exit close frame to a late client', async () => {
const exited = createPty({ id: 'pty-action', title: 'ocm:action:say:Say hi', status: 'exited', exitCode: 0 })
const { service, sockets } = createCapturingService(exited)
await service.create('/repo', { kind: 'action', actionId: 'say', name: 'Say hi', command: '/bin/sh', args: ['-c', 'echo hi'] })
const socket = await openHub(sockets)
socket.emit('message', { data: 'hi\r\n' })
socket.emit('close', { code: 1000 })
const peer = createPeer()
await service.connect('/repo', 'pty-action', undefined, peer)
expect(peer.sent[0]).toBe('hi\r\n')
expect(peer.sent[1]).toBeInstanceOf(Uint8Array)
const meta = peer.sent[1] as Uint8Array
expect(meta[0]).toBe(0)
expect(JSON.parse(new TextDecoder().decode(meta.subarray(1)))).toEqual({ cursor: 4 })
expect(peer.closeCalls).toEqual([{ code: 1000, reason: undefined }])
expect(sockets).toHaveLength(1)
})
it('forwards late-client input through the captured upstream', async () => {
const { service, sockets } = createCapturingService()
await service.create('/repo', { kind: 'shell', name: 'Terminal' })
const socket = await openHub(sockets)
const peer = createPeer()
const bridge = await service.connect('/repo', 'pty-action', undefined, peer)
bridge.send('ls\r')
expect(socket.sent).toEqual(['ls\r'])
})
it('streams live output to an attached client without duplicating the replay', async () => {
const { service, sockets } = createCapturingService()
await service.create('/repo', { kind: 'shell', name: 'Terminal' })
const socket = await openHub(sockets)
socket.emit('message', { data: 'old' })
const peer = createPeer()
await service.connect('/repo', 'pty-action', undefined, peer)
socket.emit('message', { data: 'new' })
expect(peer.sent[0]).toBe('old')
expect(peer.sent[2]).toBe('new')
})
it('drops the captured upstream when the terminal is removed', async () => {
const removed = createPty({ id: 'pty-action', title: 'Terminal', status: 'exited', exitCode: 0 })
const remove = vi.fn(async () => undefined)
const factory = createSocketFactory()
const service = createTerminalService(
createClient({ create: vi.fn(async () => ({ data: removed })), list: vi.fn(async () => ({ data: [removed] })), remove }),
createCredentialProvider(),
factory.openSocket,
)
await service.create('/repo', { kind: 'shell', name: 'Terminal' })
await openHub(factory.sockets)
await service.remove('/repo', 'pty-action')
const peer = createPeer()
await service.connect('/repo', 'pty-action', undefined, peer)
expect(remove).toHaveBeenCalledWith({ ptyID: 'pty-action', location: { directory: '/repo' } })
expect(factory.sockets).toHaveLength(2)
expect(new URL(factory.sockets[1]!.url).searchParams.has('cursor')).toBe(false)
})
})
describe('remote target', () => {
+19 -1
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { executeCommand } from '../../src/utils/process'
import { logger } from '../../src/utils/logger'
describe('executeCommand signal handling', () => {
it('reports a signal-terminated child as a non-zero exit code when exit codes are ignored', async () => {
@@ -50,4 +51,21 @@ describe('executeCommand signal handling', () => {
expect(result).toBe('hello')
})
it('logs a git command as one debug line and never at info level', async () => {
const infoSpy = vi.spyOn(logger, 'info').mockImplementation(() => {})
const debugSpy = vi.spyOn(logger, 'debug').mockImplementation(() => {})
try {
await executeCommand(['git', '--version'], { silent: true })
expect(infoSpy).not.toHaveBeenCalled()
expect(debugSpy).toHaveBeenCalledTimes(1)
expect(debugSpy.mock.calls[0]).toHaveLength(1)
expect(debugSpy.mock.calls[0]?.[0]).toContain('git --version')
} finally {
infoSpy.mockRestore()
debugSpy.mockRestore()
}
})
})
+1
View File
@@ -43,6 +43,7 @@ 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,6 +41,7 @@ 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}
-13
View File
@@ -4,18 +4,6 @@ import path from 'node:path'
import { test as base, expect, request as playwrightRequest, type Page } from '@playwright/test'
import { BASE_URL, E2E_TMP, STORAGE_STATE } from './env'
const UNAUTHENTICATED_BOOTSTRAP_ENDPOINTS = [
'/api/settings',
'/api/schedules/all/runs/unread',
'/api/repos',
'/api/sse/stream',
]
function isIgnoredConsoleError(text: string): boolean {
if (!text.includes('401 (Unauthorized)')) return false
return UNAUTHENTICATED_BOOTSTRAP_ENDPOINTS.some((endpoint) => text.includes(endpoint))
}
export interface RepoFixture {
id: number
name: string
@@ -48,7 +36,6 @@ export const test = base.extend<{ page: Page }, WorkerFixtures>({
if (message.type() !== 'error') return
const url = message.location().url
const text = `${message.text()}${url ? ` (${url})` : ''}`
if (isIgnoredConsoleError(text)) return
errors.push(`console.error: ${text}`)
})
+116 -91
View File
@@ -21,6 +21,7 @@ import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt'
import { MobileTabBar } from '@/components/navigation/MobileTabBar'
import { MobileSheetHost } from '@/components/navigation/MobileSheetHost'
import { RouteErrorBoundary } from '@/components/ui/route-error-boundary'
import { NotFoundState } from '@/components/ui/not-found-state'
import { DesktopSidebar } from '@/components/navigation/DesktopSidebar'
import { useRightEdgeSwipe, useSwipeBack } from './hooks/useMobile'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
@@ -164,6 +165,19 @@ function ServerScope({ children }: { children: ReactNode }) {
return <OpenCodeServerProvider serverId={serverId}>{children}</OpenCodeServerProvider>
}
function RootLayout() {
return (
<AuthProvider>
<ThemeProvider>
<TTSProvider>
<ThemedToaster />
<Outlet />
</TTSProvider>
</ThemeProvider>
</AuthProvider>
)
}
function AppShell() {
const navigate = useNavigate()
const location = useLocation()
@@ -233,41 +247,36 @@ function AppShell() {
)
return (
<ThemeProvider>
<AuthProvider>
<EventProvider>
<RepoWorktreesProvider>
<KeyboardShortcutsProvider>
<GlobalShortcuts />
<SidebarServerRouteSync />
<div className="flex h-dvh w-full min-w-0 flex-col">
<PwaUpdatePrompt />
<div ref={rootRef} className="flex flex-1 min-h-0 w-full min-w-0">
<DesktopSidebar />
<main className="flex-1 min-w-0 min-h-0 flex flex-col">
<Outlet />
</main>
</div>
</div>
<MobileTabBar />
<MobileSheetHost />
<PermissionDialogWrapper />
<SSHHostKeyDialogWrapper />
<SettingsDialog />
<HealthMonitor />
<VersionNotifier />
<ThemedToaster />
</KeyboardShortcutsProvider>
</RepoWorktreesProvider>
</EventProvider>
</AuthProvider>
</ThemeProvider>
<EventProvider>
<RepoWorktreesProvider>
<KeyboardShortcutsProvider>
<GlobalShortcuts />
<SidebarServerRouteSync />
<div className="flex h-dvh w-full min-w-0 flex-col">
<PwaUpdatePrompt />
<div ref={rootRef} className="flex flex-1 min-h-0 w-full min-w-0">
<DesktopSidebar />
<main className="flex-1 min-w-0 min-h-0 flex flex-col">
<Outlet />
</main>
</div>
</div>
<MobileTabBar />
<MobileSheetHost />
<PermissionDialogWrapper />
<SSHHostKeyDialogWrapper />
<SettingsDialog />
<HealthMonitor />
<VersionNotifier />
</KeyboardShortcutsProvider>
</RepoWorktreesProvider>
</EventProvider>
)
}
const router = createBrowserRouter([
{
element: <AppShell />,
element: <RootLayout />,
errorElement: <RouteErrorBoundary />,
children: [
{
@@ -286,62 +295,80 @@ const router = createBrowserRouter([
loader: setupLoader,
},
{
path: '/',
element: <Repos />,
loader: protectedLoader,
},
{
path: '/assistant',
element: <AssistantRedirect />,
loader: protectedLoader,
},
{
path: '/repos/:id',
element: <RepoDetail />,
loader: protectedLoader,
},
{
path: '/repos/:id/assistant',
element: <AssistantRedirect />,
loader: protectedLoader,
},
{
path: '/repos/:id/sessions/:sessionId',
element: <SessionDetail />,
loader: protectedLoader,
},
{
path: '/repos/:id/schedules',
element: <Schedules />,
loader: protectedLoader,
},
{
path: '/schedules',
element: <GlobalSchedules />,
loader: protectedLoader,
},
{
path: '/servers/:serverId',
element: <LinkedServerRedirect />,
loader: protectedLoader,
},
{
path: '/servers/:serverId/projects',
element: (
<ServerScope>
<RemoteProject />
</ServerScope>
),
loader: protectedLoader,
},
{
path: '/servers/:serverId/sessions/:sessionId',
element: (
<ServerScope>
<SessionDetail />
</ServerScope>
),
loader: protectedLoader,
element: <AppShell />,
errorElement: <RouteErrorBoundary />,
children: [
{
path: '/',
element: <Repos />,
loader: protectedLoader,
},
{
path: '/assistant',
element: <AssistantRedirect />,
loader: protectedLoader,
},
{
path: '/repos/:id',
element: <RepoDetail />,
loader: protectedLoader,
},
{
path: '/repos/:id/assistant',
element: <AssistantRedirect />,
loader: protectedLoader,
},
{
path: '/repos/:id/sessions/:sessionId',
element: <SessionDetail />,
loader: protectedLoader,
},
{
path: '/repos/:id/schedules',
element: <Schedules />,
loader: protectedLoader,
},
{
path: '/schedules',
element: <GlobalSchedules />,
loader: protectedLoader,
},
{
path: '/servers/:serverId',
element: <LinkedServerRedirect />,
loader: protectedLoader,
},
{
path: '/servers/:serverId/projects',
element: (
<ServerScope>
<RemoteProject />
</ServerScope>
),
loader: protectedLoader,
},
{
path: '/servers/:serverId/sessions/:sessionId',
element: (
<ServerScope>
<SessionDetail />
</ServerScope>
),
loader: protectedLoader,
},
{
path: '*',
element: (
<NotFoundState
title="Page Not Found"
message="The page you are looking for does not exist."
backTo="/"
backLabel="Go home"
/>
),
loader: protectedLoader,
},
],
},
],
},
@@ -350,11 +377,9 @@ const router = createBrowserRouter([
function App() {
return (
<QueryClientProvider client={queryClient}>
<TTSProvider>
<SwipeNavigationProvider>
<RouterProvider router={router} />
</SwipeNavigationProvider>
</TTSProvider>
<SwipeNavigationProvider>
<RouterProvider router={router} />
</SwipeNavigationProvider>
</QueryClientProvider>
)
}
+7
View File
@@ -12,6 +12,13 @@ function walkthroughUrl(sessionId: string): string {
return `${API_BASE_URL}/api/change-walkthroughs/${encodeURIComponent(sessionId)}`
}
const HELPER_SESSIONS_URL = `${API_BASE_URL}/api/change-walkthroughs/helper-sessions`
export async function getWalkthroughHelperSessionIds(): Promise<string[]> {
const response = await fetchWrapper<{ sessionIds: string[] }>(HELPER_SESSIONS_URL)
return response.sessionIds
}
export async function getChangeWalkthrough(
sessionId: string,
source: WalkthroughSource,
+1
View File
@@ -42,6 +42,7 @@ export async function getRepo(id: number): Promise<Repo> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`)
}
export function workspaceLabel(workspace: RepoSibling): string {
return workspace.currentBranch || workspace.branch || workspace.localPath || 'worktree'
}
@@ -615,7 +615,7 @@ useEffect(() => {
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={handleRefresh}>
<Button variant="outline" size="sm" aria-label="Refresh files" onClick={handleRefresh}>
<RefreshCw className="w-4 h-4" />
</Button>
<FileOperations
@@ -705,7 +705,7 @@ useEffect(() => {
<FolderOpen className="w-5 h-5" />
File Browser
</CardTitle>
<Button variant="outline" size="sm" onClick={handleRefresh}>
<Button variant="outline" size="sm" aria-label="Refresh files" onClick={handleRefresh}>
<RefreshCw className="w-4 h-4" />
</Button>
</div>
@@ -117,6 +117,7 @@ export function FileDiffContent({
size="sm"
onClick={onBack}
className="h-7 w-7 p-0 mr-1"
aria-label="Back to file list"
>
<ArrowLeft className="w-4 h-4" />
</Button>
@@ -57,7 +57,7 @@ export const FileOperations = memo(function FileOperations({ onUpload, onCreate
{isMobile ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<Button variant="outline" size="sm" aria-label="Upload files">
<Upload className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
@@ -73,7 +73,7 @@ export const FileOperations = memo(function FileOperations({ onUpload, onCreate
</DropdownMenuContent>
</DropdownMenu>
) : (
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
<Button variant="outline" size="sm" aria-label="Upload files" onClick={() => fileInputRef.current?.click()}>
<Upload className="w-4 h-4" />
<span className="hidden sm:inline ml-1">Upload</span>
</Button>
@@ -81,7 +81,7 @@ export const FileOperations = memo(function FileOperations({ onUpload, onCreate
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm">
<Button variant="outline" size="sm" aria-label="Create file or folder">
<Plus className="w-4 h-4" />
</Button>
</DialogTrigger>
@@ -105,6 +105,14 @@ describe('FilePreview header buttons', () => {
expect(external).toHaveAttribute('rel', 'noopener noreferrer')
})
it('shows the binary message and no edit action for non-text files', () => {
render(<FilePreview file={{ ...textFile('blob.bin', 'application/octet-stream'), content: btoa('\u0000\u0001\u0002') }} />)
expect(screen.getByText('Binary file - download to view content')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Edit file' })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Download file' })).toBeInTheDocument()
})
it('keeps the success and destructive tints on the edit actions in dark mode', () => {
render(<FilePreview file={textFile('Dockerfile', 'text/plain')} />)
@@ -426,25 +426,25 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
)}
{isTextFile && viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleEdit() }} className="h-7 w-7 p-0">
<Button variant="outline" size="sm" aria-label="Edit file" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleEdit() }} className="h-7 w-7 p-0">
<Edit3 className="w-3 h-3" />
</Button>
)}
{showSaveButton && (
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); if (shouldVirtualize) { handleVirtualizedSaveClick(); } else { handleSave(); } }} disabled={isSaving || (shouldVirtualize && !hasVirtualizedChanges)} className={SUCCESS_TINT_BUTTON_CLASS}>
<Button variant="ghost" size="sm" aria-label="Save file" onClick={(e) => { e.stopPropagation(); e.preventDefault(); if (shouldVirtualize) { handleVirtualizedSaveClick(); } else { handleSave(); } }} disabled={isSaving || (shouldVirtualize && !hasVirtualizedChanges)} className={SUCCESS_TINT_BUTTON_CLASS}>
<Save className="w-3 h-3" />
</Button>
)}
{showCancelButton && (
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleCancel() }} className={DESTRUCTIVE_TINT_BUTTON_CLASS}>
<Button variant="ghost" size="sm" aria-label="Cancel editing" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleCancel() }} className={DESTRUCTIVE_TINT_BUTTON_CLASS}>
<XIcon className="w-3 h-3" />
</Button>
)}
{viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleDownload() }} className="h-7 w-7 p-0">
<Button variant="outline" size="sm" aria-label="Download file" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleDownload() }} className="h-7 w-7 p-0">
<Download className="w-3 h-3" />
</Button>
)}
@@ -0,0 +1,31 @@
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import type { FileInfo } from '@/types/files'
import { FileTree } from './FileTree'
const file: FileInfo = {
name: 'notes.txt',
path: 'docker/notes.txt',
isDirectory: false,
size: 5,
mimeType: 'text/plain',
content: '',
lastModified: new Date('2026-07-28T09:12:40Z'),
}
describe('FileTree row actions', () => {
it('names the per-row actions trigger after the file', () => {
render(
<FileTree
files={[file]}
onFileSelect={vi.fn()}
onDirectoryClick={vi.fn()}
selectedFile={null}
onDelete={vi.fn()}
onRename={vi.fn()}
/>,
)
expect(screen.getByRole('button', { name: 'Actions for notes.txt' })).toBeInTheDocument()
})
})
@@ -181,7 +181,8 @@ function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, o
<Button
variant="ghost"
size="sm"
className={`w-6 h-6 p-0 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}
aria-label={`Actions for ${file.name}`}
className={`w-6 h-6 p-0 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100'}`}
>
<MoreVertical className="w-3 h-3" />
</Button>
@@ -0,0 +1,85 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import type { SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { ExplorationGroup } from './ExplorationGroup'
const mocks = vi.hoisted(() => ({
useSettings: vi.fn(),
useToolCallPermission: vi.fn(),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: mocks.useSettings,
}))
vi.mock('@/contexts/EventContext', () => ({
useToolCallPermission: mocks.useToolCallPermission,
}))
const readTool = (id: string, status: 'completed' | 'running' | 'error'): SessionMessageAssistantTool => {
if (status === 'completed') {
return {
type: 'tool',
id,
name: 'read',
state: { status, input: { filePath: '/repo/a.ts' }, content: [], metadata: {} },
time: { created: 0, ran: 1, completed: 2 },
}
}
if (status === 'error') {
return {
type: 'tool',
id,
name: 'read',
state: { status, input: { filePath: '/repo/missing.ts' }, error: { type: 'tool.failed', message: 'File not found' }, metadata: {} },
time: { created: 0, ran: 1, completed: 2 },
}
}
return {
type: 'tool',
id,
name: 'read',
state: { status, input: { filePath: '/repo/a.ts' } },
time: { created: 0, ran: 1 },
}
}
describe('ExplorationGroup', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
isLoading: false,
updateSettings: vi.fn(),
isUpdating: false,
})
mocks.useToolCallPermission.mockReturnValue(null)
})
it('summarises a successful run and keeps the arrow marker', () => {
render(<ExplorationGroup parts={[readTool('r1', 'completed'), readTool('r2', 'completed')]} messageID="msg_1" />)
const summary = screen.getByRole('button', { name: /Explored: 2 reads/ })
expect(summary).toHaveTextContent('→')
expect(summary).not.toHaveTextContent('✗')
})
it('marks a run with a failed member and counts it in the label', () => {
render(<ExplorationGroup parts={[readTool('r1', 'completed'), readTool('r2', 'error')]} messageID="msg_1" />)
const summary = screen.getByRole('button', { name: /Explored: 2 reads, 1 failed/ })
const marker = screen.getByText('✗')
expect(marker).toHaveClass('text-destructive')
expect(summary).not.toHaveTextContent('→')
})
it('keeps the spinner while an exploration run is still in progress', () => {
const { container } = render(
<ExplorationGroup parts={[readTool('r1', 'error'), readTool('r2', 'running')]} messageID="msg_1" />,
)
expect(screen.getByRole('button', { name: /Exploring: 2 reads/ })).toBeInTheDocument()
expect(screen.queryByText('✗')).not.toBeInTheDocument()
expect(container.querySelector('.animate-spin')).not.toBeNull()
})
})
@@ -3,7 +3,7 @@ import { ChevronRight, Loader2 } from 'lucide-react'
import type { SessionMessageAssistantTool } from '@opencode-manager/shared/opencode'
import { useSettings } from '@/hooks/useSettings'
import { useToolCallPermission } from '@/contexts/EventContext'
import { explorationLabel, isExplorationComplete } from '@/lib/explorationGroups'
import { explorationFailureCount, explorationLabel, isExplorationComplete } from '@/lib/explorationGroups'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import { MessagePart } from './MessagePart'
@@ -31,6 +31,7 @@ export const ExplorationGroup = memo(function ExplorationGroup({ parts, ...membe
const { preferences } = useSettings()
const [expanded, setExpanded] = useState(preferences?.expandToolCalls ?? false)
const completed = isExplorationComplete(parts)
const failed = completed && explorationFailureCount(parts) > 0
return (
<div className="my-1">
@@ -40,7 +41,13 @@ export const ExplorationGroup = memo(function ExplorationGroup({ parts, ...membe
aria-expanded={expanded}
className="group flex w-full min-w-0 items-center gap-2 py-0.5 text-left text-sm text-muted-foreground hover:text-foreground transition-colors"
>
{completed ? <span className="shrink-0">→</span> : <Loader2 className="w-3.5 h-3.5 shrink-0 animate-spin" />}
{failed ? (
<span className="shrink-0 text-destructive">✗</span>
) : completed ? (
<span className="shrink-0">→</span>
) : (
<Loader2 className="w-3.5 h-3.5 shrink-0 animate-spin" />
)}
<span className="truncate">{explorationLabel(parts)}</span>
<ChevronRight className={`w-3.5 h-3.5 shrink-0 opacity-0 group-hover:opacity-100 transition-transform ${expanded ? 'rotate-90 opacity-100' : ''}`} />
</button>
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput, type PromptInputHandle } from './PromptInput'
import { useComposerDraftStore } from '@/stores/composerDraftStore'
import { BUILTIN_COMMANDS } from '@/lib/builtinCommands'
import { createCommandActionsMock, stubMatchMedia, createVoiceConversationControllerMock } from '@/test/test-utils'
@@ -174,6 +175,7 @@ describe('PromptInput command submission', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.runCommand.mockResolvedValue(undefined)
mocks.switchSessionModel.mockResolvedValue(undefined)
@@ -496,7 +498,7 @@ describe('PromptInput command submission', () => {
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
})
it('clears attachments and exits bash mode on Escape while idle', async () => {
it('exits bash mode on Escape while idle and keeps the attachments', async () => {
const { container } = renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
@@ -510,7 +512,7 @@ describe('PromptInput command submission', () => {
expect(input).toHaveValue('')
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
expect(screen.queryByText('pic.png')).not.toBeInTheDocument()
expect(screen.getByText('pic.png')).toBeInTheDocument()
})
it('keeps attachments and clears only the text when a built-in command is submitted', async () => {
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor, within, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useComposerDraftStore } from '@/stores/composerDraftStore'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
@@ -116,6 +117,7 @@ describe('PromptInput composer layout', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.hasPendingPermission.mockReturnValue(false)
mocks.useMobile.mockReturnValue(false)
@@ -0,0 +1,258 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useComposerDraftStore } from '@/stores/composerDraftStore'
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
useSTT: vi.fn(),
useVoiceConversation: vi.fn(),
useMobile: vi.fn(),
useCommands: vi.fn(),
useCommandHandler: vi.fn(),
useFileSearch: vi.fn(),
useModelSelection: vi.fn(),
useVariants: vi.fn(),
useSessionAgent: vi.fn(),
useUserBash: vi.fn(),
useSessionAgentStore: vi.fn(),
useSendErrorStore: vi.fn(),
useHasBackgroundActivity: vi.fn(),
useSendPrompt: vi.fn(),
hasPendingPermission: vi.fn(() => false),
setShowDialog: vi.fn(),
}))
vi.mock('@/hooks/useSTT', () => ({
useSTT: mocks.useSTT,
useSttAvailability: () => ({ isEnabled: true, isSupported: true }),
}))
vi.mock('@/hooks/useVoiceConversation', () => ({ useVoiceConversation: mocks.useVoiceConversation }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile }))
vi.mock('@/hooks/useCommands', () => ({ useCommands: mocks.useCommands }))
vi.mock('@/hooks/useCommandHandler', () => ({ useCommandHandler: mocks.useCommandHandler }))
vi.mock('@/hooks/useFileSearch', () => ({ useFileSearch: mocks.useFileSearch }))
vi.mock('@/hooks/useModelSelection', () => ({ useModelSelection: mocks.useModelSelection }))
vi.mock('@/hooks/useVariants', () => ({ useVariants: mocks.useVariants }))
vi.mock('@/hooks/useSessionAgent', () => ({ useSessionAgent: mocks.useSessionAgent }))
vi.mock('@/stores/userBashStore', () => ({ useUserBash: mocks.useUserBash }))
vi.mock('@/stores/sessionAgentStore', () => ({ useSessionAgentStore: mocks.useSessionAgentStore }))
vi.mock('@/stores/sendErrorStore', () => ({ useSendErrorStore: mocks.useSendErrorStore }))
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/stores/sessionStatusStore')>()
return { ...actual, useHasBackgroundActivity: mocks.useHasBackgroundActivity }
})
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), loading: vi.fn(), promise: vi.fn(), dismiss: vi.fn() },
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSendPrompt: () => ({ mutate: mocks.useSendPrompt, isPending: false }),
useInterruptSession: () => ({ mutate: vi.fn() }),
useSendShell: () => ({ mutate: vi.fn(), isPending: false }),
useAgents: () => ({ data: [] }),
useSkills: () => ({ data: [] }),
}))
vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ data: undefined }) }))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({
hasForSession: mocks.hasPendingPermission,
setShowDialog: mocks.setShowDialog,
}),
}))
vi.mock('@/components/agent/AgentQuickSelect', () => ({
AgentQuickSelect: () => <div data-testid="agent-quick-select" />,
}))
vi.mock('@/components/model/ModelQuickSelect', () => ({
ModelQuickSelect: ({ children }: { children?: React.ReactNode }) => (
<div data-testid="model-quick-select">{children}</div>
),
}))
vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: () => null }))
vi.mock('@/components/session/SessionSandboxMenu', () => ({ SessionSandboxMenu: () => null }))
vi.mock('./ComposerToolsMenu', () => ({ ComposerToolsMenu: () => null }))
vi.mock('./PromptSuggestions', () => ({ PromptSuggestions: () => null }))
vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useSessionPermissionMode', () => ({ useSessionPermissionMode: () => ({ data: undefined }) }))
const createTestQueryClient = () => new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
const defaultProps = {
directory: '/test',
sessionID: 'session-a',
showScrollButton: false,
isSessionActive: false,
isStreamingResponse: false,
onScrollToBottom: vi.fn(),
commandActions: createCommandActionsMock(),
onPromptChange: vi.fn(),
}
describe('PromptInput per-session composer draft', () => {
const harness = (sessionID: string, overrides: Partial<typeof defaultProps> = {}) => (
<QueryClientProvider client={createTestQueryClient()}>
<PromptInput key={sessionID} {...defaultProps} {...overrides} sessionID={sessionID} />
</QueryClientProvider>
)
const renderSession = (sessionID: string, overrides: Partial<typeof defaultProps> = {}) =>
render(harness(sessionID, overrides))
const promptInput = () => screen.getByPlaceholderText(/Send a message\.\.\.|Enter bash command\.\.\./)
const attachImage = async (container: HTMLElement) => {
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement
fireEvent.change(fileInput, { target: { files: [new File(['img'], 'pic.png', { type: 'image/png' })] } })
await screen.findByText('pic.png')
}
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useSendPrompt.mockImplementation((_variables, options) => {
options?.onSuccess?.()
})
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.hasPendingPermission.mockReturnValue(false)
mocks.useMobile.mockReturnValue(false)
mocks.useSTT.mockReturnValue({
isRecording: false,
isProcessing: false,
isSupported: false,
isEnabled: false,
interimTranscript: '',
transcript: '',
startRecording: vi.fn(),
stopRecording: vi.fn(),
abortRecording: vi.fn(),
reset: vi.fn(),
clear: vi.fn(),
})
mocks.useCommands.mockReturnValue({ searchCommands: () => [], findCommand: () => undefined, recentNames: [] })
mocks.useCommandHandler.mockReturnValue({ executeCommand: vi.fn() })
mocks.useFileSearch.mockReturnValue({ files: [] })
mocks.useModelSelection.mockReturnValue({
model: null,
modelString: 'test-model',
setModel: vi.fn(),
setActiveAgent: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelReady: true,
})
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: vi.fn() })
mocks.useSessionAgent.mockReturnValue({ agent: 'default' })
mocks.useUserBash.mockImplementation((selector: (state: unknown) => unknown) => selector({ addUserBashCommand: vi.fn() }))
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
mocks.useHasBackgroundActivity.mockReturnValue(false)
})
it('keeps the typed draft of each session', () => {
const { rerender } = renderSession('session-a')
fireEvent.change(promptInput(), { target: { value: 'draft for A' } })
rerender(harness('session-b'))
expect(promptInput()).toHaveValue('')
fireEvent.change(promptInput(), { target: { value: 'draft for B' } })
rerender(harness('session-a'))
expect(promptInput()).toHaveValue('draft for A')
rerender(harness('session-b'))
expect(promptInput()).toHaveValue('draft for B')
})
it('keeps bash mode and attachments of each session', async () => {
const { container, rerender } = renderSession('session-a')
fireEvent.change(promptInput(), { target: { value: '!' } })
await attachImage(container)
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
rerender(harness('session-b'))
expect(promptInput()).toHaveValue('')
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
expect(screen.queryByText('pic.png')).not.toBeInTheDocument()
rerender(harness('session-a'))
expect(promptInput()).toHaveValue('!')
expect(screen.getByPlaceholderText('Enter bash command...')).toBeInTheDocument()
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
expect(screen.getByText('pic.png')).toBeInTheDocument()
})
it('sends the restored draft to the session that owns it and clears only that draft', () => {
const { rerender } = renderSession('session-a')
fireEvent.change(promptInput(), { target: { value: 'draft for A' } })
rerender(harness('session-b'))
fireEvent.change(promptInput(), { target: { value: 'draft for B' } })
rerender(harness('session-a'))
fireEvent.click(screen.getByTitle('Send'))
expect(mocks.useSendPrompt).toHaveBeenCalledWith(
expect.objectContaining({ sessionID: 'session-a', text: 'draft for A' }),
expect.anything(),
)
expect(promptInput()).toHaveValue('')
rerender(harness('session-b'))
expect(promptInput()).toHaveValue('draft for B')
})
it('keeps the draft when Escape is pressed while the session is idle', () => {
renderSession('session-a')
fireEvent.change(promptInput(), { target: { value: 'an important draft' } })
fireEvent.keyDown(promptInput(), { key: 'Escape' })
expect(promptInput()).toHaveValue('an important draft')
})
it('reports suggestion list changes instead of clearing on Escape', async () => {
const onSuggestionsOpenChange = vi.fn()
mocks.useCommands.mockReturnValue({
searchCommands: () => [{ item: { name: 'alpha', description: 'Alpha' }, ranges: [] }],
findCommand: () => undefined,
recentNames: [],
})
renderSession('session-a', { onSuggestionsOpenChange })
expect(onSuggestionsOpenChange).toHaveBeenLastCalledWith(false)
fireEvent.change(promptInput(), { target: { value: '/al', selectionStart: 3 } })
await waitFor(() => expect(onSuggestionsOpenChange).toHaveBeenLastCalledWith(true))
expect(promptInput()).toHaveValue('/al')
fireEvent.keyDown(promptInput(), { key: 'Escape' })
await waitFor(() => expect(onSuggestionsOpenChange).toHaveBeenLastCalledWith(false))
expect(promptInput()).toHaveValue('/al')
})
it('labels the attachment remove button with the filename', async () => {
const { container } = renderSession('session-a')
await attachImage(container)
expect(screen.getByRole('button', { name: 'Remove pic.png' })).toBeInTheDocument()
})
})
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
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'
import { createCommandActionsMock, stubMatchMedia, createVoiceConversationControllerMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
@@ -164,6 +165,7 @@ describe('PromptInput goal mode', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.useSessionGoal.mockReturnValue({ data: null })
mocks.useSessionPermissionMode.mockReturnValue({ data: undefined })
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useComposerDraftStore } from '@/stores/composerDraftStore'
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
const mocks = vi.hoisted(() => ({
@@ -9,7 +10,7 @@ const mocks = vi.hoisted(() => ({
switchSessionModel: vi.fn(),
switchSessionAgent: vi.fn(),
runCommand: vi.fn(),
agents: [] as Array<{ name: string; description?: string }>,
agents: [] as Array<{ name: string; description?: string; mode?: string; hidden?: boolean }>,
skills: [] as Array<{ id: string; name: string; description?: string }>,
useSTT: vi.fn(),
useVoiceConversation: vi.fn(),
@@ -24,7 +25,7 @@ const mocks = vi.hoisted(() => ({
useSendErrorStore: vi.fn(),
}))
const suggestionProps = vi.hoisted(() => ({ isOpen: false, selectedIndex: 0 }))
const suggestionProps = vi.hoisted(() => ({ isOpen: false, selectedIndex: 0, labels: [] as string[] }))
vi.mock('@/api/opencode', async () => {
const actual = await vi.importActual('@/api/opencode')
@@ -95,10 +96,11 @@ vi.mock('@/hooks/useSessionPermissionMode', () => ({
}))
vi.mock('./PromptSuggestions', () => ({
PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number }) => {
PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number; items: Array<{ label: string }> }) => {
if (props.isOpen) {
suggestionProps.isOpen = true
suggestionProps.selectedIndex = props.selectedIndex
suggestionProps.labels = props.items.map((item) => item.label)
}
return null
},
@@ -153,6 +155,7 @@ describe('PromptInput agent mention submission', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useVoiceConversation.mockReturnValue(createVoiceConversationControllerMock())
mocks.sendPrompt.mockResolvedValue({
id: 'inbox_1',
@@ -199,6 +202,7 @@ describe('PromptInput agent mention submission', () => {
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
suggestionProps.isOpen = false
suggestionProps.selectedIndex = 0
suggestionProps.labels = []
})
it('sends an @agent mention as an attachment without switching the session agent', async () => {
@@ -311,4 +315,23 @@ describe('PromptInput agent mention submission', () => {
fireEvent.keyDown(input, { key: 'ArrowDown' })
await waitFor(() => expect(suggestionProps.selectedIndex).toBe(1))
})
it('offers only mentionable subagents in the @ list', async () => {
mocks.agents = [
{ name: 'build', description: 'Build', mode: 'primary', hidden: false },
{ name: 'plan', description: 'Plan', mode: 'primary', hidden: false },
{ name: 'explore', description: 'Explore', mode: 'subagent', hidden: false },
{ name: 'general', description: 'General', mode: 'all', hidden: false },
{ name: 'Compaction', description: 'Compaction', mode: 'primary', hidden: true },
{ name: 'Title', description: 'Title', mode: 'primary', hidden: true },
]
mocks.skills = []
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '@', selectionStart: 1 } })
await waitFor(() => expect(suggestionProps.isOpen).toBe(true))
expect(suggestionProps.labels).toEqual(['explore', 'general'])
})
})
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { PromptInput } from './PromptInput'
import { useComposerDraftStore } from '@/stores/composerDraftStore'
import {
SessionTranscriptContext,
type SessionTranscriptSnapshot,
@@ -220,6 +221,7 @@ describe('PromptInput voice conversation', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useSendPromptMutate.mockImplementation((_variables, options) => {
options?.onSuccess?.()
})
@@ -423,6 +425,7 @@ describe('PromptInput submission', () => {
beforeEach(() => {
vi.clearAllMocks()
useComposerDraftStore.setState({ drafts: {} })
mocks.useSendPromptMutate.mockImplementation((_variables, options) => {
options?.onSuccess?.()
})
+37 -10
View File
@@ -11,6 +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 { useRecentCommandsStore } from '@/stores/recentCommandsStore'
import { useHasBackgroundActivity } from '@/stores/sessionStatusStore'
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
@@ -119,6 +120,7 @@ interface PromptInputProps {
directory?: string
sessionID: string
onVoiceConversationActiveChange?: (active: boolean) => void
onSuggestionsOpenChange?: (open: boolean) => void
showScrollButton?: boolean
isSessionActive?: boolean
isStreamingResponse?: boolean
@@ -131,6 +133,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
directory,
sessionID,
onVoiceConversationActiveChange,
onSuggestionsOpenChange,
showScrollButton,
isSessionActive = false,
isStreamingResponse = false,
@@ -138,13 +141,14 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
commandActions,
onPromptChange
}, ref) {
const [prompt, setPrompt] = useState('')
const [isBashMode, setIsBashMode] = useState(false)
const [restoredDraft] = useState(() => useComposerDraftStore.getState().getDraft(sessionID))
const [prompt, setPrompt] = useState(restoredDraft.prompt)
const [isBashMode, setIsBashMode] = useState(restoredDraft.isBashMode)
const [isGoalArmed, setIsGoalArmed] = useState(false)
const [showSuggestions, setShowSuggestions] = useState(false)
const [suggestionQuery, setSuggestionQuery] = useState('')
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileAttachmentInfo>())
const [imageAttachments, setImageAttachments] = useState<ImageAttachment[]>([])
const [attachedFiles, setAttachedFiles] = useState(restoredDraft.attachedFiles)
const [imageAttachments, setImageAttachments] = useState(restoredDraft.imageAttachments)
const [isDragging, setIsDragging] = useState(false)
const [isModelPickerOpen, setIsModelPickerOpen] = useState(false)
const [showMentionSuggestions, setShowMentionSuggestions] = useState(false)
@@ -183,6 +187,17 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
imageAttachmentsRef.current = imageAttachments
}, [attachedFiles, imageAttachments, prompt])
const saveDraft = useComposerDraftStore((state) => state.saveDraft)
const clearDraft = useComposerDraftStore((state) => state.clearDraft)
useEffect(() => {
if (prompt === '' && !isBashMode && attachedFiles.size === 0 && imageAttachments.length === 0) {
clearDraft(sessionID)
return
}
saveDraft(sessionID, { prompt, isBashMode, attachedFiles, imageAttachments })
}, [sessionID, prompt, isBashMode, attachedFiles, imageAttachments, saveDraft, clearDraft])
const clearSubmittedPrompt = useCallback((submittedPrompt: string, submittedAttachedFiles: Map<string, FileAttachmentInfo>, submittedImageAttachments: ImageAttachment[], options?: { keepAttachments?: boolean }) => {
if (
promptRef.current !== submittedPrompt ||
@@ -246,6 +261,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const { data: agents = [] } = useAgents(directory)
const { data: skills = [] } = useSkills(directory)
const mentionableAgents = useMemo(
() => agents.filter((agent) => !agent.hidden && agent.mode !== 'primary'),
[agents],
)
const agentNames = useMemo(() => agents.map((agent) => agent.name), [agents])
const skillIds = useMemo(() => skills.map((skill) => skill.id), [skills])
const failedPrompt = useSendErrorStore((state) => state.errors[sessionID]?.failedPrompt)
@@ -269,7 +288,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}, [failedPrompt])
const mentionSuggestions = useMemo((): PromptSuggestion<MentionItem>[] => {
const agentMatches = rankByMatch(agents, mentionQuery, {
const agentMatches = rankByMatch(mentionableAgents, mentionQuery, {
getName: (agent) => agent.name,
getDescription: (agent) => agent.description,
}).map(({ item, tier, ranges }) => ({
@@ -321,7 +340,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
return [...agentMatches, ...skillMatches, ...fileMatches]
.sort((a, b) => a.tier - b.tier)
.map(({ suggestion }) => suggestion)
}, [agents, skills, searchResults, mentionQuery])
}, [mentionableAgents, skills, searchResults, mentionQuery])
const commandSuggestions = useMemo((): PromptSuggestion<CommandInfo>[] =>
searchCommands(suggestionQuery).map(({ item, ranges }) => ({
@@ -735,7 +754,10 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (isBashMode && e.key === 'Escape') {
e.preventDefault()
resetPrompt()
if (prompt === '!' || prompt === '') {
setIsBashMode(false)
setPrompt('')
}
return
}
@@ -815,8 +837,6 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
textareaRef.current?.blur()
}
handleSubmit()
} else if (e.key === 'Escape' && !isSessionActive) {
resetPrompt()
}
}
@@ -1063,6 +1083,12 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
})
const isCommandListOpen = showSuggestions && commandSuggestions.length > 0
const isMentionListOpen = showMentionSuggestions && mentionSuggestions.length > 0
const isSuggestionListOpen = isCommandListOpen || isMentionListOpen
useEffect(() => {
onSuggestionsOpenChange?.(isSuggestionListOpen)
}, [isSuggestionListOpen, onSuggestionsOpenChange])
const composerMode: ComposerMode | null = isBashMode
? 'bash'
: isMentionListOpen
@@ -1071,7 +1097,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
? 'command'
: null
const composerModeStyle = composerMode ? COMPOSER_MODE_STYLES[composerMode] : null
const isTakeoverOpen = isMobile && (isCommandListOpen || isMentionListOpen)
const isTakeoverOpen = isMobile && isSuggestionListOpen
const showStopButton = isSessionActive
const showMobileScrollButton = isMobile && showScrollButton
const hasOpenGoal = isOpenSessionGoal(sessionGoal)
@@ -1279,6 +1305,7 @@ return (
<span className="max-w-[120px] truncate">{attachment.filename}</span>
<button
type="button"
aria-label={`Remove ${attachment.filename}`}
onClick={() => removeImageAttachment(attachment.id)}
className="p-0.5 rounded hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground"
>
@@ -0,0 +1,15 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { TextPart } from './TextPart'
describe('TextPart code blocks', () => {
it('reserves room for the copy button so the first code line is not covered', () => {
const { container } = render(<TextPart text={'```ts\nconst answer = 42\n```'} />)
const pre = container.querySelector('pre')
expect(pre).not.toBeNull()
expect(pre).toHaveClass('pr-10')
expect(screen.getByTitle('Copy code')).toBeInTheDocument()
expect(pre?.textContent).toContain('const answer = 42')
})
})
+1 -1
View File
@@ -167,7 +167,7 @@ function CodeBlock({ children, className, ...props }: CodeBlockProps) {
return (
<div className="relative">
<pre className={`bg-accent p-1 rounded-lg overflow-x-auto whitespace-pre-wrap break-words border border-border my-4 ${className || ''}`} {...props}>
<pre className={`bg-accent py-1 pl-1 pr-10 rounded-lg overflow-x-auto whitespace-pre-wrap break-words border border-border my-4 ${className || ''}`} {...props}>
{children}
</pre>
<CopyButton content={codeContent} title="Copy code" className="absolute top-2 right-2" />
@@ -292,6 +292,78 @@ describe('ToolCallPart background indicator', () => {
})
})
describe('ToolCallPart shell exit status', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
isLoading: false,
updateSettings: vi.fn(),
isUpdating: false,
})
mocks.useToolCallPermission.mockReturnValue(null)
useUserBash.setState({ userBashCommands: new Map() })
})
const completedShell = (metadata: Record<string, unknown>): SessionMessageAssistantTool => ({
type: 'tool',
id: 'call_exit',
name: 'shell',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { command: 'cat does-not-exist.txt' },
content: [{ type: 'text', text: 'Exited with code 1' }],
metadata,
},
})
it('marks a completed shell with a non-zero exit as failed', () => {
renderWithProviders(<ToolCallPart part={completedShell({ exit: 1 })} messageID="msg_1" />)
expect(screen.getByText('exit 1')).toBeInTheDocument()
expect(screen.queryByText('completed')).not.toBeInTheDocument()
expect(screen.getByText('✗').parentElement).toHaveClass('text-destructive')
})
it('keeps a completed shell with exit code zero successful', () => {
renderWithProviders(<ToolCallPart part={completedShell({ exit: 0 })} messageID="msg_1" />)
expect(screen.getByText('completed')).toBeInTheDocument()
expect(screen.getByText('✓').parentElement).toHaveClass('text-success')
expect(screen.queryByText('✗')).not.toBeInTheDocument()
})
it('keeps a completed shell without an exit code successful', () => {
renderWithProviders(<ToolCallPart part={completedShell({})} messageID="msg_1" />)
expect(screen.getByText('completed')).toBeInTheDocument()
})
it('does not read an exit code from a non-shell tool', () => {
renderWithProviders(
<ToolCallPart
part={{
type: 'tool',
id: 'call_fetch',
name: 'webfetch',
time: { created: 1, ran: 2, completed: 3 },
state: {
status: 'completed',
input: { url: 'https://example.com' },
content: [{ type: 'text', text: 'ok' }],
metadata: { exit: 1 },
},
}}
messageID="msg_1"
/>,
)
expect(screen.getByText('completed')).toBeInTheDocument()
expect(screen.queryByText('✗')).not.toBeInTheDocument()
})
})
describe('ToolCallPart execute renderer', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -121,6 +121,12 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
return typeof provider === 'string' ? provider : undefined
})()
const sandboxProviderLabel = sandboxProvider !== undefined && sandboxProvider !== 'ocm' ? sandboxProvider : undefined
const foregroundShellExit =
part.name === 'shell' && !isBackgroundShell && part.state.status === 'completed'
? toolMetadata(part).exit
: undefined
const failedShellExit =
typeof foregroundShellExit === 'number' && foregroundShellExit !== 0 ? foregroundShellExit : undefined
const [detailsOpen, setDetailsOpen] = useToolDetailsState(preferences?.expandToolCalls ?? false)
useEffect(() => {
@@ -132,6 +138,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
const getStatusColor = () => {
if (isBackgroundShell) return backgroundTaskStatusColor(shellStatus)
if (failedShellExit !== undefined) return 'text-destructive'
switch (part.state.status) {
case 'completed':
return 'text-success'
@@ -151,6 +158,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
const getStatusIcon = () => {
if (isBackgroundShell) return renderShellLifecycleIcon(shellStatus)
if (failedShellExit !== undefined) return <span>✗</span>
switch (part.state.status) {
case 'completed':
return <span>✓</span>
@@ -294,7 +302,9 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
? 'awaiting permission'
: isBackgroundShell
? lifecycleLabel(shellStatus)
: part.state.status
: failedShellExit !== undefined
? `exit ${failedShellExit}`
: part.state.status
const commandBlock = (
<div className="text-sm">
<div className="flex items-center gap-2 mb-1">
@@ -188,6 +188,22 @@ describe('VoiceConversationBar', () => {
expect(screen.getByRole('button', { name: 'Sending' })).toHaveAttribute('aria-busy', 'true')
})
it('shows the failure reason and its fix instead of a bare retry', () => {
renderBar(
buildController({
phase: 'paused',
label: 'Microphone access denied. Please allow microphone permissions.',
hint: 'Allow microphone access, then tap to retry',
orbLabel: 'Resume voice conversation',
}),
)
expect(
screen.getByText('Microphone access denied. Please allow microphone permissions.'),
).toBeInTheDocument()
expect(screen.getByText('Allow microphone access, then tap to retry')).toBeInTheDocument()
})
it('shows the notice when there is one and keeps the reserved hint line empty', () => {
renderBar(
buildController({
@@ -74,7 +74,14 @@ export function VoiceConversationBar({
return (
<div className="flex flex-col gap-1 border-t border-border bg-card px-3 pt-2 pb-2">
<div role="status" aria-live="polite" className="flex h-5 items-center gap-2">
<span className="max-w-[50%] shrink-0 truncate text-xs font-semibold">{label}</span>
<span
className={cn(
'truncate text-xs font-semibold',
liveTranscript ? 'max-w-[50%] shrink-0' : 'min-w-0 flex-1',
)}
>
{label}
</span>
{liveTranscript ? (
<span
dir="rtl"
@@ -593,7 +593,7 @@ export function ModelQuickSelect({
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder="Search models..."
className="h-9 border-border bg-muted pl-9 text-sm text-foreground placeholder:text-muted-foreground"
className="h-9 border-border bg-muted pl-9 text-sm text-foreground placeholder:text-placeholder"
autoComplete="off"
name="model-search"
/>
@@ -16,6 +16,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { MobileTabBar } from './MobileTabBar'
import { useMobile } from '@/hooks/useMobile'
import { useUnreadScheduleRuns } from '@/hooks/useSchedules'
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
function LocationSpy() {
@@ -27,6 +28,9 @@ describe('MobileTabBar', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.clear()
vi.mocked(useUnreadScheduleRuns).mockReturnValue(
{ data: undefined } as unknown as ReturnType<typeof useUnreadScheduleRuns>,
)
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
})
@@ -420,4 +424,43 @@ describe('MobileTabBar', () => {
expect(container.firstChild).toBeNull()
})
it('shows the unread schedule indicator on More when the Schedules tab is replaced by Git', () => {
vi.mocked(useMobile).mockReturnValue(true)
vi.mocked(useUnreadScheduleRuns).mockReturnValue({
data: { total: 2, runs: [] },
} as unknown as ReturnType<typeof useUnreadScheduleRuns>)
const queryClient = new QueryClient()
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/123']}>
<MobileTabBar />
</MemoryRouter>
</QueryClientProvider>,
)
expect(screen.queryByText('Schedules')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'More' }).querySelector('[data-unread-badge]')).not.toBeNull()
expect(screen.getByRole('button', { name: 'Git' }).querySelector('[data-unread-badge]')).toBeNull()
})
it('keeps the unread schedule indicator on Schedules and off More when that tab is shown', () => {
vi.mocked(useMobile).mockReturnValue(true)
vi.mocked(useUnreadScheduleRuns).mockReturnValue({
data: { total: 1, runs: [] },
} as unknown as ReturnType<typeof useUnreadScheduleRuns>)
const queryClient = new QueryClient()
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/']}>
<MobileTabBar />
</MemoryRouter>
</QueryClientProvider>,
)
expect(screen.getByRole('button', { name: 'Schedules' }).querySelector('[data-unread-badge]')).not.toBeNull()
expect(screen.getByRole('button', { name: 'More' }).querySelector('[data-unread-badge]')).toBeNull()
})
})
@@ -159,6 +159,7 @@ function buildGlobalTabs({ pathname, openSheet, open, close, navigate, isInsideR
icon: Menu,
onClick: () => open('more'),
active: openSheet === 'more',
badge: !showsSchedules && unreadScheduleCount > 0,
},
]
}
@@ -213,7 +214,11 @@ const TabBarRow = memo(function TabBarRow({ tabs }: TabBarRowProps) {
<div className="relative">
<Icon className="w-5 h-5" />
{tab.badge && (
<span className="absolute -top-0.5 -right-1 w-2 h-2 rounded-full bg-highlight ring-2 ring-card animate-pulse" />
<span
aria-hidden="true"
data-unread-badge
className="absolute -top-0.5 -right-1 w-2 h-2 rounded-full bg-highlight ring-2 ring-card animate-pulse"
/>
)}
</div>
<span className="leading-none">{tab.label}</span>
@@ -229,7 +229,7 @@ describe('MoreDrawer', () => {
renderMoreDrawer({ onClose: handleClose })
fireEvent.click(screen.getByText('Settings'))
expect(navigateMock).toHaveBeenCalledWith(
{ search: 'settings=open&settingsTab=account' },
{ search: 'settings=open' },
{ replace: true },
)
})
@@ -332,7 +332,10 @@ describe('MoreDrawer', () => {
fireEvent.click(screen.getByText('Repos'))
expect(navigateMock).toHaveBeenCalledWith({ search: 'mobileTab=repos' }, { replace: false })
expect(navigateMock).toHaveBeenCalledWith(
{ search: 'mobileTab=repos' },
{ state: { urlParamHistory: { previousSearch: '?mobileTab=more' } } },
)
})
it('keeps Home and hides the Repos row outside a session', () => {
@@ -110,7 +110,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
updateParams((p) => {
p.delete('mobileTab')
p.set('settings', 'open')
p.set('settingsTab', 'account')
p.delete('settingsTab')
}, 'replace')
}
@@ -5,6 +5,7 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
import { getRepoSiblings, listRepos } from '@/api/repos'
import { stubMatchMedia } from '@/test/test-utils'
import { listProjects, type OpenCodeProject } from '@/api/opencode'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
@@ -236,6 +237,7 @@ describe('RepoQuickSwitchSheet', () => {
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
setActivityGroups({})
setLinkedServers([])
stubMatchMedia(true)
})
it('renders with loading state', async () => {
@@ -246,7 +248,7 @@ describe('RepoQuickSwitchSheet', () => {
{ wrapper: createWrapper() },
)
await waitFor(() => {
expect(screen.getByPlaceholderText('Search projects...')).toBeInTheDocument()
expect(screen.getByPlaceholderText('Search repos...')).toBeInTheDocument()
})
})
@@ -294,7 +296,7 @@ describe('RepoQuickSwitchSheet', () => {
expect(screen.getByText('repo1')).toBeInTheDocument()
expect(screen.getByText('repo2')).toBeInTheDocument()
})
const input = screen.getByPlaceholderText('Search projects...')
const input = screen.getByPlaceholderText('Search repos...')
fireEvent.change(input, { target: { value: 'repo1' } })
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
@@ -773,7 +775,7 @@ describe('RepoQuickSwitchSheet', () => {
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
const input = await screen.findByPlaceholderText('Search projects...')
const input = await screen.findByPlaceholderText('Search repos...')
await waitFor(() => expect(screen.getByText('repo2')).toBeInTheDocument())
expect(screen.queryByLabelText('Clear search')).toBeNull()
@@ -927,7 +929,7 @@ describe('RepoQuickSwitchSheet', () => {
expect(await screen.findByRole('heading', { name: 'Activity' })).toBeInTheDocument()
fireEvent.change(screen.getByPlaceholderText('Search projects...'), { target: { value: 'repo' } })
fireEvent.change(screen.getByPlaceholderText('Search repos...'), { target: { value: 'repo' } })
expect(screen.queryByRole('heading', { name: 'Activity' })).toBeNull()
expect(screen.queryByText('Session s1')).toBeNull()
@@ -1093,4 +1095,34 @@ describe('RepoQuickSwitchSheet', () => {
)
expect(handleClose).toHaveBeenCalled()
})
it('leaves the search input unfocused on touch screens so the keyboard stays closed', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
stubMatchMedia(false)
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
const input = await screen.findByPlaceholderText('Search repos...')
expect(input).not.toHaveFocus()
})
it('focuses the search input when a fine pointer is available', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
stubMatchMedia(true)
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
const input = await screen.findByPlaceholderText('Search repos...')
await waitFor(() => expect(input).toHaveFocus())
})
it('uses project wording for the search placeholder when a linked server is selected', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
vi.mocked(listProjects).mockResolvedValue([createProject('p1', 'Alpha', '/projects/alpha')])
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
expect(await screen.findByPlaceholderText('Search projects...')).toBeInTheDocument()
})
})
@@ -2,6 +2,7 @@ import { useState, useMemo } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
import { Input } from '@/components/ui/input'
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
import { Button } from '@/components/ui/button'
@@ -32,6 +33,7 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
const [selectedServerId] = useSidebarServerSelection()
const isRemote = selectedServerId !== LOCAL_OPENCODE_SERVER_ID
const activeRepoId = getActiveRepoId(location.pathname)
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
const { repos, isLoading, refetch } = useNavigableRepos(isOpen)
@@ -76,10 +78,10 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
<div className="relative flex-1">
<Input
type="text"
placeholder="Search projects..."
placeholder={isRemote ? 'Search projects...' : 'Search repos...'}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
autoFocus
autoFocus={hasFinePointer}
className="pr-9"
autoComplete="off"
name="repo-quick-switch"
@@ -36,6 +36,9 @@ vi.mock('@/components/terminal/TerminalPanel', () => ({
TerminalWorkspace: ({ onLastTerminalExited }: { onLastTerminalExited?: () => void }) => (
<div>
terminal-tool
<div className="xterm">
<textarea aria-label="terminal input" />
</div>
<button type="button" onClick={onLastTerminalExited}>Exit last terminal</button>
</div>
),
@@ -100,6 +103,14 @@ function search(): URLSearchParams {
return new URLSearchParams(screen.getByTestId('search').textContent ?? '')
}
function stubNarrowPage(): () => void {
const main = document.createElement('main')
main.getBoundingClientRect = () =>
({ width: 560, height: 800, top: 0, left: 0, right: 560, bottom: 800, x: 0, y: 0, toJSON: () => ({}) }) as DOMRect
document.body.append(main)
return () => main.remove()
}
const WINDOW_MINUTES = 30
const NOW = Date.now()
@@ -276,6 +287,137 @@ describe('ToolSidePanel', () => {
await waitFor(() => expect(search().has('panel')).toBe(false))
})
it('renders the panel as a modal sheet over the page when docking would squeeze it', async () => {
const removePage = stubNarrowPage()
try {
renderAt('?panel=files')
const panel = await screen.findByRole('dialog', { name: 'Files' })
const backdrop = screen.getByTestId('tool-panel-backdrop')
expect(panel.className).toContain('fixed')
expect(panel).toHaveAttribute('aria-modal', 'true')
expect(panel).not.toHaveAttribute('style')
expect(panel.className).toContain('z-50')
expect(backdrop.className).toContain('z-50')
expect(backdrop).toHaveAttribute('aria-hidden', 'true')
expect(screen.queryByRole('separator', { name: 'Resize panel' })).not.toBeInTheDocument()
} finally {
removePage()
}
})
it('portals the floating overlay into the document body so page stacking contexts cannot cover it', async () => {
const removePage = stubNarrowPage()
try {
renderAt('?panel=files')
const panel = await screen.findByRole('dialog', { name: 'Files' })
const backdrop = screen.getByTestId('tool-panel-backdrop')
expect(panel.parentElement).toBe(document.body)
expect(backdrop.parentElement).toBe(document.body)
expect(backdrop.className).toContain('inset-y-0')
} finally {
removePage()
}
})
it('moves focus into the floating panel and returns it to the rail on close', async () => {
const user = userEvent.setup()
const removePage = stubNarrowPage()
try {
renderAt('')
const filesButton = screen.getByRole('button', { name: 'Files' })
await user.click(filesButton)
const panel = await screen.findByRole('dialog', { name: 'Files' })
await waitFor(() => expect(document.activeElement).toBe(panel))
await user.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Files' })).not.toBeInTheDocument())
await waitFor(() => expect(document.activeElement).toBe(filesButton))
expect(search().has('panel')).toBe(false)
} finally {
removePage()
}
})
it('closes the floating panel on Escape and on an outside click', async () => {
const user = userEvent.setup()
const removePage = stubNarrowPage()
try {
renderAt('?panel=files')
await screen.findByRole('dialog', { name: 'Files' })
await user.keyboard('{Escape}')
await waitFor(() => expect(search().has('panel')).toBe(false))
await user.click(screen.getByRole('button', { name: 'Files' }))
await screen.findByRole('dialog', { name: 'Files' })
await user.click(screen.getByTestId('tool-panel-backdrop'))
await waitFor(() => expect(search().has('panel')).toBe(false))
} finally {
removePage()
}
})
it('keeps the floating terminal open on Escape typed into the terminal', async () => {
const user = userEvent.setup()
const removePage = stubNarrowPage()
try {
renderAt('?panel=terminal&terminal=pty-1')
await screen.findByRole('dialog', { name: 'Terminal' })
const terminalInput = screen.getByLabelText('terminal input')
await user.click(terminalInput)
await user.keyboard('{Escape}')
expect(screen.getByRole('dialog', { name: 'Terminal' })).toBeInTheDocument()
expect(search().get('panel')).toBe('terminal')
} finally {
removePage()
}
})
it('keeps a docked panel open on Escape', async () => {
const user = userEvent.setup()
renderAt('?panel=files')
await screen.findByRole('complementary', { name: 'Files' })
await user.keyboard('{Escape}')
expect(search().get('panel')).toBe('files')
})
it('resizes the docked panel from the keyboard and clamps it', async () => {
const user = userEvent.setup()
renderAt('?panel=files')
const handle = await screen.findByRole('separator', { name: 'Resize panel' })
const panel = screen.getByRole('complementary', { name: 'Files' })
expect(panel.parentElement).not.toBe(document.body)
const initial = Number(handle.getAttribute('aria-valuenow'))
handle.focus()
await user.keyboard('{ArrowRight}')
expect(Number(handle.getAttribute('aria-valuenow'))).toBe(initial - 16)
expect(panel).toHaveStyle({ width: `${initial - 16}px` })
await user.keyboard('{Home}')
expect(Number(handle.getAttribute('aria-valuenow'))).toBe(320)
expect(panel).toHaveStyle({ width: '320px' })
})
it('opens non-panel session items from the rail as dialogs', async () => {
const user = userEvent.setup()
renderAt('?panel=files')
@@ -1,5 +1,6 @@
import { useEffect, useRef } from 'react'
import type { ReactNode } from 'react'
import { useCallback, useEffect, useRef } from 'react'
import type { ReactNode, RefObject } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { useLocation, useNavigate } from 'react-router-dom'
import { FileBrowser } from '@/components/file-browser/FileBrowser'
@@ -32,15 +33,138 @@ import { useActiveWorkCounts, useActivityWindowMinutes } from '@/hooks/useActive
import { formatActivityWindow } from '@/lib/activeWork'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TOOLTIP_OPEN_DELAY_MS } from '@/components/ui/tooltip'
import { restoreOverlayFocus } from '@/lib/overlayFocus'
import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
import { cn } from '@/lib/utils'
import { useToolPanelLayout, useToolPanelWidth } from '@/hooks/useToolPanelLayout'
import { isLocalOpenCodeServer, useRouteOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
const PANEL_WIDTH_CLASSES: Partial<Record<PanelTool, string>> = {
activity: 'w-80',
}
interface PanelResizeState {
pointerId: number
startX: number
startWidth: number
}
interface PanelResizeHandleProps {
width: number
minWidth: number
maxWidth: number
onWidthChange: (width: number) => void
}
function PanelResizeHandle({ width, minWidth, maxWidth, onWidthChange }: PanelResizeHandleProps) {
const dragRef = useRef<PanelResizeState | null>(null)
const handlePointerDown = useCallback(
(event: React.PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return
event.preventDefault()
event.currentTarget.setPointerCapture?.(event.pointerId)
dragRef.current = { pointerId: event.pointerId, startX: event.clientX, startWidth: width }
},
[width],
)
const handlePointerMove = useCallback(
(event: React.PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current
if (!drag || drag.pointerId !== event.pointerId) return
onWidthChange(drag.startWidth - (event.clientX - drag.startX))
},
[onWidthChange],
)
const handlePointerEnd = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current
if (!drag || drag.pointerId !== event.pointerId) return
if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
event.currentTarget.releasePointerCapture?.(event.pointerId)
}
dragRef.current = null
}, [])
const handleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
const step = event.shiftKey ? 64 : 16
let nextWidth: number
switch (event.key) {
case 'ArrowLeft':
nextWidth = width + step
break
case 'ArrowRight':
nextWidth = width - step
break
case 'Home':
nextWidth = minWidth
break
case 'End':
nextWidth = maxWidth
break
default:
return
}
event.preventDefault()
onWidthChange(nextWidth)
},
[maxWidth, minWidth, onWidthChange, width],
)
return (
<div
role="separator"
aria-orientation="vertical"
aria-label="Resize panel"
tabIndex={0}
aria-valuenow={width}
aria-valuemin={minWidth}
aria-valuemax={maxWidth}
className="absolute inset-y-0 -left-1 z-10 w-2 cursor-col-resize touch-none bg-transparent hover:bg-highlight/30 focus-visible:bg-highlight/30 focus-visible:outline-none"
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerEnd}
onPointerCancel={handlePointerEnd}
onKeyDown={handleKeyDown}
/>
)
}
const REMOTE_TOOL_KEYS: ReadonlySet<string> = new Set(['activity', 'mcp', 'skills', 'source-control', 'terminal'])
/**
* Escape closes the floating panel, except while a nested menu is open or the terminal owns
* the key. Focus moving into the opener is handled by `useRestoreFocusOnClose`.
*/
function useFloatingPanelDismiss(
floating: boolean,
closePanel: () => void,
panelRef: RefObject<HTMLElement | null>,
) {
const closeRef = useRef(closePanel)
closeRef.current = closePanel
useEffect(() => {
if (!floating) return
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
const target = event.target
if (target instanceof Element) {
if (target.closest('.xterm')) return
if (target.closest('[role="listbox"], [role="menu"]')) return
const dialog = target.closest('[role="dialog"]')
if (dialog !== null && dialog !== panelRef.current) return
}
closeRef.current()
}
document.addEventListener('keydown', handleKeyDown)
return () => document.removeEventListener('keydown', handleKeyDown)
}, [floating, panelRef])
}
function ActivityWindowLabel() {
const minutes = useActivityWindowMinutes()
return (
@@ -141,8 +265,10 @@ function RailButton({ item, active, onClick, indicator }: RailButtonProps) {
}
/**
* Desktop-only docked tool panel with its icon rail, rendered to the right of a page's content.
* The rail lists the current route's tool items; repo- and session-scoped tools render only when their context is given.
* Desktop-only tool panel with its icon rail, rendered to the right of a page's content. The panel
* docks when the page has room and otherwise floats over the page as a sheet, so the content keeps
* a usable width. The rail lists the current route's tool items; repo- and session-scoped tools
* render only when their context is given.
*/
export function ToolSidePanel({
panel,
@@ -167,7 +293,21 @@ export function ToolSidePanel({
const routeServerId = useRouteOpenCodeServerId()
const isRemoteRoute = !isLocalOpenCodeServer(routeServerId)
const railRef = useRef<HTMLElement>(null)
const panelRef = useRef<HTMLElement>(null)
const previousActiveToolRef = useRef(activeTool)
const panelWidth = useToolPanelWidth()
const { docked } = useToolPanelLayout()
const floating = activeTool !== null && !docked
useRestoreFocusOnClose(floating, panelRef)
useFloatingPanelDismiss(floating, closePanel, panelRef)
useEffect(() => {
if (!floating) return
const panelElement = panelRef.current
if (panelElement === null || panelElement.contains(document.activeElement)) return
panelElement.focus()
}, [floating])
useEffect(() => {
const previousTool = previousActiveToolRef.current
@@ -247,40 +387,73 @@ export function ToolSidePanel({
}
}
const panelContent =
const fixedWidthClass = activeTool ? PANEL_WIDTH_CLASSES[activeTool] : undefined
const panelBody =
activeTool && activeLabel ? (
<aside
aria-label={activeLabel}
className={cn(
'flex shrink-0 flex-col border-l border-border bg-background',
PANEL_WIDTH_CLASSES[activeTool] ?? 'w-[min(600px,45vw)]',
)}
>
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">
<div className="flex min-w-0 flex-1 items-baseline gap-2">
<h2 className="min-w-0 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
{activeTool === 'activity' ? <ActivityWindowLabel /> : null}
</div>
{activeTool === 'walkthrough' ? (
<>
<ChangesWalkthroughSourcePicker />
<ChangesWalkthroughCancel />
<ChangesWalkthroughRegenerate />
</>
) : null}
<button
type="button"
<>
{docked ? null : (
<div
data-testid="tool-panel-backdrop"
aria-hidden="true"
className="fixed inset-y-0 left-0 right-11 z-50 bg-black/50 backdrop-blur-sm"
onClick={closePanel}
aria-label="Close panel"
className="rounded-sm p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="flex min-h-0 flex-1 flex-col">{renderTool(activeTool)}</div>
</aside>
/>
)}
<aside
ref={panelRef}
aria-label={activeLabel}
role={docked ? undefined : 'dialog'}
aria-modal={docked ? undefined : true}
tabIndex={docked ? undefined : -1}
className={cn(
'flex flex-col border-l border-border bg-background outline-none',
docked
? 'relative shrink-0'
: 'fixed inset-y-0 right-11 z-50 w-[min(420px,calc(100vw-2.75rem))] pt-safe pb-safe shadow-2xl',
fixedWidthClass,
)}
style={docked && !fixedWidthClass ? { width: panelWidth.width } : undefined}
>
{docked && !fixedWidthClass ? (
<PanelResizeHandle
width={panelWidth.width}
minWidth={panelWidth.minWidth}
maxWidth={panelWidth.maxWidth}
onWidthChange={panelWidth.setWidth}
/>
) : null}
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">
<div className="flex min-w-0 flex-1 items-baseline gap-2">
<h2 className="min-w-0 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
{activeTool === 'activity' ? <ActivityWindowLabel /> : null}
</div>
{activeTool === 'walkthrough' ? (
<>
<ChangesWalkthroughSourcePicker />
<ChangesWalkthroughCancel />
<ChangesWalkthroughRegenerate />
</>
) : null}
<button
type="button"
onClick={closePanel}
aria-label="Close panel"
className="rounded-sm p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="flex min-h-0 flex-1 flex-col">{renderTool(activeTool)}</div>
</aside>
</>
) : null
const panelContent =
panelBody !== null && !docked && typeof document !== 'undefined'
? createPortal(panelBody, document.body)
: panelBody
return (
<>
{panelContent ? (
@@ -0,0 +1,83 @@
import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { AddRepoDialog } from './AddRepoDialog'
const mocks = vi.hoisted(() => ({
createRepo: vi.fn(),
discoverRepos: vi.fn(),
listRepos: vi.fn(),
}))
vi.mock('@/api/repos', () => ({
createRepo: mocks.createRepo,
discoverRepos: mocks.discoverRepos,
listRepos: mocks.listRepos,
}))
vi.mock('@/lib/toast', () => ({
showToast: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
}))
function Harness() {
const [open, setOpen] = useState(true)
const [queryClient] = useState(() => new QueryClient({ defaultOptions: { queries: { retry: false } } }))
return (
<QueryClientProvider client={queryClient}>
<button onClick={() => setOpen(true)}>reopen</button>
<AddRepoDialog open={open} onOpenChange={setOpen} />
</QueryClientProvider>
)
}
describe('AddRepoDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.listRepos.mockResolvedValue([])
})
it('links each field label to its input', () => {
render(<Harness />)
expect(screen.getByLabelText('Repository URL')).toBeInTheDocument()
expect(screen.getByLabelText('Directory Name')).toBeInTheDocument()
expect(screen.getByLabelText('Branch (optional)')).toBeInTheDocument()
})
it('rejects a URL containing whitespace before submitting', async () => {
const user = userEvent.setup()
render(<Harness />)
await user.type(screen.getByLabelText('Repository URL'), 'not a url !!')
expect(screen.getByText('Enter a valid repository URL without spaces.')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Add Repository' })).toBeDisabled()
expect(mocks.createRepo).not.toHaveBeenCalled()
})
it('clears the previous error and input when reopened', async () => {
mocks.createRepo.mockRejectedValue(new Error('Repository not found or access denied: https://github.com/test/missing.'))
const user = userEvent.setup()
render(<Harness />)
const input = screen.getByLabelText('Repository URL')
await user.type(input, 'test/missing')
await user.click(screen.getByRole('button', { name: 'Add Repository' }))
expect(await screen.findByText('Repository not found or access denied: https://github.com/test/missing.')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Close' }))
await user.click(screen.getByRole('button', { name: 'reopen' }))
expect(screen.getByLabelText('Repository URL')).toHaveValue('')
expect(screen.queryByText('Repository not found or access denied: https://github.com/test/missing.')).not.toBeInTheDocument()
})
})
+50 -24
View File
@@ -39,6 +39,22 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
staleTime: 30_000,
})
const resetForm = useCallback(() => {
setRepoUrl('')
setLocalPath('')
setFolderPath('')
setDirectoryName('')
setBranch('')
setRepoType('remote')
setSkipSSHVerification(false)
directoryTouched.current = false
}, [])
const repoUrlError = useMemo(() => {
if (repoType !== 'remote' || !repoUrl.trim()) return null
return /\s/.test(repoUrl.trim()) ? 'Enter a valid repository URL without spaces' : null
}, [repoType, repoUrl])
const directoryNameError = useMemo(() => {
if (!showDirectoryName || !directoryName) return null
return getRepoDirectoryNameError(directoryName)
@@ -82,14 +98,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
},
onSuccess: (result) => {
invalidateRepoListCaches(queryClient)
setRepoUrl('')
setLocalPath('')
setFolderPath('')
setDirectoryName('')
setBranch('')
setRepoType('remote')
setSkipSSHVerification(false)
directoryTouched.current = false
resetForm()
if (result.mode === 'discover') {
const summary = [
@@ -118,11 +127,19 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if ((repoType === 'remote' && repoUrl) || (repoType === 'local' && localPath) || (repoType === 'folder' && folderPath)) {
if ((repoType === 'remote' && repoUrl && !repoUrlError) || (repoType === 'local' && localPath) || (repoType === 'folder' && folderPath)) {
mutation.mutate()
}
}
const handleOpenChange = (nextOpen: boolean) => {
if (!nextOpen) {
resetForm()
mutation.reset()
}
onOpenChange(nextOpen)
}
const handleRepoUrlChange = useCallback((value: string) => {
setRepoUrl(value)
if (!isSSHUrl(value)) {
@@ -140,7 +157,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
}, [])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose className="content-start gap-0 sm:max-w-[500px] sm:max-h-[80vh] sm:h-auto sm:top-[50%] sm:translate-y-[-50%] bg-card border-border">
<DialogHeader className="px-4 sm:px-6 pt-2 sm:pt-6 pb-2 sm:pb-3 h-fit">
<DialogTitle className="text-xl text-foreground">
@@ -161,28 +178,34 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
{repoType === 'remote' ? (
<div className="space-y-2">
<label className="text-sm text-muted-foreground">Repository URL</label>
<label htmlFor="add-repo-url" className="text-sm text-muted-foreground">Repository URL</label>
<Input
id="add-repo-url"
placeholder="owner/repo or https://github.com/user/repo.git"
value={repoUrl}
onChange={(e) => handleRepoUrlChange(e.target.value)}
disabled={mutation.isPending}
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
/>
<p className="text-xs text-muted-foreground">
Full URL or shorthand format (owner/repo for GitHub)
</p>
{repoUrlError ? (
<p className="text-xs text-warning">{repoUrlError}.</p>
) : (
<p className="text-xs text-muted-foreground">
Full URL or shorthand format (owner/repo for GitHub)
</p>
)}
</div>
) : repoType === 'local' ? (
<div className="space-y-2">
<label className="text-sm text-muted-foreground">Local Path</label>
<label htmlFor="add-repo-local-path" className="text-sm text-muted-foreground">Local Path</label>
<div className="flex gap-2">
<Input
id="add-repo-local-path"
placeholder="my-local-project OR /absolute/path/to/git-repo"
value={localPath}
onChange={(e) => setLocalPath(e.target.value)}
disabled={mutation.isPending}
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
/>
<Button
type="button"
@@ -201,14 +224,15 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
</div>
) : (
<div className="space-y-2">
<label className="text-sm text-muted-foreground">Folder Path</label>
<label htmlFor="add-repo-folder-path" className="text-sm text-muted-foreground">Folder Path</label>
<div className="flex gap-2">
<Input
id="add-repo-folder-path"
placeholder="/absolute/path/to/projects"
value={folderPath}
onChange={(e) => setFolderPath(e.target.value)}
disabled={mutation.isPending}
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
/>
<Button
type="button"
@@ -229,13 +253,14 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
{showDirectoryName && (
<div className="space-y-2">
<label className="text-sm text-muted-foreground">Directory Name</label>
<label htmlFor="add-repo-directory-name" className="text-sm text-muted-foreground">Directory Name</label>
<Input
id="add-repo-directory-name"
placeholder="Auto-detected from URL"
value={directoryName}
onChange={(e) => handleDirectoryNameChange(e.target.value)}
disabled={mutation.isPending}
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
/>
{directoryNameError ? (
<p className="text-xs text-warning">
@@ -259,13 +284,14 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
)}
<div className="space-y-2">
<label className="text-sm text-muted-foreground">Branch (optional)</label>
<label htmlFor="add-repo-branch" className="text-sm text-muted-foreground">Branch (optional)</label>
<Input
id="add-repo-branch"
placeholder="Uses default if empty"
value={branch}
onChange={(e) => setBranch(e.target.value)}
disabled={mutation.isPending || repoType === 'folder'}
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
className="bg-muted border-border text-foreground placeholder:text-placeholder min-h-[44px] text-base"
/>
<p className="text-xs text-muted-foreground">
{repoType === 'folder'
@@ -300,7 +326,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
<Button
type="submit"
disabled={(!repoUrl && repoType === 'remote') || (!localPath && repoType === 'local') || (!folderPath && repoType === 'folder') || mutation.isPending || (showDirectoryName && (!!directoryNameError || !!directoryCollision))}
disabled={(!repoUrl && repoType === 'remote') || !!repoUrlError || (!localPath && repoType === 'local') || (!folderPath && repoType === 'folder') || mutation.isPending || (showDirectoryName && (!!directoryNameError || !!directoryCollision))}
className="w-full min-h-[48px] bg-primary hover:bg-primary-hover text-primary-foreground text-base font-medium"
>
{mutation.isPending ? (
@@ -317,6 +317,25 @@ describe('MultiRunSheet', () => {
expect(screen.getByText('1/5 selected')).toBeInTheDocument()
})
it('names the missing required fields while Launch is disabled', async () => {
const user = userEvent.setup()
renderSheet()
await openNewRun(user)
expect(screen.getByRole('button', { name: 'Launch' })).toBeDisabled()
expect(screen.getByText('Required: group name, prompt, at least one model')).toBeInTheDocument()
await user.type(screen.getByLabelText('Group name'), 'Sweep')
expect(screen.getByText('Required: prompt, at least one model')).toBeInTheDocument()
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
expect(screen.queryByText(/^Required:/)).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Launch' })).toBeEnabled()
})
it('caps model selection at five', async () => {
const user = userEvent.setup()
renderSheet()
+20 -4
View File
@@ -308,8 +308,13 @@ function NewRunForm({ target, directory, defaultBaseRef, open, onLaunched }: New
})
}, [])
const canSubmit =
name.trim().length > 0 && prompt.trim().length > 0 && selectedModels.length > 0 && !launch.isPending
const missingRequirements = [
name.trim().length > 0 ? null : 'group name',
prompt.trim().length > 0 ? null : 'prompt',
selectedModels.length > 0 ? null : 'at least one model',
].filter((requirement): requirement is string => requirement !== null)
const canSubmit = missingRequirements.length === 0 && !launch.isPending
const handleLaunch = () => {
if (!canSubmit) return
@@ -411,11 +416,22 @@ function NewRunForm({ target, directory, defaultBaseRef, open, onLaunched }: New
</div>
) : null}
<div className="flex justify-end">
<Button className="min-w-32" onClick={handleLaunch} disabled={!canSubmit} aria-busy={launch.isPending}>
<div className="flex flex-col items-end gap-1">
<Button
className="min-w-32"
onClick={handleLaunch}
disabled={!canSubmit}
aria-busy={launch.isPending}
aria-describedby={missingRequirements.length > 0 ? 'multi-run-requirements' : undefined}
>
{launch.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
{launch.isPending ? 'Launching…' : 'Launch'}
</Button>
{missingRequirements.length > 0 ? (
<p id="multi-run-requirements" className="text-xs text-muted-foreground">
Required: {missingRequirements.join(', ')}
</p>
) : null}
</div>
</SideDrawerContent>
)
+110 -6
View File
@@ -1,11 +1,17 @@
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter } from 'react-router-dom'
import { createUseSettingsMock } from '@/test/test-utils'
import { RepoList } from './RepoList'
import type { Repo } from '@/api/types'
const mocks = vi.hoisted(() => ({ listRepos: vi.fn() }))
const mocks = vi.hoisted(() => ({
listRepos: vi.fn(),
useRepoActivityState: vi.fn(),
fetchReposGitStatus: vi.fn(),
}))
vi.mock('@/api/repos', () => ({
listRepos: mocks.listRepos,
@@ -13,23 +19,75 @@ vi.mock('@/api/repos', () => ({
updateRepoOrder: vi.fn(),
}))
vi.mock('@/api/git', () => ({
fetchReposGitStatus: mocks.fetchReposGitStatus,
}))
vi.mock('@/hooks/useActiveWork', () => ({
useRepoActivityState: mocks.useRepoActivityState,
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: () => createUseSettingsMock(),
}))
vi.mock('@/hooks/useMobile', () => ({ useMobile: () => true }))
vi.mock('@/hooks/useMobile', () => ({
useMobile: () => false,
useSwipeBack: () => ({
bind: vi.fn(),
swipeProgress: 0,
swipeStyles: {},
}),
}))
function renderRepoList(onAddRepo: () => void) {
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom')
return {
...actual,
useNavigate: () => vi.fn(),
}
})
function createRepo(overrides: Partial<Repo> = {}): Repo {
return {
id: 1,
name: 'demo-app',
localPath: 'demo-app',
fullPath: '/workspace/repos/demo-app',
defaultBranch: 'main',
branch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
isWorktree: false,
isLocal: true,
...overrides,
}
}
function renderRepoList(onAddRepo: () => void = vi.fn()) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<RepoList onAddRepo={onAddRepo} />
<BrowserRouter>
<RepoList onAddRepo={onAddRepo} />
</BrowserRouter>
</QueryClientProvider>,
)
}
async function openRepoDeleteDialog(user: ReturnType<typeof userEvent.setup>) {
await user.click(await screen.findByRole('button', { name: /Unlink Repository|Delete Repository/ }))
return screen.findByRole('dialog')
}
describe('RepoList', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useRepoActivityState.mockReturnValue(null)
mocks.fetchReposGitStatus.mockResolvedValue(new Map())
})
it('calls onAddRepo once from the empty state', async () => {
mocks.listRepos.mockResolvedValue([])
const onAddRepo = vi.fn()
@@ -41,4 +99,50 @@ describe('RepoList', () => {
expect(onAddRepo).toHaveBeenCalledTimes(1)
})
it('shows a search-aware empty message when nothing matches the query', async () => {
mocks.listRepos.mockResolvedValue([createRepo()])
const user = userEvent.setup()
renderRepoList()
await screen.findByText('demo-app')
await user.type(screen.getByPlaceholderText('Search repositories...'), 'zzzz-nomatch')
expect(await screen.findByText('No repositories found matching "zzzz-nomatch"')).toBeInTheDocument()
expect(screen.queryByText('No recently accessed repositories')).not.toBeInTheDocument()
})
it('keeps the filter empty message when no search query is active', async () => {
mocks.listRepos.mockResolvedValue([createRepo({ cloneStatus: 'cloning' })])
renderRepoList()
expect(await screen.findByText('No recently accessed repositories')).toBeInTheDocument()
})
it('labels the confirm button "Unlink" for a local repository', async () => {
mocks.listRepos.mockResolvedValue([createRepo()])
const user = userEvent.setup()
renderRepoList()
const dialog = await openRepoDeleteDialog(user)
expect(within(dialog).getByText('Unlink Repository')).toBeInTheDocument()
expect(within(dialog).getByRole('button', { name: 'Unlink' })).toBeInTheDocument()
expect(within(dialog).queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument()
})
it('labels the confirm button "Delete" for a cloned repository', async () => {
mocks.listRepos.mockResolvedValue([
createRepo({ id: 2, name: 'cloned', localPath: 'cloned', repoUrl: 'https://github.com/test/cloned', isLocal: false }),
])
const user = userEvent.setup()
renderRepoList()
const dialog = await openRepoDeleteDialog(user)
expect(within(dialog).getByText('Delete Repository')).toBeInTheDocument()
expect(within(dialog).getByRole('button', { name: 'Delete' })).toBeInTheDocument()
})
})
+10 -3
View File
@@ -22,6 +22,7 @@ import {
sortRepos,
groupReposIntoSections,
countAttentionItems,
getRepoListEmptyMessage,
type RepoFilterMode,
type RepoSortMode,
} from "./repo-list-state"
@@ -181,11 +182,15 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
if (!repos) return { hasLocalRepos: false, hasClonedRepos: false }
const selectedRepoObjects = repos.filter(r => selectedRepos.has(r.id))
return {
hasLocalRepos: selectedRepoObjects.some(r => r.isLocal),
hasClonedRepos: selectedRepoObjects.some(r => !r.isLocal),
hasLocalRepos: selectedRepoObjects.some(r => r.isLocal && !r.isWorktree),
hasClonedRepos: selectedRepoObjects.some(r => !r.isLocal || r.isWorktree),
}
}, [selectedRepos, repos])
const unlinkOnly = selectedRepos.size > 0
? hasLocalRepos && !hasClonedRepos
: Boolean(repoForDelete?.isLocal && !repoForDelete?.isWorktree)
const repoIds = regularRepos?.map((repo) => repo.id) || []
const { data: gitStatuses } = useQuery({
@@ -430,7 +435,7 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
<div className="text-center p-12">
<Search className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
<p className="text-muted-foreground">
{sections[0]?.emptyMessage || `No repositories found${searchQuery ? ` matching "${searchQuery}"` : ''}`}
{getRepoListEmptyMessage(sections, searchQuery)}
</p>
</div>
)
@@ -565,6 +570,8 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
: "Are you sure you want to delete this repository? This will remove all local files. This action cannot be undone."
}
isDeleting={deleteMutation.isPending || batchDeleteMutation.isPending}
confirmLabel={unlinkOnly ? 'Unlink' : 'Delete'}
pendingLabel={unlinkOnly ? 'Unlinking...' : 'Deleting...'}
>
{selectedRepos.size === 0 && repoForDelete?.isWorktree && (
<div>
@@ -67,4 +67,63 @@ describe('RepoListControls', () => {
expect(screen.queryByRole('button', { name: 'Add repository' })).not.toBeInTheDocument()
})
it('offers the sort options in the mobile filter menu', async () => {
mocks.mobile.current = true
const props = baseProps()
const user = userEvent.setup()
render(<RepoListControls {...props} />)
await user.click(screen.getByRole('button', { name: 'Filter and sort repositories' }))
expect(await screen.findByText('Sort by')).toBeInTheDocument()
await user.click(screen.getByRole('menuitem', { name: 'Name' }))
expect(props.onSortModeChange).toHaveBeenCalledWith('name')
})
it('shows the active non-default filter on mobile and clears it back to the default', async () => {
mocks.mobile.current = true
const props = { ...baseProps(), filterMode: 'attention' as const }
const user = userEvent.setup()
render(<RepoListControls {...props} />)
const chip = screen.getByRole('button', { name: 'Clear filter: Changes' })
expect(chip).toHaveTextContent('Changes')
await user.click(chip)
expect(props.onFilterModeChange).toHaveBeenCalledWith('recent')
})
it('hides the active filter chip for the default filter', () => {
mocks.mobile.current = true
render(<RepoListControls {...baseProps()} />)
expect(screen.queryByRole('button', { name: /Clear filter/ })).not.toBeInTheDocument()
})
it('shows the selection toolbar as soon as select mode is on', () => {
mocks.mobile.current = true
render(<RepoListControls {...baseProps()} selectionMode selectedCount={0} />)
expect(screen.getByText('0 selected')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Select All' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Done selecting repositories' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled()
})
it('exits select mode from the Done button', async () => {
mocks.mobile.current = true
const props = { ...baseProps(), selectionMode: true, selectedCount: 2 }
const user = userEvent.setup()
render(<RepoListControls {...props} />)
await user.click(screen.getByRole('button', { name: 'Done selecting repositories' }))
expect(props.onClearSelection).toHaveBeenCalledTimes(1)
})
})
@@ -8,6 +8,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuCheckboxItem,
DropdownMenuLabel,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { useMobile } from "@/hooks/useMobile";
@@ -73,7 +74,10 @@ export function RepoListControls({
const currentSortLabel =
SORT_OPTIONS.find((s) => s.value === sortMode)?.label ?? "Recent";
const inSelectionMode = selectedCount > 0;
const activeFilterLabel =
FILTER_OPTIONS.find((option) => option.value === filterMode)?.label ?? "All";
const showActiveFilter = isMobile && filterMode !== "recent";
const inSelectionMode = selectionMode || selectedCount > 0;
const getDeleteLabel = () => {
if (hasLocalRepos && !hasClonedRepos) {
@@ -85,14 +89,14 @@ export function RepoListControls({
if (inSelectionMode) {
return (
<div className="px-2 md:px-0">
<div className="flex items-center gap-2 bg-accent/50 rounded-md p-2">
<span className="text-sm font-medium text-foreground shrink-0 min-w-[80px]">
<div className="flex items-center gap-1.5 bg-accent/50 rounded-md p-2">
<span className="text-sm font-medium text-foreground shrink-0">
{selectedCount} selected
</span>
<Button
variant="ghost"
onClick={onSelectAll}
className="shrink-0 h-9 text-xs"
className="shrink-0 h-8 px-2 text-xs"
size="sm"
>
{allVisibleSelected ? "Unselect All" : "Select All"}
@@ -100,7 +104,8 @@ export function RepoListControls({
<Button
variant="ghost"
onClick={onDelete}
className="shrink-0 h-9 text-xs text-destructive hover:text-destructive"
disabled={selectedCount === 0}
className="shrink-0 h-8 px-2 text-xs text-destructive hover:text-destructive"
size="sm"
>
<Trash2 className="w-3 h-3 mr-1" />
@@ -108,11 +113,13 @@ export function RepoListControls({
</Button>
<Button
variant="ghost"
size="icon"
onClick={onClearSelection}
className="shrink-0 size-9 ml-auto text-destructive hover:text-destructive"
aria-label="Done selecting repositories"
className="shrink-0 h-8 px-2 text-xs gap-1 ml-auto"
size="sm"
>
<X className="w-4 h-4" />
<X className="w-3.5 h-3.5" />
Done
</Button>
</div>
</div>
@@ -150,7 +157,7 @@ export function RepoListControls({
<SlidersHorizontal className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuContent align="end" className="w-52">
<DropdownMenuCheckboxItem
checked={selectionMode}
onCheckedChange={(checked) =>
@@ -160,6 +167,21 @@ export function RepoListControls({
Select repositories
</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
<DropdownMenuLabel>Sort by</DropdownMenuLabel>
{SORT_OPTIONS.map((option) => (
<DropdownMenuItem
key={option.value}
onClick={() => {
onSortModeChange(option.value);
setShowMenu(false);
}}
className={sortMode === option.value ? "bg-accent" : ""}
>
{option.label}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuLabel>Filter</DropdownMenuLabel>
{FILTER_OPTIONS.map((option) => {
const count =
option.value === "attention"
@@ -214,6 +236,21 @@ export function RepoListControls({
)}
</div>
{showActiveFilter && (
<div className="flex items-center gap-2">
<Button
variant="secondary"
size="sm"
onClick={() => onFilterModeChange("recent")}
aria-label={`Clear filter: ${activeFilterLabel}`}
className="h-7 gap-1 rounded-full px-2.5 text-xs"
>
{activeFilterLabel}
<X className="h-3 w-3" />
</Button>
</div>
)}
{!isMobile && (
<div className="flex items-center gap-2 overflow-x-auto pb-1 -mb-1">
{FILTER_OPTIONS.map((option) => {
@@ -97,7 +97,8 @@ export function RepoRowActions({
}
const canCreateWorktree = isReady && !repo.isWorktree && Boolean(repo.repoUrl)
const deleteLabel = repo.isLocal ? 'Unlink Repository' : 'Delete Repository'
const isUnlinkableLocalRepo = Boolean(repo.isLocal && !repo.isWorktree)
const deleteLabel = isUnlinkableLocalRepo ? 'Unlink Repository' : 'Delete Repository'
const handleDownload = async (options: { includeGit?: boolean; includePaths?: string[] }) => {
try {
@@ -158,7 +159,7 @@ export function RepoRowActions({
) : (
<Trash2 className="w-4 h-4 mr-2" />
)}
{repo.isLocal ? 'Unlink' : 'Delete'}
{isUnlinkableLocalRepo ? 'Unlink' : 'Delete'}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -7,6 +7,7 @@ import {
dedupeRepos,
filterReposBySearch,
filterReposByMode,
getRepoListEmptyMessage,
sortRepos,
groupReposIntoSections,
countAttentionItems,
@@ -351,6 +352,24 @@ describe('repo-list-state', () => {
})
})
describe('getRepoListEmptyMessage', () => {
it('prefers a search-aware message when a query is active', () => {
const sections = [{ title: 'Recent', repos: [], emptyMessage: 'No recently accessed repositories' }]
expect(getRepoListEmptyMessage(sections, 'zzzz-nomatch')).toBe('No repositories found matching "zzzz-nomatch"')
})
it('falls back to the section empty message without a query', () => {
const sections = [{ title: 'Needs Attention', repos: [], emptyMessage: 'No repositories need attention' }]
expect(getRepoListEmptyMessage(sections, ' ')).toBe('No repositories need attention')
})
it('falls back to the generic message when no section has one', () => {
expect(getRepoListEmptyMessage([], '')).toBe('No repositories found')
})
})
describe('countAttentionItems', () => {
it('should count repos with changes, ahead, or behind', () => {
const repos = [
@@ -112,6 +112,14 @@ export function filterReposByMode(repos: RepoViewModel[], mode: RepoFilterMode):
}
}
export function getRepoListEmptyMessage(sections: RepoListSection[], searchQuery: string): string {
const query = searchQuery.trim()
if (query) {
return `No repositories found matching "${query}"`
}
return sections[0]?.emptyMessage ?? 'No repositories found'
}
export function sortRepos(repos: RepoViewModel[], mode: RepoSortMode, manualOrder?: number[]): RepoViewModel[] {
switch (mode) {
case 'recent':
@@ -158,10 +158,10 @@ export function GeneralTab({
<div className="rounded-lg border border-border bg-card p-4">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2">
<p className="text-sm font-medium">Enabled</p>
<p id="schedule-enabled-label" className="text-sm font-medium">Enabled</p>
<InfoHint text="Auto-run this job on its schedule while still allowing manual runs from the dashboard." />
</div>
<Switch checked={enabled} onCheckedChange={onEnabledChange} />
<Switch checked={enabled} onCheckedChange={onEnabledChange} aria-labelledby="schedule-enabled-label" />
</div>
</div>
@@ -201,19 +201,27 @@ export function GeneralTab({
<div className="rounded-lg border border-border bg-card p-4">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2">
<p className="text-sm font-medium">Allow access outside the working directory</p>
<p id="schedule-allow-external-label" className="text-sm font-medium">Allow access outside the working directory</p>
<InfoHint text="When disabled, runs are confined to the worktree. Enable to allow the agent to read/write files elsewhere on the system." />
</div>
<Switch checked={allowExternalDirectory} onCheckedChange={onAllowExternalDirectoryChange} />
<Switch
checked={allowExternalDirectory}
onCheckedChange={onAllowExternalDirectoryChange}
aria-labelledby="schedule-allow-external-label"
/>
</div>
</div>
<div className="rounded-lg border border-border bg-card p-4">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2">
<p className="text-sm font-medium">Allow questions</p>
<p id="schedule-allow-questions-label" className="text-sm font-medium">Allow questions</p>
<InfoHint text="Scheduled runs are unattended. When disabled, the agent's question tool is denied so a run can never stall waiting for an answer that nobody is there to give." />
</div>
<Switch checked={allowQuestions} onCheckedChange={onAllowQuestionsChange} />
<Switch
checked={allowQuestions}
onCheckedChange={onAllowQuestionsChange}
aria-labelledby="schedule-allow-questions-label"
/>
</div>
</div>
<div className="rounded-lg border border-border bg-card p-4">
@@ -0,0 +1,174 @@
import { useState } from 'react'
import type { ReactNode } from 'react'
import { act, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
import type { ScheduleJobWithRepo } from '@/api/schedules'
import { RepoSchedulesContent } from './RepoSchedulesContent'
function createJob(id: number, name: string): ScheduleJobWithRepo {
return {
id,
repoId: 1,
name,
description: null,
enabled: true,
scheduleMode: 'interval',
intervalMinutes: 60,
cronExpression: null,
timezone: null,
agentSlug: null,
prompt: `${name} prompt`,
model: null,
skillMetadata: null,
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'worktree',
createdAt: 1,
updatedAt: 1,
lastRunAt: null,
nextRunAt: null,
repoName: 'demo',
repoPath: '/workspace/repos/demo',
repoUrl: '',
serverName: null,
lastRun: null,
retainedWorktreeCount: 0,
}
}
const store = vi.hoisted(() => ({
jobs: [] as ScheduleJobWithRepo[],
setJobs: null as ((jobs: ScheduleJobWithRepo[]) => void) | null,
deleteMutate: vi.fn(),
createMutate: vi.fn(),
}))
vi.mock('@/hooks/useSchedules', () => ({
useAllSchedules: () => ({ data: store.jobs, isLoading: false }),
useRepoSchedule: () => ({ data: undefined, isFetching: false }),
useRepoScheduleRuns: () => ({ data: [], isLoading: false }),
useScheduleWorktrees: () => ({ data: [] }),
useCreateRepoSchedule: () => ({ mutate: store.createMutate, isPending: false }),
useUpdateRepoSchedule: () => ({ mutate: vi.fn(), isPending: false }),
useDeleteRepoSchedule: () => ({ mutate: store.deleteMutate, isPending: false }),
useRunRepoSchedule: () => ({ mutate: vi.fn(), isPending: false }),
useCancelRepoScheduleRun: () => ({ mutate: vi.fn(), isPending: false }),
useClearRepoScheduleRuns: () => ({ mutate: vi.fn(), isPending: false }),
useDeleteRepoScheduleRun: () => ({ mutate: vi.fn(), isPending: false }),
}))
vi.mock('@/components/schedules', () => ({
ScheduleJobsTable: ({ jobs, onDelete }: { jobs: ScheduleJob[]; onDelete: (job: ScheduleJob) => void }) => (
<div>
{jobs.map((job) => (
<button key={job.id} onClick={() => onDelete(job)}>{`delete ${job.name}`}</button>
))}
</div>
),
ScheduleJobDialog: ({ open, onSubmit }: { open: boolean; onSubmit: (data: CreateScheduleJobRequest) => void }) => (
open ? <button onClick={() => onSubmit({} as CreateScheduleJobRequest)}>submit schedule</button> : null
),
ScheduleListToolbar: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
ScheduleTabMenu: () => null,
JobDetailTab: () => null,
RunHistoryTab: () => null,
ScheduleRunRemovalDialog: () => null,
}))
function Harness({ initialJobs }: { initialJobs: ScheduleJobWithRepo[] }) {
const [jobs, setJobs] = useState(initialJobs)
store.jobs = jobs
store.setJobs = setJobs
const location = useLocation()
return (
<div>
<span data-testid="search">{location.search}</span>
<RepoSchedulesContent repoId={1} embedded={false} />
</div>
)
}
function renderContent(initialJobs: ScheduleJobWithRepo[], initialEntry = '/repos/1/schedules') {
return render(
<MemoryRouter initialEntries={[initialEntry]}>
<Harness initialJobs={initialJobs} />
</MemoryRouter>,
)
}
describe('RepoSchedulesContent dialogs', () => {
beforeEach(() => {
store.jobs = []
store.setJobs = null
store.deleteMutate.mockReset()
store.createMutate.mockReset()
})
it('names the schedule in the delete confirmation', async () => {
const user = userEvent.setup()
const alpha = createJob(1, 'Alpha')
const beta = createJob(2, 'Beta')
store.deleteMutate.mockImplementation(() => {})
renderContent([alpha, beta])
await user.click(screen.getByRole('button', { name: 'delete Beta' }))
const dialog = screen.getByRole('dialog')
expect(within(dialog).getByText('Beta')).toBeInTheDocument()
expect(within(dialog).getByText(/This will permanently delete/)).toBeInTheDocument()
})
it('closes the delete dialog after deleting and keeps it closed', async () => {
const user = userEvent.setup()
const alpha = createJob(1, 'Alpha')
const beta = createJob(2, 'Beta')
store.deleteMutate.mockImplementation((_args: unknown, options: { onSuccess: () => void }) => {
store.setJobs?.([alpha])
options.onSuccess()
})
const { rerender } = renderContent([alpha, beta], '/repos/1/schedules?jobId=2')
await user.click(screen.getByRole('button', { name: 'delete Beta' }))
await user.click(screen.getByRole('button', { name: 'Delete' }))
expect(screen.getByTestId('search').textContent).not.toContain('scheduleDialog')
expect(screen.queryByRole('dialog')).toBeNull()
rerender(
<MemoryRouter initialEntries={['/repos/1/schedules?jobId=2']}>
<Harness initialJobs={[alpha, beta]} />
</MemoryRouter>,
)
act(() => { store.setJobs?.([alpha]) })
expect(screen.getByTestId('search').textContent).not.toContain('scheduleDialog')
expect(screen.queryByRole('dialog')).toBeNull()
})
it('closes the New schedule dialog after creating the first schedule', async () => {
const user = userEvent.setup()
const created = createJob(4, 'Gamma')
store.createMutate.mockImplementation((_args: unknown, options: { onSuccess: (job: ScheduleJob) => void }) => {
store.setJobs?.([created])
options.onSuccess(created)
})
renderContent([], '/repos/1/schedules')
await user.click(screen.getByRole('button', { name: 'Create First Schedule' }))
expect(screen.getByRole('button', { name: 'submit schedule' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'submit schedule' }))
expect(screen.getByTestId('search').textContent).not.toContain('scheduleDialog')
expect(screen.getByTestId('search').textContent).toContain('jobId=4')
expect(screen.queryByRole('button', { name: 'submit schedule' })).toBeNull()
})
})
@@ -101,14 +101,22 @@ export function RepoSchedulesContent({ repoId, embedded }: RepoSchedulesContentP
[dialog, jobId, jobs],
)
const deleteJob = useMemo<ScheduleJob | undefined>(
() => (dialog === 'delete' && jobId !== null ? jobs?.find((j) => j.id === jobId) : undefined),
[dialog, jobId, jobs],
)
useEffect(() => {
if (jobs === undefined) return
const dialogNeedsJob = dialog === 'edit' || dialog === 'delete'
if (!jobs.length) {
if (jobId !== null || scheduleTab !== 'jobs') {
if (jobId !== null || scheduleTab !== 'jobs' || dialogNeedsJob) {
replaceUrlParams((p) => {
p.delete('jobId')
p.delete('scheduleTab')
if (dialogNeedsJob) p.delete('scheduleDialog')
})
}
return
@@ -117,15 +125,16 @@ export function RepoSchedulesContent({ repoId, embedded }: RepoSchedulesContentP
const stillExists = jobId !== null && jobs.some((job) => job.id === jobId)
if (!stillExists) {
const newId = jobs[0]?.id ?? null
if (newId !== jobId || scheduleTab !== 'jobs') {
if (newId !== jobId || scheduleTab !== 'jobs' || dialogNeedsJob) {
replaceUrlParams((p) => {
if (newId === null) p.delete('jobId')
else p.set('jobId', String(newId))
p.delete('scheduleTab')
if (dialogNeedsJob) p.delete('scheduleDialog')
})
}
}
}, [jobs, jobId, scheduleTab, replaceUrlParams])
}, [jobs, jobId, scheduleTab, dialog, replaceUrlParams])
useEffect(() => {
if (runs === undefined) return
@@ -170,7 +179,7 @@ export function RepoSchedulesContent({ repoId, embedded }: RepoSchedulesContentP
}
const handleDelete = () => {
if (dialog !== 'delete' || jobId === null) {
if (dialog !== 'delete' || jobId === null || deleteJob === undefined) {
return
}
@@ -357,6 +366,7 @@ export function RepoSchedulesContent({ repoId, embedded }: RepoSchedulesContentP
onCancel={() => closeDialog()}
title="Delete Schedule"
description={DELETE_SCHEDULE_DESCRIPTION}
itemName={deleteJob?.name}
isDeleting={deleteMutation.isPending}
/>
@@ -132,6 +132,50 @@ describe('ScheduleJobDialog — permission config', () => {
expect(getAllowQuestionsSwitch()).not.toBeChecked()
})
it('names each form switch after its visible label', async () => {
const user = userEvent.setup()
render(
<ScheduleJobDialog
open
onOpenChange={vi.fn()}
onSubmit={vi.fn()}
isSaving={false}
/>,
{ wrapper: createWrapper() },
)
await navigateToGeneralTab(user)
expect(screen.getByRole('switch', { name: 'Enabled' })).toBeInTheDocument()
expect(
screen.getByRole('switch', { name: 'Allow access outside the working directory' }),
).toBeInTheDocument()
expect(screen.getByRole('switch', { name: 'Allow questions' })).toBeInTheDocument()
})
it('names the missing required fields while Create schedule is disabled', async () => {
const user = userEvent.setup()
render(
<ScheduleJobDialog
open
onOpenChange={vi.fn()}
onSubmit={vi.fn()}
isSaving={false}
/>,
{ wrapper: createWrapper() },
)
expect(screen.getByRole('button', { name: 'Create schedule' })).toBeDisabled()
expect(screen.getByText('Required: name, prompt')).toBeInTheDocument()
await user.type(screen.getByLabelText('Name'), 'Test Job')
expect(screen.getByText('Required: prompt')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Create schedule' })).toBeDisabled()
})
it('initializes permission config from an existing job', async () => {
const onSubmit = vi.fn()
const onOpenChange = vi.fn()
@@ -263,6 +263,13 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
((schedulePreset === 'daily' || schedulePreset === 'weekdays' || schedulePreset === 'weekly' || schedulePreset === 'monthly') && !timezone.trim()) ||
(schedulePreset === 'weekly' && weeklyDays.length === 0)
const missingRequirements = [
name.trim() ? null : 'name',
prompt.trim() ? null : 'prompt',
isScheduleConfigInvalid ? 'valid timing' : null,
showRepoSelector && !job && selectedRepoId === undefined ? 'repository' : null,
].filter((requirement): requirement is string => requirement !== null)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
@@ -368,9 +375,19 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
/>
</Tabs>
<div className="mt-0 shrink-0 border-t border-border px-3 sm:px-6 py-4 flex flex-row gap-2 sm:justify-end">
<div className="mt-0 shrink-0 border-t border-border px-3 sm:px-6 py-4 flex flex-row flex-wrap items-center gap-2 sm:justify-end">
{missingRequirements.length > 0 ? (
<p id="schedule-requirements" className="order-last w-full text-xs text-muted-foreground sm:order-first sm:mr-auto sm:w-auto">
Required: {missingRequirements.join(', ')}
</p>
) : null}
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving} className="flex-1 sm:flex-none">Cancel</Button>
<Button onClick={handleSubmit} disabled={isSaving || !name.trim() || !prompt.trim() || isScheduleConfigInvalid || (!!showRepoSelector && !job && selectedRepoId === undefined)} className="flex-1 sm:flex-none">
<Button
onClick={handleSubmit}
disabled={isSaving || missingRequirements.length > 0}
aria-describedby={missingRequirements.length > 0 ? 'schedule-requirements' : undefined}
className="flex-1 sm:flex-none"
>
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
{isSaving ? 'Saving...' : job ? 'Save changes' : 'Create schedule'}
</Button>
@@ -46,7 +46,7 @@ const generatingWalkthrough: ChangeWalkthrough = {
}
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return { walkthrough, currentDiffHash: 'hash-1', stale: false, generating: false, running: false, error: null, ...overrides }
return { walkthrough, currentDiffHash: 'hash-1', hasChanges: true, stale: false, generating: false, running: false, error: null, ...overrides }
}
function createWrapper() {
@@ -490,6 +490,37 @@ describe('ChangesWalkthroughSheet', () => {
expect(screen.getByRole('button', { name: 'Generate walkthrough' })).toBeEnabled()
})
it('shows an upfront empty state when the session has no changes', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(
state({ walkthrough: null, currentDiffHash: 'e3b0c44298fc1c149afbf4c8996fb924', hasChanges: false }),
)
renderSheet()
expect(await screen.findByText('No changes in this session')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
})
it('hides the refine form until a walkthrough is published', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
status: 'failed',
artifactPath: null,
publishedAt: null,
error: { message: 'The walkthrough session did not publish within 15 minutes', code: 'WALKTHROUGH_TIMEOUT' },
},
error: { message: 'The walkthrough session did not publish within 15 minutes', code: 'WALKTHROUGH_TIMEOUT' },
}),
)
renderSheet()
expect(
await screen.findByText('The walkthrough session did not publish within 15 minutes'),
).toBeInTheDocument()
expect(screen.queryByLabelText('Refine walkthrough')).not.toBeInTheDocument()
})
it.each([
['WALKTHROUGH_NO_CHANGES', 'This session has no changes to walk through', 'This session has no changes to walk through'],
['WALKTHROUGH_NO_CHANGES', 'The staged changes contain no changes to walk through', 'The staged changes contain no changes to walk through'],
@@ -49,6 +49,7 @@ function walkthroughErrorMessage(error: unknown): string {
interface ChangesWalkthroughContextValue {
isLoading: boolean
walkthrough: ChangeWalkthrough | null
hasChanges: boolean
stale: boolean
generating: boolean
running: boolean
@@ -239,6 +240,7 @@ export function ChangesWalkthroughProvider({
const value: ChangesWalkthroughContextValue = {
isLoading: stateQuery.isLoading,
walkthrough,
hasChanges: state?.hasChanges ?? true,
stale,
generating,
running,
@@ -309,6 +311,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
const {
isLoading,
walkthrough,
hasChanges,
stale,
generating,
running,
@@ -325,6 +328,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
const artifactPath = walkthrough?.artifactPath ?? null
const published = walkthrough?.publishedAt != null && artifactPath !== null
const noChanges = !hasChanges && !generating && !published
const artifactUrl = artifactPath === null ? null : getFileApiUrl(artifactPath, { params: { raw: true } })
const walkthroughSessionId = walkthrough?.walkthroughSessionId ?? null
@@ -346,7 +350,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
<WalkthroughSourceInputs />
{error ? <p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p> : null}
{error && !noChanges ? <p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p> : null}
{stale && !generating ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2">
@@ -367,12 +371,23 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
) : null}
{!isLoading && !walkthrough && !generating ? (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Build an interactive walkthrough of {describeWalkthroughSource(source)}.
</p>
<Button onClick={generate}>Generate walkthrough</Button>
</div>
noChanges ? (
<div className="space-y-1">
<p className="text-sm font-medium text-foreground">
{source.kind === 'session' ? 'No changes in this session' : 'No changes to walk through'}
</p>
<p className="text-sm text-muted-foreground">
A walkthrough covers changed files. Change something, then generate one.
</p>
</div>
) : (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Build an interactive walkthrough of {describeWalkthroughSource(source)}.
</p>
<Button onClick={generate}>Generate walkthrough</Button>
</div>
)
) : null}
{generating && !published ? (
@@ -426,7 +441,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
</div>
) : null}
{walkthroughSessionId && !generating && !running ? (
{published && walkthroughSessionId && !generating && !running ? (
<form
className="space-y-2"
onSubmit={(event) => {
@@ -41,7 +41,7 @@ describe('PermissionModeToggle', () => {
mockHooks()
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
expect(screen.getByRole('button', { name: 'Permissions: ask every time' })).toBeEnabled()
expect(screen.getByRole('button', { name: 'Permissions: follow configured rules' })).toBeEnabled()
})
it('switches to accept-everything with the directory when clicked', async () => {
@@ -50,7 +50,7 @@ describe('PermissionModeToggle', () => {
mockHooks({ mutate })
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
await user.click(screen.getByRole('button', { name: 'Permissions: ask every time' }))
await user.click(screen.getByRole('button', { name: 'Permissions: follow configured rules' }))
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'auto' })
})
@@ -61,7 +61,7 @@ describe('PermissionModeToggle', () => {
mockHooks({ state: { mode: 'auto' }, mutate })
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
await user.click(screen.getByRole('button', { name: 'Permissions: accept everything' }))
await user.click(screen.getByRole('button', { name: 'Permissions: auto-accept all' }))
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'ask' })
})
@@ -114,7 +114,7 @@ describe('PermissionModeToggle', () => {
mockHooks({ data: { ...baseState, mode: 'auto' }, mutate })
render(<PermissionModeToggle sessionID="ses_1" directory="/repo" />)
await user.click(screen.getByRole('button', { name: 'Permissions: accept everything' }))
await user.click(screen.getByRole('button', { name: 'Permissions: auto-accept all' }))
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'ask' })
})
@@ -123,6 +123,14 @@ describe('PermissionRequestDialog', () => {
expect(screen.queryByRole('button', { name: 'Open session' })).not.toBeInTheDocument()
})
it('focuses the allow action instead of the optional reason field', async () => {
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />)
const allowOnce = screen.getByRole('button', { name: 'Allow Once' })
await waitFor(() => expect(allowOnce).toHaveFocus())
expect(screen.getByLabelText('Reason (optional)')).not.toHaveFocus()
})
it('replies with the selected decision for the permission request', async () => {
const onRespond = vi.fn().mockResolvedValue(undefined)
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
@@ -1,4 +1,4 @@
import { useEffect, useId, useState } from 'react'
import { useEffect, useId, useRef, useState } from 'react'
import {
Dialog,
DialogContent,
@@ -51,6 +51,7 @@ export function PermissionRequestDialog({
const [loadingAction, setLoadingAction] = useState<PermissionResponse | null>(null)
const [rejectReason, setRejectReason] = useState('')
const reasonInputId = useId()
const allowOnceRef = useRef<HTMLButtonElement>(null)
useEffect(() => {
setRejectReason('')
@@ -81,7 +82,13 @@ export function PermissionRequestDialog({
return (
<Dialog open={parentOpen ?? true} onOpenChange={onOpenChange ?? (() => {})}>
<DialogContent className="max-w-[calc(100vw-2rem)] sm:max-w-md p-4 sm:p-6">
<DialogContent
className="max-w-[calc(100vw-2rem)] sm:max-w-md p-4 sm:p-6"
onOpenAutoFocus={(event) => {
event.preventDefault()
allowOnceRef.current?.focus()
}}
>
<DialogHeader>
<DialogTitle className="flex items-center gap-2 flex-wrap">
<span>Permission Request</span>
@@ -215,6 +222,7 @@ export function PermissionRequestDialog({
variant="default"
onClick={() => handleResponse('once')}
disabled={isLoading}
ref={allowOnceRef}
className={cn(
"w-full sm:flex-1 text-sm h-9 sm:h-10",
loadingAction === 'once' && "opacity-70"
@@ -58,6 +58,10 @@ vi.mock('@/hooks/useSessionPins', () => ({
useToggleSessionPin: () => ({ mutate: togglePinMock }),
}))
vi.mock('@/hooks/useChangeWalkthrough', () => ({
useWalkthroughHelperSessionIds: () => new Set<string>(),
}))
describe('SessionList', () => {
beforeEach(() => {
sessionsData.splice(0, sessionsData.length,
@@ -164,7 +164,7 @@ export function AccountSettings() {
<CardTitle className="text-base sm:text-lg">Profile</CardTitle>
</div>
{!editingProfile && (
<Button variant="ghost" size="sm" onClick={() => setEditingProfile(true)} className="h-8">
<Button variant="ghost" size="sm" onClick={() => setEditingProfile(true)} aria-label="Edit profile" className="h-8">
<Edit2 className="h-3.5 w-3.5" />
</Button>
)}
@@ -229,6 +229,24 @@ describe('GitSettings draft preservation', () => {
await waitFor(() => expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['repoGitIdentity'] }))
})
it('blocks saving and shows an inline error for an invalid identity email', async () => {
const user = userEvent.setup()
setupServer(buildPreferences())
renderGitSettings()
const emailInput = await screen.findByLabelText('Email', { selector: 'input#git-email' })
await user.type(emailInput, 'not-an-email')
expect(emailInput).toHaveAttribute('aria-invalid', 'true')
expect(screen.getByText('Enter a valid email address')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /save changes/i }))
expect(updateSettingsMock).not.toHaveBeenCalled()
expect(showToastMock.success).not.toHaveBeenCalled()
expect(emailInput).toHaveValue('not-an-email')
})
it('retains identity drafts when saving fails', async () => {
const user = userEvent.setup()
setupServer(buildPreferences())
@@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { randomId } from '@/lib/utils'
import type { GitCredential, GitIdentity, GitIdentityProfile, UserPreferences } from '@/api/types/settings'
import { isValidGitIdentityEmail } from '@opencode-manager/shared'
import { listRepos, updateRepoGitCredential } from '@/api/repos'
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
@@ -191,6 +192,9 @@ export function GitSettings() {
}
const saveAll = async () => {
if (![gitIdentity, ...gitIdentities].every((identity) => isValidGitIdentityEmail(identity.email))) {
return
}
setIsSaving(true)
try {
showToast.loading('Saving git configuration...', { id: 'git-config' })
@@ -265,7 +269,7 @@ export function GitSettings() {
value={gitIdentity.name}
onChange={(e) => updateIdentity('name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
className="bg-background border-border text-foreground placeholder:text-placeholder"
/>
</div>
<div className="space-y-2">
@@ -277,8 +281,13 @@ export function GitSettings() {
value={gitIdentity.email}
onChange={(e) => updateIdentity('email', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
aria-invalid={!isValidGitIdentityEmail(gitIdentity.email)}
aria-describedby={!isValidGitIdentityEmail(gitIdentity.email) ? 'git-email-error' : undefined}
className="bg-background border-border text-foreground placeholder:text-placeholder"
/>
{!isValidGitIdentityEmail(gitIdentity.email) && (
<p id="git-email-error" className="text-xs text-destructive">Enter a valid email address</p>
)}
</div>
</div>
</div>
@@ -439,7 +448,7 @@ export function GitSettings() {
value={identity.name}
onChange={(e) => updateSavedIdentity(index, 'name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
className="bg-background border-border text-foreground placeholder:text-placeholder"
/>
</div>
<div className="space-y-2">
@@ -451,8 +460,13 @@ export function GitSettings() {
value={identity.email}
onChange={(e) => updateSavedIdentity(index, 'email', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
aria-invalid={!isValidGitIdentityEmail(identity.email)}
aria-describedby={!isValidGitIdentityEmail(identity.email) ? `git-identity-${index}-email-error` : undefined}
className="bg-background border-border text-foreground placeholder:text-placeholder"
/>
{!isValidGitIdentityEmail(identity.email) && (
<p id={`git-identity-${index}-email-error`} className="text-xs text-destructive">Enter a valid email address</p>
)}
</div>
</div>
</div>
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, within, waitFor } from '@testing-library/react'
import { KeyboardShortcuts } from './KeyboardShortcuts'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
const { updateSettings, parseTuiKeybindConfig, applyTuiKeybindImport, showToast } = vi.hoisted(() => ({
@@ -18,7 +19,10 @@ const { updateSettings, parseTuiKeybindConfig, applyTuiKeybindImport, showToast
},
}))
vi.mock('@/hooks/useMobile', () => ({ useMobile: () => false }))
vi.mock('@/hooks/useMobile', () => ({
useMobile: () => false,
useSwipeBack: () => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} }),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: () => ({
preferences: { keyboardShortcuts: { customAction: 'Alt+J' } },
@@ -26,7 +30,10 @@ vi.mock('@/hooks/useSettings', () => ({
updateSettings,
}),
}))
vi.mock('@/lib/tuiKeybindImport', () => ({ parseTuiKeybindConfig, applyTuiKeybindImport }))
vi.mock('@/lib/tuiKeybindImport', async () => {
const actual = await vi.importActual<typeof import('@/lib/tuiKeybindImport')>('@/lib/tuiKeybindImport')
return { parseTuiKeybindConfig, applyTuiKeybindImport, applyRecordedShortcut: actual.applyRecordedShortcut }
})
vi.mock('@/lib/toast', () => ({ showToast }))
const getFileInput = (container: HTMLElement) => {
@@ -95,6 +102,69 @@ describe('KeyboardShortcuts layout', () => {
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: expect.objectContaining({ customAction: '' }) })
expect(within(row).getByRole('button', { name: 'Not set' })).toBeInTheDocument()
})
it('cancels recording on Escape without saving a binding', () => {
render(<KeyboardShortcuts />)
fireEvent.click(screen.getByRole('button', { name: /Alt\+J/ }))
const input = screen.getByPlaceholderText('Press keys...')
expect(fireEvent.keyDown(input, { key: 'Escape' })).toBe(false)
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
expect(updateSettings).not.toHaveBeenCalled()
})
it('cancels recording a leader key on Escape without binding Escape as the leader', () => {
render(<KeyboardShortcuts />)
fireEvent.click(screen.getByRole('button', { name: DEFAULT_LEADER_KEY }))
const input = screen.getByPlaceholderText('Press keys...')
fireEvent.keyDown(input, { key: 'Escape' })
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
expect(updateSettings).not.toHaveBeenCalled()
})
it('keeps an open Radix dialog open when Escape cancels recording', () => {
const onOpenChange = vi.fn()
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent>
<DialogTitle>Settings</DialogTitle>
<KeyboardShortcuts />
</DialogContent>
</Dialog>,
)
fireEvent.click(screen.getByRole('button', { name: /Alt\+J/ }))
fireEvent.keyDown(screen.getByPlaceholderText('Press keys...'), { key: 'Escape' })
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
expect(updateSettings).not.toHaveBeenCalled()
expect(onOpenChange).not.toHaveBeenCalledWith(false)
})
it('unbinds the action already using the recorded binding and names it in a toast', () => {
render(<KeyboardShortcuts />)
fireEvent.click(screen.getByRole('button', { name: /Alt\+J/ }))
fireEvent.keyDown(screen.getByPlaceholderText('Press keys...'), { key: 't', ctrlKey: true })
expect(updateSettings).toHaveBeenCalledWith({
keyboardShortcuts: expect.objectContaining({ customAction: 'Ctrl+T', variantCycle: '' }),
directShortcuts: [...DEFAULT_DIRECT_SHORTCUTS, 'customAction'],
})
expect(showToast.info).toHaveBeenCalledWith('Shortcut conflict resolved', {
description: 'Unbound to avoid conflicts: variant cycle',
})
})
it('resets custom shortcuts and the leader key to the defaults', () => {
render(<KeyboardShortcuts />)
fireEvent.click(screen.getByRole('button', { name: 'Reset to defaults' }))
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: {}, directShortcuts: [], leaderKey: '' })
expect(showToast.success).toHaveBeenCalledWith('Keyboard shortcuts reset to defaults')
})
})
describe('KeyboardShortcuts TUI import', () => {
@@ -4,7 +4,7 @@ import { useMobile } from '@/hooks/useMobile'
import { Loader2, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { formatEventModifiers, formatShortcutEvent, formatShortcutLabel, isModifierOnlyEvent, normalizeShortcut, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
import { applyRecordedShortcut, applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
import { showToast } from '@/lib/toast'
const CONVERSATION_ACTIONS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'timeline', 'exportSession', 'selectModel', 'variantCycle', 'favoriteCycle', 'halfPageUp', 'halfPageDown', 'speakVisible']
@@ -180,6 +180,14 @@ export function KeyboardShortcuts() {
})
}, [])
const resetShortcuts = () => {
stopRecording()
setTempShortcuts({})
setTempLeaderKey(null)
updateSettings({ keyboardShortcuts: {}, directShortcuts: [], leaderKey: '' })
showToast.success('Keyboard shortcuts reset to defaults')
}
useEffect(() => {
if (!recordingKey && !recordingLeader) return
@@ -190,6 +198,11 @@ export function KeyboardShortcuts() {
e.preventDefault()
e.stopPropagation()
if (e.key === 'Escape') {
stopRecording()
return
}
const shortcut = formatShortcutEvent(e)
if (!shortcut) {
setCurrentKeys(leaderPrefix() + formatEventModifiers(e))
@@ -212,14 +225,22 @@ export function KeyboardShortcuts() {
return
}
const otherDirectShortcuts = directShortcutsRef.current.filter((action) => action !== recordingKey)
setTempShortcuts(prev => ({ ...prev, [recordingKey]: shortcut }))
const applied = applyRecordedShortcut(recordingKey, shortcut, leaderPressed, {
keyboardShortcuts: shortcutsRef.current,
directShortcuts: directShortcutsRef.current,
})
setTempShortcuts(applied.keyboardShortcuts)
setRecordingKey(null)
setCurrentKeys('')
updateSettingsRef.current({
keyboardShortcuts: { ...shortcutsRef.current, [recordingKey]: shortcut },
directShortcuts: leaderPressed ? otherDirectShortcuts : [...otherDirectShortcuts, recordingKey],
keyboardShortcuts: applied.keyboardShortcuts,
directShortcuts: applied.directShortcuts,
})
if (applied.cleared.length > 0) {
showToast.info('Shortcut conflict resolved', {
description: `Unbound to avoid conflicts: ${applied.cleared.map((action) => formatActionLabel(action).toLowerCase()).join(', ')}`,
})
}
}
const handleKeyUp = (e: KeyboardEvent) => {
@@ -228,13 +249,13 @@ export function KeyboardShortcuts() {
}
}
document.addEventListener('keydown', handleKeyDown, true)
document.addEventListener('keyup', handleKeyUp)
window.addEventListener('keydown', handleKeyDown, true)
window.addEventListener('keyup', handleKeyUp)
return () => {
document.removeEventListener('keydown', handleKeyDown, true)
document.removeEventListener('keyup', handleKeyUp)
window.removeEventListener('keydown', handleKeyDown, true)
window.removeEventListener('keyup', handleKeyUp)
}
}, [recordingKey, recordingLeader])
}, [recordingKey, recordingLeader, stopRecording])
if (isLoading) {
return (
@@ -321,9 +342,14 @@ export function KeyboardShortcuts() {
<h2 className="text-lg font-semibold text-foreground">Keyboard Shortcuts</h2>
<div className="flex flex-col items-end gap-1">
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
Import from OpenCode TUI
</Button>
<div className="flex flex-wrap justify-end gap-2">
<Button variant="outline" size="sm" onClick={resetShortcuts}>
Reset to defaults
</Button>
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
Import from OpenCode TUI
</Button>
</div>
<input
ref={fileInputRef}
type="file"
@@ -57,6 +57,7 @@ export function ManagerTokenSettings({ isOpen: controlledOpen, onToggle }: Manag
type="button"
onClick={() => setShowToken(!showToken)}
disabled={!token}
aria-label={showToken ? 'Hide token' : 'Show token'}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{showToken ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
@@ -73,6 +74,8 @@ export function ManagerTokenSettings({ isOpen: controlledOpen, onToggle }: Manag
type="button"
onClick={handleRotate}
disabled={rotate.isPending || isLoading}
aria-label="Rotate token"
title="Rotate token"
>
<RefreshCw className={`h-4 w-4 ${rotate.isPending ? 'animate-spin' : ''}`} />
</Button>
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more