@aivin-labs/cli 1.0.68 → 1.0.75

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.
@@ -0,0 +1,219 @@
1
+ // Đăng nhập agent cho thành viên máy tính tổ chức, KHÔNG cần màn hình (17/11/2026). Máy không có trình duyệt / màn hình: CLI chạy lệnh đăng
2
+ // nhập của agent dưới tài khoản Linux của thành viên, đọc link (và mã) agent in ra, BE đưa cho người dùng mở trên máy / điện thoại của họ.
3
+ // Tệp đăng nhập agent ghi nằm trong HOME của thành viên — chỉ họ dùng.
4
+ //
5
+ // Đã đo trên container Linux sạch (node:22-bookworm-slim):
6
+ // - Claude Code 2.1.326 `claude auth login --claudeai`: in "If the browser didn't open, visit: https://claude.com/cai/oauth/authorize?…" rồi
7
+ // chờ "Paste code here if prompted >" trên stdin → người dùng đăng nhập, trang đích hiện mã, dán mã vào Aivin, CLI ghi mã vào stdin.
8
+ // - Codex 0.169.0 `codex login --device-auth`: in link https://auth.openai.com/codex/device + mã một lần (hết hạn 15 phút), tự chờ người
9
+ // dùng xác nhận rồi thoát — không cần nhập gì thêm.
10
+ import { randomUUID } from 'crypto';
11
+ import { spawn } from 'child_process';
12
+ import { DeviceErrorCode, ToolGroup } from './constants.mjs';
13
+ import { DeviceToolError } from './sandbox.mjs';
14
+ import { memberSpawnArgs } from './localLlmMembers.mjs';
15
+
16
+ // eslint-disable-next-line no-control-regex -- mã màu ANSI agent in ra
17
+ export const ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/g;
18
+ const URL_RE = /https:\/\/[^\s'"<>`]+/g;
19
+ const LOGIN_TTL_MS = 15 * 60_000;
20
+ const START_WAIT_MS = 25_000;
21
+ const CODE_WAIT_MS = 60_000;
22
+ const MAX_OUTPUT = 16_000;
23
+ const CODE_RE = /^[A-Za-z0-9_\-#.~=+/]{6,1024}$/;
24
+
25
+ export const LoginState = Object.freeze({ PENDING: 'pending', SUCCEEDED: 'succeeded', FAILED: 'failed', EXPIRED: 'expired' });
26
+
27
+ const invalid = (msg) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, msg);
28
+ const failed = (msg, code = DeviceErrorCode.EXECUTION_FAILED) => new DeviceToolError(code, msg);
29
+
30
+ /** Link / mã trong chữ agent in ra (đã bỏ mã màu). null = chưa đủ. */
31
+ export const LOGIN_FLOWS = Object.freeze({
32
+ claude: {
33
+ argv: ['auth', 'login', '--claudeai'],
34
+ needsCode: true,
35
+ parse(text) {
36
+ const url = (text.match(URL_RE) || []).find((u) => /\/oauth\/authorize\?/.test(u));
37
+ return url ? { url } : null;
38
+ },
39
+ logout: ['auth', 'logout'],
40
+ },
41
+ codex: {
42
+ argv: ['login', '--device-auth'],
43
+ needsCode: false,
44
+ parse(text) {
45
+ const url = (text.match(URL_RE) || []).find((u) => /\/device\b/.test(u));
46
+ const code = /\b([A-Z0-9]{4}-[A-Z0-9]{4,8})\b/.exec(text)?.[1];
47
+ return url && code ? { url, user_code: code } : null;
48
+ },
49
+ logout: ['logout'],
50
+ },
51
+ });
52
+
53
+ /** Bản ghi một lần đăng nhập trả cho BE — không kèm chữ thô agent in ra (có thể dài / lạ), chỉ lỗi rút gọn. */
54
+ const publicOf = (s) => ({
55
+ login_id: s.id, agent: s.agent, state: s.state, url: s.url || null, user_code: s.user_code || null, needs_code: s.needsCode && s.state === LoginState.PENDING,
56
+ expires_at: s.expiresAt, ...(s.error ? { error: s.error } : {}),
57
+ });
58
+
59
+ /**
60
+ * `llm` = bộ mô hình trên máy ở chế độ máy tổ chức (localLlm.mjs, memberMode) — dùng chung danh sách agent đã cài + bộ nhớ "đã đăng nhập".
61
+ * Mỗi (thành viên, agent) tối đa một lần đăng nhập đang chờ; bắt đầu lại thì huỷ lần cũ.
62
+ */
63
+ export function createLlmLogin({ llm, spawnImpl = spawn, now = Date.now, ttlMs = LOGIN_TTL_MS, startWaitMs = START_WAIT_MS, codeWaitMs = CODE_WAIT_MS } = {}) {
64
+ const sessions = new Map();
65
+
66
+ const accountOf = (ctx) => {
67
+ const account = ctx?.runAs;
68
+ if (!account?.name) throw invalid('Sign-in on this shared computer needs a member');
69
+ return account;
70
+ };
71
+ const adapterOf = (agent) => {
72
+ const flow = LOGIN_FLOWS[agent];
73
+ if (!flow) throw invalid(`Sign-in from Aivin is not available for "${agent}" on this computer`);
74
+ return { adapter: llm.adapterFor(agent), flow };
75
+ };
76
+ const own = (id, account) => {
77
+ const s = sessions.get(String(id || ''));
78
+ if (!s || s.account.name !== account.name) throw failed('This sign-in is not running any more — start again', DeviceErrorCode.NOT_FOUND);
79
+ return s;
80
+ };
81
+
82
+ function end(s, state, error) {
83
+ if (s.state !== LoginState.PENDING) return;
84
+ s.state = state;
85
+ if (error) s.error = String(error).replace(ANSI_RE, '').trim().slice(-300);
86
+ clearTimeout(s.timer);
87
+ try { s.child.stdin?.end(); } catch { /* đã đóng */ }
88
+ if (state !== LoginState.SUCCEEDED) try { s.child.kill(); } catch { /* đã thoát */ }
89
+ llm.signIn?.forget(s.agent, s.account);
90
+ for (const fn of s.waiters.splice(0)) fn();
91
+ }
92
+
93
+ function sweep() {
94
+ for (const [id, s] of sessions) if (s.state !== LoginState.PENDING && now() - s.endedAt > ttlMs) sessions.delete(id);
95
+ }
96
+
97
+ /** Chờ tới khi `test()` đúng, lần đăng nhập kết thúc, hoặc hết `ms`. */
98
+ function waitFor(s, test, ms) {
99
+ if (test() || s.state !== LoginState.PENDING) return Promise.resolve();
100
+ return new Promise((resolve) => {
101
+ const timer = setTimeout(done, ms);
102
+ function done() { clearTimeout(timer); const i = s.waiters.indexOf(check); if (i >= 0) s.waiters.splice(i, 1); resolve(); }
103
+ function check() { if (test() || s.state !== LoginState.PENDING) done(); }
104
+ s.waiters.push(check);
105
+ });
106
+ }
107
+
108
+ async function start(args = {}, ctx = {}) {
109
+ const account = accountOf(ctx);
110
+ const agent = String(args.agent || '');
111
+ const { adapter, flow } = adapterOf(agent);
112
+ sweep();
113
+ for (const s of sessions.values()) if (s.account.name === account.name && s.agent === agent) end(s, LoginState.FAILED, 'Replaced by a new sign-in');
114
+ const [cmd, argv, opts] = memberSpawnArgs(account, llm.binOf(adapter).bin, flow.argv, { dir: llm.memberDir });
115
+ const child = spawnImpl(cmd, argv, { ...opts, stdio: ['pipe', 'pipe', 'pipe'] });
116
+ const s = {
117
+ id: randomUUID(), agent, account, child, needsCode: flow.needsCode, state: LoginState.PENDING, output: '', url: null, user_code: null,
118
+ expiresAt: now() + ttlMs, endedAt: 0, waiters: [], timer: null, codeSent: false,
119
+ };
120
+ sessions.set(s.id, s);
121
+ const onData = (d) => {
122
+ s.output = (s.output + String(d)).slice(-MAX_OUTPUT);
123
+ if (!s.url) {
124
+ const found = flow.parse(s.output.replace(ANSI_RE, ''));
125
+ if (found) Object.assign(s, found);
126
+ }
127
+ for (const fn of [...s.waiters]) fn();
128
+ };
129
+ child.stdout?.on('data', onData);
130
+ child.stderr?.on('data', onData);
131
+ child.once('error', (e) => end(s, LoginState.FAILED, `Could not start ${adapter.label}: ${e.message}`));
132
+ child.once('exit', (code) => {
133
+ s.endedAt = now();
134
+ if (code === 0) end(s, LoginState.SUCCEEDED);
135
+ else end(s, LoginState.FAILED, s.output || `${adapter.label} sign-in exited (${code})`);
136
+ });
137
+ s.timer = setTimeout(() => { s.endedAt = now(); end(s, LoginState.EXPIRED, 'Sign-in expired'); }, ttlMs);
138
+ s.timer.unref?.();
139
+ await waitFor(s, () => !!s.url, startWaitMs);
140
+ if (!s.url && s.state === LoginState.PENDING) end(s, LoginState.FAILED, `${adapter.label} did not print a sign-in link`);
141
+ return publicOf(s);
142
+ }
143
+
144
+ /** Claude Code: mã trang đăng nhập hiện ra → ghi vào stdin, chờ agent đổi mã lấy phiên đăng nhập (thoát 0). */
145
+ async function submitCode(args = {}, ctx = {}) {
146
+ const account = accountOf(ctx);
147
+ const s = own(args.login_id, account);
148
+ const code = String(args.code || '').trim();
149
+ if (!s.needsCode) throw invalid('This sign-in does not take a code — finish it in the browser');
150
+ if (!CODE_RE.test(code)) throw invalid('That does not look like a sign-in code — copy the whole code from the sign-in page');
151
+ if (s.state !== LoginState.PENDING) return publicOf(s);
152
+ if (s.codeSent) throw invalid('A code was already sent for this sign-in — start again if it failed');
153
+ s.codeSent = true;
154
+ try { s.child.stdin.write(`${code}\n`); } catch (e) { end(s, LoginState.FAILED, e.message); }
155
+ await waitFor(s, () => false, codeWaitMs);
156
+ return publicOf(s);
157
+ }
158
+
159
+ /** Trạng thái lần đăng nhập; `wait_ms` (≤ 25 s): chờ tới khi xong (Codex: người dùng xác nhận mã trên trình duyệt). */
160
+ async function poll(args = {}, ctx = {}) {
161
+ const account = accountOf(ctx);
162
+ const s = own(args.login_id, account);
163
+ const waitMs = Math.min(Math.max(0, Number(args.wait_ms) || 0), 25_000);
164
+ if (waitMs) await waitFor(s, () => false, waitMs);
165
+ return publicOf(s);
166
+ }
167
+
168
+ /** Agent đã cài + thành viên đã đăng nhập chưa (hỏi lại thật, không dùng kết quả nhớ). */
169
+ async function status(_args = {}, ctx = {}) {
170
+ const account = accountOf(ctx);
171
+ const agents = await Promise.all(llm.agents().map(async (a) => {
172
+ const signedIn = await llm.signIn.status(llm.adapterFor(a.id), account, { fresh: true }).catch(() => false);
173
+ return { id: a.id, label: a.label, ...(a.version ? { version: a.version } : {}), signed_in: signedIn, can_sign_in: !!LOGIN_FLOWS[a.id] };
174
+ }));
175
+ return { agents };
176
+ }
177
+
178
+ async function logout(args = {}, ctx = {}) {
179
+ const account = accountOf(ctx);
180
+ const agent = String(args.agent || '');
181
+ const { adapter, flow } = adapterOf(agent);
182
+ for (const s of sessions.values()) if (s.account.name === account.name && s.agent === agent) end(s, LoginState.FAILED, 'Signed out');
183
+ const r = await llm.signIn.run(account, llm.binOf(adapter).bin, flow.logout, { dir: llm.memberDir, timeoutMs: 20_000 });
184
+ llm.signIn.forget(agent, account);
185
+ const signedIn = await llm.signIn.status(adapter, account, { fresh: true }).catch(() => false);
186
+ return { agent, signed_in: signedIn, ok: !signedIn, ...(r.code !== 0 && signedIn ? { error: (r.err || r.out).trim().slice(-300) } : {}) };
187
+ }
188
+
189
+ function closeAll() {
190
+ for (const s of sessions.values()) end(s, LoginState.FAILED, 'Computer is shutting down');
191
+ sessions.clear();
192
+ }
193
+
194
+ return { start, submitCode, poll, status, logout, closeAll };
195
+ }
196
+
197
+ const str = (description) => ({ type: 'string', description });
198
+ const schema = (properties, required = []) => ({ type: 'object', properties, required });
199
+
200
+ /** Công cụ BE-only của máy tổ chức: trạng thái đăng nhập + đăng nhập / đăng xuất agent cho thành viên của lời gọi. */
201
+ export function buildLlmLoginTools(login) {
202
+ const call = (fn) => (a, c, e) => fn(a, { ...c, runAs: e?.runAs });
203
+ const base = { group: ToolGroup.PROC, read_only: true, internal: true };
204
+ return [
205
+ { ...base, name: 'llm.status', handler: call(login.status),
206
+ description: 'BE-only: coding agents on this shared computer and whether this member is signed in to each.', input_schema: schema({}) },
207
+ { ...base, name: 'llm.login_start', handler: call(login.start),
208
+ description: "BE-only: start signing this member in to an agent. Returns a link (and a one-time code for codex) to open on the member's own device.",
209
+ input_schema: schema({ agent: str('claude | codex') }, ['agent']) },
210
+ { ...base, name: 'llm.login_code', handler: call(login.submitCode),
211
+ description: 'BE-only: give the code shown after signing in (claude) to the running sign-in, wait for it to finish.',
212
+ input_schema: schema({ login_id: str('from llm.login_start'), code: str('code from the sign-in page') }, ['login_id', 'code']) },
213
+ { ...base, name: 'llm.login_poll', handler: call(login.poll),
214
+ description: 'BE-only: state of a running sign-in (pending | succeeded | failed | expired); wait_ms waits for it to finish.',
215
+ input_schema: schema({ login_id: str('from llm.login_start'), wait_ms: { type: 'number', description: 'max 25000' } }, ['login_id']) },
216
+ { ...base, name: 'llm.logout', handler: call(login.logout),
217
+ description: 'BE-only: sign this member out of an agent on this shared computer.', input_schema: schema({ agent: str('claude | codex') }, ['agent']) },
218
+ ];
219
+ }
@@ -0,0 +1,96 @@
1
+ // Mô hình trên máy ở MÁY TÍNH TỔ CHỨC (`--multi-user`, 17/11/2026): mỗi thành viên dùng agent (Claude Code / Codex) bằng TÀI KHOẢN CỦA CHÍNH
2
+ // HỌ — agent chạy dưới tài khoản Linux của thành viên (HOME = /home/<vùng>), nên tệp đăng nhập (~/.claude, ~/.codex) và hạn mức gói là của
3
+ // người đó, không ai dùng chung tài khoản của ai. Chưa đăng nhập → lời gọi báo `LOCAL_LLM_NOT_SIGNED_IN` ngay (không khởi động agent), BE
4
+ // chạy cloud và mời người dùng đăng nhập (localLlmLogin.mjs).
5
+ //
6
+ // Antigravity không có ở chế độ này: chưa có cách đăng nhập không màn hình, và tệp cài đặt không tách được theo người.
7
+ import fs from 'fs';
8
+ import { execFile } from 'child_process';
9
+ import { accountEnv, withProcessCap } from './multiUser.mjs';
10
+ import { agentEnv } from './sandbox.mjs';
11
+
12
+ /**
13
+ * Thư mục làm việc (cwd) của agent khi chạy cho thành viên: rỗng, của root, thành viên chỉ đọc / đi qua được (0755) — agent không thấy tệp
14
+ * dự án nào, thành viên cũng không ghi vào đây được (lớp ghi của container không có hạn mức đĩa). Không đặt trong /home/<vùng>: root không tạo
15
+ * / chown gì trong thư mục do thành viên điều khiển (liên kết tượng trưng).
16
+ */
17
+ export const MEMBER_LLM_DIR = '/var/lib/aivin-llm';
18
+ export const MEMBER_LLM_AGENTS = Object.freeze(['claude', 'codex']);
19
+
20
+ /** Biến của agent mà tiến trình root có thể mang — không để lọt sang tài khoản thành viên (agent phải đọc đăng nhập trong HOME của họ). */
21
+ const ROOT_ONLY_ENV = ['CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN', 'OPENAI_API_KEY'];
22
+
23
+ /** `env` của agent chạy cho thành viên: HOME / USER của họ, không tự cập nhật (bản cài thuộc root), không mở trình duyệt (máy không màn hình). */
24
+ export function memberAgentEnv(account, base = process.env) {
25
+ const env = { ...accountEnv(account, agentEnv(base)), DISABLE_AUTOUPDATER: '1', BROWSER: '/bin/true', NO_COLOR: '1' };
26
+ for (const k of ROOT_ONLY_ENV) delete env[k];
27
+ return env;
28
+ }
29
+
30
+ let dirReady = false;
31
+ function ensureMemberDir(dir) {
32
+ if (dirReady && dir === MEMBER_LLM_DIR) return;
33
+ fs.mkdirSync(dir, { recursive: true, mode: 0o755 });
34
+ try { fs.chmodSync(dir, 0o755); } catch { /* không phải chủ (thử nghiệm) */ }
35
+ if (dir === MEMBER_LLM_DIR) dirReady = true;
36
+ }
37
+
38
+ /** `[lệnh, tham số, tuỳ chọn spawn]` để chạy `bin argv` dưới tài khoản thành viên, có trần số tiến trình (prlimit). */
39
+ export function memberSpawnArgs(account, bin, argv, { dir = MEMBER_LLM_DIR, base = process.env } = {}) {
40
+ ensureMemberDir(dir);
41
+ const [cmd, args] = withProcessCap(bin, argv);
42
+ return [cmd, args, { cwd: dir, env: memberAgentEnv(account, base), uid: account.uid, gid: account.gid, windowsHide: true }];
43
+ }
44
+
45
+ /** Lệnh hỏi "đã đăng nhập chưa" của từng agent (không gọi mạng, < 1 s). */
46
+ export const SIGN_IN_PROBES = Object.freeze({
47
+ claude: {
48
+ argv: ['auth', 'status', '--json'],
49
+ // `{"loggedIn": true, "authMethod": "claude.ai" …}` — mã thoát 1 khi chưa đăng nhập (đo 2.1.326).
50
+ parse: (code, out) => {
51
+ try { return JSON.parse(out)?.loggedIn === true; } catch { return code === 0; }
52
+ },
53
+ },
54
+ // "Not logged in", mã thoát 1 (đo 0.169.0).
55
+ codex: { argv: ['login', 'status'], parse: (code) => code === 0 },
56
+ });
57
+
58
+ function runAs(account, bin, argv, { timeoutMs = 15_000, dir } = {}) {
59
+ const [cmd, args, opts] = memberSpawnArgs(account, bin, argv, { dir });
60
+ return new Promise((resolve) => {
61
+ execFile(cmd, args, { ...opts, encoding: 'utf8', timeout: timeoutMs, maxBuffer: 256 * 1024 }, (err, stdout, stderr) => {
62
+ const code = err ? (typeof err.code === 'number' ? err.code : -1) : 0;
63
+ resolve({ code, out: String(stdout || ''), err: String(stderr || '') });
64
+ });
65
+ });
66
+ }
67
+
68
+ /**
69
+ * "Thành viên đã đăng nhập agent chưa", nhớ ngắn: đã đăng nhập 5 phút, chưa 20 s (vừa đăng nhập xong ở nơi khác thì sớm thấy). Lời gọi bị
70
+ * agent báo lỗi xác thực / đăng nhập, đăng xuất → `forget` để hỏi lại ngay.
71
+ */
72
+ export function createSignInChecker({ binOf, run = runAs, now = Date.now, okTtlMs = 5 * 60_000, noTtlMs = 20_000, dir } = {}) {
73
+ const cache = new Map();
74
+ const keyOf = (agentId, account) => `${account.name}|${agentId}`;
75
+
76
+ async function status(adapter, account, { fresh = false } = {}) {
77
+ const probe = SIGN_IN_PROBES[adapter.id];
78
+ if (!probe) return false;
79
+ const key = keyOf(adapter.id, account);
80
+ const hit = cache.get(key);
81
+ if (!fresh && hit && now() - hit.at < (hit.ok ? okTtlMs : noTtlMs)) return hit.ok;
82
+ const bin = binOf(adapter)?.bin;
83
+ if (!bin) return false;
84
+ const r = await run(account, bin, probe.argv, { dir });
85
+ const ok = !!probe.parse(r.code, r.out);
86
+ if (cache.size > 2000) cache.clear();
87
+ cache.set(key, { ok, at: now() });
88
+ return ok;
89
+ }
90
+
91
+ return {
92
+ status,
93
+ forget: (agentId, account) => cache.delete(keyOf(agentId, account)),
94
+ run: (account, bin, argv, opts) => run(account, bin, argv, { dir, ...opts }),
95
+ };
96
+ }
@@ -7,6 +7,7 @@ import { fetchMascotImage } from './images.mjs';
7
7
  import { fileChip } from './fileChips.mjs';
8
8
  import { lucidePath } from './lucideIcons.mjs';
9
9
  import { safeLinkUrl, safeWebUrl } from './safeUrl.mjs';
10
+ import { createLocalLinkRegistry, LOCAL_LINK_PREFIX, localOpenTarget, LocalOpenKind, openLocal as openLocalPath } from './localOpen.mjs';
10
11
  import { MascotText, mascotText } from './strings.mjs';
11
12
 
12
13
  /**
@@ -151,6 +152,8 @@ export function createMascotChat({
151
152
  const features = { inbox: false, cancel: false, newChat: false, parallel: false };
152
153
  /** Câu hỏi đang chờ theo thứ tự đến: `{ session_id, reply_id, kind, options, text }`; đầu hàng = câu đang có nút. */
153
154
  const queue = [];
155
+ /** Nút mở tệp / thư mục trên máy (`links[].path`): cửa sổ chỉ cầm mã `local:<id>`, daemon tra ra đường dẫn rồi kiểm (localOpen.mjs). */
156
+ const localLinks = createLocalLinkRegistry();
154
157
  const head = () => queue[0] || null;
155
158
  const seenNotify = new Set();
156
159
  /** Tệp thả vào bot, chờ đi kèm câu kế tiếp. */
@@ -191,9 +194,12 @@ export function createMascotChat({
191
194
  if (iconPath) return { icon_path: iconPath };
192
195
  return /\p{Extended_Pictographic}/u.test(icon) ? { icon } : {};
193
196
  };
194
- /** Nút lựa chọn: `multiple` = câu chọn nhiều (cửa sổ cho tích nhiều mục rồi xác nhận); `icon` của mục (nếu có) đi kèm để hiện cuối nút. */
195
- const showChoices = (options, multiple = false) => send({
196
- t: AskCommand.CHOICES, multiple,
197
+ /**
198
+ * Nút lựa chọn: `multiple` = câu chọn nhiều (cửa sổ cho tích nhiều mục rồi xác nhận); `icon` của mục (nếu có) đi kèm để hiện cuối nút.
199
+ * `hint`: gợi ý mờ trong ô nhập cho câu / trường đang hỏi (gợi ý nhập của trường biểu mẫu) — lần gửi nút kế (kể cả bỏ nút) thay / xoá nó.
200
+ */
201
+ const showChoices = (options, multiple = false, hint = '') => send({
202
+ t: AskCommand.CHOICES, multiple, ...(hint ? { hint } : {}),
197
203
  options: options.map((o) => ({ id: String(o.id), text: String(o.text), ...choiceIcon(o.icon) })),
198
204
  });
199
205
  const setPending = (sessionId, question, text, url = null, payload = null) => {
@@ -251,12 +257,14 @@ export function createMascotChat({
251
257
  const total = q.fields.length;
252
258
  const options = fieldOptions(f);
253
259
  // Một trường bắt buộc không có lựa chọn: câu hỏi đã đủ, không cần dòng tên trường.
254
- if (total > 1 || options.length || !f.required || f.placeholder) {
255
- const base = total > 1 ? t(MascotText.FORM_FIELD, { label: f.label || f.name, n: q.step + 1, total }) : String(f.label || f.name);
256
- const label = f.placeholder ? `${base} (${f.placeholder})` : base;
257
- row(ChatRole.ASSISTANT, f.required ? label : `${label} ${t(MascotText.FORM_OPTIONAL)}`, `${QUESTION_ROW}${q.reply_id}-${q.step}`);
260
+ // Dòng trường: tên trường đậm (`field`), bên dưới một dòng phụ nhạt "Bước 1/3 · Không bắt buộc" (`sub`) — không nhồi ngoặc vào câu.
261
+ // Gợi ý nhập (`placeholder`) hiện mờ trong ô nhập (`hint` của nút), không nằm trong bong bóng.
262
+ if (total > 1 || options.length || !f.required) {
263
+ const sub = [total > 1 ? t(MascotText.FORM_STEP, { n: q.step + 1, total }) : '', f.required ? '' : t(MascotText.FORM_OPTIONAL)].filter(Boolean).join(' · ');
264
+ row(ChatRole.ASSISTANT, String(f.label || f.name), `${QUESTION_ROW}${q.reply_id}-${q.step}`, { field: true, ...(sub ? { sub } : {}) });
258
265
  }
259
- showChoices(f.required ? options : [...options, { id: FORM_SKIP_ID, text: t(MascotText.FORM_SKIP) }]);
266
+ const hint = typeof f.placeholder === 'string' ? f.placeholder.trim() : '';
267
+ showChoices(f.required ? options : [...options, { id: FORM_SKIP_ID, text: t(MascotText.FORM_SKIP) }], false, hint);
260
268
  }
261
269
  /** Ghi giá trị trường hiện tại (`null` = bỏ qua) → trường kế, hoặc gửi cả biểu mẫu một lần. */
262
270
  async function fillField(q, value, shown) {
@@ -317,6 +325,13 @@ export function createMascotChat({
317
325
  const linkButtons = (payload) => {
318
326
  const web = payload?.session_id ? safeWebUrl(webUrlForSession(payload.session_id, serverUrl)) : null;
319
327
  const links = (Array.isArray(payload?.links) ? payload.links : []).map((l) => {
328
+ // (18/11/2026) Tệp / thư mục TRÊN MÁY (thẻ duyệt việc lập trình: thư mục dự án, TEST_CHECK.md): chỉ khi đường dẫn có thật trên máy này.
329
+ if (typeof l?.path === 'string' && l.path) {
330
+ const target = localOpenTarget(l.path);
331
+ if (!target) return { text: '', url: null };
332
+ const icon = lucidePath(l?.icon) || lucidePath(target.kind === LocalOpenKind.FOLDER ? 'folder-open' : 'file-text') || lucidePath('folder');
333
+ return { text: typeof l?.text === 'string' ? l.text.trim() : '', url: `${LOCAL_LINK_PREFIX}${localLinks.register(target.path)}`, icon_path: icon };
334
+ }
320
335
  const url = l?.web === true ? web : safeLinkUrl(l?.url);
321
336
  const scheme = String(url || '').split(':')[0].toLowerCase();
322
337
  return { text: typeof l?.text === 'string' ? l.text.trim() : '', url, icon_path: lucidePath(l?.icon) || lucidePath(LINK_SCHEME_ICONS[scheme] || LINK_SCHEME_ICONS.https) };
@@ -1000,8 +1015,14 @@ export function createMascotChat({
1000
1015
  }
1001
1016
  }
1002
1017
 
1018
+ /** Cửa sổ bấm nút mở trên máy: tra mã → đường dẫn đã đăng ký, kiểm lại (có thể đã bị xoá) rồi mới mở. */
1019
+ const openLocal = (id) => {
1020
+ const p = localLinks.pathOf(id);
1021
+ if (!p || !openLocalPath(p)) send({ t: AskCommand.STATUS, text: t(MascotText.ASK_LOCAL_OPEN_FAILED) });
1022
+ };
1023
+
1003
1024
  return {
1004
- openTool,
1025
+ openTool, openLocal,
1005
1026
  ask, reply, choose, attach, detach, setWorkDir, workDirDenied, workDir: () => workDir, cancel, newChat, onChatEvent, onNotify, onQuestionClosed, syncInbox, checkQuestions, setServerFeatures, busy: () => !!current || !!call, hasPending: () => queue.length > 0, userWindow: () => target,
1006
1027
  voiceStart, voiceAudio, voiceInterrupt, voiceStop, voiceMicLost, voiceDisconnected, onVoiceEvent, setVoiceSupported, inCall: () => !!call,
1007
1028
  setNotifyFreq: (val) => { const v = Number(val); if (Number.isInteger(v) && v >= 0 && v <= 2) currentNotifyFreq = v; },
@@ -269,12 +269,17 @@ $script:clickCheckTimer.Start()
269
269
  (E 'Mascot').Add_MouseRightButtonUp({ param($s, $e) CloseAsk; OpenPanel; $e.Handled = $true })
270
270
  # One button: empty box = mic, typed text = send.
271
271
  # Waiting on a turn the server can stop (chat_busy { cancel }): the empty-box button is a stop button instead of the mic.
272
+ $script:fieldHint = ''
272
273
  function StopMode { $script:chatBusy -and $script:canCancel -and -not $script:voiceLive -and -not (E 'AskBox').Text.Trim() -and -not $script:files }
273
274
  function SyncAction {
274
275
  # Files waiting (chips above the input): the button sends even with nothing typed, and the hint asks what to do with them.
275
276
  $typed = [bool](E 'AskBox').Text.Trim() -or ($script:files -gt 0 -and -not $script:voiceLive)
276
277
  $stop = StopMode
277
- (E 'AskHint').Text = if ($script:files -gt 0) { $T.ask_attached } else { $T.ask_hint }
278
+ # A form field being asked: its own input hint ("pick a member or type an email") instead of the generic one; may wrap to a second line.
279
+ $field = $script:fieldHint -and $script:files -le 0
280
+ (E 'AskHint').Text = if ($script:files -gt 0) { $T.ask_attached } elseif ($field) { $script:fieldHint } else { $T.ask_hint }
281
+ (E 'AskHint').TextWrapping = if ($field) { 'Wrap' } else { 'NoWrap' }
282
+ (E 'AskHint').FontSize = if ($field) { 13 } else { 14 }
278
283
  (E 'AskHint').Visibility = if ((E 'AskBox').Text) { 'Collapsed' } else { 'Visible' }
279
284
  (E 'SendIcon').Visibility = if ($typed) { 'Visible' } else { 'Collapsed' }; (E 'MicIcon').Visibility = if ($typed -or $stop) { 'Collapsed' } else { 'Visible' }
280
285
  (E 'StopIcon').Visibility = if ($stop) { 'Visible' } else { 'Collapsed' }
@@ -340,10 +345,11 @@ function LinkCard($text, $url, $iconPath = '${LINK_ICON_PATH}') {
340
345
  $dock = New-Object Windows.Controls.DockPanel; $dock.MaxWidth = ${CHOICE_ROW_WIDTH}
341
346
  $icon = LucideIcon $(if ($iconPath) { $iconPath } else { '${LINK_ICON_PATH}' }) 13 '${ICON_INKS[2]}'; $icon.Margin = '8,2,0,0'; $icon.VerticalAlignment = 'Top'; [Windows.Controls.DockPanel]::SetDock($icon, 'Right'); [void]$dock.Children.Add($icon)
342
347
  $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.Foreground = Brush '${CHOICE_INK}'; SetText $tb $text; [void]$dock.Children.Add($tb)
343
- $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $dock; $btn.CommandParameter = [string]$url; $btn.ToolTip = [string]$url
348
+ $btn = New-Object Windows.Controls.Button; $btn.Style = $w.FindResource('Btn'); $btn.Content = $dock; $btn.CommandParameter = [string]$url; if (-not ([string]$url).StartsWith('local:')) { $btn.ToolTip = [string]$url }
344
349
  $btn.FontSize = 13; $btn.FontWeight = 'Normal'; $btn.Padding = '10,6,10,6'; $btn.Margin = '0,0,0,3'; $btn.HorizontalAlignment = 'Left'
345
350
  $btn.Background = Brush '${CHOICE_CARDS[2]}'; $btn.BorderThickness = '0'; $btn.Tag = Brush '${CHOICE_HOVER}'
346
- $btn.Add_Click({ param($s) OpenWebUrl $s.CommandParameter })
351
+ # Open-on-this-computer buttons (url 'local:<id>'): the window never opens them itself - it sends the id, the daemon checks the path first (localOpen.mjs).
352
+ $btn.Add_Click({ param($s) $u = [string]$s.CommandParameter; if ($u.StartsWith('local:')) { Send @{ t = 'open_local'; id = $u.Substring(6) } } else { OpenWebUrl $u } })
347
353
  $btn
348
354
  }
349
355
  function ChatLinks($row, $links) {
@@ -367,13 +373,18 @@ function ChatRow($m) {
367
373
  # the same on all four sides.
368
374
  $b = New-Object Windows.Controls.Border; $b.Padding = '10,5,10,5'; $b.Margin = '0,0,0,4'; $b.MaxWidth = $script:bubbleMax
369
375
  $tb = New-Object Windows.Controls.TextBlock; $tb.TextWrapping = 'Wrap'; $tb.FontSize = 14; $tb.LineHeight = 20; $tb.LineStackingStrategy = 'BlockLineHeight'
370
- $b.Child = $tb; [void]$list.Children.Add($b)
376
+ # Links in the text (Emoji.SetLinked): a click opens the browser (http/https only, OpenWebUrl), not the bubble's own link.
377
+ $tb.AddHandler([Windows.Documents.Hyperlink]::RequestNavigateEvent, [Windows.Navigation.RequestNavigateEventHandler]{ param($s, $e) $e.Handled = $true; OpenWebUrl $e.Uri.AbsoluteUri })
378
+ # Second line under the text (a form field's "Step 1/3 - Optional"): smaller, muted.
379
+ $sub = New-Object Windows.Controls.TextBlock; $sub.TextWrapping = 'Wrap'; $sub.FontSize = 12; $sub.Margin = '0,1,0,1'; $sub.Foreground = Brush $P.muted; $sub.Visibility = 'Collapsed'
380
+ $body = New-Object Windows.Controls.StackPanel; [void]$body.Children.Add($tb); [void]$body.Children.Add($sub)
381
+ $b.Child = $body; [void]$list.Children.Add($b)
371
382
  $slide = New-Object Windows.Media.TranslateTransform 0, 6; $b.RenderTransform = $slide
372
383
  $ease = New-Object Windows.Media.Animation.CubicEase; $ease.EasingMode = 'EaseOut'
373
384
  $fade = New-Object Windows.Media.Animation.DoubleAnimation 0, 1, ([TimeSpan]::FromMilliseconds(200)); $fade.EasingFunction = $ease
374
385
  $rise = New-Object Windows.Media.Animation.DoubleAnimation 6, 0, ([TimeSpan]::FromMilliseconds(240)); $rise.EasingFunction = $ease
375
386
  $b.BeginAnimation([Windows.UIElement]::OpacityProperty, $fade); $slide.BeginAnimation([Windows.Media.TranslateTransform]::YProperty, $rise)
376
- $row = @{ box = $b; text = $tb; url = $null }
387
+ $row = @{ box = $b; body = $body; text = $tb; sub = $sub; url = $null }
377
388
  # The link rides on the bubble itself (Tag, updated below): the handler is not a closure, $row at click time is not this row.
378
389
  $b.Add_MouseLeftButtonUp({ param($s) OpenWebUrl $s.Tag })
379
390
  if ($id) { $script:chatRows[$id] = $row }
@@ -396,7 +407,10 @@ function ChatRow($m) {
396
407
  $fg = if ($role -eq 'progress') { $P.muted } elseif ($role -eq 'error') { '#CB2634' } else { $P.ink }
397
408
  $row.box.Background = Brush $bg; $row.text.Foreground = Brush $fg
398
409
  $row.text.FontStyle = if ($role -eq 'progress') { 'Italic' } else { 'Normal' }
399
- SetText $row.text $m.text
410
+ if ($role -eq 'progress') { SetText $row.text $m.text } else { [AivinMascot.Emoji]::SetLinked($row.text, [string]$m.text) }
411
+ # A form field's row: the field name in bold, the step / "optional" under it.
412
+ $row.text.FontWeight = if ($m.field) { 'SemiBold' } else { 'Normal' }
413
+ if ($m.sub) { SetText $row.sub $m.sub; $row.sub.Visibility = 'Visible' } else { $row.sub.Visibility = 'Collapsed' }
400
414
  ChatLinks $row $null
401
415
  ChatBlocks $row $m.blocks
402
416
  ChatLinks $row $m.links
@@ -405,7 +419,7 @@ function ChatRow($m) {
405
419
  if ($m.typing) {
406
420
  if (-not $row.dots) { $row.dots = TypingDots }
407
421
  $row.box.Child = $row.dots; $row.box.Background = Brush '#F4F6FA'; $row.box.CornerRadius = '10,10,10,3'
408
- } elseif ($row.dots -and $row.box.Child -ne $row.text) { $row.box.Child = $row.text }
422
+ } elseif ($row.dots -and $row.box.Child -ne $row.body) { $row.box.Child = $row.body }
409
423
  # Words the owner is still saying: lighter until the sentence is settled (the box's own opacity is the fade-in).
410
424
  $row.text.Opacity = if ($m.partial) { 0.55 } else { 1 }
411
425
  $script:scrollRow = if ($row.blocks) { $row } else { $null }
@@ -634,7 +648,7 @@ function Handle($m) {
634
648
  return
635
649
  }
636
650
  'ask_status' { AskStatus $m.text; return }
637
- 'ask_choices' { ChoiceButtons $m.options $m.multiple; return }
651
+ 'ask_choices' { ChoiceButtons $m.options $m.multiple; $script:fieldHint = [string]$m.hint; SyncAction; return }
638
652
  # Files waiting for the next question: chips above the input; then on to the bot's tray (no return).
639
653
  'ask_files' { $chips = @($m.files | Where-Object { $_ }); $more = @($chips | Where-Object { -not $_.pinned }).Count -gt @((E 'AttachBar').Children | Where-Object { $_.Tag -ne 'pinned' }).Count; $script:files = [int]$m.n; AttachChips $chips; SyncAction; if ($more) { PeekAsk; HideAskLater ${ASK_IDLE_MS} } }
640
654
  'ask_pin' {
@@ -249,7 +249,65 @@ export const EMOJI_CS = String.raw`
249
249
  return tag ?? block.Text;
250
250
  }
251
251
 
252
+ static readonly System.Text.RegularExpressions.Regex UrlPattern = new System.Text.RegularExpressions.Regex(@"https?://[^\s<>""']+", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
253
+ static readonly Brush LinkBrush = MakeLinkBrush();
254
+ static Brush MakeLinkBrush() { var b = new SolidColorBrush(Color.FromRgb(0x16, 0x5D, 0xFF)); b.Freeze(); return b; }
255
+
256
+ /**
257
+ * Nhu Set, them: dia chi http(s) trong chu thanh link (xanh, gach duoi, tay tro). Bam link noi su kien Hyperlink.RequestNavigate len
258
+ * TextBlock - host bat su kien do va mo trinh duyet (qua OpenWebUrl, chi http/https). Dau cau dinh cuoi dia chi (. , ) ...) khong tinh vao link.
259
+ */
260
+ public static void SetLinked(System.Windows.Controls.TextBlock block, string text) {
261
+ string s = text ?? "";
262
+ var found = UrlPattern.Matches(s);
263
+ if (found.Count == 0) { Set(block, s); return; }
264
+ block.Tag = s;
265
+ try {
266
+ bool emoji = MayHaveEmoji(s);
267
+ if (emoji && !loaded) Load();
268
+ emoji = emoji && face != null;
269
+ var parts = new List<System.Windows.Documents.Inline>(); int at = 0;
270
+ foreach (System.Text.RegularExpressions.Match m in found) {
271
+ string url = m.Value.TrimEnd('.', ',', ';', ':', '!', '?', ')', ']', '}', '"', '\'');
272
+ Uri uri;
273
+ if (url.Length < 9 || !Uri.TryCreate(url, UriKind.Absolute, out uri)) continue;
274
+ if (m.Index > at) AddText(parts, s.Substring(at, m.Index - at), block.FontSize, emoji);
275
+ var link = new System.Windows.Documents.Hyperlink(new System.Windows.Documents.Run(LinkLabel(url))) { NavigateUri = uri, Foreground = LinkBrush, ToolTip = url };
276
+ link.TextDecorations = System.Windows.TextDecorations.Underline;
277
+ parts.Add(link); at = m.Index + url.Length;
278
+ }
279
+ if (at < s.Length) AddText(parts, s.Substring(at), block.FontSize, emoji);
280
+ block.Inlines.Clear();
281
+ block.Inlines.AddRange(parts);
282
+ } catch { block.Text = s; }
283
+ }
284
+
285
+ /** Chu hien cua link: bo "https://" / "www." / "/" cuoi; dai qua thi cat (dia chi day du o ToolTip, bam van mo dung dia chi). */
286
+ public static string LinkLabel(string url) {
287
+ string s = url;
288
+ int scheme = s.IndexOf("://", StringComparison.Ordinal);
289
+ if (scheme > 0) s = s.Substring(scheme + 3);
290
+ if (s.StartsWith("www.", StringComparison.OrdinalIgnoreCase)) s = s.Substring(4);
291
+ if (s.EndsWith("/", StringComparison.Ordinal)) s = s.Substring(0, s.Length - 1);
292
+ if (s.Length > LinkMax) s = s.Substring(0, LinkMax - 1) + (char)0x2026;
293
+ return s.Length > 0 ? s : url;
294
+ }
295
+ const int LinkMax = 42;
296
+
297
+ static void AddText(List<System.Windows.Documents.Inline> parts, string s, double fontSize, bool emoji) {
298
+ if (!emoji || !AppendPieces(parts, s, fontSize)) parts.Add(new System.Windows.Documents.Run(s));
299
+ }
300
+
252
301
  static bool SetInlines(System.Windows.Controls.TextBlock block, string s) {
302
+ var parts = new List<System.Windows.Documents.Inline>();
303
+ if (!AppendPieces(parts, s, block.FontSize)) return false;
304
+ block.Inlines.Clear();
305
+ block.Inlines.AddRange(parts);
306
+ return true;
307
+ }
308
+
309
+ /** Chu + hinh emoji cua s vao parts; false (parts khong doi) khi s khong co emoji nao ve duoc. */
310
+ static bool AppendPieces(List<System.Windows.Documents.Inline> outParts, string s, double fontSize) {
253
311
  var parts = new List<System.Windows.Documents.Inline>(); var plain = new StringBuilder(); bool any = false;
254
312
  for (int i = 0; i < s.Length; ) {
255
313
  if (char.IsHighSurrogate(s[i]) && !(i + 1 < s.Length && char.IsLowSurrogate(s[i + 1])) || char.IsLowSurrogate(s[i])) { plain.Append(s[i]); i++; continue; }
@@ -261,12 +319,11 @@ export const EMOJI_CS = String.raw`
261
319
  }
262
320
  any = true;
263
321
  if (plain.Length > 0) { parts.Add(new System.Windows.Documents.Run(plain.ToString())); plain.Clear(); }
264
- foreach (ushort g in run) if (baseFirst.ContainsKey(g)) parts.Add(PictureInline(g, block.FontSize));
322
+ foreach (ushort g in run) if (baseFirst.ContainsKey(g)) parts.Add(PictureInline(g, fontSize));
265
323
  }
266
324
  if (!any) return false;
267
325
  if (plain.Length > 0) parts.Add(new System.Windows.Documents.Run(plain.ToString()));
268
- block.Inlines.Clear();
269
- block.Inlines.AddRange(parts);
326
+ outParts.AddRange(parts);
270
327
  return true;
271
328
  }
272
329
  }
@@ -199,8 +199,14 @@ export const MASCOT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/20
199
199
  <Button x:Name="PanelClose" DockPanel.Dock="Right" Style="{StaticResource IconBtn}" Content="✕" Width="30" Height="30" FontSize="11"
200
200
  FontWeight="Normal" Background="Transparent" BorderThickness="0" Tag="#F2F3F5" Foreground="${B.muted}"/>
201
201
  </DockPanel>
202
- <TextBlock x:Name="NowLabel" DockPanel.Dock="Top" Margin="0,14,0,4" FontSize="11" FontWeight="SemiBold" Foreground="${B.muted}"/>
203
- <TextBlock x:Name="NowText" DockPanel.Dock="Top" Margin="0,0,6,0" FontSize="14" Foreground="${B.ink}" TextWrapping="Wrap" LineHeight="20"/>
202
+ <!-- "Đang làm": nhãn bên trái, việc hiện tại là tag bên phải (dài thì xuống dòng trong tag, căn phải). -->
203
+ <Grid DockPanel.Dock="Top" Margin="0,14,6,0">
204
+ <Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions>
205
+ <TextBlock x:Name="NowLabel" FontSize="11" FontWeight="SemiBold" Foreground="${B.muted}" VerticalAlignment="Center" Margin="0,0,12,0"/>
206
+ <Border Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" CornerRadius="10" Background="#F2F3F5" Padding="10,3,10,4">
207
+ <TextBlock x:Name="NowText" FontSize="12.5" FontWeight="SemiBold" Foreground="${B.ink}" TextWrapping="Wrap" TextAlignment="Right" LineHeight="18"/>
208
+ </Border>
209
+ </Grid>
204
210
  <!-- Tần suất thông báo: 3 nấc (Ít = phiên này + cần xử lý, Vừa = thêm việc trên máy, Tất cả), khối trắng trượt tới nấc đang chọn -->
205
211
  <TextBlock x:Name="NotifyFreqLabel" DockPanel.Dock="Top" Margin="0,14,0,6" FontSize="11" FontWeight="SemiBold" Foreground="${B.muted}"/>
206
212
  <Grid x:Name="NotifySteps" DockPanel.Dock="Top" Margin="0,0,6,0" Height="30">
@@ -298,7 +304,7 @@ ${[0, 1, 2].map((i) => ` <Border x:Name="NotifyStep${i}" Tag="${i}" Backgro
298
304
  <TextBlock x:Name="AskStatus" Visibility="Collapsed" FontSize="13" Foreground="${B.muted}" Margin="0,2,4,1" TextTrimming="CharacterEllipsis"/>
299
305
  </StackPanel>
300
306
  <!-- Dau x mo o goc phai tren: cat o hoi di ngay, ke ca khi Aivin dang cho tra loi (cau hoi van con, mo lai bang cach re vao bot). -->
301
- <Button x:Name="AskClose" Visibility="Collapsed" Style="{StaticResource IconBtn}" Width="18" Height="18" Padding="0" Margin="0,1,1,0" Opacity="0.3"
307
+ <Button x:Name="AskClose" Visibility="Collapsed" Style="{StaticResource IconBtn}" Width="18" Height="18" Padding="0" Margin="0,5,5,0" Opacity="0.3"
302
308
  HorizontalAlignment="Right" VerticalAlignment="Top" Background="#E8FFFFFF" BorderThickness="0" Tag="#F2F3F5">
303
309
  <Path Data="${ICON_CLOSE_X}" Stroke="${B.muted}" StrokeThickness="1.5" StrokeStartLineCap="Round" StrokeEndLineCap="Round"
304
310
  Width="9" Height="9" Stretch="Uniform"/>
@@ -122,7 +122,7 @@ export function requestMascotHide(file = MASCOT_HIDE_FILE) {
122
122
  fs.writeFileSync(file, String(Date.now()));
123
123
  }
124
124
  export const HostEvent = Object.freeze({
125
- READY: 'ready', POS: 'pos', PAUSE: 'pause', RESUME: 'resume', HIDE: 'hide', OFF: 'off', ASK: 'ask', CHOOSE: 'choose', CANCEL: 'cancel', NEW_CHAT: 'new_chat', OPEN_WEBVIEW: 'open_webview',
125
+ READY: 'ready', POS: 'pos', PAUSE: 'pause', RESUME: 'resume', HIDE: 'hide', OFF: 'off', ASK: 'ask', CHOOSE: 'choose', CANCEL: 'cancel', NEW_CHAT: 'new_chat', OPEN_WEBVIEW: 'open_webview', OPEN_LOCAL: 'open_local',
126
126
  DROP: 'drop', DETACH: 'detach', AWAY: 'away', BACK: 'back', NOTIFY_FREQ: 'notify_freq', HOTKEYS: 'hotkeys',
127
127
  VOICE_START: 'voice_start', VOICE_AUDIO: 'voice_audio', VOICE_INTERRUPT: 'voice_interrupt', VOICE_STOP: 'voice_stop', VOICE_MIC_LOST: 'voice_mic_lost',
128
128
  });
@@ -240,7 +240,7 @@ export function userWindow(w) {
240
240
  */
241
241
  export function createMascot({
242
242
  enabled = true, platform = process.platform, env = process.env, lang: preferredLang, onPause = () => {}, onResume = () => {}, say = () => {},
243
- onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onOpenTool = () => {}, onDrop = () => {}, onWorkFolder = () => {}, onDetach = () => {}, onNotifyFreq = () => {},
243
+ onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onOpenTool = () => {}, onOpenLocal = () => {}, onDrop = () => {}, onWorkFolder = () => {}, onDetach = () => {}, onNotifyFreq = () => {},
244
244
  spawnImpl = spawn, dir = MASCOT_DIR, settingsFile = MASCOT_SETTINGS_FILE, showFile = MASCOT_SHOW_FILE, hideFile = MASCOT_HIDE_FILE, voiceFile = MASCOT_VOICE_FILE, hotkeysFile = MASCOT_HOTKEYS_FILE,
245
245
  attachDir = MASCOT_ATTACH_DIR, now = Date.now, timers = { setTimeout, clearTimeout },
246
246
  thinkMs = THINK_MS, resultMs = RESULT_MS, mainThrottleMs = MAIN_THROTTLE_MS, offlineGraceMs = OFFLINE_GRACE_MS, restartDelaysMs = RESTART_DELAYS_MS, awayWaveMs = AWAY_WAVE_MS,
@@ -352,6 +352,8 @@ export function createMascot({
352
352
  // Nút "Chat mới" trên bảng: phiên chat mới cho linh vật.
353
353
  if (msg.t === HostEvent.NEW_CHAT) return onNewChat();
354
354
  if (msg.t === HostEvent.OPEN_WEBVIEW) return onOpenTool(msg);
355
+ // Nút mở tệp / thư mục trên máy (thẻ duyệt việc lập trình): cửa sổ chỉ gửi mã, daemon tra + kiểm rồi mới mở (localOpen.mjs).
356
+ if (msg.t === HostEvent.OPEN_LOCAL && typeof msg.id === 'string' && msg.id) return onOpenLocal(msg.id);
355
357
  if (msg.t === HostEvent.NOTIFY_FREQ && Number.isFinite(msg.value)) {
356
358
  const val = Number(msg.value);
357
359
  if (val >= 0 && val <= 2) {