Commit Graph
52 Commits
Author SHA1 Message Date
7d56b54324 feat(agent): 部署上限按订阅档动态化,闭合 #8 个人5/团队8 (#21)
沿用订阅体系现成先例 MaxPurchasePerUser,给 SubscriptionPlan 加 MaxAgents:

- model: SubscriptionPlan.MaxAgents(0=回退全局默认)+ GetUserMaxAgents(取用户
  active 订阅档最高 MaxAgents,无则回退默认)。
- HeicodeDeployAgent: 部署上限改 model.GetUserMaxAgents(userID, 环境默认5)。
  团队8=管理员把团队档配成8;个人5=默认;代码不硬编码 tier。
- subscription 控制器: Create/Update 校验 MaxAgents>=0;Update updateMap 补 max_agents。
- 前端管理端套餐表单(plan-form/types/drawer)加「Agent 部署上限」字段 + zh i18n。

测试 model/subscription_max_agents_test.go 全过(无订阅/团队档/0回退/过期/多档取最高/非法用户)。
go build、go vet、前端 tsc 干净。

Fixes #8

Co-authored-by: chenchen <chenchen@xinghanlab.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 14:28:19 +08:00
aa4041f604 fix(web): 钱包余额直读 /api/user/self(去 502) + 部署完成提示/动画 (#23)
两处 HM web 前端修复(此前已热部署到 VM 验证):

1. 钱包 502:wallet 不再经 /api/heicode-auth → mcp-server 读余额(那条会触发
   HM GetUser 同级权限检查 → 502)。HM 本就是 new-api,直接读用户自己的
   /api/user/self(GetSelf,无角色检查)。
2. 异步部署无反馈:deploy-agent-page 加快轮询(启动中 3s/稳定 30s)+ 检测
   Pending→running 弹「✅ 部署完成,已就绪」(失败弹错误)+「启动中」徽章转圈脉冲。

tsc 干净。

Co-authored-by: chenchen <chenchen@xinghanlab.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 14:27:19 +08:00
chenchenandClaude Opus 4.8 f4968b8072 fix(agent): review fixes — deployable-template gating, stopped-status guard, UI consistency
Backend:
- loadAgentTemplate now requires status='active' — a known template_key can no
  longer deploy a template an admin deactivated (matches the client list).
- refreshAgentStatus no longer lets AM's eventually-consistent live status
  resurrect a user-initiated "stopped" agent.
- HeicodeStopAgent persists via field-level Updates (not a stale full-row Save),
  matching refreshAgentStatus discipline.
- Drop dead amStartResult.AccessToken field (AM's token is never used; HM mints
  its own per-agent token).

Frontend:
- deploy-agent statusLabel: add the missing pending/starting → 启动中 branch so a
  just-deployed agent isn't shown as raw English fallback.
- cockpit 最近部署: map template_id → Chinese template name (consistent with the
  deploy/status pages) instead of showing the raw key.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 11:06:49 +08:00
chenchenandClaude Opus 4.8 05de8f50e4 feat(agent): log outbound env keys to AM; show direct URL + access token in 运行状态
- runtime: log the env KEY NAMES (never values) sent to AM on start, so we can
  confirm AGENT_ACCESS_TOKEN is actually transmitted without leaking secrets.
- web/运行状态: detail panel now shows the full direct-connect URL (copyable) and
  the per-agent access token (masked + reveal + copy) with a hint that the client
  sends it as X-Agent-Access-Token. These are what's actually needed to hand the
  agent to a client / test it — previously only the bare hostname was shown.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 00:16:28 +08:00
chenchenandClaude Opus 4.8 3a2ad36e5d fix(web): show unsupported resources (vm) disabled; Overview uses new-model framing
1) Deploy Sub Agent: stop hiding resource types AM doesn't support yet (vm) —
   show them but disabled with a "暂不支持" badge + tooltip, so users see their
   bindings instead of wondering where the vm went.
2) Overview (概述/cockpit): replaced the old task-model status cards
   (Running/Completed/Failed/裁决 + "code delivery runs") with template-agent
   semantics — Agent 总数 / 运行中 / 启动中 / 异常, "最近部署 · 我的 Agent",
   all Chinese. Dropped unused t()/useTranslation/PlayCircle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:59:12 +08:00
