feat(cli): add --cwd flag to web and serve commands
Summary
The opencode web and opencode serve commands did not preserve the working directory, causing process.cwd() to return an unexpected value (often /) when the server handles requests. This resulted in sessions being created with worktree: "/" instead of the intended project directory.
Changes
- Added
--cwdflag to bothwebandservecommands - Commands now call
process.chdir()before starting the server, following the same pattern used by the TUI command (thread.ts)
Testing
- Typecheck passes
- Manual verification:
--cwdoption appears in--helpoutput for both commands
Root Cause
The server middleware in server.ts (line 249) determines the directory per-request:
const directory = c.req.query("directory") || c.req.header("x-opencode-directory") || process.cwd()
Unlike the TUI command which calls process.chdir(cwd) before starting, the web and serve commands did not set the working directory, causing the fallback to process.cwd() to return an unintended value.
The following comment was made by an LLM, it may be inaccurate:
Duplicate PR Check Results
No duplicate PRs found. ✓
The search returned only PR #7011 (the current PR) when searching for variations of the --cwd flag, working directory handling, and server middleware patterns.
Two related but distinct PRs were found that address similar directory/path issues in different contexts:
-
PR #6963:
fix(desktop): desktop won't read project scope commands/skills- Different issue (desktop scope) -
PR #6413:
fix: pass --dir parameter from attach command to server- Different command and parameter name
These are not duplicates of the current PR as they address different problems in different parts of the codebase.