Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
f9ffcc6
feat: add svg icon set for the web ui
efenocchi Jul 1, 2026
1336171
feat: restyle web ui with a modern ide theme
efenocchi Jul 1, 2026
cc39c04
feat: refine app shell, chat and projects layout
efenocchi Jul 1, 2026
bc807c6
style: align accent to replit orange and enlarge display type
efenocchi Jul 1, 2026
176ee4d
fix: keep the preview proxy on the session running the app
efenocchi Jul 2, 2026
ea43618
test: cover preview proxy ownership selection
efenocchi Jul 2, 2026
a820044
fix: type tab icons as components to satisfy tsc
efenocchi Jul 2, 2026
d8cb71f
feat: replay persisted conversation history on project open
efenocchi Jul 2, 2026
2c630d2
fix: reset stale workflow selection when switching projects
efenocchi Jul 2, 2026
c4f949d
fix: push usage on project open so it is not empty until refresh
efenocchi Jul 2, 2026
0117a8f
test: move preview-proxy tests into the server test suite
efenocchi Jul 2, 2026
7dce4f7
fix: stop shell and agent-started apps on stop, not just workflow apps
efenocchi Jul 2, 2026
ca2d202
test: add pickPreview cases to the preview suite
efenocchi Jul 6, 2026
46c8695
fix: rewrite root-absolute urls in preview so the app stays in the if…
efenocchi Jul 6, 2026
44ed8d7
fix: own the running app at server level so any tab can stop it
efenocchi Jul 6, 2026
434208f
fix: retry the preview upstream so a dev-server reloader gap is trans…
efenocchi Jul 6, 2026
fe0b93f
ci: color-code the coverage summary categories by threshold
efenocchi Jul 6, 2026
8000162
fix: force identity encoding in the preview proxy and add clearPort
efenocchi Jul 7, 2026
a823a9f
fix: serialize app hub, clear stale preview port on stop, error on st…
efenocchi Jul 7, 2026
428b60e
fix: stop a workspace app when its last session leaves, add hub edge …
efenocchi Jul 8, 2026
6433300
style: use theme tokens for scrollbar, terminal and stop-hover colors
efenocchi Jul 8, 2026
4de79de
fix: resilient app teardown so stop never rejects and start errors cl…
efenocchi Jul 8, 2026
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
5 changes: 4 additions & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ jobs:
if [ -f coverage/coverage-summary.json ]; then
node -e "
const t = require('./coverage/coverage-summary.json').total;
const f = (m) => m.pct.toFixed(2) + '% (' + m.covered + '/' + m.total + ')';
// Colour each category by threshold (like hivemind): green >=90,
// orange 80-89, red <80 — so a weak metric is visible at a glance.
const dot = (p) => (p >= 90 ? '🟢' : p >= 80 ? '🟠' : '🔴');
const f = (m) => dot(m.pct) + ' ' + m.pct.toFixed(2) + '% (' + m.covered + '/' + m.total + ')';
const out = [
'### Test coverage',
'',
Expand Down
199 changes: 199 additions & 0 deletions packages/server/src/app-hub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import type { UiEvent, Workflow } from '@openrepl/shared';
import { detectWorkflows, WorkflowManager } from './workflow.js';
import { PreviewManager } from './preview.js';
import { CommandRunner } from './runner.js';

type AppStatus = Extract<UiEvent, { type: 'app_status' }>;

interface RunningApp {
mgr: WorkflowManager | null;
installer: CommandRunner | null;
preview: PreviewManager;
workflows: Workflow[];
activeWorkflow: string | null;
status: AppStatus | null;
}

/**
* Server-level owner of the *running app*, keyed by workspace dir. The app is
* one thing per workspace; sessions (tabs, reconnects) are many. Keeping run /
* stop / preview here — instead of in a per-session mount — means every client
* viewing that workspace sees the same status and Stop button, and Stop always
* reaches the real process no matter which tab clicked it.
*
* Events are broadcast with the dir they belong to; a session forwards only the
* events for the workspace it currently has open.
*/
export class AppHub {
private apps = new Map<string, RunningApp>();
private listeners = new Set<(dir: string, e: UiEvent) => void>();
/** Per-dir promise chain so overlapping run()/stop() can't interleave and
* clear or swap `app.mgr` mid-start. */
private locks = new Map<string, Promise<unknown>>();
/** How many live sessions have each workspace open, so we can stop its app
* once the last tab for it goes away (no orphaned dev servers holding ports). */
private attached = new Map<string, number>();

/** A session opened `dir`. */
attach(dir: string): void {
this.attached.set(dir, (this.attached.get(dir) ?? 0) + 1);
}

/** A session left `dir` (switched project or disconnected); stop its app when
* no session has it open anymore. */
detach(dir: string): void {
const n = (this.attached.get(dir) ?? 1) - 1;
if (n > 0) {
this.attached.set(dir, n);
return;
}
this.attached.delete(dir);
void this.stop(dir);
}

subscribe(fn: (dir: string, e: UiEvent) => void): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
private broadcast(dir: string, e: UiEvent): void {
for (const l of this.listeners) l(dir, e);
}

private appFor(dir: string): RunningApp {
const existing = this.apps.get(dir);
if (existing) return existing;
const created: RunningApp = { mgr: null, installer: null, preview: new PreviewManager(), workflows: [], activeWorkflow: null, status: null };
this.apps.set(dir, created);
return created;
}

preview(dir: string): PreviewManager | null {
return this.apps.get(dir)?.preview ?? null;
}
status(dir: string): AppStatus | null {
return this.apps.get(dir)?.status ?? null;
}
activeWorkflow(dir: string): string | null {
return this.apps.get(dir)?.activeWorkflow ?? null;
}

/** The preview of whichever workspace currently has a running app, if any. */
runningPreview(): PreviewManager | null {
for (const a of this.apps.values()) if (a.preview.getPort() != null) return a.preview;
return null;
}

/** A dev server the user started in the terminal — surface it in the preview. */
notePort(dir: string, port: number): void {
const a = this.appFor(dir);
if (a.preview.getPort() !== port) {
a.preview.setPort(port);
this.broadcast(dir, { type: 'preview_ready', url: '/__preview/' });
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

private setStatus(dir: string, status: AppStatus): void {
this.appFor(dir).status = status;
this.broadcast(dir, status);
}

/** Serialize run()/stop() per dir so they can't interleave. */
private serialize<T>(dir: string, fn: () => Promise<T>): Promise<T> {
const prev = this.locks.get(dir) ?? Promise.resolve();
const next = prev.then(fn, fn);
this.locks.set(dir, next.then(() => {}, () => {}));
return next;
}

/** Run (or re-run) the app for `dir`. Returns the detected workflows. */
run(dir: string, getEnv: () => Promise<Record<string, string>>, name?: string): Promise<Workflow[]> {
return this.serialize(dir, () => this.runLocked(dir, getEnv, name));
}

private async runLocked(dir: string, getEnv: () => Promise<Record<string, string>>, name?: string): Promise<Workflow[]> {
await this.stopLocked(dir);
const det = await detectWorkflows(dir);
const app = this.appFor(dir);
app.workflows = det.workflows;
if (det.self) {
this.setStatus(dir, { type: 'app_status', state: 'error', message: 'This is the OpenREPL folder itself — open your own app folder.' });
return det.workflows;
}
const wf = name ? det.workflows.find((w) => w.name === name) : det.workflows[0];
if (!wf) {
this.setStatus(dir, { type: 'app_status', state: 'error', message: 'No runnable app found. Ask the agent to create one (e.g. an index.html or a package.json with a dev/start script).' });
return det.workflows;
}
try {
if (det.install) {
this.setStatus(dir, { type: 'app_status', state: 'installing', message: `Installing dependencies… (${det.install})` });
app.installer = new CommandRunner(dir, getEnv, (data) => this.broadcast(dir, { type: 'term_data', data: `[install] ${data}` }), () => {});
const code = await app.installer.run(det.install);
app.installer = null;
if (code !== 0) {
this.setStatus(dir, { type: 'app_status', state: 'error', message: 'Dependency install failed — see the terminal output.' });
return det.workflows;
}
}
this.setStatus(dir, { type: 'app_status', state: 'starting', message: `Starting workflow "${wf.name}" — ${wf.steps.map((s) => s.name).join(' + ')}` });
// Only the last spawned step exiting means the app is really down: a
// backend+frontend workflow shouldn't flip to "stopped" when one exits.
let live = wf.steps.filter((s) => s.command && !s.static).length;
const mgr = new WorkflowManager(
dir,
getEnv,
(step, data) => this.broadcast(dir, { type: 'term_data', data: `[${step}] ${data}` }),
(port) => {
this.notePort(dir, port);
this.setStatus(dir, { type: 'app_status', state: 'running', message: `"${wf.name}" running` });
},
(step, code) => {
if (mgr !== app.mgr) return; // a newer run replaced this workflow
if (--live > 0) return;
app.mgr = null;
app.activeWorkflow = null;
app.preview.clearPort();
this.setStatus(dir, { type: 'app_status', state: 'stopped', message: `${step} exited (code ${code})` });
},
);
app.mgr = mgr;
await mgr.start(wf);
app.activeWorkflow = wf.name;
} catch (e) {
// spawn ENOENT, a step throwing mid-start, etc. Tear the partial app down
// first (start() may have already spawned children) so we don't orphan
// processes/ports, then surface the error instead of a stuck "starting…".
await this.teardown(app);
this.setStatus(dir, { type: 'app_status', state: 'error', message: `Failed to start: ${e instanceof Error ? e.message : String(e)}` });
}
return det.workflows;
}

/** Stop the app for `dir` — kills the workflow tree and any in-flight install. */
stop(dir: string): Promise<void> {
return this.serialize(dir, () => this.stopLocked(dir));
}

private async stopLocked(dir: string): Promise<void> {
const app = this.apps.get(dir);
if (app) await this.teardown(app);
this.setStatus(dir, { type: 'app_status', state: 'stopped' });
}

/**
* Kill the running app and reset its refs. Clears state *before* awaiting the
* process kill so a rejecting `mgr.stop()` can't leave the app half-stopped —
* `stop()` must never reject (detach() calls it fire-and-forget).
*/
private async teardown(app: RunningApp): Promise<void> {
app.installer?.stopRuns();
app.installer = null;
const mgr = app.mgr;
app.mgr = null;
app.activeWorkflow = null;
// Drop the stale port so runningPreview()/the proxy stop pointing at the
// now-dead server (the source of intermittent "target unreachable" 502s).
app.preview.clearPort();
if (mgr) await mgr.stop().catch(() => {});
}
}
17 changes: 13 additions & 4 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { WebSocketServer } from 'ws';
import type { ClientCommand, UiEvent } from '@openrepl/shared';
import { Session } from './session.js';
import { ProjectRegistry } from './projects.js';
import { pickPreview } from './preview.js';
import { AppHub } from './app-hub.js';

const MIME: Record<string, string> = {
'.html': 'text/html',
Expand Down Expand Up @@ -53,14 +55,19 @@ export async function createServer(opts: ServerOptions = {}): Promise<RunningSer
await projects.open(path.resolve(opts.initialProject)).catch(() => undefined);
}

// Single-user assumption: the most recent session owns the preview proxy.
// The running app is workspace-level, not per-connection: it lives in the hub
// so a second tab or a reconnect sees the same status/preview and can Stop it.
const hub = new AppHub();
const sessions = new Set<Session>();
let currentSession: Session | null = null;

const server = http.createServer(async (req, res) => {
const url = req.url || '/';

if (url.startsWith('/__preview')) {
const preview = currentSession?.getPreview();
// The hub owns any running app; fall back to a session's preview for a
// dev server started in the terminal before an app is registered.
const preview = hub.runningPreview() ?? pickPreview(sessions, currentSession);
if (preview) preview.proxy(req, res);
else {
res.writeHead(503);
Expand Down Expand Up @@ -95,7 +102,8 @@ export async function createServer(opts: ServerOptions = {}): Promise<RunningSer
const emit = (event: UiEvent) => {
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(event));
};
const session = new Session(emit, projects);
const session = new Session(emit, projects, hub);
sessions.add(session);
currentSession = session;
session.init().catch((e) => emit({ type: 'error', scope: 'init', message: String(e) }));

Expand All @@ -110,7 +118,8 @@ export async function createServer(opts: ServerOptions = {}): Promise<RunningSer
});
ws.on('close', () => {
session.close();
if (currentSession === session) currentSession = null;
sessions.delete(session);
if (currentSession === session) currentSession = [...sessions].pop() ?? null;
});
});

Expand Down
90 changes: 86 additions & 4 deletions packages/server/src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ export class PreviewManager {
this.port = port;
}

/** Forget the port when the app stops, so the proxy stops pointing at a dead
* server and the next start re-emits preview_ready to refresh the iframe. */
clearPort(): void {
this.port = null;
}

getPort(): number | null {
return this.port;
}
Expand All @@ -29,21 +35,97 @@ export class PreviewManager {
res.end('No dev server detected yet. Run your dev command in the terminal.');
return true;
}
this.attempt(req, res, 0);
return true;
}

/**
* Forward one request to the app, retrying a fresh connection for idempotent
* requests. Dev servers with a reloader (Flask debug, nodemon) briefly refuse
* connections while restarting on boot; without the retry the iframe's first
* GET lands in that gap and shows "Preview target unreachable".
*/
private attempt(req: http.IncomingMessage, res: http.ServerResponse, tries: number): void {
const idempotent = !req.method || req.method === 'GET' || req.method === 'HEAD';
const targetPath = (req.url || '/').replace(/^\/__preview/, '') || '/';
const proxyReq = http.request(
{ host: '127.0.0.1', port: this.port, path: targetPath, method: req.method, headers: { ...req.headers, host: `127.0.0.1:${this.port}` } },
// Force identity encoding: we buffer and rewrite text/html as UTF-8, so a
// gzip/br response from the dev server would otherwise be corrupted.
{ host: '127.0.0.1', port: this.port ?? undefined, path: targetPath, method: req.method, headers: { ...req.headers, host: `127.0.0.1:${this.port}`, 'accept-encoding': 'identity' } },
(proxyRes) => {
res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);
const headers = { ...proxyRes.headers };
// Keep redirects inside the preview: `Location: /login` would otherwise
// send the iframe to OpenREPL's own /login.
const loc = headers.location;
if (typeof loc === 'string' && loc.startsWith('/') && !loc.startsWith('//')) {
headers.location = '/__preview' + loc;
}
// Root-absolute URLs in served HTML (href="/x", src="/x", action="/x")
// resolve against OpenREPL's origin, escape /__preview, and hit the SPA
// fallback → OpenREPL renders inside its own preview ("inception").
// Rewrite them to stay under /__preview so links, forms and assets go
// to the app instead.
if (String(headers['content-type'] || '').includes('text/html')) {
const chunks: Buffer[] = [];
proxyRes.on('data', (c: Buffer) => chunks.push(c));
proxyRes.on('end', () => {
const html = rewritePreviewHtml(Buffer.concat(chunks).toString('utf8'));
delete headers['content-length']; // length changed after rewrite
delete headers['content-encoding']; // we send decoded text
res.writeHead(proxyRes.statusCode || 502, headers);
res.end(html);
});
return;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
res.writeHead(proxyRes.statusCode || 502, headers);
proxyRes.pipe(res);
},
);
proxyReq.on('error', () => {
// Retry the reloader gap for idempotent requests (~1s of 200ms backoffs).
if (idempotent && tries < 5) {
setTimeout(() => this.attempt(req, res, tries + 1), 200);
return;
}
res.writeHead(502, { 'content-type': 'text/plain' });
res.end('Preview target unreachable.');
});
req.pipe(proxyReq);
return true;
// A GET/HEAD has no body to forward; ending directly lets us retry cleanly
// without re-piping an already-consumed request stream.
if (idempotent) proxyReq.end();
else req.pipe(proxyReq);
}
}

/**
* Prefix root-absolute URLs in HTML with /__preview so a server-rendered app's
* links/forms/assets stay in the preview iframe instead of escaping to OpenREPL.
* Leaves protocol-relative (//host) and absolute (http://) URLs untouched.
*/
export function rewritePreviewHtml(html: string): string {
return html
.replace(/(\s(?:href|src|action)\s*=\s*["'])\/(?!\/)/gi, '$1/__preview/')
.replace(/(url\(\s*["']?)\/(?!\/)/gi, '$1/__preview/');
}

/** Anything that can expose a preview — a Session, in practice. */
export interface PreviewSource {
getPreview(): PreviewManager | null;
}

/**
* Pick which session's preview the /__preview proxy should serve. Ownership
* follows the running app: the first live session whose preview has a detected
* port wins, so a second tab or a reconnect can't steal the proxy from the
* session that actually launched the dev server. Falls back to the most-recent
* session (which may have no port yet) for the pre-launch "no dev server" hint.
*/
export function pickPreview(sessions: Iterable<PreviewSource>, current: PreviewSource | null): PreviewManager | null {
for (const s of sessions) {
const p = s.getPreview();
if (p?.getPort() != null) return p;
}
return current?.getPreview() ?? null;
}

export function checkPort(port: number, host = '127.0.0.1', timeout = 500): Promise<boolean> {
Expand Down
Loading
Loading