chenchenandClaude Opus 4.8 c4316f7fcd feat(web): new "运行状态" page (new-model agent status, not old task fields)
Re-add a run-status menu (I shouldn't have removed it) but showing ONLY what the
template-agent model actually has — no old 待确认/sub_agile/子任务流/智能体任务图/
产物/SK快照/合并时间线. New /agent-status page:
- summary counts (total / running / starting / other)
- agent list (template Chinese name, live status badge, subdomain, #resources)
- detail panel: live status (polls /agents/{id}/status from AM), copyable
  subdomain, mounted resources (names from /api/resources), runtime_id, timestamps.
Sidebar item "运行状态" + zh key added; build + tsc clean; route registered.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:46:22 +08:00
chenchenandClaude Opus 4.8 d19920d1d0 fix(web): remove old "运行总览" task UI; Overview shows new template agents
The old /deployments (运行总览) + /tasks/$id pages rendered the new template agents
with meaningless old sub-task fields (待确认/sub_agile/子任务流/智能体任务图/产物/
SK快照/合并时间线 — all empty). Removed the whole old-model UI cluster and pointed
the Overview dashboard at the real new endpoint:

- deleted features/agent-console, features/agent-hub, features/tasks and the
  routes /deployments and /tasks/$id.
- cockpit (Overview) now lists deployed template agents from /api/heicode/agents
  (status counts + recent agents), not the old listAgentDeployments.
- removed the "运行总览" sidebar item + dead /deployments links in footer /
  top-nav / sidebar-config.
- routeTree regenerated; frontend build + tsc clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:32:03 +08:00
chenchenandClaude Opus 4.8 074a3cc7e7 feat(agent): align HM to AM's coding_a2a_agent contract
Adapt HM's template-agent integration to AM's actual CODING_A2A API (per their
doc), keeping it isolated in agent_template_runtime.go:

- start payload -> AM's POST /agents { name, template:"coding_a2a_agent",
  framework:"A2A", config:{user_id,...}, env } with the template .md folded into
  env.AGENT_INSTRUCTION_TEXT, template_key -> AGENT_ROLE_NAME, model gateway via
  OPENAI_BASE_URL + MODEL_NAME (OPENAI_API_KEY left to the client per A2A request).
- response parse -> access_info.domain/external_ip -> subdomain, namespace/name
  -> runtime_id; AM issues no access_token (client uses A2A api_key).
- env names aligned to AM: GIT_DEFAULT_BRANCH, POSTGRES_* (was PG_*),
  AZURE_BLOB_ACCOUNT_NAME/CONTAINER/ACCOUNT_KEY (was BLOB_*); source keys aligned
  to the resource-binding form (db_name/username/database_password/access_key).
  Only AM-supported types (git/mysql/postgres/azure-blob); vm/redis/mongo/bucket
  now rejected as unsupported until AM adds them.
- frontend: resources page splits DB into MySQL/PostgreSQL (correct provider),
  drops vm; deploy page hides unsupported resource types.
- docs: AM contract + client doc updated to the real env names, payload, and the
  A2A direct-connect (message/send · message/stream) + api_key auth.
- tests updated for the new env names + AM payload/response shape. All green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 15:30:33 +08:00
chenchenandClaude Opus 4.8 7a48155568 fix(agent): apply review findings (backend data-integrity + frontend error UX)
Two review agents (backend + frontend) audited the template-agent feature. Real
findings fixed (verified the one false-positive — okOrThrow already reads the
top-level success because the response interceptor returns response, not
response.data):

Backend:
- buildAgentEnvFromBindings now filters status='active' so a revoked/disabled
  binding can't still have its KV secret resolved + injected.
- same-type binding env collision (e.g. two git repos -> GIT_REPO_URL) now errors
  instead of silently overwriting.
- refreshAgentStatus uses a field-level Updates (status/updated_at) instead of
  Save(full row) to avoid clobbering a concurrent stop/delete.
- tests added: same-type collision rejected, inactive binding rejected.

Frontend:
- deploy/stop/delete now pass noBusinessError so the global interceptor stops
  double-toasting the raw English backend message; okOrThrow+onError give one
  friendly Chinese error. Extracted okOrThrow/noBusinessError into lib/api.ts.
- resources page revoke + create + KV-secret-write now check success (okOrThrow)
  so a failed unbind / credential write no longer falsely reports success.
- clipboard copy wrapped in try/catch (no false "copied" on failure).
- resources group label shows Chinese resource-type names.

Go + frontend builds/tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 14:24:25 +08:00
chenchenandClaude Opus 4.8 16cca5df1c fix(agent): review fixes — success-check, template name, seed Once, update guard
Full review of the template-agent code surfaced and fixed:
- [frontend, critical] deploy/stop/delete treated HTTP-200-with-success:false as
  success (backend agentError returns 200 per new-api convention) -> a failed
  call wrongly toasted success. Added okOrThrow() that inspects the envelope and
  throws the server (or a friendly Chinese) message so onError fires.
- [frontend] "我的 Agent" showed the raw template key (architect) instead of the
  Chinese name; now resolves name via the templates list.
- [backend] ensureAgentTemplatesSeeded consumed sync.Once even when model.DB was
  nil (would permanently skip seeding) -> DB check moved outside the Once.
- [backend] AdminUpdateAgentTemplate could wipe name_zh/definition with empty
  values -> guard those critical fields.
- [security] warn when starting an agent with secret-bearing env over a non-HTTPS
  AM URL (secrets must not transit the network in clear).

Go + frontend build/tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 00:59:03 +08:00
chenchenandClaude Opus 4.8 8823bf5e5d feat(web): add "部署 Sub Agent" menu + page (pick resources + template -> deploy)
Customer-facing, plain Chinese (no env/technical jargon). New sidebar item
"部署 Sub Agent" -> /deploy-agent. The page:
- Step 1: pick which bound resources the agent may use (multi-select cards from
  /api/resources).
- Step 2: pick an agent template (cards show Chinese name + description from
  /api/heicode/agent-templates).
- Deploy -> POST /api/heicode/agents {template_id, binding_ids}.
- "我的 Agent" list (/api/heicode/agents) with status, copy-address, stop, delete.

Frontend builds clean (tsc + rsbuild; routeTree regenerated). zh label added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 00:25:12 +08:00
chenchenandClaude Opus 4.8 0eb754b1e1 refactor(web): Overview usage reuses WalletStatsCard (same as 模型与余额)
The wallet page already renders Current Balance / Total Usage / API Requests
from /api/user/self. Reuse that exact component (WalletStatsCard) on the
Overview instead of a hand-written block — DRY, identical numbers
($160.47 / $39.53 / 521 for the current user).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 11:08:45 +08:00
chenchenandClaude Opus 4.8 42883dac63 fix(web): Overview usage shows the CURRENT user own consumption, not global
The reused LogStatCards aggregates ALL users for admin accounts, so an admin
(root) saw gateway-wide totals (e.g. $628 / 339M tokens / 5218 req) instead of
their own. And per-user windowed quota-dates were empty (0). Replaced with the
user's own lifetime usage from /api/user/self (used_quota = spend, quota =
remaining, request_count), formatted with formatQuota. Real, non-zero, per-user.
(LogStatCards also gained an optional userScope prop for future per-user use.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 11:04:54 +08:00
chenchenandClaude Opus 4.8 448571496d feat(web): add usage & cost (user consumption) to the Overview dashboard
Reuse the existing LogStatCards (requests / quota=cost / tokens=consumption,
all props optional) on the Overview cockpit — no new data/logic, just renders
the current user usage stats under a "Usage & cost" section.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 10:40:29 +08:00
chenchenandClaude Opus 4.8 8710de7c20 feat(web): resource binding page in the Manager console (5 types)
Re-adds Resource binding to the Heicode cockpit (/resources). Add bindings for
GitHub / Gitea (type=git + provider), VM (ssh), database, blob; non-secret
fields go to metadata, the credential is written to Azure Key Vault via
POST /api/resources/:id/secret and only the secret_ref is shown (masked).
List + unbind. Backend already supported this; now functional since KV is up.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 00:39:28 +08:00
chenchenandClaude Opus 4.8 8329a323b0 refactor(web): Overview is now a dashboard, drop the idea-capture hero
Per direction: 概述 should be a 看板, not a "turn an idea into shippable
software" marketing surface.
- Removed the idea-hero (home-hero.tsx: IdeaInput + mcp-fed ContinueTasks/
  TodayFocus/HelperEntries, which were often empty/unreachable).
- Overview now renders the live metrics dashboard (CockpitView, previously
  dead code): Running / Completed / Failed / Pending counts by display_status
  + recent runs, fed by the working listAgentDeployments.
- Dropped the marketing "Quick actions / Control plane online" tier.
- Subtitle: "From an idea to shippable software." -> "Live overview of your
  Agent runs." Added zh translations.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 23:22:44 +08:00
chenchenandClaude Opus 4.8 5d7854d9ac fix(heicode): mode-filter task lists, hard-delete, mode-aware Agent runs page
- /api/heicode/sub-agile/tasks now returns only sub_agile, /swarm only swarm
  (both previously returned every deployment regardless of mode).
- DELETE /tasks/{id} now hard-deletes the record (best-effort runtime stop +
  remove row + in-memory entry) so a deleted task disappears from the list,
  instead of only marking it stopped.
- Admin runs page: renamed Task overview -> Agent runs, cards show the mode
  (Sub Agile / Swarm) chip, added a mode filter; status already uses
  display_status.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 21:11:39 +08:00
chenchenandClaude Opus 4.8 8b28c180c7 refactor(web): remove legacy/non-functional admin console pages, align to current product
The Manager console carried screens built to an early control-plane vision
that no longer matches how the product runs (desktop client drives tasks;
Manager is gateway + status judge). Removed the dead/misleading ones and
aligned task overview to the real status model. Frontend only; no backend
endpoints touched.

Deleted (routes + pages + menu entries):
- Resource binding (/sk-sources): mcp-server /api/resources unwired (301) +
  Azure Key Vault unreachable -> page was inert.
- Audit (/audit): only simulated approvals, empty leases, mcp audit unwired.
- Events / Templates / Agents pages: legacy control-plane (hardcoded mock
  templates), not in the main menu but route-reachable.
- azure-cloud-binding-sheet + create-agent-deployment-sheet (New run).

Task overview (/deployments) kept and fixed:
- status now uses Manager-judged display_status (completed / needs_codegen /
  completed_without_deliverable=fail / running ...) instead of raw phase, so
  success vs failure is legible.
- dropped New run, scope/budget/secret_ref pills, permission-manifest grants
  table, Simulate; kept the task list, per-task audit timeline and artifacts.

Cleaned all menu/nav/dashboard references to the deleted routes (sidebar,
top-nav, footer, cockpit, home-hero, agent-hub, task-card-view) and
regenerated routeTree.gen.ts. tsc -b and rsbuild build both pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 19:39:49 +08:00
chenchenandClaude Opus 4.8 0fe1d20d67 feat(agent): unify agnet→agent and implement client/runtime unification spec v0.1 core
按桌面客户端统一方案 v0.1 + agent_management Sub Mode Runtime 对接,强制全量统一,不留兼容。

命名统一(强制,无兼容):
- 全仓 agnet/Agnet/AGNET → agent/Agent/AGENT:后端 Go(路由 /api/agent/*、env AGENT_*、
  结构体/函数、19 个文件改名)、前端(agent-console/agent-hub、/api/agent 调用、i18n)、
  DB(表 agent_*、列 agent_id)、compose/.env、文档、脚本。
- DB 加幂等迁移 renameAgnetTablesToAgent():启动时 rename 老 agnet_* 表/列,保住生产数据。

统一方案核心(10 项):
- callback 统一 /api/agent/callbacks/runtime-events(路由/广播URL/函数名)。
- artifact 兜底判定改用 Runtime 权威信号 metadata.synthesized(§7.2)+ 结构化 artifact_type。
- Manager→Runtime 路径对齐 /api/agent/sub-agile/deployments(§2.2),{deployment_id} 回退 swarm_id。
- 状态裁决 display_status:Manager 唯一裁判,completed 无有效产物→needs_codegen/
  completed_without_deliverable(§10.6),接入 detail/timeline/workflow。
- GET /api/heicode/capabilities 能力发现(§6)。
- 模型策略 per_role(role_models)+ 收集 allowed_model_ids(§9)。
- resource_binding_id→secret_ref 服务端解析,客户端不再 inline secret_ref(§17.6)。
- 客户端统一路由层 /api/heicode/sub-agile|swarm/*(task≡deployment,复用控制面)+ workflow 投影。
- 日志分层 user_logs/debug_logs(§13)。

验证:go build ./... + go test(controller/router/model/middleware)全绿;前端 tsc -b + rsbuild build 通过。
待部署:VM .env 的 AGNET_*→AGENT_*;启动迁移自动 rename 表;其他三仓库需同步切到 /api/agent。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-01 23:45:10 +08:00
gongzhiyong 8e56284baa fix: polish manager account pages 2026-05-30 15:37:28 +08:00
gongzhiyong 8c1d9461f4 fix: use valid default agnet runtime models 2026-05-30 14:15:01 +08:00
gongzhiyong edf7aeaf8a feat: add agnet artifact content proxy 2026-05-30 12:55:04 +08:00
gongzhiyong 61e060909d fix: localize agnet detail copy 2026-05-28 19:15:41 +08:00
gongzhiyong 7d7c163f37 fix: localize agnet form field labels 2026-05-28 19:03:51 +08:00
gongzhiyong 53cc1a5e63 fix: localize agnet role and resource labels 2026-05-28 18:51:43 +08:00
gongzhiyong 587746db90 fix: localize agnet create run sheet 2026-05-28 18:43:08 +08:00
gongzhiyong 72cbf43dec fix: localize agnet drawer status text 2026-05-28 18:24:07 +08:00
gongzhiyong fd02edcd52 fix: localize simulated agnet status 2026-05-28 18:16:06 +08:00
gongzhiyong efaac446ab fix: localize agnet console copy 2026-05-28 18:08:18 +08:00
gongzhiyong 8075891770 feat: document and expose swarm runtime contract 2026-05-28 11:57:58 +08:00
gongzhiyong 10fc64e172 feat: complete sub task flow callbacks 2026-05-27 23:31:57 +08:00
gongzhiyong 4ccf7b1062 feat: complete swarm manager callback loop 2026-05-27 21:17:32 +08:00
gongzhiyong 8a6fea235e fix: restrict agnet simulation controls 2026-05-26 18:41:26 +08:00
gongzhiyong 2cc5e667df feat: complete manager agnet callback timeline 2026-05-26 18:38:24 +08:00
gongzhiyong 0abd761d66 feat: add manager sub deployment bridge 2026-05-26 18:23:23 +08:00
gongzhiyong d16b2ca1d5 fix: correct admin sidebar model links 2026-05-26 16:51:36 +08:00
gongzhiyong d02685dd5e fix: correct admin sidebar model links 2026-05-26 16:42:29 +08:00
gongzhiyong a80c3e0c35 feat: release manager 1.4.4 agnet persistence 2026-05-26 16:01:49 +08:00
gongzhiyong 1ebaa1ccce fix: move signup email hint below email field 2026-05-25 18:08:17 +08:00
gongzhiyong 07b307c094 fix: place signup email hint under email field 2026-05-25 17:57:09 +08:00
gongzhiyong e1b9de2a49 feat: add azure key vault resource discovery 2026-05-25 17:41:43 +08:00
chenchenandClaude Opus 4.7 da81c57db2 feat(cloud): Azure subscription binding via Service Principal (M2 phase 1)
Sprint 13. Lifts the resource-binding wizard's "Connect cloud account"
step from a disabled "Coming soon" button to a real binding flow,
scoped to Azure for now (AWS / GCP coming soon).

What ships:
  - New AzureCloudBindingSheet — Service Principal credentials form
    (subscription_id / tenant_id / client_id / client_secret + display
    name)
  - Creates a mcp-server ResourceBinding of type 'cloud_account' with
    provider=azure metadata, permission_scope=['azure:read'], status
    flips between 'active' (vault configured) and 'pending' (vault
    not yet wired)
  - Sheet shows a yellow warning when OpenBao isn't configured,
    explaining that client_secret will NOT be persisted server-side
    until vault is online — operators re-enter or rotate the secret
    once vault is up
  - Explicit "what Heicode will / will not do" footer card per
    product docs §13.9 — read-only ARM, never modify without desktop
    approval, never log client_secret
  - Cloud step "Connect" button now opens this sheet (was disabled)
  - Wizard summary description updated: AWS/GCP labelled coming soon
    instead of implying all three providers ship today

Phase 2 (Azure OAuth code flow) + phase 3 (ARM auto-discovery) need
Azure App Registration + OpenBao online first — separate sprints.

i18n localized en + zh.

Verification:
  - tsc --noEmit clean
  - no backend change — leverages existing mcp-server ResourceBinding
    endpoint which already supports cloud_account type

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 14:53:34 +08:00
chenchenandClaude Opus 4.7 cdcc864298 feat(states): unified QueryState wrapper covers permission + network errors
Sprint 11 — closes M13 ("七态完整性") on the three highest-traffic
pages (Deployments, Events, Audit). Earlier behaviour was binary
(loading skeleton OR card list); 401/403 and offline both fell
through to a toast or a blank page.

New /components/query-state.tsx:
  - One wrapper that takes isLoading + error + isEmpty + retry
  - classifyError reads axios + fetch shapes; maps to 'permission'
    / 'network' / 'generic'
  - Permission state: ShieldOff icon, no retry button (admins must
    grant access; retry would just 401 again)
  - Network state: WifiOff icon, retry wired
  - Generic state: AlertTriangle + retry + decoded error.message
  - Empty state: passthrough to existing EmptyState
  - Loading: passthrough to caller's loadingFallback or 3 skeleton rows

Applied to:
  - AgnetDeploymentsPage (replaces inline loading/empty ternary)
  - AgnetAuditPage (same)
  - AgnetEventsPage (wraps the events ol)

In all three, the existing useQuery now also surfaces error + refetch.
retry: false set so QueryState handles error display directly
instead of TanStack retrying 3 times silently.

i18n strings added for 5 new copy keys (permission denied, network
unreachable, retry, load failed) in en + zh.

Verification:
  - tsc --noEmit clean
  - no backend change

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 14:48:31 +08:00
chenchenandClaude Opus 4.7 d8f61957f0 feat(manager): version 1.4.2 — H2 sk- hash + M9 audit drawer + M3 docs + M7 vault
Bundled release bumping Manager to 1.4.2 with four product-doc gap
closures lined up in a single deploy.

VERSION:
  - 1.2.0 → 1.4.2 (catches up after Sprints 1-5 shipped under 1.2.0)

H2 — sk- hash phase A (server-side, zero client impact):
  - tokens table: new key_hash varchar(64) index column
  - Token.Insert() dual-writes Key + KeyHash on every new token
  - BackfillTokenKeyHash() runs at startup, batches 500 rows at a
    time, idempotent. Fills legacy rows that pre-date the column
    without blocking app boot
  - 5 unit tests pin: sha256 correctness, dual-write on Insert,
    empty Key → empty hash, backfill behaviour, idempotency
  - Phase B (switch lookup index off plaintext + drop Key column)
    can ship later once telemetry shows key_hash IS NULL count is 0

M9 — task detail drawer with audit timeline:
  - Deployments page click → Sheet drawer with RunDetailPanel +
    new RunAuditTimeline component
  - Timeline pulls from existing /api/agnet/deployments/:id/events
    which Sprint 1 already wired to the persistent
    agnet_audit_events table — no new backend
  - Vertical timeline w/ coloured dots (primary / amber / rose by
    classifyEventLevel), occurred_at + correlation_id per row,
    max-height + overflow for long traces
  - 15s polling; empty/loading/error states all rendered

M3 — project_doc as a first-class binding step:
  - Resource binding wizard split "SK or project docs" into two
    distinct steps: "Connect project docs" + "Connect SK skill packs"
  - Each step's Connect button pre-selects the matching type in
    the advanced sheet so users don't accidentally tag a doc repo
    as Git or SK
  - Summary dialog still receives the combined skOrDocSources view
    to keep the recommendation-card contract unchanged

M7 — secret vault status (admin panel):
  - controller/secret_store.go: new GetSecretStoreStatus handler
    + fetchHealth() method. Hits OpenBao /sys/health (token-less
    upstream endpoint), maps to a sanitized response — NEVER
    returns secret names or values per product docs §13.9
  - Graceful degradation: env vars unset → "not configured" pill;
    network error → "unreachable"; sealed → amber warning; healthy
    → green
  - Mounted at GET /api/secret-store/status behind middleware.AdminAuth
  - New SecretStoreSection in system-settings/maintenance,
    registered before Performance. Read-only card with refresh
    button, 7 status fields, message line, "how to enable" hint

Verification:
  - go vet ./... clean
  - go test ./controller/... ./middleware/... ./model/... all green
  - tsc --noEmit clean
  - Backend M7 endpoint deliberately tolerant — production may not
    have OPENBAO_ADDR set yet, UI shows "not configured" instead of
    500ing

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 11:19:42 +08:00
chenchenandClaude Opus 4.7 3fa345ff5e feat(privacy): per-session consent modal on first authenticated entry
Sprint 5. Pops a non-dismissable modal once per browser tab session
after the user lands on any /_authenticated/* route. Covers two
user-visible policy points the product team called out:

  1. Project data: Heicode does NOT guarantee against project loss.
     Users must back up to their own Git / local storage.
  2. Model privacy: when calling third-party models (OpenAI /
     Anthropic / Google etc.), each vendor's privacy, retention,
     and training-use terms apply. Heicode does NOT modify those
     terms and makes no privacy promises on the vendors' behalf.

Design:
  - Pure frontend, no schema migration, no backend endpoint. The
    "show every login" requirement is satisfied by sessionStorage
    (cleared when the tab closes); persisting acceptance server-
    side would force a forced-consent log we don't need yet.
  - Modal is intentionally non-dismissable (no overlay close, no
    Escape key, no X button). User must explicitly Agree or
    Decline.
  - Decline triggers auth.reset() + redirect to /sign-in — same
    logout path the sidebar uses.
  - Agree button stays disabled until the acknowledgement checkbox
    is ticked.
  - i18n localized en + zh.

If we later need an auditable consent trail (e.g. regulator asks
"prove user X clicked agree on date Y"), promote this to a DB-backed
flow with a users.accepted_privacy_at column and a POST endpoint.
Until then sessionStorage is the right scope.

Verification:
  - tsc --noEmit clean
  - mounted at AuthenticatedLayout — every authenticated route hits
    it; sign-in / sign-up / public pages do not
  - sessionStorage flag survives navigation within a tab, clears on
    tab close — matches "弹一次每次登录" requirement

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 20:38:58 +08:00
chenchenandClaude Opus 4.7 131639f672 feat(deploy): structured execution-confirm card replaces raw JSON dump
Sprint 4. Closes M6 from the product-doc gap analysis.

Previously the "Review" tab of the new-deployment sheet showed a
JSON.stringify of the full orchestration plan + a single checkbox.
Two problems:
  1. The raw JSON is nearly unreadable to non-engineering users
     (the typical operator of this surface).
  2. Product docs §10 "执行前确认卡" require five named sections,
     not a freeform payload dump:
       - 本次会做 (this run will do)
       - 本次允许使用 (resources this run may use)
       - 本次不会做 (this run will NOT do — static off-limits list)
       - 高危规则 (high-risk policy reminder)
       - 预计消耗 (token / cost / duration triple)

New layout puts each section in its own card pulled directly from
previewPlan so what the user confirms is byte-identical to what
gets submitted. The "本次不会做" card is static red-bordered text:
production deploys, prod DB writes, long-lived credential
extraction, any resource not listed.

The raw JSON is preserved behind a <details> disclosure so power
users debugging the payload still have access. Same checkbox
behaviour gates submit — no policy regression.

All strings localized en + zh.

Verification:
  - tsc --noEmit clean
  - data binds directly to previewPlan — no drift risk between
    preview and actual submit
  - no backend change

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 20:25:22 +08:00
chenchenandClaude Opus 4.7 4bab918808 feat(manifest): collapsible permission-manifest preview on run detail
Sprint 3. Closes M5 from the product-doc gap analysis — gives users
a safe, opt-in view of "which agents got which permissions over which
resources" without exposing plaintext credentials.

Per docs/product-package/10-frontend-detail-spec.md §"执行前确认卡"
and §13.9:
  - Default folded. Only a "Show manifest" button surfaces.
  - When expanded, shows the five policy-safe columns per resource
    grant: resource (type + id), allowed actions, constraints,
    secret_ref, status.
  - secret_ref is rendered via maskSecretRef() which keeps the
    vault path scheme + first 6 chars of the leaf and ellipsises
    the rest. The full plaintext value (if anyone ever puts one
    there by mistake) is NEVER rendered.
  - Constraints render as compact key=value chips, value truncated
    at 24 chars to keep the row scannable.
  - Status pill colors mirror the device-binding active/revoked
    palette established in May.
  - Footer note reminds the reader: "Plaintext credentials are
    never shown. The secret_ref column is a vault pointer, not
    the secret itself."

Existing "Permission manifest" stub card grew the new toggle in
place (no new card column added); the Events / Audit usage cards
stay on the same grid. M5 unblocks Sprint 4 (M6 execution-confirm
card) which depends on the same data layout.

Verification:
  - tsc --noEmit clean
  - go test ./controller/... ./middleware/... ./model/... all green
  - no backend change in this commit — pure frontend work over the
    existing AgnetDeployment payload shape
  - i18n additions for en + zh

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 17:55:51 +08:00
chenchenandClaude Opus 4.7 d022518a0a feat(agnet): canonical six-role catalog + role-templates API
Sprint 2. Materialises the six platform-recommended Agnet roles
documented in docs/product-package/13-platform-description.md §3.

Backend:
  - controller/agnet_role_template.go (new): AgnetRoleTemplate type
    + canonical catalog returned by GET /api/agnet/role-templates.
    Six roles: product / architect / frontend / backend / reviewer / ops.
    Stored as constants (not DB rows) because they are platform
    contracts, not user-editable data. Each entry carries:
      - stable key (frontend dispatches on this — never rename)
      - display name + summary (translatable)
      - default model recommendation
      - default permission scope hints
      - risk classification (low/medium/high) — Ops alone is high,
        matching the production-deploy-needs-approval rule
  - router/api-router.go: mount GET /api/agnet/role-templates inside
    the existing /api/agnet group (same auth as the other endpoints)
  - controller/agnet_role_template_test.go (new): 4 tests pin the
    six-role set, risk-level matrix, HTTP envelope shape, and the
    closed-set helper that will gate validation later

Frontend:
  - features/agnet-console/api.ts: new AgnetRoleTemplate type + a
    module-level cached listAgnetRoleTemplates() helper. Caching
    means the picker doesn't refetch every time the deployment sheet
    opens.
  - features/agnet-console/create-agnet-deployment-sheet.tsx:
    - Replace free-text role_template Input with a Select bound to
      the catalog; falls back to Input if the catalog is empty so
      the form stays usable when the endpoint is down.
    - Fix two informal role names in built-in presets (debugger →
      reviewer, executor → backend) so presets reference only
      canonical keys.

Verification:
  - go test ./controller/... ./middleware/... ./model/... all green
    (4 new role-template tests + existing suite)
  - frontend tsc --noEmit clean
  - zero touch on the token / device-signature hot paths

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 17:23:43 +08:00
chenchenandClaude Opus 4.7 8f70115c6a feat(audit): persist Agnet control-plane audit events to DB
Sprint 1 of the post-product-doc gap closure. Replaces the previous
in-process `agnetEvents map[string][]agnetEvent` (lost on every
container restart) with a real GORM table `agnet_audit_events`.

What changed:
  - model/agnet_audit.go (new): AgnetAuditEvent model + InsertAgnetAuditEvent
    / ListAgnetAuditEvents / ListAgnetAuditEventsByDeployment helpers.
    Indexes picked for the dashboard queries: user_id, deployment_id,
    binding_scope, occurred_at desc.
  - model/main.go: AutoMigrate &AgnetAuditEvent{} alongside the existing
    schema (SQLite/MySQL/PostgreSQL compatible per CLAUDE.md Rule 2).
  - controller/agnet_control_plane.go: drop agnetEvents map; the 3
    producer sites (deployment accepted / stop / sk_snapshot_refreshed)
    now call recordAgnetAuditEvent which writes to DB best-effort.
    The 3 reader sites (events list / logs / audit-logs) now query
    the table; AgnetListAuditLogs also supports limit/offset pagination.
  - controller/agnet_control_plane_test.go: reset helper no longer
    touches the deleted map.
  - model/agnet_audit_test.go (new): 4 tests covering persistence,
    nil-guard production safety, filter+paginate, chronological reads.

Sidebar UX:
  - "Preparation checklist" → "Resource binding"
    Per product-package doc README §统一表述 — user-facing term is
    "资源绑定" not "准备清单". URL /sk-sources kept to preserve
    bookmarks; can rename in a later pass with redirect.

Verification:
  - go test ./controller/... ./middleware/... ./model/... all green
  - go vet clean
  - frontend tsc --noEmit clean
  - audit writes are best-effort: errors log via SysLog but never
    fail the user API call; DB nil-guards in place

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 16:42:34 +08:00
chenchenandClaude Opus 4.7 407dbb7200 fix(http): trust private-range proxies so c.ClientIP returns real IP
Manager was created via gin.New() without calling SetTrustedProxies,
which in Gin v1.7+ defaults to trusting NOTHING — c.ClientIP() returned
the docker bridge peer (e.g. 10.2.3.4) instead of the real client IP
populated in X-Forwarded-For by the front reverse proxy.

Symptoms observed in production:
  - Devices page showed every user's "Last IP" as 10.2.3.4 / 10.2.3.5
  - tokens.device_last_seen_ip audit field useless for security review
  - Token IP allowlists effectively bypassed (always saw docker IP)
  - Rate-limit buckets keyed on docker IP — all users share a bucket

Fix: SetTrustedProxies with the standard RFC1918 + loopback ranges.
Covers every realistic Manager topology (docker compose, k8s ClusterIP,
reverse proxy on same VM). Cloudflare-direct topologies still need the
CF published ranges added; document that inline rather than auto-fetch
since we currently always front with Caddy/nginx.

UI cosmetic: When device_name is empty (pre-0.3.3 desktop clients
didn't always send it), Devices page now synthesises a label like
"Windows · 4f3a" from platform + last 4 chars of device_id instead
of the generic "Unnamed device", so users can tell their devices
apart at a glance.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 19:45:53 +08:00