Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ mcode-webui
With **npm 12 or later**, explicitly allow the native dependency install scripts:

```bash
npm install --global @minimax-webui/minimax-code --allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate
npm install --global @minimax-webui/minimax-code --allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate
```

The service listens on `http://127.0.0.1:2233/` and opens your default browser when launched in an interactive terminal. If it does not open, use the address printed in the terminal. Keep the process running while you work; press **Ctrl+C** to stop it.
Expand Down
2 changes: 1 addition & 1 deletion README_ZH.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ mcode-webui
使用 **npm 12 及以上版本**时,需要显式允许原生依赖的安装脚本:

```bash
npm install --global @minimax-webui/minimax-code --allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate
npm install --global @minimax-webui/minimax-code --allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate
```

服务默认监听 `http://127.0.0.1:2233/`,在交互式终端启动时会打开默认浏览器。如果没有自动打开,使用终端打印的地址。使用期间保持服务进程运行,按 **Ctrl+C** 停止。
Expand Down
4 changes: 2 additions & 2 deletions packages/webui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ With npm 12 or later, explicitly allow the native dependency install scripts:

```sh
npm install --global @minimax-webui/minimax-code \
--allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate
--allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate
```

To install the preview channel, use `@minimax-webui/minimax-code@preview` instead.
Expand Down Expand Up @@ -198,7 +198,7 @@ node scripts/package-webui-npm.mjs --version 0.1.6-dev.1 \
--outdir ../minimax-code-webui-build/package
npm pack ../minimax-code-webui-build/package --pack-destination ../minimax-code-webui-build
npm install --global ../minimax-code-webui-build/minimax-webui-minimax-code-0.1.6-dev.1.tgz \
--allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate
--allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate
mcode-webui --version
WEBUI_OPEN_BROWSER=0 mcode-webui --full-access
```
Expand Down
12 changes: 10 additions & 2 deletions packages/webui/docs/client/composer.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ the notice shows a transfer error beside its action so the user can select anoth
## Workspace folder selection

On the home page, `选择新项目` opens the system folder chooser in the browser
paired by an interactive local `mcode-webui` launch. Windows and macOS use their
system dialogs. On a Linux desktop the launcher uses Zenity or KDialog. Zenity opens
paired by an interactive local `mcode-webui` launch. Windows opens the native
`IFileOpenDialog` from a short-lived koffi worker, which also brings the dialog
to the foreground when the server was started in the background; macOS uses its
system dialog. On a Linux desktop the launcher uses Zenity or KDialog. Zenity opens
in the last folder confirmed during this launch if it still exists, or in the user's
home directory. This lets the chooser open even if a desktop application previously
selected a folder that has since been removed. Confirming
Expand All @@ -50,6 +52,12 @@ same origin use that pairing. After a restart, the launcher tab renews it for
the browser. A remote or unpaired browser can select a recent project or
`不需要项目`. Requesting a new folder without a native chooser displays a notice.

A local desktop host that embeds the page can receive the same grant URL through
`WEBUI_LAUNCH_URL_FILE` when it starts `mcode-webui` with `WEBUI_DESKTOP_HOST=1`.
The file is owner-only and the grant remains one-time; the route's loopback,
Host, Origin, cookie, grant and browserKey checks are unchanged. `WEBUI_OPEN_BROWSER`
still controls only the system browser.

## Where the pieces live

- The surface is `client/features/composer/ui/WebuiComposer.tsx`, with the editor staging, menus,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,15 @@ export interface WebuiTaskSessionStorage {
/**
* The catalogue reads creation completion invalidates. Injected because
* `client/application/` composes owners rather than calling transport itself.
* The project list is one of those reads: a session created in a new directory
* adds a project row the rail only sees after this read.
*/
export interface WebuiTaskSessionCatalogue {
readonly canLoadFlat: boolean;
readonly canLoadTree: boolean;
readonly loadFlat: () => Promise<void>;
readonly loadTree: () => Promise<void>;
readonly loadProjects?: () => Promise<unknown>;
}

export interface WebuiTaskSessionDeps {
Expand Down Expand Up @@ -292,6 +295,12 @@ export function createWebuiTaskSessionWorkflows(
// the created session and does not trigger a second creation.
catalogueError = formatWebuiError(error);
}
// A session created in a new directory adds a project row. The session
// catalogue above does not carry project records, so the rail would keep
// its pre-creation grouping until a full page reload without this read.
// The projects owner keeps its own error state; a failure here must not
// turn a successful creation into a failed one.
try { await catalogue.loadProjects?.(); } catch { /* Projects owns the rail's retry/error surface. */ }

return {
kind: "created",
Expand Down
27 changes: 27 additions & 0 deletions packages/webui/test/unit/task-session-workflows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ interface HarnessOptions {
) => Promise<WebuiClientCreateSessionResult>;
readonly loadFlat?: () => Promise<void>;
readonly loadTree?: () => Promise<void>;
readonly loadProjects?: () => Promise<void>;
readonly store?: WebuiSessionStore;
readonly noProjectPersisted?: boolean;
}
Expand Down Expand Up @@ -80,6 +81,10 @@ function harness(options: HarnessOptions = {}) {
catalogueCalls.push("tree");
await options.loadTree?.();
},
loadProjects: async () => {
catalogueCalls.push("projects");
await options.loadProjects?.();
},
},
...(options.createSession
? {
Expand Down Expand Up @@ -271,6 +276,28 @@ describe("the creation use case", () => {
expect(outcome).toMatchObject({ kind: "creation-failed" });
});

it("refreshes the project list after a session is created", async () => {
const { workflows, catalogueCalls } = harness({
createSession: async () => ({ sessionId: "s1" }),
});
const outcome = await workflows.submit({ workspaceDir: "/new-project" });
expect(outcome).toMatchObject({ kind: "created", sessionId: "s1" });
expect(catalogueCalls).toEqual(["flat", "tree", "projects"]);
});

it("keeps the created session when the project refresh fails", async () => {
const { workflows } = harness({
createSession: async () => ({ sessionId: "s1" }),
loadProjects: async () => {
throw new Error("projects down");
},
});
await expect(workflows.submit({ workspaceDir: "/new-project" })).resolves.toMatchObject({
kind: "created",
sessionId: "s1",
});
});

it("records a catalogue failure without undoing the created session", async () => {
const { workflows, store } = harness({
createSession: async () => ({ sessionId: "s1" }),
Expand Down
6 changes: 5 additions & 1 deletion release/public-source.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 25 additions & 5 deletions release/webui-npm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,19 @@ explicitly — npm 12 blocks dependency install scripts unless they are named:

```sh
npm install --global @minimax-webui/minimax-code \
--allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate
--allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate
```

Or allow them for every global install:

```sh
npm config set allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate --location=user
npm config set allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate --location=user
```

An install that skipped them leaves `better-sqlite3` without its binding, and
`mcode-webui` then stops at startup and prints the reinstall command instead of
running. npm 11 and earlier print the same warning but still run the scripts.
An install that skipped them leaves a native module (`better-sqlite3` or
`koffi`) without its binding, and `mcode-webui` then stops at startup and prints
the reinstall command instead of running. npm 11 and earlier print the same
warning but still run the scripts.

The server listens on `http://127.0.0.1:2233/`. Set `WEBUI_SERVER_PORT` to
change the port or `MINIMAX_DATA_DIR` to change the local data directory. The
Expand Down Expand Up @@ -62,4 +63,23 @@ listening. Set `WEBUI_OPEN_BROWSER=0` to keep it from doing that; with the
variable unset it stays quiet when the command's output is not a terminal, so a
script, a service supervisor or a CI job never takes over the desktop.

### Desktop host handoff

A local desktop host that embeds the page cannot rely on the system browser to
open the one-time native-directory grant URL. It can start the launcher with
`WEBUI_DESKTOP_HOST=1` and `WEBUI_LAUNCH_URL_FILE=<absolute path>`; after the
server is listening, the launcher writes the page URL with its
`#nativeDirectoryGrant` fragment to that private file with owner-only access
(0600 on POSIX; the user-profile ACL on Windows) and does not log it. The host
opens that URL in its own embedded page, and the existing grant/cookie/browserKey
pairing completes. The file contains only the URL — no JSON, no extra fields.

`WEBUI_DESKTOP_HOST=1` also lets the native-directory picker be created without
an interactive TTY; ordinary launches still require one. `WEBUI_OPEN_BROWSER=0`
still only means "do not open the system browser" and never disables the picker.
The HTTP route's loopback, Host, Origin, `Sec-Fetch-Site`, cookie, grant and
browserKey checks are unchanged. If the handoff file cannot be written, the
launcher logs the path and the host should fall back to the printed bare WebUI
URL; the native picker may then be unavailable.

The package requires a supported Node.js version shown in its `engines` field.
60 changes: 60 additions & 0 deletions release/webui-npm/bin/desktop-launch.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Desktop-host handoff for the one-time native-directory grant.
//
// The grant rides in the page URL fragment. A host that embeds the page cannot
// rely on the system browser opening that URL, so it names a private file; the
// launcher writes the URL there with owner-only permissions and never logs it.
// The HTTP route still checks the grant, pairing cookie and browser key.

import { randomUUID } from 'node:crypto';
import { chmod, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';

import { nativeDirectoryLaunchUrl } from './native-directory-picker.mjs';

const FILE_MODE = 0o600;

export function browserOpenEnabled(setting, tty) {
const normalized = setting?.trim().toLowerCase();
return normalized === undefined || normalized === ''
? Boolean(tty)
: !['0', 'false', 'no', 'off', 'never'].includes(normalized);
}

export async function writeLaunchUrlFile(file, url) {
if (typeof file !== 'string' || !path.isAbsolute(file)) {
throw new Error('WEBUI_LAUNCH_URL_FILE must be an absolute path');
}
const temporary = path.join(
path.dirname(file),
'.' + path.basename(file) + '.' + randomUUID() + '.tmp',
);
try {
await writeFile(temporary, url, { encoding: 'utf8', mode: FILE_MODE, flag: 'wx' });
// POSIX mode is the contract; Windows keeps the file under the user
// profile instead of exposing a group/other-readable location.
await chmod(temporary, FILE_MODE);
try {
await rename(temporary, file);
} catch (error) {
// Windows rename does not replace an existing target.
if (error.code !== 'EEXIST' && error.code !== 'EPERM') throw error;
await rm(file, { force: true });
await rename(temporary, file);
}
} finally {
await rm(temporary, { force: true }).catch(() => {});
}
}

export async function handoffDesktopLaunchUrl({ desktopHost, picker, file, browserUrl }) {
if (!desktopHost || !picker || !file) return { kind: 'skipped' };
try {
await writeLaunchUrlFile(file, nativeDirectoryLaunchUrl(browserUrl, picker.grant));
return { kind: 'written' };
} catch (error) {
// A stale file would make the host open a launch URL with another process's
// grant. Remove it so the host's missing-file fallback is unambiguous.
if (path.isAbsolute(file)) await rm(file, { force: true }).catch(() => {});
return { kind: 'failed', error };
}
}
27 changes: 20 additions & 7 deletions release/webui-npm/bin/mcode-webui.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ Start the MiniMax Code WebUI. Configuration is read from environment variables:
WEBUI_HOST Bind address (default: 127.0.0.1)
WEBUI_SERVER_PORT WebUI port (default: 2233)
WEBUI_MINIAPP_PORT Mini App port (default: 49152)
WEBUI_DESKTOP_HOST Set to 1 when a local desktop host embeds the page
WEBUI_LAUNCH_URL_FILE Absolute path for the private launch URL handoff

-h, --help Show help without starting the runtime
-v, --version Show the installed version
Expand All @@ -36,6 +38,8 @@ if (args.version) {
process.exit(0);
}

const { browserOpenEnabled, handoffDesktopLaunchUrl } = await import("./desktop-launch.mjs");

// Help/version must not load native modules, access user data or open listeners.
const {
WebuiService,
Expand Down Expand Up @@ -75,6 +79,8 @@ const dataDir = process.env.MINIMAX_DATA_DIR?.trim() || path.join(os.homedir(),
// a request that did not arrive over loopback presents the per-start
// credential, so the printed URL carries it.
const bindHost = process.env.WEBUI_HOST?.trim() || "127.0.0.1";
const desktopHost = process.env.WEBUI_DESKTOP_HOST?.trim() === "1";
const launchUrlFile = process.env.WEBUI_LAUNCH_URL_FILE?.trim() || undefined;
process.env.MAVIS_BUILTIN_AGENTS_V2_DIR ??= path.join(packageRoot, "assets/agents");
process.env.MAVIS_BUILTIN_AGENTS_DIR ??= path.join(packageRoot, "assets/agents");

Expand All @@ -92,7 +98,7 @@ process.env.MAVIS_BUILTIN_AGENTS_DIR ??= path.join(packageRoot, "assets/agents")
* The check is here, at the composition root, because it is the last place that
* knows both the dependency list and the package name a person can reinstall.
*/
const NATIVE_MODULES = ["better-sqlite3", "node-pty"];
const NATIVE_MODULES = ["better-sqlite3", ...(process.platform === "win32" ? ["koffi"] : []), "node-pty"];
/**
* Load each module the way the runtime will.
*
Expand All @@ -105,6 +111,7 @@ const NATIVE_PROBES = {
"better-sqlite3": (module) => {
new module(":memory:").close();
},
"koffi": () => {},
"node-pty": () => {},
};
const unbuilt = [];
Expand Down Expand Up @@ -260,8 +267,8 @@ await browser.initialize();
const { nativeDirectoryPickerEligible, createNativeDirectoryPicker, nativeDirectoryLaunchUrl } =
await import("./native-directory-picker.mjs");
const nativeDirectoryPicker = nativeDirectoryPickerEligible({
platform: process.platform, tty: Boolean(process.stdout.isTTY), bindHost,
fullAccess: args["full-access"], browserSetting: process.env.WEBUI_OPEN_BROWSER,
platform: process.platform, tty: Boolean(process.stdout.isTTY), desktopHost,
bindHost, fullAccess: args["full-access"],
}) ? createNativeDirectoryPicker() : undefined;
const service = new WebuiService({
nativeDirectoryPicker,
Expand Down Expand Up @@ -320,6 +327,15 @@ try {
// runtime draws its own Mini App ports from the same range, and a listener
// that waited would lose this one.
await miniappProxies.prepare();
const handoff = await handoffDesktopLaunchUrl({
desktopHost, picker: nativeDirectoryPicker, file: launchUrlFile, browserUrl,
});
if (handoff.kind === "failed") {
console.warn(
`[mcode-webui] could not write WEBUI_LAUNCH_URL_FILE (${launchUrlFile}); ` +
`the desktop host should use the printed WebUI URL instead: ${handoff.error.message}`,
);
}
console.log(`[mcode-webui] WebUI running at ${browserUrl}`);
console.log(
`[mcode-webui] Mini App port: ${miniappPort} — forward it, or a Mini App loads blank`,
Expand Down Expand Up @@ -411,10 +427,7 @@ function lanAddresses() {
* browser could not start would turn a convenience into an outage.
*/
function openBrowser(url, printableUrl = url) {
const setting = process.env.WEBUI_OPEN_BROWSER?.trim().toLowerCase();
const disabled = setting === "0" || setting === "false" || setting === "no" || setting === "off" || setting === "never";
const enabled = setting === undefined || setting === "" ? Boolean(process.stdout.isTTY) : !disabled;
if (!enabled) return;
if (!browserOpenEnabled(process.env.WEBUI_OPEN_BROWSER, process.stdout.isTTY)) return;
// Each platform names its launcher differently, and Windows' `start` is a
// shell builtin, so it needs a command interpreter in front of it. The empty
// argument is `start`'s window-title slot: without it a quoted URL is read as
Expand Down
Loading
Loading