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

Submit injected shell commands with CR so they run on Windows

[._.]/ Adam Eivy030a7e567ae2
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 7bc004a519..13e65122b6 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, 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. |
+| `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. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `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 b2f9609728..bfc07a77f3 100644
--- a/client/src/hooks/useShellSession.js
+++ b/client/src/hooks/useShellSession.js
@@ -219,7 +219,9 @@ export function useShellSession({ isFullscreen } = {}) {
return true;
}, []);
- const sendCommand = useCallback((cmd) => emitShellInput(cmd + '\n'), [emitShellInput]);
+ // CR, not LF — see SUBMIT_KEY in server/lib/tuiHandshake.js for why. Same byte as
+ // TerminalHotKeys' Enter key.
+ const sendCommand = useCallback((cmd) => emitShellInput(cmd + '\r'), [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]);
diff --git a/client/src/hooks/useShellSession.test.jsx b/client/src/hooks/useShellSession.test.jsx
index 2cda93b68c..9e2ec3471d 100644
--- a/client/src/hooks/useShellSession.test.jsx
+++ b/client/src/hooks/useShellSession.test.jsx
@@ -91,6 +91,15 @@ describe('useShellSession', () => {
expect(lastEmit('shell:cd')).toEqual(['shell:cd', { sessionId: 'abc', path: 'I:\\code\\example-app' }]);
});
+ // LF would leave the command typed-but-unexecuted on cmd.exe — see SUBMIT_KEY.
+ it('submits a quick command with a carriage return, not a line feed', () => {
+ const { result } = renderHook(() => useShellSession({}), { wrapper });
+ fire('shell:sessions', []);
+ fire('shell:started', { sessionId: 'abc' });
+ act(() => result.current.sendCommand('claude'));
+ expect(lastEmit('shell:input')).toEqual(['shell:input', { sessionId: 'abc', data: 'claude\r' }]);
+ });
+
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/docs/API.md b/docs/API.md
index e679c2fb0d..95aab3f830 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -689,8 +689,9 @@ socket.on('detect:complete', (appData) => {
socket.emit('shell:start', {});
socket.on('shell:started', ({ sessionId }) => console.log('session', sessionId));
-// Send input to shell
-socket.emit('shell:input', { sessionId, data: 'ls -la\n' });
+// Send input to shell. Submit with `\r` (the byte Enter sends), never `\n` — cmd.exe
+// under Windows ConPTY ignores LF and the line is typed but never executed.
+socket.emit('shell:input', { sessionId, data: 'ls -la\r' });
// Receive shell output
socket.on('shell:output', ({ sessionId, data }) => {
diff --git a/server/lib/README.md b/server/lib/README.md
index 993aca0d56..2c1bb12960 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -109,7 +109,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptRunner.js` | Shared LLM runner wrapper. |
| `providerCooldown.js` | Provider bench policy — `resolveProviderBench(analysis)` → `null` (don't bench) / a `usage-limit` marker / an `unavailable` marker with the per-category cooldown from `COOLDOWN_MS_BY_CATEGORY`. Declines to bench request/response-specific categories (`isRequestSpecificCategory` / `isSchemaTypeCategory`) so one bad model id or off-shape response can't take a healthy provider offline. Shared by `promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. |
| `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). |
-| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. |
+| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. Also owns `SUBMIT_KEY` — the single Enter byte every PTY writer sends, whether it's submitting a pasted TUI prompt or a command PortOS injected into a shell session. It is CR, never LF: a POSIX pty's ICRNL hides the difference, but cmd.exe under Windows ConPTY accepts only CR and leaves an LF-terminated line typed-but-unexecuted at the prompt. |
| `tuiUsageScrape.js` | `scrapeTuiUsage({ command, slashCommand, … })` + `USAGE_SANDBOX_DIR` — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels `--print` can't reach). |
| `stageRunner.js` | Shared staged-LLM runner. |
| `stagePinPolicy.js` | Run-scoped "ignore per-stage LLM pins" switch (AsyncLocalStorage) — `withStagePinsIgnored(ignore, fn)` marks an async subtree, `stagePinsIgnored()` reads it, and `stageRunner#effectiveStage` enumerates which stage-config fields it strips. Backs Series Autopilot's "use one provider/model for every stage" option. |
@@ -369,7 +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. |
+| `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. Renders the LINE only; the Enter byte that submits it is `SUBMIT_KEY` in `tuiHandshake.js`. |
| `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/tuiHandshake.js b/server/lib/tuiHandshake.js
index 74792fae17..be4c37676a 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -667,6 +667,21 @@ export function createSelfClearingSignalGate() {
export const SUBMIT_ENTER_ATTEMPTS = 3;
export const SUBMIT_ENTER_SPACING_MS = 700;
+// The byte a real terminal sends when the user presses Enter — the one every
+// `write()` above hands to a PTY, and the terminator on any command PortOS
+// injects into a shell session (services/shell.js#submitToSession).
+//
+// CR, never LF. A POSIX pty's line discipline sets ICRNL, which translates an
+// incoming CR into NL, so on macOS/Linux either byte submits the line and the
+// difference is invisible. Windows ConPTY does no such translation: cmd.exe's
+// line input accepts ONLY CR, and an LF-terminated write leaves the command
+// typed at the prompt but never executed — the next injection then concatenates
+// onto it. That is why the Shell page's "cd to app" picker and quick-command
+// buttons still did nothing on Windows after the cd line itself was rendered in
+// the right dialect (lib/shellCd.js). xterm.js already sends CR for a real Enter
+// keypress, so an injected command submits exactly the way typing does.
+export const SUBMIT_KEY = '\r';
+
/**
* Submit a freshly-pasted TUI prompt by sending Enter SUBMIT_ENTER_ATTEMPTS
* times: once immediately, then on a SUBMIT_ENTER_SPACING_MS interval until the
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index 582254629d..99ff264dab 100644
--- a/server/lib/tuiPromptRunner.js
+++ b/server/lib/tuiPromptRunner.js
@@ -68,6 +68,7 @@ import {
createInputReadyTracker,
detectMissingTuiBinary,
createSelfClearingSignalGate,
+ SUBMIT_KEY,
} from './tuiHandshake.js';
import { buildCliChildEnv } from './cliChildEnv.js';
import { isCodexCommand } from './codex.js';
@@ -717,7 +718,7 @@ ${prompt}`;
// unsent. Tracked in submitEnterTimer so finish()'s cleanupTimers()
// cancels pending retries if the run ends first.
submitEnterTimer = scheduleSubmitEnters(
- () => { try { ptyProcess.write('\r'); } catch { /* PTY may have already exited */ } },
+ () => { try { ptyProcess.write(SUBMIT_KEY); } catch { /* PTY may have already exited */ } },
() => finalized
);
}
diff --git a/server/lib/tuiUsageScrape.js b/server/lib/tuiUsageScrape.js
index 70a631d7d4..5d36e0905f 100644
--- a/server/lib/tuiUsageScrape.js
+++ b/server/lib/tuiUsageScrape.js
@@ -5,6 +5,7 @@ import { join } from 'path';
import { stripAnsi } from './ansiStrip.js';
import { sleep } from './fileUtils.js';
import { buildCliChildEnv } from './cliChildEnv.js';
+import { SUBMIT_KEY } from './tuiHandshake.js';
/**
* Drive an interactive coding-agent TUI (Antigravity `agy`, Grok Build `grok`)
@@ -180,7 +181,7 @@ export async function scrapeTuiUsage({
// "Yes, I trust"), grok shows a start menu (default highlighted item). One
// Enter clears either. On an already-trusted sandbox there is no gate and
// this is a harmless empty-prompt submit. Wait for the dismissal to repaint.
- if (!exited) { pty.write('\r'); lastDataAt = Date.now(); }
+ if (!exited) { pty.write(SUBMIT_KEY); lastDataAt = Date.now(); }
await waitForIdle(primerCapMs);
// Bracketed-paste the command so multi-word input (`/usage show`) lands
@@ -188,7 +189,7 @@ export async function scrapeTuiUsage({
if (!exited) {
pty.write(`\x1b[200~${slashCommand}\x1b[201~`);
await Promise.race([sleep(400), hardStop]);
- pty.write('\r');
+ pty.write(SUBMIT_KEY);
lastDataAt = Date.now();
}
await waitForIdle(renderCapMs, {
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 5d0cf074c8..bcc6c1731a 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -57,6 +57,7 @@ import {
PASTE_RETRY_BASE_DELAY_MS,
extractVerifiablePromptPrefix,
isPasteConfirmed,
+ SUBMIT_KEY,
} from '../lib/tuiHandshake.js';
import { injectTuiModelAndEffort } from '../lib/providerVendors.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
@@ -370,7 +371,7 @@ function createPasteRetryController({
// window (issue #1229 review).
markPromptSubmitted();
submitEnterTimer = scheduleSubmitEnters(
- () => shellService.writeToSession(sessionId, '\r'),
+ () => shellService.writeToSession(sessionId, SUBMIT_KEY),
() => isFinalized()
);
};
@@ -1385,7 +1386,7 @@ export async function spawnTuiAgent({
// Send Enter once.
if (inputReady.needsTrust && !trustAccepted) {
trustAccepted = true;
- shellService.writeToSession(sessionId, '\r');
+ shellService.writeToSession(sessionId, SUBMIT_KEY);
appendLine(`📟 Auto-confirmed ${tuiConfig.command} folder-trust prompt for session ${sessionId.slice(0, 8)}`);
return;
}
diff --git a/server/services/shell.js b/server/services/shell.js
index 7f5c506f3f..e0e31eba4b 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -2,7 +2,7 @@ import * as pty from 'node-pty';
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 { scheduleSubmitEnters, SUBMIT_KEY } from '../lib/tuiHandshake.js';
import { buildCdCommand } from '../lib/shellCd.js';
// Store active shell sessions (persist across socket reconnects)
@@ -14,6 +14,10 @@ const shellSessions = new Map();
// not a resource/abuse defense. External views (TUI runs) don't count.
const MAX_TOTAL_SESSIONS = 20;
+// Re-exported so a session caller reaches the Enter byte without importing the
+// TUI-handshake module directly. See lib/tuiHandshake.js for why it is CR.
+export { SUBMIT_KEY };
+
// PTY event handlers run outside the Express middleware chain — uncaught throws here
// crash the Node process instead of bubbling to res.next. try/catch is therefore
// justified in this one spot despite the project-wide "no try/catch" convention.
@@ -240,7 +244,7 @@ export function createShellSession(socket, options = {}) {
// prematurely satisfy its bracketed-paste gate.
const sendInitial = () => {
options.onInitialCommandSent?.();
- writeToSession(sessionId, `${options.initialCommand}\n`);
+ submitToSession(sessionId, options.initialCommand);
};
if (options.waitForPromptReady) {
// Inject the command only once the shell can ACTUALLY run commands. A fixed
@@ -260,15 +264,16 @@ export function createShellSession(socket, options = {}) {
// bounded fallback still injects the command if the probe never round-trips.
// NOTE: the probe is POSIX (`printf`). The only caller of waitForPromptReady
// is the agent-TUI path, which is developer-machine (mac/linux) only; on a
- // Windows cmd.exe shell `printf` no-ops and the command simply injects on the
- // bounded fallback below (slower, never broken). A Windows port would need a
- // platform-aware probe.
+ // Windows cmd.exe shell `printf` isn't a command, so the probe errors out,
+ // the marker never appears, and the command injects on the bounded fallback
+ // below (slower, never broken). A Windows port would need a platform-aware
+ // probe.
let sent = false;
let sub = null;
let exitSub = null;
const nonce = uuidv4().replace(/-/g, '').slice(0, 12);
const marker = `PORTOSRDY${nonce}`;
- const probe = `printf '%s\\n' 'PORTOSRDY''${nonce}'\n`;
+ const probe = `printf '%s\\n' 'PORTOSRDY''${nonce}'`;
let seen = '';
// Tear down every pending timer + listener. Called both on success
// (fire) and when the PTY exits before the probe round-trips, so no
@@ -298,7 +303,7 @@ export function createShellSession(socket, options = {}) {
// Writing earlier is harmless (zsh's line editor / p10k instant-prompt
// buffer holds it until the prompt is live and replays it), but a small
// delay avoids racing node-pty's own spawn handshake.
- const probeTimer = setTimeout(() => { if (!sent) writeToSession(sessionId, probe); }, 50);
+ const probeTimer = setTimeout(() => { if (!sent) submitToSession(sessionId, probe); }, 50);
const fallback = setTimeout(fire, options.initialCommandDelayMs ?? 8000);
} else {
setTimeout(sendInitial, options.initialCommandDelayMs ?? 200);
@@ -552,6 +557,20 @@ export function writeToSession(sessionId, data) {
return false;
}
+/**
+ * Type a command line into a session and press Enter.
+ *
+ * Every "inject a command the user didn't type" path goes through here so the
+ * terminator is decided once — see SUBMIT_KEY for why it isn't a newline.
+ *
+ * @param {string} sessionId
+ * @param {string} line - command line, WITHOUT a trailing terminator
+ * @returns {boolean} false when the session is unknown
+ */
+export function submitToSession(sessionId, line) {
+ return writeToSession(sessionId, `${line}${SUBMIT_KEY}`);
+}
+
/**
* Change a session's working directory.
*
@@ -566,7 +585,7 @@ export function writeToSession(sessionId, data) {
export function changeSessionDirectory(sessionId, dirPath) {
const session = shellSessions.get(sessionId);
if (!session) return false;
- return writeToSession(sessionId, `${buildCdCommand(dirPath, session.shell)}\n`);
+ return submitToSession(sessionId, buildCdCommand(dirPath, session.shell));
}
/**
@@ -592,7 +611,7 @@ export function pasteToSession(sessionId, text, { label = 'paste' } = {}) {
let expectedInputRevision = session.inputRevision;
const writeEnter = () => {
try {
- writeToSession(sessionId, '\r');
+ writeToSession(sessionId, SUBMIT_KEY);
expectedInputRevision = session.inputRevision;
} catch (err) {
// Timer callbacks run outside the request lifecycle, and a write to a
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index 7e62202983..8635ae5863 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -184,7 +184,7 @@ describe('createShellSession', () => {
const id = shell.createShellSession(makeSocket(), { initialCommand: 'ls', initialCommandDelayMs: 50 });
expect(ptyInstances[0].write).not.toHaveBeenCalled();
vi.advanceTimersByTime(50);
- expect(ptyInstances[0].write).toHaveBeenCalledWith('ls\n');
+ expect(ptyInstances[0].write).toHaveBeenCalledWith('ls\r');
expect(shell.getSession(id)).toBeTruthy();
vi.useRealTimers();
});
@@ -205,11 +205,11 @@ describe('createShellSession', () => {
// assembled string never appears contiguously) must NOT trip readiness.
pty.emitData('instant prompt rendering…');
pty.emitData(`% printf '%s\\n' 'PORTOSRDY''${nonce}'`);
- expect(pty.write).not.toHaveBeenCalledWith('claude\n');
+ expect(pty.write).not.toHaveBeenCalledWith('claude\r');
expect(onInitialCommandSent).not.toHaveBeenCalled();
// The assembled marker appears in the OUTPUT → shell proven, command injected.
pty.emitData(`${marker}\n`);
- expect(pty.write).toHaveBeenCalledWith('claude\n');
+ expect(pty.write).toHaveBeenCalledWith('claude\r');
expect(onInitialCommandSent).toHaveBeenCalledTimes(1);
vi.useRealTimers();
});
@@ -221,10 +221,10 @@ describe('createShellSession', () => {
vi.advanceTimersByTime(50); // probe written
// Output streams but the assembled marker never appears.
for (let i = 0; i < 10; i++) { pty.emitData('tick'); vi.advanceTimersByTime(500); }
- expect(pty.write).not.toHaveBeenCalledWith('claude\n');
+ expect(pty.write).not.toHaveBeenCalledWith('claude\r');
// …but the hard fallback (8000ms from creation) injects the command regardless.
vi.advanceTimersByTime(8000);
- expect(pty.write).toHaveBeenCalledWith('claude\n');
+ expect(pty.write).toHaveBeenCalledWith('claude\r');
vi.useRealTimers();
});
@@ -236,7 +236,7 @@ describe('createShellSession', () => {
// The shell dies before the marker round-trips → cancels pending timers.
pty.emitExit({ exitCode: 1 });
vi.advanceTimersByTime(8000); // past the (now-cleared) fallback window
- expect(pty.write).not.toHaveBeenCalledWith('claude\n');
+ expect(pty.write).not.toHaveBeenCalledWith('claude\r');
vi.useRealTimers();
});
});
@@ -375,14 +375,15 @@ 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.
+ // send is both mis-quoted and drive-blind — see lib/shellCd.js. The trailing CR
+ // is the other half of the Windows fix; see SUBMIT_KEY.
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');
+ expect(ptyInstances[0].write).toHaveBeenCalledWith('cd /d "I:\\code\\example-app"\r');
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");
+ expect(ptyInstances[1].write).toHaveBeenCalledWith("cd '/Users/example/my app'\r");
});
it('returns false for a missing session', () => {
@@ -390,6 +391,15 @@ describe('changeSessionDirectory', () => {
});
});
+describe('submitToSession', () => {
+ it('appends the Enter byte, and returns false for a missing session', () => {
+ const id = shell.createShellSession(makeSocket('sock-submit'));
+ expect(shell.submitToSession(id, 'npm test')).toBe(true);
+ expect(ptyInstances[0].write).toHaveBeenCalledWith(`npm test${shell.SUBMIT_KEY}`);
+ expect(shell.submitToSession('missing', 'npm test')).toBe(false);
+ });
+});
+
describe('pasteToSession', () => {
let id;
let pty;
diff --git a/server/services/socket.js b/server/services/socket.js
index 4c5ce76422..2bc0128633 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -642,7 +642,7 @@ export function initSocket(io) {
if (sessionId) {
socket.emit('shell:started', { sessionId });
if (initialCommand) {
- setTimeout(() => shellService.writeToSession(sessionId, initialCommand + '\n'), 200);
+ setTimeout(() => shellService.submitToSession(sessionId, initialCommand), 200);
}
} else {
socket.emit('shell:error', { error: 'Failed to create shell session' });