From 20300c017e9ef28590ba0fb31c2ae016923bb9e8 Mon Sep 17 00:00:00 2001 From: javis-bot Date: Thu, 12 Nov 2026 14:15:58 +0900 Subject: [PATCH] feat(app): M5 step 3, the management app's screens and their commands - admin_api: the one entry point of the screens (app status, data folder, PC check, Discord token check and pickers, settings, service control and the dashboard, logs query, error report and zip export). - discord_setup: token, Message Content and invite link checks over REST. - app/ui: first-run wizard, dashboard, five settings screens and the log screen in plain HTML/CSS/JS (dark theme after DESIGN.md, Korean text). - jarvis-admin-dev: a loopback, token-guarded development server so the screens run in a browser against the real commands. Checked in a browser with the real test bot and voice worker: wizard steps, start/restart/stop, settings save, chat channels, logs and export. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 548 ++++++++++++++++++++++++++++++++ app/src/admin.spec.md | 49 ++- app/src/admin_api.rs | 222 +++++++++++++ app/src/bin/jarvis-admin-dev.rs | 105 ++++++ app/src/discord_setup.rs | 106 ++++++ app/src/lib.rs | 2 + app/src/system.rs | 26 ++ app/ui/app.js | 493 ++++++++++++++++++++++++++++ app/ui/index.html | 28 ++ app/ui/style.css | 75 +++++ docs/v2/roadmap.md | 2 +- 11 files changed, 1654 insertions(+), 2 deletions(-) create mode 100644 DESIGN.md create mode 100644 app/src/admin_api.rs create mode 100644 app/src/bin/jarvis-admin-dev.rs create mode 100644 app/src/discord_setup.rs create mode 100644 app/ui/app.js create mode 100644 app/ui/index.html create mode 100644 app/ui/style.css diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..88bcd11 --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,548 @@ +--- +version: alpha +name: Linear-design-analysis +description: "A near-black product-focused marketing canvas built around #010102 (the deepest dark surface of any tool in this collection), light gray text (#f7f8f8), and the signature Linear lavender-blue (#5e6ad2) used as the single chromatic accent. The system reads as software-craft documentation: dense, technical, and quietly luxurious. Display type is set in the Linear custom sans (SF Pro Display fallback) at 500–700 with measured negative tracking. Cards live as charcoal panels (#0f1011) with hairline borders. The accent lavender appears on the brand mark, focus rings, and a few intentional CTAs — never decoratively. Page rhythm leans on product UI screenshots framed in dark panels rather than atmospheric color." + +colors: + primary: "#5e6ad2" + on-primary: "#ffffff" + primary-hover: "#828fff" + primary-focus: "#5e69d1" + ink: "#f7f8f8" + ink-muted: "#d0d6e0" + ink-subtle: "#8a8f98" + ink-tertiary: "#62666d" + canvas: "#010102" + surface-1: "#0f1011" + surface-2: "#141516" + surface-3: "#18191a" + surface-4: "#191a1b" + hairline: "#23252a" + hairline-strong: "#34343a" + hairline-tertiary: "#3e3e44" + inverse-canvas: "#ffffff" + inverse-surface-1: "#f5f6f6" + inverse-surface-2: "#f6f7f7" + inverse-ink: "#000000" + brand-secure: "#7a7fad" + semantic-success: "#27a644" + semantic-overlay: "#000000" + +typography: + display-xl: + fontFamily: Linear Display + fontSize: 80px + fontWeight: 600 + lineHeight: 1.05 + letterSpacing: -3.0px + display-lg: + fontFamily: Linear Display + fontSize: 56px + fontWeight: 600 + lineHeight: 1.10 + letterSpacing: -1.8px + display-md: + fontFamily: Linear Display + fontSize: 40px + fontWeight: 600 + lineHeight: 1.15 + letterSpacing: -1.0px + headline: + fontFamily: Linear Display + fontSize: 28px + fontWeight: 600 + lineHeight: 1.20 + letterSpacing: -0.6px + card-title: + fontFamily: Linear Display + fontSize: 22px + fontWeight: 500 + lineHeight: 1.25 + letterSpacing: -0.4px + subhead: + fontFamily: Linear Display + fontSize: 20px + fontWeight: 400 + lineHeight: 1.40 + letterSpacing: -0.2px + body-lg: + fontFamily: Linear Text + fontSize: 18px + fontWeight: 400 + lineHeight: 1.50 + letterSpacing: -0.1px + body: + fontFamily: Linear Text + fontSize: 16px + fontWeight: 400 + lineHeight: 1.50 + letterSpacing: -0.05px + body-sm: + fontFamily: Linear Text + fontSize: 14px + fontWeight: 400 + lineHeight: 1.50 + letterSpacing: 0 + caption: + fontFamily: Linear Text + fontSize: 12px + fontWeight: 400 + lineHeight: 1.40 + letterSpacing: 0 + button: + fontFamily: Linear Text + fontSize: 14px + fontWeight: 500 + lineHeight: 1.20 + letterSpacing: 0 + eyebrow: + fontFamily: Linear Text + fontSize: 13px + fontWeight: 500 + lineHeight: 1.30 + letterSpacing: 0.4px + mono: + fontFamily: Linear Mono + fontSize: 13px + fontWeight: 400 + lineHeight: 1.50 + letterSpacing: 0 + +rounded: + xs: 4px + sm: 6px + md: 8px + lg: 12px + xl: 16px + xxl: 24px + pill: 9999px + full: 9999px + +spacing: + xxs: 4px + xs: 8px + sm: 12px + md: 16px + lg: 24px + xl: 32px + xxl: 48px + section: 96px + +components: + button-primary: + backgroundColor: "{colors.primary}" + textColor: "{colors.on-primary}" + typography: "{typography.button}" + rounded: "{rounded.md}" + padding: 8px 14px + button-primary-pressed: + backgroundColor: "{colors.primary-focus}" + textColor: "{colors.on-primary}" + typography: "{typography.button}" + rounded: "{rounded.md}" + button-primary-hover: + backgroundColor: "{colors.primary-hover}" + textColor: "{colors.on-primary}" + typography: "{typography.button}" + rounded: "{rounded.md}" + button-secondary: + backgroundColor: "{colors.surface-1}" + textColor: "{colors.ink}" + typography: "{typography.button}" + rounded: "{rounded.md}" + padding: 8px 14px + button-tertiary: + backgroundColor: "{colors.canvas}" + textColor: "{colors.ink}" + typography: "{typography.button}" + rounded: "{rounded.md}" + padding: 8px 14px + button-inverse: + backgroundColor: "{colors.inverse-canvas}" + textColor: "{colors.inverse-ink}" + typography: "{typography.button}" + rounded: "{rounded.md}" + padding: 8px 14px + pricing-card: + backgroundColor: "{colors.surface-1}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.lg}" + padding: 24px + pricing-card-featured: + backgroundColor: "{colors.surface-2}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.lg}" + padding: 24px + feature-card: + backgroundColor: "{colors.surface-1}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.lg}" + padding: 24px + product-screenshot-card: + backgroundColor: "{colors.surface-1}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.xl}" + padding: 24px + testimonial-card: + backgroundColor: "{colors.surface-1}" + textColor: "{colors.ink}" + typography: "{typography.body-lg}" + rounded: "{rounded.lg}" + padding: 32px + customer-logo-tile: + backgroundColor: "{colors.canvas}" + textColor: "{colors.ink-subtle}" + typography: "{typography.caption}" + rounded: "{rounded.xs}" + padding: 16px + text-input: + backgroundColor: "{colors.surface-1}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.md}" + padding: 8px 12px + text-input-focused: + backgroundColor: "{colors.surface-1}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.md}" + padding: 8px 12px + pricing-tab-default: + backgroundColor: "{colors.canvas}" + textColor: "{colors.ink-subtle}" + typography: "{typography.button}" + rounded: "{rounded.pill}" + padding: 6px 14px + pricing-tab-selected: + backgroundColor: "{colors.surface-2}" + textColor: "{colors.ink}" + typography: "{typography.button}" + rounded: "{rounded.pill}" + padding: 6px 14px + cta-banner: + backgroundColor: "{colors.surface-1}" + textColor: "{colors.ink}" + typography: "{typography.headline}" + rounded: "{rounded.lg}" + padding: 48px + changelog-row: + backgroundColor: "{colors.canvas}" + textColor: "{colors.ink}" + typography: "{typography.body}" + rounded: "{rounded.xs}" + padding: 24px 0 + status-badge: + backgroundColor: "{colors.surface-2}" + textColor: "{colors.ink-muted}" + typography: "{typography.caption}" + rounded: "{rounded.pill}" + padding: 2px 8px + top-nav: + backgroundColor: "{colors.canvas}" + textColor: "{colors.ink}" + typography: "{typography.body-sm}" + rounded: "{rounded.xs}" + height: 56px + footer: + backgroundColor: "{colors.canvas}" + textColor: "{colors.ink-subtle}" + typography: "{typography.caption}" + rounded: "{rounded.xs}" + padding: 64px 32px +--- + +## Overview + +Linear's marketing canvas is the deepest dark surface in this collection — `{colors.canvas}` is #010102, essentially pure black with a faint blue tint. On top sits a four-step surface ladder (`{colors.surface-1}` through `{colors.surface-4}`) for cards, panels, and lifted tiles, with hairline borders running from `{colors.hairline}` (#23252a) up through `{colors.hairline-strong}` and `{colors.hairline-tertiary}`. Light gray text (`{colors.ink}` #f7f8f8) carries the body and headlines. + +The single chromatic accent is **Linear lavender-blue** `{colors.primary}` (#5e6ad2) — used on the brand mark, focus rings, and the primary CTA button. A lighter hover state (`{colors.primary-hover}` #828fff) and a focus-tinted variant (`{colors.primary-focus}` #5e69d1) extend the same hue. Linear avoids saturated greens, oranges, reds, etc. on the marketing canvas — the only semantic color is `{colors.semantic-success}` (#27a644) for status pills and the rare success indicator. + +Display type runs Linear's custom sans (with `SF Pro Display` fallback) at weight 500–700 with negative letter-spacing scaling from -3.0px at 80px down to 0 at body. The body family is Linear's text cut, and a Linear Mono is reserved for code snippets in product screenshots. + +The page rhythm is **dense product screenshots** — Linear's marketing leads with high-fidelity captures of the product UI (issue list, project view, dashboard) framed in `{colors.surface-1}` panels with `{rounded.xl}` 16px corners. The chrome is intentionally minimal so the app screenshots can do the heavy lifting. + +**Key Characteristics:** +- **Dark-canvas marketing system** — `{colors.canvas}` (#010102) is the deepest dark in this collection. +- **Lavender-blue brand accent** (`{colors.primary}` #5e6ad2) — used scarcely on brand mark, focus, and the primary CTA. +- Four-step surface ladder (canvas → surface-1 → surface-2 → surface-3 → surface-4) carries hierarchy without shadow. +- Display tracking pulls aggressively negative (-3.0px at 80px); body holds at -0.05px. +- Cards use `{rounded.lg}` 12px corners with 1px hairline borders — never pill, rarely 16px. +- **Product UI screenshots** dominate the page. The marketing chrome is a dark frame for the app. +- No second chromatic color. No atmospheric gradients. No spotlight cards. + +## Colors + +> Source pages: linear.app (home), /intake, /pricing, /contact/sales, /build. + +### Brand & Accent +- **Lavender-Blue** ({colors.primary}): The signature Linear accent — primary CTA, brand mark, link emphasis. +- **Lavender Hover** ({colors.primary-hover}): Lighter lavender (#828fff) — hovered state of the primary CTA. +- **Lavender Focus** ({colors.primary-focus}): Focus-ring tint (#5e69d1) — focused inputs, focused buttons. +- **Brand Secure** ({colors.brand-secure}): Muted lavender-gray (#7a7fad) — used in "Linear Security" surfaces. + +### Surface +- **Canvas** ({colors.canvas}): Default page background — #010102, near-pure black with a faint blue tint. +- **Surface 1** ({colors.surface-1}): One step above canvas — feature cards, pricing cards, product screenshot panels. +- **Surface 2** ({colors.surface-2}): Two steps above — featured pricing card, hovered cards. +- **Surface 3** ({colors.surface-3}): Three steps above — line-tertiary backgrounds, sub-nav. +- **Surface 4** ({colors.surface-4}): Four steps above — bg-level-3, deepest lifted surface. +- **Hairline** ({colors.hairline}): 1px borders on cards and dividers. +- **Hairline Strong** ({colors.hairline-strong}): Stronger 1px borders — input focus rings. +- **Hairline Tertiary** ({colors.hairline-tertiary}): Tertiary borders for nested surfaces. +- **Inverse Canvas** ({colors.inverse-canvas}): Pure white — surface of the inverse pill CTA on a small set of section openers. +- **Inverse Surface 1** ({colors.inverse-surface-1}): One step above inverse canvas. +- **Inverse Surface 2** ({colors.inverse-surface-2}): Two steps above inverse canvas. + +### Text +- **Ink** ({colors.ink}): All headlines and emphasized body type — light gray #f7f8f8. +- **Ink Muted** ({colors.ink-muted}): Secondary type at #d0d6e0 — meta info on hero panels. +- **Ink Subtle** ({colors.ink-subtle}): Tertiary type at #8a8f98 — deselected pricing tabs, footer columns. +- **Ink Tertiary** ({colors.ink-tertiary}): Quaternary at #62666d — disabled, footnotes. + +### Semantic +- **Success Green** ({colors.semantic-success}): Status pills, success indicators. The only semantic color on marketing. +- **Overlay** ({colors.semantic-overlay}): Pure black overlay scrim for modals. + +## Typography + +### Font Family + +- **Linear Display** — Linear's custom display sans; fallback `SF Pro Display, -apple-system, system-ui, Segoe UI, Roboto`. Carries display-xl through subhead. +- **Linear Text** — Linear's custom text sans (a slightly different cut tuned for body sizes); same fallback stack. Carries body sizes, button labels, captions. +- **Linear Mono** — Linear's custom mono; fallback `ui-monospace, SF Mono, Menlo`. Used for code snippets in product screenshots and for status / ID tokens. + +The marketing surface treats Display and Text as one continuous voice; the family change is silent. + +### Hierarchy + +| Token | Size | Weight | Line Height | Letter Spacing | Use | +|---|---|---|---|---|---| +| `{typography.display-xl}` | 80px | 600 | 1.05 | -3.0px | Largest hero headline | +| `{typography.display-lg}` | 56px | 600 | 1.10 | -1.8px | Section opener headlines | +| `{typography.display-md}` | 40px | 600 | 1.15 | -1.0px | Sub-section headlines | +| `{typography.headline}` | 28px | 600 | 1.20 | -0.6px | Pricing tier titles, CTA banner heading | +| `{typography.card-title}` | 22px | 500 | 1.25 | -0.4px | Feature card title | +| `{typography.subhead}` | 20px | 400 | 1.40 | -0.2px | Lead body, intro paragraphs | +| `{typography.body-lg}` | 18px | 400 | 1.50 | -0.1px | Hero subhead, lead paragraphs | +| `{typography.body}` | 16px | 400 | 1.50 | -0.05px | Default body | +| `{typography.body-sm}` | 14px | 400 | 1.50 | 0 | Card body, footer columns | +| `{typography.caption}` | 12px | 400 | 1.40 | 0 | Captions, meta, status | +| `{typography.button}` | 14px | 500 | 1.20 | 0 | All button labels | +| `{typography.eyebrow}` | 13px | 500 | 1.30 | 0.4px | Section eyebrow (slight positive tracking) | +| `{typography.mono}` | 13px | 400 | 1.50 | 0 | Linear Mono for code in product screenshots | + +### Principles + +- **Aggressive negative tracking on display** (-3.0px at 80px ≈ 4% of size). +- **Single voice from display to body.** Display-xl at 600 → body at 400 — same family, narrower weights. +- **Eyebrow uses positive tracking** (+0.4px) — contrast against the negative-tracked display marks the eyebrow as taxonomy. +- **Mono only in code contexts.** Linear Mono lives inside product screenshots — not on marketing chrome. + +### Note on Font Substitutes + +Linear's custom typeface isn't publicly distributed; the documented fallback `SF Pro Display, -apple-system, system-ui` is the recommended substitute on macOS. For cross-platform implementation, **Inter** at weight 500 / 600 / 700 is the closest free substitute. **Geist Sans** is also viable. For mono, **JetBrains Mono** or **Geist Mono** at weight 400 closely approximates Linear Mono. + +## Layout + +### Spacing System + +- **Base unit**: 4px. +- **Tokens (front matter)**: `{spacing.xxs}` 4px · `{spacing.xs}` 8px · `{spacing.sm}` 12px · `{spacing.md}` 16px · `{spacing.lg}` 24px · `{spacing.xl}` 32px · `{spacing.xxl}` 48px · `{spacing.section}` 96px. +- Card interior padding: `{spacing.lg}` 24px on feature/pricing cards; `{spacing.xl}` 32px on testimonial cards; `{spacing.xxl}` 48px on CTA banners. +- Pill button padding: 8px vertical · 14px horizontal — Linear's compact button spec. +- Form input padding: 8px vertical · 12px horizontal. + +### Grid & Container + +- Max content width sits around 1280px. +- Card grids are 3-up at desktop, 2-up at tablet, 1-up at mobile. +- Pricing tier grid is 3-up; comparison strip below shows checkmarks per tier. +- Product screenshot panels span full content width — they're the protagonist. + +### Whitespace Philosophy + +The dark canvas IS the whitespace. Sections separate by lift onto surface-1 panels, not by gaps in white. Within a panel, generous `{spacing.lg}` 24px gaps between content blocks; `{spacing.section}` 96px between sections. + +## Elevation & Depth + +| Level | Treatment | Use | +|---|---|---| +| 0 (flat) | No shadow, no border | Default for body type, hero text, footer | +| 1 (charcoal lift) | `{colors.surface-1}` background on canvas, 1px `{colors.hairline}` | Default cards, product panels | +| 2 (surface-2 lift) | `{colors.surface-2}` background, 1px `{colors.hairline-strong}` | Featured pricing card, hovered cards | +| 3 (surface-3 lift) | `{colors.surface-3}` background | Sub-nav, dropdown menus | +| 4 (focus ring) | 2px `{colors.primary-focus}` outline at 50% opacity | Focused input, focused button | + +Linear's depth is carried by surface ladder + hairline borders. The brand resists drop shadows on dark almost entirely. + +### Decorative Depth + +- **Product UI screenshots** dominate as decorative depth. +- **No atmospheric gradients, no spotlight cards.** +- **Subtle white edge highlight** on the top edge of lifted panels — gives the dark surface a faint "pixel rendered" feel. + +## Shapes + +### Border Radius Scale + +| Token | Value | Use | +|---|---|---| +| `{rounded.xs}` | 4px | Small chips, status badges | +| `{rounded.sm}` | 6px | Inline tags | +| `{rounded.md}` | 8px | All buttons, form inputs | +| `{rounded.lg}` | 12px | Pricing cards, feature cards, testimonial cards | +| `{rounded.xl}` | 16px | Product screenshot panels | +| `{rounded.xxl}` | 24px | Oversized CTA banners (rare) | +| `{rounded.pill}` | 9999px | Pricing tab toggles, status pills | +| `{rounded.full}` | 9999px | Avatar circles | + +### Photography & Illustration Geometry + +- Product UI screenshots dominate; they sit in `{rounded.xl}` 16px tiles with `{spacing.lg}` 24px outer padding. +- Customer logo tiles render at small sizes (~24px logo height) on `{colors.canvas}` with no border. +- Avatar circles in testimonial cards use `{rounded.full}` at 32–40px sizes. + +## Components + +### Buttons + +**`button-primary`** — Lavender CTA. The default primary CTA across all pages. +- Background `{colors.primary}`, text `{colors.on-primary}`, type `{typography.button}`, padding 8px 14px, rounded `{rounded.md}`. +- Pressed state lives in `button-primary-pressed` (background shifts to `{colors.primary-focus}`). +- Hover state lives in `button-primary-hover` (background shifts to `{colors.primary-hover}` lighter lavender). + +**`button-secondary`** — Charcoal button. Used for secondary CTAs ("Sign in", "Read changelog"). +- Background `{colors.surface-1}`, text `{colors.ink}`, type `{typography.button}`, padding 8px 14px, rounded `{rounded.md}`. 1px `{colors.hairline}` border. + +**`button-tertiary`** — Plain text button. +- Background `{colors.canvas}`, text `{colors.ink}`, type `{typography.button}`, rounded `{rounded.md}`, padding 8px 14px. + +**`button-inverse`** — White-on-dark inverse CTA. +- Background `{colors.inverse-canvas}`, text `{colors.inverse-ink}`, type `{typography.button}`, rounded `{rounded.md}`, padding 8px 14px. + +### Pricing Tabs + +**`pricing-tab-default`** + **`pricing-tab-selected`** — Pill-toggle on `/pricing`. +- Default: `{colors.canvas}` background, `{colors.ink-subtle}` text, rounded `{rounded.pill}`, padding 6px 14px. +- Selected: `{colors.surface-2}` background, `{colors.ink}` text — selected = surface lift. + +### Cards & Containers + +**`pricing-card`** — Each tier on `/pricing`. +- Background `{colors.surface-1}`, text `{colors.ink}`, type `{typography.body}`, rounded `{rounded.lg}`, padding 24px. 1px `{colors.hairline}` border. + +**`pricing-card-featured`** — Recommended tier — surface lift to surface-2. +- Background `{colors.surface-2}`, otherwise identical structure. + +**`feature-card`** — Generic feature highlight tile. +- Background `{colors.surface-1}`, text `{colors.ink}`, type `{typography.body}`, rounded `{rounded.lg}`, padding 24px. + +**`product-screenshot-card`** — The dominant card type — frames a high-fidelity Linear app UI screenshot. +- Background `{colors.surface-1}`, text `{colors.ink}`, type `{typography.body}`, rounded `{rounded.xl}`, padding 24px. + +**`testimonial-card`** — Customer quote with avatar + name + role. +- Background `{colors.surface-1}`, text `{colors.ink}`, type `{typography.body-lg}`, rounded `{rounded.lg}`, padding 32px. + +**`customer-logo-tile`** — Small tile in the customer marquee. +- Background `{colors.canvas}`, text `{colors.ink-subtle}`, type `{typography.caption}`, rounded `{rounded.xs}`, padding 16px. + +**`cta-banner`** — Closing CTA panel near page bottom. +- Background `{colors.surface-1}`, text `{colors.ink}`, type `{typography.headline}`, rounded `{rounded.lg}`, padding 48px. + +### Inputs & Forms + +**`text-input`** + **`text-input-focused`** — Form fields on `/contact/sales` and signup overlays. +- Background `{colors.surface-1}`, text `{colors.ink}`, type `{typography.body}`, rounded `{rounded.md}`, padding 8px 12px. +- Focused state retains the same surface; the focus ring is a 2px `{colors.primary-focus}` outline at 50% opacity. + +### Status & Build Page + +**`changelog-row`** — Each row in `/build` (changelog page) listing version, date, and changes. +- Background `{colors.canvas}`, text `{colors.ink}`, type `{typography.body}`, rounded `{rounded.xs}`, padding 24px 0. 1px `{colors.hairline}` bottom rule. + +**`status-badge`** — Small status pill. +- Background `{colors.surface-2}`, text `{colors.ink-muted}`, type `{typography.caption}`, rounded `{rounded.pill}`, padding 2px 8px. + +### Navigation + +**`top-nav`** — Sticky dark bar with the Linear wordmark left, primary nav links centered, and a `button-secondary` ("Sign in") + `button-primary` ("Get started") pair right. +- Background `{colors.canvas}`, text `{colors.ink}`, type `{typography.body-sm}`, height 56px. + +### Footer + +**`footer`** — Dense link grid on `{colors.canvas}` with the Linear wordmark left. +- Background `{colors.canvas}`, text `{colors.ink-subtle}`, type `{typography.caption}`, padding 64px 32px. + +## Do's and Don'ts + +### Do + +- Reserve `{colors.canvas}` (#010102) as the system's anchor surface — the faint blue tint is intentional. +- Use `{colors.primary}` lavender ONLY for: brand mark, primary CTA, focus ring, link emphasis. +- Use the four-step surface ladder for hierarchy. Avoid skipping levels. +- Pair display weight 600 with body weight 400 — Linear resists 700+ display weights. +- Apply negative letter-spacing aggressively on display. +- Use product UI screenshots as the protagonist of every section. +- Compose CTAs as `{rounded.md}` 8px corners. + +### Don't + +- Don't ship a light-mode marketing page. +- Don't use lavender as a section background or card fill. +- Don't introduce a second chromatic accent (orange, pink, green for marketing). +- Don't add atmospheric gradients or spotlight cards. +- Don't pill-round CTAs. +- Don't use `#000000` true black as the canvas. +- Don't combine multiple bright accents in product screenshot mockups. + +## Responsive Behavior + +### Breakpoints + +| Name | Width | Key Changes | +|---|---|---| +| Desktop-XL | 1440px | Default desktop layout | +| Desktop | 1280px | Card grid 3-up maintained | +| Tablet | 1024px | Card grid 3-up → 2-up | +| Mobile-Lg | 768px | Pricing comparison becomes accordion; nav hamburger | +| Mobile | 480px | Single-column; display-xl scales 80px → ~36px | + +### Touch Targets + +- CTAs hold ≥40px tap height across viewports. +- Pricing tab pills hold ≥36px tap height; touch viewports grow to ≥44px. +- Form inputs hold ≥44px tap target on touch. + +### Collapsing Strategy + +- **Top nav**: links collapse to hamburger below 768px. +- **Card grids**: 3-up → 2-up at 1024px → 1-up below 768px. +- **Pricing comparison**: per-tier accordion below 768px. +- **Display type**: `{typography.display-xl}` 80px scales toward `{typography.display-md}` 40px on mobile. + +### Image Behavior + +- Product UI screenshots maintain aspect ratio and never crop. +- Customer logos in the marquee may collapse from 6-up to 3-up below 768px. + +## Iteration Guide + +1. Focus on ONE component at a time and reference it by its `components:` token name. +2. When introducing a section, decide first which surface lift it lives on. +3. Default body to `{typography.body}` at weight 400. +4. Run `npx @google/design.md lint DESIGN.md` after edits. +5. Add new variants as separate component entries. +6. Treat lavender as scarce: brand mark, primary CTA, focus, link emphasis. +7. Lead every section with a product UI screenshot. + +## Known Gaps + +- The four-step surface ladder values are extracted directly from Linear's `--color-bg-level-3`, `--color-line-tint`, etc. CSS variables; they are Linear's canonical surface spec. +- Form-field error and validation styling is not visible on the inspected pages. +- Light mode is not documented because the marketing site does not ship a light theme. +- Linear's actual product UI uses a richer color-tag palette (red, orange, yellow, green, blue, purple) for issue priorities and project labels — those colors live in the in-product surfaces shown in mockups. +- The custom display, text, and mono families are proprietary; an open-source substitute is acceptable. diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index d4d3c1e..e068a48 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -127,6 +127,49 @@ reaches the screen. The dashboard's state is built from the core's events alone (`Dashboard::on_event` with the time), so it is tested with made-up events. +## Admin commands (`app/src/admin_api.rs`) + +`AdminApi::call(command, args)` is the one entry point of the screens, JSON in and out; errors come +back as Korean messages for the screen. The Tauri shell passes the screens' `invoke("admin", +{command, args})` to it; the development server (below) does the same over loopback HTTP. + +| Command | Does | +|---|---| +| `app_status` | version, data folder, whether a token is stored; `firstRun` while either is missing | +| `folder_check` `{path}` / `folder_choose` `{path}` | free space against the recommendation / create the folder and remember it | +| `pc_check` | OS, CPU threads, RAM, NVIDIA GPUs, the driver version and whether it is 580 or newer, free disk | +| `token_check` `{token}` | the bot's tag and IDs, whether the Message Content intent is on, the invite link (REST only, nothing stored) | +| `token_save` `{token}` / `token_status` | store it (masked from then on in logs) / `set` and the masked form, never the token | +| `discord_guilds` / `discord_channels` `{guildId}` | the bot's servers / a server's voice and text channels, for the pickers | +| `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run | +| `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot | +| `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back | + +The invite link asks for: view channels, send messages, read history, add reactions, manage +messages, manage channels, connect, speak, voice activity, and the slash command scope; never +administrator. The log hub writes to the data folder's `logs/` from the first start after a +folder is chosen (before that, memory only). + +## Screens (`app/ui/`) + +Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. All text is Korean. + +- **First-run wizard** (while `firstRun`): data folder (free space, warning under 200 GB), PC check, + the model to download (the download itself is step 4 of M5), Discord bot (token check with the + Message Content state and the invite link, then save), server and auto-join voice channel + pickers, wake words, then start. It resumes at the bot step when a folder is already chosen. +- **Dashboard**: the snapshot every second; the header with start, restart and stop is rebuilt + only when the state changes, so a click is never lost to the refresh. +- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델): built from `settings_fields`; only + changed fields are sent; the server and voice channel are pickers; the chat channels are a table + with their switches; the bot screen also changes the token. +- **Logs**: tab, level and text filters, pause, live follow (lines after the last seen), "최근 오류 + 복사" (to the clipboard; over 2,000 characters it suggests the zip), and the zip export by days. + +`jarvis-admin-dev [--port N] [--ui DIR] [--location FILE]` (development only) serves `app/ui` and +the commands on 127.0.0.1; every command needs the random token it prints (`#token=` in the page +URL), so other local programs cannot drive it. + ## Tests `cargo test`: data folder layout, location file and the environment override, a refused relative @@ -136,5 +179,9 @@ without touching the file; secrets round trip, file permissions on Unix, masking categories, query filters and follow, files per day and retention, error report bounds, zip size cap, redaction of stored secrets and token-shaped text; the controller's state rules with a fake service starter; the dashboard from made-up events (captions replaced and cleared, latency stages -and medians, an answer matched to its asker's final, missed requests without text). Windows-only paths (DPAPI, `%APPDATA%`) are +and medians, an answer matched to its asker's final, missed requests without text); the admin +commands (first run: folder then token, the token never returned whole, settings and logs through +their modules, the dashboard before anything runs), the invite link's permissions and the Message +Content flags. The screens are checked in a browser against the development server with the real +services (wizard, dashboard start, restart and stop, settings save, chat channels, logs, export). Windows-only paths (DPAPI, `%APPDATA%`) are checked on the Windows VM in the Windows build step. diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs new file mode 100644 index 0000000..844ff76 --- /dev/null +++ b/app/src/admin_api.rs @@ -0,0 +1,222 @@ +//! The commands the management app's screens call (`app/src/admin.spec.md`, "Admin commands"). +//! +//! One entry point, `AdminApi::call(command, args)`, with JSON in and out: the Tauri shell passes +//! the screen's `invoke` straight to it, and the development server does the same over loopback +//! HTTP, so both run the same code. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use serde_json::{json, Map, Value}; + +use crate::control::{Controller, ServicesHost}; +use crate::datadir::{free_bytes, DataDir, RECOMMENDED_FREE_BYTES}; +use crate::logs::{Level, LogHub}; +use crate::secrets::{masked, Secrets, DISCORD_TOKEN}; + +pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); + +pub struct AdminApi { + location_file: PathBuf, + dir: Mutex>, + controller: Mutex>>, + hub: Arc, +} + +fn arg<'a>(args: &'a Value, key: &str) -> Result<&'a Value, String> { + args.get(key).ok_or_else(|| format!("{key}이(가) 필요합니다")) +} + +fn arg_str<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { + arg(args, key)?.as_str().ok_or_else(|| format!("{key}은(는) 글자여야 합니다")) +} + +fn level_of(s: &str) -> Level { + match s { + "error" => Level::Error, + "warn" => Level::Warn, + "info" => Level::Info, + _ => Level::Debug, + } +} + +impl AdminApi { + /// `location_file`: where the data folder is remembered; `hub`: the app's log hub. + pub fn new(location_file: &Path, hub: Arc) -> Self { + let dir = DataDir::locate(location_file); + Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), hub } + } + + fn dir(&self) -> Result { + self.dir.lock().unwrap().clone().ok_or_else(|| "데이터 폴더를 먼저 골라 주세요".into()) + } + + fn secrets(&self) -> Result { + Ok(Secrets::new(&self.dir()?.secrets_file())) + } + + fn token(&self) -> Result { + self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())? + .ok_or_else(|| "봇 토큰을 먼저 저장해 주세요".into()) + } + + fn controller(&self) -> Result, String> { + let dir = self.dir()?; + let mut c = self.controller.lock().unwrap(); + Ok(c.get_or_insert_with(|| Controller::new(ServicesHost { data_dir: dir.path().to_path_buf() })).clone()) + } + + pub async fn call(&self, command: &str, args: Value) -> Result { + crate::debug_log!("admin", "command {command}"); + match command { + "app_status" => { + let dir = self.dir.lock().unwrap().clone(); + let token = dir.as_ref().and_then(|d| Secrets::new(&d.secrets_file()).get(DISCORD_TOKEN).ok().flatten()); + Ok(json!({"version": APP_VERSION, "dataDir": dir.as_ref().map(|d| d.path().to_string_lossy()), + "tokenSet": token.is_some(), "firstRun": dir.is_none() || token.is_none()})) + } + "folder_check" => { + let path = PathBuf::from(arg_str(&args, "path")?); + if !path.is_absolute() { + return Err("전체 경로를 적어 주세요 (예: D:\\JarvisBot)".into()); + } + let free = free_bytes(&path).map_err(|e| e.to_string())?; + Ok(json!({"freeBytes": free, "recommendedBytes": RECOMMENDED_FREE_BYTES, + "enough": free >= RECOMMENDED_FREE_BYTES, "exists": path.exists()})) + } + "folder_choose" => { + let path = PathBuf::from(arg_str(&args, "path")?); + let dir = DataDir::choose(&path, &self.location_file).map_err(|e| e.to_string())?; + *self.dir.lock().unwrap() = Some(dir); + *self.controller.lock().unwrap() = None; + crate::info_log!("admin", "data folder chosen"); + Ok(json!({"dataDir": path.to_string_lossy()})) + } + "pc_check" => { + let usage = crate::system::usage().await; + let driver = crate::system::driver_version().await; + let disk = self.dir.lock().unwrap().as_ref().and_then(|d| free_bytes(d.path()).ok()); + Ok(json!({"os": std::env::consts::OS, "cpuThreads": std::thread::available_parallelism().map(|n| n.get()).ok(), + "ramTotalMb": usage.ram_total_mb, "gpus": usage.gpus, "driver": driver, + "driverOk": driver.as_deref().is_some_and(crate::system::driver_ok), + "minDriver": crate::system::MIN_DRIVER_MAJOR, "diskFreeBytes": disk})) + } + "token_check" => Ok(json!(crate::discord_setup::check_token(arg_str(&args, "token")?).await?)), + "token_save" => { + let token = arg_str(&args, "token")?.trim().to_owned(); + if token.is_empty() { + return Err("봇 토큰이 비어 있습니다".into()); + } + self.secrets()?.set(DISCORD_TOKEN, &token).map_err(|e| e.to_string())?; + self.hub.set_secrets(self.secrets()?.values()); + crate::info_log!("admin", "bot token saved"); + Ok(json!({"masked": masked(&token)})) + } + "token_status" => { + let t = self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())?; + Ok(json!({"set": t.is_some(), "masked": t.as_deref().map(masked)})) + } + "discord_guilds" => Ok(json!(crate::discord_setup::guilds(&self.token()?).await?)), + "discord_channels" => { + let guild: u64 = arg_str(&args, "guildId")?.parse().map_err(|_| "서버 ID가 올바르지 않습니다")?; + Ok(json!(crate::discord_setup::channels(&self.token()?, guild).await?)) + } + "settings_fields" => Ok(json!(crate::settings_edit::fields())), + "settings_view" => crate::settings_edit::view(&self.dir()?.settings_file()) + .map(Value::Object).map_err(|e| e.0), + "settings_apply" => { + let changes: Map = arg(&args, "changes")?.as_object().cloned() + .ok_or("changes는 객체여야 합니다")?; + crate::settings_edit::apply(&self.dir()?.settings_file(), &changes).map_err(|e| e.0)?; + Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running})) + } + "service_start" => self.controller()?.start().await.map(|_| json!({"ok": true})), + "service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})), + "service_restart" => self.controller()?.restart().await.map(|_| json!({"ok": true})), + "dashboard" => Ok(self.controller()?.snapshot().await), + "logs_query" => { + let tab = args.get("tab").and_then(Value::as_str).filter(|t| !t.is_empty() && *t != "all"); + let level = level_of(args.get("level").and_then(Value::as_str).unwrap_or("debug")); + let find = args.get("find").and_then(Value::as_str).filter(|f| !f.is_empty()); + let after = args.get("after").and_then(Value::as_u64); + let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(500).min(5000) as usize; + Ok(json!(self.hub.query(tab, level, find, after, limit))) + } + "logs_error_report" => { + let report = self.hub.recent_error_report(APP_VERSION); + let too_long = report.as_ref().is_some_and(|r| r.chars().count() > crate::logs::DISCORD_MESSAGE_CHARS); + Ok(json!({"report": report, "tooLongForDiscord": too_long})) + } + "logs_export" => { + let day = |k: &str| -> Result { + chrono::NaiveDate::parse_from_str(arg_str(&args, k)?, "%Y-%m-%d").map_err(|_| format!("{k}는 YYYY-MM-DD 날짜여야 합니다")) + }; + let (from, to) = (day("from")?, day("to")?); + let out = self.dir()?.logs().join(format!("jarvis-logs-{from}-{to}.zip")); + let dropped = self.hub.export_zip(from, to, &out).map_err(|e| e.to_string())?; + Ok(json!({"path": out.to_string_lossy(), "droppedLines": dropped})) + } + _ => Err(format!("알 수 없는 명령: {command}")), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::datadir::temp_dir; + + fn api(tag: &str) -> (AdminApi, PathBuf) { + let base = temp_dir(tag); + let loc = base.join("cfg").join("location.json"); + (AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), hub: LogHub::new(None) }, + base) + } + + #[tokio::test] + async fn the_first_run_chooses_a_folder_then_stores_the_token() { + let (a, base) = api("api1"); + assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(true)); + assert!(a.call("settings_view", json!({})).await.unwrap_err().contains("데이터 폴더")); + assert!(a.call("folder_check", json!({"path": "relative"})).await.is_err()); + let data = base.join("data"); + let check = a.call("folder_check", json!({"path": data.to_string_lossy()})).await.unwrap(); + assert!(check["freeBytes"].as_u64().unwrap() > 0 && check["exists"] == json!(false)); + a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap(); + assert!(data.join("config").is_dir()); + assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(true), "no token yet"); + let saved = a.call("token_save", json!({"token": "abc.def.ghijkl"})).await.unwrap(); + assert_eq!(saved["masked"], json!("••••ijkl")); + let s = a.call("app_status", json!({})).await.unwrap(); + assert_eq!((s["firstRun"].clone(), s["tokenSet"].clone()), (json!(false), json!(true))); + // The token never comes back whole. + assert_eq!(a.call("token_status", json!({})).await.unwrap(), json!({"set": true, "masked": "••••ijkl"})); + } + + #[tokio::test] + async fn settings_go_through_the_editor_and_logs_through_the_hub() { + let (a, base) = api("api2"); + a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); + let fields = a.call("settings_fields", json!({})).await.unwrap(); + assert_eq!(fields.as_array().unwrap().len(), crate::settings_edit::fields().len()); + a.call("settings_apply", json!({"changes": {"call.mode": "everything"}})).await.unwrap(); + assert_eq!(a.call("settings_view", json!({})).await.unwrap()["call.mode"], json!("everything")); + assert!(a.call("settings_apply", json!({"changes": {"call.mode": "x"}})).await.unwrap_err().contains("call.mode")); + a.hub.push(Level::Error, "discord", "login failed"); + a.hub.push(Level::Debug, "chat", "ok"); + let lines = a.call("logs_query", json!({"tab": "discord", "level": "error"})).await.unwrap(); + assert_eq!(lines.as_array().unwrap().len(), 1); + let r = a.call("logs_error_report", json!({})).await.unwrap(); + assert!(r["report"].as_str().unwrap().contains("login failed")); + assert!(a.call("nope", json!({})).await.is_err()); + } + + #[tokio::test] + async fn the_dashboard_answers_before_anything_runs() { + let (a, base) = api("api3"); + a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); + let d = a.call("dashboard", json!({})).await.unwrap(); + assert_eq!(d["state"], json!("stopped")); + assert!(a.call("service_stop", json!({})).await.is_err()); + } +} diff --git a/app/src/bin/jarvis-admin-dev.rs b/app/src/bin/jarvis-admin-dev.rs new file mode 100644 index 0000000..7627b2f --- /dev/null +++ b/app/src/bin/jarvis-admin-dev.rs @@ -0,0 +1,105 @@ +//! Development server for the management app's screens (`app/src/admin.spec.md`, "Screens"): +//! serves `app/ui` and passes `POST /api/` to the same `AdminApi` the Tauri shell uses, +//! so the screens can be opened and tested in a browser. Loopback only, and every API call needs +//! the random token printed at start (in the page URL's `#token=`). +//! +//! jarvis-admin-dev [--port N] [--ui DIR] [--location FILE] + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use jarvis_app::admin_api::AdminApi; +use serde_json::{json, Value}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +fn arg(name: &str) -> Option { + let args: Vec = std::env::args().collect(); + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) +} + +fn content_type(path: &Path) -> &'static str { + match path.extension().and_then(|e| e.to_str()) { + Some("html") => "text/html; charset=utf-8", + Some("js") => "text/javascript; charset=utf-8", + Some("css") => "text/css; charset=utf-8", + Some("svg") => "image/svg+xml", + Some("png") => "image/png", + _ => "application/octet-stream", + } +} + +async fn respond(s: &mut TcpStream, status: &str, ctype: &str, body: &[u8]) { + let head = format!("HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n", body.len()); + let _ = s.write_all(head.as_bytes()).await; + let _ = s.write_all(body).await; +} + +async fn handle(mut s: TcpStream, api: Arc, ui: Arc, token: Arc) { + let mut buf = Vec::new(); + let mut chunk = [0u8; 8192]; + let head_end = loop { + let Ok(n) = s.read(&mut chunk).await else { return }; + if n == 0 { return; } + buf.extend_from_slice(&chunk[..n]); + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { break i + 4; } + if buf.len() > 64 * 1024 { return; } + }; + let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); + let mut lines = head.lines(); + let mut first = lines.next().unwrap_or("").split_whitespace(); + let (method, path) = (first.next().unwrap_or(""), first.next().unwrap_or("/").to_owned()); + let header = |name: &str| head.lines().find_map(|l| l.split_once(':') + .filter(|(k, _)| k.trim().eq_ignore_ascii_case(name)).map(|(_, v)| v.trim().to_owned())); + let len: usize = header("content-length").and_then(|v| v.parse().ok()).unwrap_or(0).min(4 * 1024 * 1024); + while buf.len() < head_end + len { + let Ok(n) = s.read(&mut chunk).await else { return }; + if n == 0 { break; } + buf.extend_from_slice(&chunk[..n]); + } + if method == "POST" && path.starts_with("/api/") { + if header("x-admin-token").as_deref() != Some(token.as_str()) { + return respond(&mut s, "403 Forbidden", "text/plain", b"bad token").await; + } + let args: Value = serde_json::from_slice(&buf[head_end..(head_end + len).min(buf.len())]).unwrap_or(json!({})); + let out = match api.call(&path[5..], args).await { + Ok(v) => json!({"ok": true, "value": v}), + Err(e) => json!({"ok": false, "error": e}), + }; + return respond(&mut s, "200 OK", "application/json", out.to_string().as_bytes()).await; + } + if method != "GET" { + return respond(&mut s, "405 Method Not Allowed", "text/plain", b"").await; + } + let rel = path.split(['?', '#']).next().unwrap_or("/").trim_start_matches('/'); + let rel = if rel.is_empty() { "index.html" } else { rel }; + if rel.split('/').any(|p| p == ".." || p.is_empty()) { + return respond(&mut s, "404 Not Found", "text/plain", b"").await; + } + let file = ui.join(rel); + match tokio::fs::read(&file).await { + Ok(b) => respond(&mut s, "200 OK", content_type(&file), &b).await, + Err(_) => respond(&mut s, "404 Not Found", "text/plain", b"").await, + } +} + +#[tokio::main] +async fn main() { + let ui = arg("--ui").map(PathBuf::from).unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("ui")); + let location = arg("--location").map(PathBuf::from).or_else(jarvis_app::datadir::default_location_file) + .expect("no location file path: pass --location"); + let port: u16 = arg("--port").and_then(|p| p.parse().ok()).unwrap_or(0); + // Log files go to the data folder once there is one (from the next start after the wizard). + let logs = jarvis_app::datadir::DataDir::locate(&location).map(|d| d.logs()); + let hub = jarvis_app::logs::LogHub::new(logs.as_deref()); + jarvis_app::logs::install(hub.clone()); + let api = Arc::new(AdminApi::new(&location, hub)); + let token: String = (0..16).map(|_| format!("{:02x}", rand::random::())).collect(); + let listener = TcpListener::bind(("127.0.0.1", port)).await.expect("bind"); + println!("http://127.0.0.1:{}/#token={token}", listener.local_addr().unwrap().port()); + let (ui, token) = (Arc::new(ui), Arc::new(token)); + loop { + let Ok((s, _)) = listener.accept().await else { continue }; + tokio::spawn(handle(s, api.clone(), ui.clone(), token.clone())); + } +} diff --git a/app/src/discord_setup.rs b/app/src/discord_setup.rs new file mode 100644 index 0000000..162f50c --- /dev/null +++ b/app/src/discord_setup.rs @@ -0,0 +1,106 @@ +//! The setup wizard's Discord steps (`app/src/admin.spec.md`, "Admin commands"): check a bot +//! token, the Message Content intent and the invite link, and list servers and channels for the +//! pickers. REST only: nothing here connects to the gateway or joins anything. + +use serde::Serialize; +use serenity::all::{ApplicationFlags, ChannelType, GuildId, Http, Permissions}; + +/// What the bot needs: read and post in chat channels (reply, react, delete, pin), keep channel +/// names and topics in step (desktop-app.md), and talk in voice. +pub fn needed_permissions() -> Permissions { + Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES | Permissions::READ_MESSAGE_HISTORY + | Permissions::ADD_REACTIONS | Permissions::MANAGE_MESSAGES | Permissions::MANAGE_CHANNELS + | Permissions::CONNECT | Permissions::SPEAK | Permissions::USE_VAD +} + +/// The link that adds the bot to a server with those permissions and its slash command. +pub fn invite_url(application_id: u64) -> String { + format!("https://discord.com/oauth2/authorize?client_id={application_id}&scope=bot%20applications.commands&permissions={}", + needed_permissions().bits()) +} + +/// The Message Content intent is on (either the full or the limited flag of unverified bots). +pub fn message_content_on(flags: Option) -> bool { + flags.is_some_and(|f| f.intersects(ApplicationFlags::GATEWAY_MESSAGE_CONTENT + | ApplicationFlags::GATEWAY_MESSAGE_CONTENT_LIMITED)) +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TokenCheck { + pub bot_tag: String, + pub bot_id: String, + pub application_id: String, + pub message_content: bool, + pub invite_url: String, +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Named { + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Channels { + pub voice: Vec, + pub text: Vec, +} + +fn err(e: serenity::Error) -> String { + match e { + serenity::Error::Http(h) if h.status_code().is_some_and(|s| s.as_u16() == 401) => + "디스코드가 이 봇 토큰을 받아들이지 않았습니다".into(), + e => format!("디스코드에 연결하지 못했습니다: {e}"), + } +} + +/// Check a token without storing it. +pub async fn check_token(token: &str) -> Result { + let http = Http::new(token.trim()); + let me = http.get_current_user().await.map_err(err)?; + let app = http.get_current_application_info().await.map_err(err)?; + Ok(TokenCheck { bot_tag: me.tag(), bot_id: me.id.to_string(), application_id: app.id.to_string(), + message_content: message_content_on(app.flags), invite_url: invite_url(app.id.get()) }) +} + +/// The servers the bot is in. +pub async fn guilds(token: &str) -> Result, String> { + let list = Http::new(token).get_guilds(None, Some(200)).await.map_err(err)?; + Ok(list.into_iter().map(|g| Named { id: g.id.to_string(), name: g.name }).collect()) +} + +/// A server's voice and text channels, in their server order. +pub async fn channels(token: &str, guild_id: u64) -> Result { + let mut list = Http::new(token).get_channels(GuildId::new(guild_id)).await.map_err(err)?; + list.sort_by_key(|c| c.position); + let pick = |kinds: &[ChannelType]| list.iter().filter(|c| kinds.contains(&c.kind)) + .map(|c| Named { id: c.id.to_string(), name: c.name.clone() }).collect(); + Ok(Channels { voice: pick(&[ChannelType::Voice, ChannelType::Stage]), text: pick(&[ChannelType::Text]) }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_invite_asks_for_the_bot_its_command_and_its_permissions() { + let url = invite_url(123456789012345678); + assert!(url.contains("client_id=123456789012345678")); + assert!(url.contains("scope=bot%20applications.commands")); + let bits: u64 = url.rsplit("permissions=").next().unwrap().parse().unwrap(); + let p = Permissions::from_bits_truncate(bits); + for need in [Permissions::CONNECT, Permissions::SPEAK, Permissions::SEND_MESSAGES, Permissions::MANAGE_CHANNELS] { + assert!(p.contains(need), "{need:?}"); + } + assert!(!p.contains(Permissions::ADMINISTRATOR)); + } + + #[test] + fn message_content_counts_when_full_or_limited() { + assert!(message_content_on(Some(ApplicationFlags::GATEWAY_MESSAGE_CONTENT))); + assert!(message_content_on(Some(ApplicationFlags::GATEWAY_MESSAGE_CONTENT_LIMITED))); + assert!(!message_content_on(Some(ApplicationFlags::GATEWAY_GUILD_MEMBERS))); + assert!(!message_content_on(None)); + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 348e663..f122976 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -1,6 +1,7 @@ //! Jarvis v2 app core (see `app/src/discord_core.spec.md`). pub mod log; +pub mod admin_api; pub mod calls; pub mod chat; pub mod control; @@ -8,6 +9,7 @@ pub mod conversation; pub mod dashboard; pub mod datadir; pub mod discord; +pub mod discord_setup; pub mod earcon; pub mod frames; pub mod logs; diff --git a/app/src/system.rs b/app/src/system.rs index 8947e91..9261412 100644 --- a/app/src/system.rs +++ b/app/src/system.rs @@ -46,6 +46,26 @@ pub async fn gpus() -> Vec { } } +/// The NVIDIA driver version (`581.57`), None without nvidia-smi. +pub async fn driver_version() -> Option { + let mut cmd = tokio::process::Command::new("nvidia-smi"); + cmd.args(["--query-gpu=driver_version", "--format=csv,noheader"]) + .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true); + #[cfg(windows)] + cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + match tokio::time::timeout(Duration::from_secs(2), cmd.output()).await { + Ok(Ok(o)) if o.status.success() => String::from_utf8_lossy(&o.stdout).lines().next().map(|l| l.trim().to_owned()), + _ => None, + } +} + +/// CUDA 13 needs driver 580 or newer (desktop-app.md, "PC 점검"). +pub const MIN_DRIVER_MAJOR: u32 = 580; + +pub fn driver_ok(version: &str) -> bool { + version.split('.').next().and_then(|m| m.parse::().ok()).is_some_and(|m| m >= MIN_DRIVER_MAJOR) +} + pub async fn usage() -> Usage { let (used, total) = memory_mb(); Usage { ram_used_mb: used, ram_total_mb: total, gpus: gpus().await } @@ -87,6 +107,12 @@ mod tests { vram_used_mb: 5120, vram_total_mb: 8151 }]); } + #[test] + fn drivers_from_580_run_cuda_13() { + assert!(driver_ok("581.57") && driver_ok("595.91.07") && driver_ok("580.0")); + assert!(!driver_ok("572.16") && !driver_ok("") && !driver_ok("abc")); + } + #[tokio::test] async fn usage_reads_this_machines_memory() { let u = usage().await; diff --git a/app/ui/app.js b/app/ui/app.js new file mode 100644 index 0000000..8c239af --- /dev/null +++ b/app/ui/app.js @@ -0,0 +1,493 @@ +// The management app's screens (app/src/admin.spec.md, "Screens"). Plain ES module, no build step: +// the Tauri shell and the development server load the same files. Every action goes through +// api(command, args), which the shell answers with AdminApi::call. + +const $ = (sel, el = document) => el.querySelector(sel); +const h = (tag, attrs = {}, ...kids) => { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (k === "class") el.className = v; + else if (k.startsWith("on")) el.addEventListener(k.slice(2), v); + else if (v === true) el.setAttribute(k, ""); + else if (v !== false && v != null) el.setAttribute(k, v); + } + for (const kid of kids.flat()) if (kid != null) el.append(kid instanceof Node ? kid : String(kid)); + return el; +}; + +const token = new URLSearchParams(location.hash.slice(1)).get("token"); +async function api(command, args = {}) { + if (window.__TAURI__) return window.__TAURI__.core.invoke("admin", { command, args }); + const r = await fetch(`/api/${command}`, { method: "POST", headers: { "x-admin-token": token || "" }, + body: JSON.stringify(args) }); + const out = await r.json(); + if (!out.ok) throw new Error(out.error); + return out.value; +} + +function toast(msg, bad = false) { + const t = $("#toast"); + t.textContent = msg; + t.className = bad ? "toast bad" : "toast"; + t.hidden = false; + clearTimeout(toast.timer); + toast.timer = setTimeout(() => (t.hidden = true), bad ? 6000 : 2500); +} +const fail = (e) => toast(e.message || String(e), true); +const gb = (b) => (b / 1e9).toFixed(0) + " GB"; + +const CHOICE = { + "call.mode": { wakeWord: "호출어로 부를 때만", addressed: "자비스에게 하는 말로 보이면", everything: "모든 말" }, + "response.policy": { first: "처음 대화만", inOrder: "순서대로", latest: "가장 최근 것", important: "중요한 것 먼저" }, +}; +const REASON = { busy: "다른 답을 하는 중", queue_full: "대기열이 가득 참", replaced: "더 새 요청이 대신함", + interrupted: "끼어들어 멈춤", lower_score: "다른 요청이 더 중요함", stopped: "정지 명령" }; +const STATE = { stopped: ["꺼짐", ""], starting: ["켜는 중", "warn"], running: ["실행 중", "ok"], + stopping: ["끄는 중", "warn"], failed: ["실패", "bad"] }; + +// ---- settings screens, built from the field list ------------------------------------------------ + +let FIELDS = null; +async function fields() { + return FIELDS ??= await api("settings_fields"); +} + +/** An input for one field; read() gives the value to save, or throws with a message. */ +function editor(f, value) { + const id = "f-" + f.path.replace(/\W/g, "-"); + let el, read; + const lines = (v) => (v || []).join("\n"); + const fromLines = (s) => s.split("\n").map((x) => x.trim()).filter(Boolean); + switch (f.type) { + case "bool": + el = h("input", { type: "checkbox", class: "switch", id }); + el.checked = !!value; + read = () => el.checked; + break; + case "int": case "number": + el = h("input", { type: "number", id, min: f.min, max: f.max, step: f.type === "int" ? 1 : "any", value }); + read = () => { + const n = Number(el.value); + if (el.value === "" || Number.isNaN(n) || n < f.min || n > f.max) throw new Error(`${f.label}: ${f.min}~${f.max}`); + return n; + }; + break; + case "nullableNumber": + el = h("input", { type: "number", id, step: "any", value: value ?? "" }); + read = () => (el.value === "" ? null : Number(el.value)); + break; + case "text": + el = f.max > 100 ? h("textarea", { id }, value ?? "") : h("input", { type: "text", id, value: value ?? "" }); + read = () => el.value.trim(); + break; + case "languageCode": + el = h("input", { type: "text", id, value: value ?? "", placeholder: "자동" }); + read = () => (el.value.trim() === "" ? null : el.value.trim()); + break; + case "textList": + el = h("textarea", { id, placeholder: f.nullable ? "비우면 음성 호출어와 같음" : "한 줄에 하나" }, lines(value)); + read = () => { + const v = fromLines(el.value); + return f.nullable && v.length === 0 ? null : v; + }; + break; + case "choice": + el = h("select", { id }, f.values.map((v) => h("option", { value: v, selected: v === value }, CHOICE[f.path]?.[v] ?? v))); + read = () => el.value; + break; + case "id": + if (f.path === "discord.guildId" || f.path === "discord.voiceChannelId") { + // A picker of the bot's servers and the chosen server's voice channels (the ID stays if the + // list cannot be read). + el = h("select", { id, "data-picker": f.path }, h("option", { value: value ?? "" }, value ?? "선택 안 함")); + read = () => el.value || null; + break; + } + el = h("input", { type: "text", id, value: value ?? "", placeholder: "디스코드 ID" }); + read = () => (el.value.trim() === "" ? null : el.value.trim()); + break; + case "idList": + el = h("textarea", { id, placeholder: "디스코드 사용자 ID, 한 줄에 하나" }, lines(value)); + read = () => fromLines(el.value); + break; + case "idNumberMap": + el = h("textarea", { id, placeholder: "사용자ID=우선순위" }, + Object.entries(value || {}).map(([k, v]) => `${k}=${v}`).join("\n")); + read = () => Object.fromEntries(fromLines(el.value).map((l) => { + const [k, v] = l.split("=").map((x) => x.trim()); + if (!k || v === undefined || Number.isNaN(Number(v))) throw new Error(`${f.label}: "사용자ID=숫자" 형식`); + return [k, Number(v)]; + })); + break; + case "chatChannels": + return chatChannelsEditor(f, value); + default: + el = h("span", { class: "muted" }, JSON.stringify(value)); + read = () => value; + } + return { el: h("div", {}, el, f.hint ? h("div", { class: "hint" }, f.hint) : null), read }; +} + +function chatChannelsEditor(f, value) { + const flags = [["read", "읽기", true], ["send", "보내기", true], ["edit", "수정", true], ["react", "반응", true], + ["delete", "삭제", false], ["pin", "고정", false]]; + const body = h("tbody"); + const addRow = (c = {}) => { + const tr = h("tr", {}, + h("td", {}, h("input", { type: "text", value: c.id ?? "", placeholder: "채널 ID", "data-k": "id" })), + h("td", {}, h("input", { type: "text", value: c.name ?? "", placeholder: "이름", "data-k": "name" })), + h("td", {}, h("input", { type: "text", value: c.description ?? "", placeholder: "무엇에 쓰는 채널인지", "data-k": "description" })), + flags.map(([k, , d]) => { + const box = h("input", { type: "checkbox", "data-k": k }); + box.checked = c[k] ?? d; + return h("td", {}, box); + }), + h("td", {}, h("select", { "data-k": "answer" }, + h("option", { value: "wakeWord", selected: (c.answer ?? "wakeWord") === "wakeWord" }, "호출어"), + h("option", { value: "everything", selected: c.answer === "everything" }, "모든 글"))), + h("td", {}, h("button", { class: "btn", onclick: () => tr.remove() }, "삭제"))); + body.append(tr); + }; + (value || []).forEach(addRow); + const table = h("table", {}, h("thead", {}, h("tr", {}, ["ID", "이름", "설명", ...flags.map((x) => x[1]), "대답", ""] + .map((t) => h("th", {}, t)))), body); + const read = () => [...body.rows].map((tr) => { + const c = {}; + for (const el of tr.querySelectorAll("[data-k]")) c[el.dataset.k] = el.type === "checkbox" ? el.checked : el.value.trim(); + return c; + }); + return { el: h("div", {}, table, h("button", { class: "btn", onclick: () => addRow() }, "채널 추가")), read, wide: true }; +} + +async function settingsScreen(screen, title, extra) { + const [all, view] = await Promise.all([fields(), api("settings_view")]); + const list = all.filter((f) => f.screen === screen); + const editors = list.map((f) => ({ f, ...editor(f, view[f.path]) })); + const save = async () => { + try { + const changes = {}; + for (const { f, read } of editors) { + const v = read(); + if (JSON.stringify(v) !== JSON.stringify(view[f.path])) changes[f.path] = v; + } + if (!Object.keys(changes).length) return toast("바뀐 것이 없습니다"); + const r = await api("settings_apply", { changes }); + Object.assign(view, changes); + toast(r.restartNeeded ? "저장했습니다. 다시 시작하면 적용됩니다." : "저장했습니다."); + } catch (e) { fail(e); } + }; + const view_ = h("div", {}, h("h1", {}, title), extra, + editors.map(({ f, el, wide }) => wide ? h("div", { class: "card" }, h("h2", {}, f.label), el) + : h("div", { class: "field" }, h("label", { for: "f-" + f.path.replace(/\W/g, "-") }, f.label), el)), + h("div", { class: "savebar" }, h("button", { class: "btn primary", onclick: save }, "저장"))); + fillPickers(view_, view); + return view_; +} + +async function fillPickers(root, view) { + const g = root.querySelector('[data-picker="discord.guildId"]'); + const v = root.querySelector('[data-picker="discord.voiceChannelId"]'); + if (!g) return; + const opts = (sel, list, current, none) => { + sel.replaceChildren(h("option", { value: "" }, none), + ...list.map((x) => h("option", { value: x.id, selected: x.id === current }, x.name))); + if (current && !list.some((x) => x.id === current)) sel.append(h("option", { value: current, selected: true }, current)); + }; + const loadVoice = async () => { + if (!v) return; + if (!g.value) return opts(v, [], null, "자동으로 들어가지 않음"); + try { opts(v, (await api("discord_channels", { guildId: g.value })).voice, view["discord.voiceChannelId"], "자동으로 들어가지 않음"); } + catch (e) { /* the ID stays as it was */ } + }; + try { opts(g, await api("discord_guilds"), view["discord.guildId"], "선택 안 함"); } catch (e) { return; } + g.addEventListener("change", loadVoice); + loadVoice(); +} + +async function tokenCard() { + const st = await api("token_status"); + const input = h("input", { type: "password", placeholder: "새 봇 토큰", autocomplete: "off" }); + const out = h("div", { class: "small muted" }); + return h("div", { class: "card" }, h("h2", {}, "봇 토큰"), + h("div", { class: "row" }, h("span", {}, st.set ? st.masked : "저장된 토큰 없음"), input, + h("button", { class: "btn", onclick: async () => { + try { + const c = await api("token_check", { token: input.value }); + await api("token_save", { token: input.value }); + input.value = ""; + out.textContent = `${c.botTag} 저장함. Message Content 권한: ${c.messageContent ? "켜짐" : "꺼짐"}`; + } catch (e) { fail(e); } + } }, "확인 후 저장")), out); +} + +// ---- dashboard ---------------------------------------------------------------------------------- + +/** The header with the start/stop buttons; rebuilt only when the state changes, so a click is not + * lost to the once-a-second refresh of the cards. */ +function dashboardHeader(d) { + const [label, cls] = STATE[d.state] ?? [d.state, ""]; + const act = (cmd, text, primary) => h("button", { class: "btn" + (primary ? " primary" : ""), onclick: async (e) => { + e.target.disabled = true; + try { await api(cmd); } catch (err) { fail(err); } + refresh(); + } }, text); + return h("div", {}, + h("div", { class: "row", style: "justify-content:space-between;margin-bottom:16px" }, + h("h1", { style: "margin:0" }, "대시보드"), + h("div", { class: "row" }, h("span", { class: "badge " + cls }, label), + d.state === "running" ? [act("service_restart", "다시 시작"), act("service_stop", "정지")] + : act("service_start", "시작", true))), + d.error ? h("div", { class: "card", style: "border-color:var(--bad);margin-bottom:12px" }, d.error) : null); +} + +function dashboardBody(d) { + const med = d.latency?.median ?? {}; + const s = (ms) => (ms == null ? "–" : (ms / 1000).toFixed(2) + "초"); + const w = d.worker; + return h("div", {}, + h("div", { class: "grid" }, + h("div", { class: "card" }, h("h2", {}, "연결"), h("div", { class: "kv" }, + h("span", { class: "k" }, "디스코드"), h("span", {}, d.discord ?? "연결 안 됨"), + h("span", { class: "k" }, "음성 워커"), h("span", {}, w ? (w.connected ? "연결됨" : "연결 안 됨") : "–"), + h("span", { class: "k" }, "STT / TTS"), h("span", {}, w ? `${w.sttReady ? "준비" : "–"} / ${w.ttsReady ? "준비" : "–"}` : "–"), + h("span", { class: "k" }, "워커 재시작"), h("span", {}, w?.restarts ?? "–"))), + h("div", { class: "card" }, h("h2", {}, "음성 채널"), + h("div", {}, d.voiceChannel ? `채널 ${d.voiceChannel}` : "들어가 있지 않음"), + h("div", { class: "small muted", style: "margin-top:6px" }, + (d.voiceMembers || []).map((m) => m.name).join(", ") || "참가자 없음")), + h("div", { class: "card" }, h("h2", {}, "응답 시간 (중앙값)"), h("div", { class: "kv" }, + h("span", { class: "k" }, "말 끝 → 받아 적기"), h("span", {}, s(med.finalMs)), + h("span", { class: "k" }, "두뇌"), h("span", {}, s(med.brainMs)), + h("span", { class: "k" }, "목소리"), h("span", {}, s(med.voiceMs)), + h("span", { class: "k" }, "전체"), h("span", {}, s(med.totalMs)))), + h("div", { class: "card" }, h("h2", {}, "시스템"), h("div", { class: "kv" }, + h("span", { class: "k" }, "RAM"), h("span", {}, d.system?.ramTotalMb ? `${(d.system.ramUsedMb / 1024).toFixed(1)} / ${(d.system.ramTotalMb / 1024).toFixed(1)} GB` : "–"), + (d.system?.gpus || []).flatMap((g) => [h("span", { class: "k" }, g.name.replace("NVIDIA GeForce ", "")), + h("span", {}, `${g.usePercent}% · VRAM ${(g.vramUsedMb / 1024).toFixed(1)} / ${(g.vramTotalMb / 1024).toFixed(1)} GB`)]), + h("span", { class: "k" }, "성능 단계"), h("span", { class: "muted" }, d.performance ?? "평소")))), + h("div", { class: "grid" }, + h("div", { class: "card" }, h("h2", {}, "실시간 자막"), h("div", { class: "captions" }, + (d.captions || []).length ? d.captions.map((c) => h("div", { class: "cap" + (c.final ? "" : " partial") }, h("b", {}, c.name), c.text)) + : h("div", { class: "muted" }, "아직 없음"))), + h("div", { class: "card" }, h("h2", {}, "놓친 요청"), (d.missed || []).length + ? h("table", {}, h("tbody", {}, d.missed.map((m) => h("tr", {}, h("td", {}, m.speaker), + h("td", {}, REASON[m.reason] ?? m.reason), h("td", { class: "muted" }, `${m.secondsAgo}초 전`))))) + : h("div", { class: "muted" }, "없음")))); +} + +// ---- logs --------------------------------------------------------------------------------------- + +const TABS = { all: "전체", app: "앱", discord: "디스코드", chat: "채팅", conversation: "대화", worker: "워커", + stt: "STT", llm: "LLM", tts: "TTS", browser: "브라우저", capture: "화면 캡처", game: "게임 감지" }; +function logsScreen() { + const tab = h("select", {}, Object.entries(TABS).map(([v, t]) => h("option", { value: v }, t))); + const level = h("select", {}, [["debug", "디버그 이상"], ["info", "정보 이상"], ["warn", "경고 이상"], ["error", "오류만"]] + .map(([v, t]) => h("option", { value: v }, t))); + const find = h("input", { type: "text", placeholder: "찾기", style: "max-width:220px" }); + const pause = h("input", { type: "checkbox", class: "switch" }); + const box = h("div", { class: "logs" }); + let last = null; + const reload = () => { box.textContent = ""; last = null; poll(); }; + async function poll() { + if (pause.checked) return; + try { + const lines = await api("logs_query", { tab: tab.value, level: level.value, find: find.value, after: last, limit: 500 }); + const stick = box.scrollTop + box.clientHeight >= box.scrollHeight - 20; + for (const l of lines) { + const d = new Date(l.at_ms), p2 = (n) => String(n).padStart(2, "0"); + const t = `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`; + box.append(h("div", { class: "log " + l.level }, `${t} ${l.level.toUpperCase().padEnd(5)} [${l.tab}] ${l.text}`)); + last = l.seq; + } + while (box.childElementCount > 5000) box.firstChild.remove(); + if (stick) box.scrollTop = box.scrollHeight; + } catch (e) { /* the next tick tries again */ } + } + for (const el of [tab, level]) el.addEventListener("change", reload); + find.addEventListener("input", () => { clearTimeout(find.t); find.t = setTimeout(reload, 300); }); + const today = new Date().toISOString().slice(0, 10); + const from = h("input", { type: "date", value: today }), to = h("input", { type: "date", value: today }); + const view = h("div", {}, h("h1", {}, "로그"), + h("div", { class: "row", style: "margin-bottom:10px" }, tab, level, find, h("label", { class: "row small muted" }, pause, "일시정지"), + h("button", { class: "btn", onclick: async () => { + try { + const r = await api("logs_error_report"); + if (!r.report) return toast("기록된 오류가 없습니다"); + await navigator.clipboard.writeText(r.report); + toast(r.tooLongForDiscord ? "복사했습니다. 디스코드 메시지 한도(2,000자)를 넘으니 파일로 내보내세요." : "최근 오류를 복사했습니다."); + } catch (e) { fail(e); } + } }, "최근 오류 복사")), + box, + h("div", { class: "row", style: "margin-top:10px" }, h("span", { class: "muted" }, "내보내기"), from, "~", to, + h("button", { class: "btn", onclick: async () => { + try { + const r = await api("logs_export", { from: from.value, to: to.value }); + toast(`${r.path}에 저장했습니다${r.droppedLines ? ` (10MB를 넘어 오래된 ${r.droppedLines}줄은 뺐습니다)` : ""}`); + } catch (e) { fail(e); } + } }, "zip으로 저장"))); + reload(); + return { view, tick: poll }; +} + +// ---- navigation --------------------------------------------------------------------------------- + +let current = null, ticker = null; +let headerKey = null; +async function refresh() { + if (current !== "dashboard") return; + try { + const d = await api("dashboard"); + const screen = $("#screen"); + let head = $("#dash-head"), body = $("#dash-body"); + if (!head || !body) { + head = h("div", { id: "dash-head" }); body = h("div", { id: "dash-body" }); + screen.replaceChildren(head, body); + headerKey = null; + } + const key = d.state + "|" + (d.error ?? ""); + if (key !== headerKey) { head.replaceChildren(dashboardHeader(d)); headerKey = key; } + body.replaceChildren(dashboardBody(d)); + } catch (e) { fail(e); } +} +async function show(name) { + current = name; + clearInterval(ticker); + for (const b of document.querySelectorAll(".nav")) b.classList.toggle("on", b.dataset.screen === name); + const screen = $("#screen"); + try { + if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; } + if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; } + const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델" }; + const extra = name === "bot" ? await tokenCard() : null; + screen.replaceChildren(await settingsScreen(name, titles[name], extra)); + } catch (e) { fail(e); } +} + +// ---- first-run wizard --------------------------------------------------------------------------- + +const WIZ = ["데이터 폴더", "PC 점검", "모델", "디스코드 봇", "서버·채널", "호출어", "완료"]; +async function wizard(status) { + const root = $("#wizard"); + let step = status.dataDir ? 3 : 0; + const s = {}; + const nav = (back, next, nextLabel = "다음") => h("div", { class: "nav-row" }, + back ? h("button", { class: "btn", onclick: () => go(step - 1) }, "이전") : h("span"), + next ? h("button", { class: "btn primary", onclick: next }, nextLabel) : h("span")); + async function go(n) { + step = n; + const card = h("div", { class: "card" }); + root.replaceChildren(h("h1", {}, "Jarvis 처음 설정"), + h("div", { class: "steps" }, WIZ.map((t, i) => h("span", { class: "step" + (i === step ? " on" : i < step ? " done" : "") }, t))), card); + try { card.append(...(await STEPS[step](card)).filter((x) => x != null)); } catch (e) { fail(e); } + } + const STEPS = [ + async () => { + const path = h("input", { type: "text", placeholder: "예: D:\\JarvisBot", value: s.path ?? "" }); + const info = h("p", { class: "small" }); + return [h("h2", {}, "데이터를 둘 폴더"), + h("p", {}, "모델, 대화 기록, 로그가 모두 이 폴더 안에 저장됩니다. 남은 용량은 200GB 이상을 권장합니다."), + h("div", { class: "row" }, path, h("button", { class: "btn", onclick: async () => { + try { + const c = await api("folder_check", { path: path.value }); + info.textContent = `남은 용량 ${gb(c.freeBytes)}` + (c.enough ? "" : ` · 권장 ${gb(c.recommendedBytes)}보다 적습니다`); + info.style.color = c.enough ? "" : "var(--warn)"; + } catch (e) { fail(e); } + } }, "용량 확인")), info, + nav(false, async () => { + try { await api("folder_choose", { path: path.value }); s.path = path.value; go(1); } catch (e) { fail(e); } + }, "이 폴더 사용")]; + }, + async () => { + const p = await api("pc_check"); + const g = p.gpus[0]; + return [h("h2", {}, "PC 점검"), h("div", { class: "kv" }, + h("span", { class: "k" }, "GPU"), h("span", {}, g ? `${g.name} (VRAM ${(g.vramTotalMb / 1024).toFixed(0)} GB)` : "NVIDIA GPU를 찾지 못했습니다"), + h("span", { class: "k" }, "드라이버"), h("span", {}, p.driver ? `${p.driver} ` : "–", + p.driver ? h("span", { class: "badge " + (p.driverOk ? "ok" : "bad") }, p.driverOk ? "정상" : `${p.minDriver} 이상 필요`) : null), + h("span", { class: "k" }, "RAM"), h("span", {}, p.ramTotalMb ? `${(p.ramTotalMb / 1024).toFixed(0)} GB` : "–"), + h("span", { class: "k" }, "CPU"), h("span", {}, `${p.cpuThreads ?? "–"} 스레드`), + h("span", { class: "k" }, "디스크 남은 용량"), h("span", {}, p.diskFreeBytes != null ? gb(p.diskFreeBytes) : "–")), + p.driver && !p.driverOk ? h("p", {}, "NVIDIA 드라이버를 최신으로 올려 주세요: ", h("a", { href: "https://www.nvidia.com/drivers", target: "_blank" }, "nvidia.com/drivers")) : null, + nav(true, () => go(2))]; + }, + async () => [h("h2", {}, "받을 모델"), + h("p", {}, "대화 모델 Qwen3.6-35B-A3B(약 23GB)와 받아 적기(Whisper)·음성(MeloTTS) 모델을 받습니다. 고를 것은 없고, 설치가 끝나면 이 PC에 맞는 설정을 스스로 정합니다."), + h("p", { class: "muted small" }, "자동 설치는 다음 업데이트에서 이 단계에 들어옵니다."), nav(true, () => go(3))], + async () => { + const input = h("input", { type: "password", placeholder: "디스코드 봇 토큰", autocomplete: "off" }); + const out = h("div"); + return [h("h2", {}, "디스코드 봇 연결"), + h("p", {}, "Discord Developer Portal의 Bot 탭에서 토큰을 복사해 붙여 넣으세요. 토큰은 이 PC의 Windows 계정으로 암호화해 저장합니다."), + h("div", { class: "row" }, input, h("button", { class: "btn", onclick: async () => { + try { + const c = await api("token_check", { token: input.value }); + s.token = input.value; s.check = c; + out.replaceChildren(h("div", { class: "kv", style: "margin-top:12px" }, + h("span", { class: "k" }, "봇"), h("span", {}, c.botTag), + h("span", { class: "k" }, "Message Content"), h("span", {}, h("span", { class: "badge " + (c.messageContent ? "ok" : "bad") }, + c.messageContent ? "켜짐" : "꺼짐: Developer Portal > Bot > Message Content Intent를 켜 주세요")), + h("span", { class: "k" }, "초대 링크"), h("a", { href: c.inviteUrl, target: "_blank" }, "서버에 봇 초대하기"))); + } catch (e) { fail(e); } + } }, "연결 확인")), out, + nav(true, async () => { + if (!s.check) return toast("먼저 연결을 확인해 주세요", true); + try { await api("token_save", { token: s.token }); go(4); } catch (e) { fail(e); } + })]; + }, + async () => { + const guilds = await api("discord_guilds"); + const g = h("select", {}, h("option", { value: "" }, "서버 선택"), guilds.map((x) => h("option", { value: x.id }, x.name))); + const v = h("select", {}, h("option", { value: "" }, "자동으로 들어가지 않음")); + g.addEventListener("change", async () => { + v.replaceChildren(h("option", { value: "" }, "자동으로 들어가지 않음")); + if (!g.value) return; + try { + const ch = await api("discord_channels", { guildId: g.value }); + v.append(...ch.voice.map((x) => h("option", { value: x.id }, x.name))); + } catch (e) { fail(e); } + }); + return [h("h2", {}, "서버와 음성 채널"), + guilds.length ? null : h("p", {}, "봇이 들어가 있는 서버가 없습니다. 이전 단계의 초대 링크로 먼저 초대해 주세요."), + h("div", { class: "field" }, h("label", {}, "서버"), g), + h("div", { class: "field" }, h("label", {}, "자동으로 들어갈 음성 채널"), v), + h("p", { class: "small muted" }, "AI 채팅 채널은 나중에 \"채팅 채널\" 화면에서 등록할 수 있습니다."), + nav(true, async () => { + if (!g.value) return toast("서버를 골라 주세요", true); + try { await api("settings_apply", { changes: { "discord.guildId": g.value, "discord.voiceChannelId": v.value || null } }); go(5); } + catch (e) { fail(e); } + })]; + }, + async () => { + const view = await api("settings_view"); + const words = h("textarea", {}, (view["voice.wakeWords"] || []).join("\n")); + return [h("h2", {}, "호출어"), h("p", {}, "이 말로 부르면 대답합니다. 한 줄에 하나씩 적어 주세요."), words, + nav(true, async () => { + const list = words.value.split("\n").map((x) => x.trim()).filter(Boolean); + if (!list.length) return toast("호출어를 하나 이상 적어 주세요", true); + try { await api("settings_apply", { changes: { "voice.wakeWords": list } }); go(6); } catch (e) { fail(e); } + })]; + }, + async () => [h("h2", {}, "준비됐습니다"), + h("p", {}, "시작하면 봇이 디스코드에 연결되고, 처음 시작할 때 서버에 슬래시 명령을 등록합니다."), + nav(true, async () => { + root.hidden = true; + await start(); + try { await api("service_start"); } catch (e) { fail(e); } + refresh(); + }, "시작")], + ]; + root.hidden = false; + $("#main").hidden = true; + go(step); +} + +async function start() { + const status = await api("app_status"); + $("#version").textContent = "v" + status.version; + if (status.firstRun && !start.done) { start.done = true; return wizard(status); } + $("#wizard").hidden = true; + $("#main").hidden = false; + for (const b of document.querySelectorAll(".nav")) b.onclick = () => show(b.dataset.screen); + show("dashboard"); +} +start().catch(fail); diff --git a/app/ui/index.html b/app/ui/index.html new file mode 100644 index 0000000..fe2611c --- /dev/null +++ b/app/ui/index.html @@ -0,0 +1,28 @@ + + + + + +Jarvis 관리 + + + + + + + + + diff --git a/app/ui/style.css b/app/ui/style.css new file mode 100644 index 0000000..bcb80e5 --- /dev/null +++ b/app/ui/style.css @@ -0,0 +1,75 @@ +/* Dark admin theme after DESIGN.md (near-black canvas, charcoal panels, hairline borders, one accent). */ +:root { + --canvas: #08090a; --s1: #0f1011; --s2: #141516; --s3: #1b1c1e; + --line: #23252a; --line2: #34343a; + --ink: #f7f8f8; --ink2: #d0d6e0; --ink3: #8a8f98; --ink4: #62666d; + --accent: #5e6ad2; --accent2: #828fff; --ok: #27a644; --warn: #d7a03a; --bad: #e5484d; + font-family: "Pretendard", "Malgun Gothic", "Segoe UI", system-ui, sans-serif; + color: var(--ink); background: var(--canvas); font-size: 14px; +} +* { box-sizing: border-box; } +[hidden] { display: none !important; } +body { margin: 0; min-height: 100vh; } +button, input, select, textarea { font: inherit; color: inherit; } +.layout { display: grid; grid-template-columns: 200px 1fr; min-height: 100vh; } +.side { background: var(--s1); border-right: 1px solid var(--line); padding: 16px 10px; display: flex; flex-direction: column; gap: 2px; } +.brand { font-weight: 600; font-size: 18px; letter-spacing: -0.3px; padding: 6px 10px 16px; } +.nav { text-align: left; background: none; border: 0; padding: 8px 10px; border-radius: 6px; color: var(--ink2); cursor: pointer; } +.nav:hover { background: var(--s2); } +.nav.on { background: var(--s3); color: var(--ink); } +.side-foot { margin-top: auto; color: var(--ink4); font-size: 12px; padding: 8px 10px; } +.screen { padding: 28px 32px; max-width: 1100px; } +h1 { font-size: 24px; font-weight: 600; letter-spacing: -0.4px; margin: 0 0 18px; } +h2 { font-size: 15px; font-weight: 600; margin: 0 0 10px; color: var(--ink2); } +.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; margin-bottom: 12px; } +.card { background: var(--s1); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; } +.muted { color: var(--ink3); } +.small { font-size: 12px; } +.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.btn { background: var(--s3); border: 1px solid var(--line2); border-radius: 7px; padding: 7px 14px; cursor: pointer; } +.btn:hover { border-color: var(--ink4); } +.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; } +.btn.primary:hover { background: var(--accent2); } +.btn:disabled { opacity: .45; cursor: default; } +.badge { display: inline-block; border-radius: 999px; padding: 2px 10px; font-size: 12px; border: 1px solid var(--line2); } +.badge.ok { color: var(--ok); border-color: #1f5f30; } +.badge.warn { color: var(--warn); border-color: #6b5222; } +.badge.bad { color: var(--bad); border-color: #6e2a2c; } +.kv { display: grid; grid-template-columns: max-content 1fr; gap: 6px 14px; } +.kv .k { color: var(--ink3); } +.field { display: grid; grid-template-columns: 260px 1fr; gap: 14px; padding: 12px 0; border-bottom: 1px solid var(--line); align-items: start; } +.field label { color: var(--ink2); padding-top: 6px; } +.field .hint { color: var(--ink4); font-size: 12px; margin-top: 4px; } +input[type=text], input[type=number], input[type=password], input[type=date], select, textarea { + background: var(--s2); border: 1px solid var(--line2); border-radius: 7px; padding: 7px 10px; width: 100%; max-width: 520px; outline: none; } +input:focus, select:focus, textarea:focus { border-color: var(--accent); } +textarea { min-height: 70px; resize: vertical; } +.switch { appearance: none; width: 38px; height: 22px; border-radius: 999px; background: var(--line2); position: relative; cursor: pointer; margin-top: 4px; } +.switch:checked { background: var(--accent); } +.switch::after { content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%; background: #fff; transition: left .12s; } +.switch:checked::after { left: 19px; } +table { width: 100%; border-collapse: collapse; } +th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; } +th { color: var(--ink3); font-weight: 500; font-size: 12px; } +.captions { max-height: 260px; overflow: auto; display: flex; flex-direction: column; gap: 4px; } +.cap { color: var(--ink2); } +.cap.partial { color: var(--ink4); font-style: italic; } +.cap b { color: var(--ink); font-weight: 500; margin-right: 6px; } +.logs { background: var(--s1); border: 1px solid var(--line); border-radius: 10px; height: 60vh; overflow: auto; font-family: ui-monospace, Consolas, monospace; font-size: 12px; padding: 8px 10px; } +.log { white-space: pre-wrap; word-break: break-all; padding: 1px 0; } +.log.error { color: var(--bad); } .log.warn { color: var(--warn); } .log.debug { color: var(--ink4); } +.savebar { position: sticky; bottom: 0; background: var(--canvas); padding: 14px 0; display: flex; gap: 10px; align-items: center; } +.toast { position: fixed; right: 20px; bottom: 20px; background: var(--s3); border: 1px solid var(--line2); border-radius: 8px; padding: 10px 14px; max-width: 420px; } +.toast.bad { border-color: var(--bad); } +.wizard { max-width: 720px; margin: 48px auto; padding: 0 20px; } +.steps { display: flex; gap: 6px; margin-bottom: 22px; flex-wrap: wrap; } +.step { font-size: 12px; color: var(--ink4); border: 1px solid var(--line); border-radius: 999px; padding: 3px 10px; } +.step.on { color: var(--ink); border-color: var(--accent); } +.step.done { color: var(--ok); border-color: #1f5f30; } +.wizard .card { padding: 22px 24px; } +.wizard p { color: var(--ink2); line-height: 1.6; } +.nav-row { display: flex; justify-content: space-between; margin-top: 20px; } +a { color: var(--accent2); } +.row > select, .row > input[type=date] { width: auto; } +input[type=date] { color-scheme: dark; } +th, .btn { white-space: nowrap; } diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index b33e783..f364697 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -9,7 +9,7 @@ | M2 | 디스코드 음성 코어 이전 | v1 봇 기능을 새 앱 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기). 구현과 테스트 완료(2026-11-11): `app/`(Rust, serenity + songbird), 스펙은 [discord_core.spec.md](../../app/src/discord_core.spec.md). 처음 Electron + TypeScript로 만든 것을 사용자 요청으로 Rust로 다시 씀. 앱이 음성 워커를 띄우고(실행마다 새 토큰, 죽으면 다시 시작) 연결이 끊기면 다시 붙습니다. 음성 채널에 들어갈 때마다 전사 고지를 채널 채팅에 올립니다. songbird 0.6.1의 DAVE 수신 해독이 조각 3분의 1가량을 깨뜨려서(20ms마다 음이 바뀌는 시험 신호로 확인, 보내기는 정상) 받은 패킷의 순서 맞추기와 Opus 해독은 앱이 직접 합니다. 실제 디스코드에서 봇 두 개로 확인(이 서버의 RTX 5050): 다른 봇이 채널에 튼 녹음 문장 5개를 모두 받아 적었고(문자 오류율 3개 0%, "기록해"를 "비록해"로 적은 1개 5%, "일곱 시"를 "7시"로 적은 1개 12.5%), 말이 끝난 뒤 최종 전사까지 0.71~0.90초였습니다. 자비스가 말한 문장을 상대 봇이 받아 다시 전사하니 오류율 3.4%였고, 정지 명령 뒤 0.08초 만에 소리가 끊겼습니다. 채팅 채널은 새 글 받기, 최근 글 읽기, 보내기(2,000자 넘으면 나눔, 아무도 호출하지 않음)가 됩니다. 사람이 직접 말한 소리와 게임PC(Windows) 빌드는 아직 확인하지 않았고, 음성으로 "자비스, 멈춰"는 호출 판정이 필요해 M4에서 합니다 | | M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 실패 고침(2026-11-11): 엔진의 정해진 한국어 날씨 경로를 뺌(평가의 도구 실행기를 거치지 않았고, 사용자가 말한 위치를 쓰지 못함, 큰 모델은 도구 결과를 한국어 한 문장으로 그대로 답함). 날씨 도구와 대화 지시문은 사용자가 대화나 기억에서 말한 위치를 넣고, 자동으로 잡힌 위치는 옮겨 적지 않게 함. "구, 시, 나라" 이름이 안 찾아지면 넓은 지역으로 다시 찾음. 계획 단계에 현재 시간·위치 줄을 주어, 위치를 모를 때만 기억에서 사용자 위치를 먼저 찾게 함. 같은 도구 반복 제한이 이전 답변의 호출까지 세어 사용자가 다시 해 달라고 해도 막던 버그를 고침. 기억 검색어 지시문에서 평가와 같은 문장의 예시를 바꾸고 현재 맥락 블록을 예시 뒤로 옮김(위치를 모를 때는 여전히 묻는지 보는 평가 추가, qwen2.5:7b는 바꾸기 전에도 묻지 않음). 평가 전체 202개 통과, 4개 실패, 9분 3초. 이 전체 실행의 날씨 실패 1개는 장소를 말하지 않은 "what's the weather this week"에 자동으로 잡힌 위치(`Hackney, England, UK`)를 인자로 옮겨 적은 것으로, 그 뒤 날씨 도구와 지시문을 사용자가 말한 위치만 넣도록 좁혀 고침. 고친 뒤 날씨 평가 12개를 따로 3번 돌려 36번 중 34번 통과(이 평가는 3번 모두 통과, 실패 2번은 날씨 한 번 부르기 평가가 파리 날씨 답에 도시 이름을 다시 말하지 않은 것). 전체 실행의 나머지 실패는 지식 그래프 갈래 분류 1개(모델이 "사용자가 물었다"를 사용자 사실로 하나 더 남김, 지시문을 두 번 고쳐도 같아 되돌림, v2는 v1 장기 기억을 쓰지 않음)와 다시 돌리면 통과하는 2개(유명인 두 턴 대화, 최근 일기 반영) | | M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트. 1단계 완료(2026-11-11): 앱의 호출 판정 `app/src/calls.rs`와 응답 정책 `app/src/policy.rs`(스펙 [conversation.spec.md](../../app/src/conversation.spec.md)), 설정 `call`·`response`. 비슷한 발음은 유니코드 NFKD로 한글을 자모로 나눠 편집 거리로 판단(기본 0.2: "자비즈"는 호출, "서비스"는 아님). 정책은 말이 끝난 시각 순서, 먼저 끝난 말의 전사 대기(최대 0.8초), 끼어들기, 놓친 요청 사유를 가짜 시각으로 시험함. 2단계 완료(2026-11-11): 대화 루프 `app/src/conversation.rs`가 최종 전사를 호출 판정과 응답 정책에 넣고, 정책의 결정대로 두뇌에 답을 요청해(`reply`, 답은 워커가 같은 id로 읽음) 앱의 재생 대기열에서 재생, 끼어들 때는 그 답만 멈춤, "자비스 멈춰"는 모든 말을 멈춤, 놓친 요청은 글 없이 최근 100개를 남김. 두뇌의 두 판정 `src/voice_worker/judges.py`(봇에게 하는 말인지, 중요도 순위)는 답과 따로 돌아 기다리지 않음. 평가 `evals/test_voice_judges.py` 12개를 qwen2.5:7b에서 모두 통과. 답을 만드는 중에 멈춘 요청은 말하지 않음. 실제 Python 워커(가짜 두뇌)와 앱의 통합 시험 통과. 3단계 완료(2026-11-11): 채팅 채널 호출. 채널마다 `answer`(호출어로 부를 때만 / 모든 메시지에 대답), 채팅 호출어(`call.chatWakeWords`, 없으면 음성과 같음)와 지정한 사람 설정은 음성과 같이 씀. 답은 같은 채널에 원래 메시지의 답글로 올리고 아무도 부르지 않음. 다른 봇의 글과 보내기가 꺼진 채널에는 답하지 않음. 음성 대화 순서와는 따로 감(워커가 음성 답과 채팅 답을 따로 써서 다른 사람의 채팅 답 때문에 음성 답이 기다리지 않음. 한 사람의 답은 물은 순서대로 하나씩 씀. 두 답의 LLM 호출이 동시에 돌려면 Strata를 `--parallel 2`로 띄움, 앱이 Strata를 띄우는 M5 전까지). 5분 넘게 늦은 채팅 답은 올리지 않음. 실제 디스코드 시험과 지연 측정은 4단계. 4단계 첫 측정(2026-11-12): 앱의 실제 서비스(`start_services`: 대화 루프, 응답 정책, 워커, 두뇌)를 게임PC Strata(`--parallel 2`)에 붙이고, 봇 두 개로 질문 5개를 2번씩 말해 잼(`app/tests/live_round_trip.rs`). 10개 모두 소리로 답했고, 말 끝부터 첫 소리까지 중앙값 3.5초(최소 2.8초, 날씨 도구 8.6초). 9명이 동시에 말하는 부하(워커의 두 번째 연결로 녹음 문장 9개를 실시간으로 넣음, 그동안 최종 전사 259개)에서는 중앙값 4.4초, 최종 전사가 0.6~0.9초에서 0.8~1.8초로 늦어졌고 1번은 "기분"을 "딥"으로 잘못 들어 날씨 도구를 불러 18.8초가 걸림. 짧은 답의 시간은 최종 전사 0.65~0.85초, 두뇌 2.0~2.9초(도구 고르기 0.42초, 계획 0.5초, 답 호출의 지시문 약 4,300토큰 읽기 1.1초와 생성), 재생 시작과 전달 약 0.4초. Strata의 Qwen3.6 엔진은 지시문 앞부분 재사용을 하지 않아(`--prompt-cache-every`는 "이 엔진의 옵션이 아님"으로 무시됨, 같은 대화를 그대로 이어 갈 때만 재사용) 매 호출을 처음부터 읽음. 생성은 0.2~0.5초라 문장 단위로 흘려도 짧은 답은 거의 빨라지지 않음. 1.5초 기준은 아직 못 맞춤. 같은 시험에서 찾아 고친 것: v1 TTS 설정(영어 전용 Piper) 때문에 한국어 질문에 영어로 답하던 것(v2 두뇌는 묻는 사람의 언어로 답함), 호출어 뒤에 쉬면 "자비스"만 따로 끊겨 그 이름에만 답하고 이어진 질문은 무시하던 것(이제 같은 사람이 이어서 하는 말과 합침, `call.followUpMs`). 4단계 지연 줄이기(사용자 결정, 2026-11-12): 부름을 받으면 "띠링" 효과음(앱이 만든 0.3초 소리, `call.earcon`, 이름만 부르고 쉬면 그때 바로), 답은 한국어 기본(영어 등은 따로 부탁할 때만), v2 두뇌의 짧은 지시문(성격 설명 7.4천 자를 1.3천 자로, 답은 최대한 짧게, 화면공유 도구는 v2에 없어 뺌: 인사의 답 지시문 4,500토큰이 1,400토큰), 답 전에 판단 한 번(도구 고르기로 도구가 필요한지 정하고, 필요할 때만 계획. 계획 하나로 합치거나 계획을 아예 빼 보니 날씨나 여러 단계 질문이 틀려 이 방식으로 정함), 말하는 중의 중간 전사가 호출로 읽히면 도구 고르기를 미리 해 둠(워커 `prepare`). 평가 전체(v2 설정, 마지막 지시문 수정 전) 219개 통과, 6개 실패: 파리·런던 비교와 지식 그래프 갈래 분류는 전부터 실패, 3개는 v2가 쓰지 않는 v1 개인 기억(그래프·일기) 평가, 1개는 새 답 길이 평가("하늘은 왜 파래"의 답이 72자로 기준 70자를 넘음). 그 뒤 "왜·어떻게" 질문은 핵심 이유만 말하도록 지시문을 고치고 답 길이 평가를 따로 3번 돌려 3번 모두 통과(v2 답 합계 185~205자, 예전 315~356자), 한국어 기본·지난 대화·채팅 채널·건너뛴 도구 평가 22개도 모두 통과(전체 평가는 이 수정 뒤 다시 돌리지 않음). 실제 디스코드 재측정(2026-11-12, `app/tests/live_round_trip.rs`, 질문 5개 2번): 첫 소리(효과음)는 이름 뒤에 쉬면 질문이 끝나기 전에, 쉬지 않으면 0.94~1.10초. 답의 첫 소리는 중앙값 1.9초(1.56~2.30초, 날씨 도구 5.75~5.85초), 9명이 동시에 말할 때 2.8초(2.13~3.41초, "기분"을 "딥"으로 잘못 들은 1번은 웹 검색으로 13.3초). 혼자일 때는 미리 해 둔 판단이 5번 모두 쓰여 말 끝 뒤 두뇌 시간이 0.6~0.74초였고, 9명 부하에서는 중간 전사가 밀려 미리 판단이 한 번도 되지 않음(두뇌 1.4초). 같은 시험에서 찾아 고친 것: 모델이 "10시 37분"을 오후로 읽음(시간 줄에 12시간 표기 추가), 없는 타이머 도구 호출 글자(``)를 답으로 내 TTS가 읽을 뻔함(도구 호출로 읽음) | -| M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7 | +| M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7. 3단계 완료(2026-11-12): 화면 `app/ui/`(빌드 도구 없는 HTML/CSS/JS, 어두운 테마, 한국어)와 화면이 부르는 명령 `admin_api.rs`(설정, 대시보드, 시작·정지, 로그 조회·복사·zip, PC 점검, 디스코드 토큰 확인·초대 링크·서버/채널 목록 `discord_setup.rs`). 첫 실행 마법사(데이터 폴더, PC 점검, 모델 안내, 봇 연결, 서버·음성 채널, 호출어, 시작), 대시보드, 설정 5개, 로그. 개발용 서버 `jarvis-admin-dev`로 이 서버의 브라우저에서 실제 테스트 봇과 음성 워커를 켜고 확인: 마법사 각 단계, 시작 뒤 "실행 중 · 테스트봇#9029 · 워커 연결됨", 다시 시작·정지, 설정 저장(바뀐 값만, 모르는 키 보존), 채팅 채널 추가, 로그 실시간 보기와 zip 내보내기. Tauri 창(셸)은 이 서버에서 빌드할 수 없어(webkit2gtk 없음) Windows 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영과 모델 자동 설치는 아직 | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 |