Compare commits

..

67 Commits

Author SHA1 Message Date
Codex
ae4b21e245 docs(prompts): wait on a PID instead of a self-matching pgrep -f loop
A wait loop like `while pgrep -f "pytest evals"` matches its own shell
and runs until its timeout even after the job exits. Tell Claude and Codex
owners to save the job PID and wait with kill -0, or use a [p]attern that
cannot match itself, and to confirm the job finished afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:14:57 +09:00
Codex
0f0f698fb4 fix(paired): deliver escalation notices that were silently dropped
When a paired task escalated to the user after a reviewer final, the
"⚠️ 자동 해결 불가" mention was emitted after the turn had already
published its final and released its attempt. MessageTurnController
dropped it ("Discarding late agent output after terminal final") and the
ownership guard would have suppressed it anyway, so rooms looked stalled
right after the reviewer's reply (javis_bot 2026-11-11 14:11, 15:28).

- Mark host post-completion notices (escalation, reviewer-unavailable
  answer) and send them as a fresh message past both guards and the
  reviewer direct-terminal skip.
- Reviewer prompt: NEEDS_CONTEXT is only for questions the user must
  answer; ask the owner for evidence with DONE_WITH_CONCERNS.
- run_verification: load the helper and verifier from the EJClaw install
  instead of the repo under review (was "Module not found" outside
  EJClaw), and run the helper outside the repo so its .env is not read
  by EJClaw's config loader.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:45:50 +09:00
Codex
043e9e71c5 fix(discord): do not treat embed generation or removal as message edits
Link unfurls and "Remove Embeds" (SUPPRESS_EMBEDS) both fire MessageUpdate.
Only a real author edit sets a new edited_timestamp, so skip updates whose
editedAt is null or unchanged. The same-text check alone missed Remove Embeds
when the cached old text was stale; drop the `?? new Date()` fallback that
let timestamp-less updates through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:58:57 +09:00
Codex
5c5942ae21 feat(discord): process edited user messages like new messages
Discord edits were dropped: only MessageCreate was handled, and re-storing
the same message id keeps its old seq, so the seq-based loop never re-reads
it. Handle MessageUpdate for cached human messages whose text changed and
store the edit as a new message (`<id>:edit:<editedAt ms>`, new seq) with a
"[메시지 수정됨] 원문/수정" prefix. It then follows the normal new-message
path (batched if pending, preempts a running turn, new request afterwards).
Bot edits, embed/link-preview updates (same text), uncached/partial
messages, unregistered rooms and outbound-only bots are ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:42:55 +09:00
Codex
c6afd7ccb8 feat(ipc): merge consecutive send_message updates into one live message
Repeated send_message progress updates each posted a new Discord message,
so a long run left a stack of separate status posts. While the role's
previous send_message is still the newest message in the chat, append the
new text to it by editing it (rendered like a fresh send). A message from
anyone in between, a status verdict, an attachment, or the 2000-char limit
starts a new message; a failed edit falls back to sending a new one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:14:16 +09:00
Codex
b1dc38ce62 prompts: severity-tagged reviewer findings and bounded review rounds
- Reviewer: DONE_WITH_CONCERNS now means changes required (unresolved
  P0-P2); TASK_DONE means no unresolved P0-P2 (P3 may be appended).
  Drop "same concerns 2+ turns -> BLOCKED" (system already sends
  deadlocks to the arbiter).
- Reviewer: flag only change-introduced problems or unmet requested items
  with a concrete failing path; P0-P3 severity; "지적 없음" when clean.
- Reviewer: inspect git diff/show itself, treat owner summary as claims,
  per-requirement met / not met / cannot verify.
- Reviewer: first round reports everything; later rounds check fixes and
  regressions only; verify rebuttals in code; never approve to end a loop.
- Reviewer: review only, no file edits or commits (overrides platform
  "do file work directly"); trivial change still needs a diff read but a
  verification profile only when the change can affect its result.
- Arbiter: PROCEED when only P3 remains, REVISE on evidenced P0-P2.
- Owner: answer each finding with fixed / rebutted + code evidence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:24:40 +09:00
Codex
17458995a0 prompts: stop repeated verification and unrequested tests
Owner: run needed checks once after a change, do not rerun passed checks
without a new change/failure/concern, no verification subagents (the
reviewer is the independent step), no unrequested tests/files, clean up
temp scripts. Reviewer: one run per profile per snapshot, do not block on
extra tests when existing checks cover the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:57:49 +09:00
Codex
0984d6798c feat: shift usage windows to 07/12/17/22 KST with a 03-07 gap
Primer slots move from 08/13/18/23 to 07/12/17/22 and the daily alignment
hold from 04-08 to 03-07, so the Claude 5h windows run 07-12, 12-17, 17-22
and 22-03 as requested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:26:13 +09:00
Codex
dee8b245d3 fix(deregister-room): also purge paired_workspaces and paired_session_task pointers
Deregistering dc:1557601433237459024 left 40 paired_workspaces rows (keyed by
task_id, no chat_jid) and the folder's paired_session_task router_state keys
behind as orphans. Delete both alongside the room's paired tasks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:06:51 +09:00
Codex
b621687bdc fix: read Claude usage utilization as a percent, never a fraction
The status dashboard showed Claude 5h at 100% right after a reset. The
/api/oauth/usage payload at 2026-11-04 15:01 KST was five_hour=1 (1%),
seven_day=18, but toPct() treated any value <= 1 as a 0-1 fraction and
multiplied it by 100. A freshly reset window passes through 1% (and
often 1.0 exactly), so the dashboard read 100% every time that happened.
The earlier rollover fixes (91203d8, 97cc670) addressed stale values
around resets_at and never touched this conversion.

The same heuristic was in getCachedClaudeUsageLimitResetAt, so a 1%
window also counted as exhausted when picking a usage-limit resume time.

The API always returns 0-100 (cache history: 0, 1, 12, 18, 53, 99), so
both places now use the value as a percent. Tests that used fractional
fixtures (0.2/0.4/0.7) now use percents; new tests cover 1 -> 1%,
0.4 -> 0%, 100 -> 100%, and a 1% window not counted as exhausted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:07:32 +09:00
Codex
1bb23a60db fix: park rooms during a transient Claude auth outage instead of failing
ff76d04 told the room about a transient refresh failure but still failed
the execution (completeImmediately 'failed'), which bumps
owner_failure_count and can hand the task to the arbiter after two blips.

- reportClaudeAuthRecovering now parks the turn like the usage-limit
  pause: releaseForClaudeUsagePause (lease released, no failure count, no
  follow-up) plus markRunPausedForClaudeUsage (messages stay unconsumed).
  The room is told once per incident; later blips park silently.
- token-refresh fires setOnClaudeAuthRecovered once a rejected token is
  replaced (deferred so the new token is in memory first); index.ts
  re-queues every parked room so the same turn runs without user input.
- Real-DB test: two parked owner runs leave owner_failure_count/status/
  arbiter_requested_at unchanged (control: a failed run does count).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:02:48 +09:00
Codex
ff76d041d3 fix: tell transient Claude refresh failures apart from a lost login
A 401-rejected token whose refresh failed with 429/5xx/timeout was marked
re-login-required at once, closing tasks and asking for a needless re-login.

- refreshToken throws TokenRefreshError; only 400/401/invalid_grant is
  definitive. A forced refresh of a rejected token retries transient
  failures twice right away; the periodic loop then keeps retrying the
  known-rejected token every check, and only a failure lasting 30 min turns
  into re-login-required.
- While recovering, the room is told once per incident and the paired task
  is kept, so the normal retry path can resume it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 10:55:31 +09:00
Codex
3f2e364c73 fix: stop silent Claude 401 stalls and token-family revocations
- Refreshing the OAuth token revokes the old access token, and agents hold it
  in CLAUDE_CODE_OAUTH_TOKEN (Claude Code keeps env tokens on 401). Refresh
  early only while no run is active; keep the 1h hard deadline.
- forceRefreshToken (after a 401) now probes /api/oauth/profile: a revoked
  token keeps its expiresAt, so it was handed back unchanged forever. A
  rejected token is refreshed; if that fails, re-login is flagged at once and
  held until a different token appears.
- Classify "OAuth access token has been revoked" as auth-expired. When the
  login is gone, close the paired task and tell the room to re-login instead
  of looping owner/arbiter retries with suppressed output.
- Only suppress the CLI's own short 401 banner, not an answer quoting it
  (a sketchup-app TASK_DONE report was swallowed this way).
- Runner denies Bash commands that copy or write .credentials.json: a CLI test
  against a copied login refreshed the real token family on 2026-11-02 and
  logged out every room.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 10:45:21 +09:00
Codex
0ce79c8d0c fix: do not treat an approved reviewer STEP_DONE with progress as a deadlock
The reviewer prompt defines STEP_DONE as 'this step is acceptable, send the
task back to the owner without escalating to the arbiter', but once
round_trip_count reached ARBITER_DEADLOCK_THRESHOLD (2) every STEP_DONE
requested the arbiter, and with ARBITER_MAX_INTERVENTIONS=1 the next one
closed the task as escalated. Long multi-step requests (wargame room) were
stopping every 2-3 approved steps and needed a human 'continue'.

A reviewer STEP_DONE now counts as a deadlock only when the owner made no
committed change since the start of its latest turn (task.source_ref).
When it did, the task goes back to the owner and round_trip_count resets
so the deadlock counter measures rounds since the last approved step.
No-progress STEP_DONE loops and DONE_WITH_CONCERNS loops still go to the
arbiter as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:14:56 +09:00
Codex
720223eb10 fix: keep paired rooms moving when owner turn preparation fails
A wargame room stalled after its owner ran npm install in a bun project:
both bun.lock and package-lock.json existed, so every owner turn threw
'Ambiguous package manager' while provisioning the workspace. The queue
had already claimed the turn, nothing released the claim, and the 5s
backoff retry was skipped as 'already claimed elsewhere', so the room
sat idle until a human wrote again (and then failed the same way).

- Owner workspace provisioning and the review handoff no longer fail
  when the dependency install step throws; they log a warning and go on.
- If preparing a paired run throws, mark the claimed turn failed and
  release its execution lease so the retry can run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:10:00 +09:00
Codex
fdd98e9eb8 feat: keep typing during scheduled tasks and tell waiting users
A group-context scheduled task occupies the room queue, so a human message
sent meanwhile waited silently (up to the whole task run) with no typing
indicator; the room looked unresponsive.

- Scheduled tasks (not CI watchers) hold the room's typing indicator for
  their whole run (DiscordChannel.setTypingHold: typing stays on while any
  hold is active, independent of message-turn setTyping(false)).
- A human message that has to wait behind a running scheduled task gets a
  one-time notice per wait: "지금 예약 작업을 진행하고 있습니다. 이 작업을
  마친 뒤 바로 답변드리겠습니다." (GroupQueue.claimScheduledTaskWaitNotice,
  reset when the waiting messages run).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:12:00 +09:00
Codex
fdfdd384bf fix: mark untranslated fallbacks and drop English progress text
- When the Korean rewrite errors, the stream ends before it arrives, or a
  final must go out without a result event, append a Korean notice to the
  English text instead of sending it bare (content is kept: dropping a
  NEEDS_CONTEXT question would be worse than English).
- A still-English rewrite is sent unchanged: the nudge tells the model to
  repeat only when the user explicitly asked for English.
- Intermediate progress text cannot be rewritten mid-turn, so English
  progress (>= 20 Latin letters, Hangul < 10%) is dropped before it is
  flushed by tool_progress / tool results / the result event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 02:11:42 +09:00
Codex
98011e282b fix: rewrite English final answers in Korean before delivery
A sketchup-app turn spent on English login pages (Trimble/Edge) ended
with an English NEEDS_CONTEXT answer. The Korean rule was only a prompt
line, the answer went straight to the user (no reviewer gate), and it was
carried forward into the next task, so the next turn answered in English
too.

- Claude runner: when a final answer is mostly English (Hangul < 10% of
  Latin letters, >= 150 letters, code/links/boilerplate ignored), ask the
  same session once to rewrite it in Korean and emit only the rewrite.
  Falls back to the original on error or early stream end; disabled when
  AGENT_LANGUAGE is set to a non-Korean language.
- Let handleResultMessage settle the buffered final text instead of
  pre-flushing it as progress, so the English draft never surfaces.
- Platform prompt: explicit "Reply language" section; owner rule no longer
  says "unless the user wrote in another language".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 02:07:17 +09:00
Codex
e3308eb119 feat: give owner runs a headless chrome-devtools MCP
Adds chrome-devtools-mcp 1.11.0 to the Claude runner so the owner (or a
single-mode room) can open pages, click/fill, take screenshots and read
console/network errors. Reviewer, arbiter and read-only runtimes do not
get it. Chrome runs headless with an isolated temp profile under TMPDIR,
Google usage statistics and CrUX lookups are off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:25:04 +09:00
Codex
97cc670e34 fix: show a rolled-over usage window as unknown, not 0%
91203d8 rendered an expired window as 0% unconditionally. If the post-reset
refetch fails (network error, 429) the 0% stayed for as long as fetches
kept failing, the same stale-value bug in the other direction. An expired
window now renders as -1 (the empty "─────" unknown cell) until a fetch
succeeds and brings the new window's real value.

Tests: expired window -> -1 for Claude and Codex rows; refetch failing at
+1 min and +60 min stays unknown, then success shows 3%; 429 shows the
429 indicator; renderer draws -1 as the placeholder cell.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:10:51 +09:00
Codex
91203d84fc fix: dashboard usage no longer shows a rolled-over window's old value
At 23:00 on 2026-10-19 the Claude 5h window reset, but the dashboard kept
showing "99% reset" until 23:04:34 (real value 3%): the 5-minute fetch
throttle replayed the 22:59:04 snapshot. Codex rows were also formatted
once per 5-min poll, so their % and countdown froze between polls.

- A window whose resets_at has passed renders as 0% with no countdown.
- Claude usage fetch skips the throttle once when a cached window reset
  fell after the last attempt (429 cooldown still honoured).
- Codex rows are rebuilt from cached state at every render.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:06:16 +09:00
Codex
d1068f1627 fix: don't drop human messages that paste a bot status prefix
A user copy-pasted a bot progress message into joke-app; the invisible
U+2063 status prefix came along and getProcessableMessages dropped the
human message as a task-status control message, so it was never answered.
Only treat the prefix as control when the message is bot-authored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:56:33 +09:00
Codex
0d7e345d3d fix: check every scheduled Claude attempt for the usage limit
The alignment-hold check in runTask only looked at the first attempt's
streamed trigger. A limit that came back only as the final error (no
streamed output) or on the retry after an auth refresh extended nothing.
holdAlignmentAfterClaudeTaskLimit now runs inside runTaskAttempt for
every Claude attempt and reads the streamed trigger, the final error and
the attempt error (classifyClaudeTrigger), then calls the shared
holdUntilSlotAfterLimitReset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:09:03 +09:00
Codex
0a5436e4ad fix: alignment hold also covers scheduled-task limits and the primer
- A scheduled Claude task that hits the usage limit now extends the
  alignment hold to the next slot when the reset is off the grid, like a
  room turn (it called runAgentProcess directly and skipped that path).
- The Claude primer is skipped while a hold outlasts its slot (e.g. the
  08:00 primer during a realignment hold until 13:00). A hold ending at
  the slot itself does not count: the slot timer fired at 07:59:59.999
  for 08:00 on 2026-10-16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:04:44 +09:00
Codex
a2b9898c0b fix: keep usage resets on the slot grid when Claude hits 100%
Evidence (journal): 10/04 and 10/05 08:00 and 10/12 23:00 the primer
failed (exit 1) because the account was at 100% in an off-slot window
(resets 9am / 3am); the first request after that reset then opened the
next window off the slot too, and the drift carried on.

- Usage limit that resets off the slot grid (not ~04/08/13/18/23:00 KST):
  extend the alignment hold to the next window start (08/13/18/23), so
  nothing opens a window between the reset and the primer. The pause
  notice names both times. Rooms paused by the limit stay paused
  (silently, now alignment-only, @-mention bypass works) until the hold
  ends; an expired real limit no longer counts as a limit.
- A real limit takes precedence over the hold in the pre-run gate.
- Primer: when the current 5h window (cached usage) ends within 10 min
  after the slot, wait until 5 s after that reset before firing, so the
  primer is not counted in, or rejected by, the old window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 06:03:38 +09:00
Codex
f944f97e54 feat: usage-alignment hold (04-08 KST daily + one-off hold until a set time)
Bring back the dawn gap that keeps Claude's 5h windows on the primer
slots (08-13, 13-18, 18-23, 23-04): it was dropped by the 2026-06-08
upstream merge (1dd948a).

- usage-alignment-hold.ts: hold during 04:00-08:00 KST, or until the ISO
  time in router_state `usage_alignment_hold_until` (ignored once past,
  so only the daily gap remains). A one-off end inside the gap runs on to
  08:00.
- Claude turns during a hold pause through the existing usage-pause path
  (messages kept, room resumed at the hold end) with an alignment notice.
  The stored pause is marked alignmentOnly so it does not act as an
  account-wide usage limit.
- Due Claude scheduled tasks stay due until the hold ends (Codex and
  GitHub CI watchers are not held).
- Urgent bypass like the old gate: a human @-mention lets that room run
  until the hold ends.
- Tests stub the wall-clock hold in test/vitest-env.ts so the suite does
  not pause when run between 04 and 08 KST.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 05:54:39 +09:00
Codex
9dc5d9ea70 fix: stop the usage-limit loop (new banner, RESET misread, arbiter cap)
During the 2026-10-15 02:17-03:20 Claude session limit one task cycled
owner -> arbiter -> owner ~300 times:

- The CLI banner changed to "You've hit your session limit · resets
  3:20am"; only "hit your limit" was recognised, so the banner was a
  successful answer instead of a usage-limit pause. Match "hit your
  <0-2 words> limit".
- classifyArbiterVerdict matched the keyword anywhere in a line,
  case-insensitively, so "resets 3:20am" read as RESET. Require the
  upper-case keyword to lead the line as a whole word (the arbiter
  prompt already asks for that).
- The "reviewer failed repeatedly -> request arbiter" path did not pass
  arbiter_intervention_count, so ARBITER_MAX_INTERVENTIONS never applied
  there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 05:08:08 +09:00
Codex
aed7371cfa feat: pause room work on the Claude usage limit and resume after reset
Before, a Claude run that hit the account usage limit closed the open
paired task as claude_usage_limit, posted the reset time and consumed the
user's messages, so the work was lost and had to be re-requested.

Now the room is paused instead:
- The failed turn is released without touching the paired task (no
  failure count, no status change, no follow-up) and the queue keeps the
  human messages unconsumed, so the same turn can run again.
- The room is recorded in router_state `claude_usage_pause` with the reset
  time (error text, else cached usage API reset, else a 10 min retry). A
  banner time that just passed is read as "now", not tomorrow.
- While the limit lasts, paused rooms run nothing and any other room's
  Claude turn pauses that room without spawning a run (the limit is
  account-wide). A stop request still goes through and drops the room
  from the resume list.
- The scheduler tick clears the pause 1 min after the reset, posts a
  resume notice and re-queues the rooms; the pending turn or the kept
  messages then run again. The state survives restarts.

Safety refusals keep closing the task as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:14:56 +09:00
Codex
1167023a13 fix: cap inline prompt documents, raise Discord upload cap to 10 MiB
joke-app finalize failed with "Prompt is too long (~1.18M tokens)": the
runner inlined a 162-page, 8.3 MB PDF as a base64 document block for every
[Document: ...] reference, and the prompt referenced it twice.

The Claude runner now inlines a document at most once per prompt, only
PDFs up to 20 pages / 10 MiB (512 KiB when the page count is unknown) with
at most 40 PDF pages per prompt, and text documents up to 256 KiB. Larger
ones become a path note telling the agent to use the Read tool.

The same PDF was also rejected as an outbound attachment by our local 8 MiB
cap, although Discord's default per-file limit is now 10 MiB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:26:58 +09:00
Codex
f579b4f406 fix: treat Claude safeguards refusals as failures, reset the session
Claude Code returns "API Error: <model>'s safeguards flagged this message"
as a success-typed result. EJClaw delivered it as the owner's answer,
handed it to reviewer/arbiter, resumed the refused session (refused again)
and carried the banner forward into the next task.

Now it is a `safety-refusal` trigger: the raw banner is suppressed, the
Claude session is cleared, the paired task closes as
`claude_safety_refusal`, the room gets a short Korean notice, and refusal
banners are never carried forward. Global memory gains a rule not to read
thinking blocks from session transcripts (the reasoning_extraction trigger
of the 2026-10-12 incident).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:17:22 +09:00
Codex
e22feb0215 feat(attachments): allow Office documents as outbound attachments
Bots had to zip .pptx decks because the outbound allowlist only covered
images, audio/video, pdf, zip and plain-text files. Add docx/xlsx/pptx
(checked for the ZIP local-file-header signature) and legacy doc/xls/ppt
(checked for the OLE2 compound-file signature). The 8MB cap and the
allowed-directory rules are unchanged. Prompt format lists are updated so
agents stop zipping these files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:59:49 +09:00
Codex
23f9271d04 docs: remove resolved router_state incident report
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:03:16 +09:00
Codex
20f829a73a docs: update router_state incident report to the committed state
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 05:31:58 +09:00
Codex
11c179c565 fix: allow paired_session_task router_state keys and guard new keys at write time
Commit c858b6e started writing paired_session_task:<folder> keys into
router_state, but the startup check only allowed last_seq/last_agent_seq.
The first restart after those keys existed (2026-10-03 05:11) exited with
code 78 and crash-looped ejclaw.service for 11 minutes.

- Keep the allowed keys/prefixes in one list in src/db/router-state.ts and
  use it for both the startup check and setRouterStateInDatabase, so an
  unregistered key fails on its first write and in tests instead of at the
  next startup.
- paired-session-binding imports the prefix constant instead of redefining it.
- Regression tests: app-written keys survive a re-init; unregistered keys are
  rejected on write.
- Add the incident report (docs/fix-2026-10-03-router-state-startup.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 05:28:40 +09:00
Codex
2e285c5d78 docs: slim the shared global memory and move details to ops notes
The global memory was ~40KB (~11k tokens) and loaded into every agent call.
Keep only rules every room needs and move host, credential, EJClaw ops and
project notes to groups/global/ops/*.md, referenced on demand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:52:33 +09:00
Codex
50f149dd0f Merge branch 'slim/db' into slim/all 2026-10-01 20:52:21 +09:00
Codex
0283abbb56 feat: skip or slim down the owner finalize turn
(a) When the reviewer approves the owner's first TASK_DONE answer on the
first review (one review round, outputs are exactly owner -> reviewer, no
revision or arbiter turns) and the owner workspace still matches the
approved tree with a clean working tree, no owner run happens: the task is
completed as done and the reviewed answer (status line stripped) is posted
as the final message. If the review was requested with a bare "검토해줘"
after a review-skipped answer, a one-line confirmation is posted instead of
repeating the answer.

(b) Every other finalize turn runs in a fresh, non-persisted session (no
resume of the task's long working session, no room memory briefing) with a
self-contained prompt: this task's user messages, the latest six turn
outputs and the finalize instructions/format. All three finalize entry
points (pending turn, inline bot-only follow-up, queued turn) use it.

The owner prompt now states that the first TASK_DONE answer must already
follow the final-message format because it may be posted as the final
message unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:42:12 +09:00
Codex
7f54c47e64 feat: let the owner skip review for change-free explanation answers
The owner may end a TASK_DONE answer with "리뷰 불필요: <reason>". The
host treats it as a request and honors it only when every guard holds:

- workspace content equals the task base (hasCodeChangesSinceRef), the
  working tree is clean, and HEAD did not move during the owner run
- the run used no file-mutating tool (Edit/Write/MultiEdit/NotebookEdit),
  no subagent (Agent/Task) and no state-changing or unknown MCP tool
- every Bash command is classified read-only by a conservative
  quote-aware classifier (src/bash-command-classifier.ts); anything
  unknown counts as mutating
- tool usage was reported and not truncated (agent-runner now reports
  tool names and Bash commands as toolUsage on its terminal output)
- the user did not ask for a review in this task

When honored the task completes as review_skipped with no reviewer or
finalize turn; the answer is delivered with the marker line removed and a
small "-# 검토 생략 …" note. Otherwise the marker is stripped and the
normal review runs. A bare "검토해줘"-style message right after a
review-skipped answer reopens that task for the reviewer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:36:53 +09:00
Codex
0dc0dad22a refactor: squash DB migrations 1-22 into a single baseline schema
base-schema.ts now holds the full schema at version 22, taken from the
production database (column order, indexes, provenance triggers), so a
fresh database is identical to the live one. Previously a fresh DB
differed: it had an extra idx_messages_chat_timestamp index and a
different column order in paired_tasks and paired_turn_outputs.

The migration runner keeps schema_migrations:
- empty DB: apply the baseline and record version 22 ('baseline')
- existing DB: must already be at version >= 22 (the live DB records
  1-22), otherwise startup refuses it without touching it
- later migrations (23+) run once each inside a transaction

Removed the 22 historical migrations, the legacy schema bundle, the
paired-turn provenance rebuild/backfill helpers that migration 10 replayed
on every start (all no-ops on the live DB), legacy session migration
helpers, the unused service handoff metadata helpers, and the tests that
only exercised legacy-schema upgrades. New schema tests check a fresh DB
against a snapshot dumped from production and that reopening a DB at the
baseline changes neither schema nor data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:26:15 +09:00
Codex
c858b6e446 feat: scope paired owner/reviewer sessions to one paired task
Each paired room used to resume one owner (and one reviewer) session for
weeks, so every call re-read a huge unrelated history (median ~260k input
tokens). A stored session is now resumed only while it belongs to the
running paired task; the first turn of a new task starts fresh and the new
session is bound to that task (router_state paired_session_task:<folder>,
survives restarts). Later turns of the same task (revisions, follow-up
human messages while the task is open) keep resuming it. Arbiter was
already fresh per call; single rooms are unchanged.

The previous task's final answer still reaches the new session through the
carried-forward turn-0 output, so PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL
now defaults to true.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:25:35 +09:00
Codex
8c68577a24 refactor: replace the Claude→Codex failover with a usage-limit notice
When Claude hit a limit the run was handed to a Codex service
(codex-main/codex-review) through service_handoffs and a global owner
failover. That service does not exist in this deployment, so handoffs
stayed pending forever (2 rows since May) and the user got no answer.

Removed:
- handoff creation (message-agent-executor-handoff, paired-turn-fallback)
  and the delegated paired-execution path
- the pending-handoff poll/claim worker (message-runtime-handoffs) and the
  service_handoffs CRUD module (db/service-handoffs, db exports)
- global owner failover in service-routing, its recovery timer in index,
  the dashboard failover line, the codex-review failover prompt pack and
  prompts/codex-review-failover-platform.md
- failoverOwner in RoomRoleContext and the `failover=` ROOM_ROLE field
- OWNER_/REVIEWER_/ARBITER_FALLBACK_ENABLED and FAILOVER_MIN_DURATION_MS
- tests for the removed behaviour

Now, when a Claude run fails with a usage/rate limit (trigger reason
429 or usage-exhausted) the executor closes the open paired task as
completed/claude_usage_limit and sends the room one final notice:
"Claude 사용 한도에 도달했습니다. 21:40에 재개할 수 있습니다." The reset time
comes from the error text (CLI banner "resets 9:40pm (Asia/Seoul)", dated
banners, "try again at ...", ISO timestamps), else from the cached usage
API window at 100%, else "잠시 후 다시 시도해 주세요". Nothing retries
silently; the next user message starts a new task. Other Claude failures
(session failure, org access denied) now end as ordinary run errors.

The service_handoffs table, its columns on paired_turn_attempts and the
migrations stay untouched for the later migration squash; the runtime no
longer reads or writes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:14:48 +09:00
Codex
a9eab5cb94 refactor: run Claude and Codex on one fixed account each
The deployment has a single Claude OAuth credential and a single Codex
ChatGPT account, so the N-account rotation machinery only added state
files, cooldown bookkeeping and code paths that never ran.

Removed:
- Claude token rotation (token-rotation.ts, token-rotation-base.ts):
  rotate-on-limit, per-token cooldowns, token-rotation-state.json.
  CLAUDE_CODE_OAUTH_TOKENS is still read, but only its first entry.
- Codex account rotation (codex-token-rotation.ts): account pool,
  rotate-on-429/auth, dead-auth/cooldown tracking, round-robin advance,
  d7 auto-rotate, codex-rotation-state.json, manual account switch.
- Account index plumbing in token-refresh, claude-credentials-path
  (CLAUDE_ACCOUNTS_DIR / ~/.claude-accounts/<n>), Claude/Codex usage
  collectors, the dashboard rows and the Codex warm-up.
- provider-retry.ts rotation loops and the Codex retry path.

Kept:
- Codex exclusive auth lease (one Codex run at a time), the 15-minute
  waitForCodexAuthLease, and a usage-poll lease that skips while a run
  holds the account (codex-auth.ts).
- Session auth copy and write-back of refreshed tokens
  (syncCodexSessionAuthBack, syncClaudeSessionAuthBack).
- Codex auth path: ~/.codex-accounts/0/auth.json, else ~/.codex/auth.json
  (now resolved per run, so a re-login needs no restart).
- Claude token refresh loop, CLAUDE_CREDENTIALS_PATH and the
  CLAUDE_TOKEN_REFRESH_* / CLAUDE_USAGE_USE_HOME_CREDENTIALS flags; an
  auth-expired run still force-refreshes the token and retries once.
- Error classification (classifyClaudeTrigger, classifyCodexTrigger).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:14:38 +09:00
Codex
f127ac7a2b refactor: remove the main room concept
No room has room_settings.is_main = 1, so every main-only path was dead,
and admin work is done from the host shell. Each room's agent may now
only act on its own room:

- IPC: messages/inbound injection only to the source room; schedule,
  update, pause, resume and cancel only for the source room's tasks;
  drop the assign_room and refresh_groups IPC tasks and the deps they
  needed (assignRoom/syncGroups/getAvailableGroups/writeGroupsSnapshot)
- DB/host evidence is always scoped to the source group folder
- runner MCP server: drop the assign_room tool, the target_group_jid
  parameters and the isMain flag; list_tasks shows only the room's tasks
- drop EJCLAW_IS_MAIN, RunnerInput.isMain and AgentInput.isMain; the
  global CLAUDE.md memory is now included for every room
- drop the available_groups.json snapshot (available-groups.ts), the
  inferred restart announcement that only went to the main room, and
  the unused Channel.syncGroups hook
- setup register: drop --is-main; deregister-room: drop the main-room
  refusal and --force, and fix its unknown[] binding type error
- remove the groups/main/ template

The room_settings.is_main column and migrations are untouched; new rows
get the column default (0) and nothing reads it anymore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:37:29 +09:00
Codex
ce4547daa6 feat: replace session commands with a natural-language stop
Remove the /compact, /clear and /stop session commands. They were gated
to the main room or SESSION_COMMAND_ALLOWED_SENDERS, neither of which
exists in this deployment, so nobody could use them. The agent-runner
/compact passthrough goes with them.

Instead, a short human message whose whole intent is "stop" (그만, 멈춰,
중단해, 하지 마, 취소, stop, cancel, ...; see src/stop-intent.ts) stops the
room when it has something to stop: a running or queued run, an open
paired task, or unprocessed human messages before it. The message loop
then
- advances the room cursors past the stop message (memory + router_state)
- completes the open paired task as user_stopped, cancels its open turns
  and drops its execution lease
- closes stdin with a user-stop reason and kills the agent through the
  existing GroupQueue.closeStdin/killProcess
- replies "진행 중이던 작업을 중단했습니다." once
When nothing is running the message is handled as a normal message.

The user-stop close reason is treated like a human interruption, so the
killed paired turn releases its lease without counting a failure and
queues no follow-up, and the turn controller does not post the generic
failure text on top of the stop reply.

advanceLastAgentCursor no longer moves a cursor backwards, so a run that
finishes after the stop cannot rewind the cursor and re-dispatch the
stop message (the respawn seen when an agent was only killed).

Stale SESSION_COMMAND_* keys in .env are now ignored instead of failing
startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:26:10 +09:00
Codex
fe7c5a7b23 refactor: remove the disabled periodic Codex warm-up loop
CODEX_WARMUP_ENABLED defaulted to false and was never set, so the
warm-up loop in unified-dashboard never ran. Remove the loop, the
`enabled` / `intervalMs` config keys, the `disabled` result and the
`shouldSkip` hook it alone used. The fixed-slot usage primer keeps
calling runCodexWarmupCycle with forceAttempt exactly as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:10:19 +09:00
Codex
12b262eaa9 chore: drop root yaml, zod and @modelcontextprotocol/sdk dependencies
Nothing in src/, setup/, scripts/ or test/ imports them; only
runners/agent-runner uses zod and the MCP SDK, and it declares both in
its own package.json. bun.lock regenerated with --lockfile-only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:10:19 +09:00
Codex
e999ce9a33 refactor: drop macOS launchd and nohup service install paths
The service only runs under Linux systemd. Remove setupLaunchd,
setupNohupFallback, buildLaunchdPlist, the launchd/nohup service checks
in setup/verify-services.ts, ServiceDef.launchdLabel, launchd/ and the
unused repo-tokens/ GitHub action. Without systemd, `setup --step
service` now fails with systemd_unavailable instead of writing a nohup
wrapper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:10:19 +09:00
Codex
a9fe9dac54 refactor: remove dead exports and orphan modules
Delete exported symbols that nothing in src/, setup/, scripts/ or
runners/ references (and no test exercises), iterated to a fixed point:
service-routing lease/failover helpers, paired-workspace-manager
fingerprint/registration helpers, message-runtime-rules trigger helpers,
utils.fetchWithTimeout, detectPnpmStorePath, isCodexMainService,
isDeltaHandoffEnabledForGroup with the unused DELTA_HANDOFF config, the
deprecated db/schema.applySchemaMigrations alias, unused db wrappers
(memories, router state, sessions-by-agent-type, room skill override
writes, recent chat/turn-output queries) and a few unused type aliases.

Orphan files: src/dashboard.ts + src/dashboard-status-content.ts (only
referenced each other), src/restart-context-cli.ts (never invoked) and
the unused src/config/index.ts barrel.

Service-handoff / channel-owner-lease code is left for a later batch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:10:19 +09:00
Codex
02ea212be0 refactor: remove unwired auto-paired-mode and usage exhaustion gate
src/auto-paired-mode.ts had no production importer. Remove it together
with the helpers only it used: getClaudeUsageExhaustion /
isClaudeUsageExhausted in claude-usage.ts and getCodexUsageExhaustion /
isCodexUsageExhausted in codex-usage-collector.ts, plus their tests.

auto-paired-mode-state.json stays in the data-state allowlist: the live
data dir still has that file and an unknown state file is a startup
precondition failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:10:19 +09:00
Codex
60ff19177a refactor: remove Mixture of Agents and Kimi usage
MOA_* was never configured, so enrichArbiterPromptWithMoa always
returned the prompt unchanged and the Kimi usage fetch only produced an
empty dashboard row. Remove src/moa.ts, src/kimi-usage.ts, the arbiter
prompt enrichment, MoA config/schema, the Kimi row and MoA line in the
Discord status dashboard, and the MOA_* / unused FALLBACK_* provider
examples from the docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:10:19 +09:00
Codex
1c0fbaf26a refactor: remove web dashboard, Android app and Glasses UI
WEB_DASHBOARD_ENABLED defaulted to false and was never set, so nothing
served the dashboard. Remove the server/routes, apps/dashboard,
apps/android, the dashboard-only settings modules (settings-store,
settings-store-moa, room-skill-settings, runtime-inventory,
codex-live-status, settings-effort), WEB_DASHBOARD_* config, the
web-dashboard-only startup mode, dashboard/android scripts and the
react/vite/playwright dependencies.

The Codex account refresh loop in settings-store is dropped with it: it
refreshed account index 0 through the shared ~/.codex/auth.json instead
of the isolated ~/.codex-accounts/0 used by the reviewer.

Host evidence loses the dashboard_dist / android_debug_apk artifact
kinds. The Discord status dashboard is unchanged. Room skill overrides
are still read from the DB by agent-runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:47:55 +09:00
Codex
f1abe037e9 perf: cut background polling and log noise
- Codex usage poll: run the repo-pinned CLI (0.159.3) instead of a global
  0.128 install, hold the account lease while polling (skip if a run holds
  it, so the poller cannot rotate a token under a live reviewer session), and
  poll every 5 min instead of every minute (~1,440 app-server spawns a day).
- Claude usage poll: 5 min instead of 1 min. The 1-minute cadence only served
  the auto-paired-mode gate, which is not wired into the runtime; it drew ~32
  HTTP 429s a day.
- Dashboard duplicate cleanup: was a 2 s poll fetching 100 messages (~43k
  Discord REST calls a day) plus a fetch after every edit. Clean up only when a
  fresh status message is posted or on first render, with a 5 min sweep.
- Logging: one line per event and no ANSI colors outside a TTY (events were
  split into ~11 journal lines). Progress-edit audits, Discord progress edits,
  streamed-activity and per-bucket Codex usage logs move to debug; sends,
  agent output and the usage summary stay at info.
- Two tests wrote under the real data/ipc and left fake room folders that the
  live 1 s IPC watcher kept polling; they now clean up after themselves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:32:14 +09:00
Codex
de2de33c3e fix: send NEEDS_CONTEXT straight to the user instead of the arbiter
A NEEDS_CONTEXT from the owner or reviewer is a question only the user can
answer, and the arbiter's own rules say to ESCALATE it. Routing it through the
arbiter added a full turn first (13 of 23 arbiter calls in 30 days). Escalate
directly; BLOCKED and deadlocks still go to the arbiter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:32:08 +09:00
Codex
3fcb4efa43 fix: give the reviewer and arbiter their own paired-room rules
Codex sessions always received owner-common-paired-room.md ("You are the
owner", branch rules) whatever the role, so the Codex reviewer never saw the
reviewer rules and answered with PROCEED/REVISE (26x/8x in 30 days).

The Claude arbiter runs with CLAUDE_CONFIG_DIR pointed at a directory that is
wiped before every run, and its CLAUDE.md was only written on the unsafe-host
path. In normal mode it ran with no rules at all, so 20 of 23 arbiter verdicts
in 30 days were free-form text the verdict parser could not read.

Pick the paired-room prompt by role (owner / reviewer / arbiter) for Codex
AGENTS.md, and write the role CLAUDE.md into the reviewer/arbiter config dir
in normal mode as well. The readonly-session builder now shares that code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:32:02 +09:00
Codex
3a05c5c754 docs: retitle decided section in slimming plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:35:25 +09:00
Codex
d0a8dbcb5b docs: finalize slimming plan decisions (owner-declared review skip, finalize C, drop main room)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:35:13 +09:00
Codex
a04cd92e88 docs: revise slimming plan with user decisions
Mark confirmed items (prompt bugs, failover removal, web dashboard /
android / glasses deletion, rotation simplification, natural-language
stop replacing session commands, launcher old-installer cleanup), drop
the single-mode conversion, and explain the three remaining decisions
(review skip, finalize-turn alternatives, main room role) in plain terms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:14:15 +09:00
Codex
a83d4e1fb6 docs: add EJClaw slimming and optimization plan
Evidence-backed audit (code, runtime, token usage) with 36 numbered
candidates, priorities, risks and open decisions. Includes two prompt
wiring bugs (arbiter gets no rules in normal mode, Codex reviewer gets
owner rules) and the dead codex-main failover handoff path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:41:10 +09:00
Codex
af28bae365 docs(memory): per-account model tests must pass CLAUDE_CODE_OAUTH_TOKEN
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:51:06 +09:00
Codex
4a419846f3 docs(memory): GPU module reload, KAclaw Opus 5.5 + expired OAuth, git credential helper
- GPU: driver/library mismatch can be fixed by reloading the nvidia modules
  (procedure + what to stop), done 2026-10-01 without a reboot
- KAclaw: now claude-opus-5-5 on SDK 0.3.286, backup location, the expired
  refresh token and the re-login runbook; note that the Claude CLI ignores
  CLAUDE_CREDENTIALS_PATH so per-account tests need CLAUDE_CODE_OAUTH_TOKEN
- git.tkrmagid.kr remotes no longer carry the token; document the
  secrets.json-backed credential helper

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:50:51 +09:00
Codex
e4828896f6 docs: sync memory, docs and skills with the current runtime
Global memory (groups/global/CLAUDE.md):
- add a model/runtime section: current versions (Opus 5.5, SDK 0.3.286,
  Codex 0.159.3), the model upgrade checklist, the stale nested
  node_modules and single-Codex-account gotchas, and the 09-19..10-01 fixes
- fix the garbled credentials paragraph and list every stored credential key
- correct the reviewer description (reviewer is codex, arbiter claude-code)
- the tmpfs/RAM watchdog it described no longer existed; point to the
  restored /home/claude/tmpfs-ram-watchdog.sh
- refresh stale host facts (tmpfs/disk sizes, nvidia-smi version-mismatch
  after driver auto-updates means "reboot pending", not "GPU broken")
- include the Windows CI runner section written on 2026-09-23 that was
  already live but never committed

Docs and skills:
- README / configuration.md / .env.example: current SDK and model
  versions, per-room reviewer/arbiter override, real attachment types,
  existing OpenAI Whisper fallback, src-based service and detached restart
- architecture.md: registered_groups is gone; RestartPreventExitStatus only
  applies to setup-rendered units
- setup/debug/customize skills: canonical DISCORD_*_BOT_TOKEN keys (the old
  alias now aborts startup), Bun instead of Node, Codex OAuth login instead
  of OPENAI_API_KEY, drop ignored register flags, journald instead of
  logs/*.log, room_settings query instead of registered_groups, bun run test
- CONTRIBUTING: drop the reference to the nonexistent /add-telegram skill
- legacy-compat-removal-spec: mark as implemented/historical
- CHANGELOG: add an Unreleased section for the recent fixes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:35:53 +09:00
Codex
a7f2e02699 chore: upgrade @openai/codex 0.133.0 -> 0.159.3
The reviewer's Codex app-server logged "failed to refresh available models:
failed to decode models response: unknown variant `max`" on every run: the
server now advertises a `max` reasoning effort the old CLI cannot parse. Each
failure also dumped the whole models payload (instruction templates included)
into the service journal.

The pin was misleading: codex-runner actually resolved an untracked stale
runners/codex-runner/node_modules/@openai/codex 0.124.0 from 2026-04-26 that
shadowed the root workspace copy, so earlier version bumps never reached the
runner. That nested copy (not in bun.lock, gitignored) was removed on the host
so the runner resolves the lockfile-managed root install.

End-to-end check through the real CodexAppServerClient with the reviewer's
account: thread start, turn, goal set/get, close and thread resume with context
retained all succeed, with 0 app-server errors (was 2 per run) and a simple
turn taking 5s instead of 49s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:25:36 +09:00
Codex
30ba51016a fix: wait for a busy Codex lease instead of skipping the review
The Codex auth lease is exclusive per account so two Codex processes never
rotate the same refresh token at once. With the single configured account that
also serializes every Codex run, and claimCodexAuthLease() failed immediately
while another room's Codex run held it: the turn errored with "Codex rotation
pool unavailable", the task closed as reviewer_codex_unavailable and the
review was silently skipped.

All three such failures on 2026-09-28 coincided exactly with another room's
Codex run holding the lease (10:25:55, 18:08:25, 18:22:50 KST).

runAgentProcess now waits (up to 15 min, polling every 2s) when the only
obstacle is a lease held by a live run. A dead or rate-limited pool still
fails fast, and the normal path adds no async hop because the wait is only
entered when the lease is actually busy. The exclusivity itself is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:25:36 +09:00
Codex
8b688853cc chore: upgrade claude-agent-sdk 0.3.153 -> 0.3.286 for Opus 5.5
Claude Opus 5.5 (claude-opus-5-5) is rejected by the bundled Claude Code CLI
2.1.153 with "does not support this model; version 2.1.280 or newer is
required". Bumping the SDK brings the bundled CLI to 2.1.286.

Verified end-to-end against EJClaw's own credentials through the real SDK and
binary: claude-opus-5-5 returned a normal completion after the upgrade (it
errored with the 400 before), and claude-opus-5 still works.

The model switch itself lives in .env (untracked): CLAUDE_MODEL=claude-opus-5-5.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-10-01 14:09:41 +09:00
Codex
69ae3342db fix: stop the progress ticker when a run loses its paired turn attempt
syncTrackedProgressMessage() logged "no longer owns the active paired turn
attempt" and returned, but left the 5s progress ticker running. Losing the
attempt is permanent — ownership only flips back to 'active' when a new
attempt claims the turn under its own runId — so a superseded run kept waking
every 5s for the entire life of the following turn (165 wakeups observed in
one room) while editing nothing. The channel's progress message stayed frozen
for the whole next turn, so a room that was actively working looked hung.

Clear the ticker on ownership loss, matching the repeated edit-failure path.

The regression test asserts on the ownership probe rather than editMessage:
a leaked ticker and a stopped one both produce zero edits, so counting edits
cannot distinguish them.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-09-28 10:41:36 +09:00
Codex
c7a8a4339c fix: let tribunal rooms self-heal a missing work_dir instead of going silent
preparePairedExecutionContext bailed out early when group.workDir was null,
which made the ensurePairedProject() self-heal directly below it unreachable.
A tribunal room registered without work_dir therefore produced no paired
execution context at all: the turn output was never persisted, the task
revision stayed frozen and the 10-minute execution lease was never released,
so every follow-up human message inside that window was silently dropped and
the room appeared to stop answering.

Single-mode rooms still bail out via ensureActiveTask returning null.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-09-19 20:35:09 +09:00
Codex
4485a7fd72 Cap owner/reviewer pending prompts to recent turn outputs
The owner and reviewer each resume a persistent session that already
holds the running paired thread, yet buildOwnerPendingPrompt /
buildReviewerPendingPrompt re-sent the ENTIRE accumulated turnOutputs
list every turn, so the prompt grew linearly with round-trips for no
benefit. Only the arbiter path was capped.

Reuse the arbiter's latestTurnOutputMessagesWithOmissionMarker cap
(now a shared TURN_OUTPUT_CONTEXT_LIMIT = 6) so owner/reviewer prompts
send at most the 6 most recent outputs plus an omission marker. On a
long ping-pong task this bounds per-turn prompt size instead of
re-sending every prior round's output. Behavior for tasks with <=6
outputs is unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-09-01 17:12:44 +09:00
442 changed files with 15054 additions and 55063 deletions

View File

@@ -17,8 +17,8 @@ description: Customize Discord-only EJClaw behavior, routing, integrations, prom
## 자주 보는 수정 지점
- `src/channels/discord.ts` - 디스코드 메시지 파싱, 멘션 규칙, 첨부파일 처리, 음성 전사
- `src/index.ts` - 오케스트레이션, 세션 명령, 라우팅, 상태 갱신
- `src/session-commands.ts` - `/compact`, `/clear` 같은 세션 명령
- `src/index.ts` - 오케스트레이션, 라우팅, 상태 갱신
- `src/stop-intent.ts`, `src/room-stop.ts` - "그만"/"stop" 같은 자연어 작업 중단
- `src/db.ts` - 등록 그룹, 세션, 스케줄, 마이그레이션
- `src/config.ts` - 서비스 식별값, 디렉터리, 타임아웃, 기능 플래그
- `src/agent-runner.ts` - 에이전트 실행과 환경 변수 전달
@@ -32,7 +32,7 @@ description: Customize Discord-only EJClaw behavior, routing, integrations, prom
### 동작을 바꾸고 싶을 때
- 응답 조건, 멘션 처리, 첨부파일 처리: `src/channels/discord.ts`
- 세션 명령, 상태머신, 런루프: `src/index.ts`, `src/session-commands.ts`
- 작업 중단, 상태머신, 런루프: `src/index.ts`, `src/message-runtime-dispatch.ts`, `src/room-stop.ts`
- 페르소나/응답 스타일: `groups/global/CLAUDE.md`
### 도구나 MCP를 붙일 때
@@ -43,8 +43,7 @@ description: Customize Discord-only EJClaw behavior, routing, integrations, prom
### 새 명령을 만들 때
- 먼저 슬래시 명령인지, 자연어 규칙인지 구분합니다.
- 슬래시/예약 명령이면 `src/session-commands.ts`와 `src/index.ts` 경로를 봅니다.
- 슬래시 세션 명령은 없습니다. 런타임이 직접 처리해야 하는 짧은 자연어 명령이면 `src/room-stop.ts`처럼 메시지 루프(`src/message-runtime-dispatch.ts`)에서 가로챕니다.
- 자연어 지시만으로 충분하면 프롬프트 문서만 수정합니다.
### 등록/배포 흐름을 바꿀 때
@@ -59,7 +58,7 @@ description: Customize Discord-only EJClaw behavior, routing, integrations, prom
```bash
bun run typecheck
bun test
bun run test
```
러너나 실행 경로를 건드렸으면 추가로 확인합니다.

View File

@@ -12,7 +12,7 @@ description: Debug EJClaw runtime issues on the current Discord-only, host-proce
1. 타입과 테스트부터 확인
```bash
bun run typecheck
bun test
bun run test
```
2. 서비스 상태 확인
```bash
@@ -20,8 +20,7 @@ description: Debug EJClaw runtime issues on the current Discord-only, host-proce
```
3. 런타임 로그 확인
```bash
tail -f logs/ejclaw.log
tail -f logs/ejclaw.error.log
journalctl --user -u ejclaw -f
ls -t groups/*/logs/agent-*.log | head
```
4. 러너 빌드 확인
@@ -45,12 +44,12 @@ description: Debug EJClaw runtime issues on the current Discord-only, host-proce
### 봇이 아예 말이 없음
```bash
grep -n '^DISCORD_BOT_TOKEN=' .env
grep -nE '^DISCORD_(OWNER|REVIEWER|ARBITER)_BOT_TOKEN=' .env
bun run setup -- --step verify
```
- `DISCORD_BOT_TOKEN`이 없으면 채널이 안 붙습니다.
- `REGISTERED_GROUPS=0`이면 채널 등록이 안 된 상태입니다.
- `DISCORD_OWNER_BOT_TOKEN` / `DISCORD_REVIEWER_BOT_TOKEN` / `DISCORD_ARBITER_BOT_TOKEN`이 없으면 채널이 안 붙습니다. 구 이름(`DISCORD_BOT_TOKEN` 등)이 남아 있으면 시작 시 오류로 종료됩니다.
- `ASSIGNED_ROOMS=0`이면 채널 등록이 안 된 상태입니다.
- 메인 채널이 아니면 디스코드 멘션이나 트리거 조건을 먼저 확인합니다.
### 에이전트가 실행 직후 죽음
@@ -61,14 +60,14 @@ ls -t groups/*/logs/agent-*.log | head -3
```
- Claude 계열은 `CLAUDE_CODE_OAUTH_TOKEN` 또는 `ANTHROPIC_API_KEY`가 필요합니다.
- Codex 계열은 `OPENAI_API_KEY` 또는 `CODEX_OPENAI_API_KEY`가 필요합니다.
- Codex는 API 키가 아니라 OAuth 인증 파일(`~/.codex-accounts/0/auth.json`)을 씁니다. 만료됐으면 `CODEX_HOME=$HOME/.codex-accounts/0 ./node_modules/.bin/codex login --device-auth`로 다시 로그인합니다. 실패 원인은 `paired_turn_attempts.last_error`에서 확인합니다.
- 러너 로그에 인증 실패나 CLI 실행 오류가 바로 찍힙니다.
### 음성 전사가 안 됨
```bash
grep -nE '^(GROQ_API_KEY|OPENAI_API_KEY)=' .env
tail -f logs/ejclaw.log | grep -iE 'transcri|audio|whisper|groq'
journalctl --user -u ejclaw -f | grep -iE 'transcri|audio|whisper|groq'
```
- 기본 우선순위는 Groq Whisper, 없으면 OpenAI Whisper fallback입니다.
@@ -77,12 +76,12 @@ tail -f logs/ejclaw.log | grep -iE 'transcri|audio|whisper|groq'
### 등록은 되어 있는데 응답이 이상함
```bash
sqlite3 store/messages.db "select jid, folder, requires_trigger, is_main, agent_type from registered_groups;"
bun -e "import {Database} from 'bun:sqlite'; const db=new Database('store/messages.db',{readonly:true}); console.table(db.query('select chat_jid, folder, room_mode, requires_trigger, owner_agent_type, work_dir from room_settings').all())"
```
- `jid`는 `dc:<channel_id>` 형식이어야 합니다.
- `folder`는 `discord_main` 또는 `discord_<name>` 형태를 유지합니다.
- 세션 명령 문제면 `src/session-commands.ts`와 `src/index.ts` 호출부를 같이 봅니다.
- `chat_jid`는 `dc:<channel_id>` 형식이어야 합니다. tribunal 방인데 `work_dir`가 비어 있으면 첫 턴에 자동 복구됩니다.
- `folder`는 `discord_<name>` 형태를 유지합니다.
- 작업 중단("그만", "stop")이 안 먹으면 로그의 `Stopped room work on user request`와 `src/stop-intent.ts` 판정 규칙을 같이 봅니다.
## 원칙

View File

@@ -10,7 +10,7 @@ description: Run initial EJClaw setup for the unified single-service Discord arc
EJClaw는 현재 **단일 서비스**로 동작합니다:
- **ejclaw** — 통합 런타임 서비스
Claude가 기본 봇으로 동작하고, Codex는 별도 서비스가 아니라 필요 시 내부 러너/역할 라우팅으로 사용됩니다.
owner 역할의 코드 기본값은 Codex(`OWNER_AGENT_TYPE`, reviewer 기본값은 Claude Code)이며, `.env`에서 바꿀 수 있습니다(현재 운영 배포는 owner=claude-code, reviewer=codex, arbiter=claude-code). Codex는 별도 서비스가 아니라 같은 `ejclaw` 서비스 안에서 내부 러너/역할 라우팅으로 실행됩니다.
## 1. 부트스트랩
@@ -18,7 +18,7 @@ Claude가 기본 봇으로 동작하고, Codex는 별도 서비스가 아니라
bash setup.sh
```
- Node 20 이상과 의존성이 준비되어야 합니다.
- Bun 1.3 이상과 의존성이 준비되어야 합니다(`setup.sh`가 Bun을 확인합니다).
- 실패하면 `logs/setup.log`를 먼저 봅니다.
## 2. 현재 상태 확인
@@ -40,7 +40,10 @@ bun run setup -- --step environment
`.env`에 최소한 아래 값이 있어야 합니다.
```bash
DISCORD_BOT_TOKEN=... # Claude 봇 토큰
DISCORD_OWNER_BOT_TOKEN=... # owner 봇 토큰
DISCORD_REVIEWER_BOT_TOKEN=... # reviewer 봇 토큰
DISCORD_ARBITER_BOT_TOKEN=... # arbiter 봇 토큰
# 구 이름(DISCORD_BOT_TOKEN 등)은 더 이상 지원되지 않으며, 남아 있으면 시작 시 오류로 종료됩니다
CLAUDE_CODE_OAUTH_TOKEN=... # 또는 ANTHROPIC_API_KEY=...
ASSISTANT_NAME=claude # 트리거 이름 (@claude)
```
@@ -48,7 +51,6 @@ ASSISTANT_NAME=claude # 트리거 이름 (@claude)
권장:
```bash
CLAUDE_CODE_OAUTH_TOKENS=token1,token2 # 다중 계정 자동 로테이션
GROQ_API_KEY=... # Discord 음성 전사 (Groq Whisper)
```
@@ -58,7 +60,12 @@ Codex 관련 선택 설정은 **별도 서비스 파일이 아니라 같은 `.en
# 같은 .env 또는 서비스 Environment=에 추가 가능
CODEX_MODEL=gpt-5.5
CODEX_EFFORT=xhigh
OPENAI_API_KEY=...
```
Codex는 API 키가 아니라 OAuth로만 인증합니다(러너가 `OPENAI_API_KEY`를 일부러 제거함). 로그인:
```bash
CODEX_HOME=$HOME/.codex-accounts/0 ./node_modules/.bin/codex login --device-auth
```
### 선택 환경 변수
@@ -70,7 +77,6 @@ USAGE_DASHBOARD=true
# 고급 설정
MAX_CONCURRENT_AGENTS=5
SESSION_COMMAND_ALLOWED_SENDERS=... # 세션 명령 허용 유저 ID (쉼표 구분)
```
## 4. 러너 빌드
@@ -100,20 +106,16 @@ bun run setup -- --step runners
bun run setup -- --step register -- \
--jid dc:123456789012345678 \
--name "My Server #general" \
--folder discord_main \
--trigger @claude \
--is-main \
--no-trigger-required
--folder discord_general
```
보조 채널 예시:
다른 채널 예시 (모든 방은 동등하며 자기 방만 다룹니다):
```bash
bun run setup -- --step register -- \
--jid dc:123456789012345678 \
--name "My Server #ops" \
--folder discord_ops \
--trigger @claude
--folder discord_ops
```
## 6. 서비스 시작
@@ -125,10 +127,7 @@ bun run setup -- --step service
이 명령은:
- **ejclaw** 서비스를 설치하고 시작합니다
플랫폼별:
- Linux (systemd): `~/.config/systemd/user/ejclaw.service`
- macOS: `~/Library/LaunchAgents/com.ejclaw.plist`
- WSL (no systemd): `start-ejclaw.sh`
Linux systemd만 지원합니다: `~/.config/systemd/user/ejclaw.service`
수동으로 서비스 관리:
@@ -156,8 +155,8 @@ bun run setup -- --step verify
## 빠른 문제 해결
- 빌드 문제: `bun run typecheck`, `bun test`, `bun run build:runners`
- Claude 서비스 문제: `logs/ejclaw.error.log` 또는 `journalctl --user -u ejclaw -f`
- Codex 실행 문제: 같은 `ejclaw` 서비스 로그에서 `CODEX_MODEL`, `CODEX_EFFORT`, `OPENAI_API_KEY` 설정을 같이 확인
- 디스코드 연결 문제: `.env`의 `DISCORD_BOT_TOKEN`과 등록된 `dc:*` JID 확인
- 응답 문제: `tail -f logs/ejclaw.log`
- 빌드 문제: `bun run typecheck`, `bun run test`, `bun run build:runners`
- Claude 서비스 문제: `journalctl --user -u ejclaw -f`
- Codex 실행 문제: 같은 `ejclaw` 서비스 로그와 `CODEX_MODEL`, `CODEX_EFFORT`, Codex 인증 파일(`~/.codex-accounts/0/auth.json`)을 확인
- 디스코드 연결 문제: `.env`의 `DISCORD_OWNER_BOT_TOKEN` / `DISCORD_REVIEWER_BOT_TOKEN` / `DISCORD_ARBITER_BOT_TOKEN`과 등록된 `dc:*` JID 확인
- 응답 문제: `journalctl --user -u ejclaw -f`

View File

@@ -16,22 +16,21 @@ REVIEWER_AGENT_TYPE=claude-code # claude-code | codex
# ARBITER_AGENT_TYPE=codex # optional: codex | claude-code
# --- API keys ---
CLAUDE_CODE_OAUTH_TOKENS= # Canonical comma-separated Claude Code OAuth tokens (use one value for single-account too)
CLAUDE_CODE_OAUTH_TOKEN= # Legacy single-token fallback
CLAUDE_CODE_OAUTH_TOKEN= # Claude Code OAuth token (single account)
GROQ_API_KEY= # Voice transcription (Groq Whisper, free: console.groq.com)
# --- Bot identity ---
ASSISTANT_NAME=claude # Trigger name (@claude)
# --- Claude model ---
CLAUDE_MODEL=claude-opus-4-8 # Claude model
CLAUDE_MODEL=claude-opus-5-5 # Claude model
CLAUDE_EFFORT=high # Claude effort level
CLAUDE_THINKING=adaptive # Claude thinking mode
# --- Codex model ---
CODEX_MODEL=gpt-5.5 # Codex model
CODEX_EFFORT=xhigh # Codex reasoning effort
# Codex fast mode / goals: dashboard Settings → Codex, or ~/.codex/config.toml:
# Codex fast mode / goals: ~/.codex/config.toml:
# [features]
# fast_mode = true
# goals = true # /goal — opt-in, default OFF on Codex 0.133+
@@ -40,71 +39,30 @@ CODEX_EFFORT=xhigh # Codex reasoning effort
STATUS_CHANNEL_ID= # Discord channel ID for live status updates
# STATUS_SHOW_ROOMS=true # Show room status in dashboard
# STATUS_SHOW_ROOM_DETAILS=false # Show detailed room info
# WEB_DASHBOARD_ENABLED=false # Local dashboard server
# WEB_DASHBOARD_HOST=127.0.0.1 # Keep localhost unless using VPN/tunnel
# WEB_DASHBOARD_PORT=8734
# WEB_DASHBOARD_TOKEN= # Optional bearer token for /api/* when exposing to phone clients
# --- Discord image attachments ---
# Extra local directories that agents may attach from. Keep this narrow:
# prefer screenshot/output folders over /home. Comma or path-delimiter separated.
# EJCLAW_ATTACHMENT_ALLOWED_DIRS=~/Pictures/Screenshots,~/Downloads/ejclaw-images
# --- Codex warm-up (optional, disabled by default) ---
# Sends a tiny real Codex prompt only when both 5h and 7d usage are 0%, so
# reset countdown starts once after a fresh quota window. Keep disabled if
# OpenAI changes policy or starts blocking automated warm-up prompts.
# Normally only set this one line; the other knobs have conservative defaults.
# CODEX_WARMUP_ENABLED=false
# --- Codex usage primer ---
# The usage primer sends a tiny real Codex prompt at fixed KST slots
# (08/13/18/23). These keys override its prompt, model and timeout.
# CODEX_WARMUP_PROMPT=Reply exactly OK. Do not run tools.
# CODEX_WARMUP_MODEL= # Defaults to CODEX_MODEL
# CODEX_WARMUP_INTERVAL_MS=300000 # Check every 5min
# CODEX_WARMUP_MIN_INTERVAL_MS=18300000 # Per-account minimum gap: 5h5m
# CODEX_WARMUP_STAGGER_MS=1800000 # Global gap between accounts: 30min
# CODEX_WARMUP_MAX_USAGE_PCT=0 # Only warm accounts at/below this 5h usage
# CODEX_WARMUP_MAX_D7_USAGE_PCT=0 # Only warm accounts at/below this 7d usage
# CODEX_WARMUP_MAX_CONSECUTIVE_FAILURES=2
# CODEX_WARMUP_FAILURE_COOLDOWN_MS=21600000 # Back off 6h after repeated failure
# --- Fallback provider (when Claude/Codex both unavailable) ---
# FALLBACK_ENABLED=true # Enable fallback provider
# FALLBACK_PROVIDER_NAME=kimi # Provider name for logging
# FALLBACK_BASE_URL= # OpenAI-compatible API base URL
# FALLBACK_AUTH_TOKEN= # API token for fallback provider
# FALLBACK_MODEL=kimi-k2.5 # Fallback model
# FALLBACK_SMALL_MODEL=kimi-k2.5 # Fallback small model
# FALLBACK_COOLDOWN_MS=600000 # Cooldown between fallback attempts (10min)
# CODEX_WARMUP_COMMAND_TIMEOUT_MS=120000
# --- Per-role model overrides (paired rooms) ---
# Override global CLAUDE_MODEL/CODEX_MODEL per role.
# Model is injected based on each role's agent type (claude-code → CLAUDE_MODEL, codex → CODEX_MODEL).
# OWNER_MODEL=gpt-5.5 # Owner model override
# OWNER_EFFORT=xhigh # Owner effort override
# OWNER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true)
#
# REVIEWER_MODEL=claude-opus-4-8 # Reviewer model override
# REVIEWER_MODEL=claude-opus-5-5 # Reviewer model override
# REVIEWER_EFFORT=high # Reviewer effort override
# REVIEWER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true)
#
# ARBITER_MODEL=gpt-5.5 # Arbiter model override when ARBITER_AGENT_TYPE=codex
# ARBITER_EFFORT=xhigh # Arbiter effort override
# ARBITER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true)
# --- Mixture of Agents (MoA) ---
# Queries external API models in parallel before arbiter runs.
# Their opinions are injected into the arbiter's prompt for better judgment.
# The SDK arbiter (subscription-based, no extra cost) aggregates all perspectives.
# MOA_ENABLED=true
# MOA_REF_MODELS=kimi,glm # Comma-separated reference model names
# MOA_KIMI_MODEL=kimi-k2.6 # Kimi model
# MOA_KIMI_BASE_URL=https://api.kimi.com/coding # Kimi API endpoint
# MOA_KIMI_API_FORMAT=anthropic # Kimi Code API format
# MOA_KIMI_API_KEY=sk-kimi-xxx # Kimi API key
# MOA_GLM_MODEL=glm-5.1 # GLM model
# MOA_GLM_BASE_URL=https://open.bigmodel.cn/api/anthropic # GLM API endpoint
# MOA_GLM_API_FORMAT=anthropic # GLM Anthropic-compatible API
# MOA_GLM_API_KEY=xxx # GLM API key
# --- Advanced ---
# MAX_CONCURRENT_AGENTS=5 # Max parallel agent processes
# SESSION_COMMAND_ALLOWED_SENDERS= # Comma-separated Discord user IDs for session commands

1
.github/CODEOWNERS vendored
View File

@@ -1,7 +1,6 @@
# Core code - maintainer only
/src/ @gavrielc @gabi-simons
/groups/ @gavrielc @gabi-simons
/launchd/ @gavrielc @gabi-simons
/package.json @gavrielc @gabi-simons
/bun.lock @gavrielc @gabi-simons

7
.gitignore vendored
View File

@@ -4,10 +4,6 @@ node_modules/
# Build output
dist/
runners/*/dist/
apps/android/.gradle/
apps/android/build/
apps/android/app/build/
apps/android/local.properties
# Local data & auth
store/
@@ -24,11 +20,8 @@ logs/
# Groups - only track base structure and specific CLAUDE.md files
groups-*/
groups/*
!groups/main/
!groups/global/
groups/main/*
groups/global/*
!groups/main/CLAUDE.md
!groups/global/CLAUDE.md
# Secrets

View File

@@ -2,6 +2,47 @@
이 문서는 EJClaw의 주요 변경 사항을 기록합니다.
## [Unreleased]
### Added
- owner가 "리뷰 불필요" 표시: 설명·조사만 하고 아무것도 바꾸지 않은 TASK_DONE 답변 끝에 owner가 `리뷰 불필요: <이유>` 한 줄을 붙이면, 시스템이 다시 확인해 리뷰어·마무리 턴 없이 그 답변을 최종 답변으로 보내고 task를 `review_skipped`로 닫음. 표시 줄은 사용자에게 보이지 않고, 답변 끝에 `-# 검토 생략(변경 없는 설명형 답변) · "검토해줘"라고 하면 검토합니다`가 붙음. 다음 중 하나라도 해당하면 표시를 무시하고 평소처럼 리뷰: task 기준 이후 작업 폴더 내용 변경, 커밋되지 않은 변경, owner 실행 중 HEAD 이동, 파일 수정 도구(Edit/Write/MultiEdit/NotebookEdit)·서브에이전트(Agent/Task)·상태를 바꾸는 MCP 도구(schedule_task 등)·알 수 없는 도구 사용, 읽기 전용으로 확실히 분류되지 않는 셸 명령(`src/bash-command-classifier.ts`), 도구 사용 기록이 없거나 잘림(Codex owner 포함), 이번 task에서 사용자가 검토를 요청함. agent-runner는 실행 중 호출한 도구 이름과 Bash 명령을 최종 출력의 `toolUsage`로 보고함. 검토가 생략된 직후 사용자가 "검토해줘" 같은 짧은 검토 요청만 보내면 그 task를 다시 열어 리뷰어가 그 답변을 검토함
- 자연어 작업 중단: 작업이 실행 중이거나 대기 중인 방에 "그만", "멈춰", "중단해", "취소", "stop" 같은 중단 의도만 담긴 짧은 메시지를 보내면 실행 중인 에이전트를 종료하고, 열린 paired task를 `user_stopped`로 닫고(남은 turn 취소·lease 해제), 중단 메시지까지 처리된 것으로 넘긴 뒤 "진행 중이던 작업을 중단했습니다."라고 답함. 다른 지시가 섞인 메시지는 중단으로 보지 않음
### Changed
- 마무리(finalize) 턴 비용 절감. (가) 리뷰어가 owner의 첫 TASK_DONE 답변을 첫 리뷰에서 바로 승인했고(리뷰 1회, owner 수정·중재 턴 없음) 승인 이후 작업 폴더가 그대로면 owner를 다시 실행하지 않고 그 답변(상태 줄 제외)을 최종 메시지로 올리고 task를 완료함. 검토 생략 답변에 "검토해줘"로 받은 리뷰가 바로 승인되면 답변을 반복하지 않고 `-# 검토 완료: …` 한 줄만 올림. (나) 그 밖의 마무리 턴은 task의 긴 작업 세션을 resume하지 않는 새 세션에서, 이번 task의 사용자 요청과 최근 turn 출력(최대 6개)과 마무리 형식 안내만 담은 프롬프트로 실행하고 세션을 저장하지 않음(방 메모리 브리핑도 생략). owner 규칙에 첫 TASK_DONE 답변도 최종 답변 형식을 따라야 한다고 명시
- paired 방의 owner·리뷰어 세션을 paired task 단위로 새로 시작. 같은 task 안의 후속 턴(리뷰 반영, 같은 task에 들어온 사용자 후속 메시지)은 그 세션을 이어 쓰고, 새 task의 첫 턴은 이전 세션을 resume하지 않음. 세션이 어느 task 것인지는 `router_state`의 `paired_session_task:<세션 폴더>`에 기록. 이전 task의 마지막 최종 답변은 새 task의 turn 0(carry-forward)으로 계속 전달되며, 이를 위해 `PAIRED_CARRY_FORWARD_LATEST_OWNER_FINAL` 기본값을 `true`로 변경. single 방은 그대로
- Claude가 사용 한도에 도달하면 Codex로 넘기지 않고 그 방의 작업을 일시정지했다가, 사용량이 초기화되면 자동으로 이어서 진행함. 한도에 걸린 turn은 실패로 세지 않고 paired task 상태를 그대로 두며, 처리하던 사용자 메시지도 처리 완료로 넘기지 않음. 방에는 "Claude 사용 한도에 도달해서 이 방의 작업을 일시정지했습니다. 21:40에 사용량이 초기화되면 자동으로 이어서 진행합니다."처럼 재개 시각(KST)을 알림. 한도는 계정 전체에 걸리므로 일시정지 중에는 다른 방의 Claude turn도 실행하지 않고 같은 방식으로 일시정지함(일시정지되지 않은 방의 Codex turn은 그대로 실행). 일시정지 상태는 `router_state`의 `claude_usage_pause`에 저장되어 재시작 후에도 유지되고, 스케줄러 tick이 초기화 시각 1분 뒤에 "Claude 사용량이 초기화되어서 일시정지했던 작업을 이어서 진행합니다."를 보내고 방들을 다시 큐에 넣음. 재개 시각은 오류 문구(`resets 9:40pm (Asia/Seoul)` 등)에서 읽고, 없으면 사용량 API 캐시에서, 그것도 없으면 10분 뒤에 다시 시도함. 일시정지 중 "중단"을 보내면 그 방의 작업을 버리고 재개 대상에서 뺌
- 기본 Claude 모델을 Claude Opus 5.5(`claude-opus-5-5`)로 상향. Opus 5.5는 Claude Code CLI 2.1.280 이상이 필요해 `@anthropic-ai/claude-agent-sdk`를 0.3.153 → 0.3.286(번들 CLI 2.1.286)으로 올림 (8b68885)
- `@openai/codex`를 0.133.0 → 0.159.3으로 상향. 구버전이 매 실행마다 내던 `failed to decode models response: unknown variant max` 오류와 로그 폭주가 사라지고, 단순 리뷰 턴이 49초 → 5초로 단축됨 (a7f2e02)
### Removed
- 웹 대시보드(`src/web-dashboard-*`, `apps/dashboard`), Android 앱(`apps/android`), Glasses UI와 이를 위해서만 있던 설정 저장소(`settings-store`, `settings-store-moa`, `room-skill-settings`, `runtime-inventory`, `codex-live-status`, `settings-effort`), `WEB_DASHBOARD_*` 설정, `dashboard:*`/`android:*` 스크립트, react·vite·playwright 의존성. 잘못된 계정(`~/.codex`)을 갱신하던 Codex 계정 새로고침 루프도 함께 제거. 호스트 증거 도구의 `dashboard_dist`/`android_debug_apk` 항목 제거. Discord 상태 대시보드는 그대로 유지
- Mixture of Agents(MoA) arbiter 프롬프트 보강, Kimi 사용량 조회/대시보드 행, `MOA_*` 설정, 코드에서 읽지 않던 `FALLBACK_*` provider 설정 예시
- 런타임에 연결되지 않았던 auto-paired-mode(`src/auto-paired-mode.ts`)와 그것만 쓰던 Claude/Codex 사용량 소진 판정 함수
- 쓰이지 않던 export·고아 모듈(`src/dashboard.ts`, `src/dashboard-status-content.ts`, `src/restart-context-cli.ts`)과 `DELTA_HANDOFF_*` 설정
- macOS launchd·nohup(WSL) 설치 경로와 `launchd/`, 쓰이지 않던 `repo-tokens/` GitHub Action. 서비스 설치는 Linux systemd만 지원
- 루트에서 import하지 않던 `yaml`, `zod`, `@modelcontextprotocol/sdk` 의존성 (agent-runner는 자체 의존성 유지)
- `/compact`·`/clear`·`/stop` 세션 명령(main 방·관리자 전용이라 실제로 쓰이지 않음)과 `SESSION_COMMAND_ALLOWED_SENDERS` 설정, agent-runner의 `/compact` 처리. `.env`에 남아 있는 `SESSION_COMMAND_*` 값은 더 이상 시작을 막지 않고 무시됨
- main(관리) 방 개념과 그것이 열어 주던 방 간 기능. 모든 방의 `is_main`이 0이라 실제로 쓰이지 않았음. 이제 각 방의 에이전트는 자기 방만 다룸: 다른 방 예약 작업 생성/수정/일시정지/취소(`target_group_jid`), 다른 방으로 메시지 전송·inbound 주입, 전체 방 범위의 DB 증거 조회, IPC `assign_room`/`refresh_groups`와 에이전트용 `assign_room` 도구, `available_groups.json` 스냅샷, main 방 전용 global memory 제외, `EJCLAW_IS_MAIN` 환경 변수, main 방으로 보내던 추론 재시작 알림, `setup --step register`의 `--is-main`, `scripts/deregister-room.ts`의 main 방 보호(`--force`), `groups/main/` 템플릿 제거. `room_settings.is_main` 컬럼은 스키마에 남아 있으나 더 이상 읽거나 쓰지 않음
- 기본 비활성이던 주기적 Codex warm-up 루프와 `CODEX_WARMUP_ENABLED`/`CODEX_WARMUP_INTERVAL_MS`. 고정 슬롯 usage primer는 그대로 동작
- 다중 계정 로테이션. Claude·Codex 모두 계정 1개 고정으로 동작: 한도·인증 오류 시 다음 계정으로 넘어가기, 계정별 쿨다운·상태 파일(`token-rotation-state.json`, `codex-rotation-state.json`), Codex 1시간 전체 계정 사용량 스캔, `CLAUDE_ACCOUNTS_DIR`(`~/.claude-accounts/<n>`) 제거. Codex는 `~/.codex-accounts/0/auth.json`(없으면 `~/.codex/auth.json`)을 매 실행마다 확인하므로 재로그인 후 재시작이 필요 없음. 계정 잠금(동시 실행 1개, 최대 15분 대기)과 세션 토큰 write-back, Claude 토큰 자동 갱신(만료 시 1회 강제 갱신 후 재시도)은 유지. `CLAUDE_CODE_OAUTH_TOKENS`는 첫 번째 값만 사용
- Claude→Codex failover/handoff 체인: 한도·인증 오류 시 `service_handoffs`에 작업을 넘기던 생성 경로, 핸드오프 폴링·claim 워커, 전역 owner failover(`codex-review`가 owner 대행)와 그 프롬프트(`prompts/codex-review-failover-platform.md`), 대시보드 failover 표시, `ROOM_ROLE` 헤더의 `failover=` 필드, `OWNER_/REVIEWER_/ARBITER_FALLBACK_ENABLED` 설정. 이 배포에는 받을 Codex 서비스가 없어 넘긴 작업이 `pending`으로 남기만 했음. `service_handoffs` 테이블과 마이그레이션은 그대로 두며(다음 마이그레이션 정리 때 처리), 런타임은 더 이상 읽거나 쓰지 않음(방 등록 해제 스크립트의 행 정리만 남김). `.env`에 남은 `*_FALLBACK_ENABLED`는 무시됨
### Fixed
- `scripts/deregister-room.ts`의 타입 오류(`bun run typecheck:all`에서만 보이던 `unknown[]` 바인딩) 수정
- 메시지 처리 커서가 뒤로 감기지 않도록 함. 더 새로운 메시지를 이미 처리한 뒤 끝난 이전 실행이 커서를 되돌려 같은 메시지가 다시 실행되던 경로를 막음
- Codex 계정이 1개일 때 두 방이 동시에 Codex를 쓰면 두 번째 실행이 "Codex rotation pool unavailable"로 즉시 실패하고 리뷰가 조용히 생략되던 문제 수정. 잠금이 다른 실행에 잡혀 있으면 최대 15분 기다림 (30ba510)
- 이미 턴 소유권을 잃은 실행의 5초 진행 표시 타이머가 멈추지 않아, 실제로 작업 중인 방의 진행 메시지가 멈춘 것처럼 보이던 문제 수정 (69ae334)
- `work_dir`가 비어 있는 tribunal 방에서 실행 컨텍스트가 만들어지지 않아 작업 리비전이 얼고 10분 안의 후속 메시지가 버려지던 문제 수정. 자동 복구 경로가 동작하도록 함 (c7a8a43)
### Docs
- README / `docs/configuration.md` / `docs/architecture.md` / setup·debug 스킬을 현재 동작에 맞게 정리: 현재 SDK·모델 버전, room별 reviewer/arbiter override, 제거된 `registered_groups`, 더 이상 지원되지 않는 `DISCORD_BOT_TOKEN`, Codex OAuth 로그인, journald 로그 위치, `bun run test`
## [0.2.3] - 2026-04-22
### Added

View File

@@ -12,7 +12,7 @@ A [skill](https://code.claude.com/docs/en/skills) is a markdown file in `.claude
A PR that contributes a skill should not modify any source files.
Your skill should contain the **instructions** Claude follows to add the feature—not pre-built code. See `/add-telegram` for a good example.
Your skill should contain the **instructions** Claude follows to add the feature—not pre-built code. See `.claude/skills/setup/SKILL.md` for the format.
### Why?

View File

@@ -1,8 +1,8 @@
# EJClaw
![Version](https://img.shields.io/badge/version-0.2.3-blue)
![Claude Agent SDK](https://img.shields.io/badge/Claude_Agent_SDK-0.2.126-blueviolet)
![Codex SDK](https://img.shields.io/badge/Codex_SDK-0.133.0-green)
![Claude Agent SDK](https://img.shields.io/badge/Claude_Agent_SDK-0.3.286-blueviolet)
![Codex SDK](https://img.shields.io/badge/Codex_SDK-0.159.3-green)
![Bun](https://img.shields.io/badge/Bun-1.3+-f9f1e1?logo=bun&logoColor=black)
![Discord](https://img.shields.io/badge/Discord-Tribunal-5865F2?logo=discord&logoColor=white)
@@ -17,21 +17,21 @@ EJClaw는 Discord 위에서 동작하는 Tribunal 멀티에이전트 개발 보
- 단일 `ejclaw` 서비스가 owner / reviewer / arbiter 세 역할과 세 Discord 봇을 함께 관리합니다.
- 사용자 진입점은 owner 하나이며, reviewer와 arbiter는 내부 역할로 동작합니다.
- room-level 설정은 `room_settings`를 기준으로 하며, `assign_room`이 공개 assignment 인터페이스입니다.
- room-level 설정은 `room_settings`를 기준으로 하며, 방 등록은 `bun run setup -- --step register`(내부적으로 `assignRoom`)로 합니다.
- 모든 방은 동등합니다. 별도의 main(관리) 방은 없고, 각 방의 에이전트는 자기 방의 메시지·예약 작업·DB 증거만 다룰 수 있습니다. 여러 방에 걸친 관리 작업은 호스트 셸에서 합니다.
- reviewer는 owner의 현재 worktree를 direct mount로 읽고, role-scoped read-only 보호를 적용받습니다.
- paired runtime은 SQLite(WAL), stable owner worktree, turn/lease 추적, host verification으로 구성됩니다.
## 핵심 기능
- Tribunal 3-에이전트 루프: owner / reviewer / arbiter
- Mixture of Agents(MoA): 외부 모델 의견을 arbiter 판단에 주입
- 역할별 agent type / model / effort 설정
- role-fixed Discord 봇 3개 체계
- reviewer host runtime + read-only guard
- 승인 후 변경 감지와 재리뷰
- Claude 장애 시 Codex로 넘기는 global failover
- Claude OAuth 멀티 토큰 로테이션
- `assign_room` 기반 명시적 room assignment
- Claude 사용 한도 도달 시 방 작업을 일시정지하고, 사용량이 초기화되면 자동으로 이어서 진행
- `room_settings` 기반 명시적 room assignment
- 자연어 중단: 작업 중인 방에 "그만", "멈춰", "중단해", "취소", "stop" 같은 짧은 메시지만 보내면 실행 중인 에이전트를 끝내고 열린 paired task를 닫음
- Bun + SQLite 기반 빠른 런타임
## 운영 적용 사항
@@ -45,15 +45,15 @@ GitHub `main` 베이스 위에 운영 중 검증된 변경을 현재 코드 구
- 대시보드: 등록된 방 별칭을 Discord 채널명과 분리해 보존.
- 상태 대시보드 갱신 정책: 기본 갱신을 벽시계 분 경계(:00초)에 정렬하고, 새 채팅 메시지·에이전트 활성 변화 시 즉시(1.5s 디바운스) 갱신. 상태 메시지 편집이 실패하면 15초 간격 2회 재시도 후에만 새 메시지로 재게시하며(봇 재시작 직후에는 즉시 재표시), 편집 실패로 인한 반복 재생성(알림 스팸)을 제거.
- Claude 세션 토큰 write-back: 각 Claude 턴 종료 시 세션이 rotate한 OAuth 토큰을 표준 자격증명(data/claude)으로 수렴시켜, 본체 리프레시 루프와 세션 CLI가 같은 토큰 패밀리를 각자 갱신하다 발생하던 `invalid_grant`(리프레시 토큰 패밀리 폐기 → 재로그인 강제)를 방지. 세션 자격증명 스캔 경로도 실제 구조(`services/<id>/.claude`, `tasks/<id>` 하위)에 맞게 정정해 fan-out/stale 정리가 실제 세션 파일을 덮도록 함. Codex는 기존 write-back(`syncCodexSessionAuthBack`)을 사용.
- 채널 등록 해제 도구(`scripts/deregister-room.ts`): 채널 등록 해제 시 paired 데이터·세션(reviewer·arbiter 포함)·워크스페이스·디스크 폴더(git worktree 포함)를 전부 정리하고 채팅 채널과 메시지만 보존. `--dry-run` 미리보기, main 방 보호, 다른 방과 공유하는 폴더 보호, 실행 전 DB 자동 백업 포함.
- 채널 등록 해제 도구(`scripts/deregister-room.ts`): 채널 등록 해제 시 paired 데이터·세션(reviewer·arbiter 포함)·워크스페이스·디스크 폴더(git worktree 포함)를 전부 정리하고 채팅 채널과 메시지만 보존. `--dry-run` 미리보기, 다른 방과 공유하는 폴더 보호, 실행 전 DB 자동 백업 포함.
## Tribunal 시스템
| 역할 | 현재 기본값 | 설명 |
| --- | --- | --- |
| Owner | room별 `owner_agent_type` (기본 Codex) | 사용자 요청 처리, 코드 작성, 최종 응답 |
| Reviewer | 전역 `REVIEWER_AGENT_TYPE` (기본 Claude Code) | owner 결과 비판적 리뷰, 회귀 검증 |
| Arbiter | 전역 `ARBITER_AGENT_TYPE` (옵션) | owner/reviewer 교착 시 판정 |
| Reviewer | 전역 `REVIEWER_AGENT_TYPE` (기본 Claude Code), room별 `reviewer_agent_type`로 override 가능 | owner 결과 비판적 리뷰, 회귀 검증 |
| Arbiter | 전역 `ARBITER_AGENT_TYPE` (옵션), room별 `arbiter_agent_type`로 override 가능 | owner/reviewer 교착 시 판정 |
```text
사용자 메시지
@@ -68,9 +68,14 @@ GitHub `main` 베이스 위에 운영 중 검증된 변경을 현재 코드 구
→ 왕복이 누적되면 arbiter 자동 요청 가능
```
### MoA
### 작업 중단
MoA가 켜져 있으면 arbiter가 판정하기 전에 Kimi, GLM 같은 외부 모델 의견을 병렬 수집하고, 그 결과를 arbiter 프롬프트에 주입합니다. 최종 판정은 여전히 EJClaw arbiter가 내립니다.
방에서 에이전트가 실행 중이거나, 대기 중인 메시지·열린 paired task가 있을 때 사람이 중단 의도만 담긴 짧은 메시지를 보내면 그 방의 작업을 멈춥니다.
- 인식하는 표현: `그만`, `그만해(줘)`, `그만하자`, `멈춰(줘)`, `중단(해)`, `중지`, `하지 마`, `취소(해)`, `스톱`, `stop`, `cancel` 등. 앞뒤 봇 멘션과 끝의 `. ! ~ ㅠ ㅜ`는 무시하고, "작업 중단해줘", "제발 그만"처럼 짧은 수식어는 허용합니다.
- "그거 하지 말고 이거 해줘", "중단하지 말고 계속해", "로그인 취소 기능 만들어줘"처럼 다른 지시가 섞인 메시지는 중단으로 보지 않습니다. 애매하면 일반 메시지로 처리합니다.
- 중단 시: 실행 중인 owner/reviewer/arbiter 프로세스를 종료하고, 열린 paired task를 `completion_reason = 'user_stopped'`로 닫고(남은 turn 취소, 실행 lease 해제), 중단 메시지까지의 메시지를 처리된 것으로 넘긴 뒤 "진행 중이던 작업을 중단했습니다."라고 한 번 답합니다.
- 멈출 것이 없으면 그 메시지는 평소처럼 에이전트에게 전달됩니다.
## 방 설정 모델
@@ -80,7 +85,7 @@ MoA가 켜져 있으면 arbiter가 판정하기 전에 Kimi, GLM 같은 외부
- `room_role_overrides`: owner / reviewer / arbiter 역할별 override
- `paired_projects`: canonical project root
- `paired_workspaces`: 실제 owner / reviewer 실행 workspace
- `registered_groups`: 완전히 제거되지는 않았지만, canonical source가 아니라 compatibility/read-model 성격으로 남아 있는 레이어
- `registered_groups`: 제거됨. 구버전 DB를 옮길 때 `setup/legacy-room-registrations.ts`가 입력으로만 읽음
운영적으로는:
@@ -107,11 +112,6 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
│ └─ BLOCKED → arbiter / user
│
├──► Arbiter (on-demand, fresh session)
│ │
│ ┌───┴─── MoA ───┐
│ │ Kimi / GLM │
│ │ 의견 수집 │
│ └───────────────┘
│
IPC follow-up / host tools
│
@@ -124,7 +124,7 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
### 요구사항
- Linux(Ubuntu 22.04+) 또는 macOS
- Linux(Ubuntu 22.04+, systemd)
- [Bun](https://bun.sh/) 1.3+
- Claude Code CLI
- Codex CLI
@@ -132,8 +132,8 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
현재 runner 번들 기준 버전:
- Claude Agent SDK: `@anthropic-ai/claude-agent-sdk@0.2.126`
- Codex SDK/CLI: `@openai/codex@0.133.0`
- Claude Agent SDK: `@anthropic-ai/claude-agent-sdk@0.3.286` (번들 Claude Code CLI 2.1.286 — Claude Opus 5.5는 CLI 2.1.280 이상 필요)
- Codex SDK/CLI: `@openai/codex@0.159.3`
### 설치
@@ -154,7 +154,7 @@ bun run build:all
DISCORD_OWNER_BOT_TOKEN=
DISCORD_REVIEWER_BOT_TOKEN=
DISCORD_ARBITER_BOT_TOKEN=
CLAUDE_CODE_OAUTH_TOKENS=
CLAUDE_CODE_OAUTH_TOKEN=
OWNER_AGENT_TYPE=codex
REVIEWER_AGENT_TYPE=claude-code
```
@@ -178,6 +178,8 @@ bun run deploy
3. `migrate-room-registrations` 실행
4. `systemctl --user restart ejclaw`
주의: 운영 유닛은 `bun src/index.ts`로 src를 직접 실행하므로 루트 `dist/` 빌드는 서비스에 영향이 없습니다(runner의 `dist/`는 경로로 실행되므로 `bun run build:runners`가 필요). 또 에이전트 턴 안에서 `systemctl --user restart`를 직접 실행하면 에이전트 자신이 함께 종료되므로, 턴 안에서는 `systemd-run --user --collect … systemctl --user restart ejclaw.service`처럼 분리 실행해야 합니다.
## 개발
```bash
@@ -192,7 +194,7 @@ bun run check
- [docs/architecture.md](docs/architecture.md) — 데이터 모델, 실행 흐름, 주요 파일
- [docs/configuration.md](docs/configuration.md) — `.env` 키와 디버깅 경로
- [docs/legacy-compat-removal-spec.md](docs/legacy-compat-removal-spec.md) — 남아 있는 레거시 제거 계획
- [docs/legacy-compat-removal-spec.md](docs/legacy-compat-removal-spec.md) — 레거시 제거 설계 문서(주요 결정은 반영 완료, 이력 참고용)
- [CHANGELOG.md](CHANGELOG.md) — 릴리즈 이력
## 라이선스

View File

@@ -1,11 +0,0 @@
.gradle/
build/
local.properties
*.apk
*.ap_
*.aab
*.iml
.idea/
.cxx/
captures/
app/build/

View File

@@ -1,54 +0,0 @@
# EJClaw Android
Personal Android companion for EJClaw. This is a thin client: EJClaw still runs
on the existing Bun service, and the Android app talks to the dashboard API.
## Build
```bash
cd apps/android
cp local.properties.example local.properties
./gradlew assembleDebug
```
The debug APK is written to:
```text
apps/android/app/build/outputs/apk/debug/app-debug.apk
```
Install with:
```bash
adb install -r apps/android/app/build/outputs/apk/debug/app-debug.apk
```
## Runtime Setup
- Keep EJClaw behind Tailscale, VPN, SSH tunnel, or localhost forwarding.
- Base URL defaults to `http://100.101.210.95:8734`.
- If `WEB_DASHBOARD_TOKEN` is enabled on the server, paste the same token into
the app. It sends `Authorization: Bearer <token>`.
## Current MVP
- Connect to `/api/health`.
- Load rooms from `/api/rooms-timeline`.
- Open a room timeline from `/api/rooms/:jid/timeline`.
- Send text through `/api/rooms/:jid/messages`.
- Keep the Ray-Ban Display integration isolated behind `DisplaySurface`.
## Meta DAT
The default APK does not link the Meta DAT SDK yet. Meta's Android DAT SDK is
distributed through GitHub Packages and needs Developer Preview access, a
GitHub package token, and a Wearables Developer Center application id.
The integration point is already present:
```text
app/src/main/java/com/ejclaw/android/display/
```
After DAT access is ready, replace `MetaDatDisplaySurface` with SDK calls and
keep `NoopDisplaySurface` for phone-only testing.

View File

@@ -1,26 +0,0 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.ejclaw.android"
compileSdk = 36
defaultConfig {
applicationId = "com.ejclaw.android"
minSdk = 26
targetSdk = 36
versionCode = 1
versionName = "0.1.0"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
}
kotlin {
jvmToolchain(21)
}

View File

@@ -1,25 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="false"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="false">
<!-- Fill when Meta DAT Developer Preview app registration is available. -->
<meta-data
android:name="com.meta.wearable.mwdat.ANALYTICS_OPT_OUT"
android:value="true" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -1,166 +0,0 @@
package com.ejclaw.android
import android.app.Activity
import android.os.Bundle
import android.widget.Toast
import com.ejclaw.android.api.EJClawApi
import com.ejclaw.android.display.DisplayBridge
import com.ejclaw.android.model.RoomActivity
import com.ejclaw.android.model.RoomSummary
import com.ejclaw.android.ui.EJClawView
import java.util.concurrent.Executors
class MainActivity : Activity() {
private val executor = Executors.newSingleThreadExecutor()
private val displayBridge = DisplayBridge()
private lateinit var view: EJClawView
private var api: EJClawApi? = null
private var selectedRoom: RoomSummary? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
view = EJClawView(this)
setContentView(view.root)
loadPrefs()
bindActions()
}
override fun onDestroy() {
executor.shutdownNow()
super.onDestroy()
}
private fun bindActions() {
view.connectButton.setOnClickListener { connectAndLoadRooms() }
view.refreshButton.setOnClickListener { loadRooms() }
view.sendButton.setOnClickListener { sendMessage() }
view.roomsList.setOnItemClickListener { _, _, position, _ ->
selectedRoom = view.roomsAdapter.getItem(position)
selectedRoom?.let { loadRoom(it) }
}
}
private fun loadPrefs() {
val prefs = getPreferences(MODE_PRIVATE)
view.baseUrlInput.setText(prefs.getString("baseUrl", "http://100.101.210.95:8734"))
view.tokenInput.setText(prefs.getString("token", ""))
view.nicknameInput.setText(prefs.getString("nickname", "android"))
}
private fun savePrefs() {
getPreferences(MODE_PRIVATE).edit()
.putString("baseUrl", view.baseUrlInput.text.toString().trim())
.putString("token", view.tokenInput.text.toString())
.putString("nickname", view.nicknameInput.text.toString().trim())
.apply()
}
private fun connectAndLoadRooms() {
savePrefs()
api = EJClawApi(
view.baseUrlInput.text.toString(),
view.tokenInput.text.toString(),
)
runNetwork("Connecting") {
requireNotNull(api).health()
requireNotNull(api).rooms()
}.onSuccess { rooms ->
view.statusView.text = "Connected: ${rooms.size} rooms"
replaceRooms(rooms)
}
}
private fun loadRooms() {
runNetwork("Loading rooms") {
requireNotNull(api ?: createApi()).rooms()
}.onSuccess { rooms ->
view.statusView.text = "Loaded: ${rooms.size} rooms"
replaceRooms(rooms)
}
}
private fun loadRoom(room: RoomSummary) {
runNetwork("Loading ${room.name}") {
requireNotNull(api ?: createApi()).roomTimeline(room.jid)
}.onSuccess { activity ->
renderRoom(activity)
displayBridge.updateRoom(activity.summary.name, activity.summary.status, null)
displayBridge.showLatest(activity.summary.name, activity.summary.latestText)
}
}
private fun sendMessage() {
val room = selectedRoom ?: return toast("Select a room first")
val text = view.messageInput.text.toString().trim()
if (text.isBlank()) return
runNetwork("Sending") {
requireNotNull(api ?: createApi()).sendRoomMessage(
room.jid,
text,
view.nicknameInput.text.toString(),
)
requireNotNull(api).roomTimeline(room.jid)
}.onSuccess { activity ->
view.messageInput.setText("")
renderRoom(activity)
}
}
private fun createApi(): EJClawApi {
savePrefs()
val next = EJClawApi(view.baseUrlInput.text.toString(), view.tokenInput.text.toString())
api = next
return next
}
private fun replaceRooms(rooms: List<RoomSummary>) {
view.roomsAdapter.clear()
view.roomsAdapter.addAll(rooms)
view.roomsAdapter.notifyDataSetChanged()
}
private fun renderRoom(activity: RoomActivity) {
val lines = activity.messages.takeLast(40).joinToString("\n\n") { message ->
val marker = if (message.fromMe) "me" else message.senderName.ifBlank { "agent" }
"[$marker] ${message.content}"
}
view.threadView.text = lines.ifBlank { "No messages" }
view.statusView.text = "${activity.summary.name}: ${activity.summary.status}"
}
private fun <T> runNetwork(label: String, block: () -> T): PendingUi<T> {
view.statusView.text = label
val pending = PendingUi<T>()
executor.execute {
try {
val result = block()
runOnUiThread { pending.succeed(result) }
} catch (error: Throwable) {
runOnUiThread {
view.statusView.text = "Error: ${error.message}"
toast(error.message ?: "Request failed")
}
}
}
return pending
}
private fun toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
private class PendingUi<T> {
private var callback: ((T) -> Unit)? = null
private var result: T? = null
fun onSuccess(next: (T) -> Unit) {
callback = next
result?.let(next)
}
fun succeed(value: T) {
result = value
callback?.invoke(value)
}
}

View File

@@ -1,104 +0,0 @@
package com.ejclaw.android.api
import com.ejclaw.android.model.RoomActivity
import com.ejclaw.android.model.RoomMessage
import com.ejclaw.android.model.RoomSummary
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.UUID
import org.json.JSONObject
class EJClawApi(
baseUrl: String,
private val token: String,
) {
private val baseUrl = baseUrl.trim().trimEnd('/')
fun health(): Boolean {
val payload = request("GET", "/api/health")
return JSONObject(payload).optBoolean("ok", false)
}
fun rooms(): List<RoomSummary> {
val payload = request("GET", "/api/rooms-timeline")
val root = JSONObject(payload)
return root.keys().asSequence().mapNotNull { key ->
root.optJSONObject(key)?.let { parseRoomSummary(it) }
}.sortedBy { it.name.lowercase() }.toList()
}
fun roomTimeline(jid: String): RoomActivity {
val payload = request("GET", "/api/rooms/${encode(jid)}/timeline")
val room = JSONObject(payload)
val messages = room.optJSONArray("messages") ?: return RoomActivity(parseRoomSummary(room), emptyList())
return RoomActivity(
parseRoomSummary(room),
(0 until messages.length()).mapNotNull { index ->
messages.optJSONObject(index)?.let { message ->
RoomMessage(
senderName = message.optString("senderName", message.optString("sender", "")),
content = message.optString("content", ""),
timestamp = message.optString("timestamp", ""),
fromMe = message.optBoolean("isFromMe", false),
)
}
},
)
}
fun sendRoomMessage(jid: String, text: String, nickname: String): Boolean {
val body = JSONObject()
.put("requestId", UUID.randomUUID().toString())
.put("text", text)
.put("nickname", nickname.ifBlank { "android" })
val payload = request("POST", "/api/rooms/${encode(jid)}/messages", body.toString())
return JSONObject(payload).optBoolean("ok", false)
}
private fun parseRoomSummary(room: JSONObject): RoomSummary {
val messages = room.optJSONArray("messages")
val latest = if (messages != null && messages.length() > 0) {
messages.optJSONObject(messages.length() - 1)?.optString("content", "") ?: ""
} else {
""
}
return RoomSummary(
jid = room.optString("jid"),
name = room.optString("name", room.optString("jid")),
status = room.optString("status", "unknown"),
latestText = latest.take(120),
)
}
private fun request(method: String, path: String, body: String? = null): String {
val connection = URL("$baseUrl$path").openConnection() as HttpURLConnection
connection.requestMethod = method
connection.connectTimeout = 8_000
connection.readTimeout = 12_000
connection.setRequestProperty("Accept", "application/json")
if (token.isNotBlank()) connection.setRequestProperty("Authorization", "Bearer $token")
if (body != null) {
val bytes = body.toByteArray(Charsets.UTF_8)
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json")
connection.setRequestProperty("Content-Length", bytes.size.toString())
connection.outputStream.use { it.write(bytes) }
}
val status = connection.responseCode
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
val response = stream?.use {
BufferedReader(InputStreamReader(it, Charsets.UTF_8)).readText()
} ?: ""
connection.disconnect()
if (status !in 200..299) {
val message = response.ifBlank { "HTTP $status" }
throw IllegalStateException(message)
}
return response
}
private fun encode(value: String): String =
java.net.URLEncoder.encode(value, Charsets.UTF_8.name()).replace("+", "%20")
}

View File

@@ -1,13 +0,0 @@
package com.ejclaw.android.display
class DisplayBridge(
private val surface: DisplaySurface = NoopDisplaySurface(),
) {
fun updateRoom(roomName: String, status: String, progress: String?) {
surface.showStatus(roomName, status, progress)
}
fun showLatest(roomName: String, text: String) {
if (text.isNotBlank()) surface.showMessage(roomName, text)
}
}

View File

@@ -1,6 +0,0 @@
package com.ejclaw.android.display
interface DisplaySurface {
fun showStatus(roomName: String, state: String, progress: String?)
fun showMessage(roomName: String, text: String)
}

View File

@@ -1,15 +0,0 @@
package com.ejclaw.android.display
/**
* Meta DAT integration point.
*
* Keep this class dependency-free until the Wearables Developer Center project,
* GitHub Packages token, and DAT application id are available. The phone app can
* validate EJClaw connectivity through NoopDisplaySurface first, then this class
* can be swapped to call the Meta SDK.
*/
class MetaDatDisplaySurface : DisplaySurface {
override fun showStatus(roomName: String, state: String, progress: String?) = Unit
override fun showMessage(roomName: String, text: String) = Unit
}

View File

@@ -1,16 +0,0 @@
package com.ejclaw.android.display
class NoopDisplaySurface : DisplaySurface {
var lastStatus: String = ""
private set
var lastMessage: String = ""
private set
override fun showStatus(roomName: String, state: String, progress: String?) {
lastStatus = listOfNotNull(roomName, state, progress).joinToString(" / ")
}
override fun showMessage(roomName: String, text: String) {
lastMessage = "$roomName: $text"
}
}

View File

@@ -1,25 +0,0 @@
package com.ejclaw.android.model
data class RoomSummary(
val jid: String,
val name: String,
val status: String,
val latestText: String,
) {
override fun toString(): String {
val suffix = if (latestText.isBlank()) "" else "\n$latestText"
return "$name [$status]$suffix"
}
}
data class RoomMessage(
val senderName: String,
val content: String,
val timestamp: String,
val fromMe: Boolean,
)
data class RoomActivity(
val summary: RoomSummary,
val messages: List<RoomMessage>,
)

View File

@@ -1,80 +0,0 @@
package com.ejclaw.android.ui
import android.app.Activity
import android.graphics.Typeface
import android.text.InputType
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.ScrollView
import android.widget.TextView
import com.ejclaw.android.model.RoomSummary
class EJClawView(
activity: Activity,
) {
val baseUrlInput = EditText(activity)
val tokenInput = EditText(activity)
val nicknameInput = EditText(activity)
val connectButton = Button(activity)
val refreshButton = Button(activity)
val sendButton = Button(activity)
val messageInput = EditText(activity)
val statusView = TextView(activity)
val threadView = TextView(activity)
val roomsAdapter = ArrayAdapter<RoomSummary>(activity, android.R.layout.simple_list_item_1)
val roomsList = ListView(activity)
val root: View
init {
baseUrlInput.hint = "http://100.101.210.95:8734"
baseUrlInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
tokenInput.hint = "WEB_DASHBOARD_TOKEN"
tokenInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
nicknameInput.hint = "nickname"
nicknameInput.inputType = InputType.TYPE_CLASS_TEXT
messageInput.hint = "message"
messageInput.minLines = 2
connectButton.text = "Connect"
refreshButton.text = "Refresh"
sendButton.text = "Send"
statusView.text = "Disconnected"
threadView.text = "Select a room"
threadView.setTypeface(Typeface.MONOSPACE)
roomsList.adapter = roomsAdapter
val controls = LinearLayout(activity).apply {
orientation = LinearLayout.VERTICAL
setPadding(24, 24, 24, 12)
addView(baseUrlInput)
addView(tokenInput)
addView(nicknameInput)
addView(LinearLayout(activity).apply {
orientation = LinearLayout.HORIZONTAL
addView(connectButton, LinearLayout.LayoutParams(0, -2, 1f))
addView(refreshButton, LinearLayout.LayoutParams(0, -2, 1f))
})
addView(statusView)
}
val scroll = ScrollView(activity).apply {
addView(threadView)
}
val sendRow = LinearLayout(activity).apply {
orientation = LinearLayout.HORIZONTAL
addView(messageInput, LinearLayout.LayoutParams(0, -2, 1f))
addView(sendButton)
}
root = LinearLayout(activity).apply {
orientation = LinearLayout.VERTICAL
addView(controls)
addView(roomsList, LinearLayout.LayoutParams(-1, 0, 1f))
addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f))
addView(sendRow)
}
}
}

View File

@@ -1,3 +0,0 @@
<resources>
<string name="app_name">EJClaw</string>
</resources>

View File

@@ -1,7 +0,0 @@
<resources>
<style name="AppTheme" parent="android:style/Theme.Material.Light.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:colorAccent">#2563EB</item>
</style>
</resources>

View File

@@ -1,6 +0,0 @@
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<!-- Personal Tailscale dashboard endpoint used by the debug APK. -->
<domain includeSubdomains="false">100.101.210.95</domain>
</domain-config>
</network-security-config>

View File

@@ -1,4 +0,0 @@
plugins {
id("com.android.application") version "8.13.0" apply false
id("org.jetbrains.kotlin.android") version "2.2.21" apply false
}

View File

@@ -1,3 +0,0 @@
android.useAndroidX=true
android.nonTransitiveRClass=true
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8

Binary file not shown.

View File

@@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
apps/android/gradlew vendored
View File

@@ -1,251 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@@ -1,94 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,7 +0,0 @@
## Copy to local.properties when building outside Android Studio.
## Do not commit local.properties.
sdk.dir=/home/ejclaw/android-sdk
## Optional later, when enabling Meta Wearables DAT dependencies.
## github_token=ghp_xxx
## meta_dat_application_id=your_meta_wearables_application_id

View File

@@ -1,18 +0,0 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "EJClawAndroid"
include(":app")

View File

@@ -1,22 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
/>
<meta name="theme-color" content="#2b3726" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="EJClaw" />
<meta name="mobile-web-app-capable" content="yes" />
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="icon" href="/icons/icon-192.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/icons/icon-192.png" />
<title>EJClaw Ops</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 861 B

View File

@@ -1,8 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="192" height="192" viewBox="0 0 192 192" role="img" aria-label="EJClaw">
<rect width="192" height="192" rx="46" fill="#2b3726" />
<path d="M39 122c18 21 47 29 81 17 18-6 30-18 36-35" fill="none" stroke="#f7edda" stroke-width="14" stroke-linecap="round" />
<path d="M50 78c16-24 45-36 76-25 13 5 24 13 32 25" fill="none" stroke="#bf5f2c" stroke-width="14" stroke-linecap="round" />
<circle cx="74" cy="94" r="11" fill="#f7edda" />
<circle cx="118" cy="94" r="11" fill="#f7edda" />
<path d="M88 126h21" stroke="#f7edda" stroke-width="10" stroke-linecap="round" />
</svg>

Before

Width:  |  Height:  |  Size: 627 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

View File

@@ -1,8 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" role="img" aria-label="EJClaw">
<rect width="512" height="512" rx="124" fill="#2b3726" />
<path d="M104 325c48 58 126 78 217 47 48-16 80-49 96-93" fill="none" stroke="#f7edda" stroke-width="38" stroke-linecap="round" />
<path d="M134 208c43-64 120-96 203-66 36 13 64 35 86 66" fill="none" stroke="#bf5f2c" stroke-width="38" stroke-linecap="round" />
<circle cx="198" cy="250" r="30" fill="#f7edda" />
<circle cx="314" cy="250" r="30" fill="#f7edda" />
<path d="M235 336h56" stroke="#f7edda" stroke-width="28" stroke-linecap="round" />
</svg>

Before

Width:  |  Height:  |  Size: 641 B

View File

@@ -1,27 +0,0 @@
{
"name": "EJClaw Ops",
"short_name": "EJClaw",
"description": "EJClaw operations console",
"start_url": "/",
"scope": "/",
"display": "standalone",
"display_override": ["window-controls-overlay", "standalone", "browser"],
"background_color": "#f3efe4",
"theme_color": "#2b3726",
"orientation": "portrait-primary",
"categories": ["productivity", "utilities"],
"icons": [
{
"src": "/icons/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/icons/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
}

View File

@@ -1,87 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
/>
<meta name="theme-color" content="#2b3726" />
<title>EJClaw Offline</title>
<style>
:root {
color-scheme: light;
font-family:
Avenir Next,
Segoe UI Variable,
Noto Sans KR,
ui-sans-serif,
sans-serif;
background: #f3efe4;
color: #1c211c;
}
body {
display: grid;
min-height: 100vh;
margin: 0;
place-items: center;
background:
radial-gradient(
circle at 20% 18%,
rgba(191, 95, 44, 0.2),
transparent 26rem
),
linear-gradient(135deg, #f4ead5, #edf1df);
}
main {
width: min(420px, calc(100% - 32px));
padding: 24px;
border: 1px solid rgba(43, 55, 38, 0.16);
border-radius: 28px;
background: rgba(255, 250, 240, 0.86);
box-shadow: 0 24px 70px rgba(44, 39, 25, 0.16);
}
span {
color: #8f351b;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 8px 0;
font-size: 30px;
letter-spacing: -0.05em;
}
p {
margin: 0 0 18px;
color: #6d735f;
line-height: 1.45;
}
button {
min-height: 44px;
padding: 0 18px;
border: 0;
border-radius: 999px;
color: #fffaf0;
background: linear-gradient(135deg, #bf5f2c, #8f351b);
font: inherit;
font-weight: 900;
}
</style>
</head>
<body>
<main>
<span>EJClaw</span>
<h1>Offline</h1>
<p>네트워크가 복구되면 대시보드를 다시 불러옵니다.</p>
<button type="button" onclick="window.location.reload()">Retry</button>
</main>
</body>
</html>

View File

@@ -1,78 +0,0 @@
const CACHE_NAME = 'ejclaw-dashboard-v1';
const PRECACHE_URLS = [
'/',
'/index.html',
'/offline.html',
'/manifest.webmanifest',
'/icons/icon-192.png',
'/icons/icon-512.png',
'/icons/icon-192.svg',
'/icons/icon-512.svg',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) => cache.addAll(PRECACHE_URLS))
.then(() => self.skipWaiting()),
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key)),
),
)
.then(() => self.clients.claim()),
);
});
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
if (request.method !== 'GET' || url.origin !== self.location.origin) {
return;
}
if (url.pathname.startsWith('/api/')) {
event.respondWith(fetch(request));
return;
}
if (request.mode === 'navigate') {
event.respondWith(
fetch(request)
.then((response) => {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put('/', copy));
return response;
})
.catch(() =>
caches
.match('/')
.then((cached) => cached || caches.match('/offline.html')),
),
);
return;
}
event.respondWith(
caches.match(request).then((cached) => {
if (cached) return cached;
return fetch(request).then((response) => {
if (!response.ok) return response;
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy));
return response;
});
}),
);
});

View File

@@ -1,683 +0,0 @@
import { useEffect, useState } from 'react';
import {
type CreateScheduledTaskInput,
type DashboardRoomActivity,
type DashboardTaskAction,
type DashboardOverview,
type DashboardTask,
type UpdateScheduledTaskInput,
type StatusSnapshot,
createScheduledTask,
fetchDashboardData,
runServiceAction,
runScheduledTaskAction,
sendRoomMessage,
updateScheduledTask,
} from './api';
import {
isLocale,
localeTags,
matchLocale,
messages,
type Locale,
type Messages,
} from './i18n';
import { useSelectedRoomActivity } from './useRoomActivity';
import {
SectionNav,
SideRail,
type DashboardFreshness,
type DashboardView,
} from './DashboardNav';
import { formatDate, statusLabel } from './dashboardHelpers';
import { RoomBoardV2 } from './RoomBoardV2';
import { SettingsPanel } from './SettingsPanel';
import { SystemStatusStrip } from './SystemStatusStrip';
import { TaskPanel, type RoomOption, type TaskActionKey } from './TaskPanel';
import { UsagePanel } from './UsagePanel';
import './styles.css';
interface DashboardState {
overview: DashboardOverview;
snapshots: StatusSnapshot[];
tasks: DashboardTask[];
}
type FreshnessLevel = DashboardFreshness;
const REFRESH_INTERVAL_MS = 15_000;
const LOCALE_STORAGE_KEY = 'ejclaw.dashboard.locale.v2';
const DEFAULT_VIEW: DashboardView = 'rooms';
const DASHBOARD_STALE_MS = 75_000;
function makeClientRequestId(): string {
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
function isDashboardView(
value: string | null | undefined,
): value is DashboardView {
return (
value === 'usage' ||
value === 'rooms' ||
value === 'scheduled' ||
value === 'settings'
);
}
function readViewFromHash(): DashboardView {
if (typeof window === 'undefined') return DEFAULT_VIEW;
const raw = window.location.hash.replace(/^#\/?/, '');
return isDashboardView(raw) ? raw : DEFAULT_VIEW;
}
function normalizeDashboardHash(view: DashboardView): void {
if (typeof window === 'undefined') return;
const raw = window.location.hash.replace(/^#\/?/, '');
if (!raw || isDashboardView(raw)) return;
window.history.replaceState(null, '', `#/${view}`);
}
function readInitialLocale(): Locale {
const stored =
typeof window === 'undefined'
? null
: window.localStorage.getItem(LOCALE_STORAGE_KEY);
if (isLocale(stored)) return stored;
const languages =
typeof navigator === 'undefined'
? []
: [...(navigator.languages || []), navigator.language];
for (const language of languages) {
const matched = matchLocale(language);
if (matched) return matched;
}
return 'en';
}
function persistNickname(trimmed: string): void {
if (typeof window === 'undefined') return;
if (trimmed) window.localStorage.setItem('ejclaw-nickname', trimmed);
else window.localStorage.removeItem('ejclaw-nickname');
}
function humanizeError(raw: string, t: Messages): string {
const lower = raw.toLowerCase();
if (/abort|timeout|timed out/.test(lower)) return t.error.timeout;
if (/network|fetch failed|failed to fetch|networkerror|offline/.test(lower))
return t.error.network;
const statusMatch = lower.match(/\b(\d{3})\b/);
if (statusMatch) {
const code = Number(statusMatch[1]);
if (code === 401 || code === 403) return t.error.auth;
if (code === 404) return t.error.notFound;
if (code >= 500) return t.error.server;
if (code >= 400) return t.error.unknown;
}
return raw || t.error.unknown;
}
function senderRoleClass(value: string | null | undefined): string {
const v = (value ?? '').toLowerCase();
if (v.includes('오너') || v.includes('owner')) return 'role-owner';
if (v.includes('리뷰어') || v.includes('reviewer')) return 'role-reviewer';
if (v.includes('중재자') || v.includes('arbiter')) return 'role-arbiter';
if (v.includes('cron') || v.includes('sentry') || v.includes('webhook'))
return 'role-cron';
return 'role-human';
}
function dashboardAgeMs(value: string | null | undefined): number | null {
if (!value) return null;
const date = new Date(value);
if (Number.isNaN(date.getTime())) return null;
return Math.max(0, Date.now() - date.getTime());
}
function dashboardFreshness(
online: boolean,
generatedAt: string | null | undefined,
): FreshnessLevel {
if (!online) return 'offline';
const age = dashboardAgeMs(generatedAt);
if (age !== null && age > DASHBOARD_STALE_MS) return 'stale';
return 'fresh';
}
function freshnessLabel(level: FreshnessLevel, t: Messages): string {
if (level === 'offline') return t.pwa.offline;
if (level === 'stale') return t.pwa.stale;
return t.pwa.fresh;
}
function canUsePwaCore(): boolean {
return (
typeof window !== 'undefined' &&
window.isSecureContext &&
'serviceWorker' in navigator
);
}
function formatDuration(value: number | null, t: Messages): string {
if (value === null) return '-';
const seconds = Math.floor(value / 1000);
if (seconds < 60) return `${seconds}${t.units.second}`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}${t.units.minute}`;
const hours = Math.floor(minutes / 60);
return `${hours}${t.units.hour} ${minutes % 60}${t.units.minute}`;
}
function formatLiveElapsed(value: number, t: Messages): string {
const seconds = Math.max(0, Math.floor(value / 1000));
if (seconds < 60) return `${seconds}${t.units.second}`;
const minutes = Math.floor(seconds / 60);
const remSec = seconds % 60;
if (minutes < 60)
return `${minutes}${t.units.minute} ${remSec}${t.units.second}`;
const hours = Math.floor(minutes / 60);
const remMin = minutes % 60;
return `${hours}${t.units.hour} ${remMin}${t.units.minute} ${remSec}${t.units.second}`;
}
const ROOM_BOARD_FORMATTERS = {
formatDate,
formatDuration,
formatLiveElapsed,
senderRoleClass,
statusLabel,
};
function buildRoomOptions(snapshots: StatusSnapshot[]): RoomOption[] {
const rooms = new Map<string, RoomOption>();
for (const snapshot of snapshots) {
for (const entry of snapshot.entries) {
if (!rooms.has(entry.jid)) {
rooms.set(entry.jid, {
jid: entry.jid,
name: entry.name || entry.folder || entry.jid,
folder: entry.folder,
});
}
}
}
return Array.from(rooms.values()).sort((a, b) =>
`${a.name} ${a.folder}`.localeCompare(`${b.name} ${b.folder}`),
);
}
function LoadingSkeleton({ t }: { t: Messages }) {
return (
<main className="shell shell-loading" aria-busy="true">
<section className="section-nav skeleton-topbar">
<span className="skeleton-button" />
<span className="skeleton-line skeleton-copy" />
<span className="skeleton-button" />
</section>
<section className="skeleton-grid" aria-label={t.app.loading}>
{Array.from({ length: 4 }, (_, index) => (
<div className="card skeleton-card" key={index}>
<span className="skeleton-line skeleton-short" />
<span className="skeleton-line skeleton-number" />
<span className="skeleton-line skeleton-copy" />
</div>
))}
</section>
</main>
);
}
function DashboardErrorCard({
error,
onRetry,
refreshing,
t,
}: {
error: string;
onRetry: () => void;
refreshing: boolean;
t: Messages;
}) {
return (
<section className="error-card" role="alert" aria-live="polite">
<span>
<strong>{t.error.api}</strong>
<small>{humanizeError(error, t)}</small>
</span>
<button disabled={refreshing} onClick={onRetry} type="button">
{t.actions.retry}
</button>
</section>
);
}
function App() {
const [data, setData] = useState<DashboardState | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [drawerOpen, setDrawerOpen] = useState(false);
const [activeView, setActiveView] = useState<DashboardView>(readViewFromHash);
const [locale, setLocale] = useState<Locale>(readInitialLocale);
const [online, setOnline] = useState(() =>
typeof navigator === 'undefined' ? true : navigator.onLine,
);
const [taskActionKey, setTaskActionKey] = useState<TaskActionKey | null>(
null,
);
const [serviceRestarting, setServiceRestarting] = useState(false);
const [roomMessageKey, setRoomMessageKey] = useState<string | null>(null);
const [selectedRoomJid, setSelectedRoomJid] = useState<string | null>(null);
const {
refreshRoom: refreshRoomActivity,
roomActivity,
roomActivityLoading,
} = useSelectedRoomActivity({
active: activeView === 'rooms',
selectedRoomJid: selectedRoomJid,
});
const [pendingMessages, setPendingMessages] = useState<
Record<string, Array<DashboardRoomActivity['messages'][number]>>
>({});
const [nickname, setNicknameState] = useState<string>(() => {
if (typeof window === 'undefined') return '';
return window.localStorage.getItem('ejclaw-nickname') ?? '';
});
function setNickname(next: string) {
const trimmed = next.trim().slice(0, 32);
setNicknameState(trimmed);
persistNickname(trimmed);
}
const t = messages[locale];
function setDashboardLocale(nextLocale: Locale) {
setLocale(nextLocale);
window.localStorage.setItem(LOCALE_STORAGE_KEY, nextLocale);
}
function navigateToView(view: DashboardView) {
setActiveView(view);
if (window.location.hash !== `#/${view}`) {
window.location.hash = `/${view}`;
}
}
async function refresh(showSpinner = false) {
if (showSpinner) setRefreshing(true);
try {
const nextData = await fetchDashboardData();
setData(nextData);
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
setRefreshing(false);
}
}
async function handleTaskAction(
task: DashboardTask,
action: DashboardTaskAction,
) {
if (action === 'cancel' && !window.confirm(t.tasks.actions.confirmCancel)) {
return;
}
const actionKey: TaskActionKey = `${task.id}:${action}`;
setTaskActionKey(actionKey);
try {
await runScheduledTaskAction(task.id, action);
await refresh(false);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setTaskActionKey(null);
}
}
async function handleTaskCreate(input: CreateScheduledTaskInput) {
setTaskActionKey('create');
try {
await createScheduledTask({ ...input, requestId: makeClientRequestId() });
await refresh(false);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setTaskActionKey(null);
}
}
async function handleTaskUpdate(
task: DashboardTask,
input: UpdateScheduledTaskInput,
) {
const actionKey: TaskActionKey = `${task.id}:edit`;
setTaskActionKey(actionKey);
try {
await updateScheduledTask(task.id, input);
await refresh(false);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setTaskActionKey(null);
}
}
async function handleServiceRestart() {
if (
typeof window !== 'undefined' &&
!window.confirm(t.health.confirmRestart)
) {
return;
}
setServiceRestarting(true);
try {
await runServiceAction('stack', 'restart', {
requestId: makeClientRequestId(),
});
await refresh(false);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setServiceRestarting(false);
}
}
async function handleRoomMessage(
roomJid: string,
text: string,
requestId: string,
) {
setRoomMessageKey(roomJid);
const optimisticId = `opt:${requestId}`;
const displayName = nickname || 'Web Dashboard';
const optimisticMsg = {
id: optimisticId,
sender: 'me',
senderName: displayName,
content: text,
timestamp: new Date().toISOString(),
isFromMe: true,
isBotMessage: false,
sourceKind: 'human' as const,
};
setPendingMessages((prev) => ({
...prev,
[roomJid]: [...(prev[roomJid] ?? []), optimisticMsg],
}));
try {
await sendRoomMessage(roomJid, text, requestId, nickname || null);
try {
await refreshRoomActivity(roomJid);
} catch {
/* refresh will retry on next poll */
}
void refresh(false);
return true;
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
setPendingMessages((prev) => {
const list = prev[roomJid];
if (!list) return prev;
const next = list.filter((m) => m.id !== optimisticId);
if (next.length === 0) {
const { [roomJid]: _drop, ...rest } = prev;
void _drop;
return rest;
}
return { ...prev, [roomJid]: next };
});
return false;
} finally {
setRoomMessageKey(null);
}
}
useEffect(() => {
document.documentElement.lang = localeTags[locale];
}, [locale]);
useEffect(() => {
const debug =
typeof window !== 'undefined' &&
/[?&]debug=1/.test(window.location.search);
document.body.classList.toggle('debug-outlines', debug);
if (
typeof window !== 'undefined' &&
/[?&]measure=1/.test(window.location.search)
) {
const tick = () => {
const sels = [
'.rooms-detail .room-card-v2',
'.room-card-head',
'.room-thread-section',
'.room-section.room-compose-section',
];
const out = sels
.map((s) => {
const el = document.querySelector(s);
if (!el) return `${s}: NOT FOUND`;
const r = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return `${s}:\n x=${Math.round(r.x)} w=${Math.round(r.width)}\n display=${cs.display} pl=${cs.paddingLeft} ml=${cs.marginLeft}`;
})
.join('\n');
let pre = document.getElementById('__measure');
if (!pre) {
pre = document.createElement('pre');
pre.id = '__measure';
pre.style.cssText =
'position:fixed;top:0;left:0;background:#fff;color:#000;font:11px monospace;padding:8px;z-index:99999;max-width:520px;white-space:pre;line-height:1.4;';
document.body.appendChild(pre);
}
pre.textContent = out;
};
const id = window.setTimeout(tick, 1500);
return () => window.clearTimeout(id);
}
return undefined;
});
useEffect(() => {
function handleOnline() {
setOnline(true);
}
function handleOffline() {
setOnline(false);
}
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
useEffect(() => {
if (!import.meta.env.PROD || !canUsePwaCore()) return;
void navigator.serviceWorker.register('/sw.js').catch(() => {
/* ignore registration failures */
});
}, []);
useEffect(() => {
function handleHashChange() {
const nextView = readViewFromHash();
setActiveView(nextView);
normalizeDashboardHash(nextView);
}
handleHashChange();
window.addEventListener('hashchange', handleHashChange);
return () => window.removeEventListener('hashchange', handleHashChange);
}, []);
useEffect(() => {
void refresh();
const id = window.setInterval(() => {
void refresh();
}, REFRESH_INTERVAL_MS);
return () => window.clearInterval(id);
}, []);
useEffect(() => {
setPendingMessages((prev) => {
const next: typeof prev = {};
let changed = false;
for (const [jid, list] of Object.entries(prev)) {
const fetched = roomActivity[jid]?.messages ?? [];
const confirmedKeys = new Set(
fetched.map((m) => `${m.senderName}${m.content}`),
);
const remaining = list.filter(
(m) => !confirmedKeys.has(`${m.senderName}${m.content}`),
);
if (remaining.length !== list.length) changed = true;
if (remaining.length > 0) next[jid] = remaining;
}
return changed ? next : prev;
});
}, [roomActivity]);
useEffect(() => {
if (!drawerOpen) return;
function handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') setDrawerOpen(false);
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [drawerOpen]);
if (loading && !data) {
return <LoadingSkeleton t={t} />;
}
const roomOptions = data ? buildRoomOptions(data.snapshots) : [];
const freshness = dashboardFreshness(online, data?.overview.generatedAt);
return (
<div className="shell">
<SideRail
activeView={activeView}
data={data}
onNavigate={navigateToView}
t={t}
/>
<main className="dashboard-content">
<SectionNav
activeView={activeView}
data={data}
drawerOpen={drawerOpen}
freshness={freshness}
freshnessText={freshnessLabel(freshness, t)}
onCloseDrawer={() => setDrawerOpen(false)}
onNavigate={navigateToView}
onOpenDrawer={() => setDrawerOpen(true)}
onRefresh={() => void refresh(true)}
refreshing={refreshing}
t={t}
/>
{error ? (
<DashboardErrorCard
error={error}
onRetry={() => void refresh(true)}
refreshing={refreshing}
t={t}
/>
) : null}
{data ? (
<div className={`view-stack view-${activeView}`}>
{activeView === 'usage' ? (
<section className="panel usage-first" id="usage">
<div className="panel-title">
<h2>{t.panels.usage}</h2>
<span>{t.panels.usageWindow}</span>
</div>
<UsagePanel overview={data.overview} t={t} />
</section>
) : null}
{activeView === 'rooms' ? (
<section className="panel view-panel" id="rooms">
<div className="panel-title">
<h2>{t.panels.rooms}</h2>
<span>{t.panels.queue}</span>
</div>
<SystemStatusStrip overview={data.overview} t={t} />
<RoomBoardV2
{...ROOM_BOARD_FORMATTERS}
createRequestId={makeClientRequestId}
inbox={data.overview.inbox}
locale={locale}
onSelectedJidChange={setSelectedRoomJid}
onSendRoomMessage={handleRoomMessage}
pendingMessages={pendingMessages}
roomActivity={roomActivity}
roomActivityLoading={roomActivityLoading}
roomMessageKey={roomMessageKey}
selectedJid={selectedRoomJid}
snapshots={data.snapshots}
t={t}
/>
</section>
) : null}
{activeView === 'scheduled' ? (
<section className="panel view-panel" id="scheduled">
<div className="panel-title">
<h2>{t.panels.scheduled}</h2>
</div>
<TaskPanel
locale={locale}
onTaskAction={(task, action) =>
void handleTaskAction(task, action)
}
onTaskCreate={(input) => void handleTaskCreate(input)}
onTaskUpdate={(task, input) =>
void handleTaskUpdate(task, input)
}
rooms={roomOptions}
taskActionKey={taskActionKey}
tasks={data.tasks}
t={t}
/>
</section>
) : null}
{activeView === 'settings' ? (
<section className="panel view-panel" id="settings">
<div className="panel-title">
<h2>{t.settings.title}</h2>
</div>
<SettingsPanel
locale={locale}
nickname={nickname}
onLocaleChange={setDashboardLocale}
onNicknameChange={setNickname}
onRestartStack={() => {
if (!serviceRestarting) void handleServiceRestart();
}}
t={t}
/>
</section>
) : null}
</div>
) : null}
</main>
</div>
);
}
export default App;

View File

@@ -1,245 +0,0 @@
import { type ReactNode } from 'react';
import { Clock, Gauge, MessageSquare, Settings } from 'lucide-react';
import { type DashboardOverview, type StatusSnapshot } from './api';
import { type Messages } from './i18n';
export type DashboardView = 'usage' | 'rooms' | 'scheduled' | 'settings';
export type DashboardFreshness = 'fresh' | 'stale' | 'offline';
interface DashboardNavData {
overview: DashboardOverview;
snapshots: StatusSnapshot[];
}
const NAV_ICONS: Record<DashboardView, ReactNode> = {
usage: <Gauge size={20} strokeWidth={2} aria-hidden />,
rooms: <MessageSquare size={20} strokeWidth={2} aria-hidden />,
scheduled: <Clock size={20} strokeWidth={2} aria-hidden />,
settings: <Settings size={20} strokeWidth={2} aria-hidden />,
};
function navItems(t: Messages) {
return [
{ href: '#/rooms', label: t.nav.rooms, view: 'rooms' as const },
{ href: '#/scheduled', label: t.nav.scheduled, view: 'scheduled' as const },
{ href: '#/usage', label: t.nav.usage, view: 'usage' as const },
{ href: '#/settings', label: t.nav.settings, view: 'settings' as const },
];
}
function navStats(data: DashboardNavData | null) {
if (!data) return null;
const queue = data.snapshots.reduce(
(acc, snapshot) => {
for (const entry of snapshot.entries) {
if (entry.status === 'processing') acc.processing += 1;
}
return acc;
},
{ processing: 0 },
);
return {
processing: queue.processing,
};
}
function navBadge(
view: DashboardView,
stats: ReturnType<typeof navStats>,
): number | null {
if (view === 'rooms' && stats && stats.processing > 0) {
return stats.processing;
}
return null;
}
function DashboardBrandLink({
onNavigate,
}: {
onNavigate: (view: DashboardView) => void;
}) {
return (
<a
className="rail-brand"
href="#/rooms"
onClick={() => onNavigate('rooms')}
title="EJClaw"
>
EJ
</a>
);
}
function DashboardNavLinks({
activeView,
data,
onAfterNavigate,
onNavigate,
t,
}: {
activeView: DashboardView;
data: DashboardNavData | null;
onAfterNavigate?: () => void;
onNavigate: (view: DashboardView) => void;
t: Messages;
}) {
const stats = navStats(data);
return (
<nav className="rail-nav" aria-label={t.nav.drawerNavAria}>
{navItems(t).map((item) => {
const badge = navBadge(item.view, stats);
return (
<a
aria-current={activeView === item.view ? 'page' : undefined}
aria-label={item.label}
className={`rail-item${activeView === item.view ? ' is-active' : ''}`}
href={item.href}
key={item.href}
onClick={() => {
onNavigate(item.view);
onAfterNavigate?.();
}}
title={item.label}
>
<span className="rail-icon">{NAV_ICONS[item.view]}</span>
<span className="rail-label">{item.label}</span>
{badge !== null ? (
<span className="rail-badge">{badge}</span>
) : null}
</a>
);
})}
</nav>
);
}
export function SideRail({
activeView,
data,
onNavigate,
t,
}: {
activeView: DashboardView;
data: DashboardNavData | null;
onNavigate: (view: DashboardView) => void;
t: Messages;
}) {
return (
<aside className="side-rail icon-rail" aria-label={t.nav.drawerAria}>
<DashboardBrandLink onNavigate={onNavigate} />
<DashboardNavLinks
activeView={activeView}
data={data}
onNavigate={onNavigate}
t={t}
/>
</aside>
);
}
export function SectionNav({
activeView,
data,
drawerOpen,
freshness,
freshnessText,
onCloseDrawer,
onNavigate,
onOpenDrawer,
onRefresh,
refreshing,
t,
}: {
activeView: DashboardView;
data: DashboardNavData | null;
drawerOpen: boolean;
freshness: DashboardFreshness;
freshnessText: string;
onCloseDrawer: () => void;
onNavigate: (view: DashboardView) => void;
onOpenDrawer: () => void;
onRefresh: () => void;
refreshing: boolean;
t: Messages;
}) {
const activeLabel =
navItems(t).find((item) => item.view === activeView)?.label ?? t.nav.rooms;
const showManualRefresh = freshness !== 'fresh';
return (
<>
<nav className="section-nav" aria-label={t.nav.aria}>
<button
aria-controls="dashboard-menu"
aria-expanded={drawerOpen}
aria-label={drawerOpen ? t.nav.menuClose : t.nav.menuOpen}
className="menu-button"
onClick={drawerOpen ? onCloseDrawer : onOpenDrawer}
type="button"
>
<span />
<span />
<span />
</button>
<strong className="topbar-label">{activeLabel}</strong>
<span className={`topbar-status topbar-status-${freshness}`}>
{freshnessText}
</span>
{showManualRefresh ? (
<button
aria-busy={refreshing}
aria-label={refreshing ? t.actions.refreshing : t.actions.refresh}
className="refresh-button"
disabled={refreshing}
onClick={onRefresh}
type="button"
>
{refreshing ? '...' : t.actions.refresh}
</button>
) : null}
</nav>
{drawerOpen ? (
<>
<button
aria-label={t.nav.menuClose}
className="drawer-backdrop"
onClick={onCloseDrawer}
type="button"
/>
<aside
aria-label={t.nav.drawerAria}
aria-modal="true"
className="nav-drawer"
id="dashboard-menu"
role="dialog"
>
<div className="drawer-head">
<DashboardBrandLink onNavigate={onNavigate} />
<div className="drawer-title">
<span className="eyebrow">EJClaw</span>
<strong>{t.nav.operations}</strong>
</div>
<button
aria-label={t.nav.menuClose}
className="rail-btn drawer-close"
onClick={onCloseDrawer}
type="button"
>
{t.actions.close}
</button>
</div>
<DashboardNavLinks
activeView={activeView}
data={data}
onAfterNavigate={onCloseDrawer}
onNavigate={onNavigate}
t={t}
/>
</aside>
</>
) : null}
</>
);
}

View File

@@ -1,5 +0,0 @@
import type { ReactNode } from 'react';
export function EmptyState({ children }: { children: ReactNode }) {
return <div className="empty-state">{children}</div>;
}

View File

@@ -1,207 +0,0 @@
import { useEffect, useState } from 'react';
import {
type DashboardInboxAction,
type DashboardOverview,
type StatusSnapshot,
fetchDashboardData,
runInboxAction,
sendRoomMessage,
} from './api';
import { isLocale, matchLocale, type Locale } from './i18n';
import { GlassesPanel } from './GlassesPanel';
import './styles.css';
import './glasses.css';
interface GlassesState {
overview: DashboardOverview;
snapshots: StatusSnapshot[];
}
type InboxItem = DashboardOverview['inbox'][number];
type InboxActionKey = `${string}:${DashboardInboxAction}`;
const REFRESH_INTERVAL_MS = 15_000;
const DASHBOARD_STALE_MS = 75_000;
const LOCALE_STORAGE_KEY = 'ejclaw.dashboard.locale.v2';
function makeClientRequestId(): string {
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
function readInitialLocale(): Locale {
const stored =
typeof window === 'undefined'
? null
: window.localStorage.getItem(LOCALE_STORAGE_KEY);
if (isLocale(stored)) return stored;
const languages =
typeof navigator === 'undefined'
? []
: [...(navigator.languages || []), navigator.language];
for (const language of languages) {
const matched = matchLocale(language);
if (matched) return matched;
}
return 'en';
}
function dashboardAgeMs(value: string | null | undefined): number | null {
if (!value) return null;
const date = new Date(value);
if (Number.isNaN(date.getTime())) return null;
return Math.max(0, Date.now() - date.getTime());
}
function freshnessLabel(
online: boolean,
generatedAt: string | null | undefined,
): string {
if (!online) return 'offline';
const age = dashboardAgeMs(generatedAt);
if (age !== null && age > DASHBOARD_STALE_MS) return 'stale';
return 'fresh';
}
function readNickname(): string {
if (typeof window === 'undefined') return '';
return window.localStorage.getItem('ejclaw-nickname') ?? '';
}
export function GlassesApp() {
const [data, setData] = useState<GlassesState | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [online, setOnline] = useState(() =>
typeof navigator === 'undefined' ? true : navigator.onLine,
);
const [locale] = useState<Locale>(readInitialLocale);
const [inboxActionKey, setInboxActionKey] = useState<InboxActionKey | null>(
null,
);
const [roomMessageKey, setRoomMessageKey] = useState<string | null>(null);
async function refresh(showSpinner = false) {
if (showSpinner) setRefreshing(true);
try {
const nextData = await fetchDashboardData();
setData({
overview: nextData.overview,
snapshots: nextData.snapshots,
});
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
setRefreshing(false);
}
}
async function handleInboxAction(
item: InboxItem,
action: DashboardInboxAction,
) {
const actionKey: InboxActionKey = `${item.id}:${action}`;
setInboxActionKey(actionKey);
try {
await runInboxAction(item.id, action, {
lastOccurredAt: item.lastOccurredAt,
requestId: makeClientRequestId(),
});
await refresh(false);
return true;
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
return false;
} finally {
setInboxActionKey(null);
}
}
async function handleRoomMessage(
roomJid: string,
text: string,
requestId: string,
) {
setRoomMessageKey(roomJid);
try {
await sendRoomMessage(roomJid, text, requestId, readNickname() || null);
void refresh(false);
return true;
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
return false;
} finally {
setRoomMessageKey(null);
}
}
useEffect(() => {
document.documentElement.lang = locale;
}, [locale]);
useEffect(() => {
function handleOnline() {
setOnline(true);
}
function handleOffline() {
setOnline(false);
}
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
useEffect(() => {
void refresh();
const id = window.setInterval(() => {
void refresh();
}, REFRESH_INTERVAL_MS);
return () => window.clearInterval(id);
}, []);
if (loading && !data) {
return (
<main className="glasses-shell" aria-busy="true">
<div className="glasses-empty">
<strong>EJClaw</strong>
<span>Loading</span>
</div>
</main>
);
}
if (!data) {
return (
<main className="glasses-shell">
<p className="glasses-error">{error ?? 'Dashboard unavailable'}</p>
</main>
);
}
return (
<GlassesPanel
createRequestId={makeClientRequestId}
error={error}
freshnessText={freshnessLabel(online, data.overview.generatedAt)}
inboxActionKey={inboxActionKey}
locale={locale}
onInboxAction={handleInboxAction}
onRefresh={() => void refresh(true)}
onSendRoomMessage={handleRoomMessage}
overview={data.overview}
refreshing={refreshing}
roomMessageKey={roomMessageKey}
snapshots={data.snapshots}
/>
);
}

View File

@@ -1,120 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { GlassesPanel } from './GlassesPanel';
import type { DashboardOverview, StatusSnapshot } from './api';
const overview: DashboardOverview = {
generatedAt: '2026-06-07T13:00:00.000Z',
services: [],
rooms: {
total: 1,
active: 1,
waiting: 0,
inactive: 0,
},
tasks: {
total: 1,
active: 1,
paused: 0,
completed: 0,
watchers: {
active: 0,
paused: 0,
completed: 0,
},
},
usage: {
rows: [],
fetchedAt: null,
},
inbox: [
{
createdAt: '2026-06-07T12:59:30.000Z',
groupKey: 'task:review',
id: 'inbox-1',
kind: 'reviewer-request',
lastOccurredAt: '2026-06-07T12:59:30.000Z',
occurrences: 1,
occurredAt: '2026-06-07T12:59:30.000Z',
roomJid: 'dc:ops',
roomName: 'Ops',
severity: 'warn',
source: 'paired-task',
summary: 'Reviewer requested owner changes',
taskId: 'task-1',
taskStatus: 'active',
title: 'Review follow-up',
},
],
};
const snapshots: StatusSnapshot[] = [
{
agentType: 'codex',
assistantName: 'Codex',
serviceId: 'codex-main',
updatedAt: '2026-06-07T13:00:00.000Z',
entries: [
{
agentType: 'codex',
elapsedMs: 12000,
folder: 'ejclaw',
jid: 'dc:ops',
name: 'Ops',
pendingMessages: false,
pendingTasks: 1,
status: 'processing',
},
],
},
];
describe('GlassesPanel', () => {
it('renders a compact display queue and voice input surface', () => {
const html = renderToStaticMarkup(
createElement(GlassesPanel, {
createRequestId: () => 'req-1',
error: null,
freshnessText: 'fresh',
inboxActionKey: null,
locale: 'ko',
onInboxAction: async () => true,
onRefresh: () => {},
onSendRoomMessage: async () => true,
overview,
refreshing: false,
roomMessageKey: null,
snapshots,
}),
);
expect(html).toContain('glasses-shell');
expect(html).toContain('Review follow-up');
expect(html).toContain('리뷰');
expect(html).toContain('Voice');
});
it('tolerates partial status snapshot payloads while data is refreshing', () => {
const html = renderToStaticMarkup(
createElement(GlassesPanel, {
createRequestId: () => 'req-1',
error: null,
freshnessText: 'fresh',
inboxActionKey: null,
locale: 'ko',
onInboxAction: async () => true,
onRefresh: () => {},
onSendRoomMessage: async () => true,
overview,
refreshing: false,
roomMessageKey: null,
snapshots: [{} as StatusSnapshot],
}),
);
expect(html).toContain('glasses-shell');
expect(html).toContain('Review follow-up');
});
});

View File

@@ -1,607 +0,0 @@
import {
type KeyboardEvent,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Check, Inbox, Mic, RefreshCw, Send, X } from 'lucide-react';
import {
type DashboardInboxAction,
type DashboardOverview,
type StatusSnapshot,
} from './api';
import { formatDate } from './dashboardHelpers';
import type { Locale } from './i18n';
type InboxItem = DashboardOverview['inbox'][number];
type GlassesMode = 'queue' | 'voice';
interface RoomChoice {
jid: string;
label: string;
status: StatusSnapshot['entries'][number]['status'];
pendingTasks: number;
}
interface SpeechRecognitionResultLike {
readonly 0?: { transcript?: string };
}
interface SpeechRecognitionEventLike {
readonly results: ArrayLike<SpeechRecognitionResultLike>;
}
interface SpeechRecognitionLike {
continuous: boolean;
interimResults: boolean;
lang: string;
maxAlternatives: number;
onend: (() => void) | null;
onerror: (() => void) | null;
onresult: ((event: SpeechRecognitionEventLike) => void) | null;
start: () => void;
}
type SpeechRecognitionConstructor = new () => SpeechRecognitionLike;
interface SpeechWindow extends Window {
SpeechRecognition?: SpeechRecognitionConstructor;
webkitSpeechRecognition?: SpeechRecognitionConstructor;
}
export interface GlassesPanelProps {
createRequestId: () => string;
error: string | null;
freshnessText: string;
inboxActionKey: `${string}:${DashboardInboxAction}` | null;
locale: Locale;
onInboxAction: (
item: InboxItem,
action: DashboardInboxAction,
) => Promise<boolean>;
onRefresh: () => void;
onSendRoomMessage: (
roomJid: string,
text: string,
requestId: string,
) => Promise<boolean>;
overview: DashboardOverview;
refreshing: boolean;
roomMessageKey: string | null;
snapshots: StatusSnapshot[];
}
const QUEUE_KIND_ORDER: Record<InboxItem['kind'], number> = {
approval: 0,
'reviewer-request': 1,
'arbiter-request': 2,
'ci-failure': 3,
mention: 4,
'pending-room': 5,
};
const SEVERITY_ORDER: Record<InboxItem['severity'], number> = {
error: 0,
warn: 1,
info: 2,
};
const SPEECH_LOCALES: Record<Locale, string> = {
en: 'en-US',
ja: 'ja-JP',
ko: 'ko-KR',
zh: 'zh-CN',
};
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
if (typeof window === 'undefined') return null;
const speechWindow = window as SpeechWindow;
return (
speechWindow.SpeechRecognition ??
speechWindow.webkitSpeechRecognition ??
null
);
}
function inboxActionsFor(item: InboxItem): DashboardInboxAction[] {
if (
item.source === 'paired-task' &&
(item.kind === 'reviewer-request' ||
item.kind === 'approval' ||
item.kind === 'arbiter-request')
) {
return ['run', 'decline', 'dismiss'];
}
return ['dismiss'];
}
function actionLabel(item: InboxItem, action: DashboardInboxAction): string {
if (action === 'dismiss') return '닫기';
if (action === 'decline') return '거절';
if (item.kind === 'approval') return '최종화';
if (item.kind === 'reviewer-request') return '리뷰';
if (item.kind === 'arbiter-request') return '중재';
return '실행';
}
function actionIcon(action: DashboardInboxAction) {
if (action === 'decline') return <X size={16} aria-hidden />;
if (action === 'dismiss') return <Check size={16} aria-hidden />;
return <Send size={16} aria-hidden />;
}
function sortInboxItems(items: InboxItem[]): InboxItem[] {
return [...items].sort((a, b) => {
const severity = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
if (severity !== 0) return severity;
const kind = QUEUE_KIND_ORDER[a.kind] - QUEUE_KIND_ORDER[b.kind];
if (kind !== 0) return kind;
return b.lastOccurredAt.localeCompare(a.lastOccurredAt);
});
}
function buildRoomChoices(snapshots: StatusSnapshot[]): RoomChoice[] {
const rooms = new Map<string, RoomChoice>();
for (const snapshot of snapshots) {
const entries = Array.isArray(snapshot.entries) ? snapshot.entries : [];
for (const entry of entries) {
const existing = rooms.get(entry.jid);
const label = entry.name || entry.folder || entry.jid;
if (!existing) {
rooms.set(entry.jid, {
jid: entry.jid,
label,
pendingTasks: entry.pendingTasks,
status: entry.status,
});
continue;
}
if (
entry.status === 'processing' ||
entry.pendingTasks > existing.pendingTasks
) {
rooms.set(entry.jid, {
jid: entry.jid,
label,
pendingTasks: entry.pendingTasks,
status: entry.status,
});
}
}
}
return [...rooms.values()].sort((a, b) => {
if (a.status === 'processing' && b.status !== 'processing') return -1;
if (b.status === 'processing' && a.status !== 'processing') return 1;
return b.pendingTasks - a.pendingTasks || a.label.localeCompare(b.label);
});
}
function clampIndex(index: number, length: number): number {
if (length <= 0) return 0;
return Math.max(0, Math.min(index, length - 1));
}
function nextIndex(index: number, length: number, delta: number): number {
if (length <= 0) return 0;
return (index + delta + length) % length;
}
function readTranscript(event: SpeechRecognitionEventLike): string {
return Array.from(event.results)
.map((result) => result[0]?.transcript?.trim() ?? '')
.filter(Boolean)
.join(' ')
.trim();
}
interface QueueCardProps {
inboxActionKey: `${string}:${DashboardInboxAction}` | null;
inboxActions: DashboardInboxAction[];
inboxItems: InboxItem[];
locale: Locale;
onInboxAction: (
item: InboxItem,
action: DashboardInboxAction,
) => Promise<boolean>;
selectedActionIndex: number;
selectedInbox: InboxItem | undefined;
selectedInboxIndex: number;
setSelectedActionIndex: (index: number) => void;
}
function QueueCard({
inboxActionKey,
inboxActions,
inboxItems,
locale,
onInboxAction,
selectedActionIndex,
selectedInbox,
selectedInboxIndex,
setSelectedActionIndex,
}: QueueCardProps) {
if (!selectedInbox) {
return (
<section className="glasses-card glasses-queue-card" aria-live="polite">
<div className="glasses-empty">
<strong>Queue clear</strong>
<span>새 요청 없음</span>
</div>
</section>
);
}
return (
<section className="glasses-card glasses-queue-card" aria-live="polite">
<div className="glasses-card-head">
<span className={`glasses-pill sev-${selectedInbox.severity}`}>
{selectedInbox.kind}
</span>
<small>
{selectedInboxIndex + 1}/{inboxItems.length}
</small>
</div>
<h2>{selectedInbox.title}</h2>
<p>{selectedInbox.summary}</p>
<dl className="glasses-meta">
<div>
<dt>Target</dt>
<dd>
{selectedInbox.roomName ??
selectedInbox.groupFolder ??
selectedInbox.roomJid ??
selectedInbox.taskId ??
'-'}
</dd>
</div>
<div>
<dt>Time</dt>
<dd>{formatDate(selectedInbox.lastOccurredAt, locale)}</dd>
</div>
</dl>
<div className="glasses-actions">
{inboxActions.map((action, index) => {
const actionKey = `${selectedInbox.id}:${action}`;
const busy = inboxActionKey === actionKey;
return (
<button
aria-busy={busy || undefined}
aria-pressed={index === selectedActionIndex}
className={
index === selectedActionIndex ? 'is-active' : undefined
}
disabled={busy || Boolean(inboxActionKey)}
key={action}
onClick={() => {
setSelectedActionIndex(index);
void onInboxAction(selectedInbox, action);
}}
type="button"
>
{actionIcon(action)}
{busy ? '처리 중' : actionLabel(selectedInbox, action)}
</button>
);
})}
</div>
</section>
);
}
interface VoiceCardProps {
canListen: boolean;
listening: boolean;
onSendVoiceText: () => void;
onStartListening: () => void;
selectedRoom: RoomChoice | undefined;
sendingVoice: boolean;
setSelectedRoomIndex: (index: number) => void;
setVoiceText: (value: string) => void;
rooms: RoomChoice[];
voiceText: string;
}
function VoiceCard({
canListen,
listening,
onSendVoiceText,
onStartListening,
selectedRoom,
sendingVoice,
setSelectedRoomIndex,
setVoiceText,
rooms,
voiceText,
}: VoiceCardProps) {
return (
<section className="glasses-card glasses-voice-card">
<div className="glasses-card-head">
<span className="glasses-pill">voice</span>
<small>{selectedRoom?.label ?? 'No room'}</small>
</div>
<textarea
aria-label="음성 또는 키보드 입력"
onChange={(event) => setVoiceText(event.target.value)}
placeholder="말하거나 입력..."
value={voiceText}
/>
<div className="glasses-room-strip" aria-label="room target">
{rooms.slice(0, 4).map((room, index) => (
<button
aria-pressed={room.jid === selectedRoom?.jid}
className={room.jid === selectedRoom?.jid ? 'is-active' : undefined}
key={room.jid}
onClick={() => setSelectedRoomIndex(index)}
type="button"
>
{room.label}
</button>
))}
</div>
<div className="glasses-actions">
<button
disabled={!canListen || listening}
onClick={onStartListening}
type="button"
>
<Mic size={16} aria-hidden />
{listening ? '듣는 중' : '말하기'}
</button>
<button
className="is-active"
disabled={!selectedRoom || !voiceText.trim() || sendingVoice}
onClick={onSendVoiceText}
type="button"
>
<Send size={16} aria-hidden />
{sendingVoice ? '전송 중' : '전송'}
</button>
</div>
</section>
);
}
interface GlassesHeaderProps {
onRefresh: () => void;
refreshing: boolean;
}
function GlassesHeader({ onRefresh, refreshing }: GlassesHeaderProps) {
return (
<header className="glasses-header">
<div>
<span className="glasses-kicker">EJClaw</span>
<h1>Display</h1>
</div>
<button
aria-busy={refreshing || undefined}
aria-label="새로고침"
className="glasses-icon-button"
disabled={refreshing}
onClick={onRefresh}
type="button"
>
<RefreshCw size={18} aria-hidden />
</button>
</header>
);
}
interface ModeTabsProps {
mode: GlassesMode;
setMode: (mode: GlassesMode) => void;
}
function ModeTabs({ mode, setMode }: ModeTabsProps) {
return (
<nav className="glasses-tabs" aria-label="display modes">
<button
aria-pressed={mode === 'queue'}
className={mode === 'queue' ? 'is-active' : undefined}
onClick={() => setMode('queue')}
type="button"
>
<Inbox size={16} aria-hidden />
Queue
</button>
<button
aria-pressed={mode === 'voice'}
className={mode === 'voice' ? 'is-active' : undefined}
onClick={() => setMode('voice')}
type="button"
>
<Mic size={16} aria-hidden />
Voice
</button>
</nav>
);
}
function footerStatus(
mode: GlassesMode,
busyActionKey: string | null,
selectedRoom: RoomChoice | undefined,
): string {
if (mode === 'queue') return busyActionKey ?? 'ready';
return selectedRoom?.status ?? 'ready';
}
export function GlassesPanel({
createRequestId,
error,
freshnessText,
inboxActionKey,
locale,
onInboxAction,
onRefresh,
onSendRoomMessage,
overview,
refreshing,
roomMessageKey,
snapshots,
}: GlassesPanelProps) {
const shellRef = useRef<HTMLElement | null>(null);
const [mode, setMode] = useState<GlassesMode>('queue');
const [selectedInboxIndex, setSelectedInboxIndex] = useState(0);
const [selectedActionIndex, setSelectedActionIndex] = useState(0);
const [selectedRoomIndex, setSelectedRoomIndex] = useState(0);
const [voiceText, setVoiceText] = useState('');
const [listening, setListening] = useState(false);
const inboxItems = useMemo(
() => sortInboxItems(Array.isArray(overview.inbox) ? overview.inbox : []),
[overview.inbox],
);
const rooms = useMemo(
() => buildRoomChoices(Array.isArray(snapshots) ? snapshots : []),
[snapshots],
);
const selectedInbox =
inboxItems[clampIndex(selectedInboxIndex, inboxItems.length)];
const inboxActions = selectedInbox ? inboxActionsFor(selectedInbox) : [];
const selectedAction =
inboxActions[clampIndex(selectedActionIndex, inboxActions.length)];
const selectedRoom = rooms[clampIndex(selectedRoomIndex, rooms.length)];
const canListen = getSpeechRecognition() !== null;
const busyActionKey =
selectedInbox && selectedAction
? `${selectedInbox.id}:${selectedAction}`
: null;
const sendingVoice = selectedRoom
? roomMessageKey === selectedRoom.jid
: false;
useEffect(() => {
shellRef.current?.focus();
}, []);
useEffect(() => {
setSelectedInboxIndex((value) => clampIndex(value, inboxItems.length));
}, [inboxItems.length]);
useEffect(() => {
setSelectedActionIndex((value) => clampIndex(value, inboxActions.length));
}, [inboxActions.length]);
useEffect(() => {
setSelectedRoomIndex((value) => clampIndex(value, rooms.length));
}, [rooms.length]);
function startListening() {
const SpeechRecognition = getSpeechRecognition();
if (!SpeechRecognition || listening) return;
const recognition = new SpeechRecognition();
recognition.lang = SPEECH_LOCALES[locale];
recognition.continuous = false;
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.onresult = (event) => {
const nextText = readTranscript(event);
if (nextText) setVoiceText(nextText);
};
recognition.onerror = () => setListening(false);
recognition.onend = () => setListening(false);
setListening(true);
recognition.start();
}
async function runSelectedAction() {
if (!selectedInbox || !selectedAction || inboxActionKey) return;
await onInboxAction(selectedInbox, selectedAction);
}
async function sendVoiceText() {
const text = voiceText.trim();
if (!selectedRoom || !text || sendingVoice) return;
const ok = await onSendRoomMessage(
selectedRoom.jid,
text,
createRequestId(),
);
if (ok) setVoiceText('');
}
function handleKeyDown(event: KeyboardEvent<HTMLElement>) {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement
) {
return;
}
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
event.preventDefault();
setMode((value) => (value === 'queue' ? 'voice' : 'queue'));
return;
}
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
event.preventDefault();
const delta = event.key === 'ArrowDown' ? 1 : -1;
if (mode === 'queue') {
setSelectedInboxIndex((value) =>
nextIndex(value, inboxItems.length, delta),
);
} else {
setSelectedRoomIndex((value) => nextIndex(value, rooms.length, delta));
}
return;
}
if (event.key === 'Enter') {
event.preventDefault();
if (mode === 'queue') void runSelectedAction();
else void sendVoiceText();
}
}
return (
<main
aria-label="EJClaw Ray-Ban Display"
className="glasses-shell"
onKeyDown={handleKeyDown}
ref={shellRef}
tabIndex={0}
>
<GlassesHeader onRefresh={onRefresh} refreshing={refreshing} />
<section className="glasses-status-row" aria-label="상태">
<span>{freshnessText}</span>
<strong>{inboxItems.length} items</strong>
</section>
{error ? <p className="glasses-error">{error}</p> : null}
<ModeTabs mode={mode} setMode={setMode} />
{mode === 'queue' ? (
<QueueCard
inboxActionKey={inboxActionKey}
inboxActions={inboxActions}
inboxItems={inboxItems}
locale={locale}
onInboxAction={onInboxAction}
selectedActionIndex={selectedActionIndex}
selectedInbox={selectedInbox}
selectedInboxIndex={selectedInboxIndex}
setSelectedActionIndex={setSelectedActionIndex}
/>
) : (
<VoiceCard
canListen={canListen}
listening={listening}
onSendVoiceText={() => void sendVoiceText()}
onStartListening={startListening}
rooms={rooms}
selectedRoom={selectedRoom}
sendingVoice={sendingVoice}
setSelectedRoomIndex={setSelectedRoomIndex}
setVoiceText={setVoiceText}
voiceText={voiceText}
/>
)}
<footer className="glasses-footer">
<span>{footerStatus(mode, busyActionKey, selectedRoom)}</span>
</footer>
</main>
);
}

View File

@@ -1,82 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import type { DashboardOverview } from './api';
import { InboxPanel, type InboxPanelProps } from './InboxPanel';
import { messages } from './i18n';
const t = messages.en;
function overview(inbox: DashboardOverview['inbox']): DashboardOverview {
return {
generatedAt: '2026-04-28T04:00:00.000Z',
inbox,
operations: { serviceRestarts: [] },
rooms: { active: 0, inactive: 0, total: 0, waiting: 0 },
services: [],
tasks: {
active: 0,
completed: 0,
paused: 0,
total: 0,
watchers: { active: 0, completed: 0, paused: 0 },
},
usage: { fetchedAt: null, rows: [] },
};
}
const inboxItem: DashboardOverview['inbox'][number] = {
createdAt: '2026-04-28T03:55:00.000Z',
groupFolder: 'eyejokerdb',
groupKey: 'paired:room-1',
id: 'inbox-1',
kind: 'reviewer-request',
lastOccurredAt: '2026-04-28T03:59:00.000Z',
occurrences: 2,
occurredAt: '2026-04-28T03:58:00.000Z',
roomJid: 'room-1',
roomName: 'eyejokerdb-main',
severity: 'warn',
source: 'paired-task',
summary: '<internal>hidden</internal>Reviewer needs action',
title: '<internal>hidden</internal>Review requested',
};
const baseProps: InboxPanelProps = {
inboxActionKey: null,
locale: 'en',
onInboxAction: () => {},
onTaskAction: () => {},
overview: overview([inboxItem]),
taskActionKey: null,
tasks: [],
t,
};
describe('InboxPanel', () => {
it('renders inbox summary, filters, and paired task actions', () => {
const html = renderToStaticMarkup(
createElement(InboxPanel, { ...baseProps }),
);
expect(html).toContain(t.inbox.summary);
expect(html).toContain('Review requested');
expect(html).toContain('Reviewer needs action');
expect(html).toContain(t.inbox.actions.runReview);
expect(html).toContain(t.inbox.actions.decline);
expect(html).toContain(t.inbox.actions.dismiss);
expect(html).not.toContain('internal');
});
it('renders empty state when no inbox items exist', () => {
const html = renderToStaticMarkup(
createElement(InboxPanel, {
...baseProps,
overview: overview([]),
}),
);
expect(html).toContain(t.inbox.empty);
});
});

View File

@@ -1,282 +0,0 @@
import { useMemo, useState } from 'react';
import type {
DashboardInboxAction,
DashboardOverview,
DashboardTask,
DashboardTaskAction,
} from './api';
import { formatDate } from './dashboardHelpers';
import { EmptyState } from './EmptyState';
import type { Locale, Messages } from './i18n';
import { TaskActionButtons } from './TaskActionButtons';
export type InboxItem = DashboardOverview['inbox'][number];
export type InboxActionKey = `${string}:${DashboardInboxAction}`;
type InboxFilter = 'all' | InboxItem['kind'];
export interface InboxPanelProps {
inboxActionKey: InboxActionKey | null;
locale: Locale;
onInboxAction: (item: InboxItem, action: DashboardInboxAction) => void;
onTaskAction: (task: DashboardTask, action: DashboardTaskAction) => void;
overview: DashboardOverview;
taskActionKey: string | null;
tasks: DashboardTask[];
t: Messages;
}
const INBOX_FILTERS: InboxFilter[] = [
'all',
'ci-failure',
'approval',
'reviewer-request',
'arbiter-request',
'pending-room',
'mention',
];
function sanitizeInboxText(value: string | null | undefined): string {
if (!value) return '';
return value
.replace(/<\/?internal[^>]*>/gi, '')
.replace(/<\/?intern\.{3}/gi, '')
.replace(/<\/?[a-z][a-z0-9-]*[^>]*>/gi, '')
.replace(/\s{2,}/g, ' ')
.trim();
}
function inboxActionsFor(item: InboxItem): DashboardInboxAction[] {
if (
item.source === 'paired-task' &&
(item.kind === 'reviewer-request' ||
item.kind === 'approval' ||
item.kind === 'arbiter-request')
) {
return ['run', 'decline', 'dismiss'];
}
return ['dismiss'];
}
function inboxActionLabel(
item: InboxItem,
action: DashboardInboxAction,
t: Messages,
): string {
if (action === 'dismiss') return t.inbox.actions.dismiss;
if (action === 'decline') return t.inbox.actions.decline;
if (item.kind === 'reviewer-request') return t.inbox.actions.runReview;
if (item.kind === 'approval') return t.inbox.actions.finalize;
if (item.kind === 'arbiter-request') return t.inbox.actions.runArbiter;
return t.inbox.actions.run;
}
function inboxTargetHref(item: InboxItem): string | null {
if (item.taskId) return '#/scheduled';
if (item.roomJid || item.groupFolder) return '#/rooms';
return null;
}
interface InboxCardProps {
inboxActionKey: InboxActionKey | null;
item: InboxItem;
locale: Locale;
onInboxAction: (item: InboxItem, action: DashboardInboxAction) => void;
onTaskAction: (task: DashboardTask, action: DashboardTaskAction) => void;
taskActionKey: string | null;
tasks: DashboardTask[];
t: Messages;
}
function InboxCard({
inboxActionKey,
item,
locale,
onInboxAction,
onTaskAction,
taskActionKey,
tasks,
t,
}: InboxCardProps) {
const href = inboxTargetHref(item);
const linkedTask =
item.source === 'scheduled-task' && item.taskId
? tasks.find((task) => task.id === item.taskId)
: undefined;
const inboxActions = inboxActionsFor(item);
return (
<article className={`inbox-card inbox-${item.severity}`}>
<div className="inbox-card-head">
<div>
<span className="eyebrow">{t.inbox.kinds[item.kind]}</span>
<strong>{sanitizeInboxText(item.title) || item.title}</strong>
</div>
<div className="inbox-card-badges">
<span className={`pill pill-${item.severity}`}>
{t.inbox.severity[item.severity]}
</span>
{item.occurrences > 1 ? (
<span className="pill pill-info">x{item.occurrences}</span>
) : null}
</div>
</div>
<p>{sanitizeInboxText(item.summary) || t.inbox.noSummary}</p>
<div className="inbox-meta">
<span>
<small>{t.inbox.occurred}</small>
<strong>{formatDate(item.occurredAt, locale)}</strong>
</span>
<span>
<small>{t.inbox.source}</small>
<strong>{item.source}</strong>
</span>
<span>
<small>{t.inbox.target}</small>
<strong>
{item.taskId ??
item.roomName ??
item.groupFolder ??
item.roomJid ??
'-'}
</strong>
</span>
</div>
{href ? (
<a className="inbox-target" href={href}>
{item.taskId ? t.inbox.openTask : t.inbox.openRoom}
</a>
) : null}
{linkedTask ? (
<TaskActionButtons
className="inbox-actions"
onTaskAction={onTaskAction}
task={linkedTask}
taskActionKey={taskActionKey}
t={t}
/>
) : null}
{inboxActions.length > 0 ? (
<div className="task-actions inbox-actions">
{inboxActions.map((action) => {
const actionKey: InboxActionKey = `${item.id}:${action}`;
const busy = inboxActionKey === actionKey;
return (
<button
aria-busy={busy || undefined}
className={`task-action task-action-${action}${busy ? ' is-busy' : ''}`}
disabled={busy}
key={action}
onClick={() => onInboxAction(item, action)}
type="button"
>
{busy
? t.inbox.actions.busy
: inboxActionLabel(item, action, t)}
</button>
);
})}
</div>
) : null}
</article>
);
}
export function InboxPanel({
overview,
tasks,
locale,
onInboxAction,
onTaskAction,
inboxActionKey,
taskActionKey,
t,
}: InboxPanelProps) {
const [filter, setFilter] = useState<InboxFilter>('all');
const items = overview.inbox ?? [];
const counts = useMemo(() => {
const next: Record<InboxFilter, number> = {
all: items.length,
'pending-room': 0,
'reviewer-request': 0,
approval: 0,
'arbiter-request': 0,
'ci-failure': 0,
mention: 0,
};
for (const item of items) next[item.kind] += 1;
return next;
}, [items]);
const filteredItems =
filter === 'all' ? items : items.filter((item) => item.kind === filter);
const severityCounts = items.reduce(
(acc, item) => {
acc[item.severity] += 1;
return acc;
},
{ error: 0, warn: 0, info: 0 },
);
if (items.length === 0) {
return <EmptyState>{t.inbox.empty}</EmptyState>;
}
return (
<div className="inbox-board">
<section className="inbox-summary" aria-label={t.inbox.summary}>
<div>
<span>{t.inbox.total}</span>
<strong>{items.length}</strong>
</div>
<div>
<span>{t.inbox.severity.error}</span>
<strong>{severityCounts.error}</strong>
</div>
<div>
<span>{t.inbox.severity.warn}</span>
<strong>{severityCounts.warn}</strong>
</div>
<div>
<span>{t.inbox.severity.info}</span>
<strong>{severityCounts.info}</strong>
</div>
</section>
<div className="inbox-filters" aria-label={t.inbox.filters}>
{INBOX_FILTERS.map((item) => {
if (item !== 'all' && counts[item] === 0) return null;
const label = item === 'all' ? t.inbox.all : t.inbox.kinds[item];
return (
<button
aria-pressed={filter === item}
className={filter === item ? 'is-active' : undefined}
key={item}
onClick={() => setFilter(item)}
type="button"
>
{label}
<span>{counts[item]}</span>
</button>
);
})}
</div>
<div className="inbox-list" aria-label={t.inbox.cardsAria}>
{filteredItems.map((item) => (
<InboxCard
inboxActionKey={inboxActionKey}
item={item}
key={item.id}
locale={locale}
onInboxAction={onInboxAction}
onTaskAction={onTaskAction}
taskActionKey={taskActionKey}
tasks={tasks}
t={t}
/>
))}
</div>
</div>
);
}

View File

@@ -1,390 +0,0 @@
import { useEffect, useState } from 'react';
import {
type MoaModelSettingsSnapshot,
type MoaReferenceStatus,
type MoaSettingsSnapshot,
checkMoaModel,
fetchMoaSettings,
updateMoaSettings,
} from './api';
import { type Messages } from './i18n';
import { SettingsSaveBar, SettingsSectionHeading } from './SettingsPanelChrome';
export function MoaSettingsPanel({ t }: { t: Messages }) {
const [config, setConfig] = useState<MoaSettingsSnapshot | null>(null);
const [draft, setDraft] = useState<MoaSettingsSnapshot | null>(null);
const [apiKeys, setApiKeys] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const [checking, setChecking] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [savedAt, setSavedAt] = useState<number | null>(null);
const section = t.settings.sections.moa;
useEffect(() => {
let cancelled = false;
setBusy(true);
fetchMoaSettings()
.then((next) => {
if (cancelled) return;
setConfig(next);
setDraft(next);
setError(null);
})
.catch((err) => {
if (cancelled) return;
setError(err instanceof Error ? err.message : String(err));
})
.finally(() => {
if (!cancelled) setBusy(false);
});
return () => {
cancelled = true;
};
}, []);
function setModel(name: string, patch: Partial<MoaModelSettingsSnapshot>) {
setDraft((prev) =>
prev
? {
...prev,
models: prev.models.map((model) =>
model.name === name ? { ...model, ...patch } : model,
),
}
: prev,
);
}
function updateStatus(name: string, status: MoaReferenceStatus) {
const update = (prev: MoaSettingsSnapshot | null) =>
prev
? {
...prev,
models: prev.models.map((model) =>
model.name === name ? { ...model, lastStatus: status } : model,
),
}
: prev;
setConfig(update);
setDraft(update);
}
async function save() {
if (!draft) return;
setBusy(true);
setError(null);
try {
const next = await updateMoaSettings({
enabled: draft.enabled,
models: draft.models.map((model) => ({
name: model.name,
enabled: model.enabled,
model: model.model,
baseUrl: model.baseUrl,
apiFormat: model.apiFormat,
apiKey: apiKeys[model.name]?.trim() || undefined,
})),
});
setConfig(next);
setDraft(next);
setApiKeys({});
setSavedAt(Date.now());
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
async function testModel(name: string) {
setChecking(name);
setError(null);
try {
updateStatus(name, await checkMoaModel(name));
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setChecking(null);
}
}
const dirty =
draft !== null &&
config !== null &&
(JSON.stringify(draft) !== JSON.stringify(config) ||
Object.values(apiKeys).some((value) => value.trim()));
return (
<section
aria-labelledby="settings-moa-tab"
className="settings-section"
id="settings-moa"
role="tabpanel"
>
<SettingsSectionHeading
description={section.description}
detail={section.kicker}
title={section.title}
/>
{error ? <p className="settings-error">{error}</p> : null}
{!draft ? (
<p className="settings-hint">
{busy ? t.settings.common.loading : t.settings.moa.empty}
</p>
) : (
<MoaSettingsContent
apiKeys={apiKeys}
busy={busy}
checking={checking}
dirty={dirty}
draft={draft}
onApiKeyChange={(name, value) =>
setApiKeys((prev) => ({ ...prev, [name]: value }))
}
onModelChange={setModel}
onSave={save}
onTest={testModel}
onToggle={() =>
setDraft((prev) =>
prev ? { ...prev, enabled: !prev.enabled } : prev,
)
}
savedAt={savedAt}
t={t}
/>
)}
</section>
);
}
function MoaSettingsContent({
apiKeys,
busy,
checking,
dirty,
draft,
onApiKeyChange,
onModelChange,
onSave,
onTest,
onToggle,
savedAt,
t,
}: {
apiKeys: Record<string, string>;
busy: boolean;
checking: string | null;
dirty: boolean;
draft: MoaSettingsSnapshot;
onApiKeyChange: (name: string, value: string) => void;
onModelChange: (
name: string,
patch: Partial<MoaModelSettingsSnapshot>,
) => void;
onSave: () => Promise<void>;
onTest: (name: string) => Promise<void>;
onToggle: () => void;
savedAt: number | null;
t: Messages;
}) {
return (
<>
<MoaMasterToggle
busy={busy}
enabled={draft.enabled}
onToggle={onToggle}
t={t}
/>
<ul className="settings-moa-list">
{draft.models.map((model) => (
<MoaModelRow
apiKeyValue={apiKeys[model.name] ?? ''}
busy={busy}
checking={checking}
dirty={dirty}
key={model.name}
model={model}
onApiKeyChange={onApiKeyChange}
onModelChange={onModelChange}
onTest={onTest}
t={t}
/>
))}
</ul>
<SettingsSaveBar
busy={busy || checking !== null}
dirty={dirty}
label={t.settings.moa.save}
onSave={() => void onSave()}
savedHint={t.settings.common.savedRestartHint}
savingLabel={t.settings.common.saving}
showSavedHint={savedAt !== null && !dirty}
/>
</>
);
}
function formatMoaStatus(
status: MoaReferenceStatus | null,
t: Messages,
): string {
if (!status) return t.settings.moa.notTested;
const at = new Date(status.checkedAt);
const checkedAt = Number.isNaN(at.getTime())
? status.checkedAt
: at.toLocaleString('ko-KR');
if (status.ok) {
return `${t.settings.moa.statusOk} · ${checkedAt}`;
}
return `${t.settings.moa.statusFail} · ${checkedAt} · ${status.error ?? 'unknown error'}`;
}
function MoaMasterToggle({
busy,
enabled,
onToggle,
t,
}: {
busy: boolean;
enabled: boolean;
onToggle: () => void;
t: Messages;
}) {
return (
<label className="settings-toggle-row">
<span className="settings-toggle-label">
<span className="settings-toggle-title">{t.settings.moa.master}</span>
<small className="settings-hint">{t.settings.moa.masterHint}</small>
</span>
<input
checked={enabled}
disabled={busy}
onChange={onToggle}
type="checkbox"
/>
</label>
);
}
function MoaModelRow({
apiKeyValue,
busy,
checking,
dirty,
model,
onApiKeyChange,
onModelChange,
onTest,
t,
}: {
apiKeyValue: string;
busy: boolean;
checking: string | null;
dirty: boolean;
model: MoaModelSettingsSnapshot;
onApiKeyChange: (name: string, value: string) => void;
onModelChange: (
name: string,
patch: Partial<MoaModelSettingsSnapshot>,
) => void;
onTest: (name: string) => Promise<void>;
t: Messages;
}) {
return (
<li className="settings-moa-card">
<header className="settings-moa-card-head">
<label className="settings-moa-name">
<input
checked={model.enabled}
disabled={busy}
onChange={() =>
onModelChange(model.name, { enabled: !model.enabled })
}
type="checkbox"
/>
<span className="settings-account-tag">{model.name}</span>
</label>
<span
className={`settings-account-badge ${
model.lastStatus?.ok === false ? 'is-expired' : 'is-active'
}`}
title={model.lastStatus?.error ?? undefined}
>
{formatMoaStatus(model.lastStatus, t)}
</span>
</header>
<div className="settings-moa-fields">
<label className="settings-row">
<span className="settings-label">{t.settings.moa.modelLabel}</span>
<input
aria-label={`${model.name} MoA model`}
onChange={(e) =>
onModelChange(model.name, { model: e.target.value })
}
placeholder="model"
type="text"
value={model.model}
/>
</label>
<label className="settings-row">
<span className="settings-label">{t.settings.moa.baseUrlLabel}</span>
<input
aria-label={`${model.name} MoA base URL`}
onChange={(e) =>
onModelChange(model.name, { baseUrl: e.target.value })
}
placeholder="https://…"
type="text"
value={model.baseUrl}
/>
</label>
<label className="settings-row">
<span className="settings-label">{t.settings.moa.formatLabel}</span>
<select
aria-label={`${model.name} MoA API format`}
onChange={(e) =>
onModelChange(model.name, {
apiFormat: e.target.value as 'openai' | 'anthropic',
})
}
value={model.apiFormat}
>
<option value="anthropic">anthropic</option>
<option value="openai">openai</option>
</select>
</label>
<label className="settings-row">
<span className="settings-label">API key</span>
<input
aria-label={`${model.name} MoA API key`}
onChange={(e) => onApiKeyChange(model.name, e.target.value)}
placeholder={
model.apiKeyConfigured
? t.settings.moa.apiKeySet
: t.settings.moa.apiKeyPlaceholder
}
type="password"
value={apiKeyValue}
/>
</label>
</div>
<div className="settings-account-actions">
<button
className="settings-secondary"
disabled={
busy || checking !== null || dirty || !model.apiKeyConfigured
}
onClick={() => void onTest(model.name)}
type="button"
>
{checking === model.name
? t.settings.moa.testing
: dirty
? t.settings.moa.testAfterSave
: t.settings.moa.test}
</button>
</div>
</li>
);
}

View File

@@ -1,32 +0,0 @@
import { useMemo, type ReactNode } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { redactSecretsForMarkdown } from './redaction';
export function ParsedBody({
text,
truncate,
}: {
text: string | null | undefined;
truncate?: number;
}): ReactNode {
const cleaned = useMemo(() => {
if (!text) return '';
let out = redactSecretsForMarkdown(text);
if (truncate && out.length > truncate) {
out = out.slice(0, truncate) + '…';
}
return out;
}, [text, truncate]);
if (!cleaned.trim()) {
return <span className="parsed-empty">—</span>;
}
return (
<div className="parsed-body">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{cleaned}</ReactMarkdown>
</div>
);
}

View File

@@ -1,38 +0,0 @@
import type { RoomThreadEntry } from './roomThread';
type RoomAttachment = NonNullable<RoomThreadEntry['attachments']>[number];
function attachmentDisplayName(attachment: RoomAttachment): string {
if (attachment.name) return attachment.name;
const segments = attachment.path.split(/[\\/]/);
return segments.at(-1) || 'attachment';
}
function attachmentUrl(attachment: RoomAttachment): string {
return `/api/attachments?path=${encodeURIComponent(attachment.path)}`;
}
export function RoomAttachmentGallery({
attachments,
}: {
attachments?: RoomThreadEntry['attachments'];
}) {
if (!attachments || attachments.length === 0) return null;
return (
<ul className="room-attachments">
{attachments.map((attachment) => {
const name = attachmentDisplayName(attachment);
const url = attachmentUrl(attachment);
return (
<li className="room-attachment" key={`${attachment.path}:${name}`}>
<a href={url} rel="noreferrer" target="_blank">
<img alt={name} loading="lazy" src={url} />
<span>{name}</span>
</a>
</li>
);
})}
</ul>
);
}

View File

@@ -1,122 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import type { DashboardRoomActivity, StatusSnapshot } from './api';
import { messages } from './i18n';
import { RoomBoardV2, type RoomBoardV2Props } from './RoomBoardV2';
const t = messages.ko;
const snapshot: StatusSnapshot = {
serviceId: 'svc-1',
assistantName: 'codex',
agentType: 'codex',
updatedAt: '2026-04-28T04:00:00.000Z',
entries: [
{
jid: 'room-1',
name: 'eyejokerdb-main',
folder: 'eyejokerdb',
agentType: 'codex',
status: 'processing',
elapsedMs: 180_000,
pendingMessages: false,
pendingTasks: 3,
},
],
};
const activity: DashboardRoomActivity = {
serviceId: 'svc-1',
jid: 'room-1',
name: 'eyejokerdb-main',
folder: 'eyejokerdb',
agentType: 'codex',
status: 'processing',
elapsedMs: 180_000,
pendingMessages: false,
pendingTasks: 3,
messages: [
{
id: 'bot-1',
sender: 'bot-1',
senderName: 'owner',
content: 'TASK_DONE\n\nprod 배포 완료',
timestamp: '2026-04-28T02:00:00.000Z',
isFromMe: false,
isBotMessage: true,
sourceKind: 'bot',
},
],
pairedTask: null,
};
const baseProps: RoomBoardV2Props = {
createRequestId: () => 'request-1',
formatDate: (value) => value ?? '-',
formatDuration: (value) => (value === null ? '-' : `${value}`),
formatLiveElapsed: (value) => `${value}`,
inbox: [],
locale: 'ko',
onSelectedJidChange: () => {},
onSendRoomMessage: async () => true,
pendingMessages: {},
roomActivity: { 'room-1': activity },
roomActivityLoading: false,
roomMessageKey: null,
selectedJid: 'room-1',
senderRoleClass: (value) =>
(value ?? '').toLowerCase().includes('owner') ? 'role-owner' : 'role-human',
snapshots: [snapshot],
statusLabel: (status) => status,
t,
};
describe('RoomBoardV2', () => {
it('renders room list and selected detail thread', () => {
const html = renderToStaticMarkup(createElement(RoomBoardV2, baseProps));
expect(html).toContain('eyejokerdb-main');
expect(html).toContain('TASK_DONE');
expect(html).toContain('prod 배포 완료');
});
it('surfaces merge approval items as room action badges', () => {
const html = renderToStaticMarkup(
createElement(RoomBoardV2, {
...baseProps,
inbox: [
{
id: 'paired:merge-1:merge_ready',
groupKey: 'paired:merge-1:merge_ready',
kind: 'approval',
severity: 'warn',
title: 'Ready to merge',
summary: 'merge_ready',
occurredAt: '2026-04-28T04:00:00.000Z',
lastOccurredAt: '2026-04-28T04:00:00.000Z',
createdAt: '2026-04-28T04:00:00.000Z',
occurrences: 1,
source: 'paired-task',
roomJid: 'room-1',
taskId: 'merge-1',
taskStatus: 'merge_ready',
},
],
}),
);
expect(html).toContain(t.inbox.kinds.approval);
expect(html).toContain('room-inbox-pip sev-warn');
expect(html).toContain('rooms-list-bell sev-warn');
});
it('renders an empty state without snapshots', () => {
const html = renderToStaticMarkup(
createElement(RoomBoardV2, { ...baseProps, snapshots: [] }),
);
expect(html).toContain(t.rooms.empty);
});
});

View File

@@ -1,397 +0,0 @@
import { useEffect, useState } from 'react';
import type {
DashboardOverview,
DashboardRoomActivity,
StatusSnapshot,
} from './api';
import type { Locale, Messages } from './i18n';
import { RoomCardV2, type RoomEntryWithService } from './RoomCardV2';
import { EmptyState } from './EmptyState';
import type { RoomActivityMap } from './useRoomActivity';
type InboxItem = DashboardOverview['inbox'][number];
type RoomFilter = 'all' | 'processing' | 'waiting' | 'inactive';
type RoomSort = 'recent' | 'name' | 'queue';
const ROOM_FILTER_ORDER: RoomFilter[] = [
'all',
'processing',
'waiting',
'inactive',
];
export interface RoomBoardV2Props {
createRequestId: () => string;
formatDate: (value: string | null | undefined, locale: Locale) => string;
formatDuration: (value: number | null, t: Messages) => string;
formatLiveElapsed: (value: number, t: Messages) => string;
inbox: InboxItem[];
locale: Locale;
onSelectedJidChange: (jid: string | null) => void;
onSendRoomMessage: (
roomJid: string,
text: string,
requestId: string,
) => Promise<boolean>;
pendingMessages: Record<
string,
Array<DashboardRoomActivity['messages'][number]>
>;
roomActivity: RoomActivityMap;
roomActivityLoading: boolean;
roomMessageKey: string | null;
selectedJid: string | null;
senderRoleClass: (value: string | null | undefined) => string;
snapshots: StatusSnapshot[];
statusLabel: (status: string, t: Messages) => string;
t: Messages;
}
function roomFilterLabel(
filter: RoomFilter,
statusLabel: (status: string, t: Messages) => string,
t: Messages,
): string {
if (filter === 'all') return t.rooms.filterAll;
return statusLabel(filter, t);
}
function roomSortLabel(sort: RoomSort, t: Messages): string {
if (sort === 'recent') return t.rooms.sortRecent;
if (sort === 'queue') return t.rooms.sortQueue;
return t.rooms.sortName;
}
function scrollDetailToBottom() {
if (typeof window === 'undefined') return;
const detail = document.querySelector('.rooms-detail') as HTMLElement | null;
if (!detail) return;
const tick = (n: number) => {
detail.scrollTop = detail.scrollHeight;
if (n > 0) requestAnimationFrame(() => tick(n - 1));
};
requestAnimationFrame(() => tick(3));
}
interface RoomsToolbarProps {
counts: Record<RoomFilter, number>;
filter: RoomFilter;
onFilterChange: (filter: RoomFilter) => void;
onSortChange: (sort: RoomSort) => void;
sort: RoomSort;
statusLabel: (status: string, t: Messages) => string;
t: Messages;
}
function RoomsToolbar({
counts,
filter,
onFilterChange,
onSortChange,
sort,
statusLabel,
t,
}: RoomsToolbarProps) {
return (
<div className="rooms-toolbar" role="toolbar" aria-label="Rooms filters">
<div className="rooms-filters">
{ROOM_FILTER_ORDER.map((filterKey) => (
<button
aria-pressed={filter === filterKey}
className={filter === filterKey ? 'is-active' : undefined}
key={filterKey}
onClick={() => onFilterChange(filterKey)}
type="button"
>
{roomFilterLabel(filterKey, statusLabel, t)}
<span>{counts[filterKey]}</span>
</button>
))}
</div>
<label className="rooms-sort">
<span>{t.rooms.sortLabel}</span>
<select
onChange={(event) => onSortChange(event.target.value as RoomSort)}
value={sort}
>
<option value="recent">{roomSortLabel('recent', t)}</option>
<option value="queue">{roomSortLabel('queue', t)}</option>
<option value="name">{roomSortLabel('name', t)}</option>
</select>
</label>
</div>
);
}
interface RoomsListProps {
entries: RoomEntryWithService[];
inbox: InboxItem[];
onSelect: (jid: string) => void;
selectedJid: string | null;
t: Messages;
}
function RoomsList({
entries,
inbox,
onSelect,
selectedJid,
t,
}: RoomsListProps) {
return (
<aside className="rooms-list" aria-label={t.rooms.cardsAria}>
{entries.map((entry) => {
const items = inbox.filter((item) => item.roomJid === entry.jid);
const queue = entry.pendingTasks + (entry.pendingMessages ? 1 : 0);
const active = selectedJid === entry.jid;
return (
<button
aria-current={active ? 'page' : undefined}
className={`rooms-list-item status-${entry.status}${active ? ' is-active' : ''}`}
key={`${entry.serviceId}:${entry.jid}`}
onClick={() => onSelect(entry.jid)}
type="button"
>
<span className={`room-pulse pulse-${entry.status}`}>
{entry.status === 'processing' ? (
<span className="pulse-dot" />
) : null}
</span>
<span className="rooms-list-text">
<strong>{entry.name}</strong>
<small>{entry.agentType}</small>
</span>
{items.length > 0 ? (
<span
className={`rooms-list-bell sev-${items[0].severity}`}
title={items.map((item) => t.inbox.kinds[item.kind]).join(', ')}
>
{items.length}
</span>
) : null}
{queue > 0 ? (
<span className="rooms-list-queue">{queue}</span>
) : null}
</button>
);
})}
</aside>
);
}
interface RoomsDetailProps extends Pick<
RoomBoardV2Props,
| 'formatDate'
| 'formatDuration'
| 'formatLiveElapsed'
| 'locale'
| 'pendingMessages'
| 'roomActivity'
| 'roomActivityLoading'
| 'roomMessageKey'
| 'senderRoleClass'
| 'statusLabel'
| 't'
> {
drafts: Record<string, string>;
inbox: InboxItem[];
onBack: () => void;
onDraftChange: (jid: string, value: string) => void;
onSubmit: (jid: string) => void;
selectedEntry: RoomEntryWithService | null;
}
function RoomsDetail({
drafts,
formatDate,
formatDuration,
formatLiveElapsed,
inbox,
locale,
onBack,
onDraftChange,
onSubmit,
pendingMessages,
roomActivity,
roomActivityLoading,
roomMessageKey,
selectedEntry,
senderRoleClass,
statusLabel,
t,
}: RoomsDetailProps) {
return (
<main className="rooms-detail">
<button className="rooms-mobile-back" onClick={onBack} type="button">
← {t.panels.rooms}
</button>
{selectedEntry ? (
<RoomCardV2
activity={roomActivity[selectedEntry.jid]}
activityLoading={roomActivityLoading}
busy={roomMessageKey === selectedEntry.jid}
draft={drafts[selectedEntry.jid] ?? ''}
entry={selectedEntry}
expanded={true}
formatDate={formatDate}
formatDuration={formatDuration}
formatLiveElapsed={formatLiveElapsed}
inboxItems={inbox.filter(
(item) => item.roomJid === selectedEntry.jid,
)}
key={`${selectedEntry.serviceId}:${selectedEntry.jid}`}
locale={locale}
onDraftChange={(value) => onDraftChange(selectedEntry.jid, value)}
onSendMessage={() => onSubmit(selectedEntry.jid)}
onToggle={() => {}}
pendingMessages={pendingMessages[selectedEntry.jid] ?? []}
pinned={true}
senderRoleClass={senderRoleClass}
statusLabel={statusLabel}
t={t}
/>
) : (
<EmptyState>{t.rooms.empty}</EmptyState>
)}
</main>
);
}
export function RoomBoardV2({
createRequestId,
formatDate,
formatDuration,
formatLiveElapsed,
inbox,
onSendRoomMessage,
pendingMessages,
roomActivity,
roomActivityLoading,
roomMessageKey,
selectedJid,
locale,
onSelectedJidChange,
senderRoleClass,
snapshots,
statusLabel,
t,
}: RoomBoardV2Props) {
const [filter, setFilter] = useState<RoomFilter>('all');
const [sort, setSort] = useState<RoomSort>('recent');
const [drafts, setDrafts] = useState<Record<string, string>>({});
const [mobileDetailOpen, setMobileDetailOpen] = useState(false);
const allEntries: RoomEntryWithService[] = snapshots.flatMap((snapshot) =>
snapshot.entries.map((entry) => ({
...entry,
serviceId: snapshot.serviceId,
})),
);
const counts = {
all: allEntries.length,
processing: allEntries.filter((entry) => entry.status === 'processing')
.length,
waiting: allEntries.filter((entry) => entry.status === 'waiting').length,
inactive: allEntries.filter((entry) => entry.status === 'inactive').length,
};
const filtered = allEntries.filter(
(entry) => filter === 'all' || entry.status === filter,
);
const sorted = Array.from(filtered).sort((a, b) => {
if (sort === 'name') return a.name.localeCompare(b.name);
if (sort === 'queue') {
const aQ = a.pendingTasks + (a.pendingMessages ? 1 : 0);
const bQ = b.pendingTasks + (b.pendingMessages ? 1 : 0);
return bQ - aQ;
}
const aA = roomActivity[a.jid]?.pairedTask?.updatedAt;
const bA = roomActivity[b.jid]?.pairedTask?.updatedAt;
const aT = aA ? new Date(aA).getTime() : (a.elapsedMs ?? 0);
const bT = bA ? new Date(bA).getTime() : (b.elapsedMs ?? 0);
return bT - aT;
});
const selectedEntry =
sorted.find((entry) => entry.jid === selectedJid) ?? sorted[0] ?? null;
useEffect(() => {
const nextJid = selectedEntry?.jid ?? null;
if (nextJid !== selectedJid) {
onSelectedJidChange(nextJid);
}
}, [onSelectedJidChange, selectedEntry?.jid, selectedJid]);
const detailOpen = mobileDetailOpen && selectedEntry?.jid === selectedJid;
if (allEntries.length === 0) {
return <EmptyState>{t.rooms.empty}</EmptyState>;
}
function setDraft(jid: string, value: string) {
setDrafts((previous) => ({ ...previous, [jid]: value }));
}
async function submitRoomMessage(jid: string) {
const text = drafts[jid]?.trim();
if (!text) return;
scrollDetailToBottom();
const success = await onSendRoomMessage(jid, text, createRequestId());
if (success) {
setDraft(jid, '');
scrollDetailToBottom();
}
}
return (
<div className="rooms-v2">
<RoomsToolbar
counts={counts}
filter={filter}
onFilterChange={setFilter}
onSortChange={setSort}
sort={sort}
statusLabel={statusLabel}
t={t}
/>
{sorted.length === 0 ? (
<EmptyState>{t.rooms.empty}</EmptyState>
) : (
<div className={`rooms-twopane${detailOpen ? ' is-detail-open' : ''}`}>
<RoomsList
entries={sorted}
inbox={inbox}
onSelect={(jid) => {
onSelectedJidChange(jid);
setMobileDetailOpen(true);
}}
selectedJid={selectedEntry?.jid ?? null}
t={t}
/>
<RoomsDetail
drafts={drafts}
formatDate={formatDate}
formatDuration={formatDuration}
formatLiveElapsed={formatLiveElapsed}
inbox={inbox}
locale={locale}
onBack={() => setMobileDetailOpen(false)}
onDraftChange={setDraft}
onSubmit={(jid) => void submitRoomMessage(jid)}
pendingMessages={pendingMessages}
roomActivity={roomActivity}
roomActivityLoading={roomActivityLoading}
roomMessageKey={roomMessageKey}
selectedEntry={selectedEntry}
senderRoleClass={senderRoleClass}
statusLabel={statusLabel}
t={t}
/>
</div>
)}
</div>
);
}

View File

@@ -1,418 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import type { DashboardRoomActivity } from './api';
import { messages } from './i18n';
import { RoomCardV2, type RoomEntryWithService } from './RoomCardV2';
const t = messages.ko;
const entry: RoomEntryWithService = {
jid: 'room-1',
name: 'eyejokerdb-main',
folder: 'eyejokerdb',
agentType: 'codex',
status: 'inactive',
elapsedMs: null,
pendingMessages: false,
pendingTasks: 0,
serviceId: 'svc-1',
};
const formatters = {
formatDate: (value: string | null | undefined) => value ?? '-',
formatDuration: (value: number | null) => (value === null ? '-' : `${value}`),
formatLiveElapsed: (value: number) => `${value}`,
senderRoleClass: (value: string | null | undefined) => {
const role = (value ?? '').toLowerCase();
if (role.includes('owner')) return 'role-owner';
if (role.includes('reviewer')) return 'role-reviewer';
if (role.includes('arbiter')) return 'role-arbiter';
return 'role-human';
},
statusLabel: (status: string) => status,
};
function activity(
overrides: Partial<DashboardRoomActivity> = {},
): DashboardRoomActivity {
return {
serviceId: 'svc-1',
jid: 'room-1',
name: 'eyejokerdb-main',
folder: 'eyejokerdb',
agentType: 'codex',
status: 'inactive',
elapsedMs: null,
pendingMessages: false,
pendingTasks: 0,
messages: [],
pairedTask: null,
...overrides,
};
}
describe('RoomCardV2', () => {
it('renders an inactive room without activity', () => {
const html = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: undefined,
activityLoading: false,
busy: false,
draft: '',
entry,
expanded: false,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: false,
t,
...formatters,
}),
);
expect(html).toContain('eyejokerdb-main');
expect(html).toContain(t.rooms.noActivity);
});
it('renders regular bot messages in the expanded thread', () => {
const html = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: activity({
messages: [
{
id: 'bot-1',
sender: 'bot-1',
senderName: 'owner',
content: 'TASK_DONE\n\nprod 배포 완료',
timestamp: '2026-04-28T02:00:00.000Z',
isFromMe: false,
isBotMessage: true,
sourceKind: 'bot',
},
],
}),
activityLoading: false,
busy: false,
draft: '',
entry,
expanded: true,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: true,
t,
...formatters,
}),
);
expect(html).toContain('TASK_DONE');
expect(html).toContain('prod 배포 완료');
});
it('uses canonical room messages for collapsed previews when outputs are empty', () => {
const html = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: activity({
messages: [
{
id: 'bot-1',
sender: 'bot-1',
senderName: 'owner',
content: 'TASK_DONE\n\nprod 배포 완료',
timestamp: '2026-04-28T02:00:00.000Z',
isFromMe: false,
isBotMessage: true,
sourceKind: 'bot',
},
],
pairedTask: {
id: 'task-1',
title: 'Deploy production',
status: 'completed',
roundTripCount: 1,
updatedAt: '2026-04-28T02:01:00.000Z',
currentTurn: null,
outputs: [],
},
}),
activityLoading: false,
busy: false,
draft: '',
entry,
expanded: false,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: false,
t,
...formatters,
}),
);
expect(html).toContain('TASK_DONE');
expect(html).toContain('prod 배포 완료');
expect(html).not.toContain(t.rooms.noActivity);
});
it('localizes protocol role and verdict labels in Korean rooms', () => {
const html = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: activity({
pairedTask: {
id: 'task-1',
title: 'Review pending',
status: 'in_review',
roundTripCount: 2,
updatedAt: '2026-04-28T02:03:00.000Z',
currentTurn: null,
outputs: [
{
id: 1,
turnNumber: 2,
role: 'reviewer',
verdict: 'continue',
createdAt: '2026-04-28T02:02:00.000Z',
outputText: '검증 완료. 다음 단계로 진행 가능합니다.',
},
],
},
}),
activityLoading: false,
busy: false,
draft: '',
entry,
expanded: true,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: true,
t,
...formatters,
}),
);
expect(html).toContain('>리뷰어</span>');
expect(html).toContain('>계속</span>');
expect(html).not.toContain('>reviewer</span>');
expect(html).not.toContain('>continue</span>');
});
it('renders live progress as markdown', () => {
const html = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: activity({
pairedTask: {
id: 'task-1',
title: 'OpenAPI sync',
status: 'running',
roundTripCount: 1,
updatedAt: '2026-04-28T02:01:00.000Z',
currentTurn: {
turnId: 'turn-1',
role: 'owner',
intentKind: 'implementation',
state: 'running',
attemptNo: 1,
executorServiceId: 'svc-1',
executorAgentType: 'codex',
activeRunId: null,
createdAt: '2026-04-28T02:00:00.000Z',
updatedAt: '2026-04-28T02:01:00.000Z',
completedAt: null,
lastError: null,
progressText:
'최신 `origin/dev`로 fast-forward한 뒤 `pnpm openapi:sync`를 실행합니다.',
progressUpdatedAt: '2026-04-28T02:01:00.000Z',
},
outputs: [],
},
}),
activityLoading: false,
busy: false,
draft: '',
entry: { ...entry, status: 'processing' },
expanded: false,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: false,
t,
...formatters,
}),
);
expect(html).toContain('class="live-progress"');
expect(html).toContain('<code>origin/dev</code>');
expect(html).toContain('<code>pnpm openapi:sync</code>');
expect(html).not.toContain('`origin/dev`');
});
});
describe('RoomCardV2 room thread details', () => {
it('does not render site-only active turn placeholders without visible progress', () => {
const pairedTask: NonNullable<DashboardRoomActivity['pairedTask']> = {
id: 'task-1',
title: 'OpenAPI sync',
status: 'running',
roundTripCount: 1,
updatedAt: '2026-04-28T02:01:00.000Z',
currentTurn: {
turnId: 'turn-1',
role: 'owner',
intentKind: 'implementation',
state: 'running',
attemptNo: 1,
executorServiceId: 'svc-1',
executorAgentType: 'codex',
activeRunId: 'run-site-only',
createdAt: '2026-04-28T02:00:00.000Z',
updatedAt: '2026-04-28T02:01:00.000Z',
completedAt: null,
lastError: null,
progressText: null,
progressUpdatedAt: null,
},
outputs: [],
};
const collapsed = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: activity({ pairedTask }),
activityLoading: false,
busy: false,
draft: '',
entry: { ...entry, status: 'processing' },
expanded: false,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: false,
t,
...formatters,
}),
);
const expanded = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: activity({ pairedTask }),
activityLoading: false,
busy: false,
draft: '',
entry: { ...entry, status: 'processing' },
expanded: true,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: false,
t,
...formatters,
}),
);
expect(collapsed).not.toContain('class="room-live"');
expect(expanded).not.toContain('room-timeline-live');
expect(expanded).not.toContain(t.rooms.loadingActivity);
expect(expanded).toContain(t.rooms.noActivity);
});
it('renders message attachments as dashboard images', () => {
const html = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: activity({
messages: [
{
id: 'bot-attachment',
sender: 'bot-1',
senderName: 'owner',
content: '라벨 좌측 클리핑 회귀 수정했습니다.',
timestamp: '2026-04-28T02:00:00.000Z',
isFromMe: false,
isBotMessage: true,
sourceKind: 'bot',
attachments: [
{
path: '/tmp/bar-chart-label-fit-playwright.png',
name: 'bar-chart-label-fit-playwright.png',
mime: 'image/png',
},
],
},
],
}),
activityLoading: false,
busy: false,
draft: '',
entry,
expanded: true,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: true,
t,
...formatters,
}),
);
expect(html).toContain('class="room-attachments"');
expect(html).toContain(
'/api/attachments?path=%2Ftmp%2Fbar-chart-label-fit-playwright.png',
);
expect(html).toContain('bar-chart-label-fit-playwright.png');
});
it('renders expanded watcher messages without truncating content', () => {
const watcherTail = 'WATCHER_TAIL_VISIBLE';
const html = renderToStaticMarkup(
createElement(RoomCardV2, {
activity: activity({
messages: [
{
id: 'watcher-1',
sender: 'bot-1',
senderName: 'reviewer',
content: `[Watcher] ${'검증 로그 '.repeat(40)} ${watcherTail}`,
timestamp: '2026-04-28T02:00:00.000Z',
isFromMe: false,
isBotMessage: true,
sourceKind: 'bot',
},
],
}),
activityLoading: false,
busy: false,
draft: '',
entry,
expanded: true,
inboxItems: [],
locale: 'ko',
onDraftChange: () => {},
onSendMessage: () => {},
onToggle: () => {},
pinned: true,
t,
...formatters,
}),
);
expect(html).toContain('class="room-watcher-fold"');
expect(html).toContain('>리뷰어</strong>');
expect(html).toContain(watcherTail);
});
});

View File

@@ -1,892 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { Send } from 'lucide-react';
import type { DashboardOverview, DashboardRoomActivity } from './api';
import type { Locale, Messages } from './i18n';
import { ParsedBody } from './ParsedBody';
import { RoomAttachmentGallery } from './RoomAttachmentGallery';
import { displayRole, displayVerdict } from './roomDisplayLabels';
import {
buildRoomThreadEntries,
isWatcherRoomMessage,
type RoomThreadEntry,
} from './roomThread';
type InboxItem = DashboardOverview['inbox'][number];
type RoomMessage = DashboardRoomActivity['messages'][number];
type RoomOutput = NonNullable<
DashboardRoomActivity['pairedTask']
>['outputs'][number];
type RoomTask = NonNullable<DashboardRoomActivity['pairedTask']>;
type RoomTurn = NonNullable<RoomTask['currentTurn']>;
export interface RoomEntryWithService {
jid: string;
name: string;
folder: string;
agentType: string;
status: 'processing' | 'waiting' | 'inactive';
elapsedMs: number | null;
pendingMessages: boolean;
pendingTasks: number;
serviceId: string;
}
interface RoomCardFormatters {
formatDate: (value: string | null | undefined, locale: Locale) => string;
formatDuration: (value: number | null, t: Messages) => string;
formatLiveElapsed: (value: number, t: Messages) => string;
senderRoleClass: (value: string | null | undefined) => string;
statusLabel: (status: string, t: Messages) => string;
}
interface RoomMessageFormProps {
busy: boolean;
onChange: (value: string) => void;
onSubmit: () => void;
t: Messages;
value: string;
}
function RoomMessageForm({
busy,
onChange,
onSubmit,
t,
value,
}: RoomMessageFormProps) {
return (
<form
className="room-compose"
onSubmit={(event) => {
event.preventDefault();
onSubmit();
}}
>
<textarea
aria-label={t.rooms.message}
maxLength={8000}
onChange={(event) => onChange(event.target.value)}
onKeyDown={(event) => {
if (event.key !== 'Enter') return;
if (event.shiftKey || event.nativeEvent.isComposing) return;
if (busy || !value.trim()) return;
event.preventDefault();
onSubmit();
}}
placeholder={t.rooms.messagePlaceholder}
rows={1}
value={value}
/>
<button
aria-label={busy ? t.rooms.sending : t.rooms.send}
disabled={busy || !value.trim()}
title={busy ? t.rooms.sending : t.rooms.send}
type="submit"
>
<Send size={16} strokeWidth={2} aria-hidden />
</button>
</form>
);
}
export interface RoomCardV2Props extends RoomCardFormatters {
activity: DashboardRoomActivity | undefined;
activityLoading: boolean;
busy: boolean;
draft: string;
entry: RoomEntryWithService;
expanded: boolean;
inboxItems: InboxItem[];
locale: Locale;
onDraftChange: (value: string) => void;
onSendMessage: () => void;
onToggle: () => void;
pendingMessages?: RoomMessage[];
pinned?: boolean;
t: Messages;
}
export function RoomCardV2({
activity,
activityLoading,
busy,
draft,
entry,
expanded,
formatDate,
formatDuration,
formatLiveElapsed,
inboxItems,
locale,
onDraftChange,
onSendMessage,
onToggle,
pendingMessages = [],
pinned = false,
senderRoleClass,
statusLabel,
t,
}: RoomCardV2Props) {
const task = activity?.pairedTask ?? null;
const turn = task?.currentTurn ?? null;
const outputs = task?.outputs ?? [];
const latestOutput = outputs.at(-1) ?? null;
const messages = activity?.messages ?? [];
const isProcessing = entry.status === 'processing';
const liveTurnStart =
turn && turn.completedAt === null
? new Date(turn.createdAt).getTime()
: null;
const [tick, setTick] = useState(() => Date.now());
useEffect(() => {
if (!isProcessing || liveTurnStart === null) return;
const id = window.setInterval(() => setTick(Date.now()), 1000);
return () => window.clearInterval(id);
}, [isProcessing, liveTurnStart]);
const liveElapsedMs =
liveTurnStart === null ? null : Math.max(0, tick - liveTurnStart);
const liveProgressDisplay =
turn?.progressText && turn.progressText.trim()
? turn.progressText
: getLiveStatusFallback({
isProcessing,
messages,
senderRoleClass,
turn,
});
const lastUpdated = turn?.updatedAt ?? task?.updatedAt ?? null;
const watcherMessages = messages.filter(isWatcherRoomMessage);
const lastWatcher = watcherMessages.at(-1) ?? null;
const agentMessages = buildRoomThreadEntries({
messages,
outputs,
pendingMessages,
});
useRoomDetailAutoscroll({
entryJid: entry.jid,
messagesLen: messages.length,
outputsLen: outputs.length,
pendingLen: pendingMessages.length,
});
const formatters = {
formatDate,
formatDuration,
formatLiveElapsed,
senderRoleClass,
statusLabel,
};
return (
<article
aria-expanded={pinned ? undefined : expanded}
className={`room-card-v2 status-${entry.status}${expanded ? ' is-expanded' : ''}${pinned ? ' is-pinned' : ''}`}
onClick={pinned ? undefined : onToggle}
onKeyDown={
pinned
? undefined
: (e) => {
if (e.target !== e.currentTarget) return;
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onToggle();
}
}
}
role={pinned ? undefined : 'button'}
tabIndex={pinned ? undefined : 0}
>
<RoomCardHead
entry={entry}
expanded={expanded}
inboxItems={inboxItems}
isProcessing={isProcessing}
pinned={pinned}
statusLabel={statusLabel}
t={t}
/>
<RoomCurrentTurnSummary
formatDate={formatDate}
lastUpdated={lastUpdated}
locale={locale}
senderRoleClass={senderRoleClass}
task={task}
turn={turn}
t={t}
/>
<RoomCardMeta
entry={entry}
formatDuration={formatDuration}
isProcessing={isProcessing}
t={t}
/>
<CollapsedLiveTurn
expanded={expanded}
formatDate={formatDate}
isProcessing={isProcessing}
liveProgressDisplay={liveProgressDisplay}
locale={locale}
senderRoleClass={senderRoleClass}
t={t}
turn={turn}
/>
<CollapsedOutputPreview
agentMessages={agentMessages}
expanded={expanded}
isProcessing={isProcessing}
latestOutput={latestOutput}
/>
<CollapsedWatcherStrip
expanded={expanded}
formatDate={formatDate}
lastWatcher={lastWatcher}
locale={locale}
senderRoleClass={senderRoleClass}
watcherCount={watcherMessages.length}
/>
<CollapsedEmptyState
activity={activity}
activityLoading={activityLoading}
expanded={expanded}
isProcessing={isProcessing}
t={t}
visibleActivityCount={agentMessages.length + watcherMessages.length}
/>
{expanded ? (
<RoomExpandedContent
agentMessages={agentMessages}
busy={busy}
draft={draft}
formatters={formatters}
isProcessing={isProcessing}
liveElapsedMs={liveElapsedMs}
liveProgressDisplay={liveProgressDisplay}
locale={locale}
onDraftChange={onDraftChange}
onSendMessage={onSendMessage}
t={t}
turn={turn}
watcherMessages={watcherMessages}
/>
) : null}
</article>
);
}
function useRoomDetailAutoscroll({
entryJid,
messagesLen,
outputsLen,
pendingLen,
}: {
entryJid: string;
messagesLen: number;
outputsLen: number;
pendingLen: number;
}) {
const wasNearBottomRef = useRef(true);
useEffect(() => {
const detail = document.querySelector(
'.rooms-detail',
) as HTMLElement | null;
if (!detail) return;
if (!wasNearBottomRef.current) return;
const run = () => {
detail.scrollTop = detail.scrollHeight;
};
requestAnimationFrame(() => requestAnimationFrame(run));
}, [entryJid, messagesLen, outputsLen, pendingLen]);
useEffect(() => {
const detail = document.querySelector(
'.rooms-detail',
) as HTMLElement | null;
if (!detail) return;
const onScroll = () => {
const distance =
detail.scrollHeight - detail.scrollTop - detail.clientHeight;
wasNearBottomRef.current = distance < 80;
};
detail.addEventListener('scroll', onScroll, { passive: true });
return () => detail.removeEventListener('scroll', onScroll);
}, [entryJid]);
}
const TASK_STATUS_PREFIX = '⁣⁣⁣';
function getLiveStatusFallback({
isProcessing,
messages,
senderRoleClass,
turn,
}: {
isProcessing: boolean;
messages: RoomMessage[];
senderRoleClass: RoomCardFormatters['senderRoleClass'];
turn: RoomTurn | null;
}): string | null {
if (!isProcessing) return null;
if (!turn) return null;
if (turn.progressText && turn.progressText.trim()) return null;
const turnStartMs = turn.createdAt ? new Date(turn.createdAt).getTime() : 0;
const turnRole = senderRoleClass(turn.role);
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
if (!message.content.startsWith(TASK_STATUS_PREFIX)) continue;
const ts = message.timestamp ? new Date(message.timestamp).getTime() : 0;
if (ts < turnStartMs) continue;
const senderRole = senderRoleClass(message.senderName);
if (senderRole !== turnRole) continue;
const body = message.content.slice(TASK_STATUS_PREFIX.length);
const stripped = body.replace(/\n\n\d+[초smhMSH]?$/, '').trim();
return stripped || null;
}
return null;
}
function RoomCardHead({
entry,
expanded,
inboxItems,
isProcessing,
pinned,
statusLabel,
t,
}: {
entry: RoomEntryWithService;
expanded: boolean;
inboxItems: InboxItem[];
isProcessing: boolean;
pinned: boolean;
statusLabel: RoomCardFormatters['statusLabel'];
t: Messages;
}) {
return (
<div className="room-card-head">
<span className={`room-pulse pulse-${entry.status}`}>
{isProcessing ? <span className="pulse-dot" /> : null}
</span>
<span className="room-title-block">
<strong>{entry.name}</strong>
<span className="room-sub">
<em>{entry.agentType}</em>
{inboxItems.length > 0 ? (
<span className="room-inbox-badges" aria-label={t.panels.inbox}>
{inboxItems.slice(0, 3).map((item) => (
<span
className={`room-inbox-pip sev-${item.severity}`}
key={item.id}
title={t.inbox.kinds[item.kind]}
>
{t.inbox.kinds[item.kind]}
</span>
))}
</span>
) : null}
</span>
</span>
{!isProcessing ? (
<span className={`room-status pill pill-${entry.status}`}>
{statusLabel(entry.status, t)}
</span>
) : (
<span />
)}
{!pinned ? (
<span className="room-toggle" aria-hidden>
{expanded ? '▾' : '▸'}
</span>
) : null}
</div>
);
}
function RoomCurrentTurnSummary({
formatDate,
lastUpdated,
locale,
senderRoleClass,
task,
turn,
t,
}: {
formatDate: RoomCardFormatters['formatDate'];
lastUpdated: string | null;
locale: Locale;
senderRoleClass: RoomCardFormatters['senderRoleClass'];
task: RoomTask | null;
turn: RoomTurn | null;
t: Messages;
}) {
if (!turn || turn.completedAt === null) return null;
return (
<div className="room-current-turn">
<span>
<strong className={senderRoleClass(turn.role)}>
{displayRole(turn.role, locale)}
</strong>
<em>{turn.intentKind}</em>
{turn.attemptNo > 1 ? (
<small>
{t.rooms.attempt} {turn.attemptNo}
</small>
) : null}
</span>
{task && task.roundTripCount > 0 ? (
<small>
· {t.rooms.round} {task.roundTripCount}
</small>
) : null}
{lastUpdated ? (
<small style={{ marginLeft: 'auto' }}>
{formatDate(lastUpdated, locale)}
</small>
) : null}
</div>
);
}
function RoomCardMeta({
entry,
formatDuration,
isProcessing,
t,
}: {
entry: RoomEntryWithService;
formatDuration: RoomCardFormatters['formatDuration'];
isProcessing: boolean;
t: Messages;
}) {
const queueChips: string[] = [];
if (entry.pendingTasks > 0)
queueChips.push(`${entry.pendingTasks} ${t.rooms.tasks}`);
if (entry.pendingMessages) queueChips.push(t.rooms.queueWaitingMessages);
if (
queueChips.length === 0 &&
!(entry.elapsedMs && entry.elapsedMs > 0 && isProcessing)
) {
return null;
}
return (
<div className="room-card-meta">
{queueChips.length > 0 ? (
<span className="meta-cell">
<strong>{queueChips.join(' · ')}</strong>
</span>
) : null}
{isProcessing && entry.elapsedMs ? (
<span className="meta-cell">
<strong>{formatDuration(entry.elapsedMs, t)}</strong>
</span>
) : null}
</div>
);
}
function CollapsedLiveTurn({
expanded,
formatDate,
isProcessing,
liveProgressDisplay,
locale,
senderRoleClass,
t,
turn,
}: {
expanded: boolean;
formatDate: RoomCardFormatters['formatDate'];
isProcessing: boolean;
liveProgressDisplay: string | null;
locale: Locale;
senderRoleClass: RoomCardFormatters['senderRoleClass'];
t: Messages;
turn: RoomTurn | null;
}) {
if (expanded || !isProcessing || !turn || !liveProgressDisplay) return null;
return (
<div className="room-live">
<header>
<span className="live-dot" aria-hidden />
<span className="live-label">LIVE</span>
<strong className={senderRoleClass(turn.role)}>
{displayRole(turn.role, locale)}
</strong>
<em>{turn.intentKind}</em>
<span className="live-state pill pill-processing">{turn.state}</span>
{turn.executorServiceId ? (
<span className="live-exec">{turn.executorServiceId}</span>
) : null}
{turn.attemptNo > 1 ? (
<span className="live-attempt">
{t.rooms.attempt} {turn.attemptNo}
</span>
) : null}
<time>
{formatDate(turn.progressUpdatedAt ?? turn.updatedAt, locale)}
</time>
</header>
<LiveProgressBody text={liveProgressDisplay} />
</div>
);
}
function LiveProgressBody({ text }: { text: string }) {
return (
<div className="live-progress">
<ParsedBody text={text} />
</div>
);
}
function CollapsedOutputPreview({
agentMessages,
expanded,
isProcessing,
latestOutput,
}: {
agentMessages: RoomThreadEntry[];
expanded: boolean;
isProcessing: boolean;
latestOutput: RoomOutput | null;
}) {
const latestThreadEntry = agentMessages.at(-1) ?? null;
const previewText =
latestOutput?.outputText ?? latestThreadEntry?.content ?? null;
if (expanded || !previewText || isProcessing) return null;
return (
<div className="room-preview">
<ParsedBody text={previewText} truncate={140} />
</div>
);
}
function CollapsedWatcherStrip({
expanded,
formatDate,
lastWatcher,
locale,
senderRoleClass,
watcherCount,
}: {
expanded: boolean;
formatDate: RoomCardFormatters['formatDate'];
lastWatcher: RoomMessage | null;
locale: Locale;
senderRoleClass: RoomCardFormatters['senderRoleClass'];
watcherCount: number;
}) {
if (expanded || watcherCount === 0 || !lastWatcher) return null;
return (
<div className="room-watcher-strip">
<span className="watcher-tag">워쳐 {watcherCount}</span>
<span className="watcher-line">
<strong className={senderRoleClass(lastWatcher.senderName)}>
{displayRole(lastWatcher.senderName, locale)}
</strong>
<span>{lastWatcher.content.slice(0, 90)}</span>
</span>
<time>{formatDate(lastWatcher.timestamp, locale)}</time>
</div>
);
}
function CollapsedEmptyState({
activity,
activityLoading,
expanded,
isProcessing,
t,
visibleActivityCount,
}: {
activity: DashboardRoomActivity | undefined;
activityLoading: boolean;
expanded: boolean;
isProcessing: boolean;
t: Messages;
visibleActivityCount: number;
}) {
if (expanded) return null;
if (visibleActivityCount === 0 && !isProcessing && !activityLoading) {
return <p className="room-empty">{t.rooms.noActivity}</p>;
}
if (activityLoading && !activity) {
return <p className="room-empty">{t.rooms.loadingActivity}</p>;
}
return null;
}
function RoomExpandedContent({
agentMessages,
busy,
draft,
formatters,
isProcessing,
liveElapsedMs,
liveProgressDisplay,
locale,
onDraftChange,
onSendMessage,
t,
turn,
watcherMessages,
}: {
agentMessages: RoomThreadEntry[];
busy: boolean;
draft: string;
formatters: RoomCardFormatters;
isProcessing: boolean;
liveElapsedMs: number | null;
liveProgressDisplay: string | null;
locale: Locale;
onDraftChange: (value: string) => void;
onSendMessage: () => void;
t: Messages;
turn: RoomTurn | null;
watcherMessages: RoomMessage[];
}) {
return (
<div
className="room-expanded"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
>
{turn?.lastError ? (
<div className="room-alert">
<strong>{t.rooms.error}</strong>
<ParsedBody text={turn.lastError} />
</div>
) : null}
<RoomThreadSection
agentMessages={agentMessages}
formatters={formatters}
isProcessing={isProcessing}
liveElapsedMs={liveElapsedMs}
liveProgressDisplay={liveProgressDisplay}
locale={locale}
t={t}
turn={turn}
/>
<RoomWatcherFold
formatDate={formatters.formatDate}
locale={locale}
senderRoleClass={formatters.senderRoleClass}
watcherMessages={watcherMessages}
/>
<section className="room-section room-compose-section">
<RoomMessageForm
busy={busy}
onChange={onDraftChange}
onSubmit={onSendMessage}
t={t}
value={draft}
/>
</section>
</div>
);
}
function RoomThreadSection({
agentMessages,
formatters,
isProcessing,
liveElapsedMs,
liveProgressDisplay,
locale,
t,
turn,
}: {
agentMessages: RoomThreadEntry[];
formatters: RoomCardFormatters;
isProcessing: boolean;
liveElapsedMs: number | null;
liveProgressDisplay: string | null;
locale: Locale;
t: Messages;
turn: RoomTurn | null;
}) {
const showLiveItem = !!(
turn &&
turn.completedAt === null &&
liveProgressDisplay
);
return (
<section className="room-section room-thread-section">
<header>
<h4>{t.rooms.activity}</h4>
<small>{agentMessages.length}</small>
</header>
{agentMessages.length === 0 && !showLiveItem ? (
<p className="room-empty">{t.rooms.noActivity}</p>
) : (
<ol className="room-timeline">
{agentMessages.map((entry) => (
<RoomTimelineEntry
entry={entry}
formatDate={formatters.formatDate}
key={entry.id}
locale={locale}
senderRoleClass={formatters.senderRoleClass}
/>
))}
{showLiveItem ? (
<RoomLiveTimelineEntry
formatLiveElapsed={formatters.formatLiveElapsed}
formatDate={formatters.formatDate}
isProcessing={isProcessing}
liveElapsedMs={liveElapsedMs}
liveProgressDisplay={liveProgressDisplay}
locale={locale}
senderRoleClass={formatters.senderRoleClass}
t={t}
turn={turn}
/>
) : null}
</ol>
)}
</section>
);
}
function RoomTimelineEntry({
entry,
formatDate,
locale,
senderRoleClass,
}: {
entry: RoomThreadEntry;
formatDate: RoomCardFormatters['formatDate'];
locale: Locale;
senderRoleClass: RoomCardFormatters['senderRoleClass'];
}) {
const verdict = entry.verdict;
const verdictTone = verdict
? /fail|error/i.test(verdict)
? 'fail'
: /done|ok|pass/i.test(verdict)
? 'done'
: 'info'
: null;
const sectionClass = senderRoleClass(entry.senderName).replace(
'role-',
'role-section-',
);
return (
<li className={`room-timeline-item ${sectionClass}`}>
<header className="room-timeline-header">
<span className={`role-chip ${senderRoleClass(entry.senderName)}`}>
{displayRole(entry.senderName, locale)}
</span>
<time>{formatDate(entry.timestamp, locale)}</time>
{entry.turnNumber !== undefined ? (
<span className="parsed-marker parsed-marker-info">
#{entry.turnNumber}
</span>
) : null}
{verdict ? (
<span className={`parsed-marker parsed-marker-${verdictTone}`}>
{displayVerdict(verdict, locale)}
</span>
) : null}
</header>
<div className="room-timeline-body">
<ParsedBody text={entry.content} />
<RoomAttachmentGallery attachments={entry.attachments} />
</div>
</li>
);
}
function RoomLiveTimelineEntry({
formatDate,
formatLiveElapsed,
isProcessing,
liveElapsedMs,
liveProgressDisplay,
locale,
senderRoleClass,
t,
turn,
}: {
formatDate: RoomCardFormatters['formatDate'];
formatLiveElapsed: RoomCardFormatters['formatLiveElapsed'];
isProcessing: boolean;
liveElapsedMs: number | null;
liveProgressDisplay: string | null;
locale: Locale;
senderRoleClass: RoomCardFormatters['senderRoleClass'];
t: Messages;
turn: RoomTurn;
}) {
return (
<li
className={`room-timeline-item ${senderRoleClass(turn.role).replace('role-', 'role-section-')} ${isProcessing ? 'room-timeline-live' : 'room-timeline-paused'}`}
>
<header className="room-timeline-header">
{isProcessing ? (
<span className="live-dot live-dot-inline" aria-hidden />
) : (
<span className="paused-dot" aria-hidden />
)}
<span className={`role-chip ${senderRoleClass(turn.role)}`}>
{displayRole(turn.role, locale)}
</span>
<time>
{formatDate(turn.progressUpdatedAt ?? turn.updatedAt, locale)}
</time>
{liveElapsedMs !== null ? (
<span className="live-elapsed">
+{formatLiveElapsed(liveElapsedMs, t)}
</span>
) : null}
{!isProcessing ? (
<span className="live-label paused">중단됨</span>
) : null}
</header>
<div className="room-timeline-body">
{liveProgressDisplay ? (
<LiveProgressBody text={liveProgressDisplay} />
) : (
<p className="room-empty">{t.rooms.loadingActivity}</p>
)}
</div>
</li>
);
}
function RoomWatcherFold({
formatDate,
locale,
senderRoleClass,
watcherMessages,
}: {
formatDate: RoomCardFormatters['formatDate'];
locale: Locale;
senderRoleClass: RoomCardFormatters['senderRoleClass'];
watcherMessages: RoomMessage[];
}) {
if (watcherMessages.length === 0) return null;
return (
<details className="room-watcher-fold">
<summary>
<span className="watcher-tag">워쳐</span>
<small>{watcherMessages.length}</small>
</summary>
<ul className="room-watcher-list">
{watcherMessages.map((message) => (
<li className="room-watcher-item" key={message.id}>
<header>
<strong className={senderRoleClass(message.senderName)}>
{displayRole(message.senderName, locale)}
</strong>
<time>{formatDate(message.timestamp, locale)}</time>
</header>
<ParsedBody text={message.content} />
</li>
))}
</ul>
</details>
);
}

View File

@@ -1,337 +0,0 @@
import { useEffect, useMemo, useState } from 'react';
import {
fetchRoomSkillSettings,
updateRoomSkillSetting,
type RoomSkillCatalogItem,
type RoomSkillSettingUpdateInput,
type RoomSkillSettingsSnapshot,
} from './api';
import { SettingsCard, SettingsSectionHeading } from './SettingsPanelChrome';
import { type Messages } from './i18n';
type RoomSkillRoom = RoomSkillSettingsSnapshot['rooms'][number];
type RoomSkillAgent = RoomSkillRoom['agents'][number];
type AgentType = RoomSkillAgent['agentType'];
function agentLabel(agentType: AgentType, t: Messages): string {
return agentType === 'codex'
? t.settings.runtime.agentCodex
: t.settings.runtime.agentClaude;
}
function scopeLabel(scope: RoomSkillCatalogItem['scope'], t: Messages): string {
if (scope === 'codex-user') return t.settings.runtime.scopeCodexUser;
if (scope === 'claude-user') return t.settings.runtime.scopeClaudeUser;
return t.settings.runtime.scopeRunner;
}
function applyOptimisticToggle(
snapshot: RoomSkillSettingsSnapshot,
input: RoomSkillSettingUpdateInput,
): RoomSkillSettingsSnapshot {
const { roomJid, agentType, skillId, enabled } = input;
return {
...snapshot,
rooms: snapshot.rooms.map((room) => {
if (room.jid !== roomJid) return room;
return {
...room,
agents: room.agents.map((agent) => {
if (agent.agentType !== agentType) return agent;
const disabledSkillIds = enabled
? agent.disabledSkillIds.filter((id) => id !== skillId)
: agent.disabledSkillIds.includes(skillId)
? agent.disabledSkillIds
: [...agent.disabledSkillIds, skillId];
const effectiveEnabledSkillIds = enabled
? agent.availableSkillIds.filter(
(id) => !disabledSkillIds.includes(id),
)
: agent.availableSkillIds.filter(
(id) => id !== skillId && !disabledSkillIds.includes(id),
);
return {
...agent,
mode: disabledSkillIds.length === 0 ? 'all-enabled' : 'custom',
disabledSkillIds,
effectiveEnabledSkillIds,
};
}),
};
}),
};
}
interface RoomSkillControlsProps {
onAgentChange: (agentType: AgentType) => void;
onRoomChange: (roomJid: string) => void;
selectedAgentType: AgentType;
selectedRoom: RoomSkillRoom | null;
selectedRoomJid: string;
snapshot: RoomSkillSettingsSnapshot;
t: Messages;
}
function RoomSkillControls({
onAgentChange,
onRoomChange,
selectedAgentType,
selectedRoom,
selectedRoomJid,
snapshot,
t,
}: RoomSkillControlsProps) {
return (
<div className="settings-form-grid settings-skill-controls">
<label className="settings-row">
<span className="settings-label">
{t.settings.runtime.selectRoomLabel}
</span>
<select
onChange={(event) => onRoomChange(event.target.value)}
value={selectedRoomJid}
>
{snapshot.rooms.map((room) => (
<option key={room.jid} value={room.jid}>
{room.name} ({room.folder})
</option>
))}
</select>
</label>
{selectedRoom && selectedRoom.agents.length > 1 ? (
<div className="settings-row">
<span className="settings-label">
{t.settings.runtime.selectAgentLabel}
</span>
<div className="settings-skill-agent-tabs" role="tablist">
{selectedRoom.agents.map((agent) => (
<button
aria-selected={selectedAgentType === agent.agentType}
className={
selectedAgentType === agent.agentType
? 'is-active'
: undefined
}
key={agent.agentType}
onClick={() => onAgentChange(agent.agentType)}
role="tab"
type="button"
>
{agentLabel(agent.agentType, t)}
</button>
))}
</div>
</div>
) : null}
</div>
);
}
interface SkillToggleListProps {
catalogById: Map<string, RoomSkillCatalogItem>;
onToggle: (input: RoomSkillSettingUpdateInput) => void;
savingKey: string | null;
selectedAgent: RoomSkillAgent;
selectedRoomJid: string;
t: Messages;
}
function SkillToggleList({
catalogById,
onToggle,
savingKey,
selectedAgent,
selectedRoomJid,
t,
}: SkillToggleListProps) {
return (
<div className="settings-toggle-stack">
{selectedAgent.availableSkillIds.map((skillId) => {
const skill = catalogById.get(skillId);
const key = `${selectedRoomJid}:${selectedAgent.agentType}:${skillId}`;
const enabled =
selectedAgent.effectiveEnabledSkillIds.includes(skillId);
return (
<label
aria-busy={savingKey === key}
className={`settings-toggle-row${savingKey === key ? ' is-busy' : ''}`}
key={skillId}
>
<span className="settings-toggle-label">
<span className="settings-toggle-title">
{skill?.displayName ?? skillId}
</span>
<small>
{skill ? scopeLabel(skill.scope, t) : null}
{skill?.description ? ` · ${skill.description}` : null}
</small>
</span>
<input
checked={enabled}
disabled={savingKey === key}
onChange={(event) =>
onToggle({
roomJid: selectedRoomJid,
agentType: selectedAgent.agentType,
skillId,
enabled: event.currentTarget.checked,
})
}
type="checkbox"
/>
</label>
);
})}
</div>
);
}
export function RuntimeInventorySettings({ t }: { t: Messages }) {
const [snapshot, setSnapshot] = useState<RoomSkillSettingsSnapshot | null>(
null,
);
const [error, setError] = useState<string | null>(null);
const [savingKey, setSavingKey] = useState<string | null>(null);
const [selectedRoomJid, setSelectedRoomJid] = useState<string>('');
const [selectedAgentType, setSelectedAgentType] =
useState<AgentType>('codex');
useEffect(() => {
let cancelled = false;
fetchRoomSkillSettings()
.then((value) => {
if (cancelled) return;
setSnapshot(value);
setError(null);
})
.catch((err) => {
if (cancelled) return;
setError(err instanceof Error ? err.message : String(err));
});
return () => {
cancelled = true;
};
}, []);
const selectedRoom = useMemo(
() => snapshot?.rooms.find((room) => room.jid === selectedRoomJid) ?? null,
[snapshot, selectedRoomJid],
);
const selectedAgent = useMemo(
() =>
selectedRoom?.agents.find(
(agent) => agent.agentType === selectedAgentType,
) ?? null,
[selectedRoom, selectedAgentType],
);
useEffect(() => {
if (!snapshot || snapshot.rooms.length === 0) return;
if (!snapshot.rooms.some((room) => room.jid === selectedRoomJid)) {
setSelectedRoomJid(snapshot.rooms[0]?.jid ?? '');
}
}, [snapshot, selectedRoomJid]);
useEffect(() => {
if (!selectedRoom || selectedRoom.agents.length === 0) return;
if (
!selectedRoom.agents.some(
(agent) => agent.agentType === selectedAgentType,
)
) {
setSelectedAgentType(selectedRoom.agents[0]?.agentType ?? 'codex');
}
}, [selectedRoom, selectedAgentType]);
const catalogById = useMemo(
() =>
new Map<string, RoomSkillCatalogItem>(
snapshot?.catalog.map((skill) => [skill.id, skill]) ?? [],
),
[snapshot],
);
async function handleToggle(input: RoomSkillSettingUpdateInput) {
const key = `${input.roomJid}:${input.agentType}:${input.skillId}`;
setError(null);
setSnapshot((current) =>
current ? applyOptimisticToggle(current, input) : current,
);
setSavingKey(key);
try {
const next = await updateRoomSkillSetting(input);
setSnapshot(next);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
try {
setSnapshot(await fetchRoomSkillSettings());
} catch {
/* keep optimistic state if refetch also fails */
}
} finally {
setSavingKey(null);
}
}
return (
<section
aria-labelledby="settings-runtime-tab"
className="settings-section"
id="settings-runtime"
role="tabpanel"
>
<SettingsSectionHeading
description={t.settings.sections.runtime.description}
detail={t.settings.sections.runtime.kicker}
title={t.settings.sections.runtime.title}
/>
<p className="settings-hint settings-skill-default-hint">
{t.settings.runtime.defaultHint}
</p>
{error ? <p className="settings-error">{error}</p> : null}
{!snapshot ? (
<p className="settings-hint">{t.settings.common.loading}</p>
) : snapshot.rooms.length === 0 ? (
<SettingsCard title={t.settings.runtime.selectRoomLabel}>
<p className="settings-hint">{t.settings.runtime.emptyRooms}</p>
</SettingsCard>
) : (
<SettingsCard title={t.settings.runtime.selectRoomLabel}>
<RoomSkillControls
onAgentChange={setSelectedAgentType}
onRoomChange={setSelectedRoomJid}
selectedAgentType={selectedAgentType}
selectedRoom={selectedRoom}
selectedRoomJid={selectedRoomJid}
snapshot={snapshot}
t={t}
/>
{!selectedAgent || selectedAgent.availableSkillIds.length === 0 ? (
<p className="settings-hint">{t.settings.runtime.emptySkills}</p>
) : (
<SkillToggleList
catalogById={catalogById}
onToggle={(input) => void handleToggle(input)}
savingKey={savingKey}
selectedAgent={selectedAgent}
selectedRoomJid={selectedRoomJid}
t={t}
/>
)}
</SettingsCard>
)}
</section>
);
}

View File

@@ -1,219 +0,0 @@
import { type ModelConfigSnapshot, type ModelRoleConfig } from './api';
import { type Messages } from './i18n';
import {
type AgentType,
type EffortValue,
effortValuesForAgent,
formatEffortOption,
isEffortSupported,
isPresetModel,
PRESET_MODELS,
} from './settings-options';
const MODEL_ROLES = ['owner', 'reviewer', 'arbiter'] as const;
export type ModelRole = (typeof MODEL_ROLES)[number];
function modelRoleLabel(role: ModelRole, t: Messages): string {
if (role === 'owner') return t.settings.models.roleOwner;
if (role === 'reviewer') return t.settings.models.roleReviewer;
return t.settings.models.roleArbiter;
}
function modelRoleHint(role: ModelRole, t: Messages): string {
if (role === 'owner') return t.settings.models.roleOwnerHint;
if (role === 'reviewer') return t.settings.models.roleReviewerHint;
return t.settings.models.roleArbiterHint;
}
function agentTypeLabel(agentType: AgentType, t: Messages): string {
return agentType === 'codex'
? t.settings.models.agentTypeCodex
: t.settings.models.agentTypeClaude;
}
function effortLabel(value: EffortValue, t: Messages): string {
if (value === '') return t.settings.models.effortDefault;
const key = value as keyof typeof t.settings.models.effortOptions;
const localized = t.settings.models.effortOptions[key] ?? value;
return formatEffortOption(value, localized);
}
function modelGroupLabel(model: string, t: Messages): string {
if ((PRESET_MODELS.codex as readonly string[]).includes(model)) {
return t.settings.models.groupCodex;
}
if ((PRESET_MODELS.claude as readonly string[]).includes(model)) {
return t.settings.models.groupClaude;
}
return t.settings.models.groupCustom;
}
function effortOptionsForRole(
draft: ModelConfigSnapshot,
role: ModelRole,
): readonly EffortValue[] {
const agentType = draft.agentTypes?.[role];
if (agentType) return effortValuesForAgent(agentType);
return effortValuesForAgent('codex');
}
export function hasUnsupportedModelEffort(draft: ModelConfigSnapshot): boolean {
for (const role of MODEL_ROLES) {
const agentType = draft.agentTypes?.[role];
if (!agentType) continue;
if (!isEffortSupported(agentType, draft[role].effort)) return true;
}
return false;
}
export function ModelRoleFields({
draft,
onChange,
t,
}: {
draft: ModelConfigSnapshot;
onChange: (role: ModelRole, patch: Partial<ModelRoleConfig>) => void;
t: Messages;
}) {
return (
<div className="settings-model-stack">
{MODEL_ROLES.map((role) => {
const roleConfig = draft[role];
const agentType = draft.agentTypes?.[role] ?? null;
const effortOptions = effortOptionsForRole(draft, role);
const effortInvalid =
agentType !== null &&
roleConfig.effort !== '' &&
!isEffortSupported(agentType, roleConfig.effort);
const usingCustom =
roleConfig.model.trim() !== '' && !isPresetModel(roleConfig.model);
return (
<article className="settings-model-card" key={role}>
<header className="settings-model-card-head">
<span className="settings-kicker">{role}</span>
<strong>{modelRoleLabel(role, t)}</strong>
<p className="settings-hint">{modelRoleHint(role, t)}</p>
{agentType ? (
<p className="settings-inline-meta">
{t.settings.models.agentTypeLabel}:{' '}
{agentTypeLabel(agentType, t)}
</p>
) : null}
</header>
<div className="settings-model-fields">
<label className="settings-row">
<span className="settings-label">
{t.settings.models.modelLabel}
</span>
<select
aria-label={`${modelRoleLabel(role, t)} ${t.settings.models.modelLabel}`}
onChange={(event) => {
const value = event.target.value;
if (value === '__custom__') {
onChange(role, {
model: usingCustom ? roleConfig.model : '',
});
return;
}
onChange(role, { model: value });
}}
value={usingCustom ? '__custom__' : roleConfig.model}
>
<option value="">{t.settings.models.modelDefault}</option>
<optgroup label={t.settings.models.groupCodex}>
{PRESET_MODELS.codex.map((model) => (
<option key={model} value={model}>
{model}
</option>
))}
</optgroup>
<optgroup label={t.settings.models.groupClaude}>
{PRESET_MODELS.claude.map((model) => (
<option key={model} value={model}>
{model}
</option>
))}
</optgroup>
<option value="__custom__">
{t.settings.models.modelCustom}
</option>
</select>
</label>
{usingCustom ? (
<label className="settings-row">
<span className="settings-label">
{t.settings.models.modelCustomLabel}
</span>
<input
onChange={(event) =>
onChange(role, { model: event.target.value })
}
placeholder={t.settings.models.modelPlaceholder}
type="text"
value={roleConfig.model}
/>
</label>
) : null}
<label className="settings-row">
<span className="settings-label">
{t.settings.models.effortLabel}
</span>
<select
aria-describedby={
effortInvalid ? `settings-effort-warn-${role}` : undefined
}
aria-invalid={effortInvalid || undefined}
aria-label={`${modelRoleLabel(role, t)} ${t.settings.models.effortLabel}`}
onChange={(event) =>
onChange(role, { effort: event.target.value })
}
value={roleConfig.effort}
>
{effortOptions.map((value) => (
<option key={value || 'default'} value={value}>
{effortLabel(value, t)}
</option>
))}
{effortInvalid ? (
<option value={roleConfig.effort}>
{effortLabel(roleConfig.effort as EffortValue, t)}
</option>
) : null}
</select>
</label>
{effortInvalid && agentType ? (
<p
className="settings-effort-warn"
id={`settings-effort-warn-${role}`}
role="alert"
>
{t.settings.models.effortInvalid
.replace('{value}', roleConfig.effort)
.replace('{agent}', agentTypeLabel(agentType, t))}
</p>
) : null}
{roleConfig.model || roleConfig.effort ? (
<p className="settings-inline-meta">
{roleConfig.model
? modelGroupLabel(roleConfig.model, t)
: t.settings.models.modelDefault}
{' · '}
{roleConfig.effort
? effortLabel(roleConfig.effort as EffortValue, t)
: t.settings.models.effortDefault}
</p>
) : null}
</div>
</article>
);
})}
</div>
);
}

View File

@@ -1,59 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { messages } from './i18n';
import { SettingsPanel, type SettingsPanelProps } from './SettingsPanel';
const t = messages.en;
const baseProps: SettingsPanelProps = {
locale: 'en',
nickname: 'Night Owl',
onLocaleChange: () => {},
onNicknameChange: () => {},
onRestartStack: () => {},
t,
};
describe('SettingsPanel', () => {
it('renders general nickname and language settings', () => {
const html = renderToStaticMarkup(createElement(SettingsPanel, baseProps));
expect(html).toContain('settings-panel');
expect(html).not.toContain('settings-hero');
expect(html).toContain('settings-sidebar');
expect(html).toContain('settings-nav');
expect(html).toContain(t.settings.nicknameLabel);
expect(html).toContain('value="Night Owl"');
expect(html).toContain(t.settings.languageLabel);
expect(html).toContain('한국어');
expect(html).toContain('English');
});
it('renders model, runtime, MoA, fast mode, and account controls', () => {
const html = renderToStaticMarkup(createElement(SettingsPanel, baseProps));
expect(html).toContain('role="tablist"');
expect(html).toContain('role="tabpanel"');
expect(html).toContain('aria-selected="true"');
expect(html).toContain('data-settings-target="settings-models"');
expect(html).toContain('data-settings-target="settings-runtime"');
expect(html).toContain('data-settings-target="settings-moa"');
expect(html).toContain('data-settings-target="settings-codex"');
expect(html).toContain('data-settings-target="settings-accounts"');
expect(html).toContain('aria-controls="settings-runtime"');
expect(html).toContain('aria-controls="settings-codex"');
expect(html).not.toContain('href="#settings-codex"');
expect(html).toContain('settings-apply-card');
expect(html).not.toContain('settings-apply-bar');
expect(html).toContain(t.settings.apply.title);
expect(html).toContain(t.settings.sections.runtime.title);
expect(html).toContain(t.settings.accounts.claude);
expect(html).toContain(t.settings.nav.accounts.title);
expect(html).toContain(t.settings.apply.restart);
expect(html.match(/class="settings-restart"/g)).toHaveLength(1);
expect(html).toContain('settings-card');
expect(html).toContain('settings-section-stack');
});
});

View File

@@ -1,837 +0,0 @@
import { useEffect, useState } from 'react';
import {
type ClaudeAccountSummary,
type CodexAccountSummary,
type CodexFeatureSnapshot,
type FastModeSnapshot,
type ModelConfigSnapshot,
type ModelRoleConfig,
addClaudeAccount,
deleteAccount,
fetchAccounts,
fetchCodexFeatures,
fetchFastMode,
fetchModelConfig,
refreshAllCodexAccounts as refreshAllCodexAccountsApi,
refreshCodexAccount as refreshCodexAccountApi,
setCurrentCodexAccount as setCurrentCodexAccountApi,
updateCodexFeatures,
updateFastMode,
updateModels,
} from './api';
import {
formatDateTime,
formatJwtCacheExpiry,
formatLiveStatusBadge,
formatUsageBadge,
} from './codexAccountBadges';
import { type Locale, type Messages } from './i18n';
import { MoaSettingsPanel } from './MoaSettingsPanel';
import { RuntimeInventorySettings } from './RuntimeInventorySettings';
import {
ModelRoleFields,
hasUnsupportedModelEffort,
type ModelRole,
} from './SettingsModelFields';
import {
GeneralSettings,
SettingsApplyCard,
SettingsCard,
SettingsNav,
SettingsSaveBar,
SettingsSectionHeading,
type SettingsSectionId,
} from './SettingsPanelChrome';
type AccountProvider = 'claude' | 'codex';
interface AccountData {
claude: ClaudeAccountSummary[];
codex: CodexAccountSummary[];
codexCurrentIndex?: number;
}
export interface SettingsPanelProps {
locale: Locale;
nickname: string;
onLocaleChange: (locale: Locale) => void;
onNicknameChange: (next: string) => void;
onRestartStack: () => void;
t: Messages;
}
export function SettingsPanel({
locale,
nickname,
onLocaleChange,
onNicknameChange,
onRestartStack,
t,
}: SettingsPanelProps) {
const [activeSection, setActiveSection] =
useState<SettingsSectionId>('settings-general');
return (
<div className="settings-panel">
<div className="settings-layout">
<aside className="settings-sidebar" aria-label={t.settings.sidebarAria}>
<SettingsNav
activeSection={activeSection}
onSelect={setActiveSection}
t={t}
/>
<SettingsApplyCard onRestartStack={onRestartStack} t={t} />
</aside>
<main className="settings-content" aria-label={t.settings.contentAria}>
<div hidden={activeSection !== 'settings-general'}>
<GeneralSettings
locale={locale}
nickname={nickname}
onLocaleChange={onLocaleChange}
onNicknameChange={onNicknameChange}
t={t}
/>
</div>
<div hidden={activeSection !== 'settings-models'}>
<ModelSettings t={t} />
</div>
<div hidden={activeSection !== 'settings-runtime'}>
<RuntimeInventorySettings t={t} />
</div>
<div hidden={activeSection !== 'settings-moa'}>
<MoaSettingsPanel t={t} />
</div>
<div hidden={activeSection !== 'settings-codex'}>
<CodexRuntimeSettings t={t} />
</div>
<div hidden={activeSection !== 'settings-accounts'}>
<AccountSettings t={t} />
</div>
</main>
</div>
</div>
);
}
function ModelSettings({ t }: { t: Messages }) {
const [config, setConfig] = useState<ModelConfigSnapshot | null>(null);
const [draft, setDraft] = useState<ModelConfigSnapshot | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [savedAt, setSavedAt] = useState<number | null>(null);
const section = t.settings.sections.models;
useEffect(() => {
let cancelled = false;
setBusy(true);
fetchModelConfig()
.then((c) => {
if (cancelled) return;
setConfig(c);
setDraft(c);
setError(null);
})
.catch((err) => {
if (cancelled) return;
setError(err instanceof Error ? err.message : String(err));
})
.finally(() => {
if (!cancelled) setBusy(false);
});
return () => {
cancelled = true;
};
}, []);
async function save() {
if (!draft || !config) return;
if (hasUnsupportedModelEffort(draft)) {
setError(t.settings.models.effortSaveBlocked);
return;
}
setBusy(true);
setError(null);
try {
const next = await updateModels({
owner: draft.owner,
reviewer: draft.reviewer,
arbiter: draft.arbiter,
});
setConfig(next);
setDraft(next);
setSavedAt(Date.now());
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
function setRole(role: ModelRole, patch: Partial<ModelRoleConfig>) {
setDraft((prev) =>
prev
? {
...prev,
[role]: { ...prev[role], ...patch },
}
: prev,
);
}
const dirty =
draft !== null &&
config !== null &&
JSON.stringify(draft) !== JSON.stringify(config);
const effortBlocked = draft !== null && hasUnsupportedModelEffort(draft);
return (
<section
aria-labelledby="settings-models-tab"
className="settings-section"
id="settings-models"
role="tabpanel"
>
<SettingsSectionHeading
description={section.description}
detail={section.kicker}
title={section.title}
/>
{error ? <p className="settings-error">{error}</p> : null}
{!draft ? (
<p className="settings-hint">
{busy ? t.settings.common.loading : t.settings.models.empty}
</p>
) : (
<>
<ModelRoleFields
draft={draft}
onChange={(role, patch) => setRole(role, patch)}
t={t}
/>
<SettingsSaveBar
busy={busy}
dirty={dirty}
label={t.settings.models.save}
onSave={() => void save()}
saveDisabled={effortBlocked}
savedHint={t.settings.common.savedRestartHint}
savingLabel={t.settings.common.saving}
showSavedHint={savedAt !== null && !dirty}
/>
</>
)}
</section>
);
}
function CodexRuntimeSettings({ t }: { t: Messages }) {
const section = t.settings.sections.codex;
return (
<section
aria-labelledby="settings-codex-tab"
className="settings-section"
id="settings-codex"
role="tabpanel"
>
<SettingsSectionHeading
description={section.description}
detail={section.kicker}
title={section.title}
/>
<div className="settings-section-stack">
<FastModeSettings t={t} />
<CodexFeatureSettings t={t} />
</div>
</section>
);
}
function FastModeSettings({ t }: { t: Messages }) {
const [state, setState] = useState<FastModeSnapshot | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
fetchFastMode()
.then((s) => {
if (cancelled) return;
setState(s);
setError(null);
})
.catch((err) => {
if (cancelled) return;
setError(err instanceof Error ? err.message : String(err));
});
return () => {
cancelled = true;
};
}, []);
async function toggle(provider: keyof FastModeSnapshot) {
if (!state) return;
const next = !state[provider];
const optimistic = { ...state, [provider]: next };
setState(optimistic);
setBusy(true);
setError(null);
try {
const fresh = await updateFastMode({ [provider]: next });
setState(fresh);
} catch (err) {
setState(state);
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
return (
<SettingsCard title={t.settings.codex.fastMode}>
{error ? <p className="settings-error">{error}</p> : null}
{!state ? (
<p className="settings-hint">{t.settings.common.loading}</p>
) : (
<div className="settings-toggle-stack">
<label className="settings-toggle-row">
<span className="settings-toggle-label">
<span className="settings-toggle-title">
{t.settings.codex.codexFast}
</span>
<small className="settings-hint">
{t.settings.codex.codexFastHint}
</small>
</span>
<input
checked={state.codex}
disabled={busy}
onChange={() => void toggle('codex')}
type="checkbox"
/>
</label>
<label className="settings-toggle-row">
<span className="settings-toggle-label">
<span className="settings-toggle-title">
{t.settings.codex.claudeFast}
</span>
<small className="settings-hint">
{t.settings.codex.claudeFastHint}
</small>
</span>
<input
checked={state.claude}
disabled={busy}
onChange={() => void toggle('claude')}
type="checkbox"
/>
</label>
<small className="settings-hint">
{t.settings.codex.fastModeApplyHint}
</small>
</div>
)}
</SettingsCard>
);
}
function CodexFeatureSettings({ t }: { t: Messages }) {
const [state, setState] = useState<CodexFeatureSnapshot | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
fetchCodexFeatures()
.then((snapshot) => {
if (cancelled) return;
setState(snapshot);
setError(null);
})
.catch((err) => {
if (cancelled) return;
setError(err instanceof Error ? err.message : String(err));
});
return () => {
cancelled = true;
};
}, []);
async function toggleGoals() {
if (!state) return;
const previous = state;
const optimistic = { ...state, goals: !state.goals };
setState(optimistic);
setBusy(true);
setError(null);
try {
const fresh = await updateCodexFeatures({ goals: optimistic.goals });
setState(fresh);
} catch (err) {
setState(previous);
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
return (
<SettingsCard title={t.settings.codex.features}>
{error ? <p className="settings-error">{error}</p> : null}
{!state ? (
<p className="settings-hint">{t.settings.common.loading}</p>
) : (
<>
<label className="settings-toggle-row">
<span className="settings-toggle-label">
<span className="settings-toggle-title">
{t.settings.codex.goal}
</span>
<small className="settings-hint">
{t.settings.codex.goalHint}
</small>
</span>
<input
checked={state.goals}
disabled={busy}
onChange={() => void toggleGoals()}
type="checkbox"
/>
</label>
<small className="settings-hint">
{t.settings.codex.goalApplyHint}
</small>
</>
)}
</SettingsCard>
);
}
function AccountSettings({ t }: { t: Messages }) {
const [data, setData] = useState<AccountData | null>(null);
const [busy, setBusy] = useState(false);
const [perRowBusy, setPerRowBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [tokenInput, setTokenInput] = useState('');
const section = t.settings.sections.accounts;
async function refresh() {
setBusy(true);
setError(null);
try {
const fresh = await fetchAccounts();
setData(fresh);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
useEffect(() => {
void refresh();
}, []);
async function handleDelete(provider: AccountProvider, index: number) {
if (
!window.confirm(
t.settings.accounts.deleteConfirm
.replace('{provider}', provider)
.replace('{index}', String(index)),
)
) {
return;
}
setBusy(true);
setError(null);
try {
await deleteAccount(provider, index);
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
async function handleAdd() {
const token = tokenInput.trim();
if (!token) return;
setBusy(true);
setError(null);
try {
await addClaudeAccount(token);
setTokenInput('');
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
async function handleCodexRefresh(index: number) {
setPerRowBusy(`refresh:${index}`);
setError(null);
try {
await refreshCodexAccountApi(index);
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setPerRowBusy(null);
}
}
async function handleRefreshAllCodex() {
setBusy(true);
setError(null);
try {
const result = await refreshAllCodexAccountsApi();
await refresh();
if (result.failed.length > 0) {
setError(
t.settings.accounts.refreshFailed.replace(
'{indexes}',
result.failed.map((f) => `#${f.index}`).join(', '),
),
);
}
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
async function handleSwitchCodex(index: number) {
setPerRowBusy(`switch:${index}`);
setError(null);
try {
await setCurrentCodexAccountApi(index);
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setPerRowBusy(null);
}
}
return (
<section
aria-labelledby="settings-accounts-tab"
className="settings-section"
id="settings-accounts"
role="tabpanel"
>
<SettingsSectionHeading
description={section.description}
detail={section.kicker}
title={section.title}
/>
{error ? <p className="settings-error">{error}</p> : null}
<div className="settings-section-stack">
<ClaudeAccounts
busy={busy}
data={data}
onAdd={() => void handleAdd()}
onDelete={(index) => void handleDelete('claude', index)}
onTokenInputChange={setTokenInput}
t={t}
tokenInput={tokenInput}
/>
<CodexAccounts
busy={busy}
data={data}
onDelete={(index) => void handleDelete('codex', index)}
onRefresh={(index) => void handleCodexRefresh(index)}
onRefreshAll={() => void handleRefreshAllCodex()}
onSwitch={(index) => void handleSwitchCodex(index)}
perRowBusy={perRowBusy}
t={t}
/>
</div>
</section>
);
}
function ClaudeAccounts({
busy,
data,
onAdd,
onDelete,
onTokenInputChange,
tokenInput,
t,
}: {
busy: boolean;
data: AccountData | null;
onAdd: () => void;
onDelete: (index: number) => void;
onTokenInputChange: (value: string) => void;
tokenInput: string;
t: Messages;
}) {
return (
<SettingsCard title={t.settings.accounts.claude}>
{!data ? (
<p className="settings-hint">
{busy ? t.settings.common.loading : t.settings.common.none}
</p>
) : data.claude.length === 0 ? (
<p className="settings-hint">{t.settings.accounts.noAccounts}</p>
) : (
<ul className="settings-account-list">
{data.claude.map((acc) => (
<li key={acc.index}>
<article
className={`settings-account-row${acc.index === 0 ? ' is-primary' : ''}`}
>
<div className="settings-account-row-main">
<span className="settings-account-index">#{acc.index}</span>
<div className="settings-account-row-copy">
<strong>{acc.subscriptionType ?? 'unknown'}</strong>
<span className="settings-hint">
{acc.rateLimitTier ?? 'claude-code'}
{' · '}
{t.settings.accounts.autoRefresh}
</span>
</div>
{acc.index === 0 ? (
<span className="settings-pill is-primary is-compact">
{t.settings.accounts.primaryAccount}
</span>
) : null}
</div>
{acc.index > 0 ? (
<div className="settings-account-actions">
<button
className="settings-delete"
disabled={busy}
onClick={() => onDelete(acc.index)}
type="button"
>
{t.settings.common.delete}
</button>
</div>
) : null}
</article>
</li>
))}
</ul>
)}
<div className="settings-add-token">
<label className="settings-row">
<span className="settings-label">
{t.settings.accounts.addTokenLabel}
</span>
<textarea
onChange={(e) => onTokenInputChange(e.target.value)}
placeholder={t.settings.accounts.tokenPlaceholder}
rows={2}
value={tokenInput}
/>
</label>
<button
className="settings-save"
disabled={!tokenInput.trim() || busy}
onClick={onAdd}
type="button"
>
{t.settings.common.add}
</button>
</div>
</SettingsCard>
);
}
function CodexAccounts({
busy,
data,
onDelete,
onRefresh,
onRefreshAll,
onSwitch,
perRowBusy,
t,
}: {
busy: boolean;
data: AccountData | null;
onDelete: (index: number) => void;
onRefresh: (index: number) => void;
onRefreshAll: () => void;
onSwitch: (index: number) => void;
perRowBusy: string | null;
t: Messages;
}) {
return (
<SettingsCard
actions={
<button
className="settings-secondary"
disabled={busy}
onClick={onRefreshAll}
type="button"
>
{t.settings.common.refreshAll}
</button>
}
description={t.settings.accounts.codexRefreshHint}
title={t.settings.accounts.codex}
>
{!data ? (
<p className="settings-hint">
{busy ? t.settings.common.loading : t.settings.common.none}
</p>
) : data.codex.length === 0 ? (
<p className="settings-hint">{t.settings.accounts.noAccounts}</p>
) : (
<ul className="settings-account-list">
{data.codex.map((acc) => (
<li key={acc.index}>
<CodexAccountRow
acc={acc}
busy={busy}
isActive={data.codexCurrentIndex === acc.index}
onDelete={onDelete}
onRefresh={onRefresh}
onSwitch={onSwitch}
perRowBusy={perRowBusy}
t={t}
/>
</li>
))}
</ul>
)}
</SettingsCard>
);
}
function CodexAccountRow({
acc,
busy,
isActive,
onDelete,
onRefresh,
onSwitch,
perRowBusy,
t,
}: {
acc: CodexAccountSummary;
busy: boolean;
isActive: boolean;
onDelete: (index: number) => void;
onRefresh: (index: number) => void;
onSwitch: (index: number) => void;
perRowBusy: string | null;
t: Messages;
}) {
const liveBadge = formatLiveStatusBadge(acc.liveStatus);
const usageBadge = formatUsageBadge(acc.liveStatus);
const cachedExpiry = acc.liveStatus
? null
: formatJwtCacheExpiry(acc.subscriptionUntil);
const checkedAt = acc.subscriptionLastChecked
? formatDateTime(acc.subscriptionLastChecked)
: null;
const refreshing = perRowBusy === `refresh:${acc.index}`;
const switching = perRowBusy === `switch:${acc.index}`;
return (
<article
className={`settings-account-row${isActive ? ' is-active-account' : ''}`}
>
<div className="settings-account-row-main">
<span className="settings-account-index">#{acc.index}</span>
<div className="settings-account-row-copy">
<strong>{acc.email ?? acc.planType ?? 'Codex account'}</strong>
<span className="settings-account-row-meta">
<span className="settings-account-plan">
{acc.planType ?? 'unknown'}
</span>
{liveBadge ? (
<span
className={`settings-account-badge ${liveBadge.cls}`}
title={liveBadge.title}
>
{liveBadge.label}
</span>
) : cachedExpiry ? (
<span
className={`settings-account-badge ${cachedExpiry.cls}`}
title={cachedExpiry.title}
>
{cachedExpiry.label}
</span>
) : null}
{usageBadge ? (
<span
className="settings-account-badge is-muted"
title={usageBadge.title}
>
{usageBadge.label}
</span>
) : null}
{checkedAt ? (
<span
className="settings-account-badge is-muted"
title={
acc.liveStatus
? 'wham/usage live checked_at'
: 'JWT subscription_last_checked cache'
}
>
{t.settings.common.refresh} {checkedAt}
</span>
) : null}
</span>
</div>
{isActive ? (
<span className="settings-pill is-active is-compact">
{t.settings.accounts.activeAccount}
</span>
) : null}
</div>
<div className="settings-account-actions">
<button
className="settings-secondary"
disabled={busy || perRowBusy !== null}
onClick={() => onRefresh(acc.index)}
title={t.settings.accounts.refreshTitle}
type="button"
>
{refreshing
? t.settings.common.refreshing
: t.settings.common.refresh}
</button>
{!isActive ? (
<button
className="settings-secondary"
disabled={busy || perRowBusy !== null}
onClick={() => onSwitch(acc.index)}
title={t.settings.accounts.switchTitle}
type="button"
>
{switching ? t.settings.common.switching : t.settings.common.switch}
</button>
) : null}
{acc.index > 0 ? (
<button
className="settings-delete"
disabled={busy || perRowBusy !== null}
onClick={() => onDelete(acc.index)}
type="button"
>
{t.settings.common.delete}
</button>
) : null}
</div>
</article>
);
}

View File

@@ -1,267 +0,0 @@
import { useState, type ReactNode } from 'react';
import { LOCALES, languageNames, type Locale, type Messages } from './i18n';
export const SETTINGS_NAV_ITEMS = [
{ targetId: 'settings-general', navKey: 'general' },
{ targetId: 'settings-models', navKey: 'models' },
{ targetId: 'settings-runtime', navKey: 'runtime' },
{ targetId: 'settings-moa', navKey: 'moa' },
{ targetId: 'settings-codex', navKey: 'codex' },
{ targetId: 'settings-accounts', navKey: 'accounts' },
] as const;
export type SettingsSectionId = (typeof SETTINGS_NAV_ITEMS)[number]['targetId'];
type SettingsNavKey = (typeof SETTINGS_NAV_ITEMS)[number]['navKey'];
function navItem(t: Messages, navKey: SettingsNavKey) {
return t.settings.nav[navKey];
}
export function SettingsNav({
activeSection,
onSelect,
t,
}: {
activeSection: SettingsSectionId;
onSelect: (section: SettingsSectionId) => void;
t: Messages;
}) {
return (
<div className="settings-nav-scroll">
<div
className="settings-nav"
aria-label={t.settings.navAria}
role="tablist"
>
{SETTINGS_NAV_ITEMS.map((item) => {
const copy = navItem(t, item.navKey);
return (
<button
aria-controls={item.targetId}
aria-selected={activeSection === item.targetId}
data-settings-target={item.targetId}
id={`${item.targetId}-tab`}
key={item.targetId}
onClick={() => onSelect(item.targetId)}
role="tab"
type="button"
>
<strong>{copy.title}</strong>
<small>{copy.detail}</small>
</button>
);
})}
</div>
</div>
);
}
export function GeneralSettings({
locale,
nickname,
onLocaleChange,
onNicknameChange,
t,
}: {
locale: Locale;
nickname: string;
onLocaleChange: (locale: Locale) => void;
onNicknameChange: (next: string) => void;
t: Messages;
}) {
const section = t.settings.sections.general;
return (
<section
aria-labelledby="settings-general-tab"
className="settings-section"
id="settings-general"
role="tabpanel"
>
<SettingsSectionHeading
description={section.description}
detail={section.kicker}
title={section.title}
/>
<div className="settings-card">
<div className="settings-form-grid">
<label className="settings-row">
<span className="settings-label">{t.settings.nicknameLabel}</span>
<input
maxLength={32}
onChange={(event) => onNicknameChange(event.target.value)}
placeholder={t.settings.nicknamePlaceholder}
type="text"
value={nickname}
/>
<small className="settings-hint">{t.settings.nicknameHelp}</small>
</label>
<label className="settings-row">
<span className="settings-label">{t.settings.languageLabel}</span>
<select
aria-label={t.settings.languageLabel}
onChange={(event) => onLocaleChange(event.target.value as Locale)}
value={locale}
>
{LOCALES.map((item) => (
<option key={item} value={item}>
{languageNames[item]}
</option>
))}
</select>
</label>
</div>
</div>
</section>
);
}
export function SettingsSectionHeading({
detail,
title,
description,
}: {
detail: string;
title: string;
description: string;
}) {
return (
<header className="settings-section-head">
<span>{detail}</span>
<h3>{title}</h3>
<p>{description}</p>
</header>
);
}
export function SettingsCard({
title,
description,
actions,
children,
}: {
title?: string;
description?: string;
actions?: ReactNode;
children: ReactNode;
}) {
return (
<section className="settings-card">
{title || description || actions ? (
<header className="settings-card-head">
<div>
{title ? <h4>{title}</h4> : null}
{description ? (
<p className="settings-hint">{description}</p>
) : null}
</div>
{actions ? (
<div className="settings-card-actions">{actions}</div>
) : null}
</header>
) : null}
{children}
</section>
);
}
export function SettingsCollapsible({
title,
description,
defaultOpen = false,
children,
}: {
title: string;
description?: string;
defaultOpen?: boolean;
children: ReactNode;
}) {
const [open, setOpen] = useState(defaultOpen);
return (
<section className={`settings-collapsible${open ? ' is-open' : ''}`}>
<button
aria-expanded={open}
className="settings-collapsible-trigger"
onClick={() => setOpen((value) => !value)}
type="button"
>
<span className="settings-collapsible-text">
<strong>{title}</strong>
{description ? <small>{description}</small> : null}
</span>
<span aria-hidden="true" className="settings-collapsible-chevron">
{open ? '▾' : '▸'}
</span>
</button>
{open ? (
<div className="settings-collapsible-body">{children}</div>
) : null}
</section>
);
}
export function SettingsSaveBar({
busy,
dirty,
label,
savingLabel,
onSave,
savedHint,
showSavedHint,
saveDisabled = false,
}: {
busy: boolean;
dirty: boolean;
label: string;
savingLabel: string;
onSave: () => void;
savedHint?: string;
showSavedHint?: boolean;
saveDisabled?: boolean;
}) {
return (
<div className="settings-actions">
<button
className="settings-save"
disabled={!dirty || busy || saveDisabled}
onClick={onSave}
type="button"
>
{busy ? savingLabel : label}
</button>
{showSavedHint && savedHint ? (
<small className="settings-hint">{savedHint}</small>
) : null}
</div>
);
}
export function SettingsApplyCard({
onRestartStack,
t,
}: {
onRestartStack: () => void;
t: Messages;
}) {
const apply = t.settings.apply;
return (
<section aria-label={apply.aria} className="settings-apply-card">
<div>
<span className="settings-kicker">{apply.kicker}</span>
<strong>{apply.title}</strong>
<small>{apply.hint}</small>
</div>
<button
className="settings-restart"
onClick={onRestartStack}
type="button"
>
{apply.restart}
</button>
</section>
);
}

View File

@@ -1,99 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import type { DashboardOverview } from './api';
import { messages } from './i18n';
import { SystemStatusStrip } from './SystemStatusStrip';
const t = messages.en;
function overview(
overrides: Partial<DashboardOverview> = {},
): DashboardOverview {
return {
generatedAt: '2026-04-28T04:15:00.000Z',
inbox: [],
operations: { serviceRestarts: [] },
rooms: { active: 0, inactive: 0, total: 0, waiting: 0 },
services: [
{
activeRooms: 2,
agentType: 'codex',
assistantName: 'owner',
serviceId: 'svc-owner',
totalRooms: 3,
updatedAt: '2026-04-28T04:14:00.000Z',
},
],
tasks: {
active: 0,
completed: 0,
paused: 0,
total: 0,
watchers: { active: 0, completed: 0, paused: 0 },
},
usage: { fetchedAt: '2026-04-28T04:15:00.000Z', rows: [] },
...overrides,
};
}
describe('SystemStatusStrip', () => {
it('stays hidden when services and CI watchers are healthy', () => {
const html = renderToStaticMarkup(
createElement(SystemStatusStrip, { overview: overview(), t }),
);
expect(html).toBe('');
});
it('surfaces paused CI watchers as a room-level system warning', () => {
const html = renderToStaticMarkup(
createElement(SystemStatusStrip, {
overview: overview({
tasks: {
active: 0,
completed: 0,
paused: 2,
total: 2,
watchers: { active: 0, completed: 0, paused: 2 },
},
}),
t,
}),
);
expect(html).toContain('system-status-strip');
expect(html).toContain(t.health.ciFailures);
expect(html).toContain('2');
});
it('surfaces stale and missing service heartbeat signals', () => {
const staleHtml = renderToStaticMarkup(
createElement(SystemStatusStrip, {
overview: overview({
services: [
{
activeRooms: 0,
agentType: 'claude',
assistantName: 'reviewer',
serviceId: 'svc-reviewer',
totalRooms: 1,
updatedAt: '2026-04-28T03:58:00.000Z',
},
],
}),
t,
}),
);
const missingHtml = renderToStaticMarkup(
createElement(SystemStatusStrip, {
overview: overview({ services: [] }),
t,
}),
);
expect(staleHtml).toContain(t.health.levels.down);
expect(missingHtml).toContain(t.service.empty);
});
});

View File

@@ -1,66 +0,0 @@
import type { DashboardOverview } from './api';
import type { Messages } from './i18n';
type HealthLevel = 'stale' | 'down';
type ServiceRow = DashboardOverview['services'][number];
export interface SystemStatusStripProps {
overview: DashboardOverview;
t: Messages;
}
const HEALTH_STALE_MS = 5 * 60_000;
const HEALTH_DOWN_MS = 15 * 60_000;
function serviceAgeMs(service: ServiceRow, generatedAt: string): number | null {
const updated = new Date(service.updatedAt).getTime();
const now = new Date(generatedAt).getTime();
if (Number.isNaN(updated) || Number.isNaN(now)) return null;
return Math.max(0, now - updated);
}
function serviceHealthLevel(
service: ServiceRow,
generatedAt: string,
): HealthLevel | null {
const age = serviceAgeMs(service, generatedAt);
if (age === null) return 'stale';
if (age >= HEALTH_DOWN_MS) return 'down';
if (age >= HEALTH_STALE_MS) return 'stale';
return null;
}
export function SystemStatusStrip({ overview, t }: SystemStatusStripProps) {
const serviceLevels = overview.services.map((service) =>
serviceHealthLevel(service, overview.generatedAt),
);
const down = serviceLevels.filter((level) => level === 'down').length;
const stale = serviceLevels.filter((level) => level === 'stale').length;
const ciPaused = overview.tasks.watchers.paused;
const hasNoHeartbeat = overview.services.length === 0;
const level: HealthLevel = hasNoHeartbeat || down > 0 ? 'down' : 'stale';
if (!hasNoHeartbeat && down === 0 && stale === 0 && ciPaused === 0) {
return null;
}
const signals: string[] = [];
if (hasNoHeartbeat) signals.push(t.service.empty);
if (down > 0) signals.push(`${down} ${t.health.levels.down}`);
if (stale > 0) signals.push(`${stale} ${t.health.stale}`);
if (ciPaused > 0) signals.push(`${ciPaused} ${t.health.ciFailures}`);
return (
<aside
aria-label={t.health.signals}
className={`system-status-strip system-status-${level}`}
role="status"
>
<div>
<span className="eyebrow">{t.health.system}</span>
<strong>{t.health.levels[level]}</strong>
</div>
<p>{signals.join(' · ')}</p>
</aside>
);
}

View File

@@ -1,50 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import type { DashboardTask } from './api';
import { messages } from './i18n';
import { TaskActionButtons } from './TaskActionButtons';
const t = messages.en;
const task: DashboardTask = {
agentType: 'codex',
chatJid: 'room-1',
ciMetadata: null,
ciProvider: null,
contextMode: 'group',
createdAt: '2026-04-28T04:00:00.000Z',
groupFolder: 'eyejokerdb',
id: 'task-1',
isWatcher: false,
lastResult: null,
lastRun: null,
nextRun: '2026-04-28T05:00:00.000Z',
promptLength: 42,
promptPreview: 'Run production check',
scheduleType: 'interval',
scheduleValue: '10m',
status: 'active',
suspendedUntil: null,
};
describe('TaskActionButtons', () => {
it('renders task actions with shared busy state styling', () => {
const html = renderToStaticMarkup(
createElement(TaskActionButtons, {
className: 'inbox-actions',
onTaskAction: () => {},
task,
taskActionKey: 'task-1:pause',
t,
}),
);
expect(html).toContain('task-actions inbox-actions');
expect(html).toContain('task-action task-action-pause is-busy');
expect(html).toContain('aria-busy="true"');
expect(html).toContain(t.tasks.actions.busy);
expect(html).toContain(t.tasks.actions.cancel);
});
});

View File

@@ -1,52 +0,0 @@
import type { DashboardTask, DashboardTaskAction } from './api';
import { taskActionsFor } from './dashboardHelpers';
import type { Messages } from './i18n';
export type TaskActionKey =
| 'create'
| `${string}:edit`
| `${string}:${DashboardTaskAction}`;
interface TaskActionButtonsProps {
className?: string;
onTaskAction: (task: DashboardTask, action: DashboardTaskAction) => void;
task: DashboardTask;
taskActionKey: string | null;
t: Messages;
}
export function TaskActionButtons({
className,
onTaskAction,
task,
taskActionKey,
t,
}: TaskActionButtonsProps) {
const taskActions = taskActionsFor(task);
if (taskActions.length === 0) return null;
const rootClassName = className
? `task-actions ${className}`
: 'task-actions';
return (
<div className={rootClassName}>
{taskActions.map((action) => {
const actionKey: TaskActionKey = `${task.id}:${action}`;
const busy = taskActionKey === actionKey;
return (
<button
aria-busy={busy || undefined}
className={`task-action task-action-${action}${busy ? ' is-busy' : ''}`}
disabled={busy}
key={action}
onClick={() => onTaskAction(task, action)}
type="button"
>
{busy ? t.tasks.actions.busy : t.tasks.actions[action]}
</button>
);
})}
</div>
);
}

View File

@@ -1,647 +0,0 @@
.task-board {
display: grid;
gap: 10px;
min-width: 0;
}
.task-summary-bar {
display: flex;
gap: 10px;
align-items: stretch;
justify-content: space-between;
padding: 12px 14px;
border: 1px solid var(--panel-border);
border-radius: 14px;
background: rgba(255, 255, 255, 0.03);
}
.task-summary-next {
display: grid;
gap: 2px;
min-width: 0;
flex: 1 1 auto;
}
.task-summary-next small {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.task-summary-next strong {
font-size: 20px;
line-height: 1.1;
letter-spacing: -0.04em;
}
.task-summary-next span {
overflow: hidden;
color: var(--muted);
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.task-summary-chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
align-content: center;
justify-content: flex-end;
flex: none;
}
.task-chip {
display: inline-flex;
min-height: 26px;
align-items: center;
padding: 0 8px;
border: 1px solid var(--panel-border);
border-radius: 999px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
white-space: nowrap;
background: rgba(255, 255, 255, 0.03);
}
.task-filter-scroll {
min-width: 0;
width: 100%;
border-bottom: 1px solid var(--panel-border);
}
.task-filter-tabs {
display: flex;
gap: 8px;
overflow-x: auto;
overflow-y: hidden;
padding: 6px 0 10px;
-webkit-overflow-scrolling: touch;
}
.task-filter-tab {
display: grid;
gap: 1px;
flex: 0 0 auto;
min-width: 72px;
min-height: 46px;
padding: 7px 10px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(19, 24, 22, 0.72);
color: var(--muted);
font: inherit;
text-align: left;
cursor: pointer;
}
.task-filter-tab[aria-selected='true'] {
border-color: rgba(214, 130, 88, 0.38);
background: rgba(214, 130, 88, 0.12);
color: var(--bg-ink);
}
.task-filter-tab strong {
font-size: 12px;
}
.task-filter-tab small {
color: inherit;
font-size: 10px;
opacity: 0.85;
}
.task-create-panel {
border: 1px solid var(--panel-border);
border-radius: 14px;
background: rgba(255, 255, 255, 0.025);
}
.task-create-panel > summary {
padding: 12px 14px;
color: var(--accent-strong);
font-size: 13px;
font-weight: 800;
cursor: pointer;
list-style: none;
}
.task-create-panel > summary::-webkit-details-marker {
display: none;
}
.task-create-form {
display: grid;
gap: 10px;
padding: 0 12px 12px;
}
.task-create-hint {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.task-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.task-create-form label,
.task-edit-form label {
display: grid;
gap: 4px;
min-width: 0;
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
.task-create-form input,
.task-create-form select,
.task-create-form textarea,
.task-edit-form input,
.task-edit-form select,
.task-edit-form textarea {
width: 100%;
min-height: 40px;
padding: 8px 10px;
border: 1px solid var(--panel-border-strong);
border-radius: 10px;
background: var(--bg-card);
color: var(--bg-ink);
font: inherit;
font-size: 13px;
}
.task-create-form textarea,
.task-edit-form textarea {
min-height: 72px;
resize: vertical;
}
.task-create-form button,
.task-edit-form button {
justify-self: start;
min-height: 40px;
padding: 0 16px;
border: 0;
border-radius: 999px;
background: var(--accent);
color: var(--bg);
font: inherit;
font-size: 12px;
font-weight: 800;
cursor: pointer;
}
.task-create-form button:disabled,
.task-edit-form button:disabled {
cursor: progress;
opacity: 0.55;
}
.task-form-wide {
grid-column: 1 / -1;
}
.task-lanes {
display: grid;
gap: 8px;
}
.task-group {
display: grid;
gap: 6px;
min-width: 0;
}
.task-group-completed {
padding: 10px 12px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(255, 255, 255, 0.02);
}
.task-group-completed summary {
cursor: pointer;
list-style: none;
}
.task-group-completed summary::-webkit-details-marker {
display: none;
}
.task-group-head {
display: flex;
gap: 8px;
align-items: center;
justify-content: space-between;
padding: 0 2px;
}
.task-group-head strong {
font-size: 13px;
letter-spacing: -0.02em;
}
.task-list {
display: grid;
gap: 4px;
}
.task-row {
display: grid;
gap: 0;
min-width: 0;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(255, 255, 255, 0.02);
}
.task-row-head {
display: flex;
gap: 10px;
align-items: flex-start;
justify-content: space-between;
padding: 8px 10px;
}
.task-row-lead {
display: flex;
gap: 8px;
align-items: flex-start;
min-width: 0;
flex: 1 1 auto;
}
.task-row-copy {
display: grid;
gap: 2px;
min-width: 0;
}
.task-kind {
color: var(--accent-strong);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.task-row-copy strong {
overflow: hidden;
font-size: 13px;
line-height: 1.35;
letter-spacing: -0.02em;
text-overflow: ellipsis;
white-space: nowrap;
}
.task-meta-strip {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.task-meta-strip span {
display: inline-flex;
max-width: 100%;
min-height: 20px;
align-items: center;
padding: 0 7px;
overflow: hidden;
border-radius: 999px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
background: rgba(255, 255, 255, 0.04);
text-overflow: ellipsis;
white-space: nowrap;
}
.task-row-aside {
display: grid;
gap: 6px;
justify-items: end;
flex: none;
}
.task-row-next {
display: grid;
gap: 1px;
justify-items: end;
text-align: right;
}
.task-row-next small,
.task-row-next em {
color: var(--muted);
font-size: 10px;
font-style: normal;
font-weight: 600;
}
.task-row-next strong {
font-size: 13px;
letter-spacing: -0.02em;
}
.task-row-actions {
justify-content: flex-end;
}
.task-actions {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.task-action {
min-height: 30px;
padding: 0 10px;
border: 1px solid var(--panel-border-strong);
border-radius: 999px;
background: rgba(255, 255, 255, 0.04);
color: var(--bg-ink);
font: inherit;
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
.task-action:hover,
.task-action:focus-visible {
border-color: rgba(214, 130, 88, 0.42);
outline: none;
box-shadow: 0 0 0 2px rgba(214, 130, 88, 0.12);
}
.task-action:disabled {
cursor: progress;
opacity: 0.55;
}
.task-action.is-busy {
display: inline-flex;
gap: 6px;
align-items: center;
justify-content: center;
border-color: rgba(214, 130, 88, 0.32);
background: rgba(214, 130, 88, 0.12);
}
.task-action.is-busy::before {
content: '';
display: block;
width: 10px;
height: 10px;
border: 2px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: ej-spin 0.7s linear infinite;
}
@keyframes ej-spin {
to {
transform: rotate(360deg);
}
}
.task-action-cancel {
color: #8f2f22;
border-color: rgba(183, 71, 52, 0.22);
background: rgba(183, 71, 52, 0.08);
}
.task-row-details {
border-top: 1px solid var(--panel-border);
}
.task-row-details > summary {
padding: 7px 10px;
color: var(--muted);
font-size: 11px;
font-weight: 800;
cursor: pointer;
list-style: none;
}
.task-row-details > summary::-webkit-details-marker {
display: none;
}
.task-row-details-body {
display: grid;
gap: 8px;
padding: 0 10px 10px;
}
.task-time-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 6px;
}
.task-time-grid > span,
.task-suspended,
.task-result {
display: grid;
gap: 2px;
min-width: 0;
padding: 8px;
border: 1px solid var(--panel-border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.02);
}
.task-next-run {
border-color: rgba(214, 130, 88, 0.25);
background: rgba(214, 130, 88, 0.08);
}
.task-time-grid small,
.task-suspended span,
.task-result span,
.task-time-grid em,
.task-suspended em {
color: var(--muted);
font-size: 10px;
font-style: normal;
font-weight: 600;
}
.task-time-grid strong,
.task-suspended strong,
.task-result strong {
overflow: hidden;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.task-suspended {
border-color: rgba(181, 138, 34, 0.22);
background: rgba(181, 138, 34, 0.08);
}
.task-result {
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: 8px;
border-color: rgba(63, 127, 81, 0.15);
}
.result-fail {
border-color: rgba(183, 71, 52, 0.28);
background: rgba(183, 71, 52, 0.08);
}
.result-none {
border-color: rgba(109, 115, 95, 0.14);
}
.task-prompt-block {
display: grid;
gap: 4px;
padding: 8px;
border: 1px solid var(--panel-border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.02);
}
.task-prompt-block > span {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.task-prompt-block p {
margin: 0;
overflow-wrap: anywhere;
font-size: 12px;
line-height: 1.45;
}
.task-prompt-block small {
overflow: hidden;
color: var(--muted);
font-family: 'JetBrains Mono', ui-monospace, monospace;
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.task-edit {
border: 1px solid var(--panel-border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.02);
}
.task-edit > summary {
padding: 8px 10px;
color: var(--accent-strong);
font-size: 11px;
font-weight: 800;
cursor: pointer;
list-style: none;
}
.task-edit > summary::-webkit-details-marker {
display: none;
}
.task-edit-form {
display: grid;
gap: 8px;
padding: 0 10px 10px;
}
.task-group-empty {
padding: 10px 12px;
border-radius: 10px;
color: var(--muted);
font-size: 12px;
background: rgba(255, 255, 255, 0.02);
}
.pill-watchers {
color: #d7f5e7;
background: rgba(80, 180, 130, 0.14);
}
.pill-scheduled,
.pill-paused {
color: #f0dfaa;
background: rgba(181, 138, 34, 0.16);
}
.pill-completed {
color: var(--muted);
background: rgba(109, 115, 95, 0.16);
}
@media (max-width: 760px) {
.task-summary-bar {
flex-direction: column;
padding: 10px 12px;
}
.task-summary-chips {
justify-content: flex-start;
}
.task-form-grid {
grid-template-columns: 1fr;
}
.task-create-form button {
width: 100%;
justify-self: stretch;
}
.task-row-head {
flex-direction: column;
gap: 8px;
}
.task-row-aside {
width: 100%;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
justify-items: stretch;
}
.task-row-next {
justify-items: start;
text-align: left;
}
.task-row-actions {
justify-content: flex-end;
}
.task-time-grid {
grid-template-columns: 1fr;
}
.task-action {
min-height: 36px;
padding-inline: 12px;
font-size: 11px;
}
}
@media (max-width: 640px) {
.task-filter-tab {
min-width: 64px;
min-height: 44px;
}
}

View File

@@ -1,67 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import type { DashboardTask } from './api';
import { messages } from './i18n';
import { TaskPanel, type TaskPanelProps } from './TaskPanel';
const t = messages.en;
const task: DashboardTask = {
agentType: 'codex',
chatJid: 'room-1',
ciMetadata: null,
ciProvider: null,
contextMode: 'group',
createdAt: '2026-04-28T04:00:00.000Z',
groupFolder: 'eyejokerdb',
id: 'task-1',
isWatcher: false,
lastResult: '<internal>hidden</internal>Task completed',
lastRun: '2026-04-28T04:30:00.000Z',
nextRun: '2026-04-28T05:00:00.000Z',
promptLength: 42,
promptPreview: '<internal>hidden</internal>Run production check',
scheduleType: 'interval',
scheduleValue: '10m',
status: 'active',
suspendedUntil: null,
};
const baseProps: TaskPanelProps = {
locale: 'en',
onTaskAction: () => {},
onTaskCreate: () => {},
onTaskUpdate: () => {},
rooms: [{ folder: 'eyejokerdb', jid: 'room-1', name: 'eyejokerdb-main' }],
taskActionKey: null,
tasks: [task],
t,
};
describe('TaskPanel', () => {
it('renders task groups, actions, and sanitized previews', () => {
const html = renderToStaticMarkup(createElement(TaskPanel, baseProps));
expect(html).toContain(t.tasks.groups.scheduled);
expect(html).toContain('eyejokerdb-main');
expect(html).toContain(t.tasks.next);
expect(html).toContain('10m');
expect(html).toContain(t.tasks.actions.pause);
expect(html).toContain(t.tasks.actions.cancel);
expect(html).toContain('Task completed');
expect(html).toContain('Run production check');
expect(html).toContain('task-row');
expect(html).toContain('task-filter-tabs');
expect(html).not.toContain('internal');
});
it('renders an empty state without scheduled tasks', () => {
const html = renderToStaticMarkup(
createElement(TaskPanel, { ...baseProps, tasks: [] }),
);
expect(html).toContain(t.tasks.empty);
});
});

View File

@@ -1,881 +0,0 @@
import { useMemo, useState } from 'react';
import type {
CreateScheduledTaskInput,
DashboardTask,
DashboardTaskAction,
DashboardTaskContextMode,
DashboardTaskScheduleType,
UpdateScheduledTaskInput,
} from './api';
import { EmptyState } from './EmptyState';
import { localeTags, type Locale, type Messages } from './i18n';
import { redactSecretsForPreview } from './redaction';
import { statusLabel } from './dashboardHelpers';
import { TaskActionButtons, type TaskActionKey } from './TaskActionButtons';
import './TaskPanel.css';
export type { TaskActionKey } from './TaskActionButtons';
type TaskGroupKey = 'watchers' | 'scheduled' | 'paused' | 'completed';
type TaskFilterKey = TaskGroupKey | 'all';
type TaskResultTone = 'ok' | 'fail' | 'none';
export interface RoomOption {
jid: string;
name: string;
folder: string;
}
export interface TaskPanelProps {
tasks: DashboardTask[];
rooms: RoomOption[];
locale: Locale;
onTaskAction: (task: DashboardTask, action: DashboardTaskAction) => void;
onTaskCreate: (input: CreateScheduledTaskInput) => void;
onTaskUpdate: (task: DashboardTask, input: UpdateScheduledTaskInput) => void;
taskActionKey: TaskActionKey | null;
t: Messages;
}
interface TaskGroup {
key: TaskGroupKey;
tasks: DashboardTask[];
}
interface TaskSummary {
completed: number;
nextTask: DashboardTask | null;
paused: number;
scheduled: number;
total: number;
watchers: number;
}
interface TaskCreateFormProps {
rooms: RoomOption[];
onTaskCreate: (input: CreateScheduledTaskInput) => void;
taskActionKey: TaskActionKey | null;
t: Messages;
}
interface TaskGroupSectionProps {
group: TaskGroup;
locale: Locale;
onTaskAction: (task: DashboardTask, action: DashboardTaskAction) => void;
onTaskUpdate: (task: DashboardTask, input: UpdateScheduledTaskInput) => void;
taskActionKey: TaskActionKey | null;
t: Messages;
}
interface TaskCardProps {
groupKey: TaskGroupKey;
locale: Locale;
onTaskAction: (task: DashboardTask, action: DashboardTaskAction) => void;
onTaskUpdate: (task: DashboardTask, input: UpdateScheduledTaskInput) => void;
task: DashboardTask;
taskActionKey: TaskActionKey | null;
t: Messages;
}
interface TaskDateProps {
locale: Locale;
t: Messages;
task: DashboardTask;
}
interface TaskEditFormProps {
onTaskUpdate: (task: DashboardTask, input: UpdateScheduledTaskInput) => void;
task: DashboardTask;
taskActionKey: TaskActionKey | null;
t: Messages;
}
const TASK_TIME_FORMATTERS: Record<Locale, Intl.DateTimeFormat> = {
en: new Intl.DateTimeFormat(localeTags.en, {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}),
ja: new Intl.DateTimeFormat(localeTags.ja, {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}),
ko: new Intl.DateTimeFormat(localeTags.ko, {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}),
zh: new Intl.DateTimeFormat(localeTags.zh, {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}),
};
const EN_TASK_DATE_TIME_FORMATTER = new Intl.DateTimeFormat(localeTags.en, {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false,
});
const RELATIVE_TIME_FORMATTERS: Record<Locale, Intl.RelativeTimeFormat> = {
en: new Intl.RelativeTimeFormat(localeTags.en, {
numeric: 'auto',
style: 'short',
}),
ja: new Intl.RelativeTimeFormat(localeTags.ja, {
numeric: 'auto',
style: 'short',
}),
ko: new Intl.RelativeTimeFormat(localeTags.ko, {
numeric: 'auto',
style: 'short',
}),
zh: new Intl.RelativeTimeFormat(localeTags.zh, {
numeric: 'auto',
style: 'short',
}),
};
function formatTaskDate(
value: string | null | undefined,
locale: Locale,
): string {
if (!value) return '-';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const time = TASK_TIME_FORMATTERS[locale].format(date);
if (locale === 'ko')
return `${date.getMonth() + 1}월 ${date.getDate()}일 ${time}`;
if (locale === 'ja' || locale === 'zh')
return `${date.getMonth() + 1}月${date.getDate()}日 ${time}`;
return EN_TASK_DATE_TIME_FORMATTER.format(date);
}
function formatRelativeDate(
value: string | null | undefined,
locale: Locale,
t: Messages,
): string {
if (!value) return t.tasks.noTime;
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const diffMs = date.getTime() - Date.now();
const absMs = Math.abs(diffMs);
if (absMs < 45_000) return t.tasks.now;
const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [
['day', 86_400_000],
['hour', 3_600_000],
['minute', 60_000],
];
const [unit, unitMs] =
units.find(([, threshold]) => absMs >= threshold) ?? units.at(-1)!;
return RELATIVE_TIME_FORMATTERS[locale].format(
Math.round(diffMs / unitMs),
unit,
);
}
function safePreview(
value: string | null | undefined,
fallback: string,
): string {
const cleaned = redactSecretsForPreview(value ?? '')
.replace(/<\/?internal[^>]*>/gi, '')
.replace(/\s+/g, ' ')
.trim();
if (!cleaned) return fallback;
return cleaned.length > 120 ? `${cleaned.slice(0, 120)}...` : cleaned;
}
function taskGroupKey(task: DashboardTask): TaskGroupKey {
if (task.status === 'completed') return 'completed';
if (task.status === 'paused') return 'paused';
if (task.isWatcher) return 'watchers';
return 'scheduled';
}
function taskResultTone(task: DashboardTask): TaskResultTone {
if (!task.lastResult) return 'none';
const normalized = task.lastResult.toLowerCase();
if (
normalized.includes('fail') ||
normalized.includes('error') ||
normalized.includes('timeout') ||
normalized.includes('cancel') ||
normalized.includes('reject')
) {
return 'fail';
}
return 'ok';
}
function taskDisplayName(task: DashboardTask, t: Messages): string {
if (task.isWatcher) return t.tasks.ciWatch;
if (task.scheduleType) return task.scheduleType;
return task.id;
}
function taskHeadline(task: DashboardTask, t: Messages): string {
if (task.isWatcher && task.ciProvider) {
return `${t.tasks.ciWatch} · ${task.ciProvider}`;
}
return safePreview(task.promptPreview, taskDisplayName(task, t));
}
function taskScheduleText(task: DashboardTask, t: Messages): string {
const scheduleType =
task.scheduleType === 'cron' ||
task.scheduleType === 'interval' ||
task.scheduleType === 'once'
? t.tasks.scheduleTypes[task.scheduleType]
: task.scheduleType;
return `${scheduleType} · ${task.scheduleValue || '-'}`;
}
function isTaskScheduleType(
value: FormDataEntryValue | null,
): value is DashboardTaskScheduleType {
return value === 'cron' || value === 'interval' || value === 'once';
}
function isTaskContextMode(
value: FormDataEntryValue | null,
): value is DashboardTaskContextMode {
return value === 'group' || value === 'isolated';
}
function readRequiredText(form: FormData, name: string): string | null {
const value = form.get(name);
if (typeof value !== 'string') return null;
const trimmed = value.trim();
return trimmed ? trimmed : null;
}
function readTaskForm(
form: FormData,
includeRoom: true,
): CreateScheduledTaskInput | null;
function readTaskForm(
form: FormData,
includeRoom: false,
): UpdateScheduledTaskInput | null;
function readTaskForm(
form: FormData,
includeRoom: boolean,
): CreateScheduledTaskInput | UpdateScheduledTaskInput | null {
const prompt = readRequiredText(form, 'prompt');
const scheduleValue = readRequiredText(form, 'scheduleValue');
const scheduleTypeValue = form.get('scheduleType');
if (!scheduleValue || !isTaskScheduleType(scheduleTypeValue)) {
return null;
}
const scheduleType = scheduleTypeValue;
if (!includeRoom) {
return prompt
? { prompt, scheduleType, scheduleValue }
: { scheduleType, scheduleValue };
}
if (!prompt) {
return null;
}
const roomJid = readRequiredText(form, 'roomJid');
const contextMode = form.get('contextMode');
if (!roomJid || !isTaskContextMode(contextMode)) return null;
return {
contextMode,
prompt,
roomJid,
scheduleType,
scheduleValue,
};
}
function buildTaskGroups(tasks: DashboardTask[]): TaskGroup[] {
const groups: Record<TaskGroupKey, DashboardTask[]> = {
watchers: [],
scheduled: [],
paused: [],
completed: [],
};
for (const task of tasks) {
groups[taskGroupKey(task)].push(task);
}
for (const groupTasks of Object.values(groups)) {
groupTasks.sort((a, b) =>
(a.nextRun ?? a.lastRun ?? a.createdAt).localeCompare(
b.nextRun ?? b.lastRun ?? b.createdAt,
),
);
}
return [
{ key: 'watchers', tasks: groups.watchers },
{ key: 'scheduled', tasks: groups.scheduled },
{ key: 'paused', tasks: groups.paused },
{ key: 'completed', tasks: groups.completed },
];
}
function buildTaskSummary(tasks: DashboardTask[]): TaskSummary {
const summary: TaskSummary = {
completed: 0,
nextTask: null,
paused: 0,
scheduled: 0,
total: tasks.length,
watchers: 0,
};
for (const task of tasks) {
const group = taskGroupKey(task);
if (group === 'watchers') summary.watchers += 1;
if (group === 'scheduled') summary.scheduled += 1;
if (group === 'paused') summary.paused += 1;
if (group === 'completed') summary.completed += 1;
if (task.status !== 'active' || !task.nextRun) continue;
const nextTime = new Date(task.nextRun).getTime();
if (Number.isNaN(nextTime)) continue;
const currentTime = summary.nextTask?.nextRun
? new Date(summary.nextTask.nextRun).getTime()
: Number.POSITIVE_INFINITY;
if (nextTime < currentTime) {
summary.nextTask = task;
}
}
return summary;
}
function TaskSummaryBar({
locale,
summary,
t,
}: {
locale: Locale;
summary: TaskSummary;
t: Messages;
}) {
const nextTask = summary.nextTask;
return (
<section className="task-summary-bar" aria-label={t.panels.scheduled}>
<div className="task-summary-next">
<small>{t.tasks.next}</small>
<strong>
{nextTask ? formatRelativeDate(nextTask.nextRun, locale, t) : '-'}
</strong>
<span>
{nextTask
? taskHeadline(nextTask, t)
: summary.total > 0
? `${summary.total} ${t.tasks.count}`
: t.tasks.empty}
</span>
</div>
<div className="task-summary-chips" aria-hidden="true">
<span className="task-chip">
{t.tasks.groups.scheduled} {summary.scheduled}
</span>
<span className="task-chip">
{t.tasks.groups.watchers} {summary.watchers}
</span>
<span className="task-chip">
{t.tasks.groups.paused} {summary.paused}
</span>
<span className="task-chip">
{t.tasks.groups.completed} {summary.completed}
</span>
</div>
</section>
);
}
function TaskFilterTabs({
activeFilter,
counts,
onSelect,
t,
}: {
activeFilter: TaskFilterKey;
counts: Record<TaskFilterKey, number>;
onSelect: (filter: TaskFilterKey) => void;
t: Messages;
}) {
const tabs: Array<{ key: TaskFilterKey; label: string }> = [
{ key: 'all', label: t.tasks.filterAll },
{ key: 'scheduled', label: t.tasks.groups.scheduled },
{ key: 'watchers', label: t.tasks.groups.watchers },
{ key: 'paused', label: t.tasks.groups.paused },
{ key: 'completed', label: t.tasks.groups.completed },
];
return (
<div className="task-filter-scroll">
<div
aria-label={t.panels.scheduled}
className="task-filter-tabs"
role="tablist"
>
{tabs.map((tab) => (
<button
aria-selected={activeFilter === tab.key}
className="task-filter-tab"
key={tab.key}
onClick={() => onSelect(tab.key)}
role="tab"
type="button"
>
<strong>{tab.label}</strong>
<small>{counts[tab.key]}</small>
</button>
))}
</div>
</div>
);
}
function TaskCreateForm({
rooms,
onTaskCreate,
taskActionKey,
t,
}: TaskCreateFormProps) {
return (
<details className="task-create-panel">
<summary>{t.tasks.createTitle}</summary>
<form
className="task-create-form"
onSubmit={(event) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
const input = readTaskForm(form, true);
if (!input) return;
onTaskCreate(input);
event.currentTarget.reset();
}}
>
<p className="task-create-hint">{t.tasks.scheduleValueHint}</p>
<label className="task-form-wide">
<span>{t.tasks.prompt}</span>
<textarea
name="prompt"
placeholder={t.tasks.promptPlaceholder}
required
rows={3}
/>
</label>
<div className="task-form-grid">
<label>
<span>{t.tasks.room}</span>
<select name="roomJid" required>
<option value="">{t.tasks.selectRoom}</option>
{rooms.map((room) => (
<option key={room.jid} value={room.jid}>
{room.name} · {room.folder}
</option>
))}
</select>
</label>
<label>
<span>{t.tasks.scheduleType}</span>
<select name="scheduleType" required>
<option value="once">{t.tasks.scheduleTypes.once}</option>
<option value="interval">{t.tasks.scheduleTypes.interval}</option>
<option value="cron">{t.tasks.scheduleTypes.cron}</option>
</select>
</label>
<label>
<span>{t.tasks.scheduleValue}</span>
<input
name="scheduleValue"
placeholder={t.tasks.scheduleValueHint}
required
/>
</label>
<label>
<span>{t.tasks.context}</span>
<select name="contextMode" required>
<option value="isolated">{t.tasks.contextModes.isolated}</option>
<option value="group">{t.tasks.contextModes.group}</option>
</select>
</label>
</div>
<button disabled={taskActionKey === 'create'} type="submit">
{taskActionKey === 'create'
? t.tasks.actions.busy
: t.tasks.actions.create}
</button>
</form>
</details>
);
}
function TaskTimeGrid({ locale, t, task }: TaskDateProps) {
return (
<div className="task-time-grid">
<span className="task-next-run">
<small>{t.tasks.next}</small>
<strong>{formatRelativeDate(task.nextRun, locale, t)}</strong>
<em>{formatTaskDate(task.nextRun, locale)}</em>
</span>
<span>
<small>{t.tasks.last}</small>
<strong>{formatTaskDate(task.lastRun, locale)}</strong>
<em>{formatRelativeDate(task.lastRun, locale, t)}</em>
</span>
<span>
<small>{t.tasks.schedule}</small>
<strong>{taskScheduleText(task, t)}</strong>
<em>{task.contextMode}</em>
</span>
</div>
);
}
function TaskSuspendedUntil({ locale, t, task }: TaskDateProps) {
if (!task.suspendedUntil) return null;
return (
<div className="task-suspended">
<span>{t.tasks.suspendedUntil}</span>
<strong>{formatTaskDate(task.suspendedUntil, locale)}</strong>
<em>{formatRelativeDate(task.suspendedUntil, locale, t)}</em>
</div>
);
}
function TaskResult({ task, t }: { task: DashboardTask; t: Messages }) {
const resultTone = taskResultTone(task);
const lastResult = safePreview(task.lastResult, t.tasks.noResult);
return (
<div className={`task-result result-${resultTone}`}>
<span>
{resultTone === 'fail'
? t.tasks.resultFail
: resultTone === 'ok'
? t.tasks.resultOk
: t.tasks.result}
</span>
<strong>{lastResult}</strong>
</div>
);
}
function TaskPromptBlock({ task, t }: { task: DashboardTask; t: Messages }) {
return (
<div className="task-prompt-block">
<span>{t.tasks.prompt}</span>
<p>{safePreview(task.promptPreview, t.tasks.emptyPrompt)}</p>
<small>
{task.id} · {taskScheduleText(task, t)} · {task.promptLength}{' '}
{t.units.chars}
</small>
</div>
);
}
function TaskMetaStrip({ task, t }: { task: DashboardTask; t: Messages }) {
return (
<div className="task-meta-strip">
<span>{task.groupFolder}</span>
<span>{task.agentType ?? t.tasks.task}</span>
{task.ciProvider ? <span>{task.ciProvider}</span> : null}
</div>
);
}
function TaskEditForm({
onTaskUpdate,
task,
taskActionKey,
t,
}: TaskEditFormProps) {
if (task.isWatcher || task.status === 'completed') return null;
return (
<details className="task-edit">
<summary>{t.tasks.actions.edit}</summary>
<form
className="task-edit-form"
onSubmit={(event) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
const input = readTaskForm(form, false);
if (!input) return;
onTaskUpdate(task, input);
}}
>
<label className="task-form-wide">
<span>{t.tasks.prompt}</span>
<textarea name="prompt" placeholder={t.tasks.editPromptPlaceholder} />
</label>
<label>
<span>{t.tasks.scheduleType}</span>
<select name="scheduleType" defaultValue={task.scheduleType} required>
<option value="once">{t.tasks.scheduleTypes.once}</option>
<option value="interval">{t.tasks.scheduleTypes.interval}</option>
<option value="cron">{t.tasks.scheduleTypes.cron}</option>
</select>
</label>
<label>
<span>{t.tasks.scheduleValue}</span>
<input
name="scheduleValue"
defaultValue={task.scheduleValue}
required
/>
</label>
<button disabled={taskActionKey === `${task.id}:edit`} type="submit">
{taskActionKey === `${task.id}:edit`
? t.tasks.actions.busy
: t.tasks.actions.save}
</button>
</form>
</details>
);
}
function TaskCard({
groupKey,
locale,
onTaskAction,
onTaskUpdate,
task,
taskActionKey,
t,
}: TaskCardProps) {
return (
<article className={`task-row task-row-${groupKey}`}>
<div className="task-row-head">
<div className="task-row-lead">
<span className={`pill pill-${task.status}`}>
{statusLabel(task.status, t)}
</span>
<div className="task-row-copy">
<span className="task-kind">{taskDisplayName(task, t)}</span>
<strong title={taskHeadline(task, t)}>
{taskHeadline(task, t)}
</strong>
<TaskMetaStrip task={task} t={t} />
</div>
</div>
<div className="task-row-aside">
<div className="task-row-next">
<small>{t.tasks.next}</small>
<strong>{formatRelativeDate(task.nextRun, locale, t)}</strong>
<em>{formatTaskDate(task.nextRun, locale)}</em>
</div>
<TaskActionButtons
className="task-row-actions"
onTaskAction={onTaskAction}
task={task}
taskActionKey={taskActionKey}
t={t}
/>
</div>
</div>
<details className="task-row-details">
<summary>{t.tasks.details}</summary>
<div className="task-row-details-body">
<TaskTimeGrid locale={locale} t={t} task={task} />
<TaskSuspendedUntil locale={locale} t={t} task={task} />
<TaskResult task={task} t={t} />
<TaskPromptBlock task={task} t={t} />
<TaskEditForm
onTaskUpdate={onTaskUpdate}
task={task}
taskActionKey={taskActionKey}
t={t}
/>
</div>
</details>
</article>
);
}
function TaskGroupBody({
group,
locale,
onTaskAction,
onTaskUpdate,
taskActionKey,
t,
}: TaskGroupSectionProps) {
if (group.tasks.length === 0) {
return <div className="task-group-empty">{t.tasks.groupEmpty}</div>;
}
return (
<div className="task-list">
{group.tasks.map((task) => (
<TaskCard
groupKey={group.key}
key={task.id}
locale={locale}
onTaskAction={onTaskAction}
onTaskUpdate={onTaskUpdate}
task={task}
taskActionKey={taskActionKey}
t={t}
/>
))}
</div>
);
}
function TaskGroupHead({
countLabel,
group,
label,
}: {
countLabel: string;
group: TaskGroup;
label: string;
}) {
return (
<div className="task-group-head">
<strong>
{label} · {group.tasks.length} {countLabel}
</strong>
</div>
);
}
function TaskGroupSection({
group,
locale,
onTaskAction,
onTaskUpdate,
showHead,
taskActionKey,
t,
}: TaskGroupSectionProps & { showHead: boolean }) {
if (group.tasks.length === 0) return null;
const label = t.tasks.groups[group.key];
const body = (
<TaskGroupBody
group={group}
locale={locale}
onTaskAction={onTaskAction}
onTaskUpdate={onTaskUpdate}
taskActionKey={taskActionKey}
t={t}
/>
);
if (group.key === 'completed') {
return (
<details className="task-group task-group-completed">
<summary className="task-group-head">
<strong>{label}</strong>
<span className={`pill pill-${group.key}`}>{group.tasks.length}</span>
</summary>
{body}
</details>
);
}
if (!showHead) {
return (
<section className={`task-group task-group-${group.key}`}>{body}</section>
);
}
return (
<section className={`task-group task-group-${group.key}`}>
<TaskGroupHead countLabel={t.tasks.count} group={group} label={label} />
{body}
</section>
);
}
function buildFilterCounts(groups: TaskGroup[]): Record<TaskFilterKey, number> {
const counts: Record<TaskFilterKey, number> = {
all: 0,
watchers: 0,
scheduled: 0,
paused: 0,
completed: 0,
};
for (const group of groups) {
counts[group.key] = group.tasks.length;
counts.all += group.tasks.length;
}
return counts;
}
export function TaskPanel({
tasks,
rooms,
locale,
onTaskAction,
onTaskCreate,
onTaskUpdate,
taskActionKey,
t,
}: TaskPanelProps) {
const taskGroups = useMemo(() => buildTaskGroups(tasks), [tasks]);
const taskSummary = useMemo(() => buildTaskSummary(tasks), [tasks]);
const filterCounts = useMemo(
() => buildFilterCounts(taskGroups),
[taskGroups],
);
const [activeFilter, setActiveFilter] = useState<TaskFilterKey>('all');
const visibleGroups = useMemo(() => {
if (activeFilter === 'all') {
return taskGroups.filter((group) => group.tasks.length > 0);
}
return taskGroups.filter((group) => group.key === activeFilter);
}, [activeFilter, taskGroups]);
return (
<div className="task-board" aria-label={t.tasks.cardsAria}>
<TaskSummaryBar locale={locale} summary={taskSummary} t={t} />
<TaskFilterTabs
activeFilter={activeFilter}
counts={filterCounts}
onSelect={setActiveFilter}
t={t}
/>
<TaskCreateForm
onTaskCreate={onTaskCreate}
rooms={rooms}
taskActionKey={taskActionKey}
t={t}
/>
{tasks.length === 0 ? <EmptyState>{t.tasks.empty}</EmptyState> : null}
{tasks.length > 0 && visibleGroups.length === 0 ? (
<EmptyState>{t.tasks.groupEmpty}</EmptyState>
) : null}
<div className="task-lanes">
{visibleGroups.map((group) => (
<TaskGroupSection
group={group}
key={group.key}
locale={locale}
onTaskAction={onTaskAction}
onTaskUpdate={onTaskUpdate}
showHead={activeFilter === 'all'}
taskActionKey={taskActionKey}
t={t}
/>
))}
</div>
</div>
);
}

View File

@@ -1,71 +0,0 @@
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import type { DashboardOverview } from './api';
import { messages } from './i18n';
import { UsagePanel, type UsagePanelProps } from './UsagePanel';
const t = messages.en;
function overview(rows: DashboardOverview['usage']['rows']): DashboardOverview {
return {
generatedAt: '2026-04-28T04:00:00.000Z',
inbox: [],
operations: { serviceRestarts: [] },
rooms: { active: 0, inactive: 0, total: 0, waiting: 0 },
services: [],
tasks: {
active: 0,
completed: 0,
paused: 0,
total: 0,
watchers: { active: 0, completed: 0, paused: 0 },
},
usage: { fetchedAt: '2026-04-28T04:00:00.000Z', rows },
};
}
const baseProps: UsagePanelProps = {
overview: overview([
{
d7pct: 88,
d7reset: '2d',
h5pct: 52,
h5reset: '1h',
name: '*Claude max',
},
{
d7pct: 12,
d7reset: '',
h5pct: 45,
h5reset: '3h',
name: 'codex-pro mid',
},
]),
t,
};
describe('UsagePanel', () => {
it('renders grouped usage rows, quota remaining, and risk labels', () => {
const html = renderToStaticMarkup(createElement(UsagePanel, baseProps));
expect(html).toContain(t.usage.groupPrimary);
expect(html).toContain(t.usage.groupCodex);
expect(html).toContain('Claude');
expect(html).toContain('codex-pro');
expect(html).toContain(t.usage.inUse);
expect(html).toContain(t.usage.risk.critical);
expect(html).toContain('12%');
expect(html).toContain('48%');
expect(html).toContain('10%/h');
});
it('renders an empty state without usage rows', () => {
const html = renderToStaticMarkup(
createElement(UsagePanel, { ...baseProps, overview: overview([]) }),
);
expect(html).toContain(t.usage.empty);
});
});

View File

@@ -1,259 +0,0 @@
import { useMemo } from 'react';
import type { DashboardOverview } from './api';
import { EmptyState } from './EmptyState';
import type { Messages } from './i18n';
export type UsageRow = DashboardOverview['usage']['rows'][number];
type RiskLevel = 'ok' | 'warn' | 'critical';
type UsageGroup = 'primary' | 'codex';
type UsageLimitWindow = 'h5' | 'd7';
export interface UsagePanelProps {
overview: DashboardOverview;
t: Messages;
}
function formatPct(value: number): string {
if (value < 0) return '-';
return `${Math.round(value)}%`;
}
function usagePeak(row: UsageRow): number {
return Math.max(row.h5pct, row.d7pct);
}
function usageLimitWindow(row: UsageRow): UsageLimitWindow {
return row.d7pct >= row.h5pct ? 'd7' : 'h5';
}
function usageWindowRemaining(
row: UsageRow,
window: UsageLimitWindow,
): number | null {
const pct = window === 'h5' ? row.h5pct : row.d7pct;
if (pct < 0) return null;
return Math.max(0, 100 - pct);
}
function usageRiskLevel(row: UsageRow): RiskLevel {
const peak = usagePeak(row);
if (peak >= 85) return 'critical';
if (peak >= 65) return 'warn';
return 'ok';
}
function usageActive(row: UsageRow): boolean {
return row.name.includes('*');
}
function usageLimited(row: UsageRow): boolean {
return row.name.includes('!');
}
function usageNameParts(row: UsageRow): {
account: string;
plan: string | null;
} {
const cleaned = row.name.replace(/[*!]/g, '').replace(/\s+/g, ' ').trim();
const parts = cleaned.split(' ');
const plan = parts.at(-1) ?? null;
if (plan && ['max', 'mid', 'pro', 'team'].includes(plan.toLowerCase())) {
return { account: parts.slice(0, -1).join(' ') || cleaned, plan };
}
return { account: cleaned, plan: null };
}
function usageWindowReset(row: UsageRow, window: UsageLimitWindow): string {
return (window === 'd7' ? row.d7reset : row.h5reset).trim();
}
function usageBurnRate(row: UsageRow): number | null {
if (row.h5pct < 0) return null;
return row.h5pct / 5;
}
function usageSpeedLevel(rate: number | null): RiskLevel {
if (rate === null) return 'ok';
if (rate >= 12) return 'critical';
if (rate >= 7) return 'warn';
return 'ok';
}
function formatUsageRate(rate: number | null): string {
if (rate === null) return '-';
if (rate > 0 && rate < 1) return '<1%/h';
return `${Math.round(rate)}%/h`;
}
function usageGroup(row: UsageRow): UsageGroup {
return row.name.toLowerCase().startsWith('codex') ? 'codex' : 'primary';
}
function UsageQuotaMeter({
row,
rowName,
window,
t,
}: {
row: UsageRow;
rowName: string;
window: UsageLimitWindow;
t: Messages;
}) {
const remaining = usageWindowRemaining(row, window);
const reset = usageWindowReset(row, window);
const tightest = usageLimitWindow(row) === window;
const label = t.usage.quota[window];
return (
<div className={`usage-quota ${tightest ? 'usage-quota-tight' : ''}`}>
<div>
<span>{label}</span>
<strong>{remaining === null ? '-' : formatPct(remaining)}</strong>
</div>
<progress
aria-label={`${rowName} ${label} ${
remaining === null ? '-' : formatPct(remaining)
}`}
max={100}
value={remaining ?? 0}
/>
<small>{reset ? `${t.usage.reset} ${reset}` : t.usage.noReset}</small>
</div>
);
}
function UsageSpeed({ row, t }: { row: UsageRow; t: Messages }) {
const rate = usageBurnRate(row);
const level = usageSpeedLevel(rate);
return (
<div className={`usage-speed usage-speed-${level}`}>
<span>{t.usage.speed}</span>
<strong>{formatUsageRate(rate)}</strong>
<small>{t.usage.speedLabel[level]}</small>
</div>
);
}
export function UsagePanel({ overview, t }: UsagePanelProps) {
const rows = useMemo(
() =>
Array.from(overview.usage.rows).sort((a, b) => {
if (usageActive(a) !== usageActive(b)) return usageActive(a) ? -1 : 1;
return usagePeak(b) - usagePeak(a);
}),
[overview.usage.rows],
);
const watched = rows.filter((row) => usagePeak(row) >= 65).length;
if (rows.length === 0) {
return <EmptyState>{t.usage.empty}</EmptyState>;
}
const activeRows = rows.filter(usageActive);
const focusRows = activeRows.length > 0 ? activeRows : rows.slice(0, 1);
const focusLabel = activeRows.length > 0 ? t.usage.current : t.usage.tightest;
const focusValue = focusRows
.map((row) => {
const { account } = usageNameParts(row);
const h5Remaining = usageWindowRemaining(row, 'h5');
const d7Remaining = usageWindowRemaining(row, 'd7');
return `${account} ${t.usage.quota.h5} ${
h5Remaining === null ? '-' : formatPct(h5Remaining)
} · ${t.usage.quota.d7} ${
d7Remaining === null ? '-' : formatPct(d7Remaining)
}`;
})
.join(' · ');
const groups = [
{
key: 'primary' as const,
label: t.usage.groupPrimary,
rows: rows.filter((row) => usageGroup(row) === 'primary'),
},
{
key: 'codex' as const,
label: t.usage.groupCodex,
rows: rows.filter((row) => usageGroup(row) === 'codex'),
},
].filter((group) => group.rows.length > 0);
return (
<div className="usage-dashboard">
<div className="usage-summary">
<div>
<span>{focusLabel}</span>
<strong>{focusValue}</strong>
</div>
<div>
<span>{t.usage.watch}</span>
<strong>{watched}</strong>
</div>
</div>
<table className="usage-matrix" aria-label={t.panels.usage}>
<thead>
<tr className="usage-matrix-head">
<th scope="col">{t.usage.usage}</th>
<th scope="col">{t.usage.quota.h5}</th>
<th scope="col">{t.usage.quota.d7}</th>
<th scope="col">{t.usage.speed}</th>
</tr>
</thead>
{groups.map((group) => (
<tbody className="usage-group" key={group.key}>
<tr className="usage-group-label">
<th colSpan={4} scope="colgroup">
{group.label}
</th>
</tr>
{group.rows.map((row) => {
const risk = usageRiskLevel(row);
const { account, plan } = usageNameParts(row);
return (
<tr className={`usage-row usage-${risk}`} key={row.name}>
<th className="usage-account" scope="row">
<strong>{account}</strong>
<div>
{usageActive(row) ? (
<span className="pill pill-info">{t.usage.inUse}</span>
) : null}
{plan ? <span className="mono-chip">{plan}</span> : null}
{usageLimited(row) || risk !== 'ok' ? (
<span className={`pill pill-${risk}`}>
{t.usage.risk[risk]}
</span>
) : null}
</div>
</th>
<td>
<UsageQuotaMeter
row={row}
rowName={account}
window="h5"
t={t}
/>
</td>
<td>
<UsageQuotaMeter
row={row}
rowName={account}
window="d7"
t={t}
/>
</td>
<td>
<UsageSpeed row={row} t={t} />
</td>
</tr>
);
})}
</tbody>
))}
</table>
</div>
);
}

View File

@@ -1,833 +0,0 @@
export interface DashboardOverview {
generatedAt: string;
services: Array<{
serviceId: string;
assistantName: string;
agentType: string;
updatedAt: string;
totalRooms: number;
activeRooms: number;
}>;
rooms: {
total: number;
active: number;
waiting: number;
inactive: number;
};
tasks: {
total: number;
active: number;
paused: number;
completed: number;
watchers: {
active: number;
paused: number;
completed: number;
};
};
usage: {
rows: Array<{
name: string;
h5pct: number;
h5reset: string;
d7pct: number;
d7reset: string;
}>;
fetchedAt: string | null;
};
operations?: {
serviceRestarts: DashboardServiceRestart[];
};
inbox: Array<{
id: string;
groupKey: string;
kind:
| 'pending-room'
| 'reviewer-request'
| 'approval'
| 'arbiter-request'
| 'ci-failure'
| 'mention';
severity: 'info' | 'warn' | 'error';
title: string;
summary: string;
occurredAt: string;
lastOccurredAt: string;
createdAt: string;
occurrences: number;
source: 'status-snapshot' | 'paired-task' | 'scheduled-task';
roomJid?: string;
roomName?: string;
groupFolder?: string;
serviceId?: string;
taskId?: string;
taskStatus?: string;
}>;
}
export interface DashboardServiceRestart {
id: string;
target: 'stack';
requestedAt: string;
completedAt: string | null;
status: 'running' | 'success' | 'failed';
services: string[];
error?: string;
}
export interface StatusSnapshot {
serviceId: string;
agentType: string;
assistantName: string;
updatedAt: string;
entries: Array<{
jid: string;
name: string;
folder: string;
agentType: string;
status: 'processing' | 'waiting' | 'inactive';
elapsedMs: number | null;
pendingMessages: boolean;
pendingTasks: number;
}>;
}
export interface DashboardRoomActivity {
serviceId: string;
jid: string;
name: string;
folder: string;
agentType: string;
status: 'processing' | 'waiting' | 'inactive';
elapsedMs: number | null;
pendingMessages: boolean;
pendingTasks: number;
messages: Array<{
id: string;
sender: string;
senderName: string;
content: string;
attachments?: Array<{
path: string;
name?: string;
mime?: string;
}>;
timestamp: string;
isFromMe: boolean;
isBotMessage: boolean;
sourceKind: string;
}>;
pairedTask: {
id: string;
title: string | null;
status: string;
roundTripCount: number;
updatedAt: string;
currentTurn: {
turnId: string;
role: string;
intentKind: string;
state: string;
attemptNo: number;
executorServiceId: string | null;
executorAgentType: string | null;
activeRunId: string | null;
createdAt: string;
updatedAt: string;
completedAt: string | null;
lastError: string | null;
progressText: string | null;
progressUpdatedAt: string | null;
} | null;
outputs: Array<{
id: number;
turnNumber: number;
role: string;
verdict: string | null;
createdAt: string;
outputText: string;
attachments?: Array<{
path: string;
name?: string;
mime?: string;
}>;
}>;
} | null;
}
export interface DashboardTask {
id: string;
groupFolder: string;
chatJid: string;
agentType: string | null;
ciProvider: string | null;
ciMetadata: string | null;
scheduleType: string;
scheduleValue: string;
contextMode: string;
nextRun: string | null;
lastRun: string | null;
lastResult: string | null;
status: 'active' | 'paused' | 'completed';
suspendedUntil: string | null;
createdAt: string;
promptPreview: string;
promptLength: number;
isWatcher: boolean;
}
export type DashboardTaskAction = 'pause' | 'resume' | 'cancel';
export type DashboardInboxAction = 'run' | 'decline' | 'dismiss';
export type DashboardServiceAction = 'restart';
export type DashboardTaskScheduleType = 'cron' | 'interval' | 'once';
export type DashboardTaskContextMode = 'group' | 'isolated';
export interface CreateScheduledTaskInput {
roomJid: string;
prompt: string;
scheduleType: DashboardTaskScheduleType;
scheduleValue: string;
contextMode: DashboardTaskContextMode;
requestId?: string;
}
export interface UpdateScheduledTaskInput {
prompt?: string;
scheduleType: DashboardTaskScheduleType;
scheduleValue: string;
}
async function fetchJson<T>(path: string): Promise<T> {
const response = await fetch(path, {
headers: { accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`${path} failed: ${response.status}`);
}
return (await response.json()) as T;
}
async function postJson<T>(path: string, body: unknown): Promise<T> {
const response = await fetch(path, {
method: 'POST',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify(body),
});
if (!response.ok) {
let message = `${path} failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) message = payload.error;
} catch {
// Keep the status-based message when the server body is not JSON.
}
throw new Error(message);
}
return (await response.json()) as T;
}
export async function fetchDashboardData(): Promise<{
overview: DashboardOverview;
snapshots: StatusSnapshot[];
tasks: DashboardTask[];
}> {
const [overview, snapshots, tasks] = await Promise.all([
fetchJson<DashboardOverview>('/api/overview'),
fetchJson<StatusSnapshot[]>('/api/status-snapshots'),
fetchJson<DashboardTask[]>('/api/tasks'),
]);
return { overview, snapshots, tasks };
}
export async function fetchRoomTimeline(
roomJid: string,
): Promise<DashboardRoomActivity> {
return fetchJson<DashboardRoomActivity>(
`/api/rooms/${encodeURIComponent(roomJid)}/timeline`,
);
}
export async function fetchRoomsTimelineBatch(): Promise<
Record<string, DashboardRoomActivity>
> {
return fetchJson<Record<string, DashboardRoomActivity>>(
'/api/rooms-timeline',
);
}
export async function runScheduledTaskAction(
taskId: string,
action: DashboardTaskAction,
): Promise<{
ok: true;
id?: string;
deleted?: boolean;
task?: DashboardTask | null;
}> {
return postJson(`/api/tasks/${encodeURIComponent(taskId)}/actions`, {
action,
});
}
export async function createScheduledTask(
input: CreateScheduledTaskInput,
): Promise<{ ok: true; task: DashboardTask | null }> {
return postJson('/api/tasks', input);
}
export async function updateScheduledTask(
taskId: string,
input: UpdateScheduledTaskInput,
): Promise<{ ok: true; task: DashboardTask | null }> {
const response = await fetch(`/api/tasks/${encodeURIComponent(taskId)}`, {
method: 'PATCH',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify(input),
});
if (!response.ok) {
let message = `/api/tasks/${taskId} failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) message = payload.error;
} catch {
// Keep the status-based message when the server body is not JSON.
}
throw new Error(message);
}
return (await response.json()) as { ok: true; task: DashboardTask | null };
}
export async function runInboxAction(
inboxId: string,
action: DashboardInboxAction,
options: { requestId?: string; lastOccurredAt?: string } = {},
): Promise<{
ok: true;
id: string;
taskId?: string;
intentKind?: string;
status?: string;
queued?: boolean;
dismissed?: boolean;
duplicate?: boolean;
}> {
return postJson(`/api/inbox/${encodeURIComponent(inboxId)}/actions`, {
action,
lastOccurredAt: options.lastOccurredAt,
requestId: options.requestId,
});
}
export async function runServiceAction(
serviceId: 'stack',
action: DashboardServiceAction,
options: { requestId?: string } = {},
): Promise<{
ok: true;
duplicate?: boolean;
restart: DashboardServiceRestart;
}> {
return postJson(`/api/services/${encodeURIComponent(serviceId)}/actions`, {
action,
requestId: options.requestId,
});
}
export async function sendRoomMessage(
roomJid: string,
text: string,
requestId: string,
nickname?: string | null,
): Promise<{ ok: true; id: string; queued: boolean }> {
return postJson(`/api/rooms/${encodeURIComponent(roomJid)}/messages`, {
requestId,
text,
nickname: nickname ?? undefined,
});
}
export interface ClaudeAccountSummary {
index: number;
expiresAt: number | null;
scopes: string[];
subscriptionType?: string;
rateLimitTier?: string;
exists: boolean;
}
export interface CodexRateLimitWindowSummary {
limitWindowSeconds: number | null;
resetAfterSeconds: number | null;
resetAt: string | null;
usedPercent: number | null;
}
export interface CodexRateLimitSummary {
allowed: boolean | null;
limitReached: boolean | null;
primaryWindow: CodexRateLimitWindowSummary | null;
secondaryWindow: CodexRateLimitWindowSummary | null;
}
export interface CodexAdditionalRateLimitSummary {
limitName: string | null;
meteredFeature: string | null;
rateLimit: CodexRateLimitSummary | null;
}
export interface CodexCreditsSummary {
hasCredits: boolean | null;
overageLimitReached: boolean | null;
unlimited: boolean | null;
}
export interface CodexSpendControlSummary {
reached: boolean | null;
}
export interface CodexLiveStatusSummary {
checkedAt: string;
source: 'wham/usage';
planType: string | null;
email: string | null;
rateLimit: CodexRateLimitSummary | null;
rateLimitReachedType: string | null;
additionalRateLimits: CodexAdditionalRateLimitSummary[];
credits: CodexCreditsSummary | null;
spendControl: CodexSpendControlSummary | null;
}
export interface CodexAccountSummary {
index: number;
accountId: string | null;
email: string | null;
planType: string | null;
subscriptionUntil: string | null;
subscriptionLastChecked: string | null;
subscriptionSource: 'jwt-cache' | null;
liveStatus: CodexLiveStatusSummary | null;
exists: boolean;
}
export interface ModelRoleConfig {
model: string;
effort: string;
}
export interface ModelAgentTypes {
owner: 'claude-code' | 'codex';
reviewer: 'claude-code' | 'codex';
arbiter: 'claude-code' | 'codex' | null;
}
export interface ModelConfigSnapshot {
owner: ModelRoleConfig;
reviewer: ModelRoleConfig;
arbiter: ModelRoleConfig;
agentTypes: ModelAgentTypes;
}
export interface FastModeSnapshot {
codex: boolean;
claude: boolean;
}
export interface CodexFeatureSnapshot {
goals: boolean;
}
export interface RuntimePathSnapshot {
label: string;
path: string;
exists: boolean;
}
export interface RuntimeSkillSummary {
name: string;
description: string | null;
path: string;
}
export interface RuntimeSkillDirSnapshot extends RuntimePathSnapshot {
count: number;
skills: RuntimeSkillSummary[];
}
export interface RuntimeMcpSnapshot {
configPath: RuntimePathSnapshot;
ejclawConfigured: boolean;
serverCount: number;
}
export interface RuntimeAgentInventory {
configFiles: RuntimePathSnapshot[];
skillDirs: RuntimeSkillDirSnapshot[];
mcp: RuntimeMcpSnapshot;
}
export interface RuntimeInventorySnapshot {
generatedAt: string;
projectRoot: string;
dataDir: string;
service: {
id: string;
sessionScope: string;
agentType: string;
};
codex: RuntimeAgentInventory;
claude: RuntimeAgentInventory;
ejclaw: {
runnerSkillDir: RuntimeSkillDirSnapshot;
mcpServer: RuntimePathSnapshot;
};
}
export type RoomSkillScope = 'codex-user' | 'claude-user' | 'runner';
export interface RoomSkillCatalogItem {
id: string;
scope: RoomSkillScope;
name: string;
displayName: string;
description: string | null;
path: string;
agentTypes: Array<'claude-code' | 'codex'>;
}
export interface RoomSkillAgentPolicy {
agentType: 'claude-code' | 'codex';
mode: 'all-enabled' | 'custom';
availableSkillIds: string[];
disabledSkillIds: string[];
explicitEnabledSkillIds: string[];
effectiveEnabledSkillIds: string[];
}
export interface RoomSkillPolicyRoom {
jid: string;
name: string;
folder: string;
roomMode?: 'single' | 'tribunal';
agents: RoomSkillAgentPolicy[];
}
export interface RoomSkillSettingsSnapshot {
generatedAt: string;
catalog: RoomSkillCatalogItem[];
rooms: RoomSkillPolicyRoom[];
}
export interface RoomSkillSettingUpdateInput {
roomJid: string;
agentType: 'claude-code' | 'codex';
skillId: string;
enabled: boolean;
}
export interface MoaReferenceStatus {
model: string;
checkedAt: string;
ok: boolean;
error: string | null;
responseLength?: number;
}
export interface MoaModelSettingsSnapshot {
name: string;
enabled: boolean;
model: string;
baseUrl: string;
apiFormat: 'openai' | 'anthropic';
apiKeyConfigured: boolean;
lastStatus: MoaReferenceStatus | null;
}
export interface MoaSettingsSnapshot {
enabled: boolean;
referenceModels: string[];
models: MoaModelSettingsSnapshot[];
}
export async function fetchAccounts(): Promise<{
claude: ClaudeAccountSummary[];
codex: CodexAccountSummary[];
codexCurrentIndex?: number;
}> {
return fetchJson('/api/settings/accounts');
}
export async function fetchModelConfig(): Promise<ModelConfigSnapshot> {
return fetchJson('/api/settings/models');
}
export async function updateModels(
input: Partial<{
owner: Partial<ModelRoleConfig>;
reviewer: Partial<ModelRoleConfig>;
arbiter: Partial<ModelRoleConfig>;
}>,
): Promise<ModelConfigSnapshot> {
const response = await fetch('/api/settings/models', {
method: 'PUT',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify(input),
});
if (!response.ok) {
let msg = `update models failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
return (await response.json()) as ModelConfigSnapshot;
}
export async function refreshCodexAccount(
index: number,
): Promise<CodexAccountSummary> {
const response = await fetch(
`/api/settings/accounts/codex/${index}/refresh`,
{ method: 'POST' },
);
if (!response.ok) {
let msg = `refresh failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
const json = (await response.json()) as { account: CodexAccountSummary };
return json.account;
}
export async function refreshAllCodexAccounts(): Promise<{
refreshed: number[];
failed: Array<{ index: number; error: string }>;
}> {
const response = await fetch('/api/settings/accounts/codex/refresh-all', {
method: 'POST',
});
if (!response.ok) {
throw new Error(`refresh-all failed: ${response.status}`);
}
return (await response.json()) as {
refreshed: number[];
failed: Array<{ index: number; error: string }>;
};
}
export async function setCurrentCodexAccount(
index: number,
): Promise<{ codexCurrentIndex: number }> {
const response = await fetch('/api/settings/accounts/codex/current', {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ index }),
});
if (!response.ok) {
let msg = `switch failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
return (await response.json()) as { codexCurrentIndex: number };
}
export async function fetchFastMode(): Promise<FastModeSnapshot> {
return fetchJson('/api/settings/fast-mode');
}
export async function updateFastMode(
input: Partial<FastModeSnapshot>,
): Promise<FastModeSnapshot> {
const response = await fetch('/api/settings/fast-mode', {
method: 'PUT',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify(input),
});
if (!response.ok) {
let msg = `update fast mode failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
return (await response.json()) as FastModeSnapshot;
}
export async function fetchCodexFeatures(): Promise<CodexFeatureSnapshot> {
return fetchJson('/api/settings/codex-features');
}
export async function fetchRuntimeInventory(): Promise<RuntimeInventorySnapshot> {
return fetchJson('/api/settings/runtime-inventory');
}
export async function fetchRoomSkillSettings(): Promise<RoomSkillSettingsSnapshot> {
return fetchJson('/api/settings/room-skills');
}
export async function updateRoomSkillSetting(
input: RoomSkillSettingUpdateInput,
): Promise<RoomSkillSettingsSnapshot> {
const response = await fetch('/api/settings/room-skills', {
method: 'PATCH',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify(input),
});
if (!response.ok) {
let msg = `update room skill failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
return (await response.json()) as RoomSkillSettingsSnapshot;
}
export async function updateCodexFeatures(
input: Partial<CodexFeatureSnapshot>,
): Promise<CodexFeatureSnapshot> {
const response = await fetch('/api/settings/codex-features', {
method: 'PUT',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify(input),
});
if (!response.ok) {
let msg = `update codex features failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
return (await response.json()) as CodexFeatureSnapshot;
}
export async function fetchMoaSettings(): Promise<MoaSettingsSnapshot> {
return fetchJson('/api/settings/moa');
}
export async function updateMoaSettings(input: {
enabled?: boolean;
models?: Array<{
name: string;
enabled?: boolean;
model?: string;
baseUrl?: string;
apiFormat?: 'openai' | 'anthropic';
apiKey?: string;
}>;
}): Promise<MoaSettingsSnapshot> {
const response = await fetch('/api/settings/moa', {
method: 'PUT',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify(input),
});
if (!response.ok) {
let msg = `update MoA settings failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
return (await response.json()) as MoaSettingsSnapshot;
}
export async function checkMoaModel(name: string): Promise<MoaReferenceStatus> {
const response = await fetch('/api/settings/moa/check', {
method: 'POST',
headers: {
accept: 'application/json',
'content-type': 'application/json',
},
body: JSON.stringify({ name }),
});
if (!response.ok) {
let msg = `check MoA model failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
const payload = (await response.json()) as {
status: MoaReferenceStatus;
};
return payload.status;
}
export async function deleteAccount(
provider: 'claude' | 'codex',
index: number,
): Promise<{ ok: true; provider: string; index: number }> {
const response = await fetch(`/api/settings/accounts/${provider}/${index}`, {
method: 'DELETE',
});
if (!response.ok) {
let msg = `delete account failed: ${response.status}`;
try {
const payload = (await response.json()) as { error?: string };
if (payload.error) msg = payload.error;
} catch {
/* ignore */
}
throw new Error(msg);
}
return (await response.json()) as {
ok: true;
provider: string;
index: number;
};
}
export async function addClaudeAccount(
token: string,
): Promise<{ ok: true; index: number; accountId: string | null }> {
return postJson('/api/settings/accounts/claude', { token });
}

View File

@@ -1,120 +0,0 @@
import {
type CodexLiveStatusSummary,
type CodexRateLimitSummary,
type CodexRateLimitWindowSummary,
} from './api';
export function formatDateTime(iso: string): string | null {
const dt = new Date(iso);
if (Number.isNaN(dt.getTime())) return null;
return dt.toLocaleString('ko-KR', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
}
export function formatJwtCacheExpiry(
iso: string | null,
): { label: string; cls: string; title: string } | null {
if (!iso) return null;
const dt = new Date(iso);
if (Number.isNaN(dt.getTime())) return null;
const days = (dt.getTime() - Date.now()) / 86400000;
const dateStr = dt.toLocaleDateString('ko-KR', {
year: '2-digit',
month: '2-digit',
day: '2-digit',
});
const suffix =
days < 0 ? `${Math.ceil(-days)}일 전` : `${Math.floor(days)}일 남음`;
return {
label: `JWT 캐시 ${dateStr}`,
cls: 'is-stale',
title: `OpenAI/Auth0 JWT 캐시 만료일입니다. live wham/usage 갱신값이 있으면 이 값은 표시하지 않습니다. (${suffix})`,
};
}
function formatWindowName(seconds: number | null | undefined): string {
if (!seconds || !Number.isFinite(seconds)) return 'limit';
if (seconds % 86400 === 0) return `${Math.round(seconds / 86400)}d`;
if (seconds % 3600 === 0) return `${Math.round(seconds / 3600)}h`;
if (seconds % 60 === 0) return `${Math.round(seconds / 60)}m`;
return `${seconds}s`;
}
function formatPercent(value: number | null | undefined): string {
if (typeof value !== 'number' || !Number.isFinite(value)) return '?%';
return `${Math.round(value)}%`;
}
function formatRateLimitWindow(
window: CodexRateLimitWindowSummary | null,
): string | null {
if (!window) return null;
return `${formatWindowName(window.limitWindowSeconds)} ${formatPercent(window.usedPercent)}`;
}
export function formatLiveStatusBadge(
live: CodexLiveStatusSummary | null,
): { label: string; cls: string; title: string } | null {
if (!live) return null;
const limits = [
live.rateLimit,
...live.additionalRateLimits.map((limit) => limit.rateLimit),
].filter((limit): limit is CodexRateLimitSummary => limit !== null);
const anyReached = limits.some((limit) => limit.limitReached === true);
const anyBlocked = limits.some((limit) => limit.allowed === false);
const checkedAt = formatDateTime(live.checkedAt) ?? live.checkedAt;
if (anyReached || anyBlocked || live.rateLimitReachedType) {
return {
label: 'live 제한 도달',
cls: 'is-expired',
title: `wham/usage live 확인: ${checkedAt}${
live.rateLimitReachedType ? ` · ${live.rateLimitReachedType}` : ''
}`,
};
}
if (live.spendControl?.reached || live.credits?.overageLimitReached) {
return {
label: 'live 지출 제한',
cls: 'is-expired',
title: `wham/usage live 확인: ${checkedAt}`,
};
}
if (limits.some((limit) => limit.allowed === true)) {
return {
label: 'live 사용 가능',
cls: 'is-active',
title: `wham/usage live 확인: ${checkedAt}`,
};
}
return {
label: 'live 확인됨',
cls: 'is-soon',
title: `wham/usage live 확인: ${checkedAt}`,
};
}
export function formatUsageBadge(
live: CodexLiveStatusSummary | null,
): { label: string; title: string } | null {
if (!live?.rateLimit) return null;
const primary = formatRateLimitWindow(live.rateLimit.primaryWindow);
const secondary = formatRateLimitWindow(live.rateLimit.secondaryWindow);
const label = [primary, secondary].filter(Boolean).join(' · ');
if (!label) return null;
const resetParts = [
live.rateLimit.primaryWindow?.resetAt
? `primary reset ${formatDateTime(live.rateLimit.primaryWindow.resetAt) ?? live.rateLimit.primaryWindow.resetAt}`
: null,
live.rateLimit.secondaryWindow?.resetAt
? `secondary reset ${formatDateTime(live.rateLimit.secondaryWindow.resetAt) ?? live.rateLimit.secondaryWindow.resetAt}`
: null,
].filter(Boolean);
return {
label,
title: resetParts.join(' · ') || 'wham/usage live rate_limit',
};
}

View File

@@ -1,83 +0,0 @@
import type { DashboardTask, DashboardTaskAction } from './api';
import { localeTags, type Locale, type Messages } from './i18n';
const SHORT_TIME_FORMAT_OPTIONS = {
hour: '2-digit',
hour12: false,
minute: '2-digit',
} as const;
const MONTH_DAY_TIME_FORMAT_OPTIONS = {
day: 'numeric',
hour: '2-digit',
hour12: false,
minute: '2-digit',
month: 'short',
} as const;
const SHORT_TIME_FORMATTERS: Record<Locale, Intl.DateTimeFormat> = {
en: new Intl.DateTimeFormat(localeTags.en, SHORT_TIME_FORMAT_OPTIONS),
ja: new Intl.DateTimeFormat(localeTags.ja, SHORT_TIME_FORMAT_OPTIONS),
ko: new Intl.DateTimeFormat(localeTags.ko, SHORT_TIME_FORMAT_OPTIONS),
zh: new Intl.DateTimeFormat(localeTags.zh, SHORT_TIME_FORMAT_OPTIONS),
};
const MONTH_DAY_TIME_FORMATTERS: Record<Locale, Intl.DateTimeFormat> = {
en: new Intl.DateTimeFormat(localeTags.en, MONTH_DAY_TIME_FORMAT_OPTIONS),
ja: new Intl.DateTimeFormat(localeTags.ja, MONTH_DAY_TIME_FORMAT_OPTIONS),
ko: new Intl.DateTimeFormat(localeTags.ko, MONTH_DAY_TIME_FORMAT_OPTIONS),
zh: new Intl.DateTimeFormat(localeTags.zh, MONTH_DAY_TIME_FORMAT_OPTIONS),
};
export function formatDate(
value: string | null | undefined,
locale: Locale,
): string {
if (!value) return '-';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const now = Date.now();
const ageMs = now - date.getTime();
if (ageMs >= 0 && ageMs < 60_000) {
return locale === 'ko'
? '방금'
: locale === 'ja'
? 'たった今'
: locale === 'zh'
? '刚刚'
: 'just now';
}
if (ageMs >= 0 && ageMs < 3_600_000) {
const mins = Math.floor(ageMs / 60_000);
return locale === 'ko'
? `${mins}분 전`
: locale === 'ja'
? `${mins}分前`
: locale === 'zh'
? `${mins} 分钟前`
: `${mins}m ago`;
}
const sameDay = new Date().toDateString() === date.toDateString();
if (sameDay) {
return SHORT_TIME_FORMATTERS[locale].format(date);
}
const time = SHORT_TIME_FORMATTERS[locale].format(date);
if (locale === 'ko')
return `${date.getMonth() + 1}월 ${date.getDate()}일 ${time}`;
if (locale === 'ja')
return `${date.getMonth() + 1}月${date.getDate()}日 ${time}`;
if (locale === 'zh')
return `${date.getMonth() + 1}月${date.getDate()}日 ${time}`;
return MONTH_DAY_TIME_FORMATTERS[locale].format(date);
}
export function taskActionsFor(task: DashboardTask): DashboardTaskAction[] {
if (task.status === 'active') return ['pause', 'cancel'];
if (task.status === 'paused') return ['resume', 'cancel'];
return [];
}
export function statusLabel(status: string, t: Messages): string {
if (status in t.status) return t.status[status as keyof Messages['status']];
return status;
}

View File

@@ -1,293 +0,0 @@
body:has(.glasses-shell) {
min-width: 0;
overflow: hidden;
background: #000;
}
.glasses-shell {
display: grid;
grid-template-rows: auto auto auto minmax(0, 1fr) auto;
gap: 8px;
width: min(100vw, 600px);
height: min(100vh, 600px);
min-height: 0;
margin: 0 auto;
padding: 14px;
overflow: hidden;
background: #050706;
color: #f4f1e9;
}
.glasses-header,
.glasses-status-row,
.glasses-card-head,
.glasses-actions,
.glasses-footer,
.glasses-tabs,
.glasses-room-strip {
display: flex;
align-items: center;
}
.glasses-header {
justify-content: space-between;
gap: 12px;
}
.glasses-kicker,
.glasses-status-row,
.glasses-card-head small,
.glasses-meta dt,
.glasses-footer {
color: #a8afa6;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
}
.glasses-header h1 {
margin: 0;
font-size: 26px;
line-height: 1;
}
.glasses-icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
padding: 0;
border-radius: 8px;
}
.glasses-status-row {
justify-content: space-between;
gap: 8px;
}
.glasses-status-row strong {
color: #6cb087;
}
.glasses-error {
margin: 0;
padding: 8px 10px;
border: 1px solid rgba(224, 100, 75, 0.45);
border-radius: 8px;
background: rgba(224, 100, 75, 0.12);
color: #ffb4a4;
font-size: 12px;
}
.glasses-tabs {
gap: 6px;
min-width: 0;
}
.glasses-tabs button,
.glasses-actions button,
.glasses-room-strip button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 42px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
background: rgba(255, 255, 255, 0.06);
color: #f4f1e9;
white-space: nowrap;
}
.glasses-tabs button:hover:not(:disabled),
.glasses-actions button:hover:not(:disabled),
.glasses-room-strip button:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.1);
}
.glasses-tabs button {
flex: 1;
}
.glasses-tabs button.is-active,
.glasses-tabs button[aria-pressed='true'],
.glasses-actions button.is-active,
.glasses-actions button[aria-pressed='true'],
.glasses-room-strip button.is-active,
.glasses-room-strip button[aria-pressed='true'] {
border-color: rgba(232, 152, 112, 0.72);
background: rgba(214, 130, 88, 0.2);
color: #fff4ec;
}
.glasses-tabs button.is-active:hover:not(:disabled),
.glasses-tabs button[aria-pressed='true']:hover:not(:disabled),
.glasses-actions button.is-active:hover:not(:disabled),
.glasses-actions button[aria-pressed='true']:hover:not(:disabled),
.glasses-room-strip button.is-active:hover:not(:disabled),
.glasses-room-strip button[aria-pressed='true']:hover:not(:disabled) {
background: rgba(214, 130, 88, 0.26);
}
.glasses-card {
display: grid;
align-content: start;
gap: 10px;
min-height: 0;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
background: #111512;
padding: 12px;
}
.glasses-card-head {
justify-content: space-between;
gap: 10px;
}
.glasses-pill {
display: inline-flex;
align-items: center;
max-width: 100%;
min-height: 24px;
padding: 0 8px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 999px;
background: rgba(255, 255, 255, 0.05);
color: #d7ded2;
font-size: 11px;
font-weight: 700;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.glasses-pill.sev-error {
border-color: rgba(224, 100, 75, 0.5);
color: #ffb4a4;
}
.glasses-pill.sev-warn {
border-color: rgba(212, 160, 74, 0.5);
color: #ffd38b;
}
.glasses-queue-card h2 {
margin: 0;
overflow: hidden;
font-size: 22px;
line-height: 1.08;
text-overflow: ellipsis;
white-space: nowrap;
}
.glasses-queue-card p {
display: -webkit-box;
min-height: 0;
margin: 0;
overflow: hidden;
color: #d2d5ce;
font-size: 14px;
line-height: 1.35;
-webkit-box-orient: vertical;
-webkit-line-clamp: 4;
}
.glasses-meta {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 0;
}
.glasses-meta div {
min-width: 0;
}
.glasses-meta dt,
.glasses-meta dd {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.glasses-meta dd {
margin: 2px 0 0;
color: #f4f1e9;
font-size: 13px;
}
.glasses-actions {
gap: 6px;
min-width: 0;
}
.glasses-actions button {
flex: 1;
min-width: 0;
padding: 0 10px;
}
.glasses-empty {
display: grid;
place-items: center;
gap: 6px;
min-height: 220px;
color: #a8afa6;
text-align: center;
}
.glasses-empty strong {
color: #f4f1e9;
font-size: 24px;
}
.glasses-voice-card textarea {
width: 100%;
min-height: 126px;
resize: none;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
background: rgba(255, 255, 255, 0.04);
color: #f4f1e9;
font: inherit;
font-size: 18px;
line-height: 1.35;
padding: 10px;
}
.glasses-voice-card textarea:focus-visible {
border-color: #d68258;
outline: 2px solid rgba(214, 130, 88, 0.2);
}
.glasses-room-strip {
gap: 6px;
overflow: hidden;
}
.glasses-room-strip button {
min-width: 0;
max-width: 50%;
overflow: hidden;
padding: 0 10px;
text-overflow: ellipsis;
}
.glasses-footer {
min-height: 18px;
justify-content: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@media (max-width: 640px) {
.glasses-shell {
width: 100vw;
height: 100vh;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,205 +0,0 @@
import type { Locale } from '../i18n';
export interface RoomMessages {
empty: string;
cardsAria: string;
room: string;
service: string;
agent: string;
status: string;
queue: string;
queueWaitingMessages: string;
tasks: string;
elapsed: string;
activity: string;
loadingActivity: string;
noActivity: string;
task: string;
noTask: string;
currentTurn: string;
noTurn: string;
round: string;
attempt: string;
updated: string;
output: string;
latestOutput: string;
outputHistory: string;
noOutput: string;
recentMessages: string;
messageHistory: string;
noMessages: string;
details: string;
message: string;
messagePlaceholder: string;
send: string;
sending: string;
error: string;
filterAll: string;
sortRecent: string;
sortName: string;
sortQueue: string;
sortLabel: string;
}
export const roomMessages = {
ko: {
empty: '룸 없음.',
cardsAria: '룸 상태 카드',
room: '룸',
service: '서비스',
agent: '에이전트',
status: '상태',
queue: '큐',
queueWaitingMessages: '대기 메시지',
tasks: '태스크',
elapsed: '경과',
activity: '진행',
loadingActivity: '진행 로딩 중',
noActivity: '진행 없음',
task: '태스크',
noTask: '태스크 없음',
currentTurn: '현재 턴',
noTurn: '턴 없음',
round: '라운드',
attempt: '시도',
updated: '갱신',
output: '출력',
latestOutput: '마지막 출력',
outputHistory: '출력 기록',
noOutput: '출력 없음',
recentMessages: '메시지 기록',
messageHistory: '메시지 기록',
noMessages: '메시지 없음',
details: '세부',
message: '메시지',
messagePlaceholder: '요청 입력...',
send: '전송',
sending: '전송 중...',
error: '오류',
filterAll: '전체',
sortRecent: '최근 활동',
sortName: '이름순',
sortQueue: '큐 많은 순',
sortLabel: '정렬',
},
en: {
empty: 'No rooms yet.',
cardsAria: 'Room status cards',
room: 'room',
service: 'service',
agent: 'agent',
status: 'status',
queue: 'queue',
queueWaitingMessages: 'pending messages',
tasks: 'tasks',
elapsed: 'elapsed',
activity: 'activity',
loadingActivity: 'Loading activity',
noActivity: 'No activity',
task: 'task',
noTask: 'No task',
currentTurn: 'Current turn',
noTurn: 'No turn',
round: 'round',
attempt: 'attempt',
updated: 'updated',
output: 'output',
latestOutput: 'latest output',
outputHistory: 'output log',
noOutput: 'No output',
recentMessages: 'Message log',
messageHistory: 'Message log',
noMessages: 'No messages',
details: 'details',
message: 'message',
messagePlaceholder: 'Type request...',
send: 'Send',
sending: 'Sending',
error: 'Error',
filterAll: 'All',
sortRecent: 'Recent activity',
sortName: 'Name',
sortQueue: 'Queue size',
sortLabel: 'Sort',
},
zh: {
empty: '暂无房间。',
cardsAria: '房间状态卡片',
room: '房间',
service: '服务',
agent: '代理',
status: '状态',
queue: '队列',
queueWaitingMessages: '待处理消息',
tasks: '任务',
elapsed: '耗时',
activity: '进展',
loadingActivity: '正在加载进展',
noActivity: '暂无进展',
task: '任务',
noTask: '无任务',
currentTurn: '当前回合',
noTurn: '无回合',
round: '轮次',
attempt: '尝试',
updated: '更新',
output: '输出',
latestOutput: '最新输出',
outputHistory: '输出记录',
noOutput: '暂无输出',
recentMessages: '消息记录',
messageHistory: '消息记录',
noMessages: '暂无消息',
details: '详情',
message: 'Message',
messagePlaceholder: '输入请求...',
send: '发送',
sending: '发送中...',
error: '错误',
filterAll: '全部',
sortRecent: '最近活动',
sortName: '名称',
sortQueue: '队列大小',
sortLabel: '排序',
},
ja: {
empty: 'ルームなし。',
cardsAria: 'ルーム状態カード',
room: 'ルーム',
service: 'サービス',
agent: 'エージェント',
status: '状態',
queue: 'キュー',
queueWaitingMessages: '待機メッセージ',
tasks: 'タスク',
elapsed: '経過',
activity: '進行',
loadingActivity: '進行を読み込み中',
noActivity: '進行なし',
task: 'タスク',
noTask: 'タスクなし',
currentTurn: '現在ターン',
noTurn: 'ターンなし',
round: 'ラウンド',
attempt: '試行',
updated: '更新',
output: '出力',
latestOutput: '最新出力',
outputHistory: '出力履歴',
noOutput: '出力なし',
recentMessages: 'メッセージ履歴',
messageHistory: 'メッセージ履歴',
noMessages: 'メッセージなし',
details: '詳細',
message: 'メッセージ',
messagePlaceholder: '依頼を入力...',
send: '送信',
sending: '送信中...',
error: 'エラー',
filterAll: '全て',
sortRecent: '最近の活動',
sortName: '名前順',
sortQueue: 'キュー順',
sortLabel: '並び替え',
},
} satisfies Record<Locale, RoomMessages>;

View File

@@ -1,21 +0,0 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { GlassesApp } from './GlassesApp';
function isGlassesRoute(): boolean {
const pathname = window.location.pathname.replace(/\/+$/, '') || '/';
const search = new URLSearchParams(window.location.search);
return pathname === '/glasses' || search.get('display') === 'rayban';
}
const root = document.getElementById('root');
if (!root) {
throw new Error('Dashboard root element was not found');
}
createRoot(root).render(
<StrictMode>{isGlassesRoute() ? <GlassesApp /> : <App />}</StrictMode>,
);

View File

@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest';
import { redactSecretsForMarkdown, redactSecretsForPreview } from './redaction';
describe('dashboard redaction', () => {
it('redacts named secret assignments for markdown output', () => {
expect(redactSecretsForMarkdown('OPENAI_API_KEY=sk-testvalue1234')).toBe(
'OPENAI_API_KEY=***',
);
});
it('redacts named secret assignments for compact previews', () => {
expect(redactSecretsForPreview('BOT_TOKEN=xoxb-testvalue1234')).toBe(
'BOT_TOKEN=<redacted>',
);
});
it('redacts standalone secret values consistently', () => {
const raw = 'token sk-1234567890abcdef and ghp_1234567890abcdef';
expect(redactSecretsForMarkdown(raw)).toBe('token *** and ***');
expect(redactSecretsForPreview(raw)).toBe(
'token <redacted-token> and <redacted-token>',
);
});
});

View File

@@ -1,17 +0,0 @@
export const SECRET_ASSIGNMENT_RE =
/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY|AUTH|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*([^\s"'`]+)/gi;
export const SECRET_VALUE_RE =
/\b(?:sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]{12,}|xox[baprs]-[A-Za-z0-9-]{12,}|eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,})\b/g;
export function redactSecretsForMarkdown(value: string): string {
return value
.replace(SECRET_ASSIGNMENT_RE, (_m, key) => `${key}=***`)
.replace(SECRET_VALUE_RE, '***');
}
export function redactSecretsForPreview(value: string): string {
return value
.replace(SECRET_ASSIGNMENT_RE, '$1=<redacted>')
.replace(SECRET_VALUE_RE, '<redacted-token>');
}

View File

@@ -1,34 +0,0 @@
import type { Locale } from './i18n';
const KO_ROLE_LABELS: Record<string, string> = {
arbiter: '중재자',
owner: '오너',
reviewer: '리뷰어',
};
const KO_VERDICT_LABELS: Record<string, string> = {
blocked: '차단',
continue: '계속',
done: '완료',
done_with_concerns: '우려 있음',
needs_context: '컨텍스트 필요',
proceed: '진행',
reset: '초기화',
revise: '수정 필요',
step_done: '단계 완료',
task_done: '작업 완료',
};
export function displayRole(
value: string | null | undefined,
locale: Locale,
): string {
const raw = value ?? '';
if (locale !== 'ko') return raw;
return KO_ROLE_LABELS[raw.trim().toLowerCase()] ?? raw;
}
export function displayVerdict(value: string, locale: Locale): string {
if (locale !== 'ko') return value;
return KO_VERDICT_LABELS[value.trim().toLowerCase()] ?? value;
}

View File

@@ -1,213 +0,0 @@
import { describe, expect, it } from 'vitest';
import type { DashboardRoomActivity } from './api';
import { buildRoomThreadEntries, isWatcherRoomMessage } from './roomThread';
type RoomMessage = DashboardRoomActivity['messages'][number];
type RoomOutput = NonNullable<
DashboardRoomActivity['pairedTask']
>['outputs'][number];
function message(overrides: Partial<RoomMessage>): RoomMessage {
return {
id: 'msg-1',
sender: 'user-1',
senderName: '눈쟁이',
content: 'hello',
timestamp: '2026-04-28T01:00:00.000Z',
isFromMe: false,
isBotMessage: false,
sourceKind: 'human',
...overrides,
};
}
function output(overrides: Partial<RoomOutput>): RoomOutput {
return {
id: 1,
turnNumber: 1,
role: 'owner',
verdict: 'task_done',
createdAt: '2026-04-28T01:02:00.000Z',
outputText: 'TASK_DONE\n\nfinal output',
...overrides,
};
}
describe('room thread entries', () => {
it('keeps regular bot messages so Discord-visible outputs appear in rooms', () => {
const entries = buildRoomThreadEntries({
messages: [
message({ id: 'human-1', content: '확인해줘' }),
message({
id: 'bot-1',
sender: 'bot-1',
senderName: '오너',
content: 'TASK_DONE\n\nprod 배포 완료',
timestamp: '2026-04-28T01:01:00.000Z',
isBotMessage: true,
sourceKind: 'bot',
}),
],
outputs: [],
});
expect(entries.map((entry) => entry.id)).toEqual(['human-1', 'bot-1']);
expect(entries.at(-1)).toMatchObject({
senderName: '오너',
content: 'TASK_DONE\n\nprod 배포 완료',
sourceKind: 'bot',
});
});
it('keeps watcher messages out of the main room thread', () => {
const watcher = message({
id: 'watcher-1',
senderName: '리뷰어',
content: 'CI 완료: PR #1 Quality Check',
isBotMessage: true,
sourceKind: 'bot',
});
expect(isWatcherRoomMessage(watcher)).toBe(true);
expect(
buildRoomThreadEntries({ messages: [watcher], outputs: [] }),
).toHaveLength(0);
});
it('deduplicates bot messages that are already present as paired outputs', () => {
const entries = buildRoomThreadEntries({
messages: [
message({
id: 'bot-duplicate',
senderName: '오너',
content: 'TASK_DONE\n\nfinal output',
timestamp: '2026-04-28T01:02:30.000Z',
isBotMessage: true,
sourceKind: 'bot',
}),
],
outputs: [output({ id: 7 })],
});
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: 'out:7',
sourceKind: 'agent_output',
turnNumber: 1,
});
});
it('deduplicates continuation chunks that are contained in a paired output', () => {
const continuation =
'PR 설명에 TaskPanel.tsx + statusLabel 이동+테스트 2개 모두 명시되어 있고 검증도 완료됐습니다.';
const entries = buildRoomThreadEntries({
messages: [
message({
id: 'bot-continuation',
senderName: '리뷰어',
content: continuation,
timestamp: '2026-04-28T01:02:30.000Z',
isBotMessage: true,
sourceKind: 'bot',
}),
],
outputs: [
output({
id: 8,
role: '리뷰어',
outputText: `STEP_DONE\n\n파일 검증 완료\n\n${continuation}\n\n다음 슬라이스 권고`,
}),
],
});
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: 'out:8',
senderName: '리뷰어',
sourceKind: 'agent_output',
});
});
it('merges adjacent bot chunks from the same sender', () => {
const entries = buildRoomThreadEntries({
messages: [
message({
id: 'reviewer-1',
senderName: '리뷰어',
content: 'STEP_DONE — PR #63 검증 완료\n\n파일 검증',
timestamp: '2026-04-28T01:02:00.000Z',
isBotMessage: true,
sourceKind: 'bot',
}),
message({
id: 'reviewer-2',
senderName: '리뷰어',
content: 'PR 설명에 추출 모듈 전부 명시\n\n다음 슬라이스 권고',
timestamp: '2026-04-28T01:02:03.000Z',
isBotMessage: true,
sourceKind: 'bot',
}),
],
outputs: [],
});
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: 'reviewer-1+reviewer-2',
senderName: '리뷰어',
sourceKind: 'bot',
});
expect(entries[0].content).toContain('파일 검증');
expect(entries[0].content).toContain('다음 슬라이스 권고');
});
it('keeps adjacent human messages separate', () => {
const entries = buildRoomThreadEntries({
messages: [
message({
id: 'human-1',
content: '첫 번째 요청',
timestamp: '2026-04-28T01:02:00.000Z',
}),
message({
id: 'human-2',
content: '두 번째 요청',
timestamp: '2026-04-28T01:02:03.000Z',
}),
],
outputs: [],
});
expect(entries.map((entry) => entry.id)).toEqual(['human-1', 'human-2']);
});
it('keeps adjacent bot status outputs separate', () => {
const entries = buildRoomThreadEntries({
messages: [
message({
id: 'reviewer-status-1',
senderName: '리뷰어',
content: 'STEP_DONE — PR #63 검증 완료',
timestamp: '2026-04-28T01:02:00.000Z',
isBotMessage: true,
sourceKind: 'bot',
}),
message({
id: 'reviewer-status-2',
senderName: '리뷰어',
content: 'STEP_DONE — PR #64 검증 완료',
timestamp: '2026-04-28T01:02:03.000Z',
isBotMessage: true,
sourceKind: 'bot',
}),
],
outputs: [],
});
expect(entries.map((entry) => entry.id)).toEqual([
'reviewer-status-1',
'reviewer-status-2',
]);
});
});

View File

@@ -1,227 +0,0 @@
import type { DashboardRoomActivity } from './api';
type RoomMessage = DashboardRoomActivity['messages'][number];
type RoomOutput = NonNullable<
DashboardRoomActivity['pairedTask']
>['outputs'][number];
export type RoomThreadEntry = {
id: string;
senderName: string;
content: string;
attachments?: RoomMessage['attachments'];
timestamp: string;
isFromMe: boolean;
isBotMessage: boolean;
sourceKind: string;
verdict?: string | null;
turnNumber?: number;
};
const WATCHER_RE =
/^\s*(?:CI 완료|Build |Deploy |Lint |Release |\[CI\]|\[Watcher\]|GitHub Actions)/i;
export function isInternalProtocolPayload(
content: string | null | undefined,
): boolean {
if (!content) return false;
if (/<\/?(sub-agent[-\w]*|tool-call|internal)\b/i.test(content)) return true;
if (/"author"\s*:\s*"[^"]+"\s*,\s*"recipient"\s*:\s*"[^"]+"/.test(content)) {
return true;
}
return false;
}
export function isWatcherRoomMessage(message: RoomMessage): boolean {
return message.sourceKind === 'bot' && WATCHER_RE.test(message.content);
}
function isThreadChatMessage(message: RoomMessage): boolean {
if (isInternalProtocolPayload(message.content)) return false;
if (isWatcherRoomMessage(message)) return false;
return (
message.sourceKind === 'human' ||
message.sourceKind === 'ipc_injected_human' ||
message.sourceKind === 'trusted_external_bot' ||
message.sourceKind === 'bot'
);
}
function toMessageEntry(message: RoomMessage): RoomThreadEntry {
return {
id: message.id,
senderName: message.senderName,
content: message.content,
attachments: message.attachments,
timestamp: message.timestamp,
isFromMe: message.isFromMe,
isBotMessage: message.isBotMessage,
sourceKind: message.sourceKind,
};
}
function toOutputEntry(output: RoomOutput): RoomThreadEntry | null {
if (isInternalProtocolPayload(output.outputText)) return null;
return {
id: `out:${output.id}`,
senderName: output.role,
content: output.outputText,
attachments: output.attachments,
timestamp: output.createdAt,
isFromMe: false,
isBotMessage: true,
sourceKind: 'agent_output',
verdict: output.verdict,
turnNumber: output.turnNumber,
};
}
function messageKey(message: { content: string; senderName: string }): string {
return `${message.senderName}\u0001${message.content}`;
}
function normalizeForDedupe(value: string): string {
return value.replace(/\s+/g, ' ').trim();
}
const MIN_SUBSTRING_DEDUPE_LENGTH = 40;
const BOT_CHUNK_MERGE_WINDOW_MS = 15_000;
const STATUS_OUTPUT_PREFIX_RE =
/^(?:STEP_DONE|TASK_DONE|DONE_WITH_CONCERNS|DONE|BLOCKED|NEEDS_CONTEXT)\b/;
function isDuplicateOutputMessage(
message: RoomThreadEntry,
outputEntries: RoomThreadEntry[],
): boolean {
if (message.sourceKind !== 'bot') return false;
const messageText = normalizeForDedupe(message.content);
if (!messageText) return false;
const messageTime = new Date(message.timestamp).getTime();
return outputEntries.some((output) => {
const outputText = normalizeForDedupe(output.content);
if (!outputText) return false;
const contentMatches =
outputText === messageText ||
outputText.startsWith(messageText) ||
messageText.startsWith(outputText) ||
(messageText.length >= MIN_SUBSTRING_DEDUPE_LENGTH &&
outputText.includes(messageText)) ||
(outputText.length >= MIN_SUBSTRING_DEDUPE_LENGTH &&
messageText.includes(outputText));
if (!contentMatches) return false;
const outputTime = new Date(output.timestamp).getTime();
if (!Number.isFinite(messageTime) || !Number.isFinite(outputTime)) {
return true;
}
return Math.abs(outputTime - messageTime) <= 120_000;
});
}
function entryTimeMs(entry: RoomThreadEntry): number | null {
const time = new Date(entry.timestamp).getTime();
return Number.isFinite(time) ? time : null;
}
function shouldMergeAdjacentBotChunk(
previous: RoomThreadEntry,
next: RoomThreadEntry,
): boolean {
if (
previous.sourceKind === 'agent_output' ||
next.sourceKind === 'agent_output'
) {
return false;
}
if (previous.senderName !== next.senderName) return false;
if (previous.sourceKind !== next.sourceKind) return false;
if (!previous.isBotMessage || !next.isBotMessage) return false;
if (STATUS_OUTPUT_PREFIX_RE.test(next.content.trimStart())) return false;
const previousTime = entryTimeMs(previous);
const nextTime = entryTimeMs(next);
if (previousTime === null || nextTime === null) {
return previous.timestamp === next.timestamp;
}
return Math.abs(nextTime - previousTime) <= BOT_CHUNK_MERGE_WINDOW_MS;
}
function mergeEntryContent(left: string, right: string): string {
const trimmedLeft = left.trimEnd();
const trimmedRight = right.trimStart();
if (!trimmedLeft) return trimmedRight;
if (!trimmedRight) return trimmedLeft;
return `${trimmedLeft}\n\n${trimmedRight}`;
}
function mergeAdjacentBotChunks(entries: RoomThreadEntry[]): RoomThreadEntry[] {
const merged: RoomThreadEntry[] = [];
for (const entry of entries) {
const previous = merged.at(-1);
if (previous && shouldMergeAdjacentBotChunk(previous, entry)) {
previous.id = `${previous.id}+${entry.id}`;
previous.content = mergeEntryContent(previous.content, entry.content);
previous.verdict ??= entry.verdict;
previous.turnNumber ??= entry.turnNumber;
continue;
}
merged.push({ ...entry });
}
return merged;
}
function collectOutputEntries(outputs: RoomOutput[]): RoomThreadEntry[] {
const entries: RoomThreadEntry[] = [];
for (const output of outputs) {
const entry = toOutputEntry(output);
if (entry) entries.push(entry);
}
return entries;
}
function collectChatEntries(
messages: RoomMessage[],
outputEntries: RoomThreadEntry[],
): RoomThreadEntry[] {
const entries: RoomThreadEntry[] = [];
for (const message of messages) {
if (!isThreadChatMessage(message)) continue;
const entry = toMessageEntry(message);
if (!isDuplicateOutputMessage(entry, outputEntries)) entries.push(entry);
}
return entries;
}
function collectOptimisticPending(
pendingMessages: RoomMessage[],
confirmedSet: Set<string>,
): RoomThreadEntry[] {
const entries: RoomThreadEntry[] = [];
for (const message of pendingMessages) {
if (confirmedSet.has(messageKey(message))) continue;
if (isInternalProtocolPayload(message.content)) continue;
entries.push(toMessageEntry(message));
}
return entries;
}
export function buildRoomThreadEntries({
messages,
outputs,
pendingMessages = [],
}: {
messages: RoomMessage[];
outputs: RoomOutput[];
pendingMessages?: RoomMessage[];
}): RoomThreadEntry[] {
const confirmedSet = new Set(messages.map(messageKey));
const outputEntries = collectOutputEntries(outputs);
const chatEntries = collectChatEntries(messages, outputEntries);
const optimisticPending = collectOptimisticPending(
pendingMessages,
confirmedSet,
);
const entries = chatEntries
.concat(optimisticPending, outputEntries)
.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
return mergeAdjacentBotChunks(entries);
}

View File

@@ -1,44 +0,0 @@
import { describe, expect, it } from 'vitest';
import {
PRESET_MODELS,
buildModelOptions,
effortValuesForAgent,
formatEffortOption,
isEffortSupported,
isPresetModel,
} from './settings-options';
describe('settings-options effort', () => {
it('limits Claude agents to low through max without xhigh', () => {
expect(effortValuesForAgent('claude-code')).toEqual([
'',
'low',
'medium',
'high',
'max',
]);
expect(isEffortSupported('claude-code', 'xhigh')).toBe(false);
expect(isEffortSupported('claude-code', 'high')).toBe(true);
});
it('allows xhigh for Codex agents', () => {
expect(effortValuesForAgent('codex')).toContain('xhigh');
expect(isEffortSupported('codex', 'xhigh')).toBe(true);
});
it('shows raw effort keys beside localized labels', () => {
expect(formatEffortOption('high', '높음')).toBe('높음 (high)');
expect(formatEffortOption('', '기본값')).toBe('기본값');
});
});
describe('settings-options models', () => {
it('offers Claude Opus 4.8 as the only Claude preset', () => {
expect(PRESET_MODELS.claude).toEqual(['claude-opus-4-8']);
expect(buildModelOptions('')).toContain('claude-opus-4-8');
expect(isPresetModel('claude-opus-4-8')).toBe(true);
expect(isPresetModel('claude-opus-4-7')).toBe(false);
expect(isPresetModel('claude-opus-4-6')).toBe(false);
});
});

View File

@@ -1,70 +0,0 @@
export const PRESET_MODELS = {
codex: ['gpt-5.5', 'gpt-5.5-pro', 'gpt-5.4', 'gpt-5.3-codex'],
claude: ['claude-opus-4-8'],
} as const;
export type AgentType = 'claude-code' | 'codex';
export const CODEX_EFFORT_VALUES = [
'',
'low',
'medium',
'high',
'xhigh',
'max',
] as const;
export const CLAUDE_EFFORT_VALUES = [
'',
'low',
'medium',
'high',
'max',
] as const;
/** @deprecated Use agent-specific lists via effortValuesForAgent */
export const EFFORT_VALUES = CODEX_EFFORT_VALUES;
export type EffortValue = (typeof CODEX_EFFORT_VALUES)[number];
export function effortValuesForAgent(
agentType: AgentType,
): readonly EffortValue[] {
return agentType === 'claude-code'
? CLAUDE_EFFORT_VALUES
: CODEX_EFFORT_VALUES;
}
export function isEffortSupported(
agentType: AgentType | null | undefined,
effort: string,
): boolean {
if (!effort) return true;
if (!agentType) return true;
return effortValuesForAgent(agentType).includes(effort as EffortValue);
}
export function formatEffortOption(
value: EffortValue,
localizedLabel: string,
): string {
if (value === '') return localizedLabel;
return `${localizedLabel} (${value})`;
}
export function buildModelOptions(current: string): string[] {
const presets = [...PRESET_MODELS.codex, ...PRESET_MODELS.claude];
const trimmed = current.trim();
if (!trimmed || presets.includes(trimmed as (typeof presets)[number])) {
return [...presets];
}
return [trimmed, ...presets.filter((model) => model !== trimmed)];
}
export function isPresetModel(model: string): boolean {
const trimmed = model.trim();
return (
(PRESET_MODELS.codex as readonly string[]).includes(trimmed) ||
(PRESET_MODELS.claude as readonly string[]).includes(trimmed)
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,72 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { fetchRoomTimeline, type DashboardRoomActivity } from './api';
export type RoomActivityMap = Record<string, DashboardRoomActivity>;
interface UseSelectedRoomActivityOptions {
active: boolean;
pollMs?: number;
selectedRoomJid: string | null;
}
export function useSelectedRoomActivity({
active,
pollMs = 2000,
selectedRoomJid,
}: UseSelectedRoomActivityOptions): {
refreshRoom: (roomJid: string) => Promise<DashboardRoomActivity>;
roomActivity: RoomActivityMap;
roomActivityLoading: boolean;
} {
const [roomActivity, setRoomActivity] = useState<RoomActivityMap>({});
const [roomActivityLoading, setRoomActivityLoading] = useState(false);
const refreshRoom = useCallback(async (roomJid: string) => {
const activity = await fetchRoomTimeline(roomJid);
setRoomActivity((previous) => ({
...previous,
[roomJid]: activity,
}));
return activity;
}, []);
useEffect(() => {
if (!active || !selectedRoomJid) {
return undefined;
}
let cancelled = false;
let inFlight = false;
let pollIntervalId: number | null = null;
const fetchOnce = async (initial: boolean) => {
if (cancelled || inFlight) return;
inFlight = true;
if (initial) setRoomActivityLoading(true);
try {
await refreshRoom(selectedRoomJid);
} catch {
/* Keep the last good timeline snapshot. */
} finally {
inFlight = false;
if (!cancelled && initial) setRoomActivityLoading(false);
}
};
void fetchOnce(true);
pollIntervalId = window.setInterval(() => void fetchOnce(false), pollMs);
return () => {
cancelled = true;
if (pollIntervalId !== null) window.clearInterval(pollIntervalId);
};
}, [active, pollMs, refreshRoom, selectedRoomJid]);
return {
refreshRoom,
roomActivity,
roomActivityLoading:
active && selectedRoomJid !== null ? roomActivityLoading : false,
};
}

View File

@@ -1 +0,0 @@
/// <reference types="vite/client" />

View File

@@ -1,21 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"references": []
}

View File

@@ -1,18 +0,0 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
export default defineConfig({
root: __dirname,
plugins: [react()],
build: {
outDir: 'dist',
emptyOutDir: true,
},
server: {
host: process.env.VITE_DEV_HOST ?? '127.0.0.1',
port: 5174,
proxy: {
'/api': process.env.VITE_API_TARGET ?? 'http://127.0.0.1:8734',
},
},
});

301
bun.lock
View File

@@ -5,39 +5,25 @@
"": {
"name": "ejclaw",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.27.1",
"cron-parser": "^5.6.1",
"discord.js": "^14.26.4",
"ejclaw-runners-shared": "workspace:*",
"lucide-react": "^1.11.0",
"pino": "^9.6.0",
"pino-pretty": "^13.0.0",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"yaml": "^2.9.0",
"zod": "^4.3.6",
},
"devDependencies": {
"@axe-core/playwright": "^4.11.3",
"@eslint/js": "^10.0.1",
"@types/better-sqlite3": "^7.6.13",
"@types/bun": "^1.3.11",
"@types/node": "^22.10.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.9",
"better-sqlite3": "^12.8.0",
"eslint": "^10.2.1",
"globals": "^17.5.0",
"husky": "^9.1.7",
"playwright": "^1.59.1",
"prettier": "^3.8.1",
"typescript": "^5.7.0",
"typescript-eslint": "^8.59.0",
"vite": "^8.1.3",
"vitest": "^4.1.9",
},
},
@@ -45,9 +31,10 @@
"name": "ejclaw-agent-runner",
"version": "1.0.0",
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "0.3.153",
"@anthropic-ai/claude-agent-sdk": "0.3.286",
"@anthropic-ai/sdk": "0.100.0",
"@modelcontextprotocol/sdk": "1.29.0",
"chrome-devtools-mcp": "1.11.0",
"cron-parser": "^5.0.0",
"ejclaw-runners-shared": "workspace:*",
"zod": "^4.0.0",
@@ -61,7 +48,7 @@
"name": "ejclaw-codex-runner",
"version": "1.0.0",
"dependencies": {
"@openai/codex": "0.133.0",
"@openai/codex": "0.159.3",
"ejclaw-runners-shared": "workspace:*",
},
"devDependencies": {
@@ -79,28 +66,26 @@
},
},
"packages": {
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.153", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.153", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.153", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.153", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.153", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.153", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.153", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.153", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.153" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-+WYWQ5ih2dOuiJY4yql5pje3w8iA+aS7eZXJSFo6LZxmEiH4nV4n/fjhJCWPcqyo7TdvhAjS2cPqwIslNw3c7A=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.286", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.286", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.286", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.286", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.286", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.286", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.286", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.286", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.286" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-InL/UNmRGSwBM/81PME0J0TZDsDBBlweWqRZgq2XSViSIg2hBi8nIL8j9Hm6MHRH85wgDJQE5n6Vo/r9hIO0NQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.153", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4K2K/n/qikp24ufO38owSEj5RPMWjBmf83BSUxLlzOhOXt7dHXs1CitmY9ZYM58Wmn3qhJs9DaS//ptO1siskQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.286", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gkxWcJ+Z23UxwghI1V3dL09PkELIZmB2vPelR8XsdfhS+yP1KvoW7FThvRLojcxXb3fj0ddYawjQSQYIkXFbxw=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.153", "", { "os": "darwin", "cpu": "x64" }, "sha512-kY5DPMAK+ZkphoIUjOiP6sSB57Lw2H1RUNK2HVEDowagbl9T47DSbkjYE4NWYqfy22aebPj02VAIbFfFmYxnMw=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.286", "", { "os": "darwin", "cpu": "x64" }, "sha512-eMdni7sy1ud2IISI4QSsfVBCxotzSe62zCGdXISejL9MxDIwcRgEGZpO5OV+j7t8mNGMTe6Opl1t/3Z/1RUJaQ=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.153", "", { "os": "linux", "cpu": "arm64" }, "sha512-XoIP6xJn+QlfBta96yfxdtaeJ/BstA2S9abZJYeWs/wwNjQNWs83repg/v1VPuGn7i44teSzLtzoAv9t1w4Ybg=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.286", "", { "os": "linux", "cpu": "arm64" }, "sha512-3h+WWGek9beZ6i1qbIjjwYEFbs46D6qumjSBc6cLsEvnufcoi7mc0iBwbFSh9yRb3upxoi4ZTJdl53T3gLTdUQ=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.153", "", { "os": "linux", "cpu": "arm64" }, "sha512-5fD6MagyX+1tZdpVjZ6rN178pR7K10c+JyTsEh4HUJR3tnVO9uZYcmEcsKLX1TjWX+mz5+TW9rwDP5AMHXsjNA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.286", "", { "os": "linux", "cpu": "arm64" }, "sha512-fG8Cqx53jkFyEL86ETA0tdLH3p06yFQKHcoxnMpiU+VmJ5g6uGFhsUZbJ6gFvuT3EgyMcNI2kZwhCCDF/DTnpQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.153", "", { "os": "linux", "cpu": "x64" }, "sha512-U2eY8iBLF0vrvuHnh33UA3LA/aIVgSk2Pw5KY7N5lH5fYzcnDBoT8bG32lelQIoaUDY0znOWIc0vqN5/Yih51w=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.286", "", { "os": "linux", "cpu": "x64" }, "sha512-kNczbWhWJ1G8sPRZd4Nsx/Ozr/kx16lT2NGp/EEmTV4Hn732xfLkUOlg+tFcS78i6lOPBknjDB/cz/J5Ha4wDQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.153", "", { "os": "linux", "cpu": "x64" }, "sha512-4o+1RnNAL31iZDDT46AWl/t5lUSVJ5Gq8o2IxPgNBltPHAL3aUmTTDLxjDb+gFVEyegyy9FwK0yPJGpNp4CxKA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.286", "", { "os": "linux", "cpu": "x64" }, "sha512-WeO/wG2uPh95BhOQi1IsIECdW5gJgC1Q9xtGw4RjV04it1fBMAbUe7aVwP4DQgH8PHnmduA7dRnLtbnZnrGsjg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.153", "", { "os": "win32", "cpu": "arm64" }, "sha512-GQsZTvf4pJVVAgaXwpN/W7RpO7dtUd3VCM3zxD7RQ1X+Dc8tUNPMWr7JCHEYwrUWiS1jeSjLOsrAuRFopSP43Q=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.286", "", { "os": "win32", "cpu": "arm64" }, "sha512-N4p7Gw5Qg3q9+Y5sEht1cIHHZkmBAUfWXJnqfmDD7N8twqF3XNVK3w65hDLqli4i0ttuZu79bGmRGkgNGm9Imw=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.153", "", { "os": "win32", "cpu": "x64" }, "sha512-t/+IEFLsp+fY1G5EZhzVBNKI1mm28rPNcyrlJHy3wCbl1aA/Myd7mWnNCRckDGENZz4V7KyqCslLsCt5gT2iPg=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.286", "", { "os": "win32", "cpu": "x64" }, "sha512-pg35GRPBKyviod0i8Z3EVMzDnTiiiucuWUbyH1bVIFFN0UWCQQ+PRUJ15qrPKjL6+vlFxOX2ei9FfsWYjGYZwA=="],
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.100.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-cAm3aXm6qAiHIvHxyIIGd6tVmsD2gDqlc2h0R20ijNUzGgVnIN822bit4mKbF6CkuV7qIrLQIPoAepHEpanrQQ=="],
"@axe-core/playwright": ["@axe-core/playwright@4.11.3", "", { "dependencies": { "axe-core": "~4.11.4" }, "peerDependencies": { "playwright-core": ">= 1.0.0" } }, "sha512-h/kfksv4F0cVIDlKpT4700OehdRgpvuVskuQ2nb7/JmtWUXpe9ftHAPtwyXGvVSsa6SJ64A9ER7Zrzc/sIvC4w=="],
"@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="],
"@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
@@ -159,21 +144,21 @@
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.27.1", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
"@openai/codex": ["@openai/codex@0.133.0", "", { "optionalDependencies": { "@openai/codex-darwin-arm64": "npm:@openai/codex@0.133.0-darwin-arm64", "@openai/codex-darwin-x64": "npm:@openai/codex@0.133.0-darwin-x64", "@openai/codex-linux-arm64": "npm:@openai/codex@0.133.0-linux-arm64", "@openai/codex-linux-x64": "npm:@openai/codex@0.133.0-linux-x64", "@openai/codex-win32-arm64": "npm:@openai/codex@0.133.0-win32-arm64", "@openai/codex-win32-x64": "npm:@openai/codex@0.133.0-win32-x64" }, "bin": { "codex": "bin/codex.js" } }, "sha512-Gh42kLLBo/6gpnHmDzUWDVvyS57ekCB1+1Dz0RG2oIl3Lhk1uwrjSj/PwaJWWh4Rw/rUp1RqkwrMugFfFEOlqQ=="],
"@openai/codex": ["@openai/codex@0.159.3", "", { "optionalDependencies": { "@openai/codex-darwin-arm64": "npm:@openai/codex@0.159.3-darwin-arm64", "@openai/codex-darwin-x64": "npm:@openai/codex@0.159.3-darwin-x64", "@openai/codex-linux-arm64": "npm:@openai/codex@0.159.3-linux-arm64", "@openai/codex-linux-x64": "npm:@openai/codex@0.159.3-linux-x64", "@openai/codex-win32-arm64": "npm:@openai/codex@0.159.3-win32-arm64", "@openai/codex-win32-x64": "npm:@openai/codex@0.159.3-win32-x64" }, "bin": { "codex": "bin/codex.js" } }, "sha512-hg4nlqCwRb87GocxNnHvz4sadOrdJ71mO0a4CUYWXjAozJe2gtuAdRFldKGSQXw9m7SgR4ydis12KDVVPgzDkQ=="],
"@openai/codex-darwin-arm64": ["@openai/codex@0.133.0-darwin-arm64", "", { "os": "darwin", "cpu": "arm64" }, "sha512-W7f8+DckLujnqGlptKCzgJU+ooeHKMuk6KYgMFP6A9asn7YUsGUgJqjiBaX8oNcXO6w/pTbKGRARx1kCNS8lIg=="],
"@openai/codex-darwin-arm64": ["@openai/codex@0.159.3-darwin-arm64", "", { "os": "darwin", "cpu": "arm64" }, "sha512-aI4UY14YURYxJxnRK+AE4QU+aek0mgtyyo7Rw9rNbCQUYETRQ0NYdJzU9ytljERGpPlht3dHHI1u4NhqHoDJDQ=="],
"@openai/codex-darwin-x64": ["@openai/codex@0.133.0-darwin-x64", "", { "os": "darwin", "cpu": "x64" }, "sha512-Ek8ikvLOiXZ8emcIJVBXxK6fm8ratBy0kaEt3JNisTNszxGshUHf/R4xxDxIyKNcUkYYXjW7A/rMwW3iu3OFlg=="],
"@openai/codex-darwin-x64": ["@openai/codex@0.159.3-darwin-x64", "", { "os": "darwin", "cpu": "x64" }, "sha512-KTOQOD184DMXpR3TqnDUnLsgad14WJn+x3XmjBaXRHchKYGttjREwqrwzC61xQYFeh6VkogAceybR+SMbbgvYQ=="],
"@openai/codex-linux-arm64": ["@openai/codex@0.133.0-linux-arm64", "", { "os": "linux", "cpu": "arm64" }, "sha512-uKXYYSJ3mY16sp4hcG/4BMNRjva/ZS4oARiI1+7k8+NiuoAhdCGWNe5u4KJ3sMuL3tp/IXcmc6B56EFX1+WDBQ=="],
"@openai/codex-linux-arm64": ["@openai/codex@0.159.3-linux-arm64", "", { "os": "linux", "cpu": "arm64" }, "sha512-84C1yhAI+i0hqh77Akp/Ma09Z4d5oLKcZKqW1WZpEDh8bKbNvvbNEd6pE+GMUe2Kwg7jCbuvkRNH1zgK+SCM3Q=="],
"@openai/codex-linux-x64": ["@openai/codex@0.133.0-linux-x64", "", { "os": "linux", "cpu": "x64" }, "sha512-9YfyqrfUj/UZ2+aXE4zBz47t6RXbVni95ZorGsNh857vxYK/asVpUtR2cymo9lB3JaI4mQaKFfV/t7IRItqkuA=="],
"@openai/codex-linux-x64": ["@openai/codex@0.159.3-linux-x64", "", { "os": "linux", "cpu": "x64" }, "sha512-xlHydfOksnNt/qz4BEVFvjMWunweaVSNtha/DkVUwWZnVZxbqiJwsXSl2iZDk04b6k/g0OI7jU06XqzHB2s5og=="],
"@openai/codex-win32-arm64": ["@openai/codex@0.133.0-win32-arm64", "", { "os": "win32", "cpu": "arm64" }, "sha512-mRzND0PSGHRoLk0X41GTSoc3tFjZSF4HgDlfjU5fiQcWVi0/kLb7Ku6/tPFT/X2hOLa3YdJkbIcHC0Hc9ni80g=="],
"@openai/codex-win32-arm64": ["@openai/codex@0.159.3-win32-arm64", "", { "os": "win32", "cpu": "arm64" }, "sha512-4C+EuH1zE4rO5w1MsrnS98Tvq6Ff4+zeNr3pVeR/UsQ+VrTY5BCA9nZuXuCXNLKak1tLOw81b+fQM4jKGFCeDA=="],
"@openai/codex-win32-x64": ["@openai/codex@0.133.0-win32-x64", "", { "os": "win32", "cpu": "x64" }, "sha512-u3ji78DIPZCGJeELuovsAnaZH+vK9gsA4F6M1y+Uy2s80Sz7/i1S0KL81qGReYji3urSjgBpkQuNP47GXOqxrQ=="],
"@openai/codex-win32-x64": ["@openai/codex@0.159.3-win32-x64", "", { "os": "win32", "cpu": "x64" }, "sha512-h8w5nslfQyoYbonZaRlLwvPKFS9Mcxz5vUeCeoHKF5SsZUP9jSBH7hxUdc8RWJffJtfbV2qxdnImVAj9zy2fwA=="],
"@oxc-project/types": ["@oxc-project/types@0.146.0", "", {}, "sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA=="],
@@ -209,7 +194,7 @@
"@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.5", "", { "os": "win32", "cpu": "x64" }, "sha512-e/SXpgISz+IoqVcSSI0rx/d/he8zqLex+/rCWpnHpmVfmPIUjag9H6P7zotf0gJHwPUhQxZ/mF8tr6acebT9yw=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.7", "", {}, "sha512-qujRfC8sFVInYSPPMLQByRh7zhwkGFS4+tyMQ83srV1qrxL4g8E2tyxVVyxd0+8QeBM1mIk9KbWxkegRr76XzA=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
"@sapphire/async-queue": ["@sapphire/async-queue@1.5.5", "", {}, "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg=="],
@@ -227,32 +212,16 @@
"@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
"@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],
"@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
"@types/esrecurse": ["@types/esrecurse@4.3.1", "", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
"@types/estree-jsx": ["@types/estree-jsx@1.0.5", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="],
"@types/hast": ["@types/hast@3.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ=="],
"@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
"@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="],
"@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
"@types/node": ["@types/node@22.19.11", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/react": ["@types/react@19.2.14", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
"@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],
"@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.59.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.59.0", "@typescript-eslint/type-utils": "8.59.0", "@typescript-eslint/utils": "8.59.0", "@typescript-eslint/visitor-keys": "8.59.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.59.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-HyAZtpdkgZwpq8Sz3FSUvCR4c+ScbuWa9AksK2Jweub7w4M3yTz4O11AqVJzLYjy/B9ZWPyc81I+mOdJU/bDQw=="],
@@ -275,10 +244,6 @@
"@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.59.0", "", { "dependencies": { "@typescript-eslint/types": "8.59.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-/uejZt4dSere1bx12WLlPfv8GktzcaDtuJ7s42/HEZ5zGj9oxRaD4bj7qwSunXkf+pbAhFt2zjpHYUiT5lHf0Q=="],
"@ungap/structured-clone": ["@ungap/structured-clone@1.3.0", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="],
"@vitejs/plugin-react": ["@vitejs/plugin-react@6.0.1", "", { "dependencies": { "@rolldown/pluginutils": "1.0.0-rc.7" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ=="],
"@vitest/coverage-v8": ["@vitest/coverage-v8@4.1.11", "", { "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/utils": "4.1.11", "ast-v8-to-istanbul": "^1.0.0", "istanbul-lib-coverage": "^3.2.2", "istanbul-lib-report": "^3.0.1", "istanbul-reports": "^3.2.0", "magicast": "^0.5.2", "obug": "^2.1.1", "std-env": "^4.0.0-rc.1", "tinyrainbow": "^3.1.0" }, "peerDependencies": { "@vitest/browser": "4.1.11", "vitest": "4.1.11" }, "optionalPeers": ["@vitest/browser"] }, "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw=="],
"@vitest/expect": ["@vitest/expect@4.1.11", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw=="],
@@ -313,10 +278,6 @@
"atomic-sleep": ["atomic-sleep@1.0.0", "", {}, "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="],
"axe-core": ["axe-core@4.11.4", "", {}, "sha512-KunSNx+TVpkAw/6ULfhnx+HWRecjqZGTOyquAoWHYLRSdK1tB5Ihce1ZW+UY3fj33bYAFWPu7W/GRSmmrCGuxA=="],
"bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
"balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
@@ -341,23 +302,13 @@
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],
"chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],
"character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],
"character-entities-html4": ["character-entities-html4@2.1.0", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="],
"character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="],
"character-reference-invalid": ["character-reference-invalid@2.0.1", "", {}, "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="],
"chownr": ["chownr@1.1.4", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
"colorette": ["colorette@2.0.20", "", {}, "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w=="],
"chrome-devtools-mcp": ["chrome-devtools-mcp@1.11.0", "", { "peerDependencies": { "@blackwell-systems/gcf": "^2.2.2", "@toon-format/toon": "^4.1.0" }, "optionalPeers": ["@blackwell-systems/gcf", "@toon-format/toon"], "bin": { "chrome-devtools": "build/src/bin/chrome-devtools.js", "chrome-devtools-mcp": "build/src/bin/chrome-devtools-mcp.js" } }, "sha512-CytJ/5tnzrS+J/74be2P5aCOsS/mmGRHys/Si+IYC4ucrbnWAmES/dYdxGJjeUCECRcoFUilZAysdjlwqUjXIA=="],
"comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],
"colorette": ["colorette@2.0.20", "", {}, "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w=="],
"content-disposition": ["content-disposition@1.0.1", "", {}, "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q=="],
@@ -375,14 +326,10 @@
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"dateformat": ["dateformat@4.6.3", "", {}, "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="],
"decompress-response": ["decompress-response@6.0.0", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
"deep-extend": ["deep-extend@0.6.0", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
@@ -391,12 +338,8 @@
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
"discord-api-types": ["discord-api-types@0.38.53", "", {}, "sha512-HL1zz/UuZ+bbJjA/X8Kbxx9gk8v9rJAbTeWRNYKmIdjwJ7EovjlHgoJTxcLpATfNJ+AonOtMdy3Y5MVIJAAd/A=="],
"discord.js": ["discord.js@14.27.0", "", { "dependencies": { "@discordjs/builders": "^1.14.1", "@discordjs/collection": "1.5.3", "@discordjs/formatters": "^0.6.2", "@discordjs/rest": "^2.6.2", "@discordjs/util": "^1.2.0", "@discordjs/ws": "^1.2.3", "@sapphire/snowflake": "3.5.5", "discord-api-types": "^0.38.49", "fast-deep-equal": "3.1.3", "lodash.snakecase": "4.1.1", "magic-bytes.js": "^1.13.0", "tslib": "^2.6.3", "undici": "^6.27.0" } }, "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A=="],
@@ -441,8 +384,6 @@
"estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
"estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="],
"estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
"esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
@@ -461,8 +402,6 @@
"express-rate-limit": ["express-rate-limit@8.3.1", "", { "dependencies": { "ip-address": "10.1.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw=="],
"extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
"fast-copy": ["fast-copy@4.0.2", "", {}, "sha512-ybA6PDXIXOXivLJK/z9e+Otk7ve13I4ckBvGO5I2RRmBU1gMHLVDJYEuJYhGwez7YNlYji2M2DvVU+a9mSFDlw=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
@@ -497,7 +436,7 @@
"fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
@@ -519,18 +458,12 @@
"hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
"hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.6", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
"hast-util-whitespace": ["hast-util-whitespace@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
"help-me": ["help-me@5.0.0", "", {}, "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg=="],
"hono": ["hono@4.12.9", "", {}, "sha512-wy3T8Zm2bsEvxKZM5w21VdHDDcwVS1yUFFY6i8UobSsKfFceT7TOwhbhfKsDyx7tYQlmRM5FLpIuYvNFyjctiA=="],
"html-escaper": ["html-escaper@2.0.2", "", {}, "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg=="],
"html-url-attributes": ["html-url-attributes@3.0.1", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"husky": ["husky@9.1.7", "", { "bin": "bin.js" }, "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA=="],
@@ -547,26 +480,14 @@
"ini": ["ini@1.3.8", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
"inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
"ip-address": ["ip-address@10.1.0", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="],
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
"is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
"is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="],
"is-decimal": ["is-decimal@2.0.1", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="],
"is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
"is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
"is-hexadecimal": ["is-hexadecimal@2.0.1", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="],
"is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
@@ -627,10 +548,6 @@
"lodash.snakecase": ["lodash.snakecase@4.1.1", "", {}, "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="],
"longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],
"lucide-react": ["lucide-react@1.11.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-UOhjdztXCgdBReRcIhsvz2siIBogfv/lhJEIViCpLt924dO+GDms9T7DNoucI23s6kEPpe988m5N0D2ajnzb2g=="],
"luxon": ["luxon@3.7.2", "", {}, "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew=="],
"magic-bytes.js": ["magic-bytes.js@1.13.0", "", {}, "sha512-afO2mnxW7GDTXMm5/AoN1WuOcdoKhtgXjIvHmobqTD1grNplhGdv3PFOyjCVmrnOZBIT/gD/koDKpYG+0mvHcg=="],
@@ -641,100 +558,12 @@
"make-dir": ["make-dir@4.0.0", "", { "dependencies": { "semver": "^7.5.3" } }, "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw=="],
"markdown-table": ["markdown-table@3.0.4", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg=="],
"mdast-util-from-markdown": ["mdast-util-from-markdown@2.0.3", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q=="],
"mdast-util-gfm": ["mdast-util-gfm@3.1.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-gfm-autolink-literal": "^2.0.0", "mdast-util-gfm-footnote": "^2.0.0", "mdast-util-gfm-strikethrough": "^2.0.0", "mdast-util-gfm-table": "^2.0.0", "mdast-util-gfm-task-list-item": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ=="],
"mdast-util-gfm-autolink-literal": ["mdast-util-gfm-autolink-literal@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-find-and-replace": "^3.0.0", "micromark-util-character": "^2.0.0" } }, "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ=="],
"mdast-util-gfm-footnote": ["mdast-util-gfm-footnote@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0" } }, "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ=="],
"mdast-util-gfm-strikethrough": ["mdast-util-gfm-strikethrough@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg=="],
"mdast-util-gfm-table": ["mdast-util-gfm-table@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg=="],
"mdast-util-gfm-task-list-item": ["mdast-util-gfm-task-list-item@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ=="],
"mdast-util-mdx-expression": ["mdast-util-mdx-expression@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ=="],
"mdast-util-mdx-jsx": ["mdast-util-mdx-jsx@3.2.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0", "unist-util-stringify-position": "^4.0.0", "vfile-message": "^4.0.0" } }, "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q=="],
"mdast-util-mdxjs-esm": ["mdast-util-mdxjs-esm@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg=="],
"mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="],
"mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="],
"mdast-util-to-markdown": ["mdast-util-to-markdown@2.1.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA=="],
"mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="],
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
"merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
"micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="],
"micromark-core-commonmark": ["micromark-core-commonmark@2.0.3", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg=="],
"micromark-extension-gfm": ["micromark-extension-gfm@3.0.0", "", { "dependencies": { "micromark-extension-gfm-autolink-literal": "^2.0.0", "micromark-extension-gfm-footnote": "^2.0.0", "micromark-extension-gfm-strikethrough": "^2.0.0", "micromark-extension-gfm-table": "^2.0.0", "micromark-extension-gfm-tagfilter": "^2.0.0", "micromark-extension-gfm-task-list-item": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w=="],
"micromark-extension-gfm-autolink-literal": ["micromark-extension-gfm-autolink-literal@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw=="],
"micromark-extension-gfm-footnote": ["micromark-extension-gfm-footnote@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw=="],
"micromark-extension-gfm-strikethrough": ["micromark-extension-gfm-strikethrough@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw=="],
"micromark-extension-gfm-table": ["micromark-extension-gfm-table@2.1.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg=="],
"micromark-extension-gfm-tagfilter": ["micromark-extension-gfm-tagfilter@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg=="],
"micromark-extension-gfm-task-list-item": ["micromark-extension-gfm-task-list-item@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw=="],
"micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="],
"micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="],
"micromark-factory-space": ["micromark-factory-space@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg=="],
"micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="],
"micromark-factory-whitespace": ["micromark-factory-whitespace@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ=="],
"micromark-util-character": ["micromark-util-character@2.1.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="],
"micromark-util-chunked": ["micromark-util-chunked@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA=="],
"micromark-util-classify-character": ["micromark-util-classify-character@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q=="],
"micromark-util-combine-extensions": ["micromark-util-combine-extensions@2.0.1", "", { "dependencies": { "micromark-util-chunked": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg=="],
"micromark-util-decode-numeric-character-reference": ["micromark-util-decode-numeric-character-reference@2.0.2", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw=="],
"micromark-util-decode-string": ["micromark-util-decode-string@2.0.1", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ=="],
"micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="],
"micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="],
"micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="],
"micromark-util-resolve-all": ["micromark-util-resolve-all@2.0.1", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg=="],
"micromark-util-sanitize-uri": ["micromark-util-sanitize-uri@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ=="],
"micromark-util-subtokenize": ["micromark-util-subtokenize@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA=="],
"micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="],
"micromark-util-types": ["micromark-util-types@2.0.2", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="],
"mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
@@ -777,8 +606,6 @@
"p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="],
"parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
@@ -791,7 +618,7 @@
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],
"picomatch": ["picomatch@4.0.4", "", {}, "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A=="],
"pino": ["pino@9.14.0", "", { "dependencies": { "@pinojs/redact": "^0.4.0", "atomic-sleep": "^1.0.0", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^2.0.0", "pino-std-serializers": "^7.0.0", "process-warning": "^5.0.0", "quick-format-unescaped": "^4.0.3", "real-require": "^0.2.0", "safe-stable-stringify": "^2.3.1", "sonic-boom": "^4.0.1", "thread-stream": "^3.0.0" }, "bin": "bin.js" }, "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w=="],
@@ -803,10 +630,6 @@
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"playwright": ["playwright@1.59.1", "", { "dependencies": { "playwright-core": "1.59.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw=="],
"playwright-core": ["playwright-core@1.59.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg=="],
"postcss": ["postcss@8.5.26", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="],
"prebuild-install": ["prebuild-install@7.1.3", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
@@ -817,8 +640,6 @@
"process-warning": ["process-warning@5.0.0", "", {}, "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA=="],
"property-information": ["property-information@7.1.0", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"pump": ["pump@3.0.3", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA=="],
@@ -835,24 +656,10 @@
"rc": ["rc@1.2.8", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
"react": ["react@19.2.5", "", {}, "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA=="],
"react-dom": ["react-dom@19.2.5", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.5" } }, "sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag=="],
"react-markdown": ["react-markdown@10.1.0", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "html-url-attributes": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "unified": "^11.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" }, "peerDependencies": { "@types/react": ">=18", "react": ">=18" } }, "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ=="],
"readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"real-require": ["real-require@0.2.0", "", {}, "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="],
"remark-gfm": ["remark-gfm@4.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
"remark-parse": ["remark-parse@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="],
"remark-rehype": ["remark-rehype@11.1.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "mdast-util-to-hast": "^13.0.0", "unified": "^11.0.0", "vfile": "^6.0.0" } }, "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw=="],
"remark-stringify": ["remark-stringify@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-to-markdown": "^2.0.0", "unified": "^11.0.0" } }, "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"rolldown": ["rolldown@1.2.5", "", { "dependencies": { "@oxc-project/types": "=0.146.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.5", "@rolldown/binding-android-arm64": "1.2.5", "@rolldown/binding-darwin-arm64": "1.2.5", "@rolldown/binding-darwin-x64": "1.2.5", "@rolldown/binding-freebsd-x64": "1.2.5", "@rolldown/binding-linux-arm-gnueabihf": "1.2.5", "@rolldown/binding-linux-arm64-gnu": "1.2.5", "@rolldown/binding-linux-arm64-musl": "1.2.5", "@rolldown/binding-linux-ppc64-gnu": "1.2.5", "@rolldown/binding-linux-s390x-gnu": "1.2.5", "@rolldown/binding-linux-x64-gnu": "1.2.5", "@rolldown/binding-linux-x64-musl": "1.2.5", "@rolldown/binding-openharmony-arm64": "1.2.5", "@rolldown/binding-win32-arm64-msvc": "1.2.5", "@rolldown/binding-win32-x64-msvc": "1.2.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-VD2IE5PUG4Oj8zz2VGykiYd5wbnjdIiSsNQb8Qu5B+noEp+A78mu2iVvpp27g8es14Tk9rofNs5Tku9iQCS4fA=="],
@@ -865,8 +672,6 @@
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"secure-json-parse": ["secure-json-parse@4.1.0", "", {}, "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA=="],
"semver": ["semver@7.7.4", "", { "bin": "bin/semver.js" }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
@@ -899,8 +704,6 @@
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="],
"split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="],
"stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
@@ -913,14 +716,8 @@
"string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
"strip-json-comments": ["strip-json-comments@5.0.3", "", {}, "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw=="],
"style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
"style-to-object": ["style-to-object@1.0.14", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
"supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
"tar-fs": ["tar-fs@2.1.4", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
@@ -933,16 +730,12 @@
"tinyexec": ["tinyexec@1.0.2", "", {}, "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg=="],
"tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
"tinyglobby": ["tinyglobby@0.2.16", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg=="],
"tinyrainbow": ["tinyrainbow@3.1.1", "", {}, "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="],
"trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="],
"ts-algebra": ["ts-algebra@2.0.0", "", {}, "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw=="],
"ts-api-utils": ["ts-api-utils@2.5.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="],
@@ -965,18 +758,6 @@
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
"unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
"unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="],
"unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="],
"unist-util-visit": ["unist-util-visit@5.1.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg=="],
"unist-util-visit-parents": ["unist-util-visit-parents@6.0.2", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
@@ -985,10 +766,6 @@
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
"vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
"vite": ["vite@8.2.2", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.5", "postcss": "^8.5.26", "rolldown": "~1.2.4", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.4.0 || ^0.5.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q=="],
"vitest": ["vitest@4.1.11", "", { "dependencies": { "@vitest/expect": "4.1.11", "@vitest/mocker": "4.1.11", "@vitest/pretty-format": "4.1.11", "@vitest/runner": "4.1.11", "@vitest/snapshot": "4.1.11", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.11", "@vitest/browser-preview": "4.1.11", "@vitest/browser-webdriverio": "4.1.11", "@vitest/coverage-istanbul": "4.1.11", "@vitest/coverage-v8": "4.1.11", "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw=="],
@@ -1011,8 +788,6 @@
"zod-to-json-schema": ["zod-to-json-schema@3.25.1", "", { "peerDependencies": { "zod": "^3.25 || ^4" } }, "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA=="],
"zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
"@discordjs/formatters/discord-api-types": ["discord-api-types@0.38.41", "", {}, "sha512-yMECyR8j9c2fVTvCQ+Qc24pweYFIZk/XoxDOmt1UvPeSw5tK6gXBd/2hhP+FEAe9Y6ny8pRMaf618XDK4U53OQ=="],
"@discordjs/rest/@discordjs/collection": ["@discordjs/collection@2.1.1", "", {}, "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg=="],
@@ -1031,29 +806,15 @@
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
"@typescript-eslint/typescript-estree/tinyglobby": ["tinyglobby@0.2.16", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg=="],
"ajv-formats/ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
"ejclaw-agent-runner/@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
"ejclaw-agent-runner/cron-parser": ["cron-parser@5.5.0", "", { "dependencies": { "luxon": "^3.7.1" } }, "sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww=="],
"mdast-util-find-and-replace/escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
"parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
"pino-pretty/pino-abstract-transport": ["pino-abstract-transport@3.0.0", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg=="],
"rc/strip-json-comments": ["strip-json-comments@2.0.1", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
"rolldown/@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
"vite/picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],
"vite/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"vitest/picomatch": ["picomatch@4.0.4", "", {}, "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A=="],
"vitest/tinyglobby": ["tinyglobby@0.2.16", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg=="],
"vite/tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
"@discordjs/ws/@discordjs/rest/@sapphire/snowflake": ["@sapphire/snowflake@3.5.3", "", {}, "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ=="],
@@ -1061,12 +822,6 @@
"@modelcontextprotocol/sdk/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"@typescript-eslint/typescript-estree/tinyglobby/picomatch": ["picomatch@4.0.4", "", {}, "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A=="],
"ajv-formats/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"ejclaw-agent-runner/@modelcontextprotocol/sdk/ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
"ejclaw-agent-runner/@modelcontextprotocol/sdk/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
}
}

View File

@@ -3,12 +3,11 @@
# codex_relogin.sh — Codex(ChatGPT) 계정을 device-code OAuth 로 재로그인한다.
#
# 사용법:
# ./codex_relogin.sh # 기본 슬롯(0) 재로그인
# ./codex_relogin.sh 1 # ~/.codex-accounts/1 슬롯 재로그인
# ./codex_relogin.sh
#
# 참고:
# * Codex 로그인은 이 호스트에서 두 봇(EJClaw / KAClaw)이 "공유"한다.
# 계정 저장 위치가 폴더별이 아니라 ~/.codex-accounts/{n} 이기 때문.
# 계정 저장 위치가 폴더별이 아니라 ~/.codex-accounts/0 이기 때문.
# → 한 번만 재로그인하면 두 봇 모두에 반영된다.
# * codex CLI 가 URL + 일회용 코드를 출력한다(15분 유효). 브라우저에서
# 로그인/코드입력을 마치면 codex 가 auth.json 을 자동 저장한다.
@@ -31,18 +30,11 @@ if [ -z "$CODEX" ]; then
exit 1
fi
# --- 대상 슬롯 결정 --------------------------------------------------------
# 앱은 ~/.codex-accounts/{n}/auth.json 를 읽는다. 없으면 ~/.codex 로 폴백.
SLOT="${1:-0}"
ACCOUNTS_DIR="$HOME/.codex-accounts"
if [ -d "$ACCOUNTS_DIR/$SLOT" ]; then
CODEX_TARGET="$ACCOUNTS_DIR/$SLOT"
elif [ -d "$ACCOUNTS_DIR" ] && ls -d "$ACCOUNTS_DIR"/[0-9]* >/dev/null 2>&1; then
echo "❌ 슬롯 '$SLOT' 이(가) 없습니다. 사용 가능한 슬롯:" >&2
ls -d "$ACCOUNTS_DIR"/[0-9]* 2>/dev/null | sed 's#.*/# - #' >&2
exit 1
# --- 대상 위치 결정 --------------------------------------------------------
# 앱은 ~/.codex-accounts/0/auth.json 를 읽는다. 없으면 ~/.codex 로 폴백.
if [ -d "$HOME/.codex-accounts/0" ]; then
CODEX_TARGET="$HOME/.codex-accounts/0"
else
# accounts 디렉터리가 비어있으면 기본 codex home 사용
CODEX_TARGET="$HOME/.codex"
fi
export CODEX_HOME="$CODEX_TARGET"

View File

@@ -1,94 +0,0 @@
# Android / Meta Ray-Ban Display Plan
## Goal
Build a personal Android companion for EJClaw that reuses the existing server and dashboard APIs, then extend it to Meta Ray-Ban Display through the Meta Wearables Device Access Toolkit (DAT) when the device developer preview is available to the account.
## Current Platform Facts
- EJClaw is a Bun/Node host service. Android should be a thin client, not a port of the runtime.
- Meta DAT is in developer preview and provides Android SDK artifacts and sample app guidance through the public `facebook/meta-wearables-dat-android` repo.
- DAT preview allows SDK/documentation access and sharing builds with organization/team testers; general public publishing is limited during preview.
- Ray-Ban Display currently has two developer paths: Web Apps Dev Mode for HTML/CSS/JS standalone display apps, and DAT Display Developer Preview for extending Android/iOS apps onto the display.
Sources:
- https://developers.meta.com/blog/introducing-meta-wearables-device-access-toolkit/
- https://github.com/facebook/meta-wearables-dat-android
- https://www.levinriegner.com/news/l-r-joins-meta-to-open-ray-ban-display-to-developers/
## MVP Shape
1. Keep EJClaw running on the existing server.
2. Expose the web dashboard only through localhost, VPN, or a private tunnel.
3. Require `WEB_DASHBOARD_TOKEN` for `/api/*` before phone clients connect.
4. Build an Android app that talks to the existing dashboard API:
- `GET /api/overview`
- `GET /api/rooms-timeline`
- `GET /api/rooms/:jid/timeline`
- `POST /api/rooms/:jid/messages`
5. Add DAT only for the display surface:
- short current-room status
- latest assistant output
- progress text
- quick reply / send command entry
## Security Model
Do not expose EJClaw directly to the internet without a private transport.
Recommended personal setup:
- `WEB_DASHBOARD_HOST=127.0.0.1` for local-only use, or bind through Tailscale / VPN / SSH tunnel.
- Set `WEB_DASHBOARD_TOKEN` and send it from Android as `Authorization: Bearer <token>`.
- Keep restart/settings/account routes available only over the same protected API; do not add unauthenticated mobile-only shortcuts.
## Android App Plan
Use Kotlin for the first native client. The app can be small:
- `EJClawApi`: HTTP client with bearer token.
- `RoomListViewModel`: fetches `/api/rooms-timeline` on interval.
- `RoomThreadViewModel`: fetches room timeline and sends messages.
- `DisplayBridge`: DAT integration boundary, initially hidden behind an interface so the app can run without glasses.
The first build does not need DAT to validate EJClaw connectivity. DAT comes after the phone client can read rooms and send one message.
## DAT Integration Boundary
Keep Meta SDK code isolated under an Android module/package such as:
```text
apps/android/app/src/main/java/.../display/
```
Suggested interfaces:
```kotlin
interface DisplaySurface {
fun showStatus(roomName: String, state: String, progress: String?)
fun showMessage(roomName: String, text: String)
}
class NoopDisplaySurface : DisplaySurface { ... }
class MetaDatDisplaySurface : DisplaySurface { ... }
```
This avoids blocking normal phone testing when DAT access, glasses firmware, region support, or Developer Mode is not ready.
## Open Questions
- Is the Meta Wearables Developer Center account approved for DAT Display Developer Preview?
- Is the target phone able to pair with Ray-Ban Display in the current region/account setup?
- Should first Android build be native Kotlin UI or a minimal WebView wrapper around the existing dashboard?
- Which private transport will be used: Tailscale, SSH tunnel, Cloudflare Tunnel with access policy, or LAN only?
## Next Step
Implement the Android MVP only after the API token guard is merged and deployed. The initial Android client should prove:
1. Authenticate to EJClaw.
2. List rooms.
3. Open one room timeline.
4. Send one message.
5. Run without DAT using `NoopDisplaySurface`.

View File

@@ -24,13 +24,12 @@ EJClaw는 단일 `ejclaw` 서비스가 세 Discord 봇과 paired runtime을 함
| `paired_projects` | canonical project root (`canonical_work_dir`) |
| `paired_tasks` | paired runtime의 상태 머신 |
| `paired_workspaces` | owner / reviewer의 실제 실행 workspace 경로 |
| `registered_groups` | compatibility / materialized read-model 성격의 잔존 레이어 |
현재 기준에서 중요한 점:
- room 설정의 기준은 `room_settings`
- reviewer / arbiter는 room의 공개 진입점이 아니라 내부 역할
- `registered_groups`는 제거 진행 대상이지만 아직 완전히 사라진 것은 아님
- `registered_groups` 테이블은 제거됨(구버전 DB 이전 시 `setup/legacy-room-registrations.ts`가 입력으로만 읽음)
## 실행 흐름
@@ -46,11 +45,6 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
│ └─ BLOCKED → arbiter / user
│
├──► Arbiter (on-demand)
│ │
│ ┌───┴─── MoA ───┐
│ │ Kimi / GLM │
│ │ 의견 수집 │
│ └───────────────┘
│
IPC polling / host tools
│
@@ -59,13 +53,18 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
paired_turn_outputs Discord display
```
## 방 격리와 작업 중단
- 모든 방은 동등합니다. main(관리) 방 개념은 없으며, 각 방의 에이전트가 IPC로 할 수 있는 일(메시지 전송·inbound 주입, 예약 작업 생성/수정/일시정지/취소, DB·호스트 증거 조회)은 자기 방(같은 group folder)으로만 제한됩니다. 방 등록/변경은 호스트 셸(`setup --step register`, `scripts/deregister-room.ts`)에서 합니다.
- 사람이 "그만"·"멈춰"·"stop" 같은 중단 의도만 담긴 짧은 메시지를 보내면 메시지 루프(`src/message-runtime-dispatch.ts` → `src/room-stop.ts`)가 가로채, 커서를 그 메시지까지 넘기고 열린 paired task를 `user_stopped`로 닫은 뒤 `GroupQueue.closeStdin`(사유 `user-stop`) + `killProcess`로 실행 중인 에이전트를 끝냅니다. 판정 규칙은 `src/stop-intent.ts`에 있습니다.
## Tribunal 역할 분리
| 역할 | 기본 선택 | 설명 |
| --- | --- | --- |
| owner | room별 `owner_agent_type` (기본 Codex) | 사용자 요청 처리, 코드 작성, 최종 응답 |
| reviewer | 전역 `REVIEWER_AGENT_TYPE` (기본 Claude Code) | owner 결과 검토, 회귀 검증 |
| arbiter | 전역 `ARBITER_AGENT_TYPE` (옵션) | owner / reviewer 교착 시 판정 |
| reviewer | 전역 `REVIEWER_AGENT_TYPE` (기본 Claude Code), room별 `reviewer_agent_type` override | owner 결과 검토, 회귀 검증 |
| arbiter | 전역 `ARBITER_AGENT_TYPE` (옵션), room별 `arbiter_agent_type` override | owner / reviewer 교착 시 판정 |
역할별 model / effort는 전역 env(`OWNER_*`, `REVIEWER_*`, `ARBITER_*`)로 정하고, room-level `agentConfig`는 provider별(`claudeModel`, `codexModel`) override만 제공합니다.
@@ -98,8 +97,9 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
- test
- build
- reviewer / arbiter가 직접 로컬 빌드를 못 돌려도, host verification 경로로 `typecheck`, `test`, `build`를 수행할 수 있음
- startup precondition은 전용 오류로 올리고, `RestartPreventExitStatus=78`로 crash loop를 막음
- startup precondition은 전용 오류로 올리고, setup이 생성하는 유닛은 `RestartPreventExitStatus=78`로 crash loop를 막음(현재 운영 호스트의 `ejclaw.service`는 수동 작성 유닛으로 `bun src/index.ts`를 실행하며 이 줄이 없고, 로그는 journald로 감)
- deploy는 `migrate-room-registrations`를 선행한 뒤 service restart를 수행
- DB 스키마: 과거 마이그레이션 1~22는 `src/db/base-schema.ts`(기준 버전 22) 하나로 합쳐짐. 새 DB는 이 스키마로 만들고, 기존 DB는 `schema_migrations` 최대 버전이 22 이상이어야 열림(그보다 오래된 DB는 시작 시 거부). 스키마 변경은 `src/db/migrations/index.ts`에 23번부터 마이그레이션을 추가하고 `src/db/schema.snapshot.sql`을 갱신
## 주요 파일
@@ -107,6 +107,7 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
| --- | --- |
| `src/index.ts` | 전체 오케스트레이션 진입점 |
| `src/message-runtime.ts` | 메시지 루프, paired flow 연결 |
| `src/room-stop.ts`, `src/stop-intent.ts` | 자연어 작업 중단 |
| `src/message-turn-controller.ts` | progress / final delivery 제어 |
| `src/paired-execution-context.ts` | owner / reviewer / arbiter 실행 준비 |
| `src/paired-workspace-manager.ts` | owner / reviewer workspace 관리 |

View File

@@ -9,7 +9,7 @@ EJClaw의 설정 기준은 `.env` 하나입니다.
- reviewer 기본 provider는 `claude-code`
- owner 기본 provider는 `codex`
- room-level override는 provider 단위(`claudeModel`, `codexModel`)만 지원합니다
- `CLAUDE_CODE_OAUTH_TOKENS`가 canonical이고, `CLAUDE_CODE_OAUTH_TOKEN`은 legacy fallback입니다
- Claude와 Codex는 각각 계정 1개로 동작합니다 (계정 로테이션 없음)
## Discord 봇
@@ -31,7 +31,7 @@ ARBITER_AGENT_TYPE=codex
# provider 기본 모델
# 공식 Claude API 모델 ID입니다.
CLAUDE_MODEL=claude-opus-4-8
CLAUDE_MODEL=claude-opus-5-5
CLAUDE_EFFORT=high
CLAUDE_THINKING=adaptive
CODEX_MODEL=gpt-5.5
@@ -40,23 +40,20 @@ CODEX_EFFORT=xhigh
# 역할별 override
OWNER_MODEL=gpt-5.5
OWNER_EFFORT=xhigh
OWNER_FALLBACK_ENABLED=true
REVIEWER_MODEL=claude-opus-4-8
REVIEWER_MODEL=claude-opus-5-5
REVIEWER_EFFORT=high
REVIEWER_FALLBACK_ENABLED=true
ARBITER_MODEL=gpt-5.5
ARBITER_EFFORT=xhigh
ARBITER_FALLBACK_ENABLED=true
```
설명:
- reviewer / arbiter provider 선택은 **전역 설정**
- reviewer / arbiter provider는 전역 `REVIEWER_AGENT_TYPE` / `ARBITER_AGENT_TYPE`이 기본값이고, 방마다 `src/db.ts`의 `assignRoom(jid, { name, reviewerAgentType, arbiterAgentType })`를 관리 셸에서 호출해 덮어쓸 수 있습니다 (에이전트용 `assign_room` 도구는 제거됨)
- 역할별 `*_MODEL`은 해당 역할의 provider에 맞춰 주입됩니다. `codex` 역할에는 Codex 모델을, `claude-code` 역할에는 Claude 모델을 넣어야 합니다.
- 예를 들어 `ARBITER_AGENT_TYPE=claude-code`로 바꾸면 그때 `ARBITER_MODEL=claude-opus-4-8`을 사용할 수 있습니다.
- 특정 방에서만 reviewer를 Codex로 고르는 기능은 없음
- 예를 들어 `ARBITER_AGENT_TYPE=claude-code`로 바꾸면 그때 `ARBITER_MODEL=claude-opus-5-5`를 사용할 수 있습니다.
- 모델 ID는 추측하지 말고 `GET https://api.anthropic.com/v1/models`로 확인하세요(`claude-opus-5-0` 같은 표기는 존재하지 않음). 새 모델은 더 높은 Claude Code CLI 버전을 요구할 수 있으므로(예: Opus 5.5는 CLI 2.1.280 이상), `.env`를 바꾸기 전에 runner SDK로 실제 호출해 보고 적용하세요. Opus/Sonnet 5.x는 `CLAUDE_THINKING=adaptive`만 지원합니다.
- room-level `agentConfig`의 `claudeModel`, `codexModel`은 역할별이 아니라 provider별 override
- `ARBITER_AGENT_TYPE`은 옵션이며, 설정하지 않으면 arbiter는 비활성 상태입니다
@@ -64,8 +61,8 @@ ARBITER_FALLBACK_ENABLED=true
```bash
# Claude Code OAuth
CLAUDE_CODE_OAUTH_TOKENS=
CLAUDE_CODE_OAUTH_TOKEN=
CLAUDE_CREDENTIALS_PATH=
# Claude host env (선택)
ANTHROPIC_API_KEY=
@@ -75,11 +72,11 @@ ANTHROPIC_BASE_URL=
설명:
- `CLAUDE_CODE_OAUTH_TOKENS`: canonical, 쉼표 구분
- `CLAUDE_CODE_OAUTH_TOKEN`: 단일 토큰 legacy fallback
- 실제 runner에는 현재 선택된 Claude 토큰 하나만 주입됩니다
- `CLAUDE_CODE_OAUTH_TOKEN`: runner에 주입하는 Claude 토큰. 예전 `CLAUDE_CODE_OAUTH_TOKENS`(쉼표 구분)가 남아 있으면 첫 번째 값만 씁니다
- `CLAUDE_CREDENTIALS_PATH`: 이 서비스의 Claude OAuth credentials 파일. `CLAUDE_TOKEN_REFRESH_USE_CREDENTIALS=true`면 만료 전에 자동 갱신하고 새 토큰을 `.env`에도 기록합니다
- Claude가 사용 한도에 도달하면 다른 provider로 넘기지 않고 그 방의 작업을 일시정지합니다. 방에 `Claude 사용 한도에 도달해서 이 방의 작업을 일시정지했습니다. 21:40에 사용량이 초기화되면 자동으로 이어서 진행합니다.`처럼 재개 시각을 보내고, paired task와 처리하던 메시지는 그대로 둡니다. 한도가 남아 있는 동안 다른 방의 Claude turn도 실행하지 않고 일시정지합니다. 초기화 시각 1분 뒤 스케줄러가 방들을 다시 큐에 넣어 같은 turn을 이어서 실행합니다. 재개 시각을 모르면 10분 뒤에 다시 시도합니다. 일시정지 상태는 `router_state.claude_usage_pause`에 저장되어 재시작 후에도 유지되며, 일시정지 중 "중단"을 보내면 그 방은 재개하지 않습니다
Codex 쪽은 현재 **OAuth 세션 파일** 기준으로 동작합니다. `OPENAI_API_KEY`를 Codex child process에 넘겨서 빌링하는 구조는 사용하지 않습니다.
Codex 쪽은 **OAuth 세션 파일** 기준으로 동작합니다. `~/.codex-accounts/0/auth.json`을 쓰고, 없으면 `~/.codex/auth.json`을 씁니다. Codex 실행은 계정 잠금으로 한 번에 하나만 돌고, 잠겨 있으면 최대 15분 기다립니다. `OPENAI_API_KEY`를 Codex child process에 넘겨서 빌링하는 구조는 사용하지 않습니다.
## 음성 전사
@@ -87,37 +84,14 @@ Codex 쪽은 현재 **OAuth 세션 파일** 기준으로 동작합니다. `OPENA
GROQ_API_KEY=
```
- 기본은 Groq Whisper
- 필요 시 OpenAI Whisper fallback을 별도 확장할 수 있지만, 현재 README / 문서 기준 최소 키는 `GROQ_API_KEY`입니다
## MoA
```bash
MOA_ENABLED=true
MOA_REF_MODELS=kimi,glm
MOA_KIMI_MODEL=kimi-k2.6
MOA_KIMI_BASE_URL=https://api.kimi.com/coding
MOA_KIMI_API_KEY=sk-kimi-xxx
MOA_KIMI_API_FORMAT=anthropic
MOA_GLM_MODEL=glm-5.1
MOA_GLM_BASE_URL=https://open.bigmodel.cn/api/anthropic
MOA_GLM_API_KEY=xxx
MOA_GLM_API_FORMAT=anthropic
```
MoA는 arbiter 판정 전에 외부 모델 의견을 수집해 prompt에 주입합니다.
대시보드 설정 화면에서 `MOA_ENABLED`, `MOA_REF_MODELS`, 모델명, base URL,
API format, API key 교체와 연결 테스트를 관리할 수 있습니다. 저장 후에는
스택 재시작이 필요합니다.
- 기본은 Groq Whisper(`whisper-large-v3-turbo`)
- `GROQ_API_KEY`가 없고 `OPENAI_API_KEY`가 있으면 OpenAI Whisper(`whisper-1`)로 자동 대체됩니다(`src/channels/discord.ts`)
## 운영 / 배포 관련 설정
```bash
ASSISTANT_NAME=claude
STATUS_CHANNEL_ID=
SESSION_COMMAND_ALLOWED_SENDERS=
MAX_CONCURRENT_AGENTS=5
```
@@ -128,13 +102,15 @@ EJCLAW_ATTACHMENT_ALLOWED_DIRS=~/Pictures/Screenshots,~/Downloads/ejclaw-images
```
- 콤마 또는 플랫폼 path delimiter(Linux는 `:`)로 여러 폴더를 지정합니다.
- 지정한 폴더 하위의 PNG/JPEG/GIF/WebP/BMP만 Discord 첨부 후보가 됩니다.
- 기본 허용 폴더는 `data/attachments`와 Codex `generated_images`이며, 이 설정은 그 외 폴더를 추가합니다.
- 첨부 가능 형식: PNG/JPEG/GIF/WebP/BMP, MP4/MOV/WebM, MP3/WAV/OGG/M4A/FLAC, PDF, ZIP, TXT/Markdown/CSV/JSON (SVG 불가). 파일당 최대 8MB.
- `realpath`, 이미지 signature, size cap 검증은 그대로 적용됩니다.
- `/home/**` 전체보다 자주 쓰는 스크린샷/이미지 출력 폴더만 추가하는 것을 권장합니다.
- `ASSISTANT_NAME`은 owner trigger 기본 이름을 만듭니다
- paired room에서도 사용자 진입점은 owner가 기준입니다
- status dashboard와 session command는 선택 설정입니다
- status dashboard는 선택 설정입니다
- `/compact`·`/clear`·`/stop` 세션 명령과 `SESSION_COMMAND_ALLOWED_SENDERS`는 제거됐습니다. 남아 있는 값은 무시됩니다. 작업 중단은 방에 "그만"·"멈춰"·"stop" 같은 짧은 메시지를 보내면 됩니다(README "작업 중단" 참고)
## 디버깅 경로

View File

@@ -1,6 +1,6 @@
# EJClaw 레거시 호환 제거 및 구조 정리 Spec
- 상태: Draft
- 상태: 구현 완료 · 이력 참고용 (주요 결정은 921c241 "finish legacy room cleanup"에서 반영: `registered_groups` 테이블 제거, 구 env 별칭은 시작 시 오류로 거부)
- 대상: 코어 개발자 / 리팩토링 담당자
- 기준일: 2026-04-09
- 기준: 저장소 정적 분석 결과

250
docs/slimming-plan.md Normal file
View File

@@ -0,0 +1,250 @@
# EJClaw 경량화·최적화 계획 (v3 — 사용자 결정 반영 완료)
- 최초 조사: 2026-10-01 (기준 커밋 af28bae), 결정 반영: 2026-10-01 16시, 최종 결정: 2026-10-01 16시 30분
- 번호는 첫 조사 문서와 같다. 빠진 번호는 "제외"로 표시했다.
- 상태 표기
- **확정**: 결정이 끝나 바로 진행
- **추천**: 결정은 필요 없지만, 진행하겠다고 확인만 받으면 됨
- **결정 필요**: 아래 설명을 보고 골라 주셔야 함
- **제외**: 하지 않음
## 0. 한눈에 보기
| 번호 | 내용 | 상태 |
|---|---|---|
| 1 | 중재자가 판정 규칙을 못 받는 버그 수정 | 확정 (버그) |
| 2 | 리뷰어가 owner 규칙을 받는 버그 수정 | 확정 (버그) |
| 3 | 사용자에게 묻는 경우(NEEDS_CONTEXT) 중재 없이 바로 전달 | 확정 (버그) |
| 4·17 | Claude 한도 소진 시 답변이 사라지는 failover 경로 제거 | 확정 (버그) |
| 5 | Codex 사용량 조회가 구버전·잠금 없이 실행되는 문제 | 확정 (버그) |
| 6 | owner 세션을 작업 단위로 새로 시작 | 추천 (효과 가장 큼) |
| 7 | 공용 메모리 다이어트 | 추천 |
| 8 | owner가 "리뷰 필요 없음"을 스스로 표시하면 리뷰 생략 (시스템이 변경 여부를 다시 확인) | 확정 (사용자 제안 방식, 아래 설계) |
| 9 | 리뷰 효과 낮은 방을 single로 | 제외 (요청 시에만 전환) |
| 10 | 마무리 턴 비용 줄이기 | 확정 (C안) |
| 11~15 | 폴링·로그·IPC 정리 | 추천 |
| 16 | 웹 대시보드·Android·Glasses 전부 삭제 | 확정 |
| 18~21, 23, 24, 29 | 안 쓰는 기능·죽은 코드·의존성 삭제 | 추천 |
| 22 | `/stop` 등 명령어 → 대화 중 "그만해"로 중단 | 확정 (새 기능으로 교체) |
| 25 | DB 마이그레이션 정리 | 추천 (백업 후) |
| 26 | 서비스 ID 단일화 | 보류 (위험 높음) |
| 27 | main 방 개념과 방 간 관리 기능 삭제 | 확정 ((다)안) |
| 28 | 계정 로테이션 단순화 (계정 1개 고정) | 확정 |
| 30~35 | 디스크 정리 약 3.3GB | 추천 |
| 36 | 런처 이전 버전 설치 파일 삭제 약 10.5GB | 확정 |
---
## 결정한 3가지 — 설명 (8번은 아래 B절의 확정 설계 참고)
### 8. "리뷰 생략"이 뭔가요?
지금은 어떤 질문이든 이렇게 3번 돌아갑니다.
1. Claude(owner)가 답을 만든다
2. Codex(리뷰어)가 그 답을 검토한다 (평균 1분 30초)
3. Claude가 최종 정리를 한다 (평균 20초)
그런데 "이 채널 왜 답 안 해?", "main 방 역할이 뭐야?"처럼 **파일을 하나도 고치지 않고 설명만 하는 작업**이 전체의 약 44%입니다. "리뷰 생략"은 이런 경우에 2·3번을 건너뛰고 1번 답을 바로 보내는 것입니다.
| | 지금 | 리뷰 생략 시 |
|---|---|---|
| 코드를 고친 작업 | 3단계 그대로 | 3단계 그대로 (변화 없음) |
| 설명만 한 작업 | 3단계 (약 2분 더 걸림) | 1단계 (약 2분 빨라짐) |
| 잃는 것 | — | 설명 답변의 사실 오류를 리뷰어가 잡아줄 기회 |
- 참고: 오늘도 리뷰어가 설명형 답변에서 실수를 잡은 적이 있습니다(KAclaw 로그인 미확인 상태로 완료 처리하려던 것). 리뷰 품질을 중시하시면 **하지 않는 것**을 권합니다.
- 선택지: (가) 하지 않음 / (나) 설명만 한 작업은 리뷰 생략
### 10. 마무리 턴, 다른 해결책
마무리 턴이 생긴 이유(말씀하신 것): owner와 리뷰어가 서로 대화만 하고, 마지막에 "해결했어요"만 남기는 경우가 많아서 전체를 정리해 보여달라고 하신 것.
지금 문제: 마무리 턴이 **owner의 거대한 대화 세션 전체(수십만 토큰)를 다시 읽고** 정리합니다. 정리 자체는 몇 천 토큰이면 되는데, 매번 수십만 토큰을 씁니다(30일 178회).
| 안 | 방법 | 결과물 | 비용 |
|---|---|---|---|
| A | 리뷰어가 **수정 요청 없이 바로 승인**하면, owner의 첫 답변을 그대로 최종 답변으로 보냄 (owner 규칙상 첫 답변도 이미 "사용자용 완결 답변" 형식) | 수정 없이 끝난 작업은 그대로 / 수정이 있었던 작업만 마무리 턴 | 작업의 약 80%에서 마무리 턴 0회 |
| B | 마무리 턴은 유지하되, 거대한 세션 대신 **이번 작업의 owner·리뷰어 답변(최대 6개, 수천 토큰)만 넣은 가벼운 호출**로 정리 | 지금과 같은 정리 형식 | 마무리 1회당 수십만 → 수천 토큰 |
| C | A + B 함께: 바로 승인 → A, 수정 있었음 → B | 같음 | 가장 적음 |
- **결정: C안.** 보여지는 최종 답변 형식은 지금과 같고, 비용만 줄어듭니다.
- 참고: 6번(세션을 작업 단위로 새로 시작)을 하면 마무리 턴이 읽는 세션도 작아져서 B의 효과 일부가 자동으로 생깁니다.
### 27. main 방의 역할
main 방은 "관리자 방"입니다. 코드상 main 방만 할 수 있는 일은 다음과 같습니다.
| main 방만 가능한 것 | 근거 |
|---|---|
| 다른 방의 예약 작업 보기·취소·일시정지·새로 만들기 | `src/ipc-task-processor/tasks.ts`, `schedule.ts` |
| 채널 등록·설정 변경 도구(`assign_room`) | `src/ipc-task-processor/rooms.ts` |
| 다른 방으로 메시지 보내기 | `src/ipc-message-forwarding.ts` |
| 전체 방 목록, 모든 방의 DB 기록 조회 | `agent-runner-snapshot.ts`, `db-evidence.ts` |
| 트리거 없이 항상 응답, 세션 명령 허용 | `message-runtime-rules.ts`, `session-commands.ts` |
| (부작용) 공용 메모리를 받지 않음 | `agent-runner-environment.ts:671` |
현재 상황:
- main 방이 하나도 없어서 위 기능은 **모든 방에서 꺼져 있습니다.**
- 대신 base_all 방에서 셸 명령으로 같은 관리 작업(채널 등록, 다른 방 작업 중단, 서비스 재시작 등)을 해 왔습니다. 에이전트가 호스트 셸을 직접 쓸 수 있어서 main 권한이 사실상 필요 없었습니다.
| 선택지 | 내용 | 장점 | 단점 |
|---|---|---|---|
| (가) 지금처럼 둠 | main 없음, 관리는 base_all에서 셸로 | 변경 없음 | main 관련 코드 163곳이 쓸모없이 남음 |
| (나) base_all을 main으로 지정 | base_all에서 관리 도구를 정식으로 사용 | 다른 방 예약 작업 관리 등이 도구로 깔끔해짐 | base_all이 공용 메모리를 못 받게 됨(코드 수정 필요). 위험한 관리 도구가 한 방에 열림 |
| (다) main 개념과 방 간 기능 삭제 | 관련 코드 제거 | 코드 정리, 지금 실제 사용 방식 그대로 | 방 간 관리 도구는 영구히 없어짐(셸로는 계속 가능) |
- **결정: (다)안.** 지금도 쓰지 않고 있고, 셸로 다 하고 있기 때문입니다.
---
## A. 버그 수정 (확정)
### 1. 중재자가 판정 규칙을 받지 못함
- 근거: 규칙 파일을 읽는 코드가 꺼져 있는 경로(unsafe 모드, MoA)에서만 호출된다. 중재자 세션 폴더에 규칙 파일이 없다.
- 영향: 30일간 중재 23회 중 20회가 판정을 해석하지 못하고 사용자에게 그냥 넘어감.
- 수정: 일반 경로의 중재자 세션에 중재자 규칙을 넣는다.
### 2. Codex 리뷰어가 owner 규칙을 받음
- 근거: 실제 리뷰어 세션 `AGENTS.md`에 "You are the owner"가 들어 있다.
- 수정: 리뷰어 세션에는 리뷰어 규칙만 넣는다.
### 3. NEEDS_CONTEXT가 중재자를 거침
- 근거: 중재 23회 중 13회가 이 경우. 중재자 규칙상 항상 사용자에게 넘기는 경우다.
- 수정: 중재 없이 바로 사용자에게 보낸다. 중재 호출 -57% 이상.
### 4·17. 받을 곳 없는 Claude→Codex failover 제거
- 근거: Claude 한도 소진 시 이 배포에 없는 `codex-main`으로 작업을 넘긴다. 5월에 넘긴 2건이 아직 `pending`.
- 수정: 체인 제거(코드 약 -2천 줄), 한도 소진 시 "한도 소진, ○시 재개 예정"을 바로 보냄.
- 주의: DB 스키마와 엮여 있어 백업 후 진행.
### 5. Codex 사용량 조회
- 근거: 구버전 전역 Codex(0.128)를 계정 잠금 없이 실행 → 토큰 충돌 위험.
- 수정: 저장소에 고정된 0.159.3 사용 + 계정 잠금 + 주기 5~10분(12번과 함께).
## B. 토큰·속도
### 6. owner 세션을 작업 단위로 새로 시작 (추천, 효과 가장 큼)
- 근거: 방마다 한 세션을 몇 주씩 이어 써서 호출 1회에 중앙값 26만, 최대 100만 토큰을 읽는다. Claude 5시간 사용량 89%의 주원인.
- 수정: 새 작업이 시작되면 세션을 새로 연다. 직전 최종 답변은 이미 자동으로 넘겨주고 있어 맥락 손실이 작다.
- 효과: Claude 입력 토큰 -50~70% (추정).
### 7. 공용 메모리 다이어트 (추천)
- 근거: 모든 세션에 공용 메모리 약 1.1만 토큰이 들어간다. 세탁기 앱 배포, Windows CI, .5 docker, EJClaw 운영 절차 등 대부분 방과 무관한 내용.
- 수정: 공통 규칙만 남기고, 프로젝트·운영 내용은 해당 방 메모리나 "필요하면 이 문서를 읽어라" 링크로 옮긴다.
- 효과: 호출당 -7~8K 토큰.
### 8. 리뷰 필요 여부를 owner가 표시 (확정 — 사용자 제안 방식)
**가능 여부: 가능합니다.** owner 답변 뒤에 무엇을 할지 정하는 곳이 한 군데(`src/paired-completion-signals.ts`의 `resolveOwnerCompletionSignal`)라서, 여기에 "owner가 리뷰 불필요라고 표시했고, 안전 조건도 통과하면 바로 끝낸다"는 분기를 넣으면 됩니다.
동작 방식:
1. owner가 답을 만들 때, 정말 설명·조사만 했고 아무것도 바꾸지 않았으면 답변 끝에 `리뷰 불필요: (이유)` 한 줄을 붙인다. 애매하면 붙이지 않는다(기본값은 리뷰).
2. 시스템이 그 표시를 그대로 믿지 않고 다시 확인한다. 아래 중 **하나라도 해당하면 표시를 무시하고 평소처럼 리뷰**한다.
- 작업 폴더에 코드 변경이나 커밋이 있음 (이미 있는 `hasCodeChangesSinceRef`로 확인)
- 파일을 고치는 도구(Edit, Write 등)를 썼음
- 셸 명령 중에 무언가를 바꾸는 명령이 있었음: 삭제·이동, 서비스 재시작, 프로세스 종료, DB 쓰기, git 커밋·푸시, crontab 수정, 외부 API 쓰기 요청 등
3. 통과하면 리뷰어와 마무리 턴 없이 owner 답변이 바로 최종 답변이 된다. 답변 끝에 "검토 생략(변경 없는 설명형 답변)"을 작게 표시하고, 사용자가 "검토해줘"라고 하면 그때 리뷰를 돌린다.
왜 안전한가:
- 오늘 리뷰어가 실수를 잡은 경우(KAclaw 로그인 미확인 상태로 완료 처리)는 서비스 재시작·설정 변경이 있었던 작업이라 2번 조건에 걸려 **어차피 리뷰를 받습니다.**
- 이 방(base_all)의 최근 세션은 셸 명령 415개 중 77개가 변경 명령이었습니다. 운영 작업은 거의 항상 리뷰를 거치고, 순수 질문·설명만 리뷰를 건너뜁니다.
남는 한계: owner가 설명 내용 자체를 틀리게 말하는 경우(변경 없이 잘못된 정보만 준 경우)는 리뷰어가 못 잡습니다. 그래서 owner가 확신이 없거나 사실 확인이 중요한 답이면 표시하지 않도록 규칙에 넣습니다.
예상 효과: 30일 기준 단순 질답 83건 중 상당수에서 리뷰어(평균 1분 30초)와 마무리 턴(20초)이 빠짐.
### 9. single 전환 — 제외 (요청하신 방만 전환)
### 10. 마무리 턴 — C안 확정 (위 표의 C: 바로 승인이면 owner 답변 그대로, 수정이 있었으면 가벼운 정리 호출)
- 리뷰어 effort를 xhigh → high로 낮추는 것은 별도로 추천(리뷰 평균 97초 단축 예상).
## C. 실행 자원 (추천)
| 번호 | 내용 | 효과 |
|---|---|---|
| 11 | 대시보드 중복 정리: 2초마다 Discord 메시지 100개 조회 → 시작 시 1회 + 5분 주기 | Discord 호출 하루 4.3만 건 → 수백 건 |
| 12 | Codex 사용량 조회: 1분마다 프로세스 생성 → 5~10분 + 리뷰 직후 | 프로세스 생성 -80~90% |
| 13 | Claude 사용량 조회: 1분 → 5분 | 호출 -80%, 429 오류 거의 0 |
| 14 | 로그 한 줄 출력 + 반복 로그 4종 debug로 | 로그 줄 수 -90% |
| 15 | IPC 고아 폴더 7개 삭제 | 1초 폴링 부담 -20% |
## D. 코드 덜어내기
| 번호 | 내용 | 줄어드는 코드 | 상태 |
|---|---|---|---|
| 16 | 웹 대시보드·Android 앱·Glasses·관련 설정/스크립트·의존성(react, vite, playwright 등) | 약 -2.4만 줄 (+테스트 -5.8천) | 확정 |
| 18 | MoA + Kimi 사용량 | 약 -600 | 추천 |
| 19 | auto-paired-mode | 약 -370 | 추천 |
| 20 | 참조 0인 코드 28개 + 고아 파일 3개 | 약 -500 | 추천 |
| 21 | 엉뚱한 계정을 갱신하는 6시간 Codex 갱신 루프 | 약 -150 | 추천 |
| 22 | `/compact`·`/clear`·`/stop` 명령 삭제 → 아래 새 기능으로 교체 | 약 -280 (+테스트 -324) | 확정 |
| 23 | macOS·launchd·nohup 설치 경로, repo-tokens | 약 -150 | 추천 |
| 24 | 쓰지 않는 의존성, 루트 dist 빌드 | — | 추천 |
| 25 | DB 마이그레이션 정리 | 약 -4천 | 추천 (백업 후) |
| 26 | 서비스 ID 단일화 | 약 -1천 | 보류 (위험 높음) |
| 27 | main 방 개념과 방 간 관리 기능 | 163곳 정리 | 확정 ((다)안) |
| 28 | 계정 로테이션을 계정 1개 기준으로 단순화 (Codex 잠금은 유지) | 약 -400~600 | 확정 |
| 29 | Codex warmup 설정을 primer로 합침 | 약 -200 | 추천 |
- 전부 진행하면 운영 코드 약 7.6만 줄 중 약 3만 줄(약 40%) 감소.
### 22번 새 기능: 대화 중 "그만해"로 작업 중단 (확정)
| 항목 | 설계 |
|---|---|
| 언제 멈추나 | 방에서 작업이 돌고 있을 때 사용자가 중단 의사만 담긴 짧은 메시지를 보내면 |
| 멈추는 말 | "그만", "그만해", "멈춰", "중단", "하지마", "하지 마", "취소", "스톱", "stop" 등 |
| 멈추지 않는 경우 | "그거 하지 말고 이걸 해줘"처럼 **다른 지시가 함께 있는 메시지**는 방향 수정으로 보고 평소처럼 처리 |
| 멈출 때 하는 일 | ① 그 방에서 돌던 owner·리뷰어·중재자 실행 종료 ② 진행 중이던 작업 종료 처리 ③ 대기 중이던 메시지까지 처리 완료로 표시(지난번 pdf 방처럼 저절로 다시 시작되는 것 방지) ④ "진행 중이던 작업을 중단했습니다"라고 답장 |
| 다시 시작 | 다음에 보내는 메시지부터 평소처럼 새 작업으로 처리 |
| 오작동 방지 | 짧은 메시지만 대상, 판단이 애매하면 멈추지 않고 평소처럼 처리 |
## E. 디스크 정리
| 번호 | 대상 | 크기 | 상태 |
|---|---|---|---|
| 30 | DB 백업 23개 중 최근 3개만 남김 | 약 555MB | 추천 |
| 31 | Codex 임시 플러그인 복제본 등 | 약 1.2GB | 추천 |
| 32 | 세션별 Codex 로그 DB | 약 536MB | 추천 |
| 33 | 등록 안 된 방의 폴더 | 약 560MB | 추천 |
| 34 | 리뷰용 임시 폴더 | 약 208MB | 추천 |
| 35 | 30일 지난 작업 첨부 | 일부 | 추천 |
| 36 | 음악퀴즈 런처 `release` 폴더의 이전 버전 설치 파일 0.4.9~0.4.30 (6종 × 22버전). 최신 1.0.0 설치 파일 6개(474MB)와 `win-unpacked`는 남김 | 약 10.5GB | 확정 |
| 36-참고 | unifi-site 작업공간의 `.venv` 7.7GB | — | 남김 (이전 버전이 아니라 지금 쓰는 개발 환경. 실제 사이트는 `/home/claude/unifi-site/.venv`를 씀. 지우길 원하시면 말씀해 주세요, 다시 만들 수 있음) |
- 30·31·32·35는 주기적으로 정리하는 cron도 함께 추가(추천).
## F. 유지
| 대상 | 이유 |
|---|---|
| Tribunal(owner·리뷰어·중재자) 구조, 방별 모드 | 사용자 결정. 리뷰가 결과를 바꾼 비율 13~16% |
| Discord 상태 대시보드 | 사용량 확인용으로 실제 사용 중 (웹 대시보드와 별개) |
| usage primer, evidence·verification 도구, 재시작 복구 등 안전장치 | 실제 동작 기록 있음 |
| DB 보존 정책 | 37MB, 증가 완만. 당장 불필요 |
## G. 진행 순서 (제안)
| 단계 | 번호 | 내용 |
|---|---|---|
| 1단계 | 1, 2, 3, 5, 11~15 | 버그 수정 + 폴링·로그 정리 (작은 수정, 바로 효과) |
| 2단계 | 16, 18~21, 22, 23, 24, 27, 28, 29 | 삭제·단순화 일괄(main 방 포함) + "그만해" 중단 기능 |
| 3단계 | 6, 7, 8, 10 | 토큰 절감 (세션 교체, 공용 메모리, 리뷰 필요 여부 표시, 마무리 턴 C안) |
| 4단계 | 4·17, 25 | DB와 엮인 구조 정리 (백업 후) |
| 5단계 | 30~36 | 디스크 정리 + 주기 정리 cron |
| 보류 | 26 | 서비스 ID 단일화 |
## H. 결정 현황
모든 결정이 끝났다.
| 번호 | 결정 |
|---|---|
| 8 | owner가 리뷰 필요 여부 표시 + 시스템 재확인 (사용자 제안) |
| 10 | C안 |
| 27 | (다)안: main 방 개념 삭제 |
| 16 | 웹 대시보드·Android·Glasses 전부 삭제 |
| 22 | 명령어 대신 대화 중 "그만해"로 중단 |
| 28 | 계정 1개 기준으로 단순화 |
| 36 | 런처 이전 버전 삭제 |
| 9 | single 전환 안 함 (요청 시에만) |

View File

@@ -7,7 +7,6 @@ export default tseslint.config(
ignores: [
'dist/**',
'node_modules/**',
'apps/dashboard/dist/**',
'runners/*/dist/**',
'runners/*/node_modules/**',
'store/**',

View File

@@ -1,166 +1,38 @@
# Global Memory
This file is for mutable memory shared across Claude groups.
Shared, mutable memory for every room. Keep it short: only rules every room needs.
Detailed notes live in `/home/claude/EJClaw/groups/global/ops/` — read the matching file when a task touches that topic:
Use it for durable facts, preferences, and shared context that may change over time.
- `ops/host.md` — GPU (RTX 5050, `/home/claude/gpu-venv`, NVML mismatch fix), tmpfs/RAM rules and watchdogs, Windows CI VM on .9 (nested KVM, resource caps), .5 Docker host and `docker5` context
- `ops/credentials.md` — what is in `secrets.json`, git.tkrmagid.kr credential helper, Claude/Codex per-service credentials and re-login runbooks
- `ops/ejclaw-ops.md` — room mode policy, channel register/deregister, safe restarts, model upgrade checklist, current versions, recent EJClaw fixes
- `ops/projects.md` — javis_bot deployment target, washing_machine_app release process
Do not store platform-wide operating rules here. Those now live in `prompts/claude-platform.md`.
## User preferences
## Host hardware (GPU)
- Answer the user in Korean 존댓말 unless asked otherwise.
- GPU: ask before running GPU workloads, except for the `javis_bot` project (pre-approved).
This host has an NVIDIA GPU available for compute:
- GPU: NVIDIA GeForce RTX 5050 (GB207, Blackwell), 8GB VRAM, compute capability 12.0 (sm_120)
- Driver 595.71.05, CUDA runtime 13.2; `libcuda.so` present so GPU compute is usable
- Ready-to-use PyTorch (CUDA 12.8 / Blackwell-capable) venv at `/home/claude/gpu-venv` — run with `/home/claude/gpu-venv/bin/python`. `torch.cuda.is_available()` is True.
- For CUDA C compilation, `nvcc` is not installed; install the CUDA Toolkit only if a task needs it.
## Host safety (always)
Behavioral rule: when a task could meaningfully benefit from the GPU (ML inference/training, heavy parallel compute, large media processing), first ask the user whether they want to use the GPU before doing so. Do not silently run GPU workloads. Once confirmed, use the `/home/claude/gpu-venv` Python (or install what the task needs) and verify with a real GPU run.
- `/tmp` and `/dev/shm` are RAM (tmpfs). Never put venvs, models, datasets or other large files there; use disk paths under `$HOME` (`TMPDIR=$HOME/.tmp`).
- Heavy jobs (GPU, VMs, big builds) must not run inside the bot's cgroup: launch them with `systemd-run --user --scope -p MemoryMax=... ...`.
- Never run a plain `systemctl --user restart ejclaw.service` inside a turn (it kills you). Room binding changes use SIGHUP; code/env changes use the detached `systemd-run` restart. Verify before claiming success. Details: `ops/ejclaw-ops.md`.
- 2026-06-18 exception (javis_bot project): the user pre-approved GPU use for the `javis_bot` project — do NOT ask before using the GPU on javis_bot tasks. Other projects still follow the ask-first rule above.
## Sending files
## javis_bot deployment target
Only files under `/home/claude/EJClaw/data/attachments` can be attached. Copy the file there (prefer `data/attachments/generated/`, auto-deleted after 60 min) and reference it with a `MEDIA:` line. Do not widen the allowlist.
- 2026-06-18: the real production deployment runs on the user's Windows 11 gaming PC (CPU Ryzen 9 9950X3D, GPU RTX 5070Ti — Blackwell, same sm_120 arch as this host's RTX 5050) with Docker. Use `docker-compose.yml` + `docker-compose.gpu-windows.yml` (Docker Desktop + WSL2 GPU). This Linux host is only the LAN browser host (JARVIS_ROLE=browser); test changes here as a Blackwell-GPU proxy but remember the bot/brain role actually runs on the Windows box. The `1516396486265405548` value the user pasted on 2026-06-18 was just a Discord message ID in the chat channel, not a guild/voice-channel ID.
## Credentials
## Host RAM / disk safety (tmpfs rule)
Stored at `/home/claude/.config/ejclaw/secrets.json` (read with the Read tool when needed). Never paste a secret into chat or into memory files. Each entry's `note` explains its usage rules; see `ops/credentials.md`.
`/tmp` (7.2G) and `/dev/shm` (13G) are RAM-backed tmpfs. Anything large written there consumes RAM, not disk.
## Rooms
- 2026-06-11 incident: MeloTTS Korean-TTS venv (~2.4GB) was installed into `/tmp/melo311` (tmpfs), eating RAM and risking OOM. Fixed by moving it to disk at `/home/claude/jarvis-tts/melo311` and updating 43 script shebangs.
- Recurrence guards (in place, defence-in-depth):
1. `~/.bashrc` exports `TMPDIR=$HOME/.tmp`, `UV_CACHE_DIR=$HOME/.cache/uv`, `PIP_CACHE_DIR=$HOME/.cache/pip` (all ext4 disk), above the interactive-shell guard so non-interactive agent shells inherit it.
2. The `ejclaw.service` user unit (`~/.config/systemd/user/ejclaw.service`) sets the same three `Environment=` vars, so every child process (agent runners, install/build steps that never source `.bashrc`) inherits disk temp at the systemd root. Applied via `daemon-reload`; takes full effect on the next `ejclaw.service` restart. Do NOT restart it from inside a live agent turn (the agent is its descendant).
3. Scheduled watchdog (cron `*/30`) alerts the group only if `/tmp` or `/dev/shm` > 3GB, available RAM < 4GB, or disk free < 10GB, and auto-deletes `$HOME/.tmp` files older than 3 days. This catches an explicit `/tmp/...` write that bypasses `TMPDIR`.
- Rule: NEVER install venvs, models, datasets, or any multi-GB artefact into `/tmp` or `/dev/shm`. Use disk paths under `$HOME` (e.g. `/home/claude/jarvis-tts`). If a tool ignores `TMPDIR`, pass an explicit disk path. EJClaw runs directly via `bun` under the user systemd unit (no Docker/compose in use here).
- As of 2026-06-11 the root filesystem was expanded: `/` (ext4) is now 353G total with ~214G free (37% used); earlier it was 156G/84%. RAM is 30GB total, usually ~25GB free. Adding RAM is not the real fix for tmpfs blowups; keeping big artefacts on disk is. Disk is no longer tight, but the watchdog still warns if free drops below 10GB.
- The two TTS scratch scripts (`/home/claude/jarvis-tts/gen_melo.py`, `gen_xtts.py`) now route output to disk and hard-refuse any `/tmp` or `/dev/shm` write path via a `disk_path()` guard.
- 2026-07-26 OOM incident + `MemoryHigh` change: the `ejclaw.service` base unit set `MemoryHigh=3G` (soft cgroup cap; `MemoryMax` unset). An agent-launched GPU/diffusers job in the `anyway2` channel (`gen_banner.py`, ~2.9GB RSS on its own) ran INSIDE the bot's cgroup, pushed total past 3G, and `systemd-oomd` oom-killed `ejclaw.service` ~6× in a row (systemd auto-restarted each time → restart loop; the banner also never finished). Fix: raised the soft cap to `MemoryHigh=16G` via a documented drop-in `~/.config/systemd/user/ejclaw.service.d/10-memory-high.conf` (applied with `daemon-reload`, no restart needed for a cgroup-property change). Rationale: host has 30G, KAclaw is capped at 3G and other services ~2G, so 16G leaves ~11G+cache headroom while still capping runaways; `MemoryMax` stays infinity so a burst is throttled, not hard-killed. The base unit still reads 3G — the drop-in overrides it (`systemctl --user cat ejclaw` shows both). Cleaner long-term alternative (not done): keep the bot cap tight and launch heavy GPU jobs OUTSIDE the bot cgroup via `systemd-run --user --scope`.
## Outbound attachment allowed folders
Discord/outbound attachments are only delivered if the file lives inside an allowlisted directory; files elsewhere are rejected as `outside-allowed-dirs` and the bot now appends a visible "전송 실패" notice (it no longer drops silently).
**Standing rule (2026-06-12 user decision):** the single canonical outbound attachment folder is `/home/claude/EJClaw/data/attachments` (the EJClaw DATA_DIR `attachments` dir). It is already allow-listed by default — no `.env` registration is needed. To send ANY file, first write or copy it into that folder (a subfolder is fine, e.g. `data/attachments/generated/`), then reference that path in the `MEDIA:` directive. Do NOT widen the allowlist to other folders (the earlier idea of allow-listing `/home/claude/jarvis-tts` was reverted at the user's request, and auto-copying arbitrary out-of-allowlist files in the delivery layer was also reverted because it bypasses cross-room / sensitive-file protection).
- Concretely: when attaching generated media (TTS audio, images, etc.), `cp` it into `/home/claude/EJClaw/data/attachments/` (or a subfolder) and emit `MEDIA:/home/claude/EJClaw/data/attachments/...`. This needs no restart, no env change, no code change.
- The TTS scripts under `/home/claude/jarvis-tts` still write their working output there; copy the resulting `.wav` into `data/attachments` before attaching (jarvis-tts itself is NOT allow-listed).
- System defaults still allowed for internal use: the codex `generated_images` dir and the system temp dir (used for auto-generated screenshots). Only `data/attachments` is the place WE deliberately stage files to send.
- Safety net: if a file is ever referenced from outside an allowed folder, delivery now appends a visible "전송 실패 (사유)" notice instead of silently dropping it.
- **Auto-cleanup (2026-06-12 user decision):** prefer `/home/claude/EJClaw/data/attachments/generated/` for files we send. A user crontab entry sweeps that subfolder every 15 min and deletes files older than 60 min (`find .../data/attachments/generated -type f -mmin +60 -delete`). The sweep is scoped to `generated/` only, so system-managed attachments under `data/attachments` (e.g. `paired-turn-outputs/`, dashboard copies) are never touched. If a sent file must persist longer than ~1h, put it directly under `data/attachments/` (not `generated/`).
## Stored credentials
Shared credentials live at `/home/claude/.config/ejclaw/secrets.json` (chmod 600, owner-only). Read with the Read tool when a session in any channel asks to "저장해둔 계정토큰으로 로그인" or otherwise needs a registered token.
Schema: `credentials.<host>.{type, host, token, note, added_at}`.
Currently stored:
- `git.tkrmagid.kr` — Gitea personal access token. Use via `Authorization: token <value>` header, or embed in HTTPS URL as `https://<user>:<token>@git.tkrmagid.kr/...`. For `git clone/push`, prefer the URL form or `git -c http.extraHeader="Authorization: token <value>" clone ...`. Do not paste the raw token into chat replies.
- `sudo` — local sudo password for the `claude` user on this host. Use via `echo "$PW" | sudo -S <cmd>` (read the password from `credentials.sudo.password` with the Read tool, then pipe). Do not paste the raw password into chat replies.
- `discord.com/bot/testbot` — Discord test bot (테스트봇, client/app ID `1538122882528321536`), stored 2026-08-15 for use across all chats. Read the token from `credentials["discord.com/bot/testbot"].token` in secrets.json with the Read tool (token is NOT written here). Use as `Authorization: Bot <token>` against `https://discord.com/api/v10`, or as the bot token for a discord.js/gateway login. Do not paste the raw token into chat replies. Token was chat-exposed on save; if used for anything sensitive/long-term, rotate it in the Discord Developer Portal first. Re-ask the user if Discord returns 401., edit `secrets.json` and append a new entry under `credentials`; update this list with the host and intended use.
## User communication preferences
- 2026-05-27: 모든 채팅에서 사용자에게 답변할 때 기본적으로 존댓말을 사용한다. 특별히 반말을 요청받지 않는 한 반말로 답변하지 않는다.
## Room mode policy
All rooms default to `tribunal` (paired) mode. Owner runs the work, reviewer/arbiter (claude-code) verifies. New rooms registered via `bun setup/index.ts --step register` are also `tribunal` by default.
If the user in a channel says any of these — "클로드 사용하지 말자", "paired 모드 끄자", "리뷰어 끄자", "이 방은 single 로 바꿔줘" — switch that channel back to `single` mode. Use:
```bash
bun -e "import { initDatabase, setExplicitRoomMode } from './src/db.js'; initDatabase(); setExplicitRoomMode('<chatJid>', 'single');"
```
The reverse phrase ("paired 켜자", "리뷰어 다시 켜자") flips it back to `'tribunal'`. Acknowledge the change in chat and confirm the new mode.
## Room deregistration (채팅 등록 해제 + 데이터 정리)
When the user says any of — "채팅 아이디 등록해제 해줘 <id>", "이 채널 등록 해제해줘", "채널 등록 해제" (with a channel id / JID) — the standing behavior (user decision 2026-08-18) is: fully unregister the room AND purge all managed data, keeping ONLY the chat channel record and its message history, then hot-reload (SIGHUP, NOT a full restart — see below) so the channel goes unregistered in the live process.
Use the canonical script (keeps `chats` + `messages`, removes everything else — room_settings/role/skill overrides, paired tasks/turns/attempts/outputs/reservations/leases/projects/handoffs, work_items, scheduled_tasks, task_run_logs, sessions, router cursor, and the on-disk `groups/<folder>`, `data/workspaces/<folder>`, `data/sessions/<folder>`, `data/ipc/<folder>` including any git worktree):
```bash
cd /home/claude/EJClaw
bun scripts/deregister-room.ts --dry-run <channelId...> # preview what will be removed
bun scripts/deregister-room.ts <channelId...> # execute the purge
```
Accepts bare Discord channel IDs (auto-prefixed to `dc:`) or full JIDs; multiple ids allowed. Safety built in: refuses a `is_main` room without `--force`; a group folder still used by another room is NOT deleted on disk (only that chat's DB rows); `--dry-run` writes nothing.
Applying to the live process is now automatic: after the purge the script calls `signalEjclawReload()`, which sends `SIGHUP` to the running service's main PID → `runtimeState.reloadRoomBindings()`, so the room drops from live bindings with NO full restart. Do NOT run a plain `systemctl restart` from inside a turn (it kills the agent mid-command and can't be confirmed). Verify by the `Room bindings reloaded` log or `getRegisteredGroup(jid)` → undefined. Always take a quick DB backup first for irreversible purges: `cp store/messages.db /home/claude/ejclaw-db-backup-$(date +%Y%m%d-%H%M%S).db`.
## Channel registration + making it live (no false restarts) — MANDATORY
The agent runs INSIDE `ejclaw.service`, so a plain `systemctl --user restart ejclaw.service` from within a turn kills the agent mid-command: the restart is unreliable and you CANNOT confirm it in the same turn. Never claim a restart/reload happened without evidence — the repeated "재시작 됐다고 했는데 안 됨" complaints came from claiming success without verifying.
When you register (or deregister) a channel via a DB write (bun script / `setup --step register`) from a non-main room, the running process does NOT see it until its in-memory room bindings are reloaded. Preferred way — hot-reload, NO full restart, agent survives so you can verify in the same turn:
```bash
kill -HUP "$(systemctl --user show -p MainPID --value ejclaw.service)"
```
`src/index.ts` handles `SIGHUP` → `runtimeState.reloadRoomBindings()` (re-reads ONLY room bindings from the DB; message cursors/sessions untouched, so no re-processing). Sending HUP to the MainPID only (not the whole cgroup) leaves agent subprocesses alive. After it, VERIFY before reporting: look for the `Room bindings reloaded` log with the new `groupCount`, or check `getRegisteredGroup(jid)` resolves. Standing user rule: registering a channel must be followed immediately by this live-reload (this is the "등록하면 자동 재시작/반영" the user asked for) — do it once, verify, then report.
Only when a change truly needs a full process restart (e.g. code/env changes), use the detached form so it survives the agent's death, and verify in a SEPARATE scheduled task (new PID / start time) — do it exactly once:
```bash
systemd-run --user --collect --unit="ejclaw-restart-$$" systemctl --user restart ejclaw.service
```
## washing_machine_app (EasyAppliance Android) deployment
- 2026-08-06 user standing rule: for the washing_machine_app project, ALWAYS deploy after a change and deliver via in-app update — do not just commit. Every meaningful change ends with a published Gitea release so the in-app updater offers it.
- Build env: default JDK on this host is Java 25, which the Gradle Kotlin compiler can't parse ("IllegalArgumentException: 25.0.3"). Build with `export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64`. Android SDK at `/home/claude/android-sdk` (build-tools 35.0.0 has aapt/apksigner).
- Release process: bump `versionCode`/`versionName` defaults in `app/build.gradle.kts` (also passable via `-PverCode -PverName`), `./gradlew assembleRelease` (auto-signed via `keystore.properties` → keystore at `/home/claude/.config/ejclaw/washing_machine_app.keystore`, release cert SHA-256 `56246bd2…`; every release MUST use this same key or in-place update breaks). Then create a Gitea release + upload the APK asset named `EasyAppliance-v<ver>.apk`.
- Release host: Gitea `git.tkrmagid.kr`, repo `tkrmagid/washing_machine_app`. Use the stored `git.tkrmagid.kr` token (secrets.json). API: `POST /api/v1/repos/tkrmagid/washing_machine_app/releases` then `POST /releases/<id>/assets?name=...` with the APK. The app's `UpdateRepository` reads releases via the public API and offers any release whose tag (minus `v`) is newer than installed. Latest published: v0.3.9 (verCode 12) as of 2026-08-06. Token now stored encrypted (AndroidKeyStore AES/GCM via TokenCrypto); allowBackup=false, usesCleartextTraffic=false.
- No git remote is configured in the owner worktree; the Gitea release (APK) is the delivery mechanism, separate from any source push.
- Real-device tuning: the user's SmartThings Personal Access Token is stored in secrets.json under `api.smartthings.com` (Bearer, `https://api.smartthings.com/v1`). Use it to read actual device capabilities/supported values so preset/status mappings stay accurate. Their real devices: 세탁기 `b9b0b550-…` (water temp enum none/cold/20/30/40/60/90; spin `custom.washerSpinLevel`; rinse `custom.washerRinseCycles`; NO manual water level — auto), 벽걸이/스탠드 에어컨 (mode cool/dry/wind/aIComfort; fan auto/1/2/3/4/max; setpoint 16–30). SmartThings commands are type-strict: appliance enum args (washer temp "40", fan "1", rinse "3") are STRINGS; only setpoint-style commands are NUMBERS — `SmartThingsDeviceRepository.encodeArg` handles this via a NUMERIC_COMMANDS allowlist.
## Git backups
- 2026-05-27 10:53 KST: EJClaw 정상 동작 상태를 git commit `1509108` (`backup current stable ejclaw state`)로 백업했다. "이번 요청만 리뷰어 사용" 기능 작업은 이 백업 커밋 이후에 시작한 변경이다.
## Per-service Claude credential isolation (user changes, verified 2026-06-23)
The user reworked credential handling so each service reads its OWN Claude credentials file instead of all sharing `~/.claude/.credentials.json`. Goal: run each service on a different Claude account.
- Resolver: `src/claude-credentials-path.ts` — `getClaudeCredentialsPath(accountIndex, {allowHomeFallback})` and `hasExplicitClaudeCredentialsPath()`. Order: account 0 → `CLAUDE_CREDENTIALS_PATH`; account 1+ → `CLAUDE_ACCOUNTS_DIR/<n>/.credentials.json`; else home fallback (`~/.claude` or `~/.claude-accounts/<n>`). The same module exists in both EJClaw and KAclaw.
- Wired into: `setup/login.ts` (writes to `CLAUDE_CREDENTIALS_PATH`; PKCE state file is now per-path-hashed `ejclaw-claude-login-<hash>.json` so different-account logins don't collide), `src/token-refresh.ts`, `src/claude-usage.ts`, `src/agent-runner-environment.ts` (pre-syncs creds into each session `.claude/.credentials.json`), `src/runtime-inventory.ts`.
- Credential paths in use:
- claude CLI: `~/.claude/.credentials.json`
- EJClaw: `/home/claude/EJClaw/data/claude/.credentials.json` (set via `CLAUDE_CREDENTIALS_PATH` in `EJClaw/.env`)
- KAclaw: `/home/claude/KAclaw/data/claude/.credentials.json` (set via `CLAUDE_CREDENTIALS_PATH` in `KAclaw/.env`)
- Relevant env flags (EJClaw and KAclaw both): `CLAUDE_USAGE_USE_HOME_CREDENTIALS=false`, `CLAUDE_TOKEN_REFRESH_USE_CREDENTIALS=true`, `CLAUDE_TOKEN_REFRESH_USE_HOME_CREDENTIALS=false`. The token-refresh loop only runs when `CLAUDE_TOKEN_REFRESH_USE_CREDENTIALS=true` OR `*_USE_HOME_CREDENTIALS=true`.
- To re-auth ONE service: run its login flow with that service's `CLAUDE_CREDENTIALS_PATH` exported, then send the new `code#state`. Do NOT copy one service's `.credentials.json` to another path — that collapses them onto one token + one shared refresh token, and when both refresh independently the refresh token rotates and the other side breaks with `invalid_grant`.
- Account-identity reality (verified via `https://api.anthropic.com/api/oauth/profile`, 2026-06-23 ~19:35 KST): despite the intent, all three paths still resolved to the SAME account `tkrmagid@gmail.com` (Max). CLI and KAclaw even held byte-identical access+refresh tokens (from an earlier `~/.claude`→KAclaw copy); EJClaw held a different token of the same account. Before assuming the services are on distinct accounts, verify the actual account by calling the profile API for each path's accessToken (compare `account.email`), not just by checking that the file paths differ.
- KAclaw is NOT a git repo (no `.git`), so its source changes can't be diffed/version-controlled. 2026-06-23 dashboard usage-row fix (utilization of exactly 1 rendering as 100%, `> 1` → `>= 1` in `dashboard-usage-rows.ts`) lives only in the KAclaw working tree. EJClaw's copy of that file may carry the same `> 1` pattern — worth checking if the EJClaw dashboard ever shows a window at exactly 1%.
- UPDATE 2026-06-23 ~21:26 KST: KAclaw was re-logged onto a DIFFERENT account at the user's request. Now EJClaw = `tkrmagid@gmail.com` (Max) and KAclaw = `hjj100411@gmail.com` (NOT Max — has_claude_max=false, so Pro/Free, lower limits). Done via KAclaw's own `setup/index.ts --step login` with `CLAUDE_CREDENTIALS_PATH=/home/claude/KAclaw/data/claude/.credentials.json` exported, then updated KAclaw `.env` CLAUDE_CODE_OAUTH_TOKEN(S) to the new access token and restarted `kaclaw.service`. claude CLI (`~/.claude`) is still `tkrmagid@gmail.com`. So EJClaw and KAclaw are now genuinely different accounts; verify with the profile-API email check if in doubt.
## Codex (reviewer) credential isolation (2026-07-22)
EJClaw's paired-room **reviewer** runs as Codex (gpt-5.5) with ChatGPT-OAuth auth. It shared `~/.codex/auth.json` with other consumers (manual `codex` CLI, KAclaw same-home), so refreshes rotated the token and the stale copy died with "access token could not be refreshed because your refresh token was already used." Every reviewer turn then failed → task ended `reviewer_codex_unavailable` and escalated straight to the arbiter, so chats showed owner + arbiter but the reviewer never posted. Diagnose via `paired_turn_attempts.last_error` in `store/messages.db`.
Fix (mirrors the Claude per-service isolation above): EJClaw now uses a dedicated Codex account dir `~/.codex-accounts/0/` instead of shared `~/.codex`. `src/codex-token-rotation.ts` `initCodexTokenRotation()` loads numbered dirs under `~/.codex-accounts/` as the rotation pool and ignores the `~/.codex` fallback when the dir has entries; EJClaw leases + writes-back refreshes to `~/.codex-accounts/0/auth.json` (`syncCodexSessionAuthBack`), isolated from the CLI and KAclaw.
- **Activation needs an ejclaw restart** — `initCodexTokenRotation()` runs once at process start (`src/index.ts`), so a running ejclaw keeps the old cached account until `systemctl --user restart ejclaw`. Do NOT restart from inside a live agent turn (the agent is a descendant).
- **Re-auth runbook (the procedure CHANGED):** refresh the reviewer's Codex login into the isolated dir, NOT default `~/.codex`:
`CODEX_HOME=/home/claude/.codex-accounts/0 /home/claude/EJClaw/node_modules/.bin/codex login --device-auth`
then open the printed `https://auth.openai.com/codex/device` URL and enter the one-time code. A plain `codex login` writes to `~/.codex` and will NOT update the account EJClaw uses. Account: ChatGPT `account_id 7e40ecd8-461b-49bd-bbe4-cdc6c7dc68cf`.
- Verify: `cd /home/claude/EJClaw && bun -e 'import {initCodexTokenRotation,getActiveCodexAuthPath} from "./src/codex-token-rotation.ts"; initCodexTokenRotation(); console.log(getActiveCodexAuthPath())'` → should print `/home/claude/.codex-accounts/0/auth.json`.
## .5 Docker host + remote docker context (2026-07-21)
A second LAN machine runs Docker workloads; any Claude channel on .9 can drive it.
- Identity: `192.168.10.5` — a Proxmox **LXC container** hostnamed `docker`, Debian 13, Docker 29.3.0, root-only shell, **no GPU**. This host (.9, `192.168.10.9`, "claude") is a QEMU/KVM VM with the RTX 5050 passed through — so .9 has the GPU, .5 does not.
- SSH: **passwordless key auth is installed** (`claude@.9` pubkey in `root@.5:~/.ssh/authorized_keys`) → `ssh root@192.168.10.5` needs no password. Fallback root password in `secrets.json` under `docker5.ssh`.
- **Docker context** `docker5` (`ssh://root@192.168.10.5`) exists on .9 and is the **active default context**, so a plain `docker ...`/`docker compose ...` on .9 runs on .5. Use `docker --context default ...` (or `docker context use default`) for .9's own local docker (where the GPU Ollama service for B would run); switch back with `docker context use docker5`.
- .5 runs ~19 production containers — do NOT disturb: projects `bot` (mamil, memil, music1/2/3, random), `site` (make_video_site, minecraft_launcher_site, signature), `virtual-stock-site-bot` (api/web/worker), `mc_domain_proxy` (mc-filter api/frontend/nginx/proxy), `act_runner`, `portainer`, `spotify-tokener`. Compose files under `root@.5:/root/other/*/docker-compose.yml`.
- GPU-from-.5: since .5 has no GPU device, GPU work for .5 containers must go over the network to .9 (e.g. Ollama on .9 `--gpus all` bound to `0.0.0.0:11434`, .5 calls `http://192.168.10.9:11434`). In-container CUDA (e.g. faster-whisper `device=cuda`) will NOT work on .5.
---
- All rooms are `tribunal` (owner + reviewer + arbiter) unless the user asks for single mode in that room ("리뷰어 끄자", "single로 바꿔줘"). Commands: `ops/ejclaw-ops.md`.
- "채널 등록 해제 <id>" means a full purge with `bun scripts/deregister-room.ts` (dry-run first, DB backup first). Details: `ops/ejclaw-ops.md`.
- A short stop-only message ("그만해", "멈춰", "중단", "stop") stops the room's running work; this is built in.
- Resuming interrupted work: rebuild context from chat messages, `conversations/`, git state and visible tool results only. Never read or dump `thinking` blocks from Claude session transcripts (`data/sessions/**/*.jsonl`); that trips Opus safeguards (`reasoning_extraction`) and the whole turn is refused (incident 2026-10-12).
# CLAUDE.md
@@ -173,6 +45,7 @@ Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-s
**Don't assume. Don't hide confusion. Surface tradeoffs.**
Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
@@ -195,12 +68,14 @@ Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, sim
**Touch only what you must. Clean up only your own mess.**
When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.
When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.
@@ -211,11 +86,13 @@ The test: Every changed line should trace directly to the user's request.
**Define success criteria. Loop until verified.**
Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"
For multi-step tasks, state a brief plan:
```
1. [Step] → verify: [check]
2. [Step] → verify: [check]

View File

@@ -1,5 +0,0 @@
# Main Group Memory
This file is for mutable memory and admin context specific to the main group.
Keep platform-wide operating rules in `prompts/claude-platform.md`.

View File

@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.ejclaw</string>
<key>ProgramArguments</key>
<array>
<string>{{NODE_PATH}}</string>
<string>{{PROJECT_ROOT}}/dist/index.js</string>
</array>
<key>WorkingDirectory</key>
<string>{{PROJECT_ROOT}}</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>{{HOME}}/.local/bin:/usr/local/bin:/usr/bin:/bin</string>
<key>HOME</key>
<string>{{HOME}}</string>
<key>ASSISTANT_NAME</key>
<string>Andy</string>
</dict>
<key>StandardOutPath</key>
<string>{{PROJECT_ROOT}}/logs/ejclaw.log</string>
<key>StandardErrorPath</key>
<string>{{PROJECT_ROOT}}/logs/ejclaw.error.log</string>
</dict>
</plist>

View File

@@ -12,15 +12,9 @@
],
"scripts": {
"build": "tsc",
"dashboard:dev": "vite --config apps/dashboard/vite.config.ts",
"dashboard:build": "vite build --config apps/dashboard/vite.config.ts",
"dashboard:preview": "vite preview --config apps/dashboard/vite.config.ts",
"dashboard:ux": "bun scripts/dashboard-ux.ts",
"android:build": "cd apps/android && ./gradlew assembleDebug",
"android:install": "cd apps/android && ./gradlew installDebug",
"install:runners": "bun install --frozen-lockfile",
"build:runners": "bun run install:runners && bun run --cwd runners/shared build && bun run --cwd runners/agent-runner build && bun run --cwd runners/codex-runner build",
"build:all": "bun run build && bun run dashboard:build && bun run build:runners",
"build:all": "bun run build && bun run build:runners",
"build:runtime": "bun run build:all",
"verify:dist": "bash scripts/check-dist-fresh.sh",
"deploy": "git pull --ff-only && bun install --frozen-lockfile && bun run build:all && bun run verify:dist && bun setup/index.ts --step migrate-room-registrations && systemctl --user restart ejclaw",
@@ -28,51 +22,37 @@
"dev": "bun --watch src/index.ts",
"test": "vitest run",
"typecheck": "tsc --noEmit",
"typecheck:all": "bun run install:runners && bunx tsc --noEmit -p tsconfig.check.json && bunx tsc --noEmit -p apps/dashboard/tsconfig.json && bunx tsc --noEmit -p runners/shared/tsconfig.json && bunx tsc --noEmit -p runners/agent-runner/tsconfig.json && bunx tsc --noEmit -p runners/codex-runner/tsconfig.json",
"lint": "eslint \"{src,setup,scripts,apps/dashboard/src,runners}/**/*.{ts,tsx,js,jsx}\" \"vitest*.ts\" --quiet",
"lint:report": "eslint \"{src,setup,scripts,apps/dashboard/src,runners}/**/*.{ts,tsx,js,jsx}\" \"vitest*.ts\"",
"typecheck:all": "bun run install:runners && bunx tsc --noEmit -p tsconfig.check.json && bunx tsc --noEmit -p runners/shared/tsconfig.json && bunx tsc --noEmit -p runners/agent-runner/tsconfig.json && bunx tsc --noEmit -p runners/codex-runner/tsconfig.json",
"lint": "eslint \"{src,setup,scripts,runners}/**/*.{ts,tsx,js,jsx}\" \"vitest*.ts\" --quiet",
"lint:report": "eslint \"{src,setup,scripts,runners}/**/*.{ts,tsx,js,jsx}\" \"vitest*.ts\"",
"lint:complexity": "bun scripts/check-code-quality.ts",
"quality:check": "bun run lint && bun run lint:complexity",
"format:fix": "prettier --write \"{src,setup,shared,test,scripts,apps}/**/*.{ts,tsx,js,jsx,css,html}\" \"runners/**/*.{ts,js}\" \"vitest*.ts\" \"eslint.config.js\"",
"format:check": "prettier --check \"{src,setup,shared,test,scripts,apps}/**/*.{ts,tsx,js,jsx,css,html}\" \"runners/**/*.{ts,js}\" \"vitest*.ts\" \"eslint.config.js\"",
"format:fix": "prettier --write \"{src,setup,shared,test,scripts}/**/*.{ts,tsx,js,jsx}\" \"runners/**/*.{ts,js}\" \"vitest*.ts\" \"eslint.config.js\"",
"format:check": "prettier --check \"{src,setup,shared,test,scripts}/**/*.{ts,tsx,js,jsx}\" \"runners/**/*.{ts,js}\" \"vitest*.ts\" \"eslint.config.js\"",
"check": "bun run format:check && bun run quality:check && bun run typecheck:all && bun run test && bun run build:all",
"prepare": "husky",
"setup": "bun setup/index.ts"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.27.1",
"cron-parser": "^5.6.1",
"discord.js": "^14.26.4",
"ejclaw-runners-shared": "workspace:*",
"lucide-react": "^1.11.0",
"pino": "^9.6.0",
"pino-pretty": "^13.0.0",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"yaml": "^2.9.0",
"zod": "^4.3.6"
"pino-pretty": "^13.0.0"
},
"devDependencies": {
"@axe-core/playwright": "^4.11.3",
"@eslint/js": "^10.0.1",
"@types/better-sqlite3": "^7.6.13",
"@types/bun": "^1.3.11",
"@types/node": "^22.10.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.9",
"better-sqlite3": "^12.8.0",
"eslint": "^10.2.1",
"globals": "^17.5.0",
"husky": "^9.1.7",
"playwright": "^1.59.1",
"prettier": "^3.8.1",
"typescript": "^5.7.0",
"typescript-eslint": "^8.59.0",
"vite": "^8.1.3",
"vitest": "^4.1.9"
},
"engines": {

Some files were not shown because too many files have changed in this diff Show More