Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"name": "Emdash Contributors",
"email": "support@emdash.sh"
},
"homepage": "https://emdash.sh",
"engines": {
"node": ">=20.0.0 <23.0.0",
"pnpm": ">=10.28.0"
Expand Down
92 changes: 52 additions & 40 deletions src/main/services/hostPreviewService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { EventEmitter } from 'node:events';
import { spawn, ChildProcessWithoutNullStreams } from 'node:child_process';
import net from 'node:net';
import http from 'node:http';
import https from 'node:https';
import fs from 'node:fs';
import path from 'node:path';
import { log } from '../lib/logger';
Expand Down Expand Up @@ -140,9 +142,7 @@ class HostPreviewService extends EventEmitter {
// If process exists, verify it's running from the correct directory
if (existingProc) {
// Check if process is still running
try {
// On Unix, signal 0 checks if process exists
existingProc.kill(0);
if (existingProc.exitCode === null && existingProc.signalCode === null) {
// Process is still running - check if cwd matches
if (existingCwd && path.resolve(existingCwd) === cwd) {
log.info?.('[hostPreview] reusing existing process', {
Expand All @@ -163,7 +163,7 @@ class HostPreviewService extends EventEmitter {
this.procs.delete(taskId);
this.procCwds.delete(taskId);
}
} catch {
} else {
// Process has exited - clean up
this.procs.delete(taskId);
this.procCwds.delete(taskId);
Expand All @@ -181,6 +181,7 @@ class HostPreviewService extends EventEmitter {
const parentExists = fs.existsSync(parentNm);
if (!wsExists && parentExists) {
try {
// On Windows, 'junction' avoids needing administrator privileges
const linkType = process.platform === 'win32' ? 'junction' : 'dir';
fs.symlinkSync(parentNm, wsNm, linkType as any);
log.info?.('[hostPreview] linked node_modules', {
Expand Down Expand Up @@ -253,7 +254,16 @@ class HostPreviewService extends EventEmitter {
});
this.emit('event', { type: 'setup', taskId, status: 'done' } as HostPreviewEvent);
}
} catch {}
} catch (e) {
this.emit('event', {
type: 'setup',
taskId,
status: 'error',
error: e instanceof Error ? e.message : String(e),
} as HostPreviewEvent);
log.error?.('[hostPreview] auto-install failed', e);
return { ok: false, error: `Auto-install failed: ${e}` };
}

// Choose a free port (avoid 3000)
const preferred = [5173, 5174, 3001, 3002, 8080, 4200, 5500, 7000];
Expand Down Expand Up @@ -338,27 +348,28 @@ class HostPreviewService extends EventEmitter {
const port = Number(parsed.port || 0);
if (!port) return;

// Quick TCP probe to verify server is ready
const socket = net.createConnection({ host, port }, () => {
try {
socket.destroy();
} catch {}
if (!urlEmitted) {
urlEmitted = true;
try {
this.emit('event', {
type: 'url',
taskId,
url: urlToProbe,
} as HostPreviewEvent);
} catch {}
// Quick HTTP probe to verify server is ready
const client = parsed.protocol === 'https:' ? https : http;
const req = client.request(
urlToProbe,
{ method: 'HEAD', timeout: 500, rejectUnauthorized: false },
(res) => {
if (!urlEmitted) {
urlEmitted = true;
try {
this.emit('event', {
type: 'url',
taskId,
url: urlToProbe,
} as HostPreviewEvent);
} catch {}
}
}
);
req.on('error', () => {
// Server not ready yet
});
socket.on('error', () => {
try {
socket.destroy();
} catch {}
});
req.end();
} catch {}
};

Expand All @@ -378,38 +389,37 @@ class HostPreviewService extends EventEmitter {
child.stderr.on('data', onData);

// Probe periodically; if reachable and not emitted from logs, synthesize URL
const host = 'localhost';
const probeInterval = setInterval(() => {
if (urlEmitted) return;
if (urlEmitted) {
clearInterval(probeInterval);
return;
}
// If we have a candidate URL from logs, probe that first
if (candidateUrl) {
probeAndEmitUrl(candidateUrl);
return;
}
// Otherwise, probe the expected port
const socket = net.createConnection(
{ host, port: Number(env.PORT) || forcedPort },
() => {
try {
socket.destroy();
} catch {}
const expectedPort = Number(env.PORT) || forcedPort;
const req = http.request(
`http://localhost:${expectedPort}`,
{ method: 'HEAD', timeout: 500 },
(res) => {
if (!urlEmitted) {
urlEmitted = true;
clearInterval(probeInterval);
try {
this.emit('event', {
type: 'url',
taskId,
url: `http://localhost:${Number(env.PORT) || forcedPort}`,
url: `http://localhost:${expectedPort}`,
} as HostPreviewEvent);
} catch {}
}
}
);
socket.on('error', () => {
try {
socket.destroy();
} catch {}
});
req.on('error', () => {});
req.end();
}, 800);

child.on('exit', async () => {
Expand All @@ -431,8 +441,10 @@ class HostPreviewService extends EventEmitter {
if (idx >= 0 && idx + 1 < args.length) args[idx + 1] = String(forcedPort);
else if (idxPort >= 0 && idxPort + 1 < args.length)
args[idxPort + 1] = String(forcedPort);
else if (pm === 'npm') args.push('--', '-p', String(forcedPort));
else args.push('-p', String(forcedPort));
else if (pm === 'npm') {
if (!args.includes('--')) args.push('--');
args.push('-p', String(forcedPort));
} else args.push('-p', String(forcedPort));
log.info?.('[hostPreview] retry on new port', {
taskId,
port: forcedPort,
Expand Down
4 changes: 2 additions & 2 deletions src/main/services/ptyIpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
clearStoredSession,
getStoredResumeTarget,
markCodexSessionBound,
normalizeClaudeProjectPath,
} from './ptyManager';
import { log } from '../lib/logger';
import { terminalSnapshotService } from './TerminalSnapshotService';
Expand Down Expand Up @@ -803,8 +804,7 @@ export function registerPtyIpc(): void {
const claudeHashDir = path.join(os.homedir(), '.claude', 'projects', cwdHash);

// Also check for path-based directory name (Claude's actual format)
// Replace path separators with hyphens for the directory name
const pathBasedName = cwd.replace(/\//g, '-');
const pathBasedName = normalizeClaudeProjectPath(cwd);
const claudePathDir = path.join(os.homedir(), '.claude', 'projects', pathBasedName);

// Check if any Claude session directory exists for this working directory
Expand Down
36 changes: 25 additions & 11 deletions src/main/services/ptyManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -501,9 +501,19 @@ export function getStoredResumeTarget(
return normalized.target;
}

/**
* Encode a project working directory for use in Claude's ~/.claude/projects/ path.
*
* Claude encodes project paths by replacing path separators with hyphens.
* On Windows also strips ':' drive letters, and replaces backslashes.
*/
export function normalizeClaudeProjectPath(cwd: string): string {
return cwd.replace(/[:\\/]/g, '-');
}

function claudeSessionFileExists(uuid: string, cwd: string): boolean {
try {
const encoded = cwd.replace(/[:\\/]/g, '-');
const encoded = normalizeClaudeProjectPath(cwd);
const sessionFile = path.join(os.homedir(), '.claude', 'projects', encoded, `${uuid}.jsonl`);
return fs.existsSync(sessionFile);
} catch {
Expand All @@ -523,8 +533,7 @@ function claudeSessionFileExists(uuid: string, cwd: string): boolean {
*/
function discoverExistingClaudeSession(cwd: string, excludeUuids: Set<string>): string | null {
try {
// Claude encodes project paths by replacing path separators; on Windows also strip ':'.
const encoded = cwd.replace(/[:\\/]/g, '-');
const encoded = normalizeClaudeProjectPath(cwd);
const projectDir = path.join(os.homedir(), '.claude', 'projects', encoded);

if (!fs.existsSync(projectDir)) return null;
Expand Down Expand Up @@ -627,9 +636,17 @@ export function applySessionIsolation(
}
}

const pushCreateOrResumeArg = (uuid: string) => {
if (provider.id === 'claude' && claudeSessionFileExists(uuid, cwd)) {
cliArgs.push('--resume', uuid);
} else {
cliArgs.push(provider.sessionIdFlag!, uuid);
}
markClaudeSessionCreated(id, uuid, cwd);
};

if (isAdditionalChat) {
cliArgs.push(provider.sessionIdFlag, sessionUuid);
markClaudeSessionCreated(id, sessionUuid, cwd);
pushCreateOrResumeArg(sessionUuid);
return true;
}

Expand All @@ -639,20 +656,17 @@ export function applySessionIsolation(
const otherUuids = getOtherSessionUuids(id, parsed.providerId, cwd);
const existingSession = discoverExistingClaudeSession(cwd, otherUuids);
if (existingSession) {
cliArgs.push(provider.sessionIdFlag, existingSession);
markClaudeSessionCreated(id, existingSession, cwd);
pushCreateOrResumeArg(existingSession);
} else {
cliArgs.push(provider.sessionIdFlag, sessionUuid);
markClaudeSessionCreated(id, sessionUuid, cwd);
pushCreateOrResumeArg(sessionUuid);
}
return true;
}

if (!isResume) {
// First-time creation — proactively assign a session ID so we can
// reliably resume later if more chats of this provider are added.
cliArgs.push(provider.sessionIdFlag, sessionUuid);
markClaudeSessionCreated(id, sessionUuid, cwd);
pushCreateOrResumeArg(sessionUuid);
return true;
}

Expand Down
29 changes: 27 additions & 2 deletions src/main/services/ssh/SshService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,37 @@ export class SshService extends EventEmitter {
const sock = new Duplex({
read() {},
write(chunk, encoding, callback) {
return proxyProc.stdin!.write(chunk, encoding, callback);
if (!proxyProc.stdin || proxyProc.stdin.destroyed) {
callback(new Error('Proxy stdin destroyed'));
return false;
}
try {
return proxyProc.stdin.write(chunk, encoding, callback);
} catch (err: any) {
callback(err);
return false;
}
},
final(callback) {
proxyProc.stdin!.end(callback);
if (!proxyProc.stdin || proxyProc.stdin.destroyed) {
callback();
return;
}
try {
proxyProc.stdin.end(callback);
} catch (err: any) {
callback(err);
}
},
});

proxyProc.stdin!.on('error', (err: any) => {
if (err.code !== 'EPIPE') {
sock.destroy(err);
} else {
console.warn('SshService proxy stdin received EPIPE, ignoring to prevent app crash');
}
});
proxyProc.stdout!.on('data', (data) => sock.push(data));
proxyProc.stdout!.on('close', () => sock.push(null));
proxyProc.on('error', (err) => sock.destroy(err));
Expand Down
Loading