agy-mcp-bridge 0.1.29 → 0.1.30

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,45 @@
1
+ import { appendFile, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ /**
4
+ * The owner's decisions about a finished task (apply its changes, discard its worktree), one line each. The task history keeps only the
5
+ * latest tasks, so this is the record of who changed the workspace and when. Trimmed when the file grows large.
6
+ */
7
+ export const DECISIONS_FILE = 'decisions.jsonl';
8
+ const MAX_FILE_BYTES = 512 * 1024;
9
+ const KEEP_RECORDS = 500;
10
+ export async function appendDecision(stateDirectory, decision) {
11
+ const file = path.join(stateDirectory, DECISIONS_FILE);
12
+ try {
13
+ await mkdir(stateDirectory, { recursive: true });
14
+ await appendFile(file, JSON.stringify(decision) + '\n', { mode: 0o600 });
15
+ if ((await stat(file)).size > MAX_FILE_BYTES) {
16
+ const lines = (await readFile(file, 'utf8')).split('\n').filter(Boolean);
17
+ await writeFile(file, lines.slice(-KEEP_RECORDS).join('\n') + '\n', { mode: 0o600 });
18
+ }
19
+ }
20
+ catch { /* the log is a convenience, never a reason to fail the action it describes */ }
21
+ }
22
+ /** Newest first. A damaged line is skipped. */
23
+ export async function readDecisions(stateDirectory, limit = 50) {
24
+ let text;
25
+ try {
26
+ text = await readFile(path.join(stateDirectory, DECISIONS_FILE), 'utf8');
27
+ }
28
+ catch {
29
+ return [];
30
+ }
31
+ const records = [];
32
+ for (const line of text.split('\n')) {
33
+ if (!line.trim())
34
+ continue;
35
+ try {
36
+ const value = JSON.parse(line);
37
+ if (typeof value.at === 'string' && typeof value.task_id === 'string' && (value.action === 'apply' || value.action === 'discard') && typeof value.ok === 'boolean') {
38
+ records.push({ at: value.at, task_id: value.task_id, action: value.action, ok: value.ok, detail: String(value.detail ?? '').slice(0, 500) });
39
+ }
40
+ }
41
+ catch { /* skip a damaged line */ }
42
+ }
43
+ return records.slice(-limit).reverse();
44
+ }
45
+ //# sourceMappingURL=decisions.js.map
@@ -0,0 +1,96 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { realpath } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { inside } from '../security/workspace.js';
5
+ import { isOwned, normalizeOwn } from './worktree.js';
6
+ /**
7
+ * Brings a finished worktree task's changes into the original workspace as plain, uncommitted edits.
8
+ *
9
+ * Deliberately not a branch merge: nothing is committed on the owner's behalf, no branch is switched, and the owner reviews and
10
+ * commits (or `git restore`s) what arrives. The patch is built from the worktree, checked against the workspace first, and only
11
+ * then applied, so a workspace that moved on since the task started is refused instead of half-written.
12
+ */
13
+ const MAX_PATCH_BYTES = 8 * 1024 * 1024;
14
+ const MAX_FILES = 500;
15
+ const gitEnvironment = () => ({
16
+ PATH: process.env.PATH, PATHEXT: process.env.PATHEXT, SystemRoot: process.env.SystemRoot, COMSPEC: process.env.COMSPEC,
17
+ TEMP: process.env.TEMP, TMP: process.env.TMP, TMPDIR: process.env.TMPDIR,
18
+ GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null',
19
+ GIT_ATTR_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', GIT_PAGER: 'cat', LC_ALL: 'C'
20
+ });
21
+ class Refusal extends Error {
22
+ }
23
+ function git(cwd, args, input) {
24
+ return new Promise((resolve, reject) => {
25
+ const child = execFile('git', ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=' + (process.platform === 'win32' ? 'NUL' : '/dev/null'), ...args], { cwd, env: gitEnvironment(), timeout: 30000, maxBuffer: MAX_PATCH_BYTES + 1024, encoding: 'utf8', windowsHide: true }, (error, stdout, stderr) => {
26
+ if (error)
27
+ reject(new Error((stderr || error.message).trim().split('\n')[0].slice(0, 300)));
28
+ else
29
+ resolve(stdout);
30
+ });
31
+ // A git that exits before reading its input (a bad patch) closes the pipe; that is reported through the exit status, not as a crash.
32
+ child.stdin?.on('error', () => undefined);
33
+ if (input !== undefined)
34
+ child.stdin?.end(input);
35
+ });
36
+ }
37
+ /** The directory's path inside the repository, forward slashes, no trailing slash ('' at the top). */
38
+ async function prefixOf(toplevel, workspace) {
39
+ const [top, work] = await Promise.all([realpath(toplevel), realpath(workspace)]);
40
+ if (!inside(top, work))
41
+ throw new Refusal('The workspace is not inside the repository the worktree was made from');
42
+ return path.relative(top, work).split(path.sep).join('/');
43
+ }
44
+ /** The repository root of a directory, as an absolute canonical path. */
45
+ export async function repositoryRoot(directory) {
46
+ try {
47
+ return await realpath((await git(directory, ['rev-parse', '--show-toplevel'])).trim());
48
+ }
49
+ catch (error) {
50
+ throw new Error('The workspace is not a git repository: ' + (error instanceof Error ? error.message : 'git failed'));
51
+ }
52
+ }
53
+ const literal = (file) => `:(literal)${file}`;
54
+ export async function applyWorktreeChanges(input) {
55
+ try {
56
+ const prefix = await prefixOf(input.toplevel, input.workspace);
57
+ const scope = prefix ? [prefix] : ['.'];
58
+ const owns = input.owns.map(normalizeOwn);
59
+ if (!owns.length)
60
+ throw new Refusal('The task declared no owned paths, so there is nothing it was allowed to change');
61
+ // Staging is only a way to include new files in the diff: it touches the worktree's own index, never the workspace.
62
+ await git(input.worktree, ['add', '-A', '--', ...scope]);
63
+ const names = (await git(input.worktree, ['diff', '--cached', '--name-only', '-z', 'HEAD', '--', ...scope])).split('\0').filter(Boolean);
64
+ if (!names.length)
65
+ throw new Refusal('The worktree has no changes to apply');
66
+ if (names.length > MAX_FILES)
67
+ throw new Refusal(`The worktree changes ${names.length} files; apply is limited to ${MAX_FILES}`);
68
+ const relative = names.map(name => prefix && name.startsWith(`${prefix}/`) ? name.slice(prefix.length + 1) : name);
69
+ const outside = relative.filter(name => !isOwned(name, owns));
70
+ if (outside.length)
71
+ throw new Refusal(`Files outside the task's owned paths were changed (${outside.slice(0, 5).join(', ')}); review them in the worktree`);
72
+ // A symlink or a submodule pointer is more than text: it can point outside the workspace, so it is never applied from here.
73
+ const raw = (await git(input.worktree, ['diff', '--cached', '--raw', '-z', 'HEAD', '--', ...scope])).split('\0');
74
+ if (raw.some(field => /^:(?:12|16)0000 /.test(field) || /^:\d+ (?:12|16)0000 /.test(field)))
75
+ throw new Refusal('The change includes a symlink or a submodule, which is not applied from here; review it in the worktree');
76
+ const patch = await git(input.worktree, ['diff', '--cached', '--binary', '--full-index', '--no-ext-diff', '--no-textconv', 'HEAD', '--', ...scope]);
77
+ if (Buffer.byteLength(patch) > MAX_PATCH_BYTES)
78
+ throw new Refusal('The change is larger than the apply limit; review it in the worktree');
79
+ // A file the owner is editing right now is theirs to merge by hand, even if the patch would happen to fit.
80
+ const dirty = (await git(input.toplevel, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', ...names.map(literal)])).split('\0').filter(Boolean);
81
+ if (dirty.length)
82
+ throw new Refusal(`The workspace already has uncommitted changes in: ${dirty.slice(0, 5).map(line => line.slice(3)).join(', ')}`);
83
+ try {
84
+ await git(input.toplevel, ['apply', '--check', '--whitespace=nowarn', '-'], patch);
85
+ }
86
+ catch (error) {
87
+ throw new Refusal(`The changes no longer fit the workspace: ${error instanceof Error ? error.message : 'git apply --check failed'}`);
88
+ }
89
+ await git(input.toplevel, ['apply', '--whitespace=nowarn', '-'], patch);
90
+ return { applied: true, files: relative.sort(), patch_bytes: Buffer.byteLength(patch) };
91
+ }
92
+ catch (error) {
93
+ return { applied: false, reason: error instanceof Error ? error.message : 'Apply failed' };
94
+ }
95
+ }
96
+ //# sourceMappingURL=apply.js.map
@@ -299,10 +299,10 @@ export async function pruneWorktrees(repo, worktreesRoot) {
299
299
  return { pruned: 0, reason: error instanceof Error ? error.message : 'could not prune worktree records' };
300
300
  }
301
301
  }
302
- function normalizeOwn(own) {
302
+ export function normalizeOwn(own) {
303
303
  return path.posix.normalize(own.replace(/\\/g, '/')).replace(/^\.\//, '').replace(/\/+$/, '');
304
304
  }
305
- function isOwned(relative, owns) {
305
+ export function isOwned(relative, owns) {
306
306
  return owns.some(own => relative === own || relative.startsWith(`${own}/`));
307
307
  }
308
308
  /** Compare the real diff with the declared ownership list. Any file outside it must be reviewed before merging. */
@@ -1,10 +1,12 @@
1
1
  import { existsSync, statSync } from 'node:fs';
2
- import { mkdir, readdir, readFile, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
2
+ import { mkdir, readdir, readFile, realpath, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { StringDecoder } from 'node:string_decoder';
5
5
  import path from 'node:path';
6
6
  import { DEFAULT_MAX_WAIT_SECONDS, delegateSchema, promptFor } from '../security/input.js';
7
- import { validateWorkspace } from '../security/workspace.js';
7
+ import { inside, validateWorkspace } from '../security/workspace.js';
8
+ import { appendDecision } from '../decisions.js';
9
+ import { applyWorktreeChanges, repositoryRoot } from '../isolation/apply.js';
8
10
  import { redact } from '../security/redact.js';
9
11
  import { delegationState } from '../delegation.js';
10
12
  import { startProcess, terminateOwned } from '../antigravity/process.js';
@@ -732,6 +734,99 @@ export class TaskManager {
732
734
  await this.persist(entry.task);
733
735
  entry.finish?.();
734
736
  }
737
+ /**
738
+ * The owner's decisions about a finished worktree task (never an MCP client's): bring its changes into the workspace, or throw the
739
+ * worktree away. One at a time, so two clicks cannot interleave two git operations on the same repository.
740
+ */
741
+ decisionQueue = Promise.resolve();
742
+ enqueueDecision(work) {
743
+ const run = this.decisionQueue.then(work);
744
+ this.decisionQueue = run.catch(() => undefined);
745
+ return run;
746
+ }
747
+ async reviewableTask(id) {
748
+ const entry = this.entries.get(id);
749
+ if (!entry)
750
+ throw new Error('Unknown or expired task_id');
751
+ const task = entry.task;
752
+ if (task.isolation !== 'worktree' || !task.worktree)
753
+ throw new Error('This task did not run in a worktree');
754
+ if (task.status === 'queued' || task.status === 'running')
755
+ throw new Error('The task is still running');
756
+ if (task.discarded_at)
757
+ throw new Error('This task worktree was already discarded');
758
+ const [root, canonical] = await Promise.all([
759
+ realpath(path.join(this.runtime.stateDirectory, 'worktrees')).catch(() => null),
760
+ realpath(task.worktree).catch(() => null)
761
+ ]);
762
+ if (!canonical)
763
+ throw new Error('The task worktree no longer exists');
764
+ if (!root || !inside(root, canonical))
765
+ throw new Error('The task worktree is not under the bridge state directory');
766
+ return task;
767
+ }
768
+ recordDecision(id, action, ok, detail) {
769
+ return appendDecision(this.runtime.stateDirectory, { at: new Date().toISOString(), task_id: id, action, ok, detail });
770
+ }
771
+ applyTask(id) {
772
+ return this.enqueueDecision(async () => {
773
+ const task = await this.reviewableTask(id);
774
+ const refuse = async (reason) => { await this.recordDecision(id, 'apply', false, reason); throw new Error(reason); };
775
+ if (task.status !== 'completed')
776
+ return refuse(`Only a completed task can be applied (this one is ${task.status})`);
777
+ if (task.applied_at)
778
+ throw new Error('This task was already applied');
779
+ if (task.scope?.out_of_scope.length)
780
+ return refuse(`The task changed files outside its owned paths (${task.scope.out_of_scope.slice(0, 5).join(', ')}); review them in the worktree`);
781
+ let workspace;
782
+ try {
783
+ workspace = await validateWorkspace(task.workspace, this.config.allowed_workspaces);
784
+ }
785
+ catch (error) {
786
+ return refuse(`The workspace is no longer allowed: ${error instanceof Error ? error.message : 'invalid'}`);
787
+ }
788
+ let toplevel;
789
+ try {
790
+ toplevel = await repositoryRoot(workspace);
791
+ }
792
+ catch (error) {
793
+ return refuse(error instanceof Error ? error.message : 'The workspace is not a git repository');
794
+ }
795
+ const result = await applyWorktreeChanges({ worktree: task.worktree, toplevel, workspace, owns: task.owns });
796
+ if (!result.applied)
797
+ return refuse(result.reason);
798
+ task.applied_at = new Date().toISOString();
799
+ task.applied_files = result.files.slice(0, 100);
800
+ await this.persist(task);
801
+ await this.recordDecision(id, 'apply', true, `${result.files.length} file(s): ${result.files.slice(0, 5).join(', ')}`);
802
+ return { task: this.summary(id), files: result.files };
803
+ });
804
+ }
805
+ discardTask(id) {
806
+ return this.enqueueDecision(async () => {
807
+ const task = await this.reviewableTask(id);
808
+ let toplevel;
809
+ try {
810
+ toplevel = await repositoryRoot(await validateWorkspace(task.workspace, this.config.allowed_workspaces));
811
+ }
812
+ catch (error) {
813
+ const reason = error instanceof Error ? error.message : 'The workspace is not usable';
814
+ await this.recordDecision(id, 'discard', false, reason);
815
+ throw new Error(reason);
816
+ }
817
+ const worktree = { root: task.worktree, workspace: task.worktree, toplevel, branch: task.branch ?? '', prefix: '', base: '' };
818
+ const removal = await removeWorktree(worktree);
819
+ if (!removal.removed) {
820
+ const reason = removal.reason ?? 'The worktree could not be removed';
821
+ await this.recordDecision(id, 'discard', false, reason);
822
+ throw new Error(reason);
823
+ }
824
+ task.discarded_at = new Date().toISOString();
825
+ await this.persist(task);
826
+ await this.recordDecision(id, 'discard', true, task.applied_at ? 'worktree removed after its changes were applied' : 'worktree removed without applying its changes');
827
+ return this.summary(id);
828
+ });
829
+ }
735
830
  get(id) {
736
831
  const entry = this.entries.get(id);
737
832
  if (!entry)
@@ -5,6 +5,7 @@ import { redact } from '../security/redact.js';
5
5
  import { paths } from '../paths.js';
6
6
  import { knownUpdate, readPackageInfo } from '../update.js';
7
7
  import { workspaceChanges } from '../changes.js';
8
+ import { readDecisions } from '../decisions.js';
8
9
  import { validModelId, writeModel } from '../models.js';
9
10
  import { readProgress, writeProgress } from '../progress.js';
10
11
  import { readUsage, summarizeUsage } from '../usage.js';
@@ -171,6 +172,31 @@ export async function handleUi(req, res, ctx) {
171
172
  json(res, 200, await changesFor(ctx, changes[1]));
172
173
  return true;
173
174
  }
175
+ // Applying a finished task's changes edits the owner's workspace, so like stopping a plan it is a decision for a person at the page.
176
+ const apply = pathname.match(new RegExp(`^/ui/api/tasks/(${UUID})/apply$`));
177
+ if (apply && method === 'POST') {
178
+ const body = await readJson(req);
179
+ if (body.confirm !== true) {
180
+ json(res, 400, { error: 'confirm must be true' });
181
+ return true;
182
+ }
183
+ json(res, 200, await ctx.manager.applyTask(apply[1]));
184
+ return true;
185
+ }
186
+ const discard = pathname.match(new RegExp(`^/ui/api/tasks/(${UUID})/discard$`));
187
+ if (discard && method === 'POST') {
188
+ const body = await readJson(req);
189
+ if (body.confirm !== true) {
190
+ json(res, 400, { error: 'confirm must be true' });
191
+ return true;
192
+ }
193
+ json(res, 200, { task: await ctx.manager.discardTask(discard[1]) });
194
+ return true;
195
+ }
196
+ if (pathname === '/ui/api/decisions' && method === 'GET') {
197
+ json(res, 200, { decisions: await readDecisions(ctx.manager.stateDirectory) });
198
+ return true;
199
+ }
174
200
  const cancel = pathname.match(new RegExp(`^/ui/api/tasks/(${UUID})/cancel$`));
175
201
  if (cancel && method === 'POST') {
176
202
  await ctx.manager.cancel(cancel[1]);
@@ -239,6 +239,19 @@ ngân sách token theo mission — usage vẫn chỉ được ghi và tổng h
239
239
  - Hàng đợi duyệt cho hành động ngoài chính sách.
240
240
  - Nhật ký quyết định, diff theo task, nút hợp nhất nhánh.
241
241
 
242
+ **Đã làm (lát cắt 1: duyệt kết quả worktree).** Trang Task có panel "Duyệt kết quả worktree" cho task chạy trong worktree:
243
+
244
+ - `Áp dụng vào workspace` ghi thay đổi của worktree vào workspace gốc dưới dạng **chưa commit** (`git apply`; bridge không tạo commit,
245
+ không đổi nhánh). Bị từ chối, kèm lý do, khi: task chưa `completed`, có file ngoài `owns`, workspace không còn trong allowlist,
246
+ workspace đang có sửa đổi chưa commit trên cùng file, patch không còn khớp (workspace đã đi tiếp), hoặc thay đổi có symlink/submodule.
247
+ - `Bỏ worktree` xóa thư mục và nhánh `bridge/<id>` của task (giữ nguyên workspace).
248
+ - Nhật ký quyết định ở `<state>/decisions.jsonl` (mỗi dòng: thời điểm, task, apply/discard, ok, chi tiết), hiện trong panel và ở `GET /ui/api/decisions`.
249
+ - Chỉ chủ bridge làm được việc này qua web UI (`POST /ui/api/tasks/<id>/apply|discard` với `confirm: true`). Không có tool MCP tương ứng, nên một
250
+ agent hay client không tự áp dụng kết quả của chính nó.
251
+
252
+ Chưa làm của Phase 4: trang Settings cho agent ưu tiên / số task song song / autonomy mặc định (hiện là file cấu hình), hàng đợi duyệt hành động
253
+ ngoài chính sách, nút hợp nhất theo nhánh (commit) và diff nội dung từng file.
254
+
242
255
  ### Phase 5 — Tích hợp và hardening
243
256
 
244
257
  - Merge nhánh trung gian, kiểm tra xung đột, chạy test trên nhánh tích hợp.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-mcp-bridge",
3
- "version": "0.1.29",
3
+ "version": "0.1.30",
4
4
  "description": "Local loopback HTTP MCP bridge that delegates bounded coding tasks to multiple agent CLIs (Antigravity, Codex) with optional parallel git worktrees",
5
5
  "license": "MIT",
6
6
  "keywords": [
package/ui/app.css CHANGED
@@ -126,6 +126,7 @@ button { cursor: pointer; }
126
126
  .callout { padding: 10px 12px; border-radius: 10px; font-weight: 550; overflow-wrap: anywhere; }
127
127
  .callout.bad { background: var(--bad-soft); color: var(--bad); }
128
128
  .callout.warn { background: var(--warn-soft); color: var(--warn); }
129
+ .callout.good { background: var(--ok-soft); color: var(--ok); }
129
130
  .chips { display: flex; gap: 6px; flex-wrap: wrap; }
130
131
  .chip { padding: 2px 9px; border-radius: 8px; background: var(--surface); border: 1px solid var(--border); font-size: 12.5px; font-family: var(--mono); }
131
132
  .typing { display: flex; align-items: center; gap: 10px; color: var(--muted); }
package/ui/app.js CHANGED
@@ -397,6 +397,58 @@ function changesBody(task) {
397
397
  d.truncated ? h('div', {class: 'callout warn', text: 'Chỉ hiện 500 mục đầu tiên của mỗi nhóm.'}) : null
398
398
  ];
399
399
  }
400
+ /* ---------- Review a finished worktree task: apply its changes, or throw the worktree away. Both are the owner's decision, never an agent's. ---------- */
401
+ async function loadDecisions() {
402
+ try { state.decisions = (await api('decisions')).decisions; } catch { /* keep the list already on screen */ }
403
+ patch();
404
+ }
405
+ async function applyTask(task) {
406
+ if (!confirm(`Áp dụng thay đổi của task này vào workspace?\n\n${task.workspace}\n\nCác file được ghi thẳng vào thư mục làm việc ở dạng CHƯA COMMIT; bridge không tạo commit nào. Muốn bỏ thì dùng git restore.\nBị từ chối nếu workspace đang có sửa đổi chưa commit trên cùng file, hoặc thay đổi không còn khớp.`)) return;
407
+ try {
408
+ const result = await api(`tasks/${task.task_id}/apply`, {method: 'POST', body: {confirm: true}});
409
+ notify(`Đã áp dụng ${result.files.length} file vào workspace (chưa commit)`);
410
+ await refresh(true);
411
+ } catch (error) { notify(error.message); }
412
+ await loadDecisions();
413
+ }
414
+ async function discardTask(task) {
415
+ const note = task.applied_at ? 'Thay đổi đã được áp dụng vào workspace trước đó, nên không mất gì.' : 'Thay đổi của task CHƯA được áp dụng và sẽ mất cùng worktree.';
416
+ if (!confirm(`Bỏ worktree và nhánh ${task.branch || ''} của task này?\n\n${note}`)) return;
417
+ try { await api(`tasks/${task.task_id}/discard`, {method: 'POST', body: {confirm: true}}); notify('Đã bỏ worktree'); await refresh(true); }
418
+ catch (error) { notify(error.message); }
419
+ await loadDecisions();
420
+ }
421
+ /** Why the apply button is off, or null when it is available. Mirrors the checks the bridge repeats on the server. */
422
+ function applyBlock(task) {
423
+ if (task.discarded_at) return 'Worktree đã bị bỏ.';
424
+ if (task.applied_at) return 'Đã áp dụng.';
425
+ if (task.status !== 'completed') return `Chỉ áp dụng được task đã hoàn tất (task này: ${task.status}).`;
426
+ if (task.scope && task.scope.out_of_scope.length) return `Task sửa file ngoài phạm vi được giao (${task.scope.out_of_scope.slice(0, 3).join(', ')}); xem trong worktree.`;
427
+ return null;
428
+ }
429
+ function reviewBody(task) {
430
+ const block = applyBlock(task);
431
+ const mine = (state.decisions || []).filter(item => item.task_id === task.task_id);
432
+ return [
433
+ h('p', {class: 'muted', text: 'Kết quả nằm trong worktree riêng, chưa đụng tới workspace của bạn. Áp dụng ghi thay đổi vào workspace dạng chưa commit; bỏ worktree xóa thư mục và nhánh của task.'}),
434
+ task.applied_at ? h('div', {class: 'callout good', text: `Đã áp dụng lúc ${clock(task.applied_at)}: ${(task.applied_files || []).join(', ') || '(không rõ file)'}. Xem git status trong workspace rồi commit hoặc git restore.`}) : null,
435
+ task.discarded_at ? h('div', {class: 'callout', text: `Đã bỏ worktree lúc ${clock(task.discarded_at)}.`}) : null,
436
+ h('div', {class: 'chips'},
437
+ h('button', {class: 'btn primary small', disabled: Boolean(block), title: block || 'Ghi thay đổi vào workspace', onclick: () => applyTask(task), text: 'Áp dụng vào workspace'}),
438
+ h('button', {class: 'btn danger small', disabled: Boolean(task.discarded_at), onclick: () => discardTask(task), text: 'Bỏ worktree'})),
439
+ block && !task.applied_at && !task.discarded_at ? h('p', {class: 'muted', text: block}) : null,
440
+ mine.length ? h('div', {}, h('div', {class: 'msg-head', text: 'Nhật ký quyết định'}),
441
+ h('ul', {class: 'change-list'}, mine.map(item => h('li', {class: 'change-row'},
442
+ h('span', {class: `change-kind ${item.ok ? 'added' : 'deleted'}`, text: item.action === 'apply' ? 'Áp dụng' : 'Bỏ'}),
443
+ h('span', {class: 'change-path', text: `${item.ok ? '' : 'Bị từ chối: '}${item.detail}`}),
444
+ h('span', {class: 'change-count mono', text: clock(item.at)}))))) : null
445
+ ];
446
+ }
447
+ function reviewPanel(task) {
448
+ const el = details('review', 'Duyệt kết quả worktree', ...reviewBody(task));
449
+ el.addEventListener('toggle', () => { if (el.open && !state.decisions) void loadDecisions(); });
450
+ return el;
451
+ }
400
452
  function changesPanel(task) {
401
453
  const el = details('changes', 'Thay đổi trong workspace', ...changesBody(task));
402
454
  el.addEventListener('toggle', () => { if (el.open && (!state.changes || state.changes.task_id !== task.task_id)) loadChanges(task.task_id); });
@@ -501,6 +553,7 @@ function detailView() {
501
553
 
502
554
  return h('article', {class: 'card detail'}, head, progress, h('div', {class: 'convo'}, asked, replied),
503
555
  changesPanel(task),
556
+ task.isolation === 'worktree' && task.status !== 'running' && task.status !== 'queued' ? reviewPanel(task) : null,
504
557
  details('steps', `Các bước ${agentName} báo cáo`, h('div', {id: 'steps-body'}, stepsBody(state.detail?.activity))),
505
558
  details('logs', `Log của tiến trình ${agentName}`, logs),
506
559
  collapsible('more:fact', 'Xem thêm thông số task', facts),
@@ -821,7 +874,7 @@ function patch() {
821
874
  setRegion('list', JSON.stringify([state.q, state.filter, state.selected, o.budget?.task_tokens, o.tasks.map(t => stable(t))]), () => taskItems(o));
822
875
  regions.count.textContent = taskCount(o);
823
876
  const d = state.detail;
824
- const detailKey = JSON.stringify([state.selected, state.logTab, state.changes, d && {...d, activity: null, task: {...stable(d.task), stdout: '', stderr: '', stdout_bytes: 0, stderr_bytes: 0, stdout_truncated: false, stderr_truncated: false}}]);
877
+ const detailKey = JSON.stringify([state.selected, state.logTab, state.changes, state.decisions, d && {...d, activity: null, task: {...stable(d.task), stdout: '', stderr: '', stdout_bytes: 0, stderr_bytes: 0, stdout_truncated: false, stderr_truncated: false}}]);
825
878
  const rebuilt = signatures.detail !== detailKey;
826
879
  setRegion('detail', detailKey, () => detailView());
827
880
  if (!rebuilt) patchLogs();