larness 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/app.js +122 -0
- package/apps/server/dist/address-BE25lU9-.js +94 -0
- package/apps/server/dist/client-Co1thYbK.js +120 -0
- package/apps/server/dist/doctor-ClvbJZvj.js +127 -0
- package/apps/server/dist/doctor.js +12 -0
- package/apps/server/dist/index.js +27349 -0
- package/apps/server/dist/lock-DyEoZgG_.js +101 -0
- package/apps/server/dist/managed-CLFUiDbj.js +2138 -0
- package/apps/server/dist/paths-BHryFHwq.js +2337 -0
- package/apps/server/dist/status-idXF0pm6.js +49 -0
- package/apps/server/dist/status.js +30 -0
- package/apps/server/dist/tui.js +1626 -0
- package/apps/server/drizzle/0001_auth.sql +110 -0
- package/apps/server/drizzle/0002_projects.sql +13 -0
- package/apps/server/drizzle/0003_workspace.sql +81 -0
- package/apps/server/drizzle/0004_models.sql +30 -0
- package/apps/server/drizzle/0005_resources.sql +54 -0
- package/apps/server/drizzle/0006_commands.sql +24 -0
- package/apps/server/drizzle/0007_terminals.sql +42 -0
- package/apps/server/drizzle/0008_resource_actions.sql +24 -0
- package/apps/server/drizzle/0009_terminal_title.sql +1 -0
- package/apps/server/drizzle/0010_services.sql +32 -0
- package/apps/server/drizzle/0011_deployments.sql +88 -0
- package/apps/server/drizzle/0012_deployment_authorizations.sql +67 -0
- package/apps/server/drizzle/0013_service_ops.sql +64 -0
- package/apps/server/drizzle/0014_service_actions.sql +36 -0
- package/apps/server/drizzle/0015_model_catalog.sql +17 -0
- package/apps/server/drizzle/0016_multi_provider.sql +2 -0
- package/apps/server/drizzle/0017_model_visibility.sql +10 -0
- package/apps/server/drizzle/0018_model_defaults.sql +9 -0
- package/apps/server/drizzle/0019_credential_endpoint.sql +1 -0
- package/apps/server/drizzle/0020_compatible_context.sql +1 -0
- package/apps/server/drizzle/0021_context_summaries.sql +13 -0
- package/apps/server/drizzle/0022_scheduler.sql +58 -0
- package/apps/server/drizzle/0023_turn_terminal_reason.sql +1 -0
- package/apps/server/drizzle/0024_turn_checkpoints.sql +4 -0
- package/apps/server/drizzle/0025_turn_resume.sql +1 -0
- package/apps/server/drizzle/0026_session_pin.sql +1 -0
- package/apps/server/drizzle/0027_project_sort_order.sql +2 -0
- package/apps/server/drizzle/meta/0001_snapshot.json +705 -0
- package/apps/server/drizzle/meta/0002_snapshot.json +784 -0
- package/apps/server/drizzle/meta/0003_snapshot.json +1300 -0
- package/apps/server/drizzle/meta/0004_snapshot.json +1489 -0
- package/apps/server/drizzle/meta/0005_snapshot.json +1794 -0
- package/apps/server/drizzle/meta/0006_snapshot.json +1953 -0
- package/apps/server/drizzle/meta/0007_snapshot.json +2232 -0
- package/apps/server/drizzle/meta/0008_snapshot.json +2391 -0
- package/apps/server/drizzle/meta/0009_snapshot.json +2398 -0
- package/apps/server/drizzle/meta/0010_snapshot.json +2601 -0
- package/apps/server/drizzle/meta/0015_snapshot.json +4332 -0
- package/apps/server/drizzle/meta/0016_snapshot.json +4346 -0
- package/apps/server/drizzle/meta/0017_snapshot.json +4408 -0
- package/apps/server/drizzle/meta/0018_snapshot.json +4468 -0
- package/apps/server/drizzle/meta/0019_snapshot.json +4475 -0
- package/apps/server/drizzle/meta/0020_snapshot.json +4482 -0
- package/apps/server/drizzle/meta/0021_snapshot.json +4565 -0
- package/apps/server/drizzle/meta/0022_snapshot.json +4960 -0
- package/apps/server/drizzle/meta/0023_snapshot.json +4967 -0
- package/apps/server/drizzle/meta/0024_snapshot.json +4994 -0
- package/apps/server/drizzle/meta/0025_snapshot.json +5001 -0
- package/apps/server/drizzle/meta/0026_snapshot.json +5008 -0
- package/apps/server/drizzle/meta/0027_snapshot.json +5021 -0
- package/apps/server/drizzle/meta/_journal.json +195 -0
- package/apps/server/package.json +57 -0
- package/apps/web/dist/assets/FileEditor-twkRcPR8.js +1 -0
- package/apps/web/dist/assets/FileViewer-B6J1gfWW.js +1 -0
- package/apps/web/dist/assets/abap-08VXUWAP.js +1 -0
- package/apps/web/dist/assets/apex-BWPQTe0t.js +1 -0
- package/apps/web/dist/assets/azcli-Bc_sGQ0U.js +1 -0
- package/apps/web/dist/assets/bat-i0X4ZdIN.js +1 -0
- package/apps/web/dist/assets/bicep-B5-_aFwp.js +2 -0
- package/apps/web/dist/assets/cameligo-DMUM7wLl.js +1 -0
- package/apps/web/dist/assets/clojure-Cm7r79vr.js +1 -0
- package/apps/web/dist/assets/codicon-DF1abBS2.ttf +0 -0
- package/apps/web/dist/assets/coffee-Ba7i2nA0.js +1 -0
- package/apps/web/dist/assets/cpp-C7h46wYY.js +1 -0
- package/apps/web/dist/assets/csharp-BKxtCVv1.js +1 -0
- package/apps/web/dist/assets/csp-bTuwJoIa.js +1 -0
- package/apps/web/dist/assets/css-DIMkf-bt.js +3 -0
- package/apps/web/dist/assets/css.worker-C5TGqYcS.js +96 -0
- package/apps/web/dist/assets/cssMode-B2gCrV51.js +1 -0
- package/apps/web/dist/assets/cypher-CVaqCwHa.js +1 -0
- package/apps/web/dist/assets/dart-onAF5SnQ.js +1 -0
- package/apps/web/dist/assets/dockerfile-DZFCIeNp.js +1 -0
- package/apps/web/dist/assets/ecl-94qehhXe.js +1 -0
- package/apps/web/dist/assets/editor-B8GMDV7_.css +1 -0
- package/apps/web/dist/assets/editor.api-TQGsXQVT.js +908 -0
- package/apps/web/dist/assets/editor.worker-uJzjfcWc.js +33 -0
- package/apps/web/dist/assets/elixir-6RTg0lbw.js +1 -0
- package/apps/web/dist/assets/flow9-C5_-GSwl.js +1 -0
- package/apps/web/dist/assets/freemarker2-Due01FLd.js +3 -0
- package/apps/web/dist/assets/fsharp-C8Ef5oNN.js +1 -0
- package/apps/web/dist/assets/go-C-y9NEjX.js +1 -0
- package/apps/web/dist/assets/graphql-fmXr3nnJ.js +1 -0
- package/apps/web/dist/assets/handlebars-Cbmho-0R.js +1 -0
- package/apps/web/dist/assets/hcl-CpzslTdj.js +1 -0
- package/apps/web/dist/assets/html-1Ke8CI8o.js +1 -0
- package/apps/web/dist/assets/html.worker-DthhmbAk.js +509 -0
- package/apps/web/dist/assets/htmlMode-KxcipU--.js +1 -0
- package/apps/web/dist/assets/index-BvfzAW2A.js +158 -0
- package/apps/web/dist/assets/index-DxcI8GSl.css +1 -0
- package/apps/web/dist/assets/ini-sBoK_t0W.js +1 -0
- package/apps/web/dist/assets/java-BEtHBSE6.js +1 -0
- package/apps/web/dist/assets/javascript-DMPkDcJu.js +1 -0
- package/apps/web/dist/assets/json.worker-BGaEIa3n.js +65 -0
- package/apps/web/dist/assets/jsonMode-CLqudskm.js +7 -0
- package/apps/web/dist/assets/julia-Bri6UV-V.js +1 -0
- package/apps/web/dist/assets/kotlin-BOotOW0E.js +1 -0
- package/apps/web/dist/assets/less-B9JPFI3C.js +2 -0
- package/apps/web/dist/assets/lexon-CfSJPG6W.js +1 -0
- package/apps/web/dist/assets/liquid-bIUiAHG1.js +1 -0
- package/apps/web/dist/assets/lspLanguageFeatures-CplKbdW4.js +4 -0
- package/apps/web/dist/assets/lua-CsQS60Ue.js +1 -0
- package/apps/web/dist/assets/m3-D-oSqn_W.js +1 -0
- package/apps/web/dist/assets/markdown-Cimd5fb3.js +1 -0
- package/apps/web/dist/assets/mdx-DiInMCu3.js +1 -0
- package/apps/web/dist/assets/mips-CIPQ_RoX.js +1 -0
- package/apps/web/dist/assets/monaco-D_A7VB90.js +68 -0
- package/apps/web/dist/assets/monaco-n7clI0si.css +1 -0
- package/apps/web/dist/assets/msdax-DauUninz.js +1 -0
- package/apps/web/dist/assets/mysql-SOo6toE5.js +1 -0
- package/apps/web/dist/assets/objective-c-FvmIjYaQ.js +1 -0
- package/apps/web/dist/assets/pascal-DrH0SRf2.js +1 -0
- package/apps/web/dist/assets/pascaligo-D-ptJ9y-.js +1 -0
- package/apps/web/dist/assets/perl-oz_6vUea.js +1 -0
- package/apps/web/dist/assets/pgsql-DTj74zXo.js +1 -0
- package/apps/web/dist/assets/php-nr791fC2.js +1 -0
- package/apps/web/dist/assets/pla-CopQ2nXW.js +1 -0
- package/apps/web/dist/assets/postiats-43DmfD33.js +1 -0
- package/apps/web/dist/assets/powerquery-D3hlyOfw.js +1 -0
- package/apps/web/dist/assets/powershell-DmHpPYUd.js +1 -0
- package/apps/web/dist/assets/protobuf-C531GsRP.js +2 -0
- package/apps/web/dist/assets/pug-Z5eAx3Zn.js +1 -0
- package/apps/web/dist/assets/python-O93J5sRJ.js +1 -0
- package/apps/web/dist/assets/qsharp-DkqhCAOL.js +1 -0
- package/apps/web/dist/assets/r-BwWrilGY.js +1 -0
- package/apps/web/dist/assets/razor-DpA8sAYd.js +1 -0
- package/apps/web/dist/assets/redis-ClamHrr6.js +1 -0
- package/apps/web/dist/assets/redshift-DT7zqm-g.js +1 -0
- package/apps/web/dist/assets/restructuredtext-BYgofb2h.js +1 -0
- package/apps/web/dist/assets/ruby-DezsRK8O.js +1 -0
- package/apps/web/dist/assets/rust-DdL9SqIa.js +1 -0
- package/apps/web/dist/assets/sb-CcwsVR0C.js +1 -0
- package/apps/web/dist/assets/scala-DHpiXF5c.js +1 -0
- package/apps/web/dist/assets/scheme-BeGwcela.js +1 -0
- package/apps/web/dist/assets/scss-gp-XZpBa.js +3 -0
- package/apps/web/dist/assets/shell-CC2rA5mh.js +1 -0
- package/apps/web/dist/assets/solidity-BEEn4gHE.js +1 -0
- package/apps/web/dist/assets/sophia-CRfGWb83.js +1 -0
- package/apps/web/dist/assets/sparql-D_Lu-MrJ.js +1 -0
- package/apps/web/dist/assets/sql-NEE52Syq.js +1 -0
- package/apps/web/dist/assets/st-DbInun42.js +1 -0
- package/apps/web/dist/assets/swift-Bxkupp3x.js +1 -0
- package/apps/web/dist/assets/systemverilog-Bz4Y3fRF.js +1 -0
- package/apps/web/dist/assets/tcl-DISqw1ZD.js +1 -0
- package/apps/web/dist/assets/ts.worker-CUR_zL4j.js +67741 -0
- package/apps/web/dist/assets/tsMode-qBmFN2NS.js +11 -0
- package/apps/web/dist/assets/twig-De2hgUGE.js +1 -0
- package/apps/web/dist/assets/typescript-BjR2yH8S.js +1 -0
- package/apps/web/dist/assets/typespec-B8J7ngcE.js +1 -0
- package/apps/web/dist/assets/vb-DV3o63ZY.js +1 -0
- package/apps/web/dist/assets/wgsl-DpFanUEy.js +298 -0
- package/apps/web/dist/assets/workers-x9_8y1ur.js +1 -0
- package/apps/web/dist/assets/xml-CL70_TAY.js +1 -0
- package/apps/web/dist/assets/yaml-qno5z39m.js +1 -0
- package/apps/web/dist/favicon.svg +4 -0
- package/apps/web/dist/index.html +15 -0
- package/docs/README.md +26 -0
- package/docs/guides/install.md +88 -0
- package/package.json +95 -4
|
@@ -0,0 +1,1626 @@
|
|
|
1
|
+
import { _ as formatPairingCode, a as DevWebControl, c as EntryConfigError, d as devWebCache, i as DevWebAttachedSchema, r as waitChildMessage, rt as terminateProcessTree, s as DevWebUnavailable } from "./managed-CLFUiDbj.js";
|
|
2
|
+
import { n as connectIpc, t as IpcClientError } from "./client-Co1thYbK.js";
|
|
3
|
+
import { a as inspectPendingInitialization, c as loadConfig, f as findServerRoot, gn as DEFAULT_APP_CONFIG, l as resolveConfig, m as SERVER_VERSION, r as resolveDataDir, s as configFilePath, vn as deriveWebAuthn } from "./paths-BHryFHwq.js";
|
|
4
|
+
import { s as InitApplyParamsSchema } from "./address-BE25lU9-.js";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { existsSync } from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { stripVTControlCharacters } from "node:util";
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
import { PassThrough, Writable } from "node:stream";
|
|
15
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
16
|
+
import semver from "semver";
|
|
17
|
+
import { confirm, input } from "@inquirer/prompts";
|
|
18
|
+
import { emitKeypressEvents } from "node:readline";
|
|
19
|
+
import stringWidth from "fast-string-width";
|
|
20
|
+
import { wrapAnsi } from "fast-wrap-ansi";
|
|
21
|
+
import pc from "picocolors";
|
|
22
|
+
// src/modules/updates/npm.ts
|
|
23
|
+
const CHECK_INTERVAL_MS = 864e5;
|
|
24
|
+
const DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
25
|
+
function statePath(dataDir) {
|
|
26
|
+
return path.join(dataDir, "updates", "state.json");
|
|
27
|
+
}
|
|
28
|
+
async function readState(file) {
|
|
29
|
+
try {
|
|
30
|
+
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
31
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
|
|
32
|
+
return parsed;
|
|
33
|
+
} catch {
|
|
34
|
+
return {};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function writeState(file, state) {
|
|
38
|
+
try {
|
|
39
|
+
await mkdir(path.dirname(file), {
|
|
40
|
+
recursive: true,
|
|
41
|
+
mode: 448
|
|
42
|
+
});
|
|
43
|
+
await writeFile(file, JSON.stringify(state), { mode: 384 });
|
|
44
|
+
await chmod(file, 384);
|
|
45
|
+
} catch {}
|
|
46
|
+
}
|
|
47
|
+
function isChannel(value) {
|
|
48
|
+
return value === "stable" || value === "beta";
|
|
49
|
+
}
|
|
50
|
+
function commandFor(channel) {
|
|
51
|
+
return channel === "beta" ? "npm install -g larness@beta" : "npm install -g larness@latest";
|
|
52
|
+
}
|
|
53
|
+
async function checkForUpdate(options) {
|
|
54
|
+
if (options.version === "0.0.0" || process.env.LARNESS_DEV === "1") return null;
|
|
55
|
+
if (!semver.valid(options.version)) return null;
|
|
56
|
+
const now = options.now ?? Date.now;
|
|
57
|
+
const channel = options.channel ?? "stable";
|
|
58
|
+
const file = statePath(options.dataDir);
|
|
59
|
+
const state = await readState(file);
|
|
60
|
+
const timestamp = now();
|
|
61
|
+
if (typeof state.lastAttemptAt === "number" && timestamp - state.lastAttemptAt < CHECK_INTERVAL_MS) return null;
|
|
62
|
+
const registry = (options.registryUrl ?? DEFAULT_REGISTRY).replace(/\/$/, "");
|
|
63
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
64
|
+
let latestVersion;
|
|
65
|
+
try {
|
|
66
|
+
const response = await fetchImpl(`${registry}/-/package/larness/dist-tags`, {
|
|
67
|
+
headers: { accept: "application/json" },
|
|
68
|
+
redirect: "error",
|
|
69
|
+
signal: AbortSignal.timeout(5e3)
|
|
70
|
+
});
|
|
71
|
+
if (!response.ok) {
|
|
72
|
+
await writeState(file, {
|
|
73
|
+
...state,
|
|
74
|
+
lastAttemptAt: timestamp,
|
|
75
|
+
channel
|
|
76
|
+
});
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
const candidate = (await response.json())[channel === "beta" ? "beta" : "latest"];
|
|
80
|
+
if (typeof candidate !== "string" || !semver.valid(candidate)) {
|
|
81
|
+
await writeState(file, {
|
|
82
|
+
...state,
|
|
83
|
+
lastAttemptAt: timestamp,
|
|
84
|
+
channel
|
|
85
|
+
});
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
latestVersion = candidate;
|
|
89
|
+
} catch {
|
|
90
|
+
await writeState(file, {
|
|
91
|
+
...state,
|
|
92
|
+
lastAttemptAt: timestamp,
|
|
93
|
+
channel
|
|
94
|
+
});
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
const nextState = {
|
|
98
|
+
lastAttemptAt: timestamp,
|
|
99
|
+
lastCheckedAt: timestamp,
|
|
100
|
+
channel
|
|
101
|
+
};
|
|
102
|
+
if (!semver.gt(latestVersion, options.version)) {
|
|
103
|
+
await writeState(file, nextState);
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
if (state.lastNotifiedVersion === latestVersion && state.channel === channel) {
|
|
107
|
+
await writeState(file, nextState);
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
await writeState(file, {
|
|
111
|
+
...nextState,
|
|
112
|
+
lastNotifiedVersion: latestVersion
|
|
113
|
+
});
|
|
114
|
+
return {
|
|
115
|
+
currentVersion: options.version,
|
|
116
|
+
latestVersion,
|
|
117
|
+
channel,
|
|
118
|
+
command: commandFor(channel),
|
|
119
|
+
checkedAt: timestamp
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function updateNoticeText(notice) {
|
|
123
|
+
return `有新版本 ${notice.latestVersion}(当前 ${notice.currentVersion})· 运行 ${notice.command}`;
|
|
124
|
+
}
|
|
125
|
+
function updateChannel(value) {
|
|
126
|
+
return isChannel(value) ? value : "stable";
|
|
127
|
+
}
|
|
128
|
+
// src/tui/init-wizard.ts
|
|
129
|
+
var TuiError = class extends Error {
|
|
130
|
+
constructor(message) {
|
|
131
|
+
super(message);
|
|
132
|
+
this.name = "TuiError";
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
function buildInitRequest(answers) {
|
|
136
|
+
const port = Number(answers.port.trim());
|
|
137
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new TuiError("端口必须是 1-65535 的整数");
|
|
138
|
+
const parsed = InitApplyParamsSchema.required({
|
|
139
|
+
host: true,
|
|
140
|
+
port: true,
|
|
141
|
+
publicUrl: true
|
|
142
|
+
}).safeParse({
|
|
143
|
+
host: answers.host.trim(),
|
|
144
|
+
port,
|
|
145
|
+
publicUrl: answers.publicUrl.trim() || null
|
|
146
|
+
});
|
|
147
|
+
if (!parsed.success) throw new TuiError("监听地址或浏览器访问地址不合法;地址须为不带路径的 http(s) 来源");
|
|
148
|
+
const params = parsed.data;
|
|
149
|
+
const webAuthn = deriveWebAuthn(params, "Larness");
|
|
150
|
+
return {
|
|
151
|
+
params,
|
|
152
|
+
origin: webAuthn.origin,
|
|
153
|
+
rpId: webAuthn.rpId,
|
|
154
|
+
passkeyEnabled: webAuthn.enabled,
|
|
155
|
+
warning: webAuthn.reason === "rp_id_is_ip" ? "警告:RP ID 是 IP 地址,Passkey 不可用,只能使用 allow_once" : webAuthn.reason === "remote_http" ? "警告:远程 http 来源,Passkey 不可用,只能使用 allow_once" : null
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
// src/tui/screen.ts
|
|
159
|
+
function safeText(value) {
|
|
160
|
+
const text = stripVTControlCharacters(value.replace(/\r\n/g, "\n")).replace(/\t/g, " ");
|
|
161
|
+
return Array.from(text).filter((char) => {
|
|
162
|
+
const code = char.codePointAt(0) ?? 0;
|
|
163
|
+
return code === 10 || code >= 32 && (code < 127 || code > 159);
|
|
164
|
+
}).join("");
|
|
165
|
+
}
|
|
166
|
+
function clipLine(text, columns) {
|
|
167
|
+
let result = "";
|
|
168
|
+
for (const { segment } of new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(safeText(text).replace(/\n/g, " "))) {
|
|
169
|
+
if (stringWidth(result + segment) > columns) break;
|
|
170
|
+
result += segment;
|
|
171
|
+
}
|
|
172
|
+
return result;
|
|
173
|
+
}
|
|
174
|
+
function bodyLines(body, columns) {
|
|
175
|
+
return body.flatMap((line) => wrapAnsi(safeText(line), Math.max(1, columns - 1), {
|
|
176
|
+
hard: true,
|
|
177
|
+
wordWrap: false,
|
|
178
|
+
trim: false
|
|
179
|
+
}).split("\n"));
|
|
180
|
+
}
|
|
181
|
+
function frameLines(frame, columns, rows) {
|
|
182
|
+
const width = Math.max(1, columns - 1);
|
|
183
|
+
const height = Math.max(1, rows);
|
|
184
|
+
if (columns < 80 || rows < 24) return Array.from({ length: height }, (_, i) => clipLine(i === 0 ? "终端空间不足,请调整到至少 80×24" : i === height - 1 ? "Esc 返回 · Ctrl+C 停止服务" : "", width));
|
|
185
|
+
const content = bodyLines(frame.body, columns);
|
|
186
|
+
const offset = Math.min(Math.max(0, frame.offset ?? 0), Math.max(0, content.length - (height - 4)));
|
|
187
|
+
return [
|
|
188
|
+
clipLine(`Larness · ${frame.title}`, width),
|
|
189
|
+
"─".repeat(width),
|
|
190
|
+
...Array.from({ length: height - 4 }, (_, i) => clipLine(content[offset + i] ?? "", width)),
|
|
191
|
+
"─".repeat(width),
|
|
192
|
+
clipLine(frame.footer, width)
|
|
193
|
+
];
|
|
194
|
+
}
|
|
195
|
+
// src/tui/terminal.ts
|
|
196
|
+
const KeySchema = z.object({
|
|
197
|
+
name: z.string().optional(),
|
|
198
|
+
sequence: z.string().optional(),
|
|
199
|
+
ctrl: z.boolean().optional(),
|
|
200
|
+
shift: z.boolean().optional()
|
|
201
|
+
});
|
|
202
|
+
var NavigationCancelled = class extends Error {
|
|
203
|
+
constructor() {
|
|
204
|
+
super("返回上一级");
|
|
205
|
+
this.name = "NavigationCancelled";
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
var TerminalInterrupted = class extends Error {
|
|
209
|
+
constructor() {
|
|
210
|
+
super("正在停止服务");
|
|
211
|
+
this.name = "TerminalInterrupted";
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
var PromptInput = class extends PassThrough {
|
|
215
|
+
isTTY = true;
|
|
216
|
+
isRaw = true;
|
|
217
|
+
setRawMode(raw) {
|
|
218
|
+
this.isRaw = raw;
|
|
219
|
+
return this;
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
var TerminalSession = class {
|
|
223
|
+
input;
|
|
224
|
+
output;
|
|
225
|
+
term;
|
|
226
|
+
onInterrupt;
|
|
227
|
+
opened = false;
|
|
228
|
+
stopped = false;
|
|
229
|
+
previousRaw = false;
|
|
230
|
+
keys = [];
|
|
231
|
+
inputBlocked = false;
|
|
232
|
+
frame = {
|
|
233
|
+
title: "启动",
|
|
234
|
+
body: [],
|
|
235
|
+
footer: "Ctrl+C 停止服务"
|
|
236
|
+
};
|
|
237
|
+
waiting = null;
|
|
238
|
+
promptInput = null;
|
|
239
|
+
promptAbort = null;
|
|
240
|
+
constructor(options = {}) {
|
|
241
|
+
this.input = options.input ?? process.stdin;
|
|
242
|
+
this.output = options.output ?? process.stdout;
|
|
243
|
+
this.term = options.term ?? process.env.TERM ?? (process.platform === "win32" ? "xterm-256color" : void 0);
|
|
244
|
+
}
|
|
245
|
+
get columns() {
|
|
246
|
+
return this.output.columns || 80;
|
|
247
|
+
}
|
|
248
|
+
get rows() {
|
|
249
|
+
return this.output.rows || 24;
|
|
250
|
+
}
|
|
251
|
+
get bodyHeight() {
|
|
252
|
+
return Math.max(1, this.rows - 4);
|
|
253
|
+
}
|
|
254
|
+
get small() {
|
|
255
|
+
return this.columns < 80 || this.rows < 24;
|
|
256
|
+
}
|
|
257
|
+
open() {
|
|
258
|
+
if (this.opened) return;
|
|
259
|
+
if (!this.input.isTTY || !this.output.isTTY || !this.term || this.term === "dumb") throw new Error("TUI 需要交互终端(TTY,TERM 非 dumb);请在终端运行 pnpm dev 或 node app.js");
|
|
260
|
+
this.previousRaw = this.input.isRaw;
|
|
261
|
+
this.opened = true;
|
|
262
|
+
this.input.setRawMode(true);
|
|
263
|
+
emitKeypressEvents(this.input);
|
|
264
|
+
this.input.on("keypress", this.onKey);
|
|
265
|
+
this.output.on("resize", this.onResize);
|
|
266
|
+
this.input.resume();
|
|
267
|
+
this.output.write("\x1B[?1049h\x1B[?25l");
|
|
268
|
+
this.paint();
|
|
269
|
+
}
|
|
270
|
+
render(frame) {
|
|
271
|
+
this.frame = frame;
|
|
272
|
+
if (!this.promptInput) this.paint();
|
|
273
|
+
}
|
|
274
|
+
paint() {
|
|
275
|
+
if (!this.opened) return;
|
|
276
|
+
const lines = frameLines(this.frame, this.columns, this.rows);
|
|
277
|
+
this.output.write(`\x1b[?25l\x1b[2J\x1b[H${lines.join("\r\n")}`);
|
|
278
|
+
}
|
|
279
|
+
onResize = () => {
|
|
280
|
+
if (this.small) this.keys = [];
|
|
281
|
+
if (!this.promptInput || this.small) this.paint();
|
|
282
|
+
};
|
|
283
|
+
onKey = (text, raw) => {
|
|
284
|
+
const parsed = KeySchema.safeParse(raw);
|
|
285
|
+
if (!parsed.success) return;
|
|
286
|
+
const key = parsed.data;
|
|
287
|
+
if (key.ctrl && key.name === "c") {
|
|
288
|
+
this.interrupt();
|
|
289
|
+
this.onInterrupt?.();
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (this.small && key.name !== "escape") return;
|
|
293
|
+
if (this.promptInput) {
|
|
294
|
+
if (key.name === "escape") this.promptAbort?.abort();
|
|
295
|
+
else this.promptInput.write(key.sequence ?? (typeof text === "string" ? text : ""));
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (this.inputBlocked) return;
|
|
299
|
+
const event = {
|
|
300
|
+
name: key.name ?? "",
|
|
301
|
+
text: typeof text === "string" ? text : "",
|
|
302
|
+
ctrl: key.ctrl ?? false,
|
|
303
|
+
shift: key.shift ?? false
|
|
304
|
+
};
|
|
305
|
+
const waiting = this.waiting;
|
|
306
|
+
if (waiting) {
|
|
307
|
+
this.waiting = null;
|
|
308
|
+
waiting.resolve(event);
|
|
309
|
+
} else if (this.keys.length < 16) this.keys.push(event);
|
|
310
|
+
};
|
|
311
|
+
nextKey() {
|
|
312
|
+
if (this.stopped) return Promise.reject(new TerminalInterrupted());
|
|
313
|
+
if (this.waiting || this.promptInput) return Promise.reject(/* @__PURE__ */ new Error("terminal input already owned"));
|
|
314
|
+
const queued = this.keys.shift();
|
|
315
|
+
if (queued) return Promise.resolve(queued);
|
|
316
|
+
return new Promise((resolve, reject) => {
|
|
317
|
+
this.waiting = {
|
|
318
|
+
resolve,
|
|
319
|
+
reject
|
|
320
|
+
};
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
async prompt(run) {
|
|
324
|
+
if (this.stopped) throw new TerminalInterrupted();
|
|
325
|
+
if (this.waiting || this.promptInput) throw new Error("terminal input already owned");
|
|
326
|
+
this.keys = [];
|
|
327
|
+
const proxy = new PromptInput();
|
|
328
|
+
const abort = new AbortController();
|
|
329
|
+
const destination = new Writable({ write: (chunk, encoding, callback) => {
|
|
330
|
+
this.output.write(chunk, encoding, callback);
|
|
331
|
+
} });
|
|
332
|
+
Object.defineProperty(destination, "columns", { get: () => this.columns });
|
|
333
|
+
Object.defineProperty(destination, "rows", { get: () => this.rows });
|
|
334
|
+
this.promptInput = proxy;
|
|
335
|
+
this.promptAbort = abort;
|
|
336
|
+
this.output.write(`\x1b[${this.rows - 1};1H\x1b[0J\x1b[?25h`);
|
|
337
|
+
try {
|
|
338
|
+
return await run({
|
|
339
|
+
input: proxy,
|
|
340
|
+
output: destination,
|
|
341
|
+
signal: abort.signal,
|
|
342
|
+
clearPromptOnDone: true
|
|
343
|
+
});
|
|
344
|
+
} catch (error) {
|
|
345
|
+
if (this.stopped) throw new TerminalInterrupted();
|
|
346
|
+
if (abort.signal.aborted) throw new NavigationCancelled();
|
|
347
|
+
throw error;
|
|
348
|
+
} finally {
|
|
349
|
+
proxy.destroy();
|
|
350
|
+
this.promptInput = null;
|
|
351
|
+
this.promptAbort = null;
|
|
352
|
+
this.paint();
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
async ask(message, defaultValue) {
|
|
356
|
+
return this.prompt((context) => input({
|
|
357
|
+
message: clipLine(message, Math.floor((this.columns - 8) / 2)),
|
|
358
|
+
default: defaultValue,
|
|
359
|
+
transformer: (value) => clipLine(value, Math.max(1, Math.floor((this.columns - 12) / 2)))
|
|
360
|
+
}, context));
|
|
361
|
+
}
|
|
362
|
+
notify() {
|
|
363
|
+
const event = {
|
|
364
|
+
name: "update",
|
|
365
|
+
text: "",
|
|
366
|
+
ctrl: false,
|
|
367
|
+
shift: false
|
|
368
|
+
};
|
|
369
|
+
if (this.waiting) {
|
|
370
|
+
const waiting = this.waiting;
|
|
371
|
+
this.waiting = null;
|
|
372
|
+
waiting.resolve(event);
|
|
373
|
+
} else if (!this.keys.some((key) => key.name === "update")) this.keys.push(event);
|
|
374
|
+
}
|
|
375
|
+
blockInput(blocked) {
|
|
376
|
+
this.inputBlocked = blocked;
|
|
377
|
+
this.keys = [];
|
|
378
|
+
}
|
|
379
|
+
interrupt() {
|
|
380
|
+
this.keys = [];
|
|
381
|
+
this.stopped = true;
|
|
382
|
+
this.waiting?.reject(new TerminalInterrupted());
|
|
383
|
+
this.waiting = null;
|
|
384
|
+
this.promptAbort?.abort();
|
|
385
|
+
}
|
|
386
|
+
close() {
|
|
387
|
+
if (!this.opened) return;
|
|
388
|
+
this.interrupt();
|
|
389
|
+
this.opened = false;
|
|
390
|
+
this.input.off("keypress", this.onKey);
|
|
391
|
+
this.output.off("resize", this.onResize);
|
|
392
|
+
try {
|
|
393
|
+
this.input.setRawMode(this.previousRaw);
|
|
394
|
+
} finally {
|
|
395
|
+
this.input.pause();
|
|
396
|
+
this.output.write("\x1B[0m\x1B[?25h\x1B[?1049l");
|
|
397
|
+
this.frame = {
|
|
398
|
+
title: "",
|
|
399
|
+
body: [],
|
|
400
|
+
footer: ""
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
// src/tui/init-flow.ts
|
|
406
|
+
var InitCancelled = class extends Error {
|
|
407
|
+
constructor() {
|
|
408
|
+
super("初始化已取消");
|
|
409
|
+
this.name = "InitCancelled";
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
async function runInitWizard(prompts, apply, options = {}) {
|
|
413
|
+
const defaults = (options.config ?? DEFAULT_APP_CONFIG).server;
|
|
414
|
+
const maxAttempts = options.maxAttempts ?? 3;
|
|
415
|
+
let advanced = await prompts.advanced();
|
|
416
|
+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
417
|
+
const answers = {
|
|
418
|
+
host: defaults.host,
|
|
419
|
+
port: String(defaults.port),
|
|
420
|
+
publicUrl: defaults.publicUrl ?? ""
|
|
421
|
+
};
|
|
422
|
+
const fields = [
|
|
423
|
+
"host",
|
|
424
|
+
"port",
|
|
425
|
+
"publicUrl"
|
|
426
|
+
];
|
|
427
|
+
let step = 0;
|
|
428
|
+
while (advanced && step < fields.length) {
|
|
429
|
+
const field = fields[step];
|
|
430
|
+
if (field === void 0) break;
|
|
431
|
+
try {
|
|
432
|
+
answers[field] = await prompts[field]();
|
|
433
|
+
step += 1;
|
|
434
|
+
} catch (error) {
|
|
435
|
+
if (!(error instanceof NavigationCancelled)) throw error;
|
|
436
|
+
if (step > 0) step -= 1;
|
|
437
|
+
else advanced = await prompts.advanced();
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
let request;
|
|
441
|
+
const params = {};
|
|
442
|
+
try {
|
|
443
|
+
request = buildInitRequest(answers);
|
|
444
|
+
for (const [key, variable] of [
|
|
445
|
+
["host", "LARNESS_HOST"],
|
|
446
|
+
["port", "LARNESS_PORT"],
|
|
447
|
+
["publicUrl", "LARNESS_PUBLIC_URL"]
|
|
448
|
+
]) if (request.params[key] !== defaults[key]) {
|
|
449
|
+
if (options.env?.[variable] !== void 0) throw new TuiError(`${variable} 覆盖了此设置,请修改环境变量后重启`);
|
|
450
|
+
Object.assign(params, { [key]: request.params[key] });
|
|
451
|
+
}
|
|
452
|
+
} catch (error) {
|
|
453
|
+
if (attempt + 1 >= maxAttempts) throw error;
|
|
454
|
+
prompts.notify?.(error instanceof Error ? error.message : String(error));
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
const summary = [
|
|
458
|
+
`监听: ${request.params.host}:${request.params.port}`,
|
|
459
|
+
`浏览器访问地址: ${request.origin}`,
|
|
460
|
+
`RP ID: ${request.rpId}`,
|
|
461
|
+
`Passkey: ${request.passkeyEnabled ? "可用" : "不可用(将仅支持 allow_once)"}`,
|
|
462
|
+
...request.warning === null ? [] : [request.warning]
|
|
463
|
+
].join("\n");
|
|
464
|
+
if (!await prompts.confirm(summary)) throw new InitCancelled();
|
|
465
|
+
return apply(params);
|
|
466
|
+
}
|
|
467
|
+
throw new Error("初始化失败:重试次数已用尽");
|
|
468
|
+
}
|
|
469
|
+
// src/tui/lifecycle.ts
|
|
470
|
+
async function runManagedSessions(options) {
|
|
471
|
+
for (;;) {
|
|
472
|
+
const runtime = await options.start();
|
|
473
|
+
options.onRuntime(runtime);
|
|
474
|
+
let action;
|
|
475
|
+
try {
|
|
476
|
+
action = await options.attach(runtime);
|
|
477
|
+
} finally {
|
|
478
|
+
try {
|
|
479
|
+
await runtime.stop();
|
|
480
|
+
} finally {
|
|
481
|
+
options.onRuntime(null);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
if (action !== "restart") return;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
// src/tui/schemas.ts
|
|
488
|
+
const StatusSchema = z.object({
|
|
489
|
+
version: z.string(),
|
|
490
|
+
running: z.boolean(),
|
|
491
|
+
initialized: z.boolean(),
|
|
492
|
+
listen: z.object({
|
|
493
|
+
host: z.string(),
|
|
494
|
+
port: z.number()
|
|
495
|
+
}),
|
|
496
|
+
sessions: z.object({
|
|
497
|
+
online: z.number(),
|
|
498
|
+
pendingPairings: z.number()
|
|
499
|
+
}),
|
|
500
|
+
warnings: z.array(z.string())
|
|
501
|
+
});
|
|
502
|
+
const InitStatusSchema = z.object({ initialized: z.boolean() });
|
|
503
|
+
const InitResultSchema = z.object({
|
|
504
|
+
origin: z.string(),
|
|
505
|
+
rpId: z.string(),
|
|
506
|
+
restartRequired: z.boolean()
|
|
507
|
+
});
|
|
508
|
+
const LogLinesSchema = z.object({ lines: z.array(z.string()).max(500) });
|
|
509
|
+
const AuditSchema = z.object({ items: z.array(z.object({
|
|
510
|
+
id: z.string(),
|
|
511
|
+
action: z.string(),
|
|
512
|
+
decision: z.string().nullable(),
|
|
513
|
+
resourceType: z.string().nullable(),
|
|
514
|
+
resourceId: z.string().nullable(),
|
|
515
|
+
createdAt: z.number(),
|
|
516
|
+
details: z.unknown()
|
|
517
|
+
})).max(200) });
|
|
518
|
+
const PairingListSchema = z.object({ requests: z.array(z.object({
|
|
519
|
+
requestId: z.string(),
|
|
520
|
+
shortCode: z.string(),
|
|
521
|
+
status: z.string(),
|
|
522
|
+
decision: z.enum(["allow_once", "trust"]).nullable(),
|
|
523
|
+
clientLabel: z.string().nullable(),
|
|
524
|
+
clientOrigin: z.string().nullable(),
|
|
525
|
+
userAgent: z.string().nullable(),
|
|
526
|
+
createdAt: z.number(),
|
|
527
|
+
expiresAt: z.number(),
|
|
528
|
+
trustAvailable: z.boolean()
|
|
529
|
+
})) });
|
|
530
|
+
const DevicesSchema = z.object({ devices: z.array(z.object({
|
|
531
|
+
id: z.string(),
|
|
532
|
+
label: z.string(),
|
|
533
|
+
createdAt: z.number(),
|
|
534
|
+
lastSeenAt: z.number().nullable(),
|
|
535
|
+
revokedAt: z.number().nullable(),
|
|
536
|
+
credentials: z.array(z.object({
|
|
537
|
+
id: z.string(),
|
|
538
|
+
type: z.string(),
|
|
539
|
+
backupEligible: z.boolean(),
|
|
540
|
+
backupState: z.boolean(),
|
|
541
|
+
createdAt: z.number(),
|
|
542
|
+
lastUsedAt: z.number().nullable(),
|
|
543
|
+
revokedAt: z.number().nullable()
|
|
544
|
+
}))
|
|
545
|
+
})) });
|
|
546
|
+
const PairCodeSchema = z.object({
|
|
547
|
+
code: z.string().min(1).max(64),
|
|
548
|
+
expiresAt: z.number()
|
|
549
|
+
});
|
|
550
|
+
const RevokeSchema = z.object({
|
|
551
|
+
ok: z.literal(true),
|
|
552
|
+
revokedCredentials: z.number(),
|
|
553
|
+
revokedSessions: z.number()
|
|
554
|
+
});
|
|
555
|
+
const OkSchema = z.object({ ok: z.literal(true) });
|
|
556
|
+
// src/tui/page-error.ts
|
|
557
|
+
function displayError(error) {
|
|
558
|
+
if (error instanceof EntryConfigError) return error.message;
|
|
559
|
+
if (error instanceof DevWebUnavailable) return `${error.code}:${error.message}`;
|
|
560
|
+
if (error instanceof IpcClientError) return `${error.code}:操作未完成,请刷新查看实际状态`;
|
|
561
|
+
return "无法读取或校验数据,请刷新重试";
|
|
562
|
+
}
|
|
563
|
+
function disconnected(error) {
|
|
564
|
+
return error instanceof IpcClientError && error.code === "CONNECTION_CLOSED";
|
|
565
|
+
}
|
|
566
|
+
// src/tui/reading-page.ts
|
|
567
|
+
async function runReadingPage(kind, deps) {
|
|
568
|
+
const { terminal, client } = deps;
|
|
569
|
+
const snapshots = Array.from({ length: kind === "logs" ? 2 : 1 }, () => ({
|
|
570
|
+
lines: null,
|
|
571
|
+
count: 0,
|
|
572
|
+
offset: 0,
|
|
573
|
+
time: "",
|
|
574
|
+
error: ""
|
|
575
|
+
}));
|
|
576
|
+
let source = 0;
|
|
577
|
+
let generation = 0;
|
|
578
|
+
let loading = false;
|
|
579
|
+
let fatal;
|
|
580
|
+
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
581
|
+
const maxOffset = (snapshot) => Math.max(0, bodyLines(snapshot.lines ?? [], terminal.columns).length - terminal.bodyHeight);
|
|
582
|
+
const render = () => {
|
|
583
|
+
const snapshot = snapshots[source];
|
|
584
|
+
if (!snapshot) return;
|
|
585
|
+
snapshot.offset = Math.min(snapshot.offset, maxOffset(snapshot));
|
|
586
|
+
const label = kind === "audit" ? "审计" : `日志 · ${source === 0 ? "Server" : "子进程"}`;
|
|
587
|
+
const state = snapshot.error ? snapshot.lines === null ? "读取失败" : "刷新失败,当前为上次快照" : loading ? "刷新中" : "";
|
|
588
|
+
terminal.render({
|
|
589
|
+
title: `${label} · ${snapshot.count}${kind === "audit" ? "条" : "行"} · ${snapshot.time || "尚无快照"}${loading ? " · 刷新中" : ""}`,
|
|
590
|
+
body: snapshot.lines === null ? [snapshot.error || "正在读取…"] : snapshot.lines.length ? snapshot.lines : [kind === "audit" ? "暂无审计记录" : "暂无日志"],
|
|
591
|
+
offset: snapshot.offset,
|
|
592
|
+
footer: snapshot.error ? `${state} · ${snapshot.error.includes(":") ? snapshot.error.split(":")[0] : "数据错误"} · r刷新 Esc返回` : `${kind === "logs" ? "←→来源 " : ""}↑↓/PgUp/Dn Home/End · r刷新 Esc返回 ^C停止`
|
|
593
|
+
});
|
|
594
|
+
};
|
|
595
|
+
const store = (index, lines, count) => {
|
|
596
|
+
const snapshot = snapshots[index];
|
|
597
|
+
if (!snapshot) return;
|
|
598
|
+
const atBottom = snapshot.lines === null || snapshot.offset >= maxOffset(snapshot);
|
|
599
|
+
snapshot.lines = lines;
|
|
600
|
+
snapshot.count = count;
|
|
601
|
+
snapshot.error = "";
|
|
602
|
+
snapshot.time = `${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", { hour12: false })} ${zone}`;
|
|
603
|
+
snapshot.offset = kind === "logs" && atBottom ? maxOffset(snapshot) : Math.min(snapshot.offset, maxOffset(snapshot));
|
|
604
|
+
};
|
|
605
|
+
const fail = (index, error) => {
|
|
606
|
+
const snapshot = snapshots[index];
|
|
607
|
+
if (snapshot) snapshot.error = displayError(error);
|
|
608
|
+
if (disconnected(error)) fatal = error;
|
|
609
|
+
};
|
|
610
|
+
const refresh = () => {
|
|
611
|
+
if (loading) return;
|
|
612
|
+
loading = true;
|
|
613
|
+
const request = ++generation;
|
|
614
|
+
if (kind === "logs") try {
|
|
615
|
+
if (deps.localLogs) {
|
|
616
|
+
const local = LogLinesSchema.parse({ lines: deps.localLogs().slice(-300) });
|
|
617
|
+
store(1, local.lines, local.lines.length);
|
|
618
|
+
} else {
|
|
619
|
+
const local = snapshots[1];
|
|
620
|
+
if (local) local.error = "子进程输出来源不可用";
|
|
621
|
+
}
|
|
622
|
+
} catch (error) {
|
|
623
|
+
fail(1, error);
|
|
624
|
+
}
|
|
625
|
+
render();
|
|
626
|
+
client.request(kind === "logs" ? "logs.tail" : "audit.tail", kind === "logs" ? { lines: 200 } : { limit: 200 }).then((value) => {
|
|
627
|
+
if (request !== generation) return;
|
|
628
|
+
if (kind === "logs") {
|
|
629
|
+
const data = LogLinesSchema.parse(value).lines.slice(-200);
|
|
630
|
+
store(0, data, data.length);
|
|
631
|
+
} else {
|
|
632
|
+
const data = AuditSchema.parse(value).items.sort((a, b) => b.createdAt - a.createdAt);
|
|
633
|
+
store(0, data.map((item) => `${new Date(item.createdAt).toLocaleString()} ${item.action} ${item.decision ?? ""} ${item.resourceType ?? ""} ${item.resourceId ?? ""}`), data.length);
|
|
634
|
+
}
|
|
635
|
+
}).catch((error) => {
|
|
636
|
+
if (request === generation) fail(0, error);
|
|
637
|
+
}).finally(() => {
|
|
638
|
+
if (request !== generation) return;
|
|
639
|
+
loading = false;
|
|
640
|
+
render();
|
|
641
|
+
terminal.notify();
|
|
642
|
+
});
|
|
643
|
+
};
|
|
644
|
+
refresh();
|
|
645
|
+
try {
|
|
646
|
+
for (;;) {
|
|
647
|
+
const key = await terminal.nextKey();
|
|
648
|
+
if (fatal !== void 0) throw fatal;
|
|
649
|
+
if (key.name === "escape") return;
|
|
650
|
+
if (terminal.small || key.name === "update") continue;
|
|
651
|
+
if (key.name === "r") {
|
|
652
|
+
refresh();
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
if (kind === "logs" && (key.name === "left" || key.name === "right")) source = source === 0 ? 1 : 0;
|
|
656
|
+
else {
|
|
657
|
+
const snapshot = snapshots[source];
|
|
658
|
+
if (!snapshot) continue;
|
|
659
|
+
const max = maxOffset(snapshot);
|
|
660
|
+
const offset = Math.min(snapshot.offset, max);
|
|
661
|
+
const step = Math.max(1, terminal.bodyHeight - 1);
|
|
662
|
+
if (key.name === "home") snapshot.offset = 0;
|
|
663
|
+
else if (key.name === "end") snapshot.offset = max;
|
|
664
|
+
else if (key.name === "up") snapshot.offset = Math.max(0, offset - 1);
|
|
665
|
+
else if (key.name === "down") snapshot.offset = Math.min(max, offset + 1);
|
|
666
|
+
else if (key.name === "pageup") snapshot.offset = Math.max(0, offset - step);
|
|
667
|
+
else if (key.name === "pagedown") snapshot.offset = Math.min(max, offset + step);
|
|
668
|
+
else continue;
|
|
669
|
+
}
|
|
670
|
+
render();
|
|
671
|
+
}
|
|
672
|
+
} finally {
|
|
673
|
+
++generation;
|
|
674
|
+
for (const snapshot of snapshots) snapshot.lines = null;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
// src/tui/resource-pages.ts
|
|
678
|
+
const time = (value) => value === null ? "从未" : `${new Date(value).toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})`;
|
|
679
|
+
var ResourcePage = class {
|
|
680
|
+
kind;
|
|
681
|
+
terminal;
|
|
682
|
+
client;
|
|
683
|
+
view = "list";
|
|
684
|
+
pairs = [];
|
|
685
|
+
devices = [];
|
|
686
|
+
selectedId = null;
|
|
687
|
+
selected = 0;
|
|
688
|
+
action = 0;
|
|
689
|
+
confirmed = false;
|
|
690
|
+
loading = false;
|
|
691
|
+
busy = false;
|
|
692
|
+
generation = 0;
|
|
693
|
+
error = "";
|
|
694
|
+
result = "";
|
|
695
|
+
offset = 0;
|
|
696
|
+
code = null;
|
|
697
|
+
fatal;
|
|
698
|
+
revokeConfirmed = false;
|
|
699
|
+
uncertain = false;
|
|
700
|
+
pairHandled = false;
|
|
701
|
+
constructor(kind, terminal, client) {
|
|
702
|
+
this.kind = kind;
|
|
703
|
+
this.terminal = terminal;
|
|
704
|
+
this.client = client;
|
|
705
|
+
}
|
|
706
|
+
get pair() {
|
|
707
|
+
return this.pairs.find((item) => item.requestId === this.selectedId);
|
|
708
|
+
}
|
|
709
|
+
get device() {
|
|
710
|
+
return this.devices.find((item) => item.id === this.selectedId);
|
|
711
|
+
}
|
|
712
|
+
choices() {
|
|
713
|
+
if (this.uncertain || this.pairHandled) return ["返回列表"];
|
|
714
|
+
return this.pair?.trustAvailable ? [
|
|
715
|
+
"允许本次",
|
|
716
|
+
"始终允许(注册 Passkey)",
|
|
717
|
+
"拒绝",
|
|
718
|
+
"返回"
|
|
719
|
+
] : [
|
|
720
|
+
"允许本次",
|
|
721
|
+
"拒绝",
|
|
722
|
+
"返回"
|
|
723
|
+
];
|
|
724
|
+
}
|
|
725
|
+
decision() {
|
|
726
|
+
if (this.action === 0) return "allow_once";
|
|
727
|
+
return this.pair?.trustAvailable && this.action === 1 ? "trust" : "deny";
|
|
728
|
+
}
|
|
729
|
+
failure(error, write = false) {
|
|
730
|
+
if (disconnected(error)) this.fatal = error;
|
|
731
|
+
const uncertain = write && error instanceof IpcClientError && ["TIMEOUT", "CONNECTION_CLOSED"].includes(error.code);
|
|
732
|
+
if (uncertain) {
|
|
733
|
+
this.uncertain = true;
|
|
734
|
+
this.action = 0;
|
|
735
|
+
}
|
|
736
|
+
this.error = uncertain ? "结果待确认:请刷新列表确认实际状态,写操作不会自动重试。配对码未收到时,请在浏览器重新申请。" : displayError(error);
|
|
737
|
+
}
|
|
738
|
+
load() {
|
|
739
|
+
if (this.loading || this.busy) return;
|
|
740
|
+
this.loading = true;
|
|
741
|
+
const generation = ++this.generation;
|
|
742
|
+
this.render();
|
|
743
|
+
this.client.request(this.kind === "pairing" ? "pairing.list" : "devices.list", this.kind === "pairing" ? { status: "pending" } : void 0).then((value) => {
|
|
744
|
+
if (generation !== this.generation) return;
|
|
745
|
+
if (this.kind === "pairing") this.pairs = PairingListSchema.parse(value).requests;
|
|
746
|
+
else this.devices = DevicesSchema.parse(value).devices;
|
|
747
|
+
const ids = this.kind === "pairing" ? this.pairs.map((item) => item.requestId) : this.devices.map((item) => item.id);
|
|
748
|
+
const previous = this.selectedId === null ? -1 : ids.indexOf(this.selectedId);
|
|
749
|
+
this.selected = previous >= 0 ? previous : Math.max(0, Math.min(this.selected, ids.length - 1));
|
|
750
|
+
this.selectedId = ids[this.selected] ?? null;
|
|
751
|
+
this.error = "";
|
|
752
|
+
this.uncertain = false;
|
|
753
|
+
if (!this.selectedId) this.view = "list";
|
|
754
|
+
}).catch((error) => {
|
|
755
|
+
if (generation === this.generation) this.failure(error);
|
|
756
|
+
}).finally(() => {
|
|
757
|
+
if (generation === this.generation) {
|
|
758
|
+
this.loading = false;
|
|
759
|
+
this.render();
|
|
760
|
+
this.terminal.notify();
|
|
761
|
+
}
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
submit() {
|
|
765
|
+
if (this.busy || this.uncertain || this.pairHandled) return;
|
|
766
|
+
const pair = this.pair;
|
|
767
|
+
const device = this.device;
|
|
768
|
+
const decision = this.decision();
|
|
769
|
+
if (this.kind === "pairing" && !pair || this.kind === "devices" && (!device || device.revokedAt !== null || this.revokeConfirmed)) return;
|
|
770
|
+
this.busy = true;
|
|
771
|
+
this.error = "";
|
|
772
|
+
this.confirmed = false;
|
|
773
|
+
this.terminal.blockInput(true);
|
|
774
|
+
const generation = ++this.generation;
|
|
775
|
+
this.render();
|
|
776
|
+
const method = this.kind === "devices" ? "devices.revoke" : decision === "deny" ? "pairing.deny" : "pairing.approve";
|
|
777
|
+
const params = this.kind === "devices" ? { deviceId: device?.id } : decision === "deny" ? { requestId: pair?.requestId } : {
|
|
778
|
+
requestId: pair?.requestId,
|
|
779
|
+
decision
|
|
780
|
+
};
|
|
781
|
+
this.client.request(method, params).then((value) => {
|
|
782
|
+
if (generation !== this.generation) return;
|
|
783
|
+
if (this.kind === "devices") {
|
|
784
|
+
const revoked = RevokeSchema.parse(value);
|
|
785
|
+
this.result = `已撤销设备:凭据 ${revoked.revokedCredentials} 个,会话 ${revoked.revokedSessions} 个`;
|
|
786
|
+
this.revokeConfirmed = true;
|
|
787
|
+
this.view = "detail";
|
|
788
|
+
} else if (decision === "deny") {
|
|
789
|
+
OkSchema.parse(value);
|
|
790
|
+
this.result = "已拒绝配对申请";
|
|
791
|
+
this.pairHandled = true;
|
|
792
|
+
this.action = 0;
|
|
793
|
+
this.view = "actions";
|
|
794
|
+
} else {
|
|
795
|
+
this.code = PairCodeSchema.parse(value);
|
|
796
|
+
this.view = "code";
|
|
797
|
+
}
|
|
798
|
+
}).catch((error) => {
|
|
799
|
+
if (generation !== this.generation) return;
|
|
800
|
+
this.failure(error, true);
|
|
801
|
+
this.view = this.kind === "devices" ? "detail" : "actions";
|
|
802
|
+
}).finally(() => {
|
|
803
|
+
if (generation === this.generation) {
|
|
804
|
+
this.busy = false;
|
|
805
|
+
this.terminal.blockInput(false);
|
|
806
|
+
this.offset = 0;
|
|
807
|
+
this.render();
|
|
808
|
+
this.terminal.notify();
|
|
809
|
+
}
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
content() {
|
|
813
|
+
if (this.view === "code" && this.code) return {
|
|
814
|
+
title: "配对码",
|
|
815
|
+
body: [
|
|
816
|
+
"",
|
|
817
|
+
` ${formatPairingCode(this.code.code)}`,
|
|
818
|
+
"",
|
|
819
|
+
`申请:${this.pair?.shortCode ?? ""} · ${this.decision() === "trust" ? "始终允许" : "允许本次"}`,
|
|
820
|
+
`到期:${time(this.code.expiresAt)}`,
|
|
821
|
+
"仅显示本次,不会延长有效期。"
|
|
822
|
+
],
|
|
823
|
+
footer: "Enter 返回控制面板 · Esc 返回配对列表 · Ctrl+C 停止"
|
|
824
|
+
};
|
|
825
|
+
if (this.view === "list") {
|
|
826
|
+
const labels = this.kind === "pairing" ? this.pairs.map((item) => `${item.shortCode} · ${item.clientLabel ?? "未知客户端"} · ${item.clientOrigin ?? "未知来源"}`) : this.devices.map((item) => `${item.label} · ${item.revokedAt === null ? "有效" : "已撤销"}`);
|
|
827
|
+
return {
|
|
828
|
+
title: this.kind === "pairing" ? "待审批配对" : "可信设备",
|
|
829
|
+
body: [
|
|
830
|
+
this.loading ? "正在读取…" : `${labels.length} 项`,
|
|
831
|
+
"",
|
|
832
|
+
...labels.length ? labels.map((label, index) => clipLine(`${this.selected === index ? "›" : " "} ${label}`, this.terminal.columns - 1)) : [this.loading ? "" : this.error ? "读取未成功" : "暂无记录"],
|
|
833
|
+
"",
|
|
834
|
+
this.error
|
|
835
|
+
],
|
|
836
|
+
footer: "↑↓ 选择 · Enter 打开 · r 刷新 · Esc 返回控制面板"
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
if (this.view === "confirm") return {
|
|
840
|
+
title: this.kind === "devices" ? "撤销确认" : this.decision() === "deny" ? "拒绝确认" : "批准确认",
|
|
841
|
+
body: [
|
|
842
|
+
this.kind === "devices" ? `撤销 ${this.device?.label ?? "设备"} 及关联会话?` : `确认${this.choices()[this.action] ?? "批准"}申请 ${this.pair?.shortCode ?? ""}?`,
|
|
843
|
+
"",
|
|
844
|
+
`${this.confirmed ? " " : "› "}取消`,
|
|
845
|
+
`${this.confirmed ? "› " : " "}确认`,
|
|
846
|
+
"",
|
|
847
|
+
this.busy ? "正在提交,请等待结果…" : ""
|
|
848
|
+
],
|
|
849
|
+
footer: this.busy ? "写操作已发送,返回不会撤销 · Ctrl+C 停止" : "↑↓ 选择 · Enter 确认 · Esc 取消"
|
|
850
|
+
};
|
|
851
|
+
if (this.view === "actions") {
|
|
852
|
+
const pair = this.pair;
|
|
853
|
+
return {
|
|
854
|
+
title: "配对操作",
|
|
855
|
+
body: [
|
|
856
|
+
`申请:${pair?.shortCode ?? ""}`,
|
|
857
|
+
`来源:${pair?.clientOrigin ?? "未知"}`,
|
|
858
|
+
`客户端:${pair?.clientLabel ?? "未知"}`,
|
|
859
|
+
`UA:${clipLine(pair?.userAgent ?? "未知", 140)}`,
|
|
860
|
+
`申请时间:${time(pair?.createdAt ?? 0)}`,
|
|
861
|
+
"",
|
|
862
|
+
...this.choices().map((choice, index) => `${this.action === index ? "›" : " "} ${choice}`),
|
|
863
|
+
"",
|
|
864
|
+
this.result,
|
|
865
|
+
this.error
|
|
866
|
+
],
|
|
867
|
+
footer: "↑↓选择 Enter打开 · PgUp/Dn Home/End 阅读 · r刷新 Esc返回"
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
const device = this.device;
|
|
871
|
+
return {
|
|
872
|
+
title: "设备详情",
|
|
873
|
+
body: [
|
|
874
|
+
`设备:${device?.label ?? "未找到"}`,
|
|
875
|
+
`状态:${device?.revokedAt !== null || this.revokeConfirmed ? "已撤销" : "有效"}`,
|
|
876
|
+
`创建:${time(device?.createdAt ?? 0)}`,
|
|
877
|
+
`最后在线:${time(device?.lastSeenAt ?? null)}`,
|
|
878
|
+
...device?.credentials.flatMap((credential) => [
|
|
879
|
+
"",
|
|
880
|
+
`${credential.type} · ${credential.revokedAt === null && !this.revokeConfirmed ? "有效" : "已撤销"}`,
|
|
881
|
+
`允许备份:${credential.backupEligible ? "是" : "否"} · 已备份:${credential.backupState ? "是" : "否"}`,
|
|
882
|
+
`最后使用:${time(credential.lastUsedAt)}`
|
|
883
|
+
]) ?? [],
|
|
884
|
+
"",
|
|
885
|
+
this.result,
|
|
886
|
+
this.error
|
|
887
|
+
],
|
|
888
|
+
footer: device?.revokedAt === null && !this.revokeConfirmed && !this.uncertain ? "↑↓ 滚动 · Enter 撤销设备 · r 刷新 · Esc 返回列表" : "↑↓ 滚动 · r 刷新 · Esc 返回列表"
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
render(revealAction = true) {
|
|
892
|
+
const frame = this.content();
|
|
893
|
+
if (this.view === "actions" && revealAction) {
|
|
894
|
+
const selectedLine = frame.body.findIndex((line) => line.startsWith("› "));
|
|
895
|
+
if (selectedLine >= 0) {
|
|
896
|
+
const row = bodyLines(frame.body.slice(0, selectedLine), this.terminal.columns).length;
|
|
897
|
+
if (row < this.offset) this.offset = row;
|
|
898
|
+
else if (row >= this.offset + this.terminal.bodyHeight) this.offset = row - this.terminal.bodyHeight + 1;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
const length = bodyLines(frame.body, this.terminal.columns).length;
|
|
902
|
+
this.offset = Math.max(0, Math.min(this.offset, length - this.terminal.bodyHeight));
|
|
903
|
+
this.terminal.render({
|
|
904
|
+
...frame,
|
|
905
|
+
offset: this.offset
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
async run() {
|
|
909
|
+
this.load();
|
|
910
|
+
try {
|
|
911
|
+
for (;;) {
|
|
912
|
+
const key = await this.terminal.nextKey();
|
|
913
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
914
|
+
if (key.name === "update" || this.busy) continue;
|
|
915
|
+
if (key.name === "escape") {
|
|
916
|
+
if (this.view === "list") return;
|
|
917
|
+
++this.generation;
|
|
918
|
+
this.loading = false;
|
|
919
|
+
this.code = null;
|
|
920
|
+
this.offset = 0;
|
|
921
|
+
if (this.view === "confirm") this.view = this.kind === "devices" ? "detail" : "actions";
|
|
922
|
+
else {
|
|
923
|
+
this.view = "list";
|
|
924
|
+
this.result = "";
|
|
925
|
+
this.load();
|
|
926
|
+
}
|
|
927
|
+
this.render();
|
|
928
|
+
continue;
|
|
929
|
+
}
|
|
930
|
+
if (key.name === "r" && this.view !== "code" && this.view !== "confirm") {
|
|
931
|
+
if (this.view === "actions") this.view = "list";
|
|
932
|
+
this.load();
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
if (this.loading) continue;
|
|
936
|
+
if (this.view === "code") {
|
|
937
|
+
if (key.name === "return") return;
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
if (this.view === "list" && ["up", "down"].includes(key.name)) {
|
|
941
|
+
const ids = this.kind === "pairing" ? this.pairs.map((item) => item.requestId) : this.devices.map((item) => item.id);
|
|
942
|
+
this.selected = Math.max(0, Math.min(ids.length - 1, this.selected + (key.name === "up" ? -1 : 1)));
|
|
943
|
+
this.selectedId = ids[this.selected] ?? null;
|
|
944
|
+
const row = this.selected + 2;
|
|
945
|
+
if (row < this.offset) this.offset = row;
|
|
946
|
+
else if (row >= this.offset + this.terminal.bodyHeight) this.offset = row - this.terminal.bodyHeight + 1;
|
|
947
|
+
} else if (this.view === "actions" && ["up", "down"].includes(key.name)) this.action = Math.max(0, Math.min(this.choices().length - 1, this.action + (key.name === "up" ? -1 : 1)));
|
|
948
|
+
else if (this.view === "confirm" && ["up", "down"].includes(key.name)) this.confirmed = !this.confirmed;
|
|
949
|
+
else if ((this.view === "detail" || this.view === "actions") && [
|
|
950
|
+
"up",
|
|
951
|
+
"down",
|
|
952
|
+
"pageup",
|
|
953
|
+
"pagedown",
|
|
954
|
+
"home",
|
|
955
|
+
"end"
|
|
956
|
+
].includes(key.name)) this.offset = key.name === "home" ? 0 : key.name === "end" ? Number.MAX_SAFE_INTEGER : this.offset + (key.name.includes("up") ? -1 : 1) * (key.name.startsWith("page") ? this.terminal.bodyHeight : 1);
|
|
957
|
+
else if (key.name === "return") {
|
|
958
|
+
if (this.view === "list" && this.selectedId) {
|
|
959
|
+
this.view = this.kind === "devices" ? "detail" : "actions";
|
|
960
|
+
this.action = 0;
|
|
961
|
+
this.offset = 0;
|
|
962
|
+
this.result = "";
|
|
963
|
+
this.revokeConfirmed = false;
|
|
964
|
+
this.pairHandled = false;
|
|
965
|
+
} else if (this.view === "actions") {
|
|
966
|
+
if (this.action === this.choices().length - 1) {
|
|
967
|
+
this.view = "list";
|
|
968
|
+
this.load();
|
|
969
|
+
} else {
|
|
970
|
+
this.view = "confirm";
|
|
971
|
+
this.confirmed = false;
|
|
972
|
+
}
|
|
973
|
+
} else if (this.view === "detail" && this.device?.revokedAt === null && !this.revokeConfirmed) {
|
|
974
|
+
this.view = "confirm";
|
|
975
|
+
this.confirmed = false;
|
|
976
|
+
this.offset = 0;
|
|
977
|
+
} else if (this.view === "confirm") {
|
|
978
|
+
if (this.confirmed) this.submit();
|
|
979
|
+
else this.view = this.kind === "devices" ? "detail" : "actions";
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
this.render(![
|
|
983
|
+
"pageup",
|
|
984
|
+
"pagedown",
|
|
985
|
+
"home",
|
|
986
|
+
"end"
|
|
987
|
+
].includes(key.name));
|
|
988
|
+
}
|
|
989
|
+
} finally {
|
|
990
|
+
++this.generation;
|
|
991
|
+
this.code = null;
|
|
992
|
+
this.pairs = [];
|
|
993
|
+
this.devices = [];
|
|
994
|
+
this.terminal.blockInput(false);
|
|
995
|
+
this.terminal.render({
|
|
996
|
+
title: "返回",
|
|
997
|
+
body: [],
|
|
998
|
+
footer: "Ctrl+C 停止服务"
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
};
|
|
1003
|
+
function runResourcePage(kind, deps) {
|
|
1004
|
+
return new ResourcePage(kind, deps.terminal, deps.client).run();
|
|
1005
|
+
}
|
|
1006
|
+
// src/tui/screen-dashboard.ts
|
|
1007
|
+
async function runScreenDashboard(deps) {
|
|
1008
|
+
const { terminal, client } = deps;
|
|
1009
|
+
const menu = [
|
|
1010
|
+
"配对",
|
|
1011
|
+
"设备",
|
|
1012
|
+
"日志",
|
|
1013
|
+
"审计",
|
|
1014
|
+
"退出并停止服务"
|
|
1015
|
+
];
|
|
1016
|
+
let selected = 0;
|
|
1017
|
+
let page = "overview";
|
|
1018
|
+
let status = null;
|
|
1019
|
+
let error = "";
|
|
1020
|
+
let updateNotice = "";
|
|
1021
|
+
let connectionError;
|
|
1022
|
+
let generation = 0;
|
|
1023
|
+
let loading = false;
|
|
1024
|
+
let confirmExit = false;
|
|
1025
|
+
const render = () => {
|
|
1026
|
+
if (page === "child") return;
|
|
1027
|
+
if (page === "exit") {
|
|
1028
|
+
terminal.render({
|
|
1029
|
+
title: "退出确认",
|
|
1030
|
+
body: [
|
|
1031
|
+
"退出将停止 Server 与 Web。",
|
|
1032
|
+
"",
|
|
1033
|
+
`${confirmExit ? " " : "› "}取消`,
|
|
1034
|
+
`${confirmExit ? "› " : " "}确认退出并停止服务`
|
|
1035
|
+
],
|
|
1036
|
+
footer: "↑↓ 选择 · Enter 确认 · Esc 取消 · Ctrl+C 停止服务"
|
|
1037
|
+
});
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
terminal.render({
|
|
1041
|
+
title: "控制面板",
|
|
1042
|
+
body: [
|
|
1043
|
+
status ? `状态:${status.running ? "运行中" : "已停止"} · ${status.version}` : "正在读取运行状态…",
|
|
1044
|
+
`Web:${deps.webUrl ?? (status ? `http://localhost:${status.listen.port}` : "读取中")}`,
|
|
1045
|
+
status ? `待配对 ${status.sessions.pendingPairings} · 活跃会话 ${status.sessions.online}` : "",
|
|
1046
|
+
...status?.warnings.map((warning) => `! ${warning}`) ?? [],
|
|
1047
|
+
...updateNotice ? ["", updateNotice] : [],
|
|
1048
|
+
"",
|
|
1049
|
+
...menu.map((label, i) => `${selected === i ? "›" : " "} ${label}`),
|
|
1050
|
+
"",
|
|
1051
|
+
loading ? "正在刷新…" : error
|
|
1052
|
+
],
|
|
1053
|
+
footer: "↑↓ 选择 · Enter 打开 · p/d/l/a · r 刷新 · q 退出"
|
|
1054
|
+
});
|
|
1055
|
+
};
|
|
1056
|
+
const refresh = () => {
|
|
1057
|
+
if (loading) return;
|
|
1058
|
+
loading = true;
|
|
1059
|
+
const request = ++generation;
|
|
1060
|
+
render();
|
|
1061
|
+
client.request("system.status").then((value) => {
|
|
1062
|
+
if (request !== generation) return;
|
|
1063
|
+
status = StatusSchema.parse(value);
|
|
1064
|
+
error = "";
|
|
1065
|
+
}).catch((cause) => {
|
|
1066
|
+
if (request === generation) {
|
|
1067
|
+
error = displayError(cause);
|
|
1068
|
+
if (disconnected(cause)) connectionError = cause;
|
|
1069
|
+
}
|
|
1070
|
+
}).finally(() => {
|
|
1071
|
+
if (request === generation) {
|
|
1072
|
+
loading = false;
|
|
1073
|
+
render();
|
|
1074
|
+
terminal.notify();
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
};
|
|
1078
|
+
refresh();
|
|
1079
|
+
deps.updateCheck?.().then((notice) => {
|
|
1080
|
+
updateNotice = notice ?? "";
|
|
1081
|
+
render();
|
|
1082
|
+
terminal.notify();
|
|
1083
|
+
}).catch(() => void 0);
|
|
1084
|
+
try {
|
|
1085
|
+
for (;;) {
|
|
1086
|
+
const key = await terminal.nextKey();
|
|
1087
|
+
if (connectionError !== void 0) throw connectionError;
|
|
1088
|
+
if (page === "exit") {
|
|
1089
|
+
if (key.name === "escape") {
|
|
1090
|
+
page = "overview";
|
|
1091
|
+
render();
|
|
1092
|
+
} else if (key.name === "up" || key.name === "down") {
|
|
1093
|
+
confirmExit = !confirmExit;
|
|
1094
|
+
render();
|
|
1095
|
+
} else if (key.name === "return") {
|
|
1096
|
+
if (confirmExit) return;
|
|
1097
|
+
page = "overview";
|
|
1098
|
+
render();
|
|
1099
|
+
}
|
|
1100
|
+
continue;
|
|
1101
|
+
}
|
|
1102
|
+
if (key.name === "up" || key.name === "down") {
|
|
1103
|
+
selected = (selected + (key.name === "up" ? menu.length - 1 : 1)) % menu.length;
|
|
1104
|
+
render();
|
|
1105
|
+
continue;
|
|
1106
|
+
}
|
|
1107
|
+
if (key.name === "r") {
|
|
1108
|
+
refresh();
|
|
1109
|
+
continue;
|
|
1110
|
+
}
|
|
1111
|
+
const shortcut = [
|
|
1112
|
+
"p",
|
|
1113
|
+
"d",
|
|
1114
|
+
"l",
|
|
1115
|
+
"a",
|
|
1116
|
+
"q"
|
|
1117
|
+
].indexOf(key.name);
|
|
1118
|
+
if (shortcut < 0 && key.name !== "return") continue;
|
|
1119
|
+
if (shortcut >= 0) selected = shortcut;
|
|
1120
|
+
if (selected === 4) {
|
|
1121
|
+
page = "exit";
|
|
1122
|
+
confirmExit = false;
|
|
1123
|
+
render();
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
++generation;
|
|
1127
|
+
loading = false;
|
|
1128
|
+
page = "child";
|
|
1129
|
+
const lines = [];
|
|
1130
|
+
const title = menu[selected] ?? "功能";
|
|
1131
|
+
const out = (text) => {
|
|
1132
|
+
lines.push(text);
|
|
1133
|
+
terminal.render({
|
|
1134
|
+
title,
|
|
1135
|
+
body: lines,
|
|
1136
|
+
footer: "Esc 返回 · Ctrl+C 停止服务"
|
|
1137
|
+
});
|
|
1138
|
+
};
|
|
1139
|
+
const ask = async (message) => terminal.ask(message);
|
|
1140
|
+
terminal.render({
|
|
1141
|
+
title,
|
|
1142
|
+
body: ["正在读取…"],
|
|
1143
|
+
footer: "Ctrl+C 停止服务"
|
|
1144
|
+
});
|
|
1145
|
+
try {
|
|
1146
|
+
if (selected === 0 || selected === 1) await runResourcePage(selected === 0 ? "pairing" : "devices", {
|
|
1147
|
+
client,
|
|
1148
|
+
terminal
|
|
1149
|
+
});
|
|
1150
|
+
else await runReadingPage(selected === 2 ? "logs" : "audit", deps);
|
|
1151
|
+
} catch (cause) {
|
|
1152
|
+
if (disconnected(cause) || cause instanceof TerminalInterrupted) throw cause;
|
|
1153
|
+
if (!(cause instanceof NavigationCancelled)) {
|
|
1154
|
+
out(displayError(cause));
|
|
1155
|
+
await ask("按回车返回控制面板");
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
terminal.blockInput(false);
|
|
1159
|
+
page = "overview";
|
|
1160
|
+
render();
|
|
1161
|
+
refresh();
|
|
1162
|
+
}
|
|
1163
|
+
} finally {
|
|
1164
|
+
++generation;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
// src/tui/supervisor.ts
|
|
1168
|
+
const READY_TIMEOUT_MS = 9e4;
|
|
1169
|
+
const LOG_LIMIT = 300;
|
|
1170
|
+
function isLoopbackHostname(hostname) {
|
|
1171
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
1172
|
+
}
|
|
1173
|
+
function originPort(origin) {
|
|
1174
|
+
const parsed = new URL(origin);
|
|
1175
|
+
return Number(parsed.port || (parsed.protocol === "https:" ? "443" : "80"));
|
|
1176
|
+
}
|
|
1177
|
+
function resolveWebUrl(options) {
|
|
1178
|
+
const localUrl = `http://localhost:${options.serverPort}`;
|
|
1179
|
+
const canonical = new URL(options.canonicalOrigin);
|
|
1180
|
+
if (canonical.protocol === "http:" && isLoopbackHostname(canonical.hostname) && originPort(options.canonicalOrigin) !== options.serverPort) throw new EntryConfigError(options.canonicalOrigin, options.serverPort);
|
|
1181
|
+
return options.publicUrl ?? localUrl;
|
|
1182
|
+
}
|
|
1183
|
+
function serverRoot() {
|
|
1184
|
+
return findServerRoot(path.dirname(fileURLToPath(import.meta.url)));
|
|
1185
|
+
}
|
|
1186
|
+
function managedCommands(options) {
|
|
1187
|
+
const nodePath = options.nodePath ?? process.execPath;
|
|
1188
|
+
if (!options.dev) return {
|
|
1189
|
+
serverCommand: nodePath,
|
|
1190
|
+
serverArgs: [path.join(options.serverRoot, "dist", "index.js")],
|
|
1191
|
+
serverCwd: options.serverRoot,
|
|
1192
|
+
webCommand: null,
|
|
1193
|
+
webArgs: [],
|
|
1194
|
+
webCwd: null
|
|
1195
|
+
};
|
|
1196
|
+
const serverRequire = createRequire(path.join(options.serverRoot, "package.json"));
|
|
1197
|
+
const tsxLoader = pathToFileURL(serverRequire.resolve("tsx/esm")).href;
|
|
1198
|
+
return {
|
|
1199
|
+
serverCommand: nodePath,
|
|
1200
|
+
serverArgs: [
|
|
1201
|
+
"--import",
|
|
1202
|
+
tsxLoader,
|
|
1203
|
+
path.join(options.serverRoot, "src", "index.ts"),
|
|
1204
|
+
"--managed-dev-web"
|
|
1205
|
+
],
|
|
1206
|
+
serverCwd: options.serverRoot,
|
|
1207
|
+
webCommand: nodePath,
|
|
1208
|
+
webArgs: [
|
|
1209
|
+
"--import",
|
|
1210
|
+
tsxLoader,
|
|
1211
|
+
path.join(options.repoRoot, "apps", "web", "scripts", "managed-vite.ts")
|
|
1212
|
+
],
|
|
1213
|
+
webCwd: path.join(options.repoRoot, "apps", "web")
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
function delay(ms) {
|
|
1217
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1218
|
+
}
|
|
1219
|
+
async function httpOk(url, requireHtml = false, host) {
|
|
1220
|
+
try {
|
|
1221
|
+
const response = await fetch(url, {
|
|
1222
|
+
signal: AbortSignal.timeout(5e3),
|
|
1223
|
+
...host ? { headers: { host } } : {}
|
|
1224
|
+
});
|
|
1225
|
+
const ready = response.ok && (!requireHtml || (response.headers.get("content-type") ?? "").includes("text/html"));
|
|
1226
|
+
await response.arrayBuffer();
|
|
1227
|
+
return ready;
|
|
1228
|
+
} catch {
|
|
1229
|
+
return false;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
async function waitForHttp(url, child, options = {}) {
|
|
1233
|
+
const deadline = Date.now() + (options.timeoutMs ?? READY_TIMEOUT_MS);
|
|
1234
|
+
while (Date.now() < deadline) {
|
|
1235
|
+
if (child.exitCode !== null || child.signalCode !== null || options.failed?.() === true || options.signal?.aborted === true) return false;
|
|
1236
|
+
if (await httpOk(url, options.requireHtml, options.host)) return true;
|
|
1237
|
+
await delay(200);
|
|
1238
|
+
}
|
|
1239
|
+
return false;
|
|
1240
|
+
}
|
|
1241
|
+
function waitForExit(child, timeoutMs) {
|
|
1242
|
+
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
|
|
1243
|
+
return new Promise((resolve) => {
|
|
1244
|
+
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
1245
|
+
child.once("exit", () => {
|
|
1246
|
+
clearTimeout(timer);
|
|
1247
|
+
resolve(true);
|
|
1248
|
+
});
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1251
|
+
async function stopChild(child, timeoutMs, graceful = "signal") {
|
|
1252
|
+
if (child === null || child.exitCode !== null || child.signalCode !== null) return;
|
|
1253
|
+
if (process.platform === "win32" && child.pid) {
|
|
1254
|
+
if (graceful === "message" && child.connected) child.send({ type: "larness.shutdown" });
|
|
1255
|
+
else if (graceful === "disconnect" && child.connected) child.disconnect();
|
|
1256
|
+
if (await waitForExit(child, timeoutMs)) return;
|
|
1257
|
+
await terminateProcessTree(child.pid, 2e3);
|
|
1258
|
+
await waitForExit(child, 2e3);
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
child.kill("SIGTERM");
|
|
1262
|
+
if (await waitForExit(child, timeoutMs)) return;
|
|
1263
|
+
child.kill("SIGKILL");
|
|
1264
|
+
await waitForExit(child, 2e3);
|
|
1265
|
+
}
|
|
1266
|
+
async function loadManagedConfig(dataDir, env = process.env) {
|
|
1267
|
+
const pending = inspectPendingInitialization(path.join(dataDir, "larness.db"));
|
|
1268
|
+
return pending === null ? loadConfig({
|
|
1269
|
+
dataDir,
|
|
1270
|
+
env
|
|
1271
|
+
}) : {
|
|
1272
|
+
...resolveConfig(pending, env),
|
|
1273
|
+
source: "file",
|
|
1274
|
+
path: configFilePath(dataDir)
|
|
1275
|
+
};
|
|
1276
|
+
}
|
|
1277
|
+
async function startManagedRuntime(options) {
|
|
1278
|
+
options.signal?.throwIfAborted();
|
|
1279
|
+
const out = options.out ?? console.log;
|
|
1280
|
+
const root = serverRoot();
|
|
1281
|
+
const repoRoot = path.resolve(root, "../..");
|
|
1282
|
+
const dataDir = resolveDataDir();
|
|
1283
|
+
const loaded = await loadManagedConfig(dataDir);
|
|
1284
|
+
const port = loaded.config.server.port;
|
|
1285
|
+
const localBase = `http://127.0.0.1:${port}`;
|
|
1286
|
+
const serverUrl = `http://localhost:${port}`;
|
|
1287
|
+
const canonicalOrigin = loaded.webAuthn.origin;
|
|
1288
|
+
const webUrl = resolveWebUrl({
|
|
1289
|
+
dev: options.dev,
|
|
1290
|
+
serverPort: port,
|
|
1291
|
+
publicUrl: loaded.config.server.publicUrl,
|
|
1292
|
+
canonicalOrigin
|
|
1293
|
+
});
|
|
1294
|
+
if (await httpOk(`${localBase}/api/health`)) throw new Error(`已有 Larness Server 在 ${serverUrl} 运行;请先关闭原 TUI。`);
|
|
1295
|
+
const commands = managedCommands({
|
|
1296
|
+
dev: options.dev,
|
|
1297
|
+
serverRoot: root,
|
|
1298
|
+
repoRoot
|
|
1299
|
+
});
|
|
1300
|
+
const logs = [];
|
|
1301
|
+
const appendLog = (prefix, chunk) => {
|
|
1302
|
+
for (const line of chunk.toString("utf8").split(/\r?\n/)) if (line.trim()) logs.push(`${prefix} ${line}`);
|
|
1303
|
+
if (logs.length > LOG_LIMIT) logs.splice(0, logs.length - LOG_LIMIT);
|
|
1304
|
+
};
|
|
1305
|
+
let server = null;
|
|
1306
|
+
let web = null;
|
|
1307
|
+
let stopped = false;
|
|
1308
|
+
let ownedCache = null;
|
|
1309
|
+
let stopping = null;
|
|
1310
|
+
let resolveServerExit = () => void 0;
|
|
1311
|
+
const serverExited = new Promise((resolve) => {
|
|
1312
|
+
resolveServerExit = resolve;
|
|
1313
|
+
});
|
|
1314
|
+
let resolveDevFailure = () => void 0;
|
|
1315
|
+
const devFailed = new Promise((resolve) => {
|
|
1316
|
+
resolveDevFailure = resolve;
|
|
1317
|
+
});
|
|
1318
|
+
const forceKill = () => {
|
|
1319
|
+
server?.kill("SIGKILL");
|
|
1320
|
+
web?.kill("SIGKILL");
|
|
1321
|
+
};
|
|
1322
|
+
process.once("exit", forceKill);
|
|
1323
|
+
const stop = () => {
|
|
1324
|
+
stopped = true;
|
|
1325
|
+
stopping ??= (async () => {
|
|
1326
|
+
try {
|
|
1327
|
+
await stopChild(server, 1e4, "message");
|
|
1328
|
+
} finally {
|
|
1329
|
+
try {
|
|
1330
|
+
await stopChild(web, 5e3, "disconnect");
|
|
1331
|
+
} finally {
|
|
1332
|
+
try {
|
|
1333
|
+
if (ownedCache) await rm(ownedCache, {
|
|
1334
|
+
recursive: true,
|
|
1335
|
+
force: true
|
|
1336
|
+
});
|
|
1337
|
+
} finally {
|
|
1338
|
+
process.off("exit", forceKill);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
})();
|
|
1343
|
+
return stopping;
|
|
1344
|
+
};
|
|
1345
|
+
const observe = (child, prefix) => {
|
|
1346
|
+
child.stdout?.on("data", (chunk) => appendLog(prefix, chunk));
|
|
1347
|
+
child.stderr?.on("data", (chunk) => appendLog(prefix, chunk));
|
|
1348
|
+
child.on("error", () => {
|
|
1349
|
+
if (options.dev && !stopped) resolveDevFailure();
|
|
1350
|
+
});
|
|
1351
|
+
child.on("exit", () => {
|
|
1352
|
+
if (options.dev && !stopped) resolveDevFailure();
|
|
1353
|
+
});
|
|
1354
|
+
if (options.dev) child.on("disconnect", () => {
|
|
1355
|
+
if (!stopped) resolveDevFailure();
|
|
1356
|
+
});
|
|
1357
|
+
};
|
|
1358
|
+
try {
|
|
1359
|
+
const generation = randomUUID();
|
|
1360
|
+
let target = null;
|
|
1361
|
+
if (options.dev) {
|
|
1362
|
+
options.signal?.throwIfAborted();
|
|
1363
|
+
web = spawn(commands.webCommand ?? process.execPath, commands.webArgs, {
|
|
1364
|
+
cwd: commands.webCwd ?? repoRoot,
|
|
1365
|
+
env: process.env,
|
|
1366
|
+
stdio: [
|
|
1367
|
+
"ignore",
|
|
1368
|
+
"pipe",
|
|
1369
|
+
"pipe",
|
|
1370
|
+
"ipc"
|
|
1371
|
+
]
|
|
1372
|
+
});
|
|
1373
|
+
observe(web, "[web]");
|
|
1374
|
+
const control = new DevWebControl(web, generation);
|
|
1375
|
+
const child = web;
|
|
1376
|
+
const ready = waitChildMessage(child, (message) => control.accept(child, message) ? control.target : null, options.signal, "Vite");
|
|
1377
|
+
child.send({
|
|
1378
|
+
type: "dev-web.start",
|
|
1379
|
+
generation,
|
|
1380
|
+
origin: canonicalOrigin
|
|
1381
|
+
});
|
|
1382
|
+
target = await ready;
|
|
1383
|
+
ownedCache = devWebCache(target.generation);
|
|
1384
|
+
}
|
|
1385
|
+
options.signal?.throwIfAborted();
|
|
1386
|
+
server = spawn(commands.serverCommand, commands.serverArgs, {
|
|
1387
|
+
cwd: commands.serverCwd,
|
|
1388
|
+
env: {
|
|
1389
|
+
...process.env,
|
|
1390
|
+
LARNESS_LOG_STDERR: "0",
|
|
1391
|
+
LARNESS_TUI_CHILD: "1",
|
|
1392
|
+
LARNESS_PM2_AUTO_INSTALL: process.env.LARNESS_PM2_AUTO_INSTALL ?? "1",
|
|
1393
|
+
...options.dev ? { LARNESS_SERVE_WEB: "0" } : {}
|
|
1394
|
+
},
|
|
1395
|
+
stdio: [
|
|
1396
|
+
"ignore",
|
|
1397
|
+
"pipe",
|
|
1398
|
+
"pipe",
|
|
1399
|
+
"ipc"
|
|
1400
|
+
]
|
|
1401
|
+
});
|
|
1402
|
+
observe(server, "[server]");
|
|
1403
|
+
server.once("exit", resolveServerExit);
|
|
1404
|
+
if (target) {
|
|
1405
|
+
const attached = waitChildMessage(server, (message) => {
|
|
1406
|
+
const parsed = DevWebAttachedSchema.safeParse(message);
|
|
1407
|
+
return parsed.success && parsed.data.generation === generation ? true : null;
|
|
1408
|
+
}, options.signal);
|
|
1409
|
+
server.send({
|
|
1410
|
+
type: "dev-web.attach",
|
|
1411
|
+
...target
|
|
1412
|
+
});
|
|
1413
|
+
await attached;
|
|
1414
|
+
}
|
|
1415
|
+
const serverReady = await waitForHttp(`${localBase}/api/health`, server, { signal: options.signal });
|
|
1416
|
+
const host = new URL(canonicalOrigin).host;
|
|
1417
|
+
const webReady = serverReady && await waitForHttp(`${localBase}/`, server, {
|
|
1418
|
+
requireHtml: true,
|
|
1419
|
+
signal: options.signal,
|
|
1420
|
+
host,
|
|
1421
|
+
timeoutMs: options.dev ? READY_TIMEOUT_MS : 5e3
|
|
1422
|
+
});
|
|
1423
|
+
const resourcesReady = !options.dev || await waitForHttp(`${localBase}/@vite/client`, server, {
|
|
1424
|
+
signal: options.signal,
|
|
1425
|
+
host
|
|
1426
|
+
});
|
|
1427
|
+
if (!serverReady || !webReady || !resourcesReady || web?.exitCode !== null && web !== null || web?.signalCode !== null && web !== null) throw new Error("Server 或 Web 未就绪;请查看本机日志,打包模式请先运行 pnpm build。");
|
|
1428
|
+
if (!existsSync(path.join(dataDir, "ipc", "token"))) throw new Error("IPC 尚未就绪");
|
|
1429
|
+
} catch (error) {
|
|
1430
|
+
await stop();
|
|
1431
|
+
throw error;
|
|
1432
|
+
}
|
|
1433
|
+
out(pc.bold("Larness"));
|
|
1434
|
+
out(`${pc.green("✓")} 数据目录 ${dataDir}`);
|
|
1435
|
+
out(`${pc.green("✓")} Server ${serverUrl}`);
|
|
1436
|
+
out(`${pc.green("✓")} Web ${webUrl}`);
|
|
1437
|
+
out(`${pc.green("✓")} IPC ${path.join(dataDir, "ipc")}`);
|
|
1438
|
+
return {
|
|
1439
|
+
dataDir,
|
|
1440
|
+
config: loaded,
|
|
1441
|
+
dev: options.dev,
|
|
1442
|
+
serverUrl,
|
|
1443
|
+
webUrl,
|
|
1444
|
+
logs: () => [...logs],
|
|
1445
|
+
stop,
|
|
1446
|
+
serverExited,
|
|
1447
|
+
devFailed
|
|
1448
|
+
};
|
|
1449
|
+
}
|
|
1450
|
+
// src/tui/main.ts
|
|
1451
|
+
async function runSession(client, runtime, terminal) {
|
|
1452
|
+
if (!InitStatusSchema.parse(await client.request("init.status")).initialized) {
|
|
1453
|
+
const current = runtime?.config.config.server;
|
|
1454
|
+
terminal.render({
|
|
1455
|
+
title: "初始化",
|
|
1456
|
+
body: ["确认当前设置后初始化本机工作空间。", `Web:${runtime?.webUrl ?? "本机"}`],
|
|
1457
|
+
footer: "Enter 选择 · Esc 取消 · Ctrl+C 停止服务"
|
|
1458
|
+
});
|
|
1459
|
+
if ((await runInitWizard({
|
|
1460
|
+
advanced: () => terminal.prompt((context) => confirm({
|
|
1461
|
+
message: "修改高级网络设置?",
|
|
1462
|
+
default: false
|
|
1463
|
+
}, context)),
|
|
1464
|
+
host: () => terminal.ask("监听地址", current?.host ?? "127.0.0.1"),
|
|
1465
|
+
port: () => terminal.ask("端口", String(current?.port ?? 3210)),
|
|
1466
|
+
publicUrl: () => terminal.ask("浏览器访问地址(可留空)", current?.publicUrl ?? ""),
|
|
1467
|
+
confirm: (summary) => {
|
|
1468
|
+
terminal.render({
|
|
1469
|
+
title: "初始化确认",
|
|
1470
|
+
body: summary.split("\n"),
|
|
1471
|
+
footer: "Enter 确认 · Esc 取消 · Ctrl+C 停止服务"
|
|
1472
|
+
});
|
|
1473
|
+
return terminal.prompt((context) => confirm({
|
|
1474
|
+
message: "确认写入配置?",
|
|
1475
|
+
default: false
|
|
1476
|
+
}, context));
|
|
1477
|
+
},
|
|
1478
|
+
notify: (message) => terminal.render({
|
|
1479
|
+
title: "初始化",
|
|
1480
|
+
body: [message],
|
|
1481
|
+
footer: "请重新输入 · Esc 返回 · Ctrl+C 停止服务"
|
|
1482
|
+
})
|
|
1483
|
+
}, async (params) => {
|
|
1484
|
+
terminal.render({
|
|
1485
|
+
title: "初始化",
|
|
1486
|
+
body: ["正在保存配置…"],
|
|
1487
|
+
footer: "Ctrl+C 停止服务"
|
|
1488
|
+
});
|
|
1489
|
+
return InitResultSchema.parse(await client.request("init.apply", params));
|
|
1490
|
+
}, {
|
|
1491
|
+
config: runtime?.config.config,
|
|
1492
|
+
env: process.env
|
|
1493
|
+
})).restartRequired) {
|
|
1494
|
+
terminal.render({
|
|
1495
|
+
title: "应用配置",
|
|
1496
|
+
body: ["配置已保存,正在重启 Server 与 Web…"],
|
|
1497
|
+
footer: "Ctrl+C 停止服务"
|
|
1498
|
+
});
|
|
1499
|
+
return runtime ? "restart" : "done";
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
await runScreenDashboard({
|
|
1503
|
+
terminal,
|
|
1504
|
+
client,
|
|
1505
|
+
webUrl: runtime?.webUrl,
|
|
1506
|
+
localLogs: runtime?.logs,
|
|
1507
|
+
updateCheck: async () => {
|
|
1508
|
+
const notice = await checkForUpdate({
|
|
1509
|
+
version: SERVER_VERSION,
|
|
1510
|
+
dataDir: runtime?.dataDir ?? resolveDataDir(),
|
|
1511
|
+
channel: updateChannel(runtime?.config.config.updates.channel)
|
|
1512
|
+
});
|
|
1513
|
+
return notice === null ? null : updateNoticeText(notice);
|
|
1514
|
+
}
|
|
1515
|
+
});
|
|
1516
|
+
return "done";
|
|
1517
|
+
}
|
|
1518
|
+
async function main() {
|
|
1519
|
+
const args = process.argv.slice(2);
|
|
1520
|
+
const managed = args.includes("--managed") || process.env.LARNESS_TUI_MANAGED === "1";
|
|
1521
|
+
const dev = args.includes("--dev") || process.env.LARNESS_TUI_DEV === "1";
|
|
1522
|
+
const terminal = new TerminalSession();
|
|
1523
|
+
const abort = new AbortController();
|
|
1524
|
+
let runtime = null;
|
|
1525
|
+
let activeClient = null;
|
|
1526
|
+
let stopping = null;
|
|
1527
|
+
const stop = () => {
|
|
1528
|
+
abort.abort();
|
|
1529
|
+
terminal.interrupt();
|
|
1530
|
+
activeClient?.close();
|
|
1531
|
+
stopping ??= runtime?.stop() ?? Promise.resolve();
|
|
1532
|
+
};
|
|
1533
|
+
terminal.onInterrupt = stop;
|
|
1534
|
+
const signals = [
|
|
1535
|
+
"SIGINT",
|
|
1536
|
+
"SIGTERM",
|
|
1537
|
+
"SIGHUP"
|
|
1538
|
+
];
|
|
1539
|
+
for (const signal of signals) process.on(signal, stop);
|
|
1540
|
+
try {
|
|
1541
|
+
terminal.open();
|
|
1542
|
+
} catch (error) {
|
|
1543
|
+
for (const signal of signals) process.off(signal, stop);
|
|
1544
|
+
throw error;
|
|
1545
|
+
}
|
|
1546
|
+
const attach = async (current) => {
|
|
1547
|
+
for (let attempt = 0;; attempt += 1) {
|
|
1548
|
+
abort.signal.throwIfAborted();
|
|
1549
|
+
let client = null;
|
|
1550
|
+
try {
|
|
1551
|
+
client = await connectIpc({
|
|
1552
|
+
dataDir: current?.dataDir ?? resolveDataDir(),
|
|
1553
|
+
client: "tui",
|
|
1554
|
+
keepAliveMs: 3e5
|
|
1555
|
+
}).catch((error) => {
|
|
1556
|
+
if (error instanceof IpcClientError) throw error;
|
|
1557
|
+
throw new IpcClientError("CONNECTION_CLOSED", "无法连接本机 IPC");
|
|
1558
|
+
});
|
|
1559
|
+
activeClient = client;
|
|
1560
|
+
return await runSession(client, current, terminal);
|
|
1561
|
+
} catch (error) {
|
|
1562
|
+
if (abort.signal.aborted) throw new TerminalInterrupted();
|
|
1563
|
+
if (!(error instanceof IpcClientError) || !["CONNECTION_CLOSED", "TIMEOUT"].includes(error.code) || attempt >= 2) throw error;
|
|
1564
|
+
terminal.render({
|
|
1565
|
+
title: "重新连接",
|
|
1566
|
+
body: ["本机连接中断,正在重新连接…", "未确认的写操作不会自动重试。"],
|
|
1567
|
+
footer: "Ctrl+C 停止服务"
|
|
1568
|
+
});
|
|
1569
|
+
await setTimeout$1(1e3, void 0, { signal: abort.signal });
|
|
1570
|
+
} finally {
|
|
1571
|
+
client?.close();
|
|
1572
|
+
activeClient = null;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
};
|
|
1576
|
+
let failure;
|
|
1577
|
+
try {
|
|
1578
|
+
if (managed) await runManagedSessions({
|
|
1579
|
+
start: () => startManagedRuntime({
|
|
1580
|
+
dev,
|
|
1581
|
+
signal: abort.signal,
|
|
1582
|
+
out: (text) => terminal.render({
|
|
1583
|
+
title: "启动检查",
|
|
1584
|
+
body: safeText(text).split("\n"),
|
|
1585
|
+
footer: "Ctrl+C 停止服务"
|
|
1586
|
+
})
|
|
1587
|
+
}),
|
|
1588
|
+
attach: async (value) => {
|
|
1589
|
+
try {
|
|
1590
|
+
return await Promise.race([attach(value), value.devFailed.then(() => {
|
|
1591
|
+
throw new DevWebUnavailable();
|
|
1592
|
+
})]);
|
|
1593
|
+
} catch (error) {
|
|
1594
|
+
terminal.interrupt();
|
|
1595
|
+
throw error;
|
|
1596
|
+
}
|
|
1597
|
+
},
|
|
1598
|
+
onRuntime: (value) => {
|
|
1599
|
+
runtime = value;
|
|
1600
|
+
}
|
|
1601
|
+
});
|
|
1602
|
+
else await attach();
|
|
1603
|
+
} catch (error) {
|
|
1604
|
+
if (!(error instanceof TerminalInterrupted) && !(error instanceof NavigationCancelled) && !(error instanceof InitCancelled) && !abort.signal.aborted) failure = error;
|
|
1605
|
+
} finally {
|
|
1606
|
+
try {
|
|
1607
|
+
await stopping;
|
|
1608
|
+
} catch (error) {
|
|
1609
|
+
failure ??= error;
|
|
1610
|
+
} finally {
|
|
1611
|
+
for (const signal of signals) process.off(signal, stop);
|
|
1612
|
+
terminal.close();
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
if (failure !== void 0) {
|
|
1616
|
+
console.error(`[larness] ${displayError(failure)}`);
|
|
1617
|
+
process.exitCode = 1;
|
|
1618
|
+
} else console.log("Larness 已退出,Server 与 Web 已停止。");
|
|
1619
|
+
}
|
|
1620
|
+
try {
|
|
1621
|
+
await main();
|
|
1622
|
+
} catch (error) {
|
|
1623
|
+
console.error(`[larness] ${error instanceof Error ? safeText(error.message) : "TUI 启动失败"}`);
|
|
1624
|
+
process.exitCode = 1;
|
|
1625
|
+
}
|
|
1626
|
+
export {};
|