Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Make the Shell page's "cd to app" picker work on Windows

[._.]/ Adam Eivyb895fbf07ca9
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index b1316ca1b5..7bc004a519 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -76,7 +76,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |
-| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. |
+| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. |
| `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |
| `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. |
| `usePrevious` | Returns the value from the previous render — snapshot updated in a `useEffect`. | Compare-and-act on prop/state change from inside a `useEffect`. |
diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.js
index 9fb25cf4f1..b2f9609728 100644
--- a/client/src/hooks/useShellSession.js
+++ b/client/src/hooks/useShellSession.js
@@ -157,20 +157,27 @@ export function useShellSession({ isFullscreen } = {}) {
}
}, []);
+ // The one place a shell:* event addressed at the ACTIVE session goes out, so the
+ // mid-attach guard can't be applied to one sender and forgotten on the next.
// focus:false skips returning keyboard focus to the terminal after sending — used by
// the nav-key hot buttons so repeated arrow taps on touch devices don't keep re-summoning
// the on-screen keyboard (input is delivered over the socket regardless of focus).
- // Returns whether the data actually went out — the dictation bridge needs to know,
+ // Returns whether the payload actually went out — the dictation bridge needs to know,
// since it tracks what the PTY has received to compute its next correction.
- const emitShellInput = useCallback((data, { focus = true } = {}) => {
+ const emitToSession = useCallback((event, payload, { focus = true } = {}) => {
if (!socket || !sessionIdRef.current) return false;
// Don't fire quick-commands into the prior session while a switch/start is mid-flight.
if (pendingAttachRef.current.target) return false;
- socket.emit('shell:input', { sessionId: sessionIdRef.current, data });
+ socket.emit(event, { sessionId: sessionIdRef.current, ...payload });
if (focus) termInstanceRef.current?.focus();
return true;
}, [socket]);
+ const emitShellInput = useCallback(
+ (data, opts) => emitToSession('shell:input', { data }, opts),
+ [emitToSession]
+ );
+
// Send a photo (plus an optional message) to whatever is running in the active
// session — the point being a live `claude`/`codex` TUI, which reads images off
// disk. This one goes over HTTP, not the `shell:*` socket protocol: socket.io's
@@ -213,6 +220,9 @@ export function useShellSession({ isFullscreen } = {}) {
}, []);
const sendCommand = useCallback((cmd) => emitShellInput(cmd + '\n'), [emitShellInput]);
+ // cd is the one "command" the client does NOT compose itself: it sends the folder and
+ // the server renders the `cd` for the session's actual shell (server/lib/shellCd.js).
+ const sendCd = useCallback((path) => emitToSession('shell:cd', { path }), [emitToSession]);
const sendCtrlB = useCallback(() => emitShellInput('\x02'), [emitShellInput]);
const sendCtrlC = useCallback(() => emitShellInput('\x03'), [emitShellInput]);
// Arrow keys send CSI or SS3 based on the terminal's DECCKM state (see NAV_KEYS);
@@ -878,6 +888,7 @@ export function useShellSession({ isFullscreen } = {}) {
emitShellInput,
sendImage,
sendCommand,
+ sendCd,
sendCtrlB,
sendCtrlC,
sendNavKey,
diff --git a/client/src/hooks/useShellSession.test.jsx b/client/src/hooks/useShellSession.test.jsx
index 2b2c8abbef..2cda93b68c 100644
--- a/client/src/hooks/useShellSession.test.jsx
+++ b/client/src/hooks/useShellSession.test.jsx
@@ -80,6 +80,17 @@ describe('useShellSession', () => {
expect(lastEmit('shell:input')).toEqual(['shell:input', { sessionId: 'abc', data: '\x02' }]);
});
+ // cd goes over its own event carrying the PATH — the server owns the quoting,
+ // because only it knows whether the session runs cmd.exe, PowerShell, or a
+ // POSIX shell (the hard-coded POSIX form was unusable on Windows).
+ it('sends the folder path over shell:cd rather than composing a cd command', () => {
+ const { result } = renderHook(() => useShellSession({}), { wrapper });
+ fire('shell:sessions', []);
+ fire('shell:started', { sessionId: 'abc' });
+ act(() => result.current.sendCd('I:\\code\\example-app'));
+ expect(lastEmit('shell:cd')).toEqual(['shell:cd', { sessionId: 'abc', path: 'I:\\code\\example-app' }]);
+ });
+
it('ignores a shell:attached whose id does not match the pending target (strict-equality guard)', () => {
const { result } = renderHook(() => useShellSession({}), { wrapper });
// First load with one free survivor → auto-attach to s1 (claim:true), pending target 's1'.
diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsx
index 6c92fa2e27..e986dea61a 100644
--- a/client/src/pages/Shell.jsx
+++ b/client/src/pages/Shell.jsx
@@ -42,6 +42,7 @@ export default function Shell() {
emitShellInput,
sendImage,
sendCommand,
+ sendCd,
sendCtrlB,
sendCtrlC,
sendNavKey,
@@ -247,7 +248,7 @@ export default function Shell() {
<button
key={name}
onClick={() => {
- sendCommand(`cd '${path.replace(/'/g, "'\\''")}'`);
+ sendCd(path);
setFolderDropdownOpen(false);
}}
className="w-full text-left px-3 py-2 text-xs font-mono text-gray-300 hover:bg-port-border hover:text-white transition-colors"
diff --git a/docs/API.md b/docs/API.md
index 27f7597626..e679c2fb0d 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -685,22 +685,27 @@ socket.on('detect:complete', (appData) => {
> **Security**: The shell WebSocket API provides full terminal access as the PortOS process user. It relies on PortOS's network-level access control (see [Security Model](#security-model)) — do not expose the PortOS server to untrusted networks.
```javascript
-// Start a shell session
-socket.emit('shell:start', { id: 'my-session' });
+// Start a shell session — the server assigns the id and replies with shell:started
+socket.emit('shell:start', {});
+socket.on('shell:started', ({ sessionId }) => console.log('session', sessionId));
// Send input to shell
-socket.emit('shell:input', { id: 'my-session', data: 'ls -la\n' });
+socket.emit('shell:input', { sessionId, data: 'ls -la\n' });
// Receive shell output
-socket.on('shell:output', ({ id, data }) => {
+socket.on('shell:output', ({ sessionId, data }) => {
console.log(data); // Terminal output
});
+// Change directory — send the PATH, not a command. The server renders the `cd` for
+// the shell this session runs (`cd /d "…"` on cmd.exe, Set-Location on PowerShell).
+socket.emit('shell:cd', { sessionId, path: '/path/to/app' });
+
// Resize terminal
-socket.emit('shell:resize', { id: 'my-session', cols: 120, rows: 40 });
+socket.emit('shell:resize', { sessionId, cols: 120, rows: 40 });
// Stop shell session
-socket.emit('shell:stop', { id: 'my-session' });
+socket.emit('shell:stop', { sessionId });
```
### Provider Status
diff --git a/server/lib/README.md b/server/lib/README.md
index 337c919233..993aca0d56 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -369,6 +369,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
| `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. |
| `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOwnsPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. |
+| `shellCd.js` | `buildCdCommand(path, shell)` + `detectShellFlavor(shell, platform?)` — build a `cd` line for the shell a PTY session is ACTUALLY running (`cmd.exe` → `cd /d "…"`, PowerShell → `Set-Location -LiteralPath '…'`, everything else → POSIX `cd '…'` via `shellQuote`). The Shell page's "cd to app" picker used to hard-code the POSIX form, which on Windows both mis-quoted the path and silently refused to cross drives (a bare `cd` does not switch drive). Flavor comes from the shell binary name, not the platform, so git-bash on Windows still gets POSIX quoting. |
| `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. |
| `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). |
| `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so a filed-issue/printed-report run retains its non-code deliverable posture). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. Mirrored in `client/src/lib/slashdoCatalog.js` (button styling only), pinned by `slashdoCatalog.test.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 10781f2f10..673dfa7e2b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -346,6 +346,7 @@ export * from './mirrorParity.js';
export * from './objects.js';
export * from './openapiSpec.js';
export * from './prDisposition.js';
+export * from './shellCd.js';
export * from './shellQuote.js';
export * from './sidecarProcess.js';
export * from './slashdoCatalog.js';
diff --git a/server/lib/shellCd.js b/server/lib/shellCd.js
new file mode 100644
index 0000000000..06dad43cb3
--- /dev/null
+++ b/server/lib/shellCd.js
@@ -0,0 +1,67 @@
+/**
+ * Build a `cd` command line for the shell a PTY session is actually running.
+ *
+ * The Shell page's "cd to app" picker used to send a hard-coded POSIX
+ * `cd '<path>'` to every session. On Windows that fails twice over, because the
+ * default shell is `cmd.exe` (`COMSPEC`):
+ *
+ * 1. `cmd.exe` has no single-quote quoting — the quotes become part of the
+ * path, so every managed-app folder answered
+ * "The filename, directory name, or volume label syntax is incorrect."
+ * 2. Even correctly quoted, a bare `cd` does NOT switch drives. A session
+ * started in `C:\Users\…` stays there when told to `cd "I:\code\app"`;
+ * `cd /d` is required.
+ *
+ * So the command is built from the session's real shell binary rather than
+ * assumed. Flavors:
+ *
+ * • `cmd` → `cd /d "<path>"` (double quotes, /d)
+ * • `powershell` → `Set-Location -LiteralPath '<path>'` (doubled `'`; crosses
+ * drives on its own, and -LiteralPath skips glob expansion
+ * so a `[` in a folder name still resolves)
+ * • `posix` → `cd '<path>'` (shellQuote)
+ *
+ * A Windows host running a POSIX shell (git-bash `bash.exe`) is detected by the
+ * binary name, not the platform, so it keeps POSIX quoting — MSYS translates the
+ * Win32 path at the syscall layer.
+ */
+import { win32 } from 'path';
+import { shellQuote } from './shellQuote.js';
+
+/**
+ * Which quoting dialect does this shell speak?
+ *
+ * @param {string} [shell] - the spawned shell binary (path or bare name)
+ * @param {string} [platform] - `process.platform` value; only consulted when the shell is unknown
+ * @returns {'cmd'|'powershell'|'posix'}
+ */
+export function detectShellFlavor(shell, platform = process.platform) {
+ // win32.basename splits on `/` AND `\` on every host, so it reads a Windows
+ // shell path correctly even when PortOS itself is running on macOS/Linux.
+ const bin = win32.basename(String(shell ?? '')).toLowerCase().replace(/\.exe$/, '');
+ if (bin === 'cmd') return 'cmd';
+ if (bin === 'powershell' || bin === 'pwsh') return 'powershell';
+ if (bin) return 'posix';
+ // No shell recorded — an externally-registered session (a CoS agent's TUI run)
+ // hands us its PTY without one. Fall back to the platform default, which is
+ // what getDefaultShell() spawned for it.
+ return platform === 'win32' ? 'cmd' : 'posix';
+}
+
+/**
+ * @param {string} dirPath - directory to change into
+ * @param {string} [shell] - the session's shell binary; see detectShellFlavor
+ * @returns {string} a single command line, no trailing newline
+ */
+export function buildCdCommand(dirPath, shell) {
+ // Control characters are stripped, not escaped: a newline would end the `cd`
+ // line and run the rest as its own command, and no directory name has one.
+ const path = String(dirPath ?? '').replace(/[\u0000-\u001f\u007f]/g, '');
+ switch (detectShellFlavor(shell)) {
+ // cmd.exe has no escape for `"` inside a quoted token, and a Windows path
+ // can't contain one — drop rather than emit an unparseable line.
+ case 'cmd': return `cd /d "${path.replace(/"/g, '')}"`;
+ case 'powershell': return `Set-Location -LiteralPath '${path.replace(/'/g, "''")}'`;
+ default: return `cd ${shellQuote(path)}`;
+ }
+}
diff --git a/server/lib/shellCd.test.js b/server/lib/shellCd.test.js
new file mode 100644
index 0000000000..3eab4cce83
--- /dev/null
+++ b/server/lib/shellCd.test.js
@@ -0,0 +1,63 @@
+import { describe, it, expect } from 'vitest';
+import { buildCdCommand, detectShellFlavor } from './shellCd.js';
+
+describe('detectShellFlavor', () => {
+ it('reads the flavor off the shell binary, ignoring path and case', () => {
+ expect(detectShellFlavor('C:\\WINDOWS\\system32\\cmd.exe')).toBe('cmd');
+ expect(detectShellFlavor('C:\\Program Files\\PowerShell\\7\\pwsh.exe')).toBe('powershell');
+ expect(detectShellFlavor('powershell.exe')).toBe('powershell');
+ expect(detectShellFlavor('/bin/zsh')).toBe('posix');
+ expect(detectShellFlavor('/usr/bin/fish')).toBe('posix');
+ });
+
+ it('keeps POSIX quoting for a POSIX shell running on Windows (git-bash)', () => {
+ expect(detectShellFlavor('C:\\Program Files\\Git\\bin\\bash.exe', 'win32')).toBe('posix');
+ });
+
+ it('falls back to the platform default when no shell is recorded', () => {
+ expect(detectShellFlavor(undefined, 'win32')).toBe('cmd');
+ expect(detectShellFlavor('', 'darwin')).toBe('posix');
+ expect(detectShellFlavor(null, 'linux')).toBe('posix');
+ });
+});
+
+describe('buildCdCommand', () => {
+ it('uses cd /d with double quotes on cmd.exe so the drive actually changes', () => {
+ // The reported bug: a session started in C:\Users\… stayed there, because a
+ // POSIX `cd '<path>'` neither quotes nor crosses drives under cmd.exe.
+ expect(buildCdCommand('I:\\code\\example-app', 'cmd.exe'))
+ .toBe('cd /d "I:\\code\\example-app"');
+ expect(buildCdCommand('C:\\code\\my app', 'C:\\WINDOWS\\system32\\cmd.exe'))
+ .toBe('cd /d "C:\\code\\my app"');
+ });
+
+ it('uses Set-Location -LiteralPath on PowerShell, doubling embedded quotes', () => {
+ expect(buildCdCommand('D:\\code\\app', 'pwsh.exe'))
+ .toBe("Set-Location -LiteralPath 'D:\\code\\app'");
+ expect(buildCdCommand("D:\\code\\it's", 'powershell.exe'))
+ .toBe("Set-Location -LiteralPath 'D:\\code\\it''s'");
+ });
+
+ it('leaves a Windows path alone for git-bash, which translates it itself', () => {
+ expect(buildCdCommand('I:\\code\\example-app', 'C:\\Program Files\\Git\\bin\\bash.exe'))
+ .toBe("cd 'I:\\code\\example-app'");
+ });
+
+ it('uses POSIX quoting elsewhere', () => {
+ expect(buildCdCommand('/Users/example/code/app', '/bin/zsh'))
+ .toBe("cd /Users/example/code/app");
+ expect(buildCdCommand('/Users/example/my app', '/bin/bash'))
+ .toBe("cd '/Users/example/my app'");
+ expect(buildCdCommand("/tmp/it's", '/bin/bash'))
+ .toBe("cd '/tmp/it'\\''s'");
+ });
+
+ it('drops control characters so a path cannot terminate the cd line', () => {
+ expect(buildCdCommand('C:\\code\\app\r\nwhoami', 'cmd.exe')).toBe('cd /d "C:\\code\\appwhoami"');
+ expect(buildCdCommand('/tmp/app\nwhoami', '/bin/zsh')).toBe('cd /tmp/appwhoami');
+ });
+
+ it('drops double quotes on cmd.exe, which has no escape for them', () => {
+ expect(buildCdCommand('C:\\code\\"app"', 'cmd.exe')).toBe('cd /d "C:\\code\\app"');
+ });
+});
diff --git a/server/lib/socketValidation.js b/server/lib/socketValidation.js
index 709a4aa19f..849bde427c 100644
--- a/server/lib/socketValidation.js
+++ b/server/lib/socketValidation.js
@@ -48,6 +48,14 @@ export const shellInputSchema = z.object({
data: z.string()
});
+// shell:cd — session id + the directory to change into. The client sends a PATH,
+// not a command: the `cd` line is built server-side from the session's actual
+// shell (see lib/shellCd.js), since only the server knows which one it spawned.
+export const shellCdSchema = z.object({
+ sessionId: z.string().min(1, 'sessionId is required'),
+ path: z.string().min(1, 'path is required')
+});
+
// shell:resize — session ID with cols and rows
export const shellResizeSchema = z.object({
sessionId: z.string().min(1, 'sessionId is required'),
diff --git a/server/lib/socketValidation.test.js b/server/lib/socketValidation.test.js
index 80677bc825..591df6e2a2 100644
--- a/server/lib/socketValidation.test.js
+++ b/server/lib/socketValidation.test.js
@@ -6,6 +6,7 @@ import {
logsUnsubscribeSchema,
errorRecoverSchema,
shellInputSchema,
+ shellCdSchema,
shellResizeSchema,
shellSessionIdSchema,
shellStopSchema,
@@ -135,6 +136,12 @@ describe('socketValidation schemas', () => {
expect(shellInputSchema.safeParse({ data: 'ls' }).success).toBe(false);
});
+ it('shellCdSchema requires a sessionId and a non-empty path', () => {
+ expect(shellCdSchema.safeParse({ sessionId: 's1', path: '/tmp/app' }).success).toBe(true);
+ expect(shellCdSchema.safeParse({ sessionId: 's1', path: '' }).success).toBe(false);
+ expect(shellCdSchema.safeParse({ path: '/tmp/app' }).success).toBe(false);
+ });
+
it('shellResizeSchema accepts a valid resize payload', () => {
expect(shellResizeSchema.safeParse({ sessionId: 's1', cols: 80, rows: 24 }).success).toBe(true);
});
diff --git a/server/services/shell.js b/server/services/shell.js
index 050019522b..7f5c506f3f 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -3,6 +3,7 @@ import os from 'os';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
import { scheduleSubmitEnters } from '../lib/tuiHandshake.js';
+import { buildCdCommand } from '../lib/shellCd.js';
// Store active shell sessions (persist across socket reconnects)
const shellSessions = new Map();
@@ -181,6 +182,9 @@ export function createShellSession(socket, options = {}) {
pty: ptyProcess,
socket,
cwd,
+ // The spawned shell binary — kept so cd-style commands injected later can be
+ // written in the dialect this session actually speaks (see changeSessionDirectory).
+ shell,
createdAt: Date.now(),
label: options.label || null,
kind: options.kind || 'shell',
@@ -548,6 +552,23 @@ export function writeToSession(sessionId, data) {
return false;
}
+/**
+ * Change a session's working directory.
+ *
+ * Goes through the service rather than the client emitting its own `cd` string,
+ * because only the server knows which shell this PTY is running — and the command
+ * differs per shell. See lib/shellCd.js for why.
+ *
+ * @param {string} sessionId
+ * @param {string} dirPath
+ * @returns {boolean} false when the session is unknown
+ */
+export function changeSessionDirectory(sessionId, dirPath) {
+ const session = shellSessions.get(sessionId);
+ if (!session) return false;
+ return writeToSession(sessionId, `${buildCdCommand(dirPath, session.shell)}\n`);
+}
+
/**
* Deliver `text` to a session as a SINGLE bracketed-paste event, then submit it.
*
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index aa365e1380..7e62202983 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -372,6 +372,24 @@ describe('writeToSession / resizeSession', () => {
});
});
+describe('changeSessionDirectory', () => {
+ it('writes the cd in the dialect of the shell THIS session spawned', () => {
+ // A Windows session runs cmd.exe, where the POSIX form the Shell page used to
+ // send is both mis-quoted and drive-blind — see lib/shellCd.js.
+ const winId = shell.createShellSession(makeSocket('sock-win'), { shell: 'C:\\WINDOWS\\system32\\cmd.exe' });
+ expect(shell.changeSessionDirectory(winId, 'I:\\code\\example-app')).toBe(true);
+ expect(ptyInstances[0].write).toHaveBeenCalledWith('cd /d "I:\\code\\example-app"\n');
+
+ const posixId = shell.createShellSession(makeSocket('sock-posix'), { shell: '/bin/zsh' });
+ expect(shell.changeSessionDirectory(posixId, '/Users/example/my app')).toBe(true);
+ expect(ptyInstances[1].write).toHaveBeenCalledWith("cd '/Users/example/my app'\n");
+ });
+
+ it('returns false for a missing session', () => {
+ expect(shell.changeSessionDirectory('missing', '/tmp')).toBe(false);
+ });
+});
+
describe('pasteToSession', () => {
let id;
let pty;
diff --git a/server/services/socket.js b/server/services/socket.js
index 5d7ab2732e..4c5ce76422 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -37,6 +37,7 @@ import {
logsUnsubscribeSchema,
errorRecoverSchema,
shellInputSchema,
+ shellCdSchema,
shellResizeSchema,
shellAttachSchema,
shellStopSchema,
@@ -676,6 +677,17 @@ export function initSocket(io) {
}
});
+ // The client picks a FOLDER; the server renders the `cd` for the shell this
+ // session is running. A hard-coded POSIX `cd '<path>'` from the client is what
+ // made every managed-app folder unreachable from a Windows (cmd.exe) session.
+ socket.on('shell:cd', (rawData) => {
+ const validated = validateSocketData(shellCdSchema, rawData, socket, 'shell:cd');
+ if (!validated) return;
+ if (!shellService.changeSessionDirectory(validated.sessionId, validated.path)) {
+ socket.emit('shell:error', { sessionId: validated.sessionId, error: 'Session not found' });
+ }
+ });
+
socket.on('shell:resize', (rawData) => {
const validated = validateSocketData(shellResizeSchema, rawData, socket, 'shell:resize');
if (!validated) return;
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 0a7b182df8..8d8574f9f7 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -37,6 +37,7 @@ vi.mock('./shell.js', () => ({
subscribeSessionList: vi.fn(),
listAllSessions: vi.fn(() => []),
writeToSession: vi.fn(),
+ changeSessionDirectory: vi.fn(() => true),
resizeSession: vi.fn(),
killSession: vi.fn(),
unsubscribeSessionList: vi.fn(),
@@ -50,6 +51,7 @@ vi.mock('../lib/socketValidation.js', () => ({
logsUnsubscribeSchema: {},
errorRecoverSchema: {},
shellInputSchema: {},
+ shellCdSchema: {},
shellResizeSchema: {},
shellAttachSchema: {},
shellStopSchema: {},
@@ -371,6 +373,32 @@ describe('socket.js — initSocket', () => {
expect(shellService.listAllSessions).toHaveBeenCalledWith(socket);
});
+ // ===========================================================================
+ // shell:cd — the client sends a folder, the SERVER renders the cd command, so
+ // the quoting matches the shell that session actually runs (Windows cmd.exe
+ // rejects the POSIX form the client used to send).
+ // ===========================================================================
+ it('shell:cd hands the path to changeSessionDirectory', () => {
+ const socket = makeSocket('shell-cd');
+ io.connect(socket);
+ shellService.changeSessionDirectory.mockClear();
+
+ socket.handlers['shell:cd']({ sessionId: 'abc', path: 'I:\\code\\example-app' });
+
+ expect(shellService.changeSessionDirectory).toHaveBeenCalledWith('abc', 'I:\\code\\example-app');
+ });
+
+ it('shell:cd emits shell:error when the session is gone', () => {
+ const socket = makeSocket('shell-cd-missing');
+ io.connect(socket);
+ shellService.changeSessionDirectory.mockReturnValueOnce(false);
+
+ socket.handlers['shell:cd']({ sessionId: 'gone', path: '/tmp/app' });
+
+ const err = socket.emitted.find(([ev]) => ev === 'shell:error');
+ expect(err[1].sessionId).toBe('gone');
+ });
+
// ===========================================================================
// shell:attach claim semantics — auto-pick paths must not displace another tab
// ===========================================================================