Skip to content
Draft
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
Binary file added apps/studio/assets/midscene-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 33 additions & 0 deletions apps/studio/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "studio",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"build": "rsbuild build && node scripts/sync-static-assets.mjs",
"dev": "concurrently -k -n build,app \"rsbuild dev\" \"node scripts/wait-for-electron-build.mjs && node scripts/launch-electron-dev.mjs\"",
"preview": "rsbuild preview --environment renderer",
"start": "node scripts/sync-static-assets.mjs && electron dist/main/main.cjs",
"test": "vitest run"
},
"dependencies": {
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@rsbuild/core": "^1.6.15",
"@rsbuild/plugin-less": "^1.5.0",
"@rsbuild/plugin-react": "^1.4.1",
"@rsbuild/plugin-type-check": "^1.3.2",
"@tailwindcss/postcss": "4.1.11",
"@types/node": "^18.0.0",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"concurrently": "^8.2.0",
"electron": "41.2.0",
"less": "^4.2.0",
"tailwindcss": "4.1.11",
"typescript": "^5.8.3",
"vitest": "3.0.5"
}
}
7 changes: 7 additions & 0 deletions apps/studio/postcss.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default {
plugins: {
'@tailwindcss/postcss': {
preflight: false,
},
},
};
90 changes: 90 additions & 0 deletions apps/studio/rsbuild.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { defineConfig } from '@rsbuild/core';
import { pluginLess } from '@rsbuild/plugin-less';
import { pluginReact } from '@rsbuild/plugin-react';
import { pluginTypeCheck } from '@rsbuild/plugin-type-check';
import { version as appVersion } from './package.json';
import {
rendererDevHost,
rendererDevPort,
} from './scripts/renderer-dev-config.mjs';

export default defineConfig({
server: {
host: rendererDevHost,
port: rendererDevPort,
},
dev: {
writeToDisk: true,
},
plugins: [pluginReact(), pluginLess(), pluginTypeCheck()],
environments: {
renderer: {
html: {
title: 'Midscene Studio',
},
source: {
entry: {
index: './src/renderer/index.tsx',
},
define: {
__APP_VERSION__: JSON.stringify(appVersion),
},
},
output: {
target: 'web',
distPath: {
root: 'dist/renderer',
},
sourceMap: true,
},
},
main: {
tools: {
htmlPlugin: false,
},
source: {
entry: {
main: {
import: './src/main/index.ts',
html: false,
},
},
},
output: {
target: 'node',
distPath: {
root: 'dist/main',
},
filename: {
js: '[name].cjs',
},
externals: ['electron'],
sourceMap: true,
},
},
preload: {
tools: {
htmlPlugin: false,
},
source: {
entry: {
preload: {
import: './src/preload/index.ts',
html: false,
},
},
},
output: {
target: 'node',
distPath: {
root: 'dist/preload',
},
filename: {
js: '[name].cjs',
},
externals: ['electron'],
sourceMap: true,
},
},
},
});
37 changes: 37 additions & 0 deletions apps/studio/scripts/launch-electron-dev.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { rendererDevUrl } from './renderer-dev-config.mjs';

// Spawns Electron with MIDSCENE_STUDIO_RENDERER_URL sourced from the shared
// dev config, so the port is not duplicated in package.json scripts.
const require = createRequire(import.meta.url);
const electronBinary = require('electron');
const rootDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'..',
);

const child = spawn(
electronBinary,
[path.join(rootDir, 'dist/main/main.cjs')],
{
env: { ...process.env, MIDSCENE_STUDIO_RENDERER_URL: rendererDevUrl },
stdio: 'inherit',
},
);

const forwardSignal = (signal) => {
if (!child.killed) child.kill(signal);
};
process.on('SIGINT', forwardSignal);
process.on('SIGTERM', forwardSignal);

child.on('exit', (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
8 changes: 8 additions & 0 deletions apps/studio/scripts/renderer-dev-config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Single source of truth for the renderer dev server host/port.
// Imported by rsbuild.config.ts (to bind the dev server), by
// scripts/wait-for-electron-build.mjs (to probe readiness) and by
// scripts/launch-electron-dev.mjs (to tell the main process where
// to load from via MIDSCENE_STUDIO_RENDERER_URL).
export const rendererDevHost = '127.0.0.1';
export const rendererDevPort = 3210;
export const rendererDevUrl = `http://${rendererDevHost}:${rendererDevPort}`;
35 changes: 35 additions & 0 deletions apps/studio/scripts/sync-static-assets.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.resolve(__dirname, '..');

export const defaultSourceDir = path.join(rootDir, 'assets');
export const defaultTargetDir = path.join(rootDir, 'dist/assets');

/**
* Copy the shell's static assets into the build output, wiping any prior
* target contents first so files removed from source do not linger in dist.
* Throws if `sourceDir` does not exist — there is no meaningful fallback
* when the asset bundle is missing.
*/
export const syncStaticAssets = async ({
sourceDir = defaultSourceDir,
targetDir = defaultTargetDir,
} = {}) => {
await fs.access(sourceDir);
await fs.rm(targetDir, { force: true, recursive: true });
await fs.mkdir(path.dirname(targetDir), { recursive: true });
await fs.cp(sourceDir, targetDir, { recursive: true });
return targetDir;
};

const isDirectInvocation =
process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;

if (isDirectInvocation) {
const targetDir = await syncStaticAssets();
console.log(`Synced Midscene Studio static assets to ${targetDir}`);
}
122 changes: 122 additions & 0 deletions apps/studio/scripts/wait-for-electron-build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { rendererDevUrl } from './renderer-dev-config.mjs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.resolve(__dirname, '..');

export const defaultRequiredFiles = [
path.join(rootDir, 'dist/main/main.cjs'),
path.join(rootDir, 'dist/preload/preload.cjs'),
];

export const defaultRendererUrl = rendererDevUrl;
export const defaultMaxWaitMs = 180000;
export const defaultPollIntervalMs = 500;

export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export const readMtimeMs = (file) => {
try {
return fs.statSync(file).mtimeMs;
} catch (error) {
// Missing file is an expected signal ("not built yet"); anything else
// (permission denied, IO error, ...) should surface instead of being
// silently swallowed into a stale-build state.
if (error && error.code === 'ENOENT') return null;
throw new Error(
`wait-for-electron-build: failed to stat ${file}: ${
error instanceof Error ? error.message : String(error)
}`,
{ cause: error },
);
}
};

/**
* Build a "has this dev cycle produced a fresh build?" checker.
*
* The checker snapshots each required file's mtime at creation time, then
* on every call it returns true only when every file exists AND either was
* absent in the snapshot or now has a strictly newer mtime. This avoids
* treating stale dist artifacts from a previous `pnpm dev` run as "fresh".
*/
export const createFreshBuildChecker = (files, readMtime = readMtimeMs) => {
const initialMtimes = new Map(files.map((file) => [file, readMtime(file)]));

return () =>
files.every((file) => {
const current = readMtime(file);
if (current === null) {
return false;
}

const initial = initialMtimes.get(file);
return initial === null || current > initial;
});
};

export const checkRendererReady = (url) =>
new Promise((resolve) => {
const request = http.get(url, (response) => {
response.resume();
resolve(response.statusCode === 200);
});

request.on('error', () => resolve(false));
request.setTimeout(1000, () => {
request.destroy();
resolve(false);
});
});

/**
* Poll until the required build outputs are fresh AND the renderer dev
* server is serving a 200, or until `maxWaitMs` elapses. Dependencies are
* injectable so the loop can be unit-tested with a virtual clock.
*/
export const waitForBuild = async ({
requiredFiles = defaultRequiredFiles,
rendererUrl = defaultRendererUrl,
maxWaitMs = defaultMaxWaitMs,
pollIntervalMs = defaultPollIntervalMs,
readMtime = readMtimeMs,
isRendererReady = () => checkRendererReady(rendererUrl),
now = () => Date.now(),
delay = sleep,
} = {}) => {
const hasFreshBuild = createFreshBuildChecker(requiredFiles, readMtime);
const startedAt = now();

while (now() - startedAt < maxWaitMs) {
if (hasFreshBuild() && (await isRendererReady())) {
return true;
}

await delay(pollIntervalMs);
}

return false;
};

const isDirectInvocation =
process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;

if (isDirectInvocation) {
console.log('Waiting for Midscene Studio shell build output...');

const ready = await waitForBuild();

if (ready) {
console.log('Midscene Studio shell build is ready.');
process.exit(0);
}

console.error(
'Timed out waiting for the Midscene Studio shell build to finish.',
);
process.exit(1);
}
9 changes: 9 additions & 0 deletions apps/studio/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { ElectronShellApi } from './shared/electron-contract';

declare global {
interface Window {
electronShell?: ElectronShellApi;
}
}

declare const __APP_VERSION__: string;
Loading
Loading