Compare commits

..

42 Commits

Author SHA1 Message Date
607785ac0c feat(frontend): bake Fabric-purple Hangman Lab logo as brand asset
public/brand-logo.svg = ~/hangman-lab-logo-black.svg recolored
#000000 -> #9333ea (Fabric deep purple). Dockerfile writes
.env.production at build (context .env* is dockerignored) so
VITE_APP_NAME/LOGO_URL/FAVICON_URL bake in; logo+favicon -> the mark.
Overridable via build args.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 10:02:14 +01:00
92d3b4dc1b feat(frontend): OIDC login + runtime env (FABRIC_OIDC_ONLY/FIX_TO_CENTER)
- Runtime container env injected by docker/entrypoint.sh -> runtime-env.js
  (loaded before the bundle); src/lib/runtime-env.ts reads it.
  FABRIC_OIDC_ONLY hides the password form; FIX_TO_CENTER pins the
  Center base and hides its input. Dockerfile ENTRYPOINT + ENV defaults.
- LoginPage: 'Sign in with SSO' when /auth/oidc/status enabled; password
  form gated by OIDC_ONLY; center input gated by FIX_TO_CENTER.
- /oidc route (OidcCallback) redeems the fragment ticket via
  /auth/oidc/exchange and adopts the session (AuthContext.adoptSession).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 09:44:49 +01:00
4892af55e8 feat(frontend): terminal restyle + dm + grouping + brand override
- Restyle: ink 'blueprint' surfaces + IBM Plex Mono / Major Mono
  Display, hairline borders, restrained motion, 12px radii. Fabric
  purple accent kept. Layout unchanged.
- Brand override (build-time VITE_ only): VITE_APP_NAME / VITE_LOGO_URL
  / VITE_FAVICON_URL via src/lib/brand.ts (applyBrand in main.tsx);
  login wordmark/logo + title + favicon. .env.example documented.
- dm x-type: create modal participant becomes single-select (radio)
  for dm and forces private; member right-click menu gains 'Create
  new DM channel' (non-unique, fresh channel each time).
- Channels sidebar grouped by x-type with group headers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 09:18:21 +01:00
46cad0ec7c feat(chat): slash-command autocomplete
Typing / opens a command panel from the guild's synced OpenClaw catalog
(GET /api/commands): filter + ↑↓/Enter/Esc; pick inserts /<nativeName> ;
arg stage lists args (required/type/desc) with clickable choice chips
(dynamic choices already snapshotted server-side). Sent as a normal
message — execution flows plugin -> OpenClaw command system.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:15:02 +01:00
8be68d4c87 docs: rewrite README to match current architecture
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 12:53:24 +01:00
805f0db300 feat(frontend): file:// bundle support (HashRouter + build:desktop)
- main.tsx: use HashRouter when loaded over file:// (packaged desktop
  has no server for History API path routing); keep BrowserRouter on
  the http web build.
- add build:desktop script (vite build --base=./ --outDir dist-desktop)
  so assets resolve under file://; gitignore dist-desktop.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 12:11:34 +01:00
0d3a333409 fix(brand): bolder strokes + cache-bust favicon
- Thicken the mark's strokes (mask dilation ~2.2%) so it reads at
  tab size; SVG re-traced + all PNGs regenerated, deeper green
  #1DB800 kept.
- The tab kept showing a stale icon because the favicon URL never
  changed across edits (browsers cache favicons very aggressively).
  Version the hrefs (?v=3) to force a refetch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 11:21:39 +01:00
68e60de3b4 feat(brand): vector SVG favicon + deeper green
- favicon.svg: the mark vectorized (OpenCV contour trace of the
  artwork, even-odd fill) -> crisp at any tab size, ~3KB. Set as the
  primary <link rel=icon type=image/svg+xml> with PNG fallbacks.
- Deepen the green: same hue, full saturation, ~72% value
  (#1DB800) and embolden faint anti-aliased strokes (alpha gamma)
  so it no longer looks washed-out at favicon size.
- All PNGs (16/32/256, apple-touch, icon-512) regenerated to match.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 11:16:57 +01:00
42f6e84709 fix(brand): transparent bg + tight crop for favicon/app icon
The mark sat tiny on a black square (invisible in the browser tab).
Make the near-black background transparent (alpha from max channel,
sub-22 floor removes the glow haze) and crop to the mark's bounding
box with ~8% margin so it fills the frame at favicon sizes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 11:10:57 +01:00
c4ccfd787f feat(brand): use no-text mark for favicon/app icon
Switch the favicon set + icon-512 + apple-touch-icon to the no-text
hexagon+wrench mark so it stays legible at 16-32px (the wordmark
version was unreadable at favicon sizes).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 11:07:33 +01:00
1574efb010 feat(brand): apply Fabric app icon (favicon set, title)
Replace placeholder favicon.svg with the designed Fabric icon as a PNG
favicon set (16/32/256), apple-touch-icon (180), icon-512; document
title -> 'Fabric'; theme-color black to match the icon.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 11:04:26 +01:00
b1c270a6ce feat(chat): file upload + attachments + pinned canvas
- composer 📎 attach (multi-file) with removable chips; uploads to
  /files then sends a message with attachments; image preview /
  download chips via ?access_token.
- pinned per-channel canvas panel below the topbar (fixed; independent
  of message scroll): md→renderMarkdown, text→<pre>, html→sandboxed
  iframe; collapse/expand.
- share/edit canvas modal (sharer-only Edit/Remove); live via
  canvas.updated/canvas.removed sockets; channel & messages context
  menus get canvas actions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 20:17:10 +01:00
f063807089 feat(chat): custom right-click context menus
Override the native browser menu with resource-specific menus:
- guild (rail icon): open, copy node id/name, add guild
- channel: open, join/leave, close, copy id/name, create channel
- message: copy text/id, mention author, delete (soft)
- user (member row): mention, copy id/name, move-to-bypass
  (discuss/work in-channel only), settings (self)
- blank areas (rail/channels/messages/members/root): scoped
  create/refresh actions

Menu closes on click/Escape/scroll/resize; positioned within the
viewport; the most specific target wins via stopPropagation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 19:35:57 +01:00
372805c9fa feat(chat): bypass-list UI for discuss/work channels
- create-channel modal: optional bypass multi-select (discuss/work only),
  sent as bypassUserIds; reset on open/close.
- members panel (in-channel, discuss/work): bypass members tagged
  'bypass'; others get a '→ bypass' action -> POST /channels/:id/bypass.
- loadChannelMembers consumes the new {userId,bypass} member shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 19:26:24 +01:00
44c308bd06 feat(frontend): closed-channel read-only UI
Closed channels: composer replaced by a read-only banner; history still
viewable; GuildChannel carries closed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 16:52:44 +01:00
2d9aec8657 feat(frontend): render <@id> as @name mention chips
Markdown renderer turns <@userId> into a Discord-style mention chip
(@displayName, resolved via guild members; short-id fallback). Tokens
inside backticks stay literal; untranslated <@user.name:..> left as-is.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:52:43 +01:00
24eb458621 feat(frontend): per-message markdown rendering
Self-contained, HTML-escaped (XSS-safe) markdown for history messages;
each message rendered independently so a syntax error (e.g. unclosed
code fence) cannot leak into the next message.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:47:02 +01:00
8272ed495e feat(frontend): hide channel-members section for public channels
Public channel selected -> single guild member list (no In-channel split).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:27:36 +01:00
ab31afa13d feat(frontend): split members sidebar into channel + guild sections
When a channel is selected the Members panel shows 'In channel — N'
(that channel's members) above 'Guild — N' (all guild members).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:00:24 +01:00
b04b099754 feat(frontend): channel type colors, triage/custom create fields, join/leave, dev mode
- per-x_type channel row colors (general/work/report/discuss/triage/custom)
- create-channel: required On-duty select (triage) / Listeners checklist (custom)
- channel Join/Leave in topbar; list carries isMember
- Developer mode toggle (Settings): show guild /ack + per-message wakeup
  metadata; off by default (metadata stays transparent)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 14:51:20 +01:00
396b2fd231 feat(frontend): channel type selector on create
Required Type dropdown (general|work|report|discuss|triage|custom) in the
create-channel modal; sends xType; shows type badge on channel rows.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 09:35:37 +01:00
53d21381d9 feat(frontend): Discord-style dark redesign
- full design system rewrite (dark theme, system tokens)
- chat shell: server rail / channel sidebar / message area / members
- message rows with avatars, author + time; empty/loading states
- login screen redesign; add-guild moved to a modal
- removed debug v1/v2/v4 panel toggles; members toggle in topbar

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 09:26:11 +01:00
1b70f27fc4 fix(frontend): refresh guild tokens on mount to avoid stale-token 401
Guild access tokens (15-min TTL) are persisted in localStorage but were
never refreshed on page (re)load - only the center token was. After the
TTL elapsed, GET /channels failed with 401 ('Failed to load channels').
Re-issue guild tokens via refreshGuilds() on mount and reload channels
when the guild token changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 09:14:10 +01:00
6b35d92aef feat(frontend): public channels, self-excluded member picker, editable display name
- create-channel modal: Public checkbox (default off), self excluded from
  member list (creator auto-added), shows member display names
- Settings modal to edit your own display name
- members panel shows names and marks (you)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 09:09:49 +01:00
c10cdcf2e5 fix(frontend): create channel under selected guild and surface errors via modal
- createChannel falls back to selectedGuildId when guildDbId is unknown,
  so the first channel of a guild can be created (no chicken-and-egg)
- channel is created under the currently selected guild
- errors now show in a dismissible modal instead of the Messages pane

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 08:52:25 +01:00
nav
40540ab8a6 feat(frontend): add guild join flow, members panel, and channel-create member modal 2026-05-14 16:58:12 +00:00
nav
75fee7c725 fix(frontend): require guildId for channel creation and fallback from channel list 2026-05-14 16:49:57 +00:00
nav
d0bbd4a20f feat(frontend): add collapsible v1/v2/v4 panels and guild members column 2026-05-14 16:46:38 +00:00
nav
12265e09ec feat(frontend): add create channel action in channel pane 2026-05-14 16:41:20 +00:00
nav
04d8f9e3bf feat(frontend): redesign post-login layout into guild/channel/chat panes 2026-05-14 16:38:19 +00:00
nav
4f28f102e0 feat(auth): remove center api key from frontend login flow 2026-05-14 14:17:12 +00:00
nav
cfaa1cb657 feat(frontend): translate UI to English and refresh layout styles 2026-05-14 13:33:37 +00:00
nav
4724678035 feat(frontend): require center API key on login/auth calls 2026-05-13 08:18:01 +00:00
nav
c906cde209 feat(frontend): login with center URL and consume center-issued guild tokens 2026-05-13 08:00:32 +00:00
nav
66c49ff654 feat(frontend): apply API key headers to center auth client 2026-05-13 06:58:18 +00:00
nav
edb06a5a31 feat(frontend): add request-id observability logs for api calls 2026-05-12 16:10:30 +00:00
nav
25bd1df290 feat(frontend): add loading empty and error states for chat operations 2026-05-12 16:08:17 +00:00
root
763f06ab8c feat(frontend): add typing presence and reconnect repull realtime behavior 2026-05-12 16:04:25 +00:00
root
e7faf92d3c feat(frontend): show next_expected_seq and page continuity hints 2026-05-12 16:00:38 +00:00
root
e7b2721280 feat(frontend): add message edit delete and ranged pull controls 2026-05-12 15:59:11 +00:00
root
048a55aaeb feat(frontend): load guild-channel lists and sync chat channel in url 2026-05-12 15:25:40 +00:00
root
d718128f89 feat(frontend): implement center auth session flow with route guard 2026-05-12 15:09:06 +00:00
34 changed files with 3682 additions and 277 deletions

7
.dockerignore Normal file
View File

@@ -0,0 +1,7 @@
node_modules
dist
.git
.gitignore
Dockerfile
*.log
.env*

View File

@@ -1,3 +1,9 @@
VITE_CENTER_API_BASE=http://localhost:7001/api
VITE_GUILD_API_BASE=http://localhost:7002/api VITE_GUILD_API_BASE=http://localhost:7002/api
VITE_GUILD_SOCKET_BASE=http://localhost:7002/realtime VITE_GUILD_SOCKET_BASE=http://localhost:7002/realtime
VITE_API_KEY=change-me-api-key VITE_API_KEY=change-me-api-key
# Brand overrides (build-time only; baked at build). Leave empty for Fabric defaults.
VITE_APP_NAME=Fabric
VITE_LOGO_URL=
VITE_FAVICON_URL=

1
.gitignore vendored
View File

@@ -22,3 +22,4 @@ dist-ssr
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
dist-desktop

32
Dockerfile Normal file
View File

@@ -0,0 +1,32 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
# Brand is baked at build (Vite VITE_* are build-time). Written here, not
# via a context .env (.dockerignore excludes .env*). public/brand-logo.svg
# ships the Fabric-purple Hangman Lab mark; override args if rebranding.
ARG VITE_APP_NAME=Fabric
ARG VITE_LOGO_URL=/brand-logo.svg
ARG VITE_FAVICON_URL=/brand-logo.svg
RUN printf 'VITE_APP_NAME=%s\nVITE_LOGO_URL=%s\nVITE_FAVICON_URL=%s\n' \
"$VITE_APP_NAME" "$VITE_LOGO_URL" "$VITE_FAVICON_URL" > .env.production
RUN npm run build
FROM nginx:1.27-alpine AS runtime
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY docker/entrypoint.sh /docker-entrypoint-fabric.sh
COPY --from=build /app/dist /usr/share/nginx/html
RUN chmod +x /docker-entrypoint-fabric.sh
# Runtime SPA config (see docker/entrypoint.sh). Override at `docker run`
# / compose: empty values keep prior behavior.
ENV FABRIC_OIDC_ONLY=""
ENV FIX_TO_CENTER=""
EXPOSE 80
ENTRYPOINT ["/docker-entrypoint-fabric.sh"]
CMD ["nginx", "-g", "daemon off;"]

116
README.md
View File

@@ -1,73 +1,61 @@
# React + TypeScript + Vite # Fabric.Frontend
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. The Fabric **web client** — React 19 + TypeScript + Vite. This is the actual
UI; it is served on the web and **bundled unchanged** into `Fabric.Desktop`
(Electron) and `Fabric.Android` (Capacitor).
Currently, two official plugins are available: ## What it does
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs) - **Auth** — login screen with a configurable Center API base
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) (default `http://localhost:7001/api`); discovers the user's guilds and
short-lived guild access tokens; refreshes on mount.
- **Discord-style dark UI** — server rail / channel sidebar / messages /
members layout; per-`x_type` channel colors + badges.
- **Messaging** — per-message Markdown render (HTML-escaped, XSS-safe, no
cross-message bleed), `<@id>` mention chips (resolved to display names,
backtick-aware), no message length cap.
- **Channels** — create-channel modal (required Type, Public, members,
triage on-duty, custom listeners, discuss/work **bypass** multi-select);
join/leave; closed-channel read-only banner.
- **Members** — split "In channel" / "Guild" panels for non-public channels;
discuss/work bypass tag + "→ bypass" action.
- **Files** — composer attach (multi-file) with chips; image previews /
download chips (via `?access_token`).
- **Canvas** — pinned per-channel document panel (Markdown / sandboxed HTML
iframe / plain text), live via `canvas.*` sockets; sharer-only edit/remove.
- **Right-click menus** — native menu overridden with resource-specific
context menus (guild / channel / message / user / blank areas).
- **Slash autocomplete** — typing `/` opens a command panel from the
guild's synced OpenClaw catalog (`GET /api/commands`): filter, ↑↓/Enter/
Esc, pick inserts `/<name> `, arg stage shows args + clickable choices.
- **Dev mode** — surfaces guild `/ack` and per-message `wakeup` metadata
(off by default; persisted in `localStorage`).
- Routing is `BrowserRouter` on the web and `HashRouter` under `file://`
(the Electron bundle); Capacitor serves over `http://localhost` so it
uses `BrowserRouter`.
## React Compiler ## Develop
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). ```bash
npm install
## Expanding the ESLint configuration npm run dev # Vite dev server (http://localhost:5173)
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
``` ```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: ## Build
```js ```bash
// eslint.config.js npm run build # web build (absolute base) -> dist/
import reactX from 'eslint-plugin-react-x' npm run build:desktop # relative-base build -> dist-desktop/ (Electron, file://)
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
``` ```
`Fabric.Desktop` / `Fabric.Android` run their own scripts that invoke these
builds and copy the output into their shells — you normally don't build for
them by hand.
## Notes
- ES modules, Vite. App icons / favicon use the Fabric mark
(`public/favicon.svg` is a vectorized, deep-green version; PNG fallbacks +
`apple-touch-icon`). Favicon hrefs are versioned (`?v=`) for cache-busting.
- The Center API base is entered at login, so desktop/mobile builds (no web
origin) just point at the right backend host.

20
docker/entrypoint.sh Normal file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
set -e
# Inject container env into the static SPA at runtime. The app loads
# /runtime-env.js (see index.html) before its bundle.
# FABRIC_OIDC_ONLY - "true" hides the username/password login form
# FIX_TO_CENTER - non-empty pins the Center API base + hides its input
ONLY="false"
case "$(printf '%s' "${FABRIC_OIDC_ONLY:-}" | tr '[:upper:]' '[:lower:]')" in
1|true|yes|on) ONLY="true" ;;
esac
# JSON-escape FIX_TO_CENTER (backslash + double-quote)
FIX="$(printf '%s' "${FIX_TO_CENTER:-}" | sed 's/\\/\\\\/g; s/"/\\"/g')"
cat > /usr/share/nginx/html/runtime-env.js <<EOF
window.__FABRIC_ENV__ = { oidcOnly: ${ONLY}, fixToCenter: "${FIX}" };
EOF
exec "$@"

17
docker/nginx.conf Normal file
View File

@@ -0,0 +1,17 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location = /healthz {
access_log off;
return 200 'ok';
add_header Content-Type text/plain;
}
}

View File

@@ -2,12 +2,25 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg?v=3" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png?v=3" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png?v=3" />
<link rel="icon" type="image/png" sizes="256x256" href="/favicon.png?v=3" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png?v=3" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>fabric-frontend</title> <meta name="theme-color" content="#080a0d" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Major+Mono+Display&family=IBM+Plex+Mono:ital,wght@0,400;0,500;0,600;1,400&display=swap"
rel="stylesheet"
/>
<title>Fabric</title>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<!-- runtime container env (generated by docker/entrypoint.sh); absent in dev -->
<script src="/runtime-env.js"></script>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
</html> </html>

View File

@@ -7,7 +7,8 @@
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview",
"build:desktop": "tsc -b && vite build --base=./ --outDir dist-desktop"
}, },
"dependencies": { "dependencies": {
"axios": "^1.16.0", "axios": "^1.16.0",

BIN
public/apple-touch-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

44
public/brand-logo.svg Normal file
View File

@@ -0,0 +1,44 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 733.000000 733.000000" role="img" aria-label="Hangman Lab">
<g transform="translate(0.000000,733.000000) scale(0.100000,-0.100000)"
fill="#9333ea" stroke="none">
<path d="M812 6860 c-66 -40 -73 -66 -70 -242 3 -141 5 -159 24 -185 43 -58
63 -63 262 -64 l182 -1 0 -2694 0 -2694 -290 0 c-314 0 -332 -3 -380 -54 -24
-27 -25 -32 -28 -199 -3 -195 4 -218 71 -250 32 -16 257 -17 3084 -17 2955 0
3049 1 3083 19 65 34 75 66 75 236 0 186 -16 224 -104 254 -25 8 -682 11
-2512 11 l-2479 0 0 1998 0 1997 698 697 697 697 670 -3 c369 -2 680 -4 693
-5 22 -1 22 -1 22 -269 l0 -268 84 -12 c47 -7 103 -19 125 -27 41 -14 41 -14
43 283 l3 297 631 1 c698 2 673 -1 714 67 18 28 20 51 20 187 0 173 -8 201
-72 240 -33 20 -56 20 -2623 20 -2567 0 -2590 0 -2623 -20z m1725 -500 c-1 -3
-183 -185 -404 -404 l-403 -399 0 405 0 406 405 -1 c223 -1 404 -4 402 -7z
M4283 5701 c-459 -125 -690 -624 -483 -1046 67 -138 196 -266 335 -335 281
-139 612 -93 837 118 235 219 297 575 152 870 -85 174 -235 306 -427 375 -111
40 -302 48 -414 18z m267 -211 c95 -15 201 -70 274 -144 273 -274 173 -723
-189 -851 -93 -33 -236 -35 -326 -5 -202 68 -340 249 -356 465 -18 242 153
471 394 529 71 18 119 19 203 6z M5945 4716 c-56 -25 -80 -61 -80 -122 0 -48
4 -57 36 -90 88 -88 219 -29 219 98 0 45 -34 96 -75 114 -42 17 -61 17 -100 0z
M5675 4466 c-60 -26 -73 -109 -26 -157 62 -61 161 -19 161 70 0 74 -68 118
-135 87z M3747 4397 c-10 -7 -226 -223 -479 -482 -307 -313 -467 -483 -479
-510 -35 -75 -17 -177 38 -227 39 -35 114 -61 160 -54 100 13 104 17 583 554
l145 162 3 -404 c3 -455 15 -342 -137 -1186 -76 -423 -101 -587 -101 -664 0
-190 182 -307 377 -242 62 21 136 95 152 152 6 22 29 188 52 369 57 466 109
839 118 848 4 4 52 6 106 5 l99 -3 67 -210 c38 -115 68 -220 69 -232 0 -12
-38 -152 -85 -311 -47 -159 -85 -302 -85 -317 0 -128 109 -225 255 -225 109 1
185 42 228 125 26 51 237 683 237 710 0 11 -54 182 -121 380 -121 360 -121
360 -134 605 -8 135 -14 292 -14 350 l0 105 152 -158 c84 -87 166 -167 182
-177 44 -29 98 -26 135 8 38 35 187 379 173 401 -5 8 -34 20 -64 26 -59 11
-38 -8 -393 362 -89 93 -100 97 -174 59 -59 -30 -161 -62 -229 -71 -52 -7 -53
-7 -53 -41 0 -44 -21 -84 -61 -118 -38 -32 -41 0 32 -455 l52 -325 -82 -78
c-45 -43 -85 -78 -89 -78 -4 0 -42 35 -84 78 l-77 77 34 215 c19 118 46 289
61 379 26 164 26 164 -5 188 -42 33 -54 58 -61 121 -5 54 -5 54 -92 87 -98 38
-184 89 -243 145 -76 70 -123 87 -168 57z M5504 4170 c-74 -30 -69 -170 6
-170 19 0 20 -7 20 -123 0 -122 0 -122 -54 -262 -30 -77 -97 -243 -150 -369
-106 -252 -113 -287 -73 -347 46 -70 38 -69 560 -69 327 0 475 3 490 11 69 35
107 109 88 172 -5 17 -62 142 -126 277 -225 470 -215 443 -215 586 0 114 2
124 18 124 57 0 72 101 23 151 -29 29 -29 29 -298 28 -147 0 -278 -4 -289 -9z
m376 -307 c1 -148 1 -148 81 -333 101 -231 98 -222 68 -216 -13 3 -116 22
-229 42 -112 19 -208 37 -212 40 -4 2 18 75 48 160 54 156 54 156 54 305 l0
149 95 0 95 0 0 -147z m-219 -593 c22 0 49 -42 49 -75 0 -46 -29 -75 -74 -75
-37 0 -76 36 -76 71 0 46 45 94 78 83 8 -2 18 -4 23 -4z m327 -126 c53 -59 -7
-144 -80 -113 -54 22 -65 83 -22 125 30 31 67 27 102 -12z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

BIN
public/favicon-16.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 683 B

BIN
public/favicon-32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
public/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 9.3 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

BIN
public/icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@@ -1,17 +1,33 @@
import { Navigate, Route, Routes } from 'react-router-dom' import { Navigate, Route, Routes } from 'react-router-dom'
import ProtectedRoute from './auth/ProtectedRoute'
import AppLayout from './layouts/AppLayout' import AppLayout from './layouts/AppLayout'
import ChatPage from './pages/ChatPage' import ChatPage from './pages/ChatPage'
import LoginPage from './pages/LoginPage' import LoginPage from './pages/LoginPage'
import WorkspacePage from './pages/WorkspacePage' import OidcCallback from './pages/OidcCallback'
export default function App() { export default function App() {
return ( return (
<Routes> <Routes>
<Route path="/" element={<AppLayout />}> <Route path="/" element={<AppLayout />}>
<Route index element={<Navigate to="/workspace" replace />} /> <Route index element={<Navigate to="/workspace" replace />} />
<Route path="workspace" element={<WorkspacePage />} /> <Route
<Route path="chat" element={<ChatPage />} /> path="workspace"
element={
<ProtectedRoute>
<ChatPage />
</ProtectedRoute>
}
/>
<Route
path="chat"
element={
<ProtectedRoute>
<ChatPage />
</ProtectedRoute>
}
/>
<Route path="login" element={<LoginPage />} /> <Route path="login" element={<LoginPage />} />
<Route path="oidc" element={<OidcCallback />} />
</Route> </Route>
<Route path="*" element={<Navigate to="/workspace" replace />} /> <Route path="*" element={<Navigate to="/workspace" replace />} />
</Routes> </Routes>

101
src/auth/AuthContext.tsx Normal file
View File

@@ -0,0 +1,101 @@
import { useMemo, useState } from 'react'
import type { PropsWithChildren } from 'react'
import { clearAuthSession, getAuthSession, isAccessTokenStale, setAuthSession } from '../lib/auth-storage'
import type { AuthSession } from '../lib/auth-storage'
import { loginCenter, logoutCenter, meGuildsCenter, refreshCenter, updateMeNameCenter } from '../lib/center-auth-client'
import { AuthContext } from './auth-context'
import type { AuthContextValue } from './auth-context'
export function AuthProvider({ children }: PropsWithChildren) {
const [session, setSession] = useState<AuthSession | null>(getAuthSession())
const value = useMemo<AuthContextValue>(
() => ({
session,
isAuthed: !!session,
login: async (centerApiBase: string, email: string, password: string) => {
const next = await loginCenter(centerApiBase, { email, password })
setAuthSession(next)
setSession(next)
},
// Adopt a session obtained out-of-band (OIDC ticket exchange).
adoptSession: (next: AuthSession) => {
setAuthSession(next)
setSession(next)
},
logout: async () => {
if (session?.refreshToken) {
try {
await logoutCenter(session.centerApiBase, session.refreshToken)
} catch {
// noop
}
}
clearAuthSession()
setSession(null)
},
ensureFreshToken: async () => {
if (!session) return null
if (!isAccessTokenStale(session.accessToken)) return session.accessToken
const refreshed = await refreshCenter(session.centerApiBase, session.refreshToken)
const next: AuthSession = {
...session,
accessToken: refreshed.accessToken,
refreshToken: refreshed.refreshToken,
tokenType: refreshed.tokenType,
expiresIn: refreshed.expiresIn,
}
setAuthSession(next)
setSession(next)
return next.accessToken
},
refreshGuilds: async () => {
if (!session) return
let accessToken = session.accessToken
let refreshToken = session.refreshToken
let tokenType = session.tokenType
let expiresIn = session.expiresIn
if (isAccessTokenStale(session.accessToken)) {
const refreshed = await refreshCenter(session.centerApiBase, session.refreshToken)
accessToken = refreshed.accessToken
refreshToken = refreshed.refreshToken
tokenType = refreshed.tokenType
expiresIn = refreshed.expiresIn
}
const guildData = await meGuildsCenter(session.centerApiBase, accessToken)
const next: AuthSession = {
...session,
accessToken,
refreshToken,
tokenType,
expiresIn,
guilds: guildData.guilds,
guildAccessTokens: guildData.guildAccessTokens,
}
setAuthSession(next)
setSession(next)
},
updateName: async (name: string) => {
if (!session) return
const accessToken = (await (async () => {
if (!isAccessTokenStale(session.accessToken)) return session.accessToken
const refreshed = await refreshCenter(session.centerApiBase, session.refreshToken)
return refreshed.accessToken
})())
const updated = await updateMeNameCenter(session.centerApiBase, accessToken, name)
const next: AuthSession = {
...session,
accessToken,
user: { ...session.user, name: updated.name },
}
setAuthSession(next)
setSession(next)
},
}),
[session],
)
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}

View File

@@ -0,0 +1,34 @@
import { Navigate } from 'react-router-dom'
import { useAuth } from './auth-context'
import type { PropsWithChildren } from 'react'
import { useEffect, useState } from 'react'
export default function ProtectedRoute({ children }: PropsWithChildren) {
const { isAuthed, ensureFreshToken, logout } = useAuth()
const [ready, setReady] = useState(false)
useEffect(() => {
let active = true
;(async () => {
if (!isAuthed) {
if (active) setReady(true)
return
}
try {
await ensureFreshToken()
} catch {
await logout()
} finally {
if (active) setReady(true)
}
})()
return () => {
active = false
}
}, [isAuthed, ensureFreshToken, logout])
if (!ready) return null
if (!isAuthed) return <Navigate to="/login" replace />
return <>{children}</>
}

21
src/auth/auth-context.ts Normal file
View File

@@ -0,0 +1,21 @@
import { createContext, useContext } from 'react'
import type { AuthSession } from '../lib/auth-storage'
export type AuthContextValue = {
session: AuthSession | null
isAuthed: boolean
login: (centerApiBase: string, email: string, password: string) => Promise<void>
adoptSession: (session: AuthSession) => void
logout: () => Promise<void>
ensureFreshToken: () => Promise<string | null>
refreshGuilds: () => Promise<void>
updateName: (name: string) => Promise<void>
}
export const AuthContext = createContext<AuthContextValue | null>(null)
export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be used inside <AuthProvider>')
return ctx
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,5 @@
import { Link, Outlet } from 'react-router-dom' import { Outlet } from 'react-router-dom'
export default function AppLayout() { export default function AppLayout() {
return ( return <Outlet />
<div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', minHeight: '100vh' }}>
<aside style={{ borderRight: '1px solid #ddd', padding: 16 }}>
<h3>Fabric</h3>
<nav style={{ display: 'grid', gap: 8 }}>
<Link to="/workspace"></Link>
<Link to="/chat"></Link>
<Link to="/login"></Link>
</nav>
</aside>
<main style={{ padding: 16 }}>
<Outlet />
</main>
</div>
)
} }

View File

@@ -13,11 +13,44 @@ function createClient(): AxiosInstance {
instance.interceptors.request.use((request) => { instance.interceptors.request.use((request) => {
const { apiKey } = getRuntimeConfig() const { apiKey } = getRuntimeConfig()
const requestId = crypto.randomUUID()
if (apiKey) request.headers['x-api-key'] = apiKey if (apiKey) request.headers['x-api-key'] = apiKey
request.headers['x-request-id'] = crypto.randomUUID() request.headers['x-request-id'] = requestId
request.headers['x-client-name'] = 'fabric-frontend'
console.info('[api:request]', {
method: request.method,
url: `${request.baseURL ?? ''}${request.url ?? ''}`,
requestId,
})
return request return request
}) })
instance.interceptors.response.use(
(response) => {
const requestId = response.headers['x-request-id'] ?? response.config.headers['x-request-id']
console.info('[api:response]', {
method: response.config.method,
url: `${response.config.baseURL ?? ''}${response.config.url ?? ''}`,
status: response.status,
requestId,
})
return response
},
(error) => {
const response = error?.response
const config = error?.config ?? {}
const requestId = response?.headers?.['x-request-id'] ?? config?.headers?.['x-request-id']
console.error('[api:error]', {
method: config.method,
url: `${config.baseURL ?? ''}${config.url ?? ''}`,
status: response?.status,
requestId,
})
return Promise.reject(error)
},
)
return instance return instance
} }

62
src/lib/auth-storage.ts Normal file
View File

@@ -0,0 +1,62 @@
export type AuthSession = {
centerApiBase: string
accessToken: string
refreshToken: string
tokenType: string
expiresIn?: number
user: {
id: string
email: string
name: string
}
guilds: Array<{
nodeId: string
name: string
endpoint: string
status: 'active' | 'offline' | 'revoked'
}>
guildAccessTokens: Array<{
guildNodeId: string
token: string
tokenType: string
expiresIn?: number
}>
}
const KEY = 'fabric.auth.session.v1'
export function getAuthSession(): AuthSession | null {
const raw = localStorage.getItem(KEY)
if (!raw) return null
try {
return JSON.parse(raw) as AuthSession
} catch {
return null
}
}
export function setAuthSession(session: AuthSession): void {
localStorage.setItem(KEY, JSON.stringify(session))
}
export function clearAuthSession(): void {
localStorage.removeItem(KEY)
}
function parseJwtExpMs(token: string): number | null {
const payload = token.split('.')[1]
if (!payload) return null
try {
const decoded = JSON.parse(atob(payload)) as { exp?: number }
if (!decoded.exp) return null
return decoded.exp * 1000
} catch {
return null
}
}
export function isAccessTokenStale(token: string, leadMs = 60_000): boolean {
const expMs = parseJwtExpMs(token)
if (!expMs) return true
return Date.now() + leadMs >= expMs
}

21
src/lib/brand.ts Normal file
View File

@@ -0,0 +1,21 @@
// Build-time brand overrides. Values are baked from VITE_ env at build
// (not runtime-configurable by design). Empty/unset → Fabric defaults.
const env = import.meta.env as unknown as Record<string, string | undefined>
export const APP_NAME = (env.VITE_APP_NAME ?? '').trim() || 'Fabric'
export const LOGO_URL = (env.VITE_LOGO_URL ?? '').trim()
const FAVICON_URL = (env.VITE_FAVICON_URL ?? '').trim()
// Apply the document title + favicon override once at startup.
export function applyBrand(): void {
document.title = APP_NAME
if (FAVICON_URL) {
document
.querySelectorAll('link[rel~="icon"], link[rel="apple-touch-icon"]')
.forEach((n) => n.remove())
const link = document.createElement('link')
link.rel = 'icon'
link.href = FAVICON_URL
document.head.appendChild(link)
}
}

View File

@@ -0,0 +1,110 @@
import axios from 'axios'
import type { AuthSession } from './auth-storage'
export type LoginPayload = { email: string; password: string }
type LoginResponse = {
accessToken: string
refreshToken: string
tokenType: string
expiresIn?: number
user: { id: string; email: string; name: string }
guilds: Array<{ nodeId: string; name: string; endpoint: string; status: 'active' | 'offline' | 'revoked' }>
guildAccessTokens: Array<{ guildNodeId: string; token: string; tokenType: string; expiresIn?: number }>
}
type RefreshResponse = {
accessToken: string
refreshToken: string
tokenType: string
expiresIn?: number
}
type MeGuildsResponse = {
guilds: Array<{ nodeId: string; name: string; endpoint: string; status: 'active' | 'offline' | 'revoked' }>
guildAccessTokens: Array<{ guildNodeId: string; token: string; tokenType: string; expiresIn?: number }>
}
function centerClient(centerApiBase: string) {
const client = axios.create({
baseURL: centerApiBase,
timeout: 10000,
})
client.interceptors.request.use((request) => {
const requestId = crypto.randomUUID()
request.headers['x-request-id'] = requestId
request.headers['x-client-name'] = 'fabric-frontend'
return request
})
return client
}
export async function loginCenter(centerApiBase: string, payload: LoginPayload): Promise<AuthSession> {
const res = await centerClient(centerApiBase).post<LoginResponse>('/auth/login', payload)
return { ...res.data, centerApiBase }
}
export async function refreshCenter(centerApiBase: string, refreshToken: string): Promise<RefreshResponse> {
const res = await centerClient(centerApiBase).post<RefreshResponse>('/auth/refresh', { refreshToken })
return res.data
}
export async function logoutCenter(centerApiBase: string, refreshToken: string): Promise<void> {
await centerClient(centerApiBase).post('/auth/logout', { refreshToken })
}
export async function meGuildsCenter(centerApiBase: string, accessToken: string): Promise<MeGuildsResponse> {
const res = await centerClient(centerApiBase).get<MeGuildsResponse>('/auth/me/guilds', {
headers: { Authorization: `Bearer ${accessToken}` },
})
return res.data
}
export async function joinGuildCenter(centerApiBase: string, accessToken: string, guildNodeId: string): Promise<void> {
await centerClient(centerApiBase).post(
'/auth/me/guilds/join',
{ guildNodeId },
{ headers: { Authorization: `Bearer ${accessToken}` } },
)
}
export async function guildMembersCenter(
centerApiBase: string,
accessToken: string,
guildNodeId: string,
): Promise<Array<{ userId: string; email: string; name: string; status: string }>> {
const res = await centerClient(centerApiBase).get<Array<{ userId: string; email: string; name: string; status: string }>>(
`/auth/guilds/${encodeURIComponent(guildNodeId)}/members`,
{ headers: { Authorization: `Bearer ${accessToken}` } },
)
return Array.isArray(res.data) ? res.data : []
}
export async function oidcStatusCenter(centerApiBase: string): Promise<{ enabled: boolean }> {
try {
const res = await centerClient(centerApiBase).get<{ enabled: boolean }>('/auth/oidc/status')
return { enabled: !!res.data?.enabled }
} catch {
return { enabled: false }
}
}
export async function oidcExchangeCenter(centerApiBase: string, ticket: string): Promise<AuthSession> {
const res = await centerClient(centerApiBase).post<LoginResponse>('/auth/oidc/exchange', { ticket })
return { ...res.data, centerApiBase }
}
export async function updateMeNameCenter(
centerApiBase: string,
accessToken: string,
name: string,
): Promise<{ id: string; email: string; name: string }> {
const res = await centerClient(centerApiBase).patch<{ id: string; email: string; name: string }>(
'/auth/me',
{ name },
{ headers: { Authorization: `Bearer ${accessToken}` } },
)
return res.data
}

131
src/lib/markdown.ts Normal file
View File

@@ -0,0 +1,131 @@
// Minimal, self-contained Markdown -> HTML for chat messages.
// Each message is rendered independently (call once per message) so a
// syntax error in one message (e.g. an unclosed code fence) cannot affect
// the next one. All raw text is HTML-escaped first, so no user HTML or
// script can be injected; only our own tags are emitted.
export type MarkdownOpts = {
// resolve a mentioned userId to a display name (without the leading @)
resolveMention?: (id: string) => string
}
function esc(s: string): string {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
function safeUrl(u: string): string {
return /^(https?:|mailto:)/i.test(u.trim()) ? u.trim() : '#'
}
// <@id> -> mention chip. Runs on already-escaped text, so the token looks
// like &lt;@id&gt;. Untranslated <@user.name:..> tokens are left literal.
function mentions(s: string, opts?: MarkdownOpts): string {
return s.replace(/&lt;@([^&<>\s]+)&gt;/g, (full, id: string) => {
if (id.startsWith('user.name:')) return full
const label = opts?.resolveMention ? opts.resolveMention(id) : id
return `<span class="mention">@${esc(label)}</span>`
})
}
// inline formatting on already-escaped text; code spans are protected
function inline(t: string, opts?: MarkdownOpts): string {
const codes: string[] = []
let s = t.replace(/`([^`]+)`/g, (_, c) => {
codes.push(`<code>${c}</code>`)
return ` ${codes.length - 1} `
})
s = mentions(s, opts)
s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, txt, url) => `<a href="${safeUrl(url)}" target="_blank" rel="noopener noreferrer">${txt}</a>`)
s = s.replace(/(^|[\s(])((?:https?:\/\/)[^\s<]+)/g, (_, p, url) => `${p}<a href="${safeUrl(url)}" target="_blank" rel="noopener noreferrer">${url}</a>`)
s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
s = s.replace(/__([^_]+)__/g, '<strong>$1</strong>')
s = s.replace(/~~([^~]+)~~/g, '<del>$1</del>')
s = s.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>')
s = s.replace(/(^|[^_])_([^_\s][^_]*)_/g, '$1<em>$2</em>')
s = s.replace(/ (\d+) /g, (_, i) => codes[Number(i)])
return s
}
export function renderMarkdown(src: string, opts?: MarkdownOpts): string {
if (typeof src !== 'string' || src === '') return ''
const lines = src.replace(/\r\n?/g, '\n').split('\n')
const out: string[] = []
let i = 0
let para: string[] = []
const flushPara = () => {
if (para.length) {
out.push(`<p>${inline(esc(para.join('\n')), opts).replace(/\n/g, '<br>')}</p>`)
para = []
}
}
while (i < lines.length) {
const line = lines[i]
// fenced code block (unclosed fence is closed at message end)
const fence = /^```(.*)$/.exec(line)
if (fence) {
flushPara()
const buf: string[] = []
i++
while (i < lines.length && !/^```\s*$/.test(lines[i])) {
buf.push(lines[i])
i++
}
i++ // skip closing fence if present
out.push(`<pre><code>${esc(buf.join('\n'))}</code></pre>`)
continue
}
if (/^\s*$/.test(line)) {
flushPara()
i++
continue
}
const h = /^(#{1,6})\s+(.*)$/.exec(line)
if (h) {
flushPara()
const lvl = h[1].length
out.push(`<h${lvl}>${inline(esc(h[2]), opts)}</h${lvl}>`)
i++
continue
}
if (/^\s*>\s?/.test(line)) {
flushPara()
const buf: string[] = []
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
buf.push(lines[i].replace(/^\s*>\s?/, ''))
i++
}
out.push(`<blockquote>${inline(esc(buf.join('\n')), opts).replace(/\n/g, '<br>')}</blockquote>`)
continue
}
const ordered = /^\s*\d+\.\s+/.test(line)
const unordered = /^\s*[-*+]\s+/.test(line)
if (ordered || unordered) {
flushPara()
const tag = ordered ? 'ol' : 'ul'
const items: string[] = []
const re = ordered ? /^\s*\d+\.\s+(.*)$/ : /^\s*[-*+]\s+(.*)$/
while (i < lines.length && re.test(lines[i])) {
items.push(`<li>${inline(esc(re.exec(lines[i])![1]), opts)}</li>`)
i++
}
out.push(`<${tag}>${items.join('')}</${tag}>`)
continue
}
para.push(line)
i++
}
flushPara()
return out.join('')
}

View File

@@ -1,4 +1,5 @@
export type RuntimeConfig = { export type RuntimeConfig = {
centerApiBase: string
guildApiBase: string guildApiBase: string
guildSocketBase: string guildSocketBase: string
apiKey: string apiKey: string
@@ -7,6 +8,7 @@ export type RuntimeConfig = {
const KEY = 'fabric.runtime.config.v1' const KEY = 'fabric.runtime.config.v1'
const defaults: RuntimeConfig = { const defaults: RuntimeConfig = {
centerApiBase: import.meta.env.VITE_CENTER_API_BASE ?? 'http://localhost:7001/api',
guildApiBase: import.meta.env.VITE_GUILD_API_BASE ?? 'http://localhost:7002/api', guildApiBase: import.meta.env.VITE_GUILD_API_BASE ?? 'http://localhost:7002/api',
guildSocketBase: import.meta.env.VITE_GUILD_SOCKET_BASE ?? 'http://localhost:7002/realtime', guildSocketBase: import.meta.env.VITE_GUILD_SOCKET_BASE ?? 'http://localhost:7002/realtime',
apiKey: import.meta.env.VITE_API_KEY ?? '', apiKey: import.meta.env.VITE_API_KEY ?? '',

37
src/lib/runtime-env.ts Normal file
View File

@@ -0,0 +1,37 @@
// Runtime (container) env, injected by the Docker entrypoint into
// /runtime-env.js as window.__FABRIC_ENV__ (NOT build-time). Empty/unset
// keeps the prior behavior.
type FabricEnv = { oidcOnly?: boolean; fixToCenter?: string }
const env: FabricEnv =
(typeof window !== 'undefined' && (window as unknown as { __FABRIC_ENV__?: FabricEnv }).__FABRIC_ENV__) || {}
// FABRIC_OIDC_ONLY: hide the username/password form (SSO is the only login).
export const OIDC_ONLY = env.oidcOnly === true
// FIX_TO_CENTER: when non-empty, the Center API base is pinned to this and
// the login page no longer shows the "Center API Base" input.
export const FIXED_CENTER = (env.fixToCenter ?? '').trim()
export const DEFAULT_CENTER = 'http://localhost:7001/api'
// Where OIDC exchange should call back to. FIX_TO_CENTER wins; otherwise
// the value the user used to start SSO (persisted before redirect).
const OIDC_CENTER_KEY = 'fabric.oidc.center.v1'
export function rememberOidcCenter(base: string): void {
try {
localStorage.setItem(OIDC_CENTER_KEY, base)
} catch {
// ignore
}
}
export function resolveCenterBase(): string {
if (FIXED_CENTER) return FIXED_CENTER
try {
const v = localStorage.getItem(OIDC_CENTER_KEY)
if (v) return v
} catch {
// ignore
}
return DEFAULT_CENTER
}

View File

@@ -1,13 +1,24 @@
import { StrictMode } from 'react' import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom' import { BrowserRouter, HashRouter } from 'react-router-dom'
import './index.css' import './index.css'
import App from './App.tsx' import App from './App.tsx'
import { AuthProvider } from './auth/AuthContext'
import { applyBrand } from './lib/brand'
applyBrand()
// The packaged desktop app loads the bundled SPA over file://, where the
// History API has no server to back path routing — use HashRouter there.
// The web build (served over http behind nginx) keeps clean BrowserRouter URLs.
const Router = window.location.protocol === 'file:' ? HashRouter : BrowserRouter
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
<BrowserRouter> <Router>
<AuthProvider>
<App /> <App />
</BrowserRouter> </AuthProvider>
</Router>
</StrictMode>, </StrictMode>,
) )

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,119 @@
import { useEffect, useState } from 'react'
import type { FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../auth/auth-context'
import { APP_NAME, LOGO_URL } from '../lib/brand'
import { OIDC_ONLY, FIXED_CENTER, DEFAULT_CENTER, rememberOidcCenter } from '../lib/runtime-env'
import { oidcStatusCenter } from '../lib/center-auth-client'
export default function LoginPage() { export default function LoginPage() {
const navigate = useNavigate()
const { login, isAuthed, session } = useAuth()
const [centerApiBase, setCenterApiBase] = useState(FIXED_CENTER || DEFAULT_CENTER)
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [oidcEnabled, setOidcEnabled] = useState(false)
useEffect(() => {
let alive = true
oidcStatusCenter(centerApiBase.trim()).then((s) => {
if (alive) setOidcEnabled(s.enabled)
})
return () => {
alive = false
}
}, [centerApiBase])
async function onSubmit(e: FormEvent) {
e.preventDefault()
setError('')
try {
await login(centerApiBase.trim(), email, password)
navigate('/workspace')
} catch {
setError('Login failed. Please check your email and password.')
}
}
function startOidc() {
const base = centerApiBase.trim().replace(/\/$/, '')
rememberOidcCenter(base)
window.location.href = `${base}/auth/oidc/start`
}
const showPasswordForm = !OIDC_ONLY
const showCenterInput = !FIXED_CENTER
return ( return (
<section> <div className="login-screen">
<h2></h2> <div className="login-card">
<p> Center token </p> {LOGO_URL ? (
</section> <img className="brand-logo" src={LOGO_URL} alt={APP_NAME} />
) : (
<div className="brand-wordmark">{APP_NAME}</div>
)}
<h1>Welcome back</h1>
<p className="login-sub">
{isAuthed ? `Signed in as ${session?.user.email}` : `Sign in to continue to ${APP_NAME}`}
</p>
{showCenterInput ? (
<div className="field">
<label>Center API Base</label>
<input
className="input"
value={centerApiBase}
onChange={(e) => setCenterApiBase(e.target.value)}
placeholder="http://localhost:7001/api"
/>
</div>
) : null}
{oidcEnabled ? (
<button className="btn" type="button" onClick={startOidc} style={{ width: '100%' }}>
Sign in with SSO
</button>
) : null}
{OIDC_ONLY && !oidcEnabled ? (
<p className="error-text" style={{ marginTop: 12 }}>
SSO is not configured on this Center yet.
</p>
) : null}
{showPasswordForm ? (
<>
{oidcEnabled ? <div className="login-or">or</div> : null}
<form onSubmit={onSubmit}>
<div className="field">
<label>Email</label>
<input
className="input"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
type="email"
/>
</div>
<div className="field">
<label>Password</label>
<input
className="input"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
type="password"
/>
</div>
{error ? <p className="error-text" style={{ marginBottom: 12 }}>{error}</p> : null}
<button className="btn" type="submit">Sign in</button>
</form>
</>
) : error ? (
<p className="error-text" style={{ marginTop: 12 }}>{error}</p>
) : null}
</div>
</div>
) )
} }

View File

@@ -0,0 +1,66 @@
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../auth/auth-context'
import { APP_NAME } from '../lib/brand'
import { resolveCenterBase } from '../lib/runtime-env'
import { oidcExchangeCenter } from '../lib/center-auth-client'
// Landing route for the OIDC redirect: Center bounces the browser here
// with #oidc_ticket=... (or #oidc_error=...). We redeem the one-time
// ticket for a full session and adopt it.
export default function OidcCallback() {
const navigate = useNavigate()
const { adoptSession } = useAuth()
const [error, setError] = useState('')
const ran = useRef(false)
useEffect(() => {
if (ran.current) return
ran.current = true
const hash = window.location.hash.replace(/^#/, '')
const params = new URLSearchParams(hash)
const ticket = params.get('oidc_ticket')
const errParam = params.get('oidc_error')
// scrub the fragment so the ticket isn't left in the URL/history
window.history.replaceState(null, '', window.location.pathname)
if (errParam) {
setError(decodeURIComponent(errParam))
return
}
if (!ticket) {
setError('Missing OIDC ticket.')
return
}
oidcExchangeCenter(resolveCenterBase(), ticket)
.then((next) => {
adoptSession(next)
navigate('/workspace', { replace: true })
})
.catch(() => setError('SSO sign-in failed. The ticket may have expired — please try again.'))
}, [adoptSession, navigate])
return (
<div className="login-screen">
<div className="login-card">
<div className="brand-wordmark">{APP_NAME}</div>
{error ? (
<>
<h1>Sign-in failed</h1>
<p className="error-text" style={{ marginBottom: 16 }}>{error}</p>
<button className="btn" type="button" onClick={() => navigate('/login', { replace: true })}>
Back to sign in
</button>
</>
) : (
<>
<h1>Signing you in</h1>
<p className="login-sub">Completing SSO authentication.</p>
</>
)}
</div>
</div>
)
}

View File

@@ -1,61 +1,84 @@
import { useState } from 'react' import axios from 'axios'
import type { FormEvent } from 'react' import { useMemo, useState } from 'react'
import { getApiClient, resetApiClient } from '../lib/api-client' import { Link } from 'react-router-dom'
import { import { useAuth } from '../auth/auth-context'
getRuntimeConfig,
setRuntimeConfig,
} from '../lib/runtime-config'
import type { RuntimeConfig } from '../lib/runtime-config'
import { reconnectSocket } from '../lib/socket-client'
export default function WorkspacePage() { export default function WorkspacePage() {
const [form, setForm] = useState<RuntimeConfig>(getRuntimeConfig()) const { session } = useAuth()
const [health, setHealth] = useState('') const [health, setHealth] = useState('')
const [channelsByGuild, setChannelsByGuild] = useState<Record<string, Array<{ id: string; name: string }>>>({})
async function onSave(e: FormEvent) { const tokenByGuild = useMemo(() => {
e.preventDefault() const map: Record<string, string> = {}
setRuntimeConfig(form) for (const item of session?.guildAccessTokens ?? []) {
resetApiClient() map[item.guildNodeId] = item.token
reconnectSocket()
setHealth('配置已保存')
} }
return map
}, [session])
async function checkHealth() { async function checkCenterHealth() {
if (!session) return
try { try {
const res = await getApiClient().get('/healthz') const res = await axios.get(`${session.centerApiBase}/healthz`)
setHealth(JSON.stringify(res.data)) setHealth(JSON.stringify(res.data))
} catch { } catch {
setHealth('healthz 访问失败') setHealth('Failed to access center healthz')
}
}
async function loadChannels(nodeId: string, endpoint: string) {
const token = tokenByGuild[nodeId]
if (!token) {
setChannelsByGuild((prev) => ({ ...prev, [nodeId]: [] }))
return
}
try {
const res = await axios.get(`${endpoint}/api/channels`, {
headers: { Authorization: `Bearer ${token}` },
})
const list = Array.isArray(res.data) ? res.data : []
setChannelsByGuild((prev) => ({ ...prev, [nodeId]: list }))
} catch {
setChannelsByGuild((prev) => ({ ...prev, [nodeId]: [] }))
} }
} }
return ( return (
<section> <section className="panel">
<h2></h2> <h2>Workspace</h2>
<form onSubmit={onSave} style={{ display: 'grid', gap: 8, maxWidth: 760 }}> <p className="muted">Center: {session?.centerApiBase || '-'}</p>
<input <div style={{ marginBottom: 12 }}>
value={form.guildApiBase} <button className="btn" type="button" onClick={checkCenterHealth}>
onChange={(e) => setForm((v) => ({ ...v, guildApiBase: e.target.value }))} Test Center healthz
placeholder="Guild API Base"
/>
<input
value={form.guildSocketBase}
onChange={(e) => setForm((v) => ({ ...v, guildSocketBase: e.target.value }))}
placeholder="Guild Socket Base"
/>
<input
value={form.apiKey}
onChange={(e) => setForm((v) => ({ ...v, apiKey: e.target.value }))}
placeholder="API Key"
/>
<div style={{ display: 'flex', gap: 8 }}>
<button type="submit"></button>
<button type="button" onClick={checkHealth}>
healthz
</button> </button>
</div> </div>
</form> {health ? <p className="muted">{health}</p> : null}
<p>{health}</p>
<ul className="list-reset">
{(session?.guilds ?? []).map((g) => (
<li key={g.nodeId} className="card" style={{ marginTop: 12 }}>
<div>
<strong>{g.name}</strong> <span className="muted">({g.nodeId})</span>
</div>
<div className="muted">{g.endpoint}</div>
<button className="btn btn-secondary" type="button" onClick={() => loadChannels(g.nodeId, g.endpoint)}>
Load channels
</button>
<ul className="list-reset" style={{ marginTop: 10 }}>
{(channelsByGuild[g.nodeId] ?? []).map((c) => (
<li key={c.id} style={{ marginTop: 6 }}>
<Link
to={`/chat?guildId=${encodeURIComponent(g.nodeId)}&channelId=${encodeURIComponent(c.id)}`}
>
#{c.name}
</Link>
</li>
))}
</ul>
</li>
))}
</ul>
</section> </section>
) )
} }