From 3387d18e96c7e2d34cdcdc50e431dff3aecf577d Mon Sep 17 00:00:00 2001 From: alwoo Date: Sun, 18 Oct 2026 01:05:22 +0400 Subject: [PATCH 001/315] fix(compose): pass registry env through to backend Compose backend missed DOCKER_REGISTRY_* and NPM_REGISTRY_* (ecosystem.config.cjs forwards them); empty stays skipped per contract. From de5d9bd5b96e59f409cf0226d4b35d187d8391d2 Mon Sep 17 00:00:00 2001 From: alwoo Date: Sun, 18 Oct 2026 16:37:09 +0400 Subject: [PATCH 002/315] fix-frontend-monthly-limits-rework --- apps/frontend/src/api/types.ts | 15 ++ .../__tests__/profile-dropdown.test.tsx | 159 +++++++++++++++++- .../src/components/profile-dropdown.tsx | 67 ++++++-- apps/frontend/src/hooks/useProfile.ts | 10 +- apps/frontend/src/i18n/dictionaries/en.ts | 6 + apps/frontend/src/i18n/dictionaries/ru.ts | 6 + apps/frontend/src/i18n/dictionaries/types.ts | 6 + apps/frontend/src/lib/types.ts | 4 +- 8 files changed, 256 insertions(+), 17 deletions(-) diff --git a/apps/frontend/src/api/types.ts b/apps/frontend/src/api/types.ts index fd8a1fb..798883f 100644 --- a/apps/frontend/src/api/types.ts +++ b/apps/frontend/src/api/types.ts @@ -87,6 +87,19 @@ export interface ApiError { correlationId: string; } +/** Single quota bucket: consumed units vs granted total. */ +export interface LimitQuota { + used: number; + total: number; +} + +/** Optional usage limits attached to the identity (all buckets optional). */ +export interface AuthLimits { + daily?: LimitQuota; + weekly?: LimitQuota; + monthly?: LimitQuota; +} + /** POST /api/v1/auth/register + login response user (never carries passwordHash) */ export interface AuthUser { id: string; @@ -96,6 +109,8 @@ export interface AuthUser { provider: 'local' | 'sso-oauth' | 'github-app'; /** ISO-8601 timestamp */ createdAt: string; + /** Optional usage limits — absent when the backend sends no quota. */ + limits?: AuthLimits; } /** Token pair (short-lived access + rotating refresh). */ diff --git a/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx b/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx index 3db920b..eb3cd88 100644 --- a/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx +++ b/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx @@ -91,6 +91,18 @@ const ME_USER = { provider: 'local' as const, createdAt: '2026-01-15T09:00:00.000Z', }; +const ME_USER_WITH_LIMITS = { + ...ME_USER, + limits: { + daily: { used: 5, total: 100 }, + weekly: { used: 20, total: 500 }, + monthly: { used: 100, total: 2000 }, + }, +}; +function currentMeUser() { + const override = (globalThis as Record).__TEST_ME_USER__; + return (override as typeof ME_USER_WITH_LIMITS | undefined) ?? ME_USER; +} const cannedSession = { accessToken: 'test-access', refreshToken: 'test-refresh', @@ -117,7 +129,7 @@ mock.module('../../api/client', () => ({ } }, api: { - me: async () => ME_USER, + me: async () => currentMeUser(), updateMe: async () => ME_USER, logout: async () => ({ ok: true }), refresh: async () => ({ ...cannedSession }), @@ -142,7 +154,7 @@ const { setSession, clearSession } = await import('../../lib/auth-store'); }); } if (url.includes('/auth/me')) { - return new Response(JSON.stringify(ME_USER), { + return new Response(JSON.stringify(currentMeUser()), { status: 200, headers: { 'content-type': 'application/json' }, }); @@ -155,12 +167,14 @@ const { setSession, clearSession } = await import('../../lib/auth-store'); beforeEach(() => { setSession({ ...cannedSession }); + delete (globalThis as Record).__TEST_ME_USER__; }); afterEach(() => { cleanup(); clearSession(); pushMock.mockClear(); + delete (globalThis as Record).__TEST_ME_USER__; }); const USER = { name: 'Devbox Developer', email: 'dev@devbox.local' }; @@ -298,3 +312,144 @@ describe('HeaderProfileDropdown (pure kit AuthorizedUserProfile)', () => { } }); }); + +describe('HeaderProfileDropdown limits (daily/weekly/monthly)', () => { + test('renders 3 limits with values and progress (en)', async () => { + (globalThis as Record).__TEST_ME_USER__ = ME_USER_WITH_LIMITS; + const user = userEvent.setup(); + render(); + + const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); + await user.click(trigger); + await screen.findByRole('menu'); + + const group = await screen.findByTestId('profile-limits'); + expect(group.getAttribute('aria-label')).toBe('Usage limits'); + expect(screen.getByTestId('profile-limits-title').textContent).toBe('Usage limits'); + + expect(screen.getByTestId('profile-limit-daily-label').textContent).toBe('Daily'); + expect(screen.getByTestId('profile-limit-daily-value').textContent).toBe('5 / 100'); + expect(screen.getByTestId('profile-limit-weekly-label').textContent).toBe('Weekly'); + expect(screen.getByTestId('profile-limit-weekly-value').textContent).toBe('20 / 500'); + expect(screen.getByTestId('profile-limit-monthly-label').textContent).toBe('Monthly'); + expect(screen.getByTestId('profile-limit-monthly-value').textContent).toBe('100 / 2000'); + + // Simple progress: used/total % as aria-valuenow (5%, 4%, 5%). + expect(screen.getByTestId('profile-limit-daily-progress').getAttribute('aria-valuenow')).toBe('5'); + expect(screen.getByTestId('profile-limit-weekly-progress').getAttribute('aria-valuenow')).toBe('4'); + expect(screen.getByTestId('profile-limit-monthly-progress').getAttribute('aria-valuenow')).toBe('5'); + + // Old cases still hold alongside limits. + expect(screen.getByRole('link', { name: 'Profile' })).toBeDefined(); + expect(screen.getByRole('button', { name: 'Sign out' })).toBeDefined(); + }); + + test('hides limits group when backend sends no quota', async () => { + const user = userEvent.setup(); + render(); + + const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); + await user.click(trigger); + await screen.findByRole('menu'); + + expect(screen.queryByTestId('profile-limits')).toBeNull(); + expect(screen.getByRole('link', { name: 'Profile' })).toBeDefined(); + }); + + test('ru locale renders translated limit labels', async () => { + (globalThis as Record).__TEST_ME_USER__ = ME_USER_WITH_LIMITS; + document.cookie = 'devbox-locale=ru; path=/'; + try { + const user = userEvent.setup(); + render( + + + , + ); + + const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); + await user.click(trigger); + await screen.findByRole('menu'); + + expect(screen.getByTestId('profile-limits-title').textContent).toBe('Лимиты использования'); + expect(screen.getByTestId('profile-limit-daily-label').textContent).toBe('Дневной'); + expect(screen.getByTestId('profile-limit-daily-value').textContent).toBe('5 / 100'); + expect(screen.getByTestId('profile-limit-weekly-label').textContent).toBe('Недельный'); + expect(screen.getByTestId('profile-limit-weekly-value').textContent).toBe('20 / 500'); + expect(screen.getByTestId('profile-limit-monthly-label').textContent).toBe('Месячный'); + expect(screen.getByTestId('profile-limit-monthly-value').textContent).toBe('100 / 2000'); + expect(screen.getByRole('link', { name: 'Профиль' })).toBeDefined(); + expect(screen.getByRole('button', { name: 'Выйти' })).toBeDefined(); + } finally { + document.cookie = 'devbox-locale=; path=/; max-age=0'; + } + }); + + test('partial limits render only the present bucket', async () => { + (globalThis as Record).__TEST_ME_USER__ = { + ...ME_USER, + limits: { daily: { used: 7, total: 10 } }, + }; + const user = userEvent.setup(); + render(); + + const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); + await user.click(trigger); + await screen.findByRole('menu'); + + expect(screen.getByTestId('profile-limits')).toBeDefined(); + expect(screen.getByTestId('profile-limit-daily-value').textContent).toBe('7 / 10'); + expect(screen.getByTestId('profile-limit-daily-progress').getAttribute('aria-valuenow')).toBe('70'); + expect(screen.queryByTestId('profile-limit-weekly')).toBeNull(); + expect(screen.queryByTestId('profile-limit-monthly')).toBeNull(); + }); + + test('total=0 renders 0% without NaN', async () => { + (globalThis as Record).__TEST_ME_USER__ = { + ...ME_USER, + limits: { daily: { used: 0, total: 0 } }, + }; + const user = userEvent.setup(); + render(); + + const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); + await user.click(trigger); + await screen.findByRole('menu'); + + expect(screen.getByTestId('profile-limit-daily-value').textContent).toBe('0 / 0'); + expect(screen.getByTestId('profile-limit-daily-progress').getAttribute('aria-valuenow')).toBe('0'); + }); + + test('over-quota clamps progress to 100', async () => { + (globalThis as Record).__TEST_ME_USER__ = { + ...ME_USER, + limits: { monthly: { used: 2500, total: 2000 } }, + }; + const user = userEvent.setup(); + render(); + + const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); + await user.click(trigger); + await screen.findByRole('menu'); + + expect(screen.getByTestId('profile-limit-monthly-value').textContent).toBe('2500 / 2000'); + expect(screen.getByTestId('profile-limit-monthly-progress').getAttribute('aria-valuenow')).toBe('100'); + expect(screen.queryByTestId('profile-limit-daily')).toBeNull(); + }); + + test('negative used clamps progress to 0', async () => { + (globalThis as Record).__TEST_ME_USER__ = { + ...ME_USER, + limits: { weekly: { used: -5, total: 100 } }, + }; + const user = userEvent.setup(); + render(); + + const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); + await user.click(trigger); + await screen.findByRole('menu'); + + expect(screen.getByTestId('profile-limit-weekly-value').textContent).toBe('-5 / 100'); + expect(screen.getByTestId('profile-limit-weekly-progress').getAttribute('aria-valuenow')).toBe('0'); + }); +}); diff --git a/apps/frontend/src/components/profile-dropdown.tsx b/apps/frontend/src/components/profile-dropdown.tsx index b317f1e..96a947a 100644 --- a/apps/frontend/src/components/profile-dropdown.tsx +++ b/apps/frontend/src/components/profile-dropdown.tsx @@ -12,13 +12,19 @@ import type { Dictionary } from '../i18n/dictionaries/types'; /** * Header user menu — pure kit (@web2bizz/ui 0.26.0 `widgets` entry). - * Thin data adapter (<30 lines): useHeaderProfile() → kit `user`, - * userMenu snapshot en/ru → kit `labels`, sign-out/login → - * router.push('/login'), profile → profileHref="/profile". Loading — - * single kit-token skeleton (UserProfileSkeleton is kit-internal, not - * exported). a11y — native Radix DropdownMenu inside kit Authorized - * (Esc/Tab, focus ring, aria-haspopup / expanded via Trigger asChild + - * ...rest/ref-forwarded UserTrigger 0.26.0). + * Thin data adapter: useHeaderProfile() → kit `user`, userMenu snapshot + * en/ru → kit `labels`, sign-out/login → router.push('/login'), + * profile → profileHref="/profile". Limits (daily/weekly/monthly from + * GET /api/v1/auth/me optional `limits`) render as a sibling below the + * kit menu — AuthorizedUserProfile 0.26.0 has NO children slot (only + * Unauthorized does) and its `usage` prop covers daily/weekly only + * (no monthly), so the custom group preserves monthly — no kit fork. + * Loading — single kit-token skeleton (UserProfileSkeleton is kit-internal, + * not exported). + * a11y — native Radix DropdownMenu inside kit Authorized (Esc/Tab, focus + * ring, aria-haspopup / expanded via Trigger asChild + ...rest/ref-forwarded + * UserTrigger 0.26.0). Limits group uses role="group" + role="progressbar" + * per quota (aria-valuenow = used/total %). * LOCALE-DECOUPLED by design: NO useI18n subscription (it would re-render * this header on every locale switch) and useHeaderProfile() fetches * /auth/me with NO `t` in effect deps (no refetch on language change). @@ -39,6 +45,10 @@ function readStoredUserMenu(): Dictionary['userMenu'] { return isLocale(raw) && raw === 'ru' ? ru.userMenu : en.userMenu; } +/** Quota keys rendered in the dropdown, in display order. */ +const LIMIT_KEYS = ['daily', 'weekly', 'monthly'] as const; +type LimitKey = (typeof LIMIT_KEYS)[number]; + export function HeaderProfileDropdown() { // Mount snapshot — set once, never re-subscribed: language switches // neither refetch the profile nor re-render this dropdown. @@ -65,11 +75,42 @@ export function HeaderProfileDropdown() { } return ( - + <> + + {profile.limits && LIMIT_KEYS.some((key) => profile.limits?.[key]) ? ( +
+

{userMenu.limits.title}

+ {LIMIT_KEYS.map((key: LimitKey) => { + const quota = profile.limits?.[key]; + if (!quota) return null; + const used = quota.used; + const total = quota.total; + const percent = + total > 0 ? Math.min(100, Math.max(0, Math.round((used / total) * 100))) : 0; + return ( +
+ {userMenu.limits[key]} + {`${used} / ${total}`} +
+
+
+
+ ); + })} +
+ ) : null} + ); } diff --git a/apps/frontend/src/hooks/useProfile.ts b/apps/frontend/src/hooks/useProfile.ts index 8ecae96..38c3561 100644 --- a/apps/frontend/src/hooks/useProfile.ts +++ b/apps/frontend/src/hooks/useProfile.ts @@ -19,13 +19,21 @@ export interface UseProfileResult { dismiss: () => void; } -function toProfile(user: { id: string; email: string; firstName: string; lastName: string; createdAt: string }): Profile { +function toProfile(user: { + id: string; + email: string; + firstName: string; + lastName: string; + createdAt: string; + limits?: Profile['limits']; +}): Profile { return { id: user.id, name: `${user.firstName} ${user.lastName}`.trim(), email: user.email, role: 'Owner', createdAt: user.createdAt, + ...(user.limits ? { limits: user.limits } : {}), }; } diff --git a/apps/frontend/src/i18n/dictionaries/en.ts b/apps/frontend/src/i18n/dictionaries/en.ts index 7f66f91..3dd7940 100644 --- a/apps/frontend/src/i18n/dictionaries/en.ts +++ b/apps/frontend/src/i18n/dictionaries/en.ts @@ -246,6 +246,12 @@ export const en: Dictionary = { signOut: 'Sign out', login: 'Log in', noEmail: 'No email', + limits: { + title: 'Usage limits', + daily: 'Daily', + weekly: 'Weekly', + monthly: 'Monthly', + }, }, orgs: { titleA: 'Organizations', diff --git a/apps/frontend/src/i18n/dictionaries/ru.ts b/apps/frontend/src/i18n/dictionaries/ru.ts index 8ce154c..830ef2d 100644 --- a/apps/frontend/src/i18n/dictionaries/ru.ts +++ b/apps/frontend/src/i18n/dictionaries/ru.ts @@ -246,6 +246,12 @@ export const ru: Dictionary = { signOut: 'Выйти', login: 'Войти', noEmail: 'Нет email', + limits: { + title: 'Лимиты использования', + daily: 'Дневной', + weekly: 'Недельный', + monthly: 'Месячный', + }, }, orgs: { titleA: 'Организации', diff --git a/apps/frontend/src/i18n/dictionaries/types.ts b/apps/frontend/src/i18n/dictionaries/types.ts index 0b2b5c3..343ee54 100644 --- a/apps/frontend/src/i18n/dictionaries/types.ts +++ b/apps/frontend/src/i18n/dictionaries/types.ts @@ -248,6 +248,12 @@ export interface Dictionary { signOut: string; login: string; noEmail: string; + limits: { + title: string; + daily: string; + weekly: string; + monthly: string; + }; }; orgs: { titleA: string; diff --git a/apps/frontend/src/lib/types.ts b/apps/frontend/src/lib/types.ts index 9ea8741..616b0db 100644 --- a/apps/frontend/src/lib/types.ts +++ b/apps/frontend/src/lib/types.ts @@ -5,7 +5,7 @@ * TODO REAL-API: replace mock sources inside hooks with ApiClient calls. */ -import type { ProjectScope } from '../api/types'; +import type { AuthLimits, ProjectScope } from '../api/types'; export type ProjectStatus = 'active' | 'draft' | 'archived'; @@ -42,6 +42,8 @@ export interface Profile { role: string; /** ISO-8601 */ createdAt: string; + /** Optional usage limits (mirrors AuthUser.limits, all buckets optional). */ + limits?: AuthLimits; } export type AiProviderStatus = 'connected' | 'disconnected' | 'error'; From 4f97b55e2202d4b80fd317af91f4c572cc273024 Mon Sep 17 00:00:00 2001 From: alwoo Date: Mon, 19 Oct 2026 17:39:49 +0400 Subject: [PATCH 003/315] refactor(backend): single-path logging without stacks or secrets AppLogger is the only log path; warn/error are one-liners (stack only in debug, sanitized). ExternalClient logs service/operation/attempt/latencyMs/status/code only. ApiErrorFilter maps ExternalServiceError with Retry-After 30 on 429/5xx. --- apps/backend/src/common/api-error.filter.ts | 61 +++++++++++++++++-- apps/backend/src/common/app-logger.service.ts | 35 ++++++++--- .../src/common/external/external-client.ts | 34 +++++++++-- 3 files changed, 110 insertions(+), 20 deletions(-) diff --git a/apps/backend/src/common/api-error.filter.ts b/apps/backend/src/common/api-error.filter.ts index 688f3e7..ac1a368 100644 --- a/apps/backend/src/common/api-error.filter.ts +++ b/apps/backend/src/common/api-error.filter.ts @@ -96,17 +96,46 @@ export class ApiErrorFilter implements ExceptionFilter { // Messages are fixed at construction (never carry upstream bodies or // secrets); 5xx upstreams intentionally keep their safe message instead // of the generic 'Unexpected server error'. - // 503 answers carry Retry-After so clients back off instead of polling + // Retryable answers carry Retry-After so clients back off instead of + // polling: 429 rate limit + any 5xx (502 passthrough / 503 unavailable / + // 504 timeout). 4xx client states (401 invalid / 404 missing key) never + // carry it — the fix is user action, not a retry delay. // (proxy /api/v1/* and the /api/opencode/* surface throw // EXTERNAL_UNAVAILABLE when the opencode server is unreachable — // no mock 200s). - if (exception.httpStatus === 503) { + // Logging: normal-path one-liner with service/operation/status/code, + // no stack, no URL/body/Bearer (AppLogger sanitizes); cause/stack (if + // any) goes to debug only. + if (exception.httpStatus === 429 || exception.httpStatus >= 500) { try { res.setHeader('Retry-After', '30'); } catch { // headers already sent — ignore } } + try { + const line = + `[http] handled service=${exception.service} operation=${exception.operation} ` + + `status=${exception.httpStatus} code=${exception.code}`; + if (exception.httpStatus === 429 || exception.httpStatus >= 500) { + this.logger.error(line, correlationId); + } else { + this.logger.warn(line, correlationId); + } + if (exception.cause !== undefined) { + this.logger.debug( + `[http] cause service=${exception.service} operation=${exception.operation} ` + + `code=${exception.code} detail=${String( + exception.cause instanceof Error + ? (exception.cause.stack ?? exception.cause.message) + : exception.cause, + ).slice(0, 2000)}`, + correlationId, + ); + } + } catch { + // ignore logging failures + } const body: ApiError = { code: exception.code, message: exception.message, @@ -134,16 +163,36 @@ export class ApiErrorFilter implements ExceptionFilter { } // Never leak internals on 500 — generic envelope like the node:http build. if (status >= 500) message = 'Unexpected server error'; + // Normal path: one-liner with status/code, no stack, no body/headers. + try { + const line = `[http] handled status=${status} code=${code}`; + if (status >= 500) { + this.logger.error(line, correlationId); + this.logger.debug( + `[http] cause status=${status} code=${code} detail=${String( + (exception as Error)?.stack ?? (exception as Error)?.message ?? String(exception), + ).slice(0, 2000)}`, + correlationId, + ); + } else { + this.logger.warn(line, correlationId); + } + } catch { + // ignore logging failures + } const body: ApiError = { code, message, correlationId }; res.status(status).json(body); return; } - // Unknown error — message + sanitized stack (no secrets), generic envelope. + // Unknown error — fixed one-liner at error (no stack, no secrets); + // sanitized detail goes to debug only, generic envelope on the wire. try { - this.logger.error( - `[http] unhandled: ${(exception as Error)?.message ?? String(exception)}`, - (exception as Error)?.stack, + this.logger.error('[http] unhandled status=500 code=internal_error', correlationId); + this.logger.debug( + `[http] unhandled cause detail=${String( + (exception as Error)?.stack ?? (exception as Error)?.message ?? String(exception), + ).slice(0, 2000)}`, correlationId, ); } catch { diff --git a/apps/backend/src/common/app-logger.service.ts b/apps/backend/src/common/app-logger.service.ts index 30c3d67..998ff9b 100644 --- a/apps/backend/src/common/app-logger.service.ts +++ b/apps/backend/src/common/app-logger.service.ts @@ -56,11 +56,14 @@ const SECRET_KEYS = new Set([ 'jwtttl', 'passwordhash', 'password_hash', - // Per-user OpenCode keys: the server-side encryption secret plus the - // per-user API key field (PUT /api/v1/key body) must never reach - // logs (values scrubbed, keys redacted). + // Per-user OpenCode keys: the server-side encryption secret (+ the previous + // KEK while a rotation window is open) plus the per-user API key field + // (PUT /api/v1/key body) must never reach logs (values scrubbed, keys + // redacted). KEK version ids (key_id) are plaintext by design — not secrets. 'opencodekeysencryptionkey', 'opencode_keys_encryption_key', + 'opencodekeysencryptionkeyprevious', + 'opencode_keys_encryption_key_previous', 'opencodekey', 'opencode_key', ]); @@ -96,6 +99,7 @@ function liveSecrets(): string[] { process.env.JWT_ACCESS_SECRET, process.env.JWT_REFRESH_SECRET, process.env.OPENCODE_KEYS_ENCRYPTION_KEY, + process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS, ]) { if (v && v.length >= 4) out.push(v); } @@ -173,8 +177,12 @@ export function nestLogLevels(level: AppLogLevel = currentLevel()): LogLevel[] { * default-param); the `[domain] event key=value` message prefix stays * greppable and carries structured fields, never secrets. * - errors: `error(message, stack?, correlationId?)` — Nest-compatible - * `(message, stack, context)` shape; stacks are sanitized (URL credentials - * masked, live secrets scrubbed) before reaching the underlying Logger. + * `(message, stack, context)` shape, but stacks NEVER reach the error + * level: normal-path warn/error stay one-liners (`[module] op status code`, + * no `\n at `, no URL/body/Bearer). When a stack-looking second/third arg + * is passed it is sanitized (URL credentials masked, live secrets + * scrubbed, truncated) and emitted at debug only, so diagnostics stay + * available without spamming normal logs. * - requests: pass `correlationId` (or `withCorrelationId(cid)` for a bound * logger) so every line of one request shares `[cid]`. * - secrets: known secret keys redacted, URL credentials masked, @@ -221,11 +229,20 @@ export class AppLogger extends Logger { const stack = secondLooksLikeStack ? stackOrCorrelationId : undefined; const cid = secondLooksLikeStack ? correlationId : stackOrCorrelationId; const base = formatMessage(message, cid); - if (stack === undefined) { - super.error(base); - return; + if (stack !== undefined) { + // Normal path stays a one-liner without `\n at `: the stack is + // sanitized + truncated and emitted at debug only (never at error, + // never with URL/body/Bearer — sanitizeString masks credentials and + // scrubs live secrets the same way as the message path). + try { + if (isEnabled('debug')) { + super.debug(`${base} stack=${sanitizeString(String(stack)).slice(0, 2000)}`); + } + } catch { + // Diagnostics must never break the error line. + } } - super.error(base, sanitizeString(String(stack)).slice(0, 2000)); + super.error(base); } /** Lowest-volume diagnostics (per-attempt traces, payloads summaries). */ diff --git a/apps/backend/src/common/external/external-client.ts b/apps/backend/src/common/external/external-client.ts index 372b73e..1de1bd1 100644 --- a/apps/backend/src/common/external/external-client.ts +++ b/apps/backend/src/common/external/external-client.ts @@ -11,8 +11,11 @@ * network/timeout exhaustion throws ExternalServiceError. * - Logs (via AppLogger, correlationId-bound, secrets never logged — no * URL/query/headers/bodies, only service/operation/attempt/latencyMs/ - * status): debug on start + success, warn on retryable attempt failure, - * error on final failure. + * status/code): debug on start + success, warn on retryable attempt + * failure, error on final failure. Normal-path warn/error are one-liners + * without stack (`\n at ` never appears there); diagnostics (cause/stack) + * go to debug only, sanitized by AppLogger (URL credentials masked, live + * secrets scrubbed). */ import { Injectable } from '@nestjs/common'; import { AppLogger } from '../app-logger.service.js'; @@ -128,7 +131,7 @@ export class ExternalClient { const retryable = fromStatus(service, operation, res.status, attempt); this.logger.warn( `[external] retry service=${service} operation=${operation} ` + - `attempt=${attempt} status=${res.status} latencyMs=${latencyMs}`, + `attempt=${attempt} status=${res.status} code=${retryable.code} latencyMs=${latencyMs}`, correlationId, ); throw retryable; @@ -145,11 +148,23 @@ export class ExternalClient { } catch (err) { const latencyMs = Date.now() - startedAt; if (err instanceof ExternalServiceError) { + // One-liner without stack: [module operation status code]. + // Cause/stack (if any) goes to debug only — AppLogger sanitizes it + // (URL credentials masked, live secrets scrubbed), never to error. this.logger.error( `[external] failure service=${service} operation=${operation} ` + - `code=${err.code} attempt=${err.attempt} latencyMs=${latencyMs}`, + `status=${err.status ?? '-'} code=${err.code} attempt=${err.attempt} latencyMs=${latencyMs}`, correlationId, ); + if (err.cause !== undefined) { + this.logger.debug( + `[external] cause service=${service} operation=${operation} code=${err.code} ` + + `detail=${String( + err.cause instanceof Error ? (err.cause.stack ?? err.cause.message) : err.cause, + ).slice(0, 2000)}`, + correlationId, + ); + } throw err; } // Non-retryable 4xx normalization (fromStatus) or unexpected throw — @@ -157,7 +172,16 @@ export class ExternalClient { const normalized = fromUnknown(service, operation, err, retryOpts.maxAttempts ?? 1); this.logger.error( `[external] failure service=${service} operation=${operation} ` + - `code=${normalized.code} latencyMs=${latencyMs}`, + `status=${normalized.status ?? '-'} code=${normalized.code} latencyMs=${latencyMs}`, + correlationId, + ); + this.logger.debug( + `[external] cause service=${service} operation=${operation} code=${normalized.code} ` + + `detail=${String( + normalized.cause instanceof Error + ? (normalized.cause.stack ?? normalized.cause.message) + : (normalized.cause ?? err), + ).slice(0, 2000)}`, correlationId, ); throw normalized; From 6df76b0f076a7602dbd2d8a2c2ce726b7dbf9d9c Mon Sep 17 00:00:00 2001 From: alwoo Date: Mon, 19 Oct 2026 17:39:54 +0400 Subject: [PATCH 004/315] feat(backend): rotate opencode KEK without downtime, map zen go usage Dual-read decrypt by key_id (legacy rows fall back active to previous, lazily re-wrapped); keys:reencrypt script converges unread rows; migration 0006 adds key_id. Billing targets hard-coded Zen Go usage endpoint, percent windows map to used/limit 100; env drops OPENCODE_BILLING_URL override. --- .../0006_user_opencode_keys_key_id.sql | 20 + apps/backend/package.json | 1 + apps/backend/src/contracts.ts | 27 +- apps/backend/src/db/e2e-db.ts | 5 +- apps/backend/src/db/schema.ts | 14 +- apps/backend/src/env.spec.ts | 60 +- apps/backend/src/env.ts | 108 ++- .../crypto.service.hardening.spec.ts | 647 ++++++++++++++++++ .../src/opencode-keys/crypto.service.spec.ts | 123 +++- .../src/opencode-keys/crypto.service.ts | 215 ++++-- .../opencode-keys/opencode-billing.service.ts | 270 +++++++- .../opencode-keys/opencode-keys.controller.ts | 17 +- .../src/opencode-keys/opencode-keys.dto.ts | 36 +- .../src/opencode-keys/opencode-keys.e2e.ts | 235 ++++++- .../opencode-keys/opencode-keys.service.ts | 49 +- .../src/opencode-keys/reencrypt-keys.ts | 106 +++ 16 files changed, 1775 insertions(+), 158 deletions(-) create mode 100644 apps/backend/drizzle/0006_user_opencode_keys_key_id.sql create mode 100644 apps/backend/src/opencode-keys/crypto.service.hardening.spec.ts create mode 100644 apps/backend/src/opencode-keys/reencrypt-keys.ts diff --git a/apps/backend/drizzle/0006_user_opencode_keys_key_id.sql b/apps/backend/drizzle/0006_user_opencode_keys_key_id.sql new file mode 100644 index 0000000..541961f --- /dev/null +++ b/apps/backend/drizzle/0006_user_opencode_keys_key_id.sql @@ -0,0 +1,20 @@ +-- KEK rotation for per-user OpenCode API keys (backward-compatible). +-- +-- Strategy: rows carry the wrapping KEK version (`key_id`, plaintext, never +-- a secret) so decrypt can dual-read across the rotation window: +-- 1. Deploy the new secret as OPENCODE_KEYS_ENCRYPTION_KEY (+ +-- OPENCODE_KEYS_ACTIVE_KEY_ID) and keep the old one as +-- OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS (+ OPENCODE_KEYS_PREVIOUS_KEY_ID). +-- 2. Old rows keep decrypting (keyId → previous KEK, legacy '' → fallback). +-- 3. Lazy re-encrypt on read (GET /api/v1/usage) + the `keys:reencrypt` +-- background pass re-wrap stale rows under the active KEK. +-- 4. Drop the previous secret once no `key_id != ` rows remain. +-- +-- Safety: the pre-migration table is snapshotted to +-- `user_opencode_keys_backup_0006` (one-time; IF NOT EXISTS keeps reruns +-- idempotent) and legacy rows backfill to 'v1', which decrypts with the +-- unchanged secret — reads never break mid-rotation. +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "user_opencode_keys_backup_0006" AS TABLE "user_opencode_keys"; +--> statement-breakpoint +ALTER TABLE "user_opencode_keys" ADD COLUMN IF NOT EXISTS "key_id" text NOT NULL DEFAULT 'v1'; diff --git a/apps/backend/package.json b/apps/backend/package.json index 4f353a6..1994f78 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -12,6 +12,7 @@ "test": "for f in $(find dist -name '*.spec.js' | sort); do bun \"$f\" || exit 1; done", "test:e2e": "bun run build && bun dist/api/versioning.e2e.js && bun dist/opencode/opencode.e2e.js && bun dist/projects/projects.e2e.js && bun dist/projects/github/github.e2e.js && bun dist/common/external/external-client.e2e.js && bun dist/common/external/external-error.spec.js && bun dist/common/external/retry.spec.js && bun dist/env.spec.js && bun dist/auth/auth.e2e.js && bun dist/opencode-keys/crypto.service.spec.js && bun dist/opencode-keys/opencode-keys.e2e.js && bun dist/repos/repos.service.spec.js && bun dist/repos/repos.e2e.js && bun dist/docker-registry/docker-registry.service.spec.js && bun dist/docker-registry/docker-registry.e2e.js && bun dist/npm-registry/npm-registry.service.spec.js && bun dist/npm-registry/npm-registry.e2e.js && bun dist/organizations/organizations.service.spec.js && bun dist/organizations/organizations.e2e.js", "test:e2e:opencode-keys": "bun run build && bun dist/opencode-keys/crypto.service.spec.js && bun dist/opencode-keys/opencode-keys.e2e.js", + "keys:reencrypt": "bun run build && bun dist/opencode-keys/reencrypt-keys.js", "test:e2e:auth": "bun run build && bun dist/auth/auth.e2e.js", "test:e2e:projects": "bun run build && bun dist/projects/projects.e2e.js", "test:e2e:github": "bun run build && bun dist/projects/github/github.e2e.js", diff --git a/apps/backend/src/contracts.ts b/apps/backend/src/contracts.ts index cb4e08d..3c4d6dc 100644 --- a/apps/backend/src/contracts.ts +++ b/apps/backend/src/contracts.ts @@ -147,10 +147,31 @@ export interface OpencodeKeyStatus { updatedAt?: string; } -/** GET /api/v1/usage — live upstream balance+usage (no cache/TTL). */ +/** Single usage bucket — real `used/limit` pair from upstream (no derivation). */ +export interface OpencodeLimitBucket { + used: number; + limit: number; +} + +/** GET /api/v1/usage — live Zen Go usage (percent windows mapped to used/limit 100). */ export interface OpencodeUsage { - balance: number; - usage: number; + /** Legacy pay-as-you-go fields — present only for legacy upstream payloads. */ + balance?: number; + /** Legacy pay-as-you-go total — present only for legacy upstream payloads. */ + usage?: number; /** ISO-8601 time of the upstream response */ updatedAt: string; + /** + * Zen Go windows mapped to used/limit (`percent` → `{ used: percent, limit: 100 }`). + * `rolling` is the Zen 5-hour window (20% of monthly); legacy `daily` has + * no Zen equivalent and is kept for old payloads. Present only when the + * upstream payload carries finite numbers — never derived from a total. + * Upstream shape is the Zen Go endpoint (module OPENCODE_BILLING_URL + * constant = https://opencode.ai/zen/go/v1/usage) — the billing service + * maps percent windows and passes legacy buckets through when finite. + */ + rolling?: OpencodeLimitBucket; + daily?: OpencodeLimitBucket; + weekly?: OpencodeLimitBucket; + monthly?: OpencodeLimitBucket; } diff --git a/apps/backend/src/db/e2e-db.ts b/apps/backend/src/db/e2e-db.ts index 3ddf1f4..72fe9f4 100644 --- a/apps/backend/src/db/e2e-db.ts +++ b/apps/backend/src/db/e2e-db.ts @@ -11,7 +11,7 @@ * surface (503 EXTERNAL_UNAVAILABLE + Retry-After 30 + correlationId) * instead of silently passing. Never logs secrets (URLs carry * credentials — only reachability outcomes are logged). - * - `applyTestMigrations(url)` — applies drizzle/0001..0005 in order + * - `applyTestMigrations(url)` — applies drizzle/0001..0006 in order * (idempotent IF NOT EXISTS) so the suite starts from a known schema. */ import { readFileSync } from "node:fs"; @@ -73,6 +73,7 @@ const MIGRATION_FILES = [ "0003_users.sql", "0004_organizations.sql", "0005_user_opencode_keys.sql", + "0006_user_opencode_keys_key_id.sql", ]; /** Locates apps/backend/drizzle from src/ or dist/ layouts (CJS __dirname). */ @@ -81,7 +82,7 @@ function drizzleDir(): string { } /** - * Applies drizzle/0001..0005 in file order (node-pg runs multi-statement + * Applies drizzle/0001..0006 in file order (node-pg runs multi-statement * scripts in one query; files are IF NOT EXISTS idempotent). */ export async function applyTestMigrations(url: string): Promise { diff --git a/apps/backend/src/db/schema.ts b/apps/backend/src/db/schema.ts index e3a72d1..99b2802 100644 --- a/apps/backend/src/db/schema.ts +++ b/apps/backend/src/db/schema.ts @@ -129,11 +129,14 @@ export type UserRow = typeof users.$inferSelect; /** * Per-user OpenCode API keys (durable contract; see - * drizzle/0005_user_opencode_keys.sql). One row per user (user_id is both - * PK and FK → users(id) ON DELETE CASCADE, so deleting a user drops their - * key). The API key itself is stored ONLY as AES-256-GCM ciphertext - * (encrypted_key = base64(ct || tag), iv = base64(iv)) — plaintext never - * touches the DB, the logs, or the wire back to the client. + * drizzle/0005_user_opencode_keys.sql + 0006_user_opencode_keys_key_id.sql). + * One row per user (user_id is both PK and FK → users(id) ON DELETE CASCADE, + * so deleting a user drops their key). The API key itself is stored ONLY as + * AES-256-GCM ciphertext (encrypted_key = base64(ct || tag), iv = + * base64(iv)) — plaintext never touches the DB, the logs, or the wire back + * to the client. `keyId` names the KEK version that wrapped the row + * (dual-read decrypt across the rotation window; legacy '' = pre-versioning + * row, readable via the active → previous fallback, lazily re-wrapped). */ export const userOpencodeKeys = pgTable("user_opencode_keys", { userId: uuid("user_id") @@ -141,6 +144,7 @@ export const userOpencodeKeys = pgTable("user_opencode_keys", { .references(() => users.id, { onDelete: "cascade" }), encryptedKey: text("encrypted_key").notNull(), iv: text("iv").notNull(), + keyId: text("key_id").notNull().default("v1"), updatedAt: timestamp("updated_at", { withTimezone: true }) .defaultNow() .notNull(), diff --git a/apps/backend/src/env.spec.ts b/apps/backend/src/env.spec.ts index d508112..22fe6ff 100644 --- a/apps/backend/src/env.spec.ts +++ b/apps/backend/src/env.spec.ts @@ -59,7 +59,6 @@ function baseEnv(): Source { AUTH_LEGACY_MOCK_FALLBACK: 'false', ORG_INVITE_TTL_SEC: '86400', OPENCODE_KEYS_ENCRYPTION_KEY: 'test-opencode-keys-encryption-key-not-real-0123456789', - OPENCODE_BILLING_URL: 'https://billing.example.com/usage', } as Source; } @@ -112,7 +111,6 @@ const checks: Array<{ name: string; run: () => void }> = [ assert.equal(env.authLegacyMockFallback, false); assert.equal(env.orgInviteTtlSec, 86400); assert.equal(env.opencodeKeysEncryptionKey, 'test-opencode-keys-encryption-key-not-real-0123456789'); - assert.equal(env.opencodeBillingUrl, 'https://billing.example.com/usage'); assert.deepEqual(warnings, []); }, }, @@ -718,19 +716,61 @@ const checks: Array<{ name: string; run: () => void }> = [ }, }, { - name: 'OPENCODE_BILLING_URL unset → default + WARN; garbage is ERROR', + name: 'OPENCODE_KEYS rotation vars: defaults v1/v0 + empty previous; explicit ok; short previous ERROR; bad id ERROR', run: () => { - const unset = validateEnvWithWarnings(without(baseEnv(), 'OPENCODE_BILLING_URL')); - assert.equal(unset.env.opencodeBillingUrl, 'https://api.opencode.ai/usage'); + const unset = validateEnvWithWarnings( + without( + baseEnv(), + 'OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS', + 'OPENCODE_KEYS_ACTIVE_KEY_ID', + 'OPENCODE_KEYS_PREVIOUS_KEY_ID', + ), + ); + assert.equal(unset.env.opencodeKeysEncryptionKeyPrevious, ''); + assert.equal(unset.env.opencodeKeysActiveKeyId, 'v1'); + assert.equal(unset.env.opencodeKeysPreviousKeyId, 'v0'); + const explicit = validateEnv({ + ...baseEnv(), + OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS: + 'test-opencode-keys-previous-key-not-real-0123456789', + OPENCODE_KEYS_ACTIVE_KEY_ID: 'v2', + OPENCODE_KEYS_PREVIOUS_KEY_ID: 'v1', + } as Source); + assert.equal( + explicit.opencodeKeysEncryptionKeyPrevious, + 'test-opencode-keys-previous-key-not-real-0123456789', + ); + assert.equal(explicit.opencodeKeysActiveKeyId, 'v2'); + assert.equal(explicit.opencodeKeysPreviousKeyId, 'v1'); + const prevWarn = validateEnvWithWarnings({ + ...baseEnv(), + OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS: + 'test-opencode-keys-previous-key-not-real-0123456789', + } as Source); assert.ok( - unset.warnings.some((w) => w.includes('OPENCODE_BILLING_URL') && w.includes('WARN')), - `expected billing-url WARN, got: ${JSON.stringify(unset.warnings)}`, + prevWarn.warnings.some( + (w) => w.includes('OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS') && w.includes('WARN'), + ), + `expected previous-key rotation WARN, got: ${JSON.stringify(prevWarn.warnings)}`, + ); + const shortMsg = expectThrow( + () => + validateEnv({ + ...baseEnv(), + OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS: 'too-short', + } as Source), + /\[env\] OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS/, + 'short previous key', ); + assert.ok(!shortMsg.includes('too-short'), 'secret leaked into the error'); expectThrow( - () => validateEnv({ ...baseEnv(), OPENCODE_BILLING_URL: '::bad::' } as Source), - /\[env\] OPENCODE_BILLING_URL/, - 'bad billing url', + () => validateEnv({ ...baseEnv(), OPENCODE_KEYS_ACTIVE_KEY_ID: 'bad id!' } as Source), + /\[env\] OPENCODE_KEYS_ACTIVE_KEY_ID/, + 'bad active key id', ); + // Empty id falls back to the default (never throws — ids are non-secret). + const emptyId = validateEnv({ ...baseEnv(), OPENCODE_KEYS_PREVIOUS_KEY_ID: '' } as Source); + assert.equal(emptyId.opencodeKeysPreviousKeyId, 'v0'); }, }, ]; diff --git a/apps/backend/src/env.ts b/apps/backend/src/env.ts index c6928e2..53201ed 100644 --- a/apps/backend/src/env.ts +++ b/apps/backend/src/env.ts @@ -29,11 +29,22 @@ export interface AppEnv { /** * Server secret for per-user OpenCode API-key encryption at rest * ('' = unconfigured — key endpoints answer 500; explicit values must be - * ≥ 32 chars; never logged). + * ≥ 32 chars; never logged). This is the ACTIVE KEK: new rows are wrapped + * with it under `opencodeKeysActiveKeyId`. */ opencodeKeysEncryptionKey: string; - /** Upstream usage endpoint (GET, per-user Bearer; never carries secrets). */ - opencodeBillingUrl: string; + /** + * Previous KEK secret (rotation window only, '' = none). While set, rows + * wrapped with the previous KEK stay readable (dual-read); the lazy + + * background re-encrypt pass re-wraps them under the active KEK. Remove + * once no stale rows remain. Explicit values must be ≥ 32 chars; never + * logged. + */ + opencodeKeysEncryptionKeyPrevious: string; + /** Active KEK version id for new rows (default "v1"; stored plaintext). */ + opencodeKeysActiveKeyId: string; + /** Previous KEK version id (default "v0"; stored plaintext, not a secret). */ + opencodeKeysPreviousKeyId: string; /** May be '' when no credentials/host configured — pg stub stays skipped. */ databaseUrl: string; corsOrigins: string[]; @@ -285,7 +296,9 @@ export const envRawSchema = z.object({ AUTH_LEGACY_MOCK_FALLBACK: z.string().optional(), ORG_INVITE_TTL_SEC: z.string().optional(), OPENCODE_KEYS_ENCRYPTION_KEY: z.string().optional(), - OPENCODE_BILLING_URL: z.string().optional(), + OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS: z.string().optional(), + OPENCODE_KEYS_ACTIVE_KEY_ID: z.string().optional(), + OPENCODE_KEYS_PREVIOUS_KEY_ID: z.string().optional(), }); export type EnvRaw = z.infer; @@ -314,18 +327,22 @@ export const DEFAULT_JWT_REFRESH_TTL_SEC = 604800; /** Default organization invite-token TTL (24h, in seconds). */ export const DEFAULT_ORG_INVITE_TTL_SEC = 86400; -/** - * Default upstream OpenCode usage endpoint (GET with per-user Bearer). - * WARNING: unverified — no public billing/usage path was discoverable on - * opencode.ai (probed 2026-10-13: /api/*usage, /zen/v1/*usage, api.opencode.ai - * catch-all 200 "Not Found"). Override via OPENCODE_BILLING_URL in .env when - * the real endpoint is known (see .env.example). - */ -export const DEFAULT_OPENCODE_BILLING_URL = "https://api.opencode.ai/usage"; - /** Minimum OPENCODE_KEYS_ENCRYPTION_KEY length (AES-256 key material, SHA-256 derived). */ export const MIN_OPENCODE_KEYS_ENCRYPTION_KEY_LENGTH = 32; +/** Default KEK version id for newly wrapped rows (stored plaintext, not a secret). */ +export const DEFAULT_OPENCODE_KEYS_ACTIVE_KEY_ID = "v1"; + +/** Default previous-KEK version id (rotation window only; not a secret). */ +export const DEFAULT_OPENCODE_KEYS_PREVIOUS_KEY_ID = "v0"; + +/** + * Allowed KEK version-id shape: leading alnum + up to 31 alnum/`_`/`-` + * (e.g. "v1", "2026-10"). Ids travel in plaintext (`key_id` column), so the + * rule only keeps them greppable and SQL-safe. + */ +export const OPENCODE_KEYS_KEY_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/; + /** Minimum explicit JWT secret length (dev ephemeral fallback bypasses this). */ export const MIN_JWT_SECRET_LENGTH = 32; @@ -702,7 +719,32 @@ export function validateEnvWithWarnings( // unset secret WARNs and key endpoints answer 500 opencode_keys_unconfigured // instead of breaking every other suite at boot. An explicit secret shorter // than 32 chars is ERROR (value never echoed — it is key material). - // Rotation is out of scope: one key per deploy, no re-encrypt (see .env.example). + // Rotation (no downtime): deploy the new secret as + // OPENCODE_KEYS_ENCRYPTION_KEY (+ OPENCODE_KEYS_ACTIVE_KEY_ID) and keep the + // old one as OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS (+ + // OPENCODE_KEYS_PREVIOUS_KEY_ID) — dual-read keeps old rows decryptable + // while the lazy + `keys:reencrypt` background pass re-wraps them under the + // active KEK; drop the previous secret once no stale rows remain. + const keyIdOr = (raw: string | undefined, fallback: string, name: string): string => { + const id = (raw ?? "").trim() || fallback; + if (!OPENCODE_KEYS_KEY_ID_PATTERN.test(id)) { + throw new Error( + `[env] ${name} must match ${OPENCODE_KEYS_KEY_ID_PATTERN} (e.g. "v2"), got ${JSON.stringify(raw ?? "")}. ` + + "Check your .env (see .env.example).", + ); + } + return id; + }; + const opencodeKeysActiveKeyId = keyIdOr( + firstNonEmpty(env.OPENCODE_KEYS_ACTIVE_KEY_ID), + DEFAULT_OPENCODE_KEYS_ACTIVE_KEY_ID, + "OPENCODE_KEYS_ACTIVE_KEY_ID", + ); + const opencodeKeysPreviousKeyId = keyIdOr( + firstNonEmpty(env.OPENCODE_KEYS_PREVIOUS_KEY_ID), + DEFAULT_OPENCODE_KEYS_PREVIOUS_KEY_ID, + "OPENCODE_KEYS_PREVIOUS_KEY_ID", + ); const opencodeKeysEncryptionKeyRaw = firstNonEmpty( env.OPENCODE_KEYS_ENCRYPTION_KEY, ); @@ -724,25 +766,27 @@ export function validateEnvWithWarnings( "Set it explicitly (see .env.example).", ); } - // Billing endpoint: full-URL knob so the unverified default path can be - // corrected without a code change. Set-but-invalid URL is ERROR (fail-fast - // like OPENCODE_URL); empty → default + WARN. Read-only config (outbound - // GET target, carries no secrets itself). - const opencodeBillingRaw = firstNonEmpty(env.OPENCODE_BILLING_URL); - let opencodeBillingUrl: string; - if (opencodeBillingRaw) { - opencodeBillingUrl = assertValidUrl( - opencodeBillingRaw, - "OPENCODE_BILLING_URL", - ); - } else { - opencodeBillingUrl = DEFAULT_OPENCODE_BILLING_URL; + // Previous KEK (rotation window only): unset is the normal steady state + // (no WARN); set-but-short is ERROR (fail-closed, value never echoed). + const opencodeKeysEncryptionKeyPreviousRaw = firstNonEmpty( + env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS, + ); + let opencodeKeysEncryptionKeyPrevious = ""; + if (opencodeKeysEncryptionKeyPreviousRaw) { + if ( + opencodeKeysEncryptionKeyPreviousRaw.length < + MIN_OPENCODE_KEYS_ENCRYPTION_KEY_LENGTH + ) { + throw new Error( + `[env] OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS must be at least ${MIN_OPENCODE_KEYS_ENCRYPTION_KEY_LENGTH} chars (see .env.example).`, + ); + } + opencodeKeysEncryptionKeyPrevious = opencodeKeysEncryptionKeyPreviousRaw; warn( - "[env] WARN OPENCODE_BILLING_URL is unset, falling back to " + - `${DEFAULT_OPENCODE_BILLING_URL} (unverified default, see .env.example).`, + "[env] WARN OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS is set (rotation window) — " + + "finish the lazy/background re-encrypt pass, then remove it (see .env.example).", ); } - // --- database -------------------------------------------------------------- // NOTE: explicit value passes through untouched; never echoed in errors/logs. const explicitDb = firstNonEmpty(env.DATABASE_URL); @@ -1429,7 +1473,9 @@ export function validateEnvWithWarnings( opencodeUrl, opencodeToken, opencodeKeysEncryptionKey, - opencodeBillingUrl, + opencodeKeysEncryptionKeyPrevious, + opencodeKeysActiveKeyId, + opencodeKeysPreviousKeyId, databaseUrl, corsOrigins, requestTimeoutMs, diff --git a/apps/backend/src/opencode-keys/crypto.service.hardening.spec.ts b/apps/backend/src/opencode-keys/crypto.service.hardening.spec.ts new file mode 100644 index 0000000..fe99293 --- /dev/null +++ b/apps/backend/src/opencode-keys/crypto.service.hardening.spec.ts @@ -0,0 +1,647 @@ +/** + * CryptoService hardening + rotation-convergence checks — self-contained runner (plain node:assert). + * + * Runs against COMPILED dist (same constraint as the *.e2e.ts runners): + * `bun run build && bun dist/opencode-keys/crypto.service.hardening.spec.js` + * Also executes under `bun test dist` (top-level run, throws on failure). + * + * Complements crypto.service.spec.ts (which owns roundtrip/random-IV/ + * legacy/rotation/wrong-key/tamper/malformed/missing + env.spec.ts KEK + * validation + opencode-keys.e2e.ts PG-backed lifecycle): this file pins + * boundary values (empty/unicode/huge), hostile envelopes (null/undefined/ + * non-string/short-IV/long-IV/short-data/swapped/tampered-tag/truncated), + * KEK misconfiguration edges (short active, malformed ids, same-id no-op, + * whitespace trim, isActiveKeyId falsy/unconfigured), no-caching across env + * swaps, log hygiene (fixed event only), plus DB-free rotation convergence + * (old row via previous → re-encrypt under active → key_id updated) and + * integrity (decrypt == source + keyId in fake row + mocked billing usage + * 200, without PG or live secrets). + * + * Dummy KEKs only (≥32 chars, `...-not-real-...`), via process.env in-test, + * never logged (roles + keyIds only, never values). .env.example keeps the + * placeholder + comment (no real secrets there either). + */ +import assert from "node:assert/strict"; + +// --- Dummy key material (test-only, never a real OpenCode API key) --------- +const ACTIVE_A = "hardening-test-kek-active-not-real-0123456789abcd"; +const PREVIOUS_A = "hardening-test-kek-previous-not-real-0123456789ab"; +const ACTIVE_B = "hardening-test-kek-rotated-not-real-0123456789abcd"; +const THIRD_C = "hardening-test-kek-third-not-real-0123456789abcdef"; +const PLAINTEXT = "hardening-test-opencode-api-key-not-real-0123456789"; + +function setKeyring( + active: string, + opts?: { activeId?: string; previous?: string; previousId?: string }, +): void { + process.env.OPENCODE_KEYS_ENCRYPTION_KEY = active; + process.env.OPENCODE_KEYS_ACTIVE_KEY_ID = opts?.activeId ?? "v1"; + if (opts?.previous === undefined) { + delete process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS; + } else { + process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS = opts.previous; + } + process.env.OPENCODE_KEYS_PREVIOUS_KEY_ID = opts?.previousId ?? "v0"; +} + +function clearKeyring(): void { + delete process.env.OPENCODE_KEYS_ENCRYPTION_KEY; + delete process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS; + delete process.env.OPENCODE_KEYS_ACTIVE_KEY_ID; + delete process.env.OPENCODE_KEYS_PREVIOUS_KEY_ID; +} + +type SavedEnv = Record; +function saveEnv(): SavedEnv { + return { + OPENCODE_KEYS_ENCRYPTION_KEY: process.env.OPENCODE_KEYS_ENCRYPTION_KEY, + OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS: + process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS, + OPENCODE_KEYS_ACTIVE_KEY_ID: process.env.OPENCODE_KEYS_ACTIVE_KEY_ID, + OPENCODE_KEYS_PREVIOUS_KEY_ID: process.env.OPENCODE_KEYS_PREVIOUS_KEY_ID, + }; +} +function restoreEnv(saved: SavedEnv): void { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } +} + +const codeOf = (fn: () => unknown): string => { + try { + fn(); + } catch (err) { + const body = (err as { getResponse?: () => { code?: string } }).getResponse?.(); + if (body?.code) return body.code; + return (err as Error).message; + } + assert.fail("expected throw"); +}; + +const codeOfAsync = async (fn: () => Promise): Promise => { + try { + await fn(); + } catch (err) { + const body = (err as { getResponse?: () => { code?: string } }).getResponse?.(); + if (body?.code) return body.code; + return (err as Error).message; + } + assert.fail("expected throw"); +}; + +async function main(): Promise { + const saved = saveEnv(); + setKeyring(ACTIVE_A); + + const { CryptoService } = await import("./crypto.service.js"); + const { OpencodeBillingService } = await import("./opencode-billing.service.js"); + const { AppLogger } = await import("../common/app-logger.service.js"); + + let passed = 0; + const check = async (name: string, fn: () => void | Promise): Promise => { + try { + await fn(); + passed += 1; + console.log(`ok - ${name}`); + } catch (err) { + console.error(`FAIL - ${name}: ${(err as Error).message}`); + process.exitCode = 1; + } + }; + + // --- normal: envelope + integrity --------------------------------------- + await check("round-trip decrypt matches source, keyId envelope persists", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + assert.equal(svc.activeKeyId(), "v1"); + const enc = svc.encrypt(PLAINTEXT); + assert.equal(enc.keyId, "v1"); + assert.equal(enc.keyId, svc.activeKeyId()); + assert.equal(svc.decrypt(enc), PLAINTEXT); + assert.equal(svc.decrypt({ keyId: enc.keyId, iv: enc.iv, data: enc.data }), PLAINTEXT); + }); + + await check("base64 shape: 12-byte IV, ciphertext+16-byte tag", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const enc = svc.encrypt(PLAINTEXT); + assert.equal(Buffer.from(enc.iv, "base64").length, 12); + assert.ok(Buffer.from(enc.data, "base64").length > 16); + }); + + // --- boundary: empty / unicode / huge ----------------------------------- + await check("boundary: empty string round-trips", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const enc = svc.encrypt(""); + assert.equal(svc.decrypt(enc), ""); + }); + + await check("boundary: unicode/emoji/multiline/whitespace round-trips", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const tricky = "ключ-🔑-test-日本語\nline2\t tab padded "; + const enc = svc.encrypt(tricky); + assert.equal(svc.decrypt(enc), tricky); + }); + + await check("boundary: huge (32KB) plaintext round-trips", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const huge = "x".repeat(32768); + const enc = svc.encrypt(huge); + assert.equal(svc.decrypt(enc), huge); + }); + + await check("boundary: 1024-char apiKey-like value round-trips", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const long = `sk-${"a".repeat(1021)}`; + assert.equal(long.length, 1024); + assert.equal(svc.decrypt(svc.encrypt(long)), long); + }); + + await check("boundary: many encrypts keep distinct IVs, all decrypt", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const seen = new Set(); + for (let i = 0; i < 20; i += 1) { + const enc = svc.encrypt(PLAINTEXT); + assert.ok(!seen.has(enc.iv), "IV reuse"); + seen.add(enc.iv); + assert.equal(svc.decrypt(enc), PLAINTEXT); + } + assert.equal(seen.size, 20); + }); + + // --- hostile: encrypt invalid types -------------------------------------- + await check("hostile: encrypt null/undefined/non-string throws (no envelope)", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + for (const bad of [null, undefined, 123, true, {}, []] as unknown as string[]) { + assert.throws(() => svc.encrypt(bad)); + } + }); + + // --- hostile: decrypt null/undefined/missing/non-string ----------------- + await check("hostile: decrypt null/undefined/empty-object fails closed", async () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + for (const bad of [null, undefined, {}, { iv: "", data: "" }] as unknown as Array<{ + keyId?: string; + iv: string; + data: string; + }>) { + assert.equal(codeOf(() => svc.decrypt(bad as never)), "opencode_key_unreadable"); + } + }); + + await check("hostile: decrypt missing/non-string iv/data fails closed", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const good = svc.encrypt(PLAINTEXT); + const cases = [ + { keyId: "v1", data: good.data }, + { keyId: "v1", iv: good.iv }, + { keyId: "v1", iv: 123, data: good.data }, + { keyId: "v1", iv: good.iv, data: 456 }, + { keyId: "v1", iv: null, data: good.data }, + { keyId: "v1", iv: good.iv, data: null }, + { keyId: "v1", iv: "", data: "" }, + { keyId: "v1", iv: " ", data: " " }, + ] as unknown as Array<{ keyId: string; iv: string; data: string }>; + for (const c of cases) { + assert.equal(codeOf(() => svc.decrypt(c)), "opencode_key_unreadable"); + } + }); + + await check("hostile: decrypt invalid-base64 / short-IV / long-IV fails closed", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const good = svc.encrypt(PLAINTEXT); + assert.equal(codeOf(() => svc.decrypt({ iv: "!!!", data: "!!! " })), "opencode_key_unreadable"); + const shortIv = Buffer.alloc(11).toString("base64"); + const longIv = Buffer.alloc(13).toString("base64"); + assert.equal(codeOf(() => svc.decrypt({ iv: shortIv, data: good.data })), "opencode_key_unreadable"); + assert.equal(codeOf(() => svc.decrypt({ iv: longIv, data: good.data })), "opencode_key_unreadable"); + }); + + await check("hostile: decrypt tag-only / tiny / swapped / truncated fails closed", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const good = svc.encrypt(PLAINTEXT); + const tagOnly = Buffer.alloc(16).toString("base64"); + const oneByte = Buffer.alloc(1).toString("base64"); + assert.equal(codeOf(() => svc.decrypt({ iv: good.iv, data: tagOnly })), "opencode_key_unreadable"); + assert.equal(codeOf(() => svc.decrypt({ iv: good.iv, data: oneByte })), "opencode_key_unreadable"); + assert.equal( + codeOf(() => svc.decrypt({ keyId: good.keyId, iv: good.data, data: good.iv })), + "opencode_key_unreadable", + ); + const raw = Buffer.from(good.data, "base64"); + const truncated = raw.subarray(0, Math.floor(raw.length / 2)).toString("base64"); + assert.equal(codeOf(() => svc.decrypt({ iv: good.iv, data: truncated })), "opencode_key_unreadable"); + }); + + await check("hostile: tampered IV / tampered tag fails closed", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const enc = svc.encrypt(PLAINTEXT); + const iv = Buffer.from(enc.iv, "base64"); + iv[0] ^= 0xff; + assert.equal( + codeOf(() => svc.decrypt({ iv: iv.toString("base64"), data: enc.data })), + "opencode_key_unreadable", + ); + const data = Buffer.from(enc.data, "base64"); + data[data.length - 1] ^= 0xff; + assert.equal( + codeOf(() => svc.decrypt({ iv: enc.iv, data: data.toString("base64") })), + "opencode_key_unreadable", + ); + }); + + await check("hostile: wrong KEK rejected (explicit keyId + legacy shape)", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const enc = svc.encrypt(PLAINTEXT); + process.env.OPENCODE_KEYS_ENCRYPTION_KEY = ACTIVE_B; + try { + const other = new CryptoService(); + assert.equal(codeOf(() => other.decrypt(enc)), "opencode_key_unreadable"); + assert.equal( + codeOf(() => other.decrypt({ iv: enc.iv, data: enc.data })), + "opencode_key_unreadable", + ); + } finally { + setKeyring(ACTIVE_A); + } + }); + + await check("hostile: third (unknown) KEK fails even with dual-read ring", () => { + setKeyring(THIRD_C); + const third = new CryptoService(); + const foreign = third.encrypt(PLAINTEXT); + setKeyring(ACTIVE_A, { previous: PREVIOUS_A }); + try { + const svc = new CryptoService(); + assert.equal( + codeOf(() => svc.decrypt({ keyId: "v9", iv: foreign.iv, data: foreign.data })), + "opencode_key_unreadable", + ); + assert.equal( + codeOf(() => svc.decrypt({ keyId: foreign.keyId, iv: foreign.iv, data: foreign.data })), + "opencode_key_unreadable", + ); + } finally { + setKeyring(ACTIVE_A); + } + }); + + // --- KEK misconfiguration edges ------------------------------------------ + await check("short active KEK fails closed without echoing the value", () => { + setKeyring("too-short-active-not-a-secret"); + try { + const svc = new CryptoService(); + const msg = codeOf(() => svc.encrypt(PLAINTEXT)); + assert.equal(msg, "opencode_keys_unconfigured"); + assert.equal(codeOf(() => svc.activeKeyId()), "opencode_keys_unconfigured"); + assert.equal(svc.isActiveKeyId("v1"), false); + } finally { + setKeyring(ACTIVE_A); + } + }); + + await check("malformed active/previous keyIds fail closed; empty falls back to default", () => { + setKeyring(ACTIVE_A, { activeId: "bad id!" }); + try { + assert.equal(codeOf(() => new CryptoService().encrypt(PLAINTEXT)), "opencode_keys_unconfigured"); + } finally { + setKeyring(ACTIVE_A); + } + setKeyring(ACTIVE_A, { previous: PREVIOUS_A, previousId: "bad id!" }); + try { + assert.equal(codeOf(() => new CryptoService().encrypt(PLAINTEXT)), "opencode_keys_unconfigured"); + } finally { + setKeyring(ACTIVE_A); + } + setKeyring(ACTIVE_A, { activeId: "" }); + try { + const svc = new CryptoService(); + assert.equal(svc.activeKeyId(), "v1"); + assert.equal(svc.encrypt(PLAINTEXT).keyId, "v1"); + } finally { + setKeyring(ACTIVE_A); + } + }); + + await check("same id on both sides is a single effective key (no dual-read)", () => { + setKeyring(ACTIVE_B); + const before = new CryptoService().encrypt(PLAINTEXT); + assert.equal(before.keyId, "v1"); + // Same id "v1" on both sides with different secrets → previous is dropped. + setKeyring(ACTIVE_A, { activeId: "v1", previous: ACTIVE_B, previousId: "v1" }); + try { + const svc = new CryptoService(); + assert.equal(svc.decrypt(svc.encrypt(PLAINTEXT)), PLAINTEXT); + assert.equal(codeOf(() => svc.decrypt(before)), "opencode_key_unreadable"); + } finally { + setKeyring(ACTIVE_A); + } + }); + + await check("whitespace-padded secrets trim to the same key material", () => { + setKeyring(` ${ACTIVE_A} `); + const svc = new CryptoService(); + const enc = svc.encrypt(PLAINTEXT); + setKeyring(ACTIVE_A); + assert.equal(new CryptoService().decrypt(enc), PLAINTEXT); + }); + + await check("isActiveKeyId falsy/unknown/unconfigured edges", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + assert.equal(svc.isActiveKeyId(null), false); + assert.equal(svc.isActiveKeyId(undefined), false); + assert.equal(svc.isActiveKeyId(""), false); + assert.equal(svc.isActiveKeyId("v9"), false); + assert.equal(svc.isActiveKeyId(" v1 "), false); + assert.equal(svc.isActiveKeyId("v1"), true); + clearKeyring(); + try { + assert.equal(new CryptoService().isActiveKeyId("v1"), false); + } finally { + setKeyring(ACTIVE_A); + } + }); + + await check("activeKeyId fail-closed when unconfigured", () => { + clearKeyring(); + try { + assert.equal(codeOf(() => new CryptoService().activeKeyId()), "opencode_keys_unconfigured"); + } finally { + setKeyring(ACTIVE_A); + } + }); + + await check("keyring resolves at USE time (no caching across env swaps)", () => { + setKeyring(ACTIVE_A); + const enc = new CryptoService().encrypt(PLAINTEXT); + setKeyring(ACTIVE_B, { activeId: "v2", previous: ACTIVE_A, previousId: "v1" }); + assert.equal(new CryptoService().decrypt(enc), PLAINTEXT); + // Drop the previous KEK: the stale row must now fail, fresh rows work. + setKeyring(ACTIVE_B, { activeId: "v2" }); + const fresh = new CryptoService(); + assert.equal(codeOf(() => fresh.decrypt(enc)), "opencode_key_unreadable"); + assert.equal(fresh.decrypt(fresh.encrypt(PLAINTEXT)), PLAINTEXT); + setKeyring(ACTIVE_A); + }); + + await check("decrypt failure logs fixed event only (never envelope/secret/plaintext)", () => { + setKeyring(ACTIVE_A); + const svc = new CryptoService(); + const enc = svc.encrypt(PLAINTEXT); + const captured: unknown[] = []; + const methods = ["debug", "info", "warn", "error"] as const; + const originals = methods.map((m) => AppLogger.prototype[m]); + methods.forEach((m, i) => { + (AppLogger.prototype as unknown as Record void>)[m] = + function (...args: unknown[]) { + captured.push(args); + return (originals[i] as (...a: unknown[]) => unknown).apply(this, args); + }; + }); + try { + process.env.OPENCODE_KEYS_ENCRYPTION_KEY = ACTIVE_B; + assert.equal(codeOf(() => new CryptoService().decrypt(enc)), "opencode_key_unreadable"); + } finally { + methods.forEach((m, i) => { + (AppLogger.prototype as unknown as Record void>)[m] = + originals[i] as (...a: unknown[]) => void; + }); + setKeyring(ACTIVE_A); + } + const dump = JSON.stringify(captured); + assert.ok(dump.includes("opencode_key_unreadable"), "fixed event must be logged"); + assert.ok(!dump.includes(PLAINTEXT), "plaintext reached the logs"); + assert.ok(!dump.includes(ACTIVE_A), "active KEK value reached the logs"); + assert.ok(!dump.includes(ACTIVE_B), "wrong KEK value reached the logs"); + assert.ok(!dump.includes(enc.data), "ciphertext reached the logs"); + }); + + // --- rotation convergence (DB-free, in-memory row) ------------------------- + await check("rotation: old row reads via previous, re-encrypt converges to active", () => { + setKeyring(ACTIVE_A); + const oldSvc = new CryptoService(); + const oldEnc = oldSvc.encrypt(PLAINTEXT); + assert.equal(oldEnc.keyId, "v1"); + type Row = { userId: string; encryptedKey: string; iv: string; keyId: string }; + const row: Row = { + userId: "user-rotation", + encryptedKey: oldEnc.data, + iv: oldEnc.iv, + keyId: oldEnc.keyId, + }; + // Rotate: B active (v2), A previous (v1). + setKeyring(ACTIVE_B, { activeId: "v2", previous: ACTIVE_A, previousId: "v1" }); + try { + const rotated = new CryptoService(); + assert.equal(rotated.isActiveKeyId(row.keyId), false); + const plain = rotated.decrypt({ keyId: row.keyId, iv: row.iv, data: row.encryptedKey }); + assert.equal(plain, PLAINTEXT); + // Lazy/background re-wrap under the active KEK (new randomness, new id). + const fresh = rotated.encrypt(plain); + assert.equal(fresh.keyId, "v2"); + assert.ok(fresh.iv !== row.iv || fresh.data !== row.encryptedKey); + row.encryptedKey = fresh.data; + row.iv = fresh.iv; + row.keyId = fresh.keyId; + assert.equal(rotated.isActiveKeyId(row.keyId), true); + assert.equal( + rotated.decrypt({ keyId: row.keyId, iv: row.iv, data: row.encryptedKey }), + PLAINTEXT, + ); + // Drop previous: converged row still opens via active alone. + setKeyring(ACTIVE_B, { activeId: "v2" }); + assert.equal( + new CryptoService().decrypt({ keyId: row.keyId, iv: row.iv, data: row.encryptedKey }), + PLAINTEXT, + ); + // The pre-rotation envelope no longer opens once previous is dropped. + assert.equal(codeOf(() => new CryptoService().decrypt(oldEnc)), "opencode_key_unreadable"); + } finally { + setKeyring(ACTIVE_A); + } + }); + + await check("rotation: legacy row without keyId converges the same way", () => { + setKeyring(ACTIVE_A); + const enc = new CryptoService().encrypt(PLAINTEXT); + const legacy = { iv: enc.iv, data: enc.data }; + setKeyring(ACTIVE_B, { activeId: "v2", previous: ACTIVE_A, previousId: "v1" }); + try { + const rotated = new CryptoService(); + assert.equal(rotated.decrypt(legacy), PLAINTEXT); + const fresh = rotated.encrypt(rotated.decrypt(legacy)); + assert.equal(fresh.keyId, "v2"); + assert.equal(rotated.decrypt(fresh), PLAINTEXT); + } finally { + setKeyring(ACTIVE_A); + } + }); + + // --- integrity + mocked billing usage (no PG, no live secret) -------------- + await check("integrity: decrypt == source, keyId in row, mocked usage 200", async () => { + setKeyring(ACTIVE_A); + const crypto = new CryptoService(); + + type StoredRow = { + userId: string; + encryptedKey: string; + iv: string; + keyId: string; + updatedAt: string; + }; + const table = new Map(); + let saves = 0; + const fakeKeys = { + async save( + userId: string, + input: { encryptedKey: string; iv: string; keyId: string }, + ): Promise { + saves += 1; + const row: StoredRow = { userId, ...input, updatedAt: new Date().toISOString() }; + table.set(userId, row); + return row; + }, + async findByUserId(userId: string): Promise { + return table.get(userId) ?? null; + }, + }; + let lastAuth: string | null = null; + const fakeExternal = { + async fetchWithRetry(url: string, init: RequestInit = {}): Promise { + lastAuth = new Headers(init.headers).get("authorization"); + assert.ok(typeof url === "string" && url.length > 0); + return new Response(JSON.stringify({ balance: 42.5, usage: 7.25 }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }, + }; + + const billing = new OpencodeBillingService( + fakeKeys as never, + crypto as never, + fakeExternal as never, + ); + const userId = "11111111-1111-4111-8111-111111111111"; + + // PUT-like: encrypt first, persist ciphertext only. + const enc = crypto.encrypt(PLAINTEXT); + const stored = await fakeKeys.save(userId, { + encryptedKey: enc.data, + iv: enc.iv, + keyId: enc.keyId, + }); + assert.equal(stored.keyId, crypto.activeKeyId()); + assert.ok(!stored.encryptedKey.includes(PLAINTEXT)); + assert.ok(!stored.iv.includes(PLAINTEXT)); + assert.equal( + crypto.decrypt({ keyId: stored.keyId, iv: stored.iv, data: stored.encryptedKey }), + PLAINTEXT, + ); + + // GET-like usage via mock: decrypt integrity + per-user Bearer. + lastAuth = null; + const out = await billing.getUsage(userId); + assert.equal(out.balance, 42.5); + assert.equal(out.usage, 7.25); + assert.ok(typeof out.updatedAt === "string" && out.updatedAt.length > 0); + assert.equal(lastAuth, `Bearer ${PLAINTEXT}`); + assert.ok(!JSON.stringify(out).includes(PLAINTEXT)); + assert.equal(saves, 1); + + // Missing key → 404 (no secret needed). + assert.equal(await codeOfAsync(() => billing.getUsage("22222222-2222-4222-8222-222222222222")), "opencode_key_missing"); + }); + + await check("billing lazy re-encrypt: stale row serves 200 then converges to active", async () => { + setKeyring(ACTIVE_A); + const staleCrypto = new CryptoService(); + const staleEnc = staleCrypto.encrypt(PLAINTEXT); + + type StoredRow = { + userId: string; + encryptedKey: string; + iv: string; + keyId: string; + updatedAt: string; + }; + const table = new Map(); + const userId = "33333333-3333-4333-8333-333333333333"; + table.set(userId, { + userId, + encryptedKey: staleEnc.data, + iv: staleEnc.iv, + keyId: "v1", + updatedAt: new Date().toISOString(), + }); + const fakeKeys = { + async save( + uid: string, + input: { encryptedKey: string; iv: string; keyId: string }, + ): Promise { + const row: StoredRow = { userId: uid, ...input, updatedAt: new Date().toISOString() }; + table.set(uid, row); + return row; + }, + async findByUserId(uid: string): Promise { + return table.get(uid) ?? null; + }, + }; + const fakeExternal = { + async fetchWithRetry(): Promise { + return new Response(JSON.stringify({ balance: 42.5, usage: 7.25 }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }, + }; + + // Rotate before the read: stale v1 row must still serve via previous. + setKeyring(ACTIVE_B, { activeId: "v2", previous: ACTIVE_A, previousId: "v1" }); + try { + const billing = new OpencodeBillingService( + fakeKeys as never, + new CryptoService() as never, + fakeExternal as never, + ); + const out = await billing.getUsage(userId); + assert.equal(out.balance, 42.5); + const converged = table.get(userId); + assert.ok(converged); + assert.equal(converged?.keyId, "v2"); + assert.equal( + new CryptoService().decrypt({ + keyId: converged?.keyId, + iv: converged?.iv as string, + data: converged?.encryptedKey as string, + }), + PLAINTEXT, + ); + // Second read stays on the active KEK (no further rotation needed). + const again = await billing.getUsage(userId); + assert.equal(again.usage, 7.25); + assert.equal(table.get(userId)?.keyId, "v2"); + } finally { + setKeyring(ACTIVE_A); + } + }); + + restoreEnv(saved); + console.log(`crypto hardening spec: ${passed} checks run`); +} + +void main(); diff --git a/apps/backend/src/opencode-keys/crypto.service.spec.ts b/apps/backend/src/opencode-keys/crypto.service.spec.ts index b26f73c..6500863 100644 --- a/apps/backend/src/opencode-keys/crypto.service.spec.ts +++ b/apps/backend/src/opencode-keys/crypto.service.spec.ts @@ -5,16 +5,30 @@ * `bun run build && bun dist/opencode-keys/crypto.service.spec.js` * Also executes under `bun test dist` (top-level run, throws on failure). * - * Covers: AES-256-GCM roundtrip, random IV per call, wrong-key failure, - * tampered-envelope failure, malformed input failure, and fail-fast when - * OPENCODE_KEYS_ENCRYPTION_KEY is missing (never logs the secret). + * Covers: AES-256-GCM roundtrip (keyId envelope), random IV per call, + * legacy envelopes without keyId (dual-read), KEK rotation (previous KEK + * decrypts, new encrypts), unknown-keyId/wrong-key failure, tampered and + * malformed envelopes, fail-fast when OPENCODE_KEYS_ENCRYPTION_KEY is + * missing (never logs the secret). */ import assert from "node:assert/strict"; -const TEST_KEY = "spec-encryption-key-not-real-0123456789abcdef"; +const KEY_A = "spec-encryption-key-A-not-real-0123456789abcdef"; +const KEY_B = "spec-encryption-key-B-not-real-0123456789abcdef"; + +function setKeyring(active: string, previous?: string): void { + process.env.OPENCODE_KEYS_ENCRYPTION_KEY = active; + process.env.OPENCODE_KEYS_ACTIVE_KEY_ID = "v1"; + if (previous === undefined) { + delete process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS; + } else { + process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS = previous; + } + process.env.OPENCODE_KEYS_PREVIOUS_KEY_ID = "v0"; +} async function main(): Promise { - process.env.OPENCODE_KEYS_ENCRYPTION_KEY = TEST_KEY; + setKeyring(KEY_A); const { CryptoService } = await import("./crypto.service.js"); const codeOf = (fn: () => unknown): string => { @@ -41,15 +55,32 @@ async function main(): Promise { } }; - check("roundtrip returns the original plaintext", () => { + check("roundtrip returns the original plaintext (keyId envelope)", () => { + setKeyring(KEY_A); const svc = new CryptoService(); const enc = svc.encrypt("opencode-test-key-not-real-1234567890"); + assert.equal(enc.keyId, "v1"); assert.ok(enc.iv.length > 0); assert.ok(enc.data.length > 0); assert.equal(svc.decrypt(enc), "opencode-test-key-not-real-1234567890"); }); + check("active key id comes from env", () => { + setKeyring(KEY_A); + process.env.OPENCODE_KEYS_ACTIVE_KEY_ID = "2026-10"; + try { + const svc = new CryptoService(); + assert.equal(svc.activeKeyId(), "2026-10"); + assert.equal(svc.encrypt("x").keyId, "2026-10"); + assert.ok(svc.isActiveKeyId("2026-10")); + assert.ok(!svc.isActiveKeyId("v1")); + } finally { + process.env.OPENCODE_KEYS_ACTIVE_KEY_ID = "v1"; + } + }); + check("same plaintext encrypts differently every time (random IV)", () => { + setKeyring(KEY_A); const svc = new CryptoService(); const a = svc.encrypt("same-plaintext"); const b = svc.encrypt("same-plaintext"); @@ -59,7 +90,54 @@ async function main(): Promise { assert.equal(svc.decrypt(b), "same-plaintext"); }); + check("legacy envelope without keyId decrypts (dual-read fallback)", () => { + setKeyring(KEY_A); + const svc = new CryptoService(); + const enc = svc.encrypt("secret-value"); + const legacy = { iv: enc.iv, data: enc.data }; + assert.equal(svc.decrypt(legacy), "secret-value"); + assert.equal( + svc.decrypt({ keyId: "", iv: enc.iv, data: enc.data }), + "secret-value", + ); + assert.equal( + svc.decrypt({ keyId: null, iv: enc.iv, data: enc.data }), + "secret-value", + ); + }); + + check("rotation: previous KEK decrypts, active KEK encrypts", () => { + setKeyring(KEY_A); + const svc = new CryptoService(); + const oldEnc = svc.encrypt("secret-value"); + assert.equal(oldEnc.keyId, "v1"); + // Rotate: B becomes active, A stays as previous. + process.env.OPENCODE_KEYS_ENCRYPTION_KEY = KEY_B; + process.env.OPENCODE_KEYS_ACTIVE_KEY_ID = "v2"; + process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS = KEY_A; + process.env.OPENCODE_KEYS_PREVIOUS_KEY_ID = "v1"; + try { + const rotated = new CryptoService(); + // Old row (keyId v1) still opens via the previous KEK (dual-read). + assert.equal(rotated.decrypt(oldEnc), "secret-value"); + // Legacy-shaped old row (no keyId) also still opens. + assert.equal( + rotated.decrypt({ iv: oldEnc.iv, data: oldEnc.data }), + "secret-value", + ); + // New writes use the active KEK id. + const fresh = rotated.encrypt("secret-value"); + assert.equal(fresh.keyId, "v2"); + assert.equal(rotated.decrypt(fresh), "secret-value"); + assert.ok(rotated.isActiveKeyId("v2")); + assert.ok(!rotated.isActiveKeyId("v1")); + } finally { + setKeyring(KEY_A); + } + }); + check("wrong encryption key fails closed (auth-tag mismatch)", () => { + setKeyring(KEY_A); const svc = new CryptoService(); const enc = svc.encrypt("secret-value"); process.env.OPENCODE_KEYS_ENCRYPTION_KEY = @@ -67,12 +145,29 @@ async function main(): Promise { try { const other = new CryptoService(); assert.equal(codeOf(() => other.decrypt(enc)), "opencode_key_unreadable"); + // Legacy shape without keyId fails closed too. + assert.equal( + codeOf(() => other.decrypt({ iv: enc.iv, data: enc.data })), + "opencode_key_unreadable", + ); } finally { - process.env.OPENCODE_KEYS_ENCRYPTION_KEY = TEST_KEY; + setKeyring(KEY_A); } }); + check("unknown keyId with no previous KEK fails closed", () => { + setKeyring(KEY_A); + const svc = new CryptoService(); + assert.equal( + codeOf(() => + svc.decrypt({ keyId: "v9", iv: svc.encrypt("x").iv, data: "eA==" }), + ), + "opencode_key_unreadable", + ); + }); + check("tampered envelope fails closed", () => { + setKeyring(KEY_A); const svc = new CryptoService(); const enc = svc.encrypt("secret-value"); const raw = Buffer.from(enc.data, "base64"); @@ -84,6 +179,7 @@ async function main(): Promise { }); check("malformed envelope fails closed", () => { + setKeyring(KEY_A); const svc = new CryptoService(); assert.equal(codeOf(() => svc.decrypt({ iv: "!!!", data: "!!! " })), "opencode_key_unreadable"); assert.equal( @@ -108,8 +204,19 @@ async function main(): Promise { code = body?.code ?? ""; } assert.equal(code, "opencode_keys_unconfigured"); + assert.equal(codeOf(() => svc.activeKeyId()), "opencode_keys_unconfigured"); + } finally { + setKeyring(KEY_A); + } + }); + + check("set-but-short previous key fails closed (never echoes the value)", () => { + setKeyring(KEY_A, "too-short"); + try { + const svc = new CryptoService(); + assert.equal(codeOf(() => svc.encrypt("x")), "opencode_keys_unconfigured"); } finally { - process.env.OPENCODE_KEYS_ENCRYPTION_KEY = TEST_KEY; + setKeyring(KEY_A); } }); diff --git a/apps/backend/src/opencode-keys/crypto.service.ts b/apps/backend/src/opencode-keys/crypto.service.ts index 9bfb1d3..f818fc9 100644 --- a/apps/backend/src/opencode-keys/crypto.service.ts +++ b/apps/backend/src/opencode-keys/crypto.service.ts @@ -1,89 +1,220 @@ import { Injectable, InternalServerErrorException } from "@nestjs/common"; import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto"; import { AppLogger } from "../common/app-logger.service.js"; -import { MIN_OPENCODE_KEYS_ENCRYPTION_KEY_LENGTH } from "../env.js"; +import { + DEFAULT_OPENCODE_KEYS_ACTIVE_KEY_ID, + DEFAULT_OPENCODE_KEYS_PREVIOUS_KEY_ID, + MIN_OPENCODE_KEYS_ENCRYPTION_KEY_LENGTH, + OPENCODE_KEYS_KEY_ID_PATTERN, +} from "../env.js"; /** AES-256-GCM params: 12-byte IV, 16-byte auth tag (both base64 at rest). */ const IV_BYTES = 12; const TAG_BYTES = 16; -/** Encrypted per-user OpenCode API key (at-rest shape, never logged). */ +/** + * Encrypted per-user OpenCode API key (at-rest shape, never logged). + * + * - `keyId` selects the KEK version that wrapped the row (the `OPENCODE_KEYS_*` + * keyring, see below). Legacy rows written before key versioning carry no + * id (`undefined`/empty) and decrypt via the dual-read fallback. + * - `iv` is base64(12-byte random IV), `data` is base64(ciphertext || tag). + */ export interface EncryptedOpencodeKey { + /** KEK version id (e.g. "v1"); never a secret, stored in plaintext. */ + keyId: string; + /** base64(12-byte random IV) */ + iv: string; + /** base64(ciphertext || 16-byte auth tag) */ + data: string; +} + +/** Decrypt input — `keyId` is optional so pre-versioning rows stay readable. */ +export interface EncryptedOpencodeKeyInput { + /** KEK version id, or missing/empty for legacy rows. */ + keyId?: string | null; /** base64(12-byte random IV) */ iv: string; /** base64(ciphertext || 16-byte auth tag) */ data: string; } +interface KeyEntry { + id: string; + key: Buffer; +} + +interface Keyring { + active: KeyEntry; + previous?: KeyEntry; +} + +function unconfigured(): InternalServerErrorException { + return new InternalServerErrorException({ + code: "opencode_keys_unconfigured", + message: "OpenCode key storage is not configured", + }); +} + /** - * Resolves the 32-byte AES key from OPENCODE_KEYS_ENCRYPTION_KEY. - * Fail-fast at USE time (never at boot — an unconfigured secret must not - * break unrelated suites): missing/short secret → 500 - * `opencode_keys_unconfigured`. Reads process.env directly (not validateEnv) - * so encryption never breaks on unrelated env validation failures; the - * short-secret ERROR at boot stays covered by validateEnv itself. The raw - * secret is never logged and never leaves this module except as key material. + * Reads the active KEK id (`OPENCODE_KEYS_ACTIVE_KEY_ID`, default "v1"). + * Explicit-but-malformed ids fail closed (same 500, fixed message). */ -function resolveAesKey(): Buffer { - const raw = (process.env.OPENCODE_KEYS_ENCRYPTION_KEY ?? "").trim(); - if (!raw || raw.length < MIN_OPENCODE_KEYS_ENCRYPTION_KEY_LENGTH) { - throw new InternalServerErrorException({ - code: "opencode_keys_unconfigured", - message: "OpenCode key storage is not configured", - }); +function resolveKeyId(raw: string | undefined, fallback: string): string { + const id = (raw ?? "").trim() || fallback; + if (!OPENCODE_KEYS_KEY_ID_PATTERN.test(id)) throw unconfigured(); + return id; +} + +/** SHA-256 key material from a ≥32-char secret (never echoed, never logged). */ +function materialize(secret: string): Buffer { + if (!secret || secret.length < MIN_OPENCODE_KEYS_ENCRYPTION_KEY_LENGTH) { + throw unconfigured(); } - return createHash("sha256").update(raw, "utf8").digest(); + return createHash("sha256").update(secret, "utf8").digest(); } /** - * CryptoService — AES-256-GCM envelope for per-user OpenCode API keys. + * Resolves the versioned KEK keyring from env at USE time (never at boot — + * an unconfigured secret must not break unrelated suites). + * + * - Active: `OPENCODE_KEYS_ENCRYPTION_KEY` (+ `OPENCODE_KEYS_ACTIVE_KEY_ID`). + * - Previous (rotation window only): `OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS` + * (+ `OPENCODE_KEYS_PREVIOUS_KEY_ID`). Set-but-short fails closed. * - * - Key: SHA-256(OPENCODE_KEYS_ENCRYPTION_KEY) (any ≥32-char secret works; - * no re-encrypt/rotation in this iteration — one key per deploy). - * - encrypt(): fresh random 12-byte IV per call (same plaintext encrypts - * differently every time); returns base64 { iv, data } for the - * user_opencode_keys row (iv / encrypted_key columns). - * - decrypt(): throws 500 `opencode_key_unreadable` on wrong-key/auth-tag - * mismatch or malformed input (fixed message, no secret echo). + * Reads process.env directly (not validateEnv) so encryption never breaks + * on unrelated env validation failures. The raw secrets never leave this + * module except as key material. + */ +function resolveKeyring(): Keyring { + const activeSecret = (process.env.OPENCODE_KEYS_ENCRYPTION_KEY ?? "").trim(); + const active: KeyEntry = { + id: resolveKeyId( + process.env.OPENCODE_KEYS_ACTIVE_KEY_ID, + DEFAULT_OPENCODE_KEYS_ACTIVE_KEY_ID, + ), + key: materialize(activeSecret), + }; + const previousSecret = ( + process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS ?? "" + ).trim(); + if (!previousSecret) return { active }; + const previous: KeyEntry = { + id: resolveKeyId( + process.env.OPENCODE_KEYS_PREVIOUS_KEY_ID, + DEFAULT_OPENCODE_KEYS_PREVIOUS_KEY_ID, + ), + key: materialize(previousSecret), + }; + // Same id on both sides is a no-op (single effective key, no dual-read). + if (previous.id === active.id) return { active }; + return { active, previous }; +} + +function decryptWith( + entry: KeyEntry, + iv: Buffer, + raw: Buffer, +): string { + if (iv.length !== IV_BYTES || raw.length <= TAG_BYTES) { + throw new Error("malformed envelope"); + } + const tag = raw.subarray(raw.length - TAG_BYTES); + const ciphertext = raw.subarray(0, raw.length - TAG_BYTES); + const decipher = createDecipheriv("aes-256-gcm", entry.key, iv); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString( + "utf8", + ); +} + +/** + * CryptoService — AES-256-GCM envelope for per-user OpenCode API keys with + * versioned KEK rotation. + * + * - Keyring: active KEK (`OPENCODE_KEYS_ENCRYPTION_KEY`, id from + * `OPENCODE_KEYS_ACTIVE_KEY_ID`, default "v1") + optional previous KEK + * (rotation window). KEK material is SHA-256(secret); secrets live only in + * env/KMS, never next to the ciphertext, never logged. + * - encrypt(): fresh random 12-byte IV per call under the ACTIVE key; + * returns { keyId, iv, data } for the row (key_id / iv / encrypted_key). + * - decrypt(): dual-read — tries the envelope's keyId first, then the other + * known KEK; legacy envelopes without keyId try active → previous. Throws + * 500 `opencode_key_unreadable` when no KEK opens the envelope (wrong key / + * tamper / malformed — fixed message, no secret echo). + * - Rotation (no downtime): deploy new secret as active + old as previous → + * old rows keep decrypting (dual-read) → lazy re-encrypt on read + the + * `keys:reencrypt` background pass re-wraps stale rows → drop previous. * - Nothing secret-bearing is ever logged (fixed event names only). */ @Injectable() export class CryptoService { constructor(private readonly logger: AppLogger = new AppLogger("CryptoService")) {} + /** Active KEK id new rows are wrapped with (fail-closed when unconfigured). */ + activeKeyId(): string { + return resolveKeyring().active.id; + } + + /** True when the row already uses the active KEK (no re-encrypt needed). */ + isActiveKeyId(keyId: string | null | undefined): boolean { + if (!keyId) return false; + try { + return keyId === resolveKeyring().active.id; + } catch { + // Unconfigured storage fails closed downstream — never report "fresh". + return false; + } + } + encrypt(plain: string): EncryptedOpencodeKey { - const key = resolveAesKey(); + const { active } = resolveKeyring(); const iv = randomBytes(IV_BYTES); - const cipher = createCipheriv("aes-256-gcm", key, iv); + const cipher = createCipheriv("aes-256-gcm", active.key, iv); const ciphertext = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]); const tag = cipher.getAuthTag(); return { + keyId: active.id, iv: iv.toString("base64"), data: Buffer.concat([ciphertext, tag]).toString("base64"), }; } - decrypt(input: { iv: string; data: string }): string { - const key = resolveAesKey(); + decrypt(input: EncryptedOpencodeKeyInput): string { + const ring = resolveKeyring(); + let iv: Buffer; + let raw: Buffer; try { - const iv = Buffer.from(input.iv, "base64"); - const raw = Buffer.from(input.data, "base64"); - if (iv.length !== IV_BYTES || raw.length <= TAG_BYTES) { - throw new Error("malformed envelope"); - } - const tag = raw.subarray(raw.length - TAG_BYTES); - const ciphertext = raw.subarray(0, raw.length - TAG_BYTES); - const decipher = createDecipheriv("aes-256-gcm", key, iv); - decipher.setAuthTag(tag); - return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8"); - } catch (err) { - if (err instanceof InternalServerErrorException) throw err; - // Fixed event only — never the envelope, the key, or the plaintext. + iv = Buffer.from(input.iv, "base64"); + raw = Buffer.from(input.data, "base64"); + } catch { this.logger.error("[crypto] decrypt failed code=opencode_key_unreadable"); throw new InternalServerErrorException({ code: "opencode_key_unreadable", message: "Stored OpenCode key cannot be decrypted", }); } + // Candidate order: envelope's KEK first, then the other known KEK + // (dual-read across the rotation window); legacy envelopes without an + // id try active → previous. + const ordered: KeyEntry[] = + input.keyId && input.keyId === ring.previous?.id + ? [ring.previous, ring.active] + : ring.previous + ? [ring.active, ring.previous] + : [ring.active]; + for (const entry of ordered) { + try { + return decryptWith(entry, iv, raw); + } catch { + // try the next KEK — report only when none opens the envelope. + } + } + // Fixed event only — never the envelope, the key, or the plaintext. + this.logger.error("[crypto] decrypt failed code=opencode_key_unreadable"); + throw new InternalServerErrorException({ + code: "opencode_key_unreadable", + message: "Stored OpenCode key cannot be decrypted", + }); } } diff --git a/apps/backend/src/opencode-keys/opencode-billing.service.ts b/apps/backend/src/opencode-keys/opencode-billing.service.ts index 9e87afa..27f3575 100644 --- a/apps/backend/src/opencode-keys/opencode-billing.service.ts +++ b/apps/backend/src/opencode-keys/opencode-billing.service.ts @@ -6,38 +6,150 @@ import { fromStatus, fromUnknown, } from "../common/external/external-error.js"; -import { DEFAULT_OPENCODE_BILLING_URL, validateEnv } from "../env.js"; import { CryptoService } from "./crypto.service.js"; import { OpencodeKeysService } from "./opencode-keys.service.js"; -/** GET /api/v1/usage response (minimal contract: balance+usage). */ +/** GET /api/v1/usage response (Zen Go contract + legacy backward-compat). */ +export interface OpencodeLimitBucket { + used: number; + limit: number; +} + export interface OpencodeUsage { - balance: number; - usage: number; + /** Legacy pay-as-you-go fields — present only for legacy upstream payloads. */ + balance?: number; + /** Legacy pay-as-you-go total — present only for legacy upstream payloads. */ + usage?: number; /** ISO-8601 time of the upstream response (no cache/TTL). */ updatedAt: string; + /** + * Zen Go windows mapped to used/limit for backward-compat UI: + * upstream reports `percent` only, so we expose `{ used: percent, limit: 100 }`. + * `rolling` is the Zen 5-hour window (20% of the monthly limit); + * `weekly` is 50%, `monthly` is 100% (see /v2/docs/console/go). + * Legacy `daily` is kept for old payloads (no Zen daily exists). + * All buckets pass through ONLY when upstream carries finite numbers — + * never derived from a total (derivation is forbidden). + */ + rolling?: OpencodeLimitBucket; + daily?: OpencodeLimitBucket; + weekly?: OpencodeLimitBucket; + monthly?: OpencodeLimitBucket; } function isFiniteNumber(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value); } +function parseBucket(value: unknown): OpencodeLimitBucket | undefined { + if (typeof value !== "object" || value === null) return undefined; + const rec = value as Record; + const used = rec["used"]; + const limit = rec["limit"]; + if (!isFiniteNumber(used) || !isFiniteNumber(limit)) return undefined; + return { used, limit }; +} + +/** + * Zen Go usage window → legacy bucket. + * Upstream shape (GET /zen/go/v1/usage → /go/v1/usage on inference): + * `{ status: "ok" | "rate-limited", percent: number, resetsAt: ISO }`. + * The UI renders used/limit pairs only, so percent is exposed as + * `{ used: percent, limit: 100 }` (percent is real upstream data, limit 100 + * is the percent scale — not derived from any total). Missing/malformed + * windows return undefined (omitted, never faked). + */ +function parseZenWindow(value: unknown): OpencodeLimitBucket | undefined { + if (typeof value !== "object" || value === null) return undefined; + const rec = value as Record; + const status = rec["status"]; + const percent = rec["percent"]; + const resetsAt = rec["resetsAt"]; + if (status !== "ok" && status !== "rate-limited") return undefined; + if (!isFiniteNumber(percent)) return undefined; + if (typeof resetsAt !== "string" || resetsAt.length === 0) return undefined; + return { used: percent, limit: 100 }; +} + +/** + * Extract Zen Go windows from either the documented nested shape + * `{ usage: { rolling, weekly, monthly } }` or a flat + * `{ rolling, weekly, monthly }` (defensive — proxy unwraps happen). + */ +function extractZenWindows(rec: Record): { + rolling?: OpencodeLimitBucket; + weekly?: OpencodeLimitBucket; + monthly?: OpencodeLimitBucket; +} | null { + const nested = + typeof rec["usage"] === "object" && rec["usage"] !== null + ? (rec["usage"] as Record) + : null; + const src = nested ?? rec; + const rolling = parseZenWindow(src["rolling"]); + const weekly = parseZenWindow(src["weekly"]); + const monthly = parseZenWindow(src["monthly"]); + if (!rolling && !weekly && !monthly) return null; + const out: { + rolling?: OpencodeLimitBucket; + weekly?: OpencodeLimitBucket; + monthly?: OpencodeLimitBucket; + } = {}; + if (rolling) out.rolling = rolling; + if (weekly) out.weekly = weekly; + if (monthly) out.monthly = monthly; + return out; +} + +/** + * Upstream usage endpoint (GET, per-user Bearer) — hard-coded module + * constant. There is no env override (OPENCODE_BILLING_URL was removed from + * env.ts/.env.example as a breaking change): the endpoint is fixed. + * + * Spec (2026-10-19, via context7 + webfetch + live probe): + * - Official OpenAPI v2 (https://opencode.ai/v2/docs/api, + * /v2/openapi.json) describes the LOCAL instance HttpApi only + * (server/session/agent/…) — it has NO billing/usage surface. + * - The real billing/usage surface is Zen Go: + * `GET https://opencode.ai/zen/go/v1/usage` (SolidStart file route, + * proxies to inference `GET /go/v1/usage`). Live probe: no auth → 401 + * `{ type: "error", error: { type: "AuthError" } }` (real endpoint); + * `https://api.opencode.ai/usage` (old constant) → 200 `Not Found` + * catch-all (shape-mismatch → 503). 401 vs catch-all 200 proves the fix. + * - Success shape is `{ usage: { rolling, weekly, monthly } }`, each window + * `{ status: "ok" | "rate-limited", percent: number, resetsAt: ISO }` + * (Go limits: 5h = 20% monthly, weekly = 50%, monthly = 100%). + */ +export const OPENCODE_BILLING_URL = "https://opencode.ai/zen/go/v1/usage"; + /** * OpencodeBillingService — live upstream usage for the caller's own key. * * - Loads the caller's row and decrypts it (missing → 404 * `opencode_key_missing` so clients can prompt key setup; undecryptable → - * 500 from CryptoService). - * - Raw GET fetch (no SDK — the SDK has no billing surface) to - * OPENCODE_BILLING_URL with per-user `Authorization: Bearer`, via + * 500 from CryptoService). Rows wrapped with a stale KEK are lazily + * re-wrapped under the active KEK (best-effort, never fails the request). + * - Raw GET fetch (no SDK — the SDK has no billing surface) to the + * module OPENCODE_BILLING_URL constant with per-user `Authorization: + * Bearer`, via * ExternalClient (REQUEST_TIMEOUT_MS budget + EXTERNAL_RETRY_* tuning, * service='opencode-billing'). updatedAt = upstream response time. - * - Maps the response strictly to { balance, usage } (finite numbers at the - * top level; anything else → 503, never a mock). + * - Maps the response strictly (anything else → 503, never a mock): + * legacy `{ balance, usage }` finite numbers (backward-compat, kept for + * old mocks), or Zen Go `{ usage: { rolling, weekly, monthly } }` each + * `{ status, percent, resetsAt }` mapped to `{ used: percent, limit: 100 }`. + * - Additive breakdown: optional `rolling/daily/weekly/monthly` { used, limit } + * pairs pass through ONLY when upstream carries finite numbers for both fields. + * Missing/malformed buckets are omitted (undefined) — never derived from + * a total (derivation is forbidden: no percentages from totals; limit 100 + * here is the percent scale for real upstream percent, not a total). * - Errors: upstream 401/403 → 401 `opencode_key_invalid`; 429 → 429 * EXTERNAL_RATE_LIMITED; 5xx → EXTERNAL_UPSTREAM_5XX; timeout/network → * ExternalClient's typed error (504/503). Nothing secret-bearing is ever * logged or echoed (fixed messages, headers never logged). + * Normal-path warns are one-liners with operation/status/code + * (`[opencode-billing] getUsage … status=… code=…`), without stack and + * without URL/body/Bearer; stack/cause (if any) goes to debug only. */ @Injectable() export class OpencodeBillingService { @@ -49,19 +161,8 @@ export class OpencodeBillingService { ) {} private billingUrl(): string { - const raw = (process.env.OPENCODE_BILLING_URL ?? "").trim(); - // Unset → documented read-only default (never logged); set-but-invalid - // must fail fast instead of silently masking a config error. - if (!raw) return DEFAULT_OPENCODE_BILLING_URL; - try { - return validateEnv(process.env).opencodeBillingUrl; - } catch (err) { - this.logger.warn( - "[opencode-billing] invalid OPENCODE_BILLING_URL, refusing silent fallback", - ); - throw err; + return OPENCODE_BILLING_URL; } -} async getUsage(userId: string, correlationId?: string): Promise { const stored = await this.keys.findByUserId(userId, correlationId); @@ -71,7 +172,32 @@ export class OpencodeBillingService { message: "No OpenCode API key configured for this user", }); } - const apiKey = this.crypto.decrypt({ iv: stored.iv, data: stored.encryptedKey }); + // Decrypt in memory only for this request (dual-read across the KEK + // rotation window via the row's keyId; legacy rows without an id fall + // back to active → previous). The plaintext never leaves this method + // except as the upstream Bearer, and is never logged. + const apiKey = this.crypto.decrypt({ + keyId: stored.keyId, + iv: stored.iv, + data: stored.encryptedKey, + }); + // Lazy re-encrypt: rows wrapped with a stale KEK are re-wrapped under + // the active KEK on read (best-effort — a re-wrap failure only logs and + // never fails the usage request; the background `keys:reencrypt` pass + // converges the rest). + if (!this.crypto.isActiveKeyId(stored.keyId)) { + try { + const fresh = this.crypto.encrypt(apiKey); + await this.keys.save( + userId, + { encryptedKey: fresh.data, iv: fresh.iv, keyId: fresh.keyId }, + correlationId, + ); + this.logger.info("[opencode-billing] key re-encrypted", correlationId); + } catch { + this.logger.warn("[opencode-billing] lazy re-encrypt skipped", correlationId); + } + } let res: Response; try { @@ -92,7 +218,11 @@ export class OpencodeBillingService { if (res.status === 401 || res.status === 403) { await res.arrayBuffer().catch(() => null); // Fixed event only — never the key, never the upstream body. - this.logger.warn("[opencode-billing] upstream rejected the key", correlationId); + // One-liner with operation/status/code, no stack, no secrets. + this.logger.warn( + `[opencode-billing] getUsage rejected status=${res.status} code=opencode_key_invalid`, + correlationId, + ); throw new UnauthorizedException({ code: "opencode_key_invalid", message: "OpenCode API key was rejected", @@ -100,11 +230,21 @@ export class OpencodeBillingService { } if (res.status === 429 || (res.status >= 500 && res.status <= 599)) { await res.arrayBuffer().catch(() => null); - throw fromStatus("opencode-billing", "getUsage", res.status); + const mapped = fromStatus("opencode-billing", "getUsage", res.status); + this.logger.warn( + `[opencode-billing] getUsage upstream status=${res.status} code=${mapped.code}`, + correlationId, + ); + throw mapped; } if (!res.ok) { await res.arrayBuffer().catch(() => null); - throw fromStatus("opencode-billing", "getUsage", res.status); + const mapped = fromStatus("opencode-billing", "getUsage", res.status); + this.logger.warn( + `[opencode-billing] getUsage upstream status=${res.status} code=${mapped.code}`, + correlationId, + ); + throw mapped; } let payload: unknown; @@ -112,6 +252,10 @@ export class OpencodeBillingService { payload = await res.json(); } catch { await res.arrayBuffer().catch(() => null); + this.logger.warn( + `[opencode-billing] getUsage bad json status=${res.status} code=EXTERNAL_UNAVAILABLE`, + correlationId, + ); throw new ExternalServiceError({ code: "EXTERNAL_UNAVAILABLE", service: "opencode-billing", @@ -121,10 +265,11 @@ export class OpencodeBillingService { }); } const rec = payload as Record | null; - const balance = typeof rec === "object" && rec !== null ? rec["balance"] : undefined; - const usage = typeof rec === "object" && rec !== null ? rec["usage"] : undefined; - if (!isFiniteNumber(balance) || !isFiniteNumber(usage)) { - this.logger.warn("[opencode-billing] upstream shape mismatch", correlationId); + if (typeof rec !== "object" || rec === null) { + this.logger.warn( + `[opencode-billing] getUsage shape mismatch status=${res.status} code=EXTERNAL_UNAVAILABLE`, + correlationId, + ); throw new ExternalServiceError({ code: "EXTERNAL_UNAVAILABLE", service: "opencode-billing", @@ -133,6 +278,71 @@ export class OpencodeBillingService { isRetryable: true, }); } - return { balance, usage, updatedAt: observedAt }; + // Legacy pay-as-you-go shape (backward-compat for old mocks): finite + // top-level { balance, usage } numbers. + const balance = rec["balance"]; + const usage = rec["usage"]; + if (isFiniteNumber(balance) && isFiniteNumber(usage)) { + // Additive passthrough: finite { used, limit } pairs only, else omitted. + const out: OpencodeUsage = { balance, usage, updatedAt: observedAt }; + const daily = parseBucket(rec["daily"]); + const weekly = parseBucket(rec["weekly"]); + const monthly = parseBucket(rec["monthly"]); + if (daily) out.daily = daily; + if (weekly) out.weekly = weekly; + if (monthly) out.monthly = monthly; + // Legacy payloads never carry Zen windows — but tolerate them when present. + const zenExtra = extractZenWindows(rec); + if (zenExtra?.rolling && !out.rolling) out.rolling = zenExtra.rolling; + return out; + } + // Zen Go shape: { usage: { rolling, weekly, monthly } } with + // { status, percent, resetsAt } windows (percent → used/limit 100). + // Anything else → 503, never a mock. + if (typeof usage === "object" && usage !== null) { + const zen = extractZenWindows(rec); + if (zen) { + const out: OpencodeUsage = { updatedAt: observedAt }; + if (zen.rolling) out.rolling = zen.rolling; + // Legacy breakdown passthrough still honored when present. + const daily = parseBucket(rec["daily"]); + if (daily) out.daily = daily; + const legacyWeekly = parseBucket(rec["weekly"]); + const legacyMonthly = parseBucket(rec["monthly"]); + // Zen windows win for weekly/monthly (real upstream percent); + // legacy used/limit pairs are fallback when Zen windows are absent. + out.weekly = zen.weekly ?? legacyWeekly; + out.monthly = zen.monthly ?? legacyMonthly; + if (!out.rolling && !out.weekly && !out.monthly) { + this.logger.warn( + `[opencode-billing] getUsage shape mismatch status=${res.status} code=EXTERNAL_UNAVAILABLE`, + correlationId, + ); + throw new ExternalServiceError({ + code: "EXTERNAL_UNAVAILABLE", + service: "opencode-billing", + operation: "getUsage", + message: "сервис временно недоступен, повторите позже", + isRetryable: true, + }); + } + // Omit undefined keys so the envelope stays tight (no balance/usage + // for Zen — the UI renders buckets only, never fake 0% bars). + if (!out.weekly) delete out.weekly; + if (!out.monthly) delete out.monthly; + return out; + } + } + this.logger.warn( + `[opencode-billing] getUsage shape mismatch status=${res.status} code=EXTERNAL_UNAVAILABLE`, + correlationId, + ); + throw new ExternalServiceError({ + code: "EXTERNAL_UNAVAILABLE", + service: "opencode-billing", + operation: "getUsage", + message: "сервис временно недоступен, повторите позже", + isRetryable: true, + }); } } diff --git a/apps/backend/src/opencode-keys/opencode-keys.controller.ts b/apps/backend/src/opencode-keys/opencode-keys.controller.ts index 675f7de..3c4f017 100644 --- a/apps/backend/src/opencode-keys/opencode-keys.controller.ts +++ b/apps/backend/src/opencode-keys/opencode-keys.controller.ts @@ -45,9 +45,13 @@ function isUserId(value: string): boolean { * (the key is never returned, never logged). * - GET /api/v1/key — { configured, updatedAt? } (existence only). * - DELETE /api/v1/key — idempotent { ok: true }. - * - GET /api/v1/usage — { balance, usage, updatedAt } via the + * - GET /api/v1/usage — live Zen Go usage via the * per-user key (missing → 404 opencode_key_missing; rejected → 401 - * opencode_key_invalid; upstream outage → 429/5xx typed errors). + * opencode_key_invalid; upstream 429 → 429 EXTERNAL_RATE_LIMITED; + * upstream 5xx → EXTERNAL_UPSTREAM_5XX (status passthrough: 502/500…); + * timeout → 504 EXTERNAL_TIMEOUT; network/non-JSON/shape-mismatch → + * 503 EXTERNAL_UNAVAILABLE with Retry-After 30, fixed message + * «сервис временно недоступен, повторите позже», never a mock 200). */ @ApiTags("opencode-keys") @ApiBearerAuth() @@ -84,11 +88,12 @@ export class OpencodeKeysController { ): Promise { const userId = this.ownUserId(identity); const correlationId = req?.correlationId; - // Encrypt first (fail-fast 500 when unconfigured), persist ciphertext only. + // Encrypt first (fail-fast 500 when unconfigured), persist ciphertext only + // (envelope carries the active KEK id for rotation dual-read). const enc = this.crypto.encrypt((body as OpencodeKeyBodyDto).apiKey); const stored = await this.keys.save( userId, - { encryptedKey: enc.data, iv: enc.iv }, + { encryptedKey: enc.data, iv: enc.iv, keyId: enc.keyId }, correlationId, ); return { ok: true, updatedAt: stored.updatedAt }; @@ -132,6 +137,10 @@ export class OpencodeKeysController { @ApiResponse({ status: 200, type: OpencodeUsageDto }) @ApiResponse({ status: 401, description: "missing/invalid bearer or rejected key" }) @ApiResponse({ status: 404, description: "no key stored (opencode_key_missing)" }) + @ApiResponse({ status: 429, description: "upstream rate limit (EXTERNAL_RATE_LIMITED, Retry-After)" }) + @ApiResponse({ status: 502, description: "upstream server error passthrough (EXTERNAL_UPSTREAM_5XX, Retry-After)" }) + @ApiResponse({ status: 503, description: "upstream unavailable or shape mismatch (EXTERNAL_UNAVAILABLE, Retry-After)" }) + @ApiResponse({ status: 504, description: "upstream timeout (EXTERNAL_TIMEOUT, Retry-After)" }) async usage( @ReqUser() identity: RequestIdentity, @Req() req?: { correlationId?: string }, diff --git a/apps/backend/src/opencode-keys/opencode-keys.dto.ts b/apps/backend/src/opencode-keys/opencode-keys.dto.ts index bec87d5..82e2c11 100644 --- a/apps/backend/src/opencode-keys/opencode-keys.dto.ts +++ b/apps/backend/src/opencode-keys/opencode-keys.dto.ts @@ -30,15 +30,41 @@ export class OpencodeKeyStatusDto { updatedAt?: string; } -/** GET /api/v1/usage — live upstream balance+usage. */ +/** Single usage bucket — real `used/limit` pair from upstream (no derivation). */ +export class OpencodeLimitBucketDto { + @ApiProperty({ example: 12.5 }) + used!: number; + + @ApiProperty({ example: 100 }) + limit!: number; +} + +/** GET /api/v1/usage — live Zen Go usage (percent windows mapped to used/limit 100). */ export class OpencodeUsageDto { - @ApiProperty({ example: 42.5 }) - balance!: number; + @ApiProperty({ required: false, example: 42.5 }) + balance?: number; - @ApiProperty({ example: 7.25 }) - usage!: number; + @ApiProperty({ required: false, example: 7.25 }) + usage?: number; /** ISO-8601 time of the upstream response (no cache/TTL in this iteration). */ @ApiProperty({ example: "2026-10-13T00:00:00.000Z" }) updatedAt!: string; + + /** + * Zen Go windows mapped to used/limit (percent → { used: percent, limit: 100 }). + * `rolling` is the Zen 5-hour window; legacy `daily` is kept for old payloads. + * Present only when upstream carries finite numbers — never derived. + */ + @ApiProperty({ required: false, type: OpencodeLimitBucketDto }) + rolling?: OpencodeLimitBucketDto; + + @ApiProperty({ required: false, type: OpencodeLimitBucketDto }) + daily?: OpencodeLimitBucketDto; + + @ApiProperty({ required: false, type: OpencodeLimitBucketDto }) + weekly?: OpencodeLimitBucketDto; + + @ApiProperty({ required: false, type: OpencodeLimitBucketDto }) + monthly?: OpencodeLimitBucketDto; } diff --git a/apps/backend/src/opencode-keys/opencode-keys.e2e.ts b/apps/backend/src/opencode-keys/opencode-keys.e2e.ts index ba5dcd9..f1c62c1 100644 --- a/apps/backend/src/opencode-keys/opencode-keys.e2e.ts +++ b/apps/backend/src/opencode-keys/opencode-keys.e2e.ts @@ -33,7 +33,7 @@ process.env.OPENCODE_KEYS_ENCRYPTION_KEY = const TEST_API_KEY = "e2e-opencode-api-key-not-real-0123456789abcdef"; -type BillingMode = "ok" | "reject" | "ratelimit" | "badshape" | "hang"; +type BillingMode = "ok" | "breakdown" | "zen" | "reject" | "ratelimit" | "badshape" | "hang"; async function main(): Promise { // --- Programmable mock billing upstream (per-user Bearer asserted) ------- @@ -60,12 +60,43 @@ async function main(): Promise { res.end(JSON.stringify({ nope: true })); return; } + if (mode === "breakdown") { + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + balance: 42.5, + usage: 7.25, + daily: { used: 12.5, limit: 100 }, + weekly: { used: 60, limit: 100 }, + monthly: { used: 90, limit: 100 }, + }), + ); + return; + } + if (mode === "zen") { + // Real Zen Go shape: { usage: { rolling, weekly, monthly } } with + // { status, percent, resetsAt } (see /v2/docs/console/go limits). + res.writeHead(200, { "content-type": "application/json" }); + res.end( + JSON.stringify({ + usage: { + rolling: { status: "ok", percent: 23.5, resetsAt: "2026-10-19T00:00:00.000Z" }, + weekly: { status: "ok", percent: 60, resetsAt: "2026-10-26T00:00:00.000Z" }, + monthly: { status: "rate-limited", percent: 92, resetsAt: "2026-11-01T00:00:00.000Z" }, + }, + }), + ); + return; + } res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ balance: 42.5, usage: 7.25 })); }); await new Promise((resolve) => billing.listen(0, "127.0.0.1", resolve)); const billingPort = (billing.address() as { port: number }).port; - process.env.OPENCODE_BILLING_URL = `http://127.0.0.1:${billingPort}/usage`; + // Billing endpoint is a hard-coded module constant (no env override): + // requests to it are rerouted to this mock via a fetchWithRetry shim + // installed after the app boots (see below). + let billingTarget = `http://127.0.0.1:${billingPort}/usage`; const { resolveTestDb, applyTestMigrations } = await import("../db/e2e-db.js"); @@ -129,16 +160,43 @@ async function main(): Promise { await app.listen(0); const base = await app.getUrl(); + // Reroute the hard-coded billing constant to the mock above through the + // live ExternalClient (keeps timeout/retry mapping identical to prod). + const { OPENCODE_BILLING_URL, OpencodeBillingService } = await import( + "./opencode-billing.service.js" + ); + const billingSvc = app.get(OpencodeBillingService, { strict: false }) as unknown as { + external: { + fetchWithRetry: ( + url: string, + init: RequestInit, + opts: { service: string; operation: string; correlationId?: string }, + ) => Promise; + }; + }; + const realFetchWithRetry = billingSvc.external.fetchWithRetry.bind( + billingSvc.external, + ); + billingSvc.external.fetchWithRetry = (url, init, opts) => + realFetchWithRetry( + url === OPENCODE_BILLING_URL ? billingTarget : url, + init, + opts, + ); + // --- No-secret-in-logs capture (all AppLogger methods, whole suite) ------ + // Captures { method, args } so the final scans can prove both never-log + // secrets AND normal-path shape: warn/error are one-liners with + // operation/status/code and no stack (`\n at ` only ever appears on debug). const { AppLogger } = await import("../common/app-logger.service.js"); - const captured: unknown[] = []; + const captured: Array<{ method: string; args: unknown[] }> = []; const methods = ["debug", "info", "warn", "error"] as const; const originals = methods.map((m) => AppLogger.prototype[m]); methods.forEach((m, i) => { ( AppLogger.prototype as unknown as Record void> )[m] = function (...args: unknown[]) { - captured.push(args); + captured.push({ method: m, args }); return (originals[i] as (...a: unknown[]) => unknown).apply(this, args); }; }); @@ -278,16 +336,18 @@ async function main(): Promise { }); try { const { rows } = await pool.query( - "SELECT encrypted_key, iv FROM user_opencode_keys", + "SELECT encrypted_key, iv, key_id FROM user_opencode_keys", ); assert.equal(rows.length, 1); - const row = rows[0] as { encrypted_key: string; iv: string }; + const row = rows[0] as { encrypted_key: string; iv: string; key_id: string }; assert.ok(!row.encrypted_key.includes(TEST_API_KEY)); assert.ok(!row.iv.includes(TEST_API_KEY)); + // KEK version envelope: fresh rows are wrapped with the active id. + assert.equal(row.key_id, "v1"); const { CryptoService } = await import("./crypto.service.js"); const svc = new CryptoService(); assert.equal( - svc.decrypt({ iv: row.iv, data: row.encrypted_key }), + svc.decrypt({ keyId: row.key_id, iv: row.iv, data: row.encrypted_key }), TEST_API_KEY, ); } finally { @@ -320,12 +380,137 @@ async function main(): Promise { usage?: number; updatedAt?: string; apiKey?: string; + daily?: unknown; + weekly?: unknown; + monthly?: unknown; }; assert.equal(body.balance, 42.5); assert.equal(body.usage, 7.25); assert.ok(body.updatedAt); assert.equal(body.apiKey, undefined); assert.equal(lastAuth, `Bearer ${TEST_API_KEY}`); + // Additive breakdown is optional: absent upstream → omitted, never derived. + assert.equal(body.daily, undefined); + assert.equal(body.weekly, undefined); + assert.equal(body.monthly, undefined); + }); + + await check("GET /usage breakdown passthrough → daily/weekly/monthly", async () => { + mode = "breakdown"; + const res = await fetch(`${base}/api/v1/usage`, { + headers: auth(), + }); + assert.equal(res.status, 200); + const body = (await readJson(res)) as { + balance?: number; + usage?: number; + daily?: { used?: number; limit?: number }; + weekly?: { used?: number; limit?: number }; + monthly?: { used?: number; limit?: number }; + }; + assert.equal(body.balance, 42.5); + assert.deepEqual(body.daily, { used: 12.5, limit: 100 }); + assert.deepEqual(body.weekly, { used: 60, limit: 100 }); + assert.deepEqual(body.monthly, { used: 90, limit: 100 }); + mode = "ok"; + }); + + await check("billing URL is Zen Go (not the catch-all api.opencode.ai)", async () => { + assert.equal(OPENCODE_BILLING_URL, "https://opencode.ai/zen/go/v1/usage"); + }); + + await check("GET /usage Zen Go → rolling/weekly/monthly as used/limit 100", async () => { + mode = "zen"; + const res = await fetch(`${base}/api/v1/usage`, { + headers: auth(), + }); + assert.equal(res.status, 200); + const body = (await readJson(res)) as { + balance?: number; + usage?: number; + updatedAt?: string; + rolling?: { used?: number; limit?: number }; + weekly?: { used?: number; limit?: number }; + monthly?: { used?: number; limit?: number }; + }; + // Zen payloads carry no balance/usage totals — buckets only, never faked. + assert.equal(body.balance, undefined); + assert.equal(body.usage, undefined); + assert.ok(body.updatedAt); + assert.deepEqual(body.rolling, { used: 23.5, limit: 100 }); + assert.deepEqual(body.weekly, { used: 60, limit: 100 }); + assert.deepEqual(body.monthly, { used: 92, limit: 100 }); + mode = "ok"; + }); + + await check("legacy row without keyId stays readable + lazily re-encrypts", async () => { + mode = "ok"; + const { Pool } = await import("pg"); + const pool = new Pool({ + connectionString: testDb.url, + connectionTimeoutMillis: 5000, + }); + try { + // Simulate a pre-versioning row (no KEK id): dual-read fallback + // must still open it, then converge it to the active KEK id. + await pool.query("UPDATE user_opencode_keys SET key_id = ''"); + const usage = await fetch(`${base}/api/v1/usage`, { headers: auth() }); + assert.equal(usage.status, 200); + const { rows } = await pool.query( + "SELECT encrypted_key, iv, key_id FROM user_opencode_keys", + ); + const row = rows[0] as { encrypted_key: string; iv: string; key_id: string }; + assert.equal(row.key_id, "v1"); + const { CryptoService } = await import("./crypto.service.js"); + const svc = new CryptoService(); + assert.equal( + svc.decrypt({ keyId: row.key_id, iv: row.iv, data: row.encrypted_key }), + TEST_API_KEY, + ); + } finally { + await pool.end().catch(() => undefined); + } + }); + + await check("rotation: previous KEK decrypts, lazy re-encrypt converges", async () => { + mode = "ok"; + lastAuth = null; + const prevKey = process.env.OPENCODE_KEYS_ENCRYPTION_KEY as string; + const NEW_KEY = "e2e-opencode-keys-rotation-key-not-real-0123456789abcd"; + process.env.OPENCODE_KEYS_ENCRYPTION_KEY = NEW_KEY; + process.env.OPENCODE_KEYS_ACTIVE_KEY_ID = "v2"; + process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS = prevKey; + process.env.OPENCODE_KEYS_PREVIOUS_KEY_ID = "v1"; + const { Pool } = await import("pg"); + const pool = new Pool({ + connectionString: testDb.url, + connectionTimeoutMillis: 5000, + }); + try { + // Old row (keyId v1) opens via the previous KEK, then re-wraps to v2. + const usage = await fetch(`${base}/api/v1/usage`, { headers: auth() }); + assert.equal(usage.status, 200); + assert.equal(lastAuth, `Bearer ${TEST_API_KEY}`); + const { rows } = await pool.query( + "SELECT encrypted_key, iv, key_id FROM user_opencode_keys", + ); + const row = rows[0] as { encrypted_key: string; iv: string; key_id: string }; + assert.equal(row.key_id, "v2"); + assert.ok(!row.encrypted_key.includes(TEST_API_KEY)); + } finally { + await pool.end().catch(() => undefined); + // Restore the suite KEK and re-wrap the row under it so the + // remaining error-mapping checks keep decrypting. + process.env.OPENCODE_KEYS_ENCRYPTION_KEY = prevKey; + process.env.OPENCODE_KEYS_ACTIVE_KEY_ID = "v1"; + delete process.env.OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS; + process.env.OPENCODE_KEYS_PREVIOUS_KEY_ID = "v0"; + const put = await fetch(`${base}/api/v1/key`, { + ...json({ apiKey: TEST_API_KEY }, "PUT"), + headers: { "content-type": "application/json", ...auth() }, + }); + assert.equal(put.status, 200); + } }); await check("upstream 401 → 401 opencode_key_invalid (no echo)", async () => { @@ -371,8 +556,8 @@ async function main(): Promise { }); await check("upstream unreachable → 503 (no secret echo)", async () => { - const prev = process.env.OPENCODE_BILLING_URL; - process.env.OPENCODE_BILLING_URL = "http://127.0.0.1:9/usage"; + const prev = billingTarget; + billingTarget = "http://127.0.0.1:9/usage"; try { const res = await fetch(`${base}/api/v1/usage`, { headers: auth(), @@ -388,7 +573,7 @@ async function main(): Promise { ); assert.ok(!JSON.stringify(body).includes(TEST_API_KEY)); } finally { - process.env.OPENCODE_BILLING_URL = prev; + billingTarget = prev; } }); @@ -416,6 +601,36 @@ async function main(): Promise { !dump.includes(process.env.OPENCODE_KEYS_ENCRYPTION_KEY as string), "encryption secret reached the logs", ); + // Never-log Bearer/URL/body: fixed messages only — no auth header + // value and no upstream URL ever reach AppLogger on this path. + assert.ok(!dump.includes("Bearer "), "Bearer value reached the logs"); + assert.ok( + !dump.toLowerCase().includes("opencode.ai/zen/go"), + "upstream URL reached the logs", + ); + }); + + await check("normal-path warn/error are one-liners with context, no stack", async () => { + const normal = captured.filter((e) => e.method === "warn" || e.method === "error"); + assert.ok(normal.length > 0, "expected warn/error lines from the error-mapping checks"); + for (const entry of normal) { + const text = JSON.stringify(entry.args); + // Stacks always contain a newline (JSON-escaped as `\\n`) + an `at` + // frame; normal-path warn/error must stay single-line (stack lives + // on debug only). Fixed phrases like `unreachable at startup` are + // fine — only the escaped newline proves a stack leaked. + assert.ok(!text.includes("\\n"), `stack/newline in ${entry.method}: ${text.slice(0, 300)}`); + } + const warnErrorText = normal.map((e) => JSON.stringify(e.args)).join("\n"); + // Billing context: operation + status + code on rejected/shape/bad-json lines. + assert.ok(warnErrorText.includes("getUsage"), "missing billing operation context"); + assert.ok(warnErrorText.includes("status="), "missing status context"); + assert.ok(warnErrorText.includes("code="), "missing code context"); + // Http filter context: handled line with status/code. + assert.ok(warnErrorText.includes("[http] handled"), "missing filter handled line"); + // Transport context: external retry/failure lines. + const allText = JSON.stringify(captured); + assert.ok(allText.includes("[external]"), "missing external transport lines"); }); } finally { methods.forEach((m, i) => { diff --git a/apps/backend/src/opencode-keys/opencode-keys.service.ts b/apps/backend/src/opencode-keys/opencode-keys.service.ts index 80d882d..8f03329 100644 --- a/apps/backend/src/opencode-keys/opencode-keys.service.ts +++ b/apps/backend/src/opencode-keys/opencode-keys.service.ts @@ -1,14 +1,18 @@ import { Injectable } from "@nestjs/common"; -import { eq } from "drizzle-orm"; +import { eq, ne } from "drizzle-orm"; import { AppLogger } from "../common/app-logger.service.js"; import { DbService, dbUnavailable, type DbClient } from "../db/db.service.js"; import { userOpencodeKeys, type UserOpencodeKeyRow } from "../db/schema.js"; -/** Stored per-user key row (ciphertext only — plaintext never persisted). */ +/** + * Stored per-user key row (ciphertext only — plaintext never persisted). + * `keyId` names the wrapping KEK version ('' = legacy pre-versioning row). + */ export interface StoredOpencodeKey { userId: string; encryptedKey: string; iv: string; + keyId: string; /** ISO-8601 timestamp */ updatedAt: string; } @@ -18,6 +22,7 @@ function toStored(row: UserOpencodeKeyRow): StoredOpencodeKey { userId: row.userId, encryptedKey: row.encryptedKey, iv: row.iv, + keyId: row.keyId ?? "", updatedAt: row.updatedAt.toISOString(), }; } @@ -26,10 +31,10 @@ function toStored(row: UserOpencodeKeyRow): StoredOpencodeKey { * OpencodeKeysService — Postgres-backed per-user OpenCode API-key store * (strict, no memory fallback). * - * Every method hits `user_opencode_keys` (drizzle/0005); failures funnel - * through `dbUnavailable` → 503 EXTERNAL_UNAVAILABLE (Retry-After 30 via - * ApiErrorFilter), logged once with the correlationId. Plaintext keys never - * reach this service (callers encrypt via CryptoService first); nothing + * Every method hits `user_opencode_keys` (drizzle/0005 + 0006); failures + * funnel through `dbUnavailable` → 503 EXTERNAL_UNAVAILABLE (Retry-After 30 + * via ApiErrorFilter), logged once with the correlationId. Plaintext keys + * never reach this service (callers encrypt via CryptoService first); nothing * secret-bearing is ever logged (fixed event names only). */ @Injectable() @@ -47,18 +52,24 @@ export class OpencodeKeysService { /** Upserts the caller's encrypted key (insert or rotate on conflict). */ async save( userId: string, - input: { encryptedKey: string; iv: string }, + input: { encryptedKey: string; iv: string; keyId: string }, correlationId?: string, ): Promise { try { const rows = await this.client() .insert(userOpencodeKeys) - .values({ userId, encryptedKey: input.encryptedKey, iv: input.iv }) + .values({ + userId, + encryptedKey: input.encryptedKey, + iv: input.iv, + keyId: input.keyId, + }) .onConflictDoUpdate({ target: userOpencodeKeys.userId, set: { encryptedKey: input.encryptedKey, iv: input.iv, + keyId: input.keyId, updatedAt: new Date(), }, }) @@ -87,6 +98,28 @@ export class OpencodeKeysService { } } + /** + * User ids whose rows are not wrapped with the active KEK (rotation + * backlog for the `keys:reencrypt` background pass; legacy '' rows count + * as stale). Returns ids only — never ciphertext. + */ + async findStaleUserIds( + activeKeyId: string, + limit = 500, + correlationId?: string, + ): Promise { + try { + const rows = await this.client() + .select({ userId: userOpencodeKeys.userId }) + .from(userOpencodeKeys) + .where(ne(userOpencodeKeys.keyId, activeKeyId)) + .limit(limit); + return rows.map((r) => r.userId); + } catch (err) { + dbUnavailable("userOpencodeKeys.findStaleUserIds", err, this.logger, correlationId); + } + } + /** Deletes the caller's row (idempotent — missing row is still ok). */ async deleteByUserId(userId: string, correlationId?: string): Promise { try { diff --git a/apps/backend/src/opencode-keys/reencrypt-keys.ts b/apps/backend/src/opencode-keys/reencrypt-keys.ts new file mode 100644 index 0000000..3778d51 --- /dev/null +++ b/apps/backend/src/opencode-keys/reencrypt-keys.ts @@ -0,0 +1,106 @@ +/** + * KEK rotation background pass — re-wraps stale per-user OpenCode API keys + * under the active KEK. + * + * Runs against COMPILED dist (same constraint as the *.e2e.ts runners): + * `bun run keys:reencrypt` + * + * Rotation procedure (no downtime, no data loss): + * 1. Deploy the new secret as OPENCODE_KEYS_ENCRYPTION_KEY (+ + * OPENCODE_KEYS_ACTIVE_KEY_ID) and keep the old one as + * OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS (+ OPENCODE_KEYS_PREVIOUS_KEY_ID). + * Old rows keep decrypting via dual-read; GET /api/v1/usage lazily + * re-wraps rows on read. + * 2. Run this pass (repeat until `stale` is 0) to converge rows that are + * never read. + * 3. Drop OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS once `stale` stays 0. + * + * Strict Postgres (TEST_DATABASE_URL wins, DATABASE_URL fallback). Output is + * counts only — user ids, ciphertext, and plaintext never reach the logs. + * Unreadable rows (no known KEK opens them) are counted, never retried, and + * fail the run (exit 1) so the rotation is never silently incomplete. + */ +async function main(): Promise { + const { NestFactory } = await import("@nestjs/core"); + const { AppModule } = await import("../app.module.js"); + const { CryptoService } = await import("./crypto.service.js"); + const { OpencodeKeysService } = await import("./opencode-keys.service.js"); + + const app = await NestFactory.createApplicationContext(AppModule, { + logger: false, + }); + try { + const crypto = app.get(CryptoService, { strict: false }) as InstanceType; + const keys = app.get(OpencodeKeysService, { strict: false }) as InstanceType; + + let activeKeyId: string; + try { + activeKeyId = crypto.activeKeyId(); + } catch (err) { + const code = + (err as { getResponse?: () => { code?: string } }).getResponse?.()?.code ?? + "opencode_keys_unconfigured"; + console.error(`keys:reencrypt refused: ${code} (storage unconfigured)`); + process.exitCode = 1; + return; + } + + const PAGE = 500; + let scanned = 0; + let reencrypted = 0; + let unreadable = 0; + // Converge in passes: each pass re-queries the stale set (re-wrapped + // rows drop out). Stops when a pass makes no progress (only unreadable + // rows remain) — unreadable rows are counted, never retried forever. + for (;;) { + const stale = await keys.findStaleUserIds(activeKeyId, PAGE); + if (stale.length === 0) break; + let progressed = false; + for (const userId of stale) { + scanned += 1; + const stored = await keys.findByUserId(userId); + if (!stored || crypto.isActiveKeyId(stored.keyId)) { + progressed = true; + continue; + } + let plain: string; + try { + plain = crypto.decrypt({ + keyId: stored.keyId, + iv: stored.iv, + data: stored.encryptedKey, + }); + } catch { + unreadable += 1; + continue; + } + const fresh = crypto.encrypt(plain); + await keys.save(userId, { + encryptedKey: fresh.data, + iv: fresh.iv, + keyId: fresh.keyId, + }); + reencrypted += 1; + progressed = true; + } + if (!progressed || stale.length < PAGE) break; + } + console.log( + `keys:reencrypt done: ${JSON.stringify({ scanned, reencrypted, unreadable, activeKeyId })}`, + ); + if (unreadable > 0) { + console.error( + `keys:reencrypt: ${unreadable} row(s) unreadable with the configured KEKs — ` + + "restore the wrapping KEK as OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS and rerun", + ); + process.exitCode = 1; + } + } finally { + await app.close(); + } +} + +void main().catch((err: unknown) => { + console.error(`keys:reencrypt failed to run: ${(err as Error).message}`); + process.exitCode = 1; +}); From 2149d57fa0c7e208180ee9c8ac06c1df55ecbc34 Mon Sep 17 00:00:00 2001 From: alwoo Date: Mon, 19 Oct 2026 17:39:58 +0400 Subject: [PATCH 005/315] docs(env): document KEK rotation and zen go usage contract Env example/docs cover ACTIVE/PREVIOUS KEK ids plus keys:reencrypt converge; openapi adds Retry-After headers and OpencodeLimitBucket windows; AGENTS.md pins the no-stack no-secret logging contract. --- .env.example | 31 ++++++++++++++++++------ AGENTS.md | 14 +++++++++++ contracts/openapi.yaml | 55 +++++++++++++++++++++++++++++++++++++++--- docs/env-validation.md | 9 ++++--- 4 files changed, 95 insertions(+), 14 deletions(-) diff --git a/.env.example b/.env.example index b9fdccb..d383421 100644 --- a/.env.example +++ b/.env.example @@ -51,17 +51,32 @@ OPENCODE_URL=${OPENCODE_PROTOCOL}://${OPENCODE_HOST}:${OPENCODE_PORT} # Each user stores their OWN opencode.ai API key; the backend keeps ONLY the # AES-256-GCM ciphertext (user_opencode_keys table) and proxies usage with the # per-user Bearer. Plaintext keys are never logged, never returned. -# OPENCODE_KEYS_ENCRYPTION_KEY: server secret for at-rest encryption (≥32 chars, -# REQUIRED for the key endpoints — unset → they answer 500 opencode_keys_unconfigured; -# short → boot ERROR). One key per deploy, no rotation/re-encrypt in this iteration. +# OPENCODE_KEYS_ENCRYPTION_KEY: ACTIVE server secret for at-rest encryption +# (≥32 chars, REQUIRED for the key endpoints — unset → they answer 500 +# opencode_keys_unconfigured; short → boot ERROR). New rows are wrapped with +# it under OPENCODE_KEYS_ACTIVE_KEY_ID ("v1" default). # Generate: bun -e "console.log(require('node:crypto').randomBytes(48).toString('base64url'))". # Never log it, never commit it — set locally / via secrets only. # OPENCODE_KEYS_ENCRYPTION_KEY= -# OPENCODE_BILLING_URL: upstream usage endpoint (GET, per-user Bearer). -# Default https://api.opencode.ai/usage is UNVERIFIED (no public billing path was -# discoverable) — override when the real endpoint is known. Unreachable/bad-shape -# upstream answers 503 EXTERNAL_UNAVAILABLE (Retry-After 30), timeouts 504. -# OPENCODE_BILLING_URL=https://api.opencode.ai/usage +# KEK rotation (no downtime, no data loss): +# 1. Deploy the new secret as OPENCODE_KEYS_ENCRYPTION_KEY (+ bump +# OPENCODE_KEYS_ACTIVE_KEY_ID, e.g. "v2") and keep the old secret as +# OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS (+ OPENCODE_KEYS_PREVIOUS_KEY_ID +# matching the old rows). Old rows keep decrypting (dual-read by key_id; +# version-less legacy rows fall back to active → previous). +# 2. Converge: GET /api/v1/usage lazily re-wraps stale rows on read; run +# `bun run keys:reencrypt` (backend package script) for rows never read. +# 3. Drop OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS once no stale rows remain. +# (stale = user_opencode_keys.key_id != active id). +# OPENCODE_KEYS_ACTIVE_KEY_ID=v1 +# OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS= +# OPENCODE_KEYS_PREVIOUS_KEY_ID=v0 +# OPENCODE_BILLING_URL removed (breaking): the upstream usage endpoint is a +# hard-coded module constant (apps/backend/src/opencode-keys/opencode-billing.service.ts +# OPENCODE_BILLING_URL = https://opencode.ai/zen/go/v1/usage — Zen Go, per spec +# https://opencode.ai/v2/docs/api has no billing surface) — env override is no +# longer read. Unreachable/bad-shape upstream answers 503 EXTERNAL_UNAVAILABLE +# (Retry-After 30), timeouts 504. # Postgres — always EXTERNAL (no postgres service in docker-compose). # Compose requires DATABASE_URL explicitly (fail-fast when unset). diff --git a/AGENTS.md b/AGENTS.md index 1fdbf19..791d1c0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,3 +34,17 @@ package.json, не Nx-проект, вне bun workspaces). - Особенно строго: валидация конфигов и env-переменных (`env.ts`, `.env.example`, `resolveRoot`-подобные резолверы). Отсутствующая обязательная переменная для записи/мутации → fail-fast с понятной ошибкой (что задать, где), а не fallback-путь и не WARN-тихоня. Фолбэк для чтения/readonly допустим лишь как исключение для тюнинга (таймауты/ретраи/хосты dev-dial) и фиксируется комментарием — но НЕ для путей хранения. - Единый каталог: `REPOS_ROOT` — единственный источник чтения И записи всего storage (repos list, workspaces tree/submodules, project-files tree, clone dest, projects create/remove). Без конфига — отказ: storage-чтения отвечают 503 `EXTERNAL_UNAVAILABLE` (Retry-After 30, с correlationId), создание проектов — 500 до INSERT; boot без корня продолжается, но лог на уровне ERROR честно сообщает о недоступности (health без изменений). Исключения: `GET /projects` и `GET /projects/:id` без корня — как сейчас (`corrupted` + `storage-unconfigured`). Никогда не читать/создавать `/repos`, не отдавать молча `[]`/404 по нему. - Прецедент: тихий fallback `REPOS_ROOT` → `/repos` → `/repos` молча создавал проекты не там (см. strict-резолвер projects) — так больше не делать; цепочка удалена полностью, включая READ-пути. + +## Логирование — без стеков и секретов в normal path + +- Единственный путь логов бэкенда — `AppLogger` (`apps/backend/src/common/app-logger.service.ts`). Никогда `console.*` в runtime-коде. Уровни: `debug` → `info` (`log`-алиас) → `warn` (деградация, отвечаем) → `error` (операция провалена) → `fatal` (процесс не продолжается). Уважает `LOG_LEVEL`, fail-open в `info`. +- Normal path — однострочники без стека: `warn`/`error` никогда не содержат `\n at `, стек туда не передаётся. `AppLogger.error(message, stack?, correlationId?)` стек (второй/третий аргумент с `\n`) санитизирует (маска URL-кредов, scrub live-секретов, срез 2000) и отдаёт только в `debug` (`stack=…`); сам `error` — одна строка. `Error` в сообщении → только `message`. Диагностика не должна ломать error-строку. +- Секреты не логируются никогда: известные secret-ключи → `[redacted]`, `scheme://user:pass@host` → `://***:***@`, значения `DATABASE_URL`/`POSTGRES_PASSWORD`/`DOCKER_*`/`NPM_*`/`JWT_*`/`OPENCODE_KEYS_*` scrub → `[redacted]`. Запрещены URL/query/headers/body/`Bearer`/токены/пароли/connection strings/PII (напр. email) — только фиксированные имена событий `[domain] op key=value` + `correlationId` (`[cid]` префикс). +- `ExternalClient` (`apps/backend/src/common/external/external-client.ts`, `service`/`operation` + `correlationId`): только поля `service/operation/attempt/latencyMs/status/code`, без URL/body. Формат: + - `debug`: `[external] start service= operation= method=` / `[external] success service= operation= attempt= status= latencyMs=`; + - `warn`: `[external] retry service= operation= attempt= status= code= latencyMs=`; + - `error`: `[external] failure service= operation= status= code= attempt= latencyMs=`; + - `debug`: `[external] cause service= operation= code= detail=`. +- Billing (`OpencodeBillingService.getUsage`, `service='opencode-billing'`): `warn`-однострочники `[opencode-billing] getUsage … status= code=` (`rejected/upstream/shape mismatch/bad json`), без стека и без URL/body/`Bearer`; ключ живёт только в памяти запроса (Bearer upstream), `stack`/`cause` — только в `debug`. Примеры см. в JSDoc сервиса. +- Фильтр (`ApiErrorFilter`): normal path — `[http] handled … status= code=` (`service/operation/status/code` для `ExternalServiceError`), `error` только для `429/5xx` (c `Retry-After: 30`), иначе `warn`; неизвестные — `[http] unhandled status=500 code=internal_error` в `error`. `cause`/`stack` (≤2000, санитизирован) — только в `debug`: `[http] cause … detail=…`. Без body/headers. SSE-обрыв закрытого downstream (`req.destroyed/headersSent`) — штатно, тихо в `debug`, без ответа. +- e2e-скан секретов и формы обязателен (эталон — `apps/backend/src/opencode-keys/opencode-keys.e2e.ts`): перехватить все методы `AppLogger` (`debug/info/warn/error`) на весь сьют, в конце assert: дамп не содержит ключ/секрет/`"Bearer "`/upstream-URL; все `warn`/`error` без `\\n` (стек только в `debug`); текст содержит `getUsage` + `status=` + `code=` + `[http] handled` + `[external]`. diff --git a/contracts/openapi.yaml b/contracts/openapi.yaml index e4fa3b6..fd1d4d4 100644 --- a/contracts/openapi.yaml +++ b/contracts/openapi.yaml @@ -821,18 +821,48 @@ paths: $ref: '#/components/schemas/ApiError' '429': description: upstream rate limit (code EXTERNAL_RATE_LIMITED, retry later) + headers: + Retry-After: + description: seconds to wait before retrying + schema: + type: string + example: '30' + content: + application/json: + schema: + $ref: '#/components/schemas/ApiError' + '502': + description: upstream server error passthrough (code EXTERNAL_UPSTREAM_5XX, Retry-After) + headers: + Retry-After: + description: seconds to wait before retrying + schema: + type: string + example: '30' content: application/json: schema: $ref: '#/components/schemas/ApiError' '503': description: upstream unavailable or shape mismatch (code EXTERNAL_UNAVAILABLE, Retry-After) + headers: + Retry-After: + description: seconds to wait before retrying + schema: + type: string + example: '30' content: application/json: schema: $ref: '#/components/schemas/ApiError' '504': - description: upstream timeout (code EXTERNAL_TIMEOUT) + description: upstream timeout (code EXTERNAL_TIMEOUT, Retry-After) + headers: + Retry-After: + description: seconds to wait before retrying + schema: + type: string + example: '30' content: application/json: schema: @@ -2752,8 +2782,8 @@ components: format: date-time OpencodeUsage: type: object - required: [balance, usage, updatedAt] - description: Live upstream balance+usage (updatedAt = upstream response time, no cache). + required: [updatedAt] + description: Live Zen Go usage (https://opencode.ai/zen/go/v1/usage — percent windows mapped to used/limit 100; rolling is the 5h window). Legacy balance/usage are optional (old payloads only). Optional rolling/daily/weekly/monthly pass through only when upstream carries finite numbers — never derived. properties: balance: type: number @@ -2764,6 +2794,25 @@ components: updatedAt: type: string format: date-time + rolling: + $ref: '#/components/schemas/OpencodeLimitBucket' + daily: + $ref: '#/components/schemas/OpencodeLimitBucket' + weekly: + $ref: '#/components/schemas/OpencodeLimitBucket' + monthly: + $ref: '#/components/schemas/OpencodeLimitBucket' + OpencodeLimitBucket: + type: object + required: [used, limit] + description: Real used/limit pair from upstream (no derivation from totals). + properties: + used: + type: number + example: 12.5 + limit: + type: number + example: 100 AuthRegister: type: object required: [firstName, lastName, email, password] diff --git a/docs/env-validation.md b/docs/env-validation.md index 84a7534..93dbad7 100644 --- a/docs/env-validation.md +++ b/docs/env-validation.md @@ -58,7 +58,8 @@ is the only place that validates them (zod@4), and `docs/env-validation.md` | `JWT_ACCESS_TTL` / `JWT_REFRESH_TTL` | Set but not `15m`/`1h`/`7d`/seconds 60–7776000 | | `AUTH_LEGACY_MOCK_FALLBACK` | Set but not `true`/`false` (`1`/`0` ok) | | `OPENCODE_KEYS_ENCRYPTION_KEY` | Set but shorter than 32 chars (value never echoed) | -| `OPENCODE_BILLING_URL` | Set but not a URL with a host (unset → unverified default, never an error) | +| `OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS` | Set but shorter than 32 chars (value never echoed) | +| `OPENCODE_KEYS_ACTIVE_KEY_ID` / `OPENCODE_KEYS_PREVIOUS_KEY_ID` | Set but not `^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$` (ids are plaintext, never secrets) | Broken composites (`http://:` from `${...}` interpolation with an empty HOST) are NOT errors: they recompose from the parts + WARN. @@ -90,7 +91,8 @@ are NOT errors: they recompose from the parts + WARN. | `JWT_ACCESS_TTL` / `JWT_REFRESH_TTL` unset → `15m` / `7d` | Dev defaults (seconds 900 / 604800) | | `AUTH_LEGACY_MOCK_FALLBACK` unset → `true` | Dev default: `x-user-id` mock identity still accepted; set `false` for production | | `OPENCODE_KEYS_ENCRYPTION_KEY` unset → key endpoints 500 | WARN + `opencode_keys_unconfigured` at use-time (never boot fail-fast); set explicitly for production | -| `OPENCODE_BILLING_URL` unset → `https://api.opencode.ai/usage` | Unverified default (no public billing path discoverable) + WARN; override in `.env` when known | +| `OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS` set → rotation window | WARN (converge stale rows via lazy re-encrypt + `keys:reencrypt`, then remove it) | +| `OPENCODE_KEYS_ACTIVE_KEY_ID` / `OPENCODE_KEYS_PREVIOUS_KEY_ID` unset → `v1` / `v0` | Silent defaults (ids are plaintext envelope metadata, never secrets) | | `GITHUB_APP_INSTALLATION_ID` set | **Deprecated** legacy single-install dev fallback — prefer per-user installations via the install flow | | `PROJECTS_ROOT` points to a missing directory | File browser 404s until it exists | | Unknown app-prefixed key (`APP_BACKEND_PORTT`, …) | Likely typo — only `APP_/OPENCODE_/POSTGRES_/DATABASE_URL/CORS_/REQUEST_TIMEOUT_MS/EXTERNAL_/LOG_LEVEL/NEXT_PUBLIC_/GITHUB_/DOCKER_/DOCKER_REGISTRY_/NPM_/NPM_REGISTRY_/JWT_/AUTH_/PROJECTS_ROOT` prefixes are reported; unrelated OS vars (`PATH`, `HOME`, …) stay silent | @@ -100,7 +102,8 @@ are NOT errors: they recompose from the parts + WARN. `DATABASE_URL`, `POSTGRES_PASSWORD`, `DOCKER_REGISTRY_USER/PASSWORD/TOKEN`, `NPM_REGISTRY_TOKEN`, `NPM_TOKEN` (legacy fallback), `NPM_REGISTRY_USER/PASSWORD` (basic pair), `JWT_ACCESS_SECRET`, -`JWT_REFRESH_SECRET`, `OPENCODE_KEYS_ENCRYPTION_KEY`, per-user OpenCode API +`JWT_REFRESH_SECRET`, `OPENCODE_KEYS_ENCRYPTION_KEY`, +`OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS`, per-user OpenCode API keys, password hashes, access/refresh tokens, private keys, tokens: never appear in errors, warnings, or logs — only key NAMES plus the `.env.example` pointer. From f3437eaeaff12d0b191439769f2f2131eb54ad1d Mon Sep 17 00:00:00 2001 From: alwoo Date: Mon, 19 Oct 2026 17:40:04 +0400 Subject: [PATCH 006/315] feat(frontend): show zen go usage buckets on profile Profile page renders rolling/daily/weekly/monthly used/limit windows via useUsage; i18n en/ru cover the new buckets; api client/types follow the updated usage contract. --- .../frontend/app/(dashboard)/profile/page.tsx | 387 +++++++++++++++--- apps/frontend/next-env.d.ts | 4 +- apps/frontend/src/api/client.ts | 24 ++ apps/frontend/src/api/types.ts | 36 +- .../__tests__/profile-dropdown.test.tsx | 159 +------ .../src/components/profile-dropdown.tsx | 67 +-- apps/frontend/src/hooks/useProfile.ts | 19 +- apps/frontend/src/hooks/useUsage.ts | 187 +++++++++ apps/frontend/src/i18n/dictionaries/en.ts | 41 +- apps/frontend/src/i18n/dictionaries/ru.ts | 41 +- apps/frontend/src/i18n/dictionaries/types.ts | 33 +- apps/frontend/src/lib/mocks/profile.ts | 1 - apps/frontend/src/lib/types.ts | 5 +- 13 files changed, 678 insertions(+), 326 deletions(-) create mode 100644 apps/frontend/src/hooks/useUsage.ts diff --git a/apps/frontend/app/(dashboard)/profile/page.tsx b/apps/frontend/app/(dashboard)/profile/page.tsx index de08083..d6982b2 100644 --- a/apps/frontend/app/(dashboard)/profile/page.tsx +++ b/apps/frontend/app/(dashboard)/profile/page.tsx @@ -5,83 +5,220 @@ import { Alert, AlertDescription, AlertTitle, - Badge, Button, - Card, - CardContent, - CardDescription, - CardFooter, - CardHeader, - CardTitle, + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, Field, + FieldDescription, + FieldError, FieldLabel, Input, + Progress, + Separator, + Skeleton, } from '@web2bizz/ui/components'; -import { ErrorState, LoadingState } from '../../../src/components/states'; +import { EmptyState, ErrorState, ProjectDetailSkeleton } from '../../../src/components/states'; import { useProfile } from '../../../src/hooks/useProfile'; +import { useUsage } from '../../../src/hooks/useUsage'; +import { ApiClientError, api } from '../../../src/api/client'; +import { formatApiError } from '../../../src/lib/format-error'; +import { getValidAccessToken, refreshAccessToken } from '../../../src/lib/auth-store'; import { useI18n } from '../../../src/i18n'; +import type { OpencodeLimitBucket } from '../../../src/api/types'; /** - * Route: /profile — Card + form with success/error Alerts. - * TODO REAL-API: no page changes — swap inside useProfile only. + * Real bucket guard — finite used/limit with a positive limit. + * Non-finite or missing buckets are not renderable (no fake 0% bars). + */ +function isUsableBucket(bucket: OpencodeLimitBucket | undefined): bucket is OpencodeLimitBucket { + return ( + !!bucket && + Number.isFinite(bucket.used) && + Number.isFinite(bucket.limit) && + bucket.limit > 0 + ); +} + +/** Percent from a REAL used/limit pair only (never from the usage total). */ +function toPercent(used: number, limit: number): number { + const raw = (used / limit) * 100; + if (!Number.isFinite(raw)) return 0; + return Math.min(100, Math.max(0, Math.round(raw))); +} + +/** + * Indicator tone via kit Progress className only (no hex, no gradients, + * no shadows/transforms in this block; radii stay var(--radius*)). + * Kit Indicator is hardcoded bg-primary — the child selector recolors it + * through the kit className API (direct child + data-slot fallback). + */ +function toneClass(pct: number): string { + if (pct > 85) return '[&>div]:bg-destructive [&_[data-slot=progress-indicator]]:bg-destructive'; + if (pct >= 60) return '[&>div]:bg-amber-500 [&_[data-slot=progress-indicator]]:bg-amber-500'; + return '[&>div]:bg-emerald-500 [&_[data-slot=progress-indicator]]:bg-emerald-500'; +} + +/** + * Route: /profile — flat Content (§7: no nested Cards, h2 + Separator). + * Real API: GET/PATCH /api/v1/auth/me via useProfile. Email is read-only + * (backend PATCH accepts only firstName/lastName) — displayed as text + * plus a disabled input with a hint, never sent. + * Limits: live GET /api/v1/usage via useUsage — percentages ONLY from real + * used/limit pairs (rolling 5h / daily legacy / weekly / monthly, additive + * backend breakdown; Zen Go percent is exposed as { used: percent, limit: 100 }). + * No breakdown → Empty (never 0% fake bars, never derived from the total). */ export default function ProfilePage() { const { t } = useI18n(); const { profile, loading, error, saved, saving, update, reload } = useProfile(); + const { + usage, + loading: usageLoading, + error: usageError, + noKeyMissing, + noKeyInvalid, + upstreamDown, + reload: reloadUsage, + } = useUsage(); const [name, setName] = useState(''); - const [email, setEmail] = useState(''); + const [keyDialogOpen, setKeyDialogOpen] = useState(false); + const [apiKey, setApiKey] = useState(''); + const [savingKey, setSavingKey] = useState(false); + const [saveError, setSaveError] = useState(null); useEffect(() => { if (profile) { setName(profile.name); - setEmail(profile.email); } }, [profile]); + useEffect(() => { + if (!keyDialogOpen) { + setSaveError(null); + setSavingKey(false); + } + }, [keyDialogOpen]); + const submit = async (e: React.FormEvent) => { e.preventDefault(); - await update({ name, email }); + await update({ name }); + }; + + const openKeyDialog = () => { + setApiKey(''); + setSaveError(null); + setKeyDialogOpen(true); + }; + + /** + * Save the OpenCode API key via PUT /api/v1/key, then reload usage + * (which re-resolves both the key status and the limits: 404 no-key / + * 401 rejected key inline, 5xx section ErrorState, 200 live). The raw key + * is never logged. + */ + const saveKey = async (e: React.FormEvent) => { + e.preventDefault(); + const trimmed = apiKey.trim(); + if (!trimmed) { + setSaveError(t.limits.required); + return; + } + if (trimmed.length < 20) { + setSaveError(t.limits.tooShort); + return; + } + setSavingKey(true); + setSaveError(null); + try { + let token = await getValidAccessToken(); + if (!token) { + setSaveError(t.errors.sessionExpired); + return; + } + try { + await api.putKey(token, { apiKey: trimmed }); + } catch (err) { + if (err instanceof ApiClientError && err.status === 401) { + token = await refreshAccessToken(); + if (!token) { + setSaveError(t.errors.sessionExpired); + return; + } + await api.putKey(token, { apiKey: trimmed }); + } else { + throw err; + } + } + setApiKey(''); + setKeyDialogOpen(false); + reloadUsage(); + } catch (err) { + const formatted = formatApiError(err); + setSaveError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); + } finally { + setSavingKey(false); + } }; return (

- {t.profile.titleA} {t.profile.titleB} + {t.profile.titleA} {t.profile.titleB}

{t.profile.subtitle}

- {loading && } + {loading && } {error && !loading && !profile && } {profile && ( - - - {profile.name} - - - {profile.role} - {' '} - +
+
+

+ {t.profile.overviewTitle} +

+

{t.profile.overviewDesc}

+
    +
  • + {t.profile.nameLabel} + {profile.name} +
  • +
  • + {t.profile.emailLabel} + {profile.email} + {t.profile.emailReadOnlyHint} +
  • +
  • {t.profile.sincePrefix} {new Date(profile.createdAt).toLocaleDateString()} - - - -
    - - {error && ( - - {t.errors.updateFailed} - {error} - - )} - {saved && !error && ( - - {t.profile.savedTitle} - {t.profile.savedDesc} - - )} +
  • +
+
+ + + +
+

+ {t.profile.editTitle} +

+

{t.profile.editDesc}

+ {error && ( + + {t.errors.updateFailed} + {error} + + )} + {saved && !error && ( + + {t.profile.savedTitle} + {t.profile.savedDesc} + + )} + {t.profile.nameLabel} setEmail(e.target.value)} - placeholder="dev@devbox.local" + value={profile.email} + disabled + readOnly + aria-describedby="profile-email-hint" /> +

+ {t.profile.emailReadOnlyHint} +

- - - - - - - +
+ + +
+ +
+ + + +
+

+ {t.limits.title} +

+

{t.limits.desc}

+ {usageLoading && ( +
+ + + + + + +
+ )} + {!usageLoading && upstreamDown && ( + + )} + {!usageLoading && !upstreamDown && usageError && ( + + )} + {!usageLoading && !upstreamDown && !usageError && noKeyMissing && ( + + )} + {!usageLoading && !upstreamDown && !usageError && !noKeyMissing && noKeyInvalid && ( + + )} + {!usageLoading && + !upstreamDown && + !usageError && + !noKeyMissing && + !noKeyInvalid && + !usage && ( + + )} + {!usageLoading && !upstreamDown && !usageError && !noKeyMissing && !noKeyInvalid && usage && (() => { + const rows = [ + { key: 'rolling', label: t.limits.rolling, bucket: usage.rolling }, + { key: 'daily', label: t.limits.daily, bucket: usage.daily }, + { key: 'weekly', label: t.limits.weekly, bucket: usage.weekly }, + { key: 'monthly', label: t.limits.monthly, bucket: usage.monthly }, + ].filter((row): row is { key: string; label: string; bucket: OpencodeLimitBucket } => + isUsableBucket(row.bucket), + ); + if (rows.length === 0) { + return ; + } + return ( +
    + {rows.map((row) => { + const pct = toPercent(row.bucket.used, row.bucket.limit); + return ( +
  • +
    + {row.label} + + {row.bucket.used}/{row.bucket.limit} + +
    + +
  • + ); + })} +
+ ); + })()} +
+ + { + if (!savingKey) setKeyDialogOpen(open); + }} + > + + + {t.limits.dialogTitle} + {t.limits.dialogDesc} + + +
+ + {t.limits.keyLabel} + setApiKey(e.target.value)} + /> + {t.limits.keyHint} + {saveError && {saveError}} + +
+ + + + + +
+
+
)}
); diff --git a/apps/frontend/next-env.d.ts b/apps/frontend/next-env.d.ts index ce4e94a..a419cbe 100644 --- a/apps/frontend/next-env.d.ts +++ b/apps/frontend/next-env.d.ts @@ -1,7 +1,7 @@ /// /// -import "./.next/types/routes.d.ts"; -import "./.next/types/root-params.d.ts"; +import "./.next/dev/types/routes.d.ts"; +import "./.next/dev/types/root-params.d.ts"; // NOTE: This file should not be edited // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/apps/frontend/src/api/client.ts b/apps/frontend/src/api/client.ts index 5a8b4ee..bd4df30 100644 --- a/apps/frontend/src/api/client.ts +++ b/apps/frontend/src/api/client.ts @@ -13,6 +13,9 @@ import type { MemberDto, MessagesResponse, NpmRegistryStatusResponse, + OpencodeKeyResult, + OpencodeKeyStatus, + OpencodeUsage, OrganizationDto, ProjectApiDto, RegistryCatalogResponse, @@ -309,4 +312,25 @@ export const api = { requestV1(`/users/${encodeURIComponent(id)}`, { headers: { authorization: `Bearer ${accessToken}` }, }), + // GET /api/v1/usage — live Zen Go usage (+ optional legacy balance/usage, + // additive rolling/daily/weekly/monthly breakdown; Zen percent is exposed + // as { used: percent, limit: 100 }). Missing key → 404 + // opencode_key_missing (hook maps it to the no-key empty state, not 0% bars). + getUsage: (accessToken: string) => + requestV1('/usage', { + headers: { authorization: `Bearer ${accessToken}` }, + }), + // Per-user OpenCode key — PUT /api/v1/key { apiKey } (zod min 20, max + // 1024, encrypted AES-256-GCM at rest, never echoed/logged), + // GET /api/v1/key (existence only { configured, updatedAt? }). + putKey: (accessToken: string, input: { apiKey: string }) => + requestV1('/key', { + method: 'PUT', + headers: { authorization: `Bearer ${accessToken}` }, + body: JSON.stringify(input), + }), + getKeyStatus: (accessToken: string) => + requestV1('/key', { + headers: { authorization: `Bearer ${accessToken}` }, + }), }; diff --git a/apps/frontend/src/api/types.ts b/apps/frontend/src/api/types.ts index 798883f..6da320a 100644 --- a/apps/frontend/src/api/types.ts +++ b/apps/frontend/src/api/types.ts @@ -87,19 +87,6 @@ export interface ApiError { correlationId: string; } -/** Single quota bucket: consumed units vs granted total. */ -export interface LimitQuota { - used: number; - total: number; -} - -/** Optional usage limits attached to the identity (all buckets optional). */ -export interface AuthLimits { - daily?: LimitQuota; - weekly?: LimitQuota; - monthly?: LimitQuota; -} - /** POST /api/v1/auth/register + login response user (never carries passwordHash) */ export interface AuthUser { id: string; @@ -109,8 +96,6 @@ export interface AuthUser { provider: 'local' | 'sso-oauth' | 'github-app'; /** ISO-8601 timestamp */ createdAt: string; - /** Optional usage limits — absent when the backend sends no quota. */ - limits?: AuthLimits; } /** Token pair (short-lived access + rotating refresh). */ @@ -251,8 +236,25 @@ export interface OpencodeKeyStatus { } export interface OpencodeUsage { - balance: number; - usage: number; + /** Legacy pay-as-you-go fields — present only for legacy upstream payloads. */ + balance?: number; + /** Legacy pay-as-you-go total — present only for legacy upstream payloads. */ + usage?: number; /** ISO-8601 time of the upstream response */ updatedAt: string; + /** + * Zen Go windows mapped to used/limit (`percent` → `{ used: percent, limit: 100 }`). + * `rolling` is the Zen 5-hour window; legacy `daily` has no Zen equivalent. + * Present only when upstream carries finite numbers — never derived. + */ + rolling?: OpencodeLimitBucket; + daily?: OpencodeLimitBucket; + weekly?: OpencodeLimitBucket; + monthly?: OpencodeLimitBucket; +} + +/** Single usage bucket — real `used/limit` pair from upstream (no derivation). */ +export interface OpencodeLimitBucket { + used: number; + limit: number; } diff --git a/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx b/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx index eb3cd88..3db920b 100644 --- a/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx +++ b/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx @@ -91,18 +91,6 @@ const ME_USER = { provider: 'local' as const, createdAt: '2026-01-15T09:00:00.000Z', }; -const ME_USER_WITH_LIMITS = { - ...ME_USER, - limits: { - daily: { used: 5, total: 100 }, - weekly: { used: 20, total: 500 }, - monthly: { used: 100, total: 2000 }, - }, -}; -function currentMeUser() { - const override = (globalThis as Record).__TEST_ME_USER__; - return (override as typeof ME_USER_WITH_LIMITS | undefined) ?? ME_USER; -} const cannedSession = { accessToken: 'test-access', refreshToken: 'test-refresh', @@ -129,7 +117,7 @@ mock.module('../../api/client', () => ({ } }, api: { - me: async () => currentMeUser(), + me: async () => ME_USER, updateMe: async () => ME_USER, logout: async () => ({ ok: true }), refresh: async () => ({ ...cannedSession }), @@ -154,7 +142,7 @@ const { setSession, clearSession } = await import('../../lib/auth-store'); }); } if (url.includes('/auth/me')) { - return new Response(JSON.stringify(currentMeUser()), { + return new Response(JSON.stringify(ME_USER), { status: 200, headers: { 'content-type': 'application/json' }, }); @@ -167,14 +155,12 @@ const { setSession, clearSession } = await import('../../lib/auth-store'); beforeEach(() => { setSession({ ...cannedSession }); - delete (globalThis as Record).__TEST_ME_USER__; }); afterEach(() => { cleanup(); clearSession(); pushMock.mockClear(); - delete (globalThis as Record).__TEST_ME_USER__; }); const USER = { name: 'Devbox Developer', email: 'dev@devbox.local' }; @@ -312,144 +298,3 @@ describe('HeaderProfileDropdown (pure kit AuthorizedUserProfile)', () => { } }); }); - -describe('HeaderProfileDropdown limits (daily/weekly/monthly)', () => { - test('renders 3 limits with values and progress (en)', async () => { - (globalThis as Record).__TEST_ME_USER__ = ME_USER_WITH_LIMITS; - const user = userEvent.setup(); - render(); - - const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); - await user.click(trigger); - await screen.findByRole('menu'); - - const group = await screen.findByTestId('profile-limits'); - expect(group.getAttribute('aria-label')).toBe('Usage limits'); - expect(screen.getByTestId('profile-limits-title').textContent).toBe('Usage limits'); - - expect(screen.getByTestId('profile-limit-daily-label').textContent).toBe('Daily'); - expect(screen.getByTestId('profile-limit-daily-value').textContent).toBe('5 / 100'); - expect(screen.getByTestId('profile-limit-weekly-label').textContent).toBe('Weekly'); - expect(screen.getByTestId('profile-limit-weekly-value').textContent).toBe('20 / 500'); - expect(screen.getByTestId('profile-limit-monthly-label').textContent).toBe('Monthly'); - expect(screen.getByTestId('profile-limit-monthly-value').textContent).toBe('100 / 2000'); - - // Simple progress: used/total % as aria-valuenow (5%, 4%, 5%). - expect(screen.getByTestId('profile-limit-daily-progress').getAttribute('aria-valuenow')).toBe('5'); - expect(screen.getByTestId('profile-limit-weekly-progress').getAttribute('aria-valuenow')).toBe('4'); - expect(screen.getByTestId('profile-limit-monthly-progress').getAttribute('aria-valuenow')).toBe('5'); - - // Old cases still hold alongside limits. - expect(screen.getByRole('link', { name: 'Profile' })).toBeDefined(); - expect(screen.getByRole('button', { name: 'Sign out' })).toBeDefined(); - }); - - test('hides limits group when backend sends no quota', async () => { - const user = userEvent.setup(); - render(); - - const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); - await user.click(trigger); - await screen.findByRole('menu'); - - expect(screen.queryByTestId('profile-limits')).toBeNull(); - expect(screen.getByRole('link', { name: 'Profile' })).toBeDefined(); - }); - - test('ru locale renders translated limit labels', async () => { - (globalThis as Record).__TEST_ME_USER__ = ME_USER_WITH_LIMITS; - document.cookie = 'devbox-locale=ru; path=/'; - try { - const user = userEvent.setup(); - render( - - - , - ); - - const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); - await user.click(trigger); - await screen.findByRole('menu'); - - expect(screen.getByTestId('profile-limits-title').textContent).toBe('Лимиты использования'); - expect(screen.getByTestId('profile-limit-daily-label').textContent).toBe('Дневной'); - expect(screen.getByTestId('profile-limit-daily-value').textContent).toBe('5 / 100'); - expect(screen.getByTestId('profile-limit-weekly-label').textContent).toBe('Недельный'); - expect(screen.getByTestId('profile-limit-weekly-value').textContent).toBe('20 / 500'); - expect(screen.getByTestId('profile-limit-monthly-label').textContent).toBe('Месячный'); - expect(screen.getByTestId('profile-limit-monthly-value').textContent).toBe('100 / 2000'); - expect(screen.getByRole('link', { name: 'Профиль' })).toBeDefined(); - expect(screen.getByRole('button', { name: 'Выйти' })).toBeDefined(); - } finally { - document.cookie = 'devbox-locale=; path=/; max-age=0'; - } - }); - - test('partial limits render only the present bucket', async () => { - (globalThis as Record).__TEST_ME_USER__ = { - ...ME_USER, - limits: { daily: { used: 7, total: 10 } }, - }; - const user = userEvent.setup(); - render(); - - const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); - await user.click(trigger); - await screen.findByRole('menu'); - - expect(screen.getByTestId('profile-limits')).toBeDefined(); - expect(screen.getByTestId('profile-limit-daily-value').textContent).toBe('7 / 10'); - expect(screen.getByTestId('profile-limit-daily-progress').getAttribute('aria-valuenow')).toBe('70'); - expect(screen.queryByTestId('profile-limit-weekly')).toBeNull(); - expect(screen.queryByTestId('profile-limit-monthly')).toBeNull(); - }); - - test('total=0 renders 0% without NaN', async () => { - (globalThis as Record).__TEST_ME_USER__ = { - ...ME_USER, - limits: { daily: { used: 0, total: 0 } }, - }; - const user = userEvent.setup(); - render(); - - const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); - await user.click(trigger); - await screen.findByRole('menu'); - - expect(screen.getByTestId('profile-limit-daily-value').textContent).toBe('0 / 0'); - expect(screen.getByTestId('profile-limit-daily-progress').getAttribute('aria-valuenow')).toBe('0'); - }); - - test('over-quota clamps progress to 100', async () => { - (globalThis as Record).__TEST_ME_USER__ = { - ...ME_USER, - limits: { monthly: { used: 2500, total: 2000 } }, - }; - const user = userEvent.setup(); - render(); - - const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); - await user.click(trigger); - await screen.findByRole('menu'); - - expect(screen.getByTestId('profile-limit-monthly-value').textContent).toBe('2500 / 2000'); - expect(screen.getByTestId('profile-limit-monthly-progress').getAttribute('aria-valuenow')).toBe('100'); - expect(screen.queryByTestId('profile-limit-daily')).toBeNull(); - }); - - test('negative used clamps progress to 0', async () => { - (globalThis as Record).__TEST_ME_USER__ = { - ...ME_USER, - limits: { weekly: { used: -5, total: 100 } }, - }; - const user = userEvent.setup(); - render(); - - const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); - await user.click(trigger); - await screen.findByRole('menu'); - - expect(screen.getByTestId('profile-limit-weekly-value').textContent).toBe('-5 / 100'); - expect(screen.getByTestId('profile-limit-weekly-progress').getAttribute('aria-valuenow')).toBe('0'); - }); -}); diff --git a/apps/frontend/src/components/profile-dropdown.tsx b/apps/frontend/src/components/profile-dropdown.tsx index 96a947a..b317f1e 100644 --- a/apps/frontend/src/components/profile-dropdown.tsx +++ b/apps/frontend/src/components/profile-dropdown.tsx @@ -12,19 +12,13 @@ import type { Dictionary } from '../i18n/dictionaries/types'; /** * Header user menu — pure kit (@web2bizz/ui 0.26.0 `widgets` entry). - * Thin data adapter: useHeaderProfile() → kit `user`, userMenu snapshot - * en/ru → kit `labels`, sign-out/login → router.push('/login'), - * profile → profileHref="/profile". Limits (daily/weekly/monthly from - * GET /api/v1/auth/me optional `limits`) render as a sibling below the - * kit menu — AuthorizedUserProfile 0.26.0 has NO children slot (only - * Unauthorized does) and its `usage` prop covers daily/weekly only - * (no monthly), so the custom group preserves monthly — no kit fork. - * Loading — single kit-token skeleton (UserProfileSkeleton is kit-internal, - * not exported). - * a11y — native Radix DropdownMenu inside kit Authorized (Esc/Tab, focus - * ring, aria-haspopup / expanded via Trigger asChild + ...rest/ref-forwarded - * UserTrigger 0.26.0). Limits group uses role="group" + role="progressbar" - * per quota (aria-valuenow = used/total %). + * Thin data adapter (<30 lines): useHeaderProfile() → kit `user`, + * userMenu snapshot en/ru → kit `labels`, sign-out/login → + * router.push('/login'), profile → profileHref="/profile". Loading — + * single kit-token skeleton (UserProfileSkeleton is kit-internal, not + * exported). a11y — native Radix DropdownMenu inside kit Authorized + * (Esc/Tab, focus ring, aria-haspopup / expanded via Trigger asChild + + * ...rest/ref-forwarded UserTrigger 0.26.0). * LOCALE-DECOUPLED by design: NO useI18n subscription (it would re-render * this header on every locale switch) and useHeaderProfile() fetches * /auth/me with NO `t` in effect deps (no refetch on language change). @@ -45,10 +39,6 @@ function readStoredUserMenu(): Dictionary['userMenu'] { return isLocale(raw) && raw === 'ru' ? ru.userMenu : en.userMenu; } -/** Quota keys rendered in the dropdown, in display order. */ -const LIMIT_KEYS = ['daily', 'weekly', 'monthly'] as const; -type LimitKey = (typeof LIMIT_KEYS)[number]; - export function HeaderProfileDropdown() { // Mount snapshot — set once, never re-subscribed: language switches // neither refetch the profile nor re-render this dropdown. @@ -75,42 +65,11 @@ export function HeaderProfileDropdown() { } return ( - <> - - {profile.limits && LIMIT_KEYS.some((key) => profile.limits?.[key]) ? ( -
-

{userMenu.limits.title}

- {LIMIT_KEYS.map((key: LimitKey) => { - const quota = profile.limits?.[key]; - if (!quota) return null; - const used = quota.used; - const total = quota.total; - const percent = - total > 0 ? Math.min(100, Math.max(0, Math.round((used / total) * 100))) : 0; - return ( -
- {userMenu.limits[key]} - {`${used} / ${total}`} -
-
-
-
- ); - })} -
- ) : null} - + ); } diff --git a/apps/frontend/src/hooks/useProfile.ts b/apps/frontend/src/hooks/useProfile.ts index 38c3561..b752001 100644 --- a/apps/frontend/src/hooks/useProfile.ts +++ b/apps/frontend/src/hooks/useProfile.ts @@ -14,26 +14,17 @@ export interface UseProfileResult { error: string | null; saved: boolean; saving: boolean; - update: (patch: Pick) => Promise; + update: (patch: Pick & Partial>) => Promise; reload: () => void; dismiss: () => void; } -function toProfile(user: { - id: string; - email: string; - firstName: string; - lastName: string; - createdAt: string; - limits?: Profile['limits']; -}): Profile { +function toProfile(user: { id: string; email: string; firstName: string; lastName: string; createdAt: string }): Profile { return { id: user.id, name: `${user.firstName} ${user.lastName}`.trim(), email: user.email, - role: 'Owner', createdAt: user.createdAt, - ...(user.limits ? { limits: user.limits } : {}), }; } @@ -108,13 +99,15 @@ export function useProfile(): UseProfileResult { }, [nonce, t]); const update = useCallback( - async (patch: Pick) => { + async (patch: Pick & Partial>) => { setSaving(true); setError(null); setSaved(false); try { if (!patch.name.trim()) throw new Error(t.validation.nameRequired); - if (!patch.email.includes('@')) throw new Error(t.validation.invalidEmail); + // Email is read-only: backend PATCH /auth/me accepts only + // firstName/lastName — patch.email (if passed by legacy callers) + // is intentionally ignored, never validated nor sent. const token = await getValidAccessToken(); if (!token) { void signOutAndRedirect({ router: routerRef.current }); diff --git a/apps/frontend/src/hooks/useUsage.ts b/apps/frontend/src/hooks/useUsage.ts new file mode 100644 index 0000000..5406f2e --- /dev/null +++ b/apps/frontend/src/hooks/useUsage.ts @@ -0,0 +1,187 @@ +'use client'; + +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useRouter } from 'next/navigation'; +import { ApiClientError, api } from '../api/client'; +import type { OpencodeUsage } from '../api/types'; +import { formatApiError } from '../lib/format-error'; +import { getValidAccessToken, refreshAccessToken, signOutAndRedirect } from '../lib/auth-store'; +import { useI18n } from '../i18n'; + +export interface UseUsageResult { + usage: OpencodeUsage | null; + loading: boolean; + error: string | null; + /** + * True when the backend answers 404 opencode_key_missing (no stored key). + * User-side state — the Limits section renders the inline Add API key + * CTA (no ErrorBoundary, no unavailable wording). + */ + noKey: boolean; + /** 404 opencode_key_missing — same as noKey (explicit 4xx branch). */ + noKeyMissing: boolean; + /** + * True when the backend answers 401 opencode_key_invalid (the stored key + * was rejected upstream). User-side state — inline Add API key CTA like + * the missing-key branch, never a session refresh loop. + */ + noKeyInvalid: boolean; + /** + * True when the upstream is down or throttled: any 5xx (502/503/504…), + * 429, or a network/timeout failure talking to the backend. Critical + * state — the Limits section renders the section-local ErrorState + * (destructive Alert + Retry), no inline unavailable texts. + */ + upstreamDown: boolean; + /** + * Deprecated alias of upstreamDown (kept for compat, prefer upstreamDown). + */ + upstreamUnavailable: boolean; + reload: () => void; +} + +/** 401 carrying the rejected-key code (user-side) vs a session 401 (refresh). */ +function isRejectedKeyError(e: unknown): boolean { + return e instanceof ApiClientError && e.status === 401 && e.code === 'opencode_key_invalid'; +} + +/** 404 carrying the missing-key code (user-side, never an error). */ +function isMissingKeyError(e: unknown): boolean { + return e instanceof ApiClientError && e.status === 404 && e.code === 'opencode_key_missing'; +} + +/** + * Critical (downstream-of-the-user) failure: throttled, upstream 5xx, or the + * request never reached the backend (network/timeout, status 0). + */ +function isUpstreamDownError(e: unknown): boolean { + if (!(e instanceof ApiClientError)) return false; + return e.status === 429 || e.status >= 500 || e.status === 0; +} + +/** + * Live usage hook — GET /api/v1/usage (contract: { updatedAt } + * + optional legacy { balance, usage } + additive rolling/daily/weekly/monthly + * { used, limit } breakdown; Zen Go percent is exposed as { used: percent, limit: 100 }). + * Session 401 → one silent refresh retry, then the session-expired message. + * 404 opencode_key_missing / 401 opencode_key_invalid → 4xx user branches + * (usage null, error null — never fake 0% bars, never ErrorBoundary). + * 429 / 5xx / network → upstreamDown + error for the section ErrorState. + * Percentages are derived by the caller ONLY from real used/limit pairs; + * derivation from the `usage` total is forbidden. + */ +export function useUsage(): UseUsageResult { + const { t } = useI18n(); + const router = useRouter(); + const routerRef = useRef(router); + routerRef.current = router; + const [usage, setUsage] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [noKeyMissing, setNoKeyMissing] = useState(false); + const [noKeyInvalid, setNoKeyInvalid] = useState(false); + const [upstreamDown, setUpstreamDown] = useState(false); + const [nonce, setNonce] = useState(0); + + useEffect(() => { + let cancelled = false; + setLoading(true); + setError(null); + setNoKeyMissing(false); + setNoKeyInvalid(false); + setUpstreamDown(false); + (async () => { + try { + let token = await getValidAccessToken(); + if (!token) { + void signOutAndRedirect({ router: routerRef.current }); + if (!cancelled) setError(t.errors.sessionExpired); + return; + } + const fetchUsage = (accessToken: string) => api.getUsage(accessToken); + const applyUserBranch = (e: unknown): boolean => { + if (isMissingKeyError(e)) { + if (!cancelled) { + setUsage(null); + setNoKeyMissing(true); + setNoKeyInvalid(false); + setUpstreamDown(false); + setError(null); + } + return true; + } + if (isRejectedKeyError(e)) { + if (!cancelled) { + setUsage(null); + setNoKeyMissing(false); + setNoKeyInvalid(true); + setUpstreamDown(false); + setError(null); + } + return true; + } + return false; + }; + try { + const data = await fetchUsage(token); + if (!cancelled) { + setUsage(data); + setNoKeyMissing(false); + setNoKeyInvalid(false); + } + } catch (e) { + if (applyUserBranch(e)) return; + if (e instanceof ApiClientError && e.status === 401) { + token = await refreshAccessToken(); + if (!token) { + void signOutAndRedirect({ router: routerRef.current }); + if (!cancelled) setError(t.errors.sessionExpired); + return; + } + try { + const data = await fetchUsage(token); + if (!cancelled) { + setUsage(data); + setNoKeyMissing(false); + setNoKeyInvalid(false); + } + } catch (retryErr) { + if (applyUserBranch(retryErr)) return; + throw retryErr; + } + } else { + throw e; + } + } + } catch (e) { + if (!cancelled) { + const formatted = formatApiError(e); + setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); + const down = isUpstreamDownError(e); + setUpstreamDown(down); + if (down) setUsage(null); + } + } finally { + if (!cancelled) setLoading(false); + } + })(); + return () => { + cancelled = true; + }; + }, [nonce, t]); + + const reload = useCallback(() => setNonce((n) => n + 1), []); + + const noKey = noKeyMissing || noKeyInvalid; + return { + usage, + loading, + error, + noKey, + noKeyMissing, + noKeyInvalid, + upstreamDown, + upstreamUnavailable: upstreamDown, + reload, + }; +} diff --git a/apps/frontend/src/i18n/dictionaries/en.ts b/apps/frontend/src/i18n/dictionaries/en.ts index 3dd7940..f41f67d 100644 --- a/apps/frontend/src/i18n/dictionaries/en.ts +++ b/apps/frontend/src/i18n/dictionaries/en.ts @@ -138,17 +138,46 @@ export const en: Dictionary = { profile: { titleA: 'Profile', titleB: 'settings', - subtitle: 'Mock profile — update flows through the hook.', - savedTitle: 'Saved (mock)', - savedDesc: 'Profile updated locally.', + subtitle: 'Your account — name is editable, email is read-only.', + savedTitle: 'Saved', + savedDesc: 'Profile name updated.', + overviewTitle: 'Overview', + overviewDesc: 'Account details from the API.', + editTitle: 'Edit name', + editDesc: 'Only the display name can be changed. Email is managed by sign-in and cannot be edited here.', nameLabel: 'Name', emailLabel: 'Email', + emailReadOnlyHint: 'Email is read-only — contact support to change it.', namePlaceholder: 'Your name', saveChanges: 'Save changes', saving: 'Saving…', reset: 'Reset', sincePrefix: 'since', }, + limits: { + title: 'Limits', + desc: 'Live usage limits from the API — real used/limit pairs only.', + rolling: 'Rolling (5h)', + daily: 'Daily', + weekly: 'Weekly', + monthly: 'Monthly', + empty: 'No limits yet', + hint: 'Connect your OpenCode API key to see live limits. Percentages appear only for real used/limit pairs.', + invalidTitle: 'API key rejected', + invalidDesc: + 'The stored OpenCode API key was rejected. Add a valid key to see live limits.', + addKey: 'Add API key', + dialogTitle: 'Add OpenCode API key', + dialogDesc: 'Paste your OpenCode API key below. It is stored encrypted and never shown again.', + keyLabel: 'API key', + keyPlaceholder: 'Paste your key…', + keyHint: + 'Copy the key from your OpenCode dashboard and paste it here. Minimum 20 characters — the value is never logged.', + save: 'Save', + saving: 'Saving…', + required: 'API key is required.', + tooShort: 'API key must be at least 20 characters.', + }, aiProviders: { titleA: 'AI providers', titleB: 'hub', @@ -246,12 +275,6 @@ export const en: Dictionary = { signOut: 'Sign out', login: 'Log in', noEmail: 'No email', - limits: { - title: 'Usage limits', - daily: 'Daily', - weekly: 'Weekly', - monthly: 'Monthly', - }, }, orgs: { titleA: 'Organizations', diff --git a/apps/frontend/src/i18n/dictionaries/ru.ts b/apps/frontend/src/i18n/dictionaries/ru.ts index 830ef2d..17d013f 100644 --- a/apps/frontend/src/i18n/dictionaries/ru.ts +++ b/apps/frontend/src/i18n/dictionaries/ru.ts @@ -138,17 +138,46 @@ export const ru: Dictionary = { profile: { titleA: 'Профиль', titleB: 'настройки', - subtitle: 'Мок-профиль — обновление идёт через хук.', - savedTitle: 'Сохранено (мок)', - savedDesc: 'Профиль обновлён локально.', + subtitle: 'Ваш аккаунт — имя можно менять, email только для чтения.', + savedTitle: 'Сохранено', + savedDesc: 'Имя профиля обновлено.', + overviewTitle: 'Обзор', + overviewDesc: 'Детали аккаунта из API.', + editTitle: 'Изменить имя', + editDesc: 'Можно менять только отображаемое имя. Email задаётся при входе и здесь не меняется.', nameLabel: 'Имя', emailLabel: 'Email', + emailReadOnlyHint: 'Email только для чтения — для смены обратитесь в поддержку.', namePlaceholder: 'Ваше имя', saveChanges: 'Сохранить изменения', saving: 'Сохраняем…', reset: 'Сбросить', sincePrefix: 'с', }, + limits: { + title: 'Лимиты', + desc: 'Живые лимиты использования из API — только реальные пары used/limit.', + rolling: 'Пятичасовой', + daily: 'Дневной', + weekly: 'Недельный', + monthly: 'Месячный', + empty: 'Лимитов пока нет', + hint: 'Подключите OpenCode API-ключ, чтобы увидеть живые лимиты. Проценты показываются только для реальных пар used/limit.', + invalidTitle: 'API-ключ отклонён', + invalidDesc: + 'Сохранённый OpenCode API-ключ отклонён. Добавьте действующий ключ, чтобы увидеть живые лимиты.', + addKey: 'Добавить API-ключ', + dialogTitle: 'Добавить OpenCode API-ключ', + dialogDesc: 'Вставьте ваш OpenCode API-ключ ниже. Он хранится в зашифрованном виде и больше не показывается.', + keyLabel: 'API-ключ', + keyPlaceholder: 'Вставьте ключ…', + keyHint: + 'Скопируйте ключ из вашего OpenCode-кабинета и вставьте сюда. Минимум 20 символов — значение нигде не логируется.', + save: 'Сохранить', + saving: 'Сохраняем…', + required: 'API-ключ обязателен.', + tooShort: 'API-ключ должен быть не короче 20 символов.', + }, aiProviders: { titleA: 'AI-провайдеры', titleB: 'хаб', @@ -246,12 +275,6 @@ export const ru: Dictionary = { signOut: 'Выйти', login: 'Войти', noEmail: 'Нет email', - limits: { - title: 'Лимиты использования', - daily: 'Дневной', - weekly: 'Недельный', - monthly: 'Месячный', - }, }, orgs: { titleA: 'Организации', diff --git a/apps/frontend/src/i18n/dictionaries/types.ts b/apps/frontend/src/i18n/dictionaries/types.ts index 343ee54..2c31251 100644 --- a/apps/frontend/src/i18n/dictionaries/types.ts +++ b/apps/frontend/src/i18n/dictionaries/types.ts @@ -143,14 +143,41 @@ export interface Dictionary { subtitle: string; savedTitle: string; savedDesc: string; + overviewTitle: string; + overviewDesc: string; + editTitle: string; + editDesc: string; nameLabel: string; emailLabel: string; + emailReadOnlyHint: string; namePlaceholder: string; saveChanges: string; saving: string; reset: string; sincePrefix: string; }; + limits: { + title: string; + desc: string; + rolling: string; + daily: string; + weekly: string; + monthly: string; + empty: string; + hint: string; + invalidTitle: string; + invalidDesc: string; + addKey: string; + dialogTitle: string; + dialogDesc: string; + keyLabel: string; + keyPlaceholder: string; + keyHint: string; + save: string; + saving: string; + required: string; + tooShort: string; + }; aiProviders: { titleA: string; titleB: string; @@ -248,12 +275,6 @@ export interface Dictionary { signOut: string; login: string; noEmail: string; - limits: { - title: string; - daily: string; - weekly: string; - monthly: string; - }; }; orgs: { titleA: string; diff --git a/apps/frontend/src/lib/mocks/profile.ts b/apps/frontend/src/lib/mocks/profile.ts index 53dc7e6..5e54862 100644 --- a/apps/frontend/src/lib/mocks/profile.ts +++ b/apps/frontend/src/lib/mocks/profile.ts @@ -9,6 +9,5 @@ export const MOCK_PROFILE: Profile = { id: 'mock-user-1', name: 'Devbox Developer', email: 'dev@devbox.local', - role: 'Owner', createdAt: '2026-01-15T09:00:00.000Z', }; diff --git a/apps/frontend/src/lib/types.ts b/apps/frontend/src/lib/types.ts index 616b0db..8dbbb84 100644 --- a/apps/frontend/src/lib/types.ts +++ b/apps/frontend/src/lib/types.ts @@ -5,7 +5,7 @@ * TODO REAL-API: replace mock sources inside hooks with ApiClient calls. */ -import type { AuthLimits, ProjectScope } from '../api/types'; +import type { ProjectScope } from '../api/types'; export type ProjectStatus = 'active' | 'draft' | 'archived'; @@ -39,11 +39,8 @@ export interface Profile { id: string; name: string; email: string; - role: string; /** ISO-8601 */ createdAt: string; - /** Optional usage limits (mirrors AuthUser.limits, all buckets optional). */ - limits?: AuthLimits; } export type AiProviderStatus = 'connected' | 'disconnected' | 'error'; From 7bb676f8cd17cb91527fef1c9260f7fcc173a3f3 Mon Sep 17 00:00:00 2001 From: alwoo Date: Mon, 19 Oct 2026 17:40:34 +0400 Subject: [PATCH 007/315] chore(opencode): sync pointer to 4cda1c9 --- .opencode | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.opencode b/.opencode index b9ac5a0..4cda1c9 160000 --- a/.opencode +++ b/.opencode @@ -1 +1 @@ -Subproject commit b9ac5a089bd07c98e5f79e734cca20491b8dca44 +Subproject commit 4cda1c9b3fa44142ba9049d5323127c51a2e15a5 From 5aacc183d6f0b0de760220682e1f2c9139c79d52 Mon Sep 17 00:00:00 2001 From: alwoo Date: Mon, 19 Oct 2026 17:40:46 +0400 Subject: [PATCH 008/315] refactor(mobile): migrate imports to @ alias and split session screen Replace ../src relative imports with @/ alias (metro/tsconfig/babel module-resolver, @app for app dir); extract session screen into components/session widgets and lib hooks, [id].tsx becomes thin layout. NOTE: package-lock.json not updated for babel-plugin-module-resolver. --- apps/mobile/app/(tabs)/_layout.tsx | 12 +- apps/mobile/app/(tabs)/account.tsx | 2 +- apps/mobile/app/(tabs)/index.tsx | 24 +- apps/mobile/app/(tabs)/settings.tsx | 18 +- apps/mobile/app/(tabs)/tasks.tsx | 10 +- apps/mobile/app/_layout.tsx | 24 +- apps/mobile/app/connection/add.tsx | 20 +- apps/mobile/app/demo.tsx | 2 +- apps/mobile/app/login.tsx | 10 +- apps/mobile/app/project/[directory].tsx | 8 +- apps/mobile/app/project/remotes.tsx | 4 +- apps/mobile/app/session/[id].tsx | 1606 +---------------- apps/mobile/app/session/styles.ts | 286 +++ apps/mobile/babel.config.js | 21 + apps/mobile/metro.config.js | 3 + apps/mobile/package.json | 1 + apps/mobile/src/components/AuthGate.tsx | 2 +- .../mobile/src/components/ConnectionBadge.tsx | 6 +- apps/mobile/src/components/ErrorBoundary.tsx | 6 +- apps/mobile/src/components/RepoLinkRow.tsx | 2 +- apps/mobile/src/components/UpdateBanner.tsx | 2 +- .../src/components/chat/CloneRepoSheet.tsx | 6 +- .../src/components/session/ComposerDock.tsx | 265 +++ .../src/components/session/EmptyState.tsx | 45 + .../src/components/session/MessageList.tsx | 150 ++ .../src/components/session/PromptOverlay.tsx | 63 + .../src/components/session/SessionBanners.tsx | 47 + .../src/components/session/SessionHeader.tsx | 37 + .../src/components/session/SessionSheets.tsx | 78 + apps/mobile/src/lib/app-version.ts | 3 + apps/mobile/src/lib/composer.ts | 169 ++ apps/mobile/src/lib/outbox-flush.ts | 60 + apps/mobile/src/lib/reconnect-flash.ts | 14 + apps/mobile/src/lib/revert-flow.ts | 72 + apps/mobile/src/lib/session-alerts.ts | 16 + apps/mobile/src/lib/session-binding.ts | 23 + apps/mobile/src/lib/slash-state.ts | 59 + apps/mobile/src/lib/use-ai-sheet.ts | 68 + apps/mobile/src/lib/use-keyboard-dock.ts | 61 + apps/mobile/src/lib/use-session-prompts.ts | 68 + apps/mobile/src/lib/use-session-screen.ts | 569 ++++++ apps/mobile/src/lib/use-session-send.ts | 131 ++ apps/mobile/src/queries/catalog.ts | 8 +- apps/mobile/src/queries/project.ts | 8 +- apps/mobile/src/queries/session-ops.ts | 14 +- apps/mobile/src/queries/sessions.ts | 14 +- apps/mobile/src/stores/catalog.ts | 6 +- apps/mobile/src/stores/cloned-projects.ts | 2 +- apps/mobile/src/stores/connections.ts | 10 +- apps/mobile/src/stores/events.ts | 20 +- apps/mobile/src/stores/sessions.ts | 18 +- apps/mobile/src/stores/settings.ts | 8 +- apps/mobile/tsconfig.json | 1 + 53 files changed, 2468 insertions(+), 1714 deletions(-) create mode 100644 apps/mobile/app/session/styles.ts create mode 100644 apps/mobile/babel.config.js create mode 100644 apps/mobile/src/components/session/ComposerDock.tsx create mode 100644 apps/mobile/src/components/session/EmptyState.tsx create mode 100644 apps/mobile/src/components/session/MessageList.tsx create mode 100644 apps/mobile/src/components/session/PromptOverlay.tsx create mode 100644 apps/mobile/src/components/session/SessionBanners.tsx create mode 100644 apps/mobile/src/components/session/SessionHeader.tsx create mode 100644 apps/mobile/src/components/session/SessionSheets.tsx create mode 100644 apps/mobile/src/lib/composer.ts create mode 100644 apps/mobile/src/lib/outbox-flush.ts create mode 100644 apps/mobile/src/lib/reconnect-flash.ts create mode 100644 apps/mobile/src/lib/revert-flow.ts create mode 100644 apps/mobile/src/lib/session-alerts.ts create mode 100644 apps/mobile/src/lib/session-binding.ts create mode 100644 apps/mobile/src/lib/slash-state.ts create mode 100644 apps/mobile/src/lib/use-ai-sheet.ts create mode 100644 apps/mobile/src/lib/use-keyboard-dock.ts create mode 100644 apps/mobile/src/lib/use-session-prompts.ts create mode 100644 apps/mobile/src/lib/use-session-screen.ts create mode 100644 apps/mobile/src/lib/use-session-send.ts diff --git a/apps/mobile/app/(tabs)/_layout.tsx b/apps/mobile/app/(tabs)/_layout.tsx index c1ddaed..57a6968 100644 --- a/apps/mobile/app/(tabs)/_layout.tsx +++ b/apps/mobile/app/(tabs)/_layout.tsx @@ -2,11 +2,11 @@ import { Tabs } from "expo-router" import { useColorScheme } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useEvents } from "../../src/stores/events" -import { useSessions } from "../../src/stores/sessions" -import { useSessionsList } from "../../src/queries/sessions" -import { countActiveTasks } from "../../src/lib/active-tasks" -import { ConnectionBadge } from "../../src/components/ConnectionBadge" +import { useEvents } from "@/stores/events" +import { useSessions } from "@/stores/sessions" +import { useSessionsList } from "@/queries/sessions" +import { countActiveTasks } from "@/lib/active-tasks" +import { ConnectionBadge } from "@/components/ConnectionBadge" import { layout } from "@web2bizz/ui-native" export default function TabLayout() { @@ -73,7 +73,7 @@ export default function TabLayout() { tabPress: (e) => { e.preventDefault() // Open new project modal via global UI store — handled in index.tsx - const { openNewProject } = require("../../src/stores/ui").useUi.getState() + const { openNewProject } = require("@/stores/ui").useUi.getState() openNewProject() }, }} diff --git a/apps/mobile/app/(tabs)/account.tsx b/apps/mobile/app/(tabs)/account.tsx index d5d303a..235b941 100644 --- a/apps/mobile/app/(tabs)/account.tsx +++ b/apps/mobile/app/(tabs)/account.tsx @@ -2,7 +2,7 @@ import { View, Text, TouchableOpacity, ScrollView, StyleSheet, useColorScheme, A import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { router } from "expo-router" -import { useConnections } from "../../src/stores/connections" +import { useConnections } from "@/stores/connections" import { layout } from "@web2bizz/ui-native" export default function AccountScreen() { diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/index.tsx index c5968ae..e6ddfa5 100644 --- a/apps/mobile/app/(tabs)/index.tsx +++ b/apps/mobile/app/(tabs)/index.tsx @@ -21,11 +21,11 @@ import { import { router } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useSessionsList, useCreateSession, useDeleteSession, useRenameSession } from "../../src/queries/sessions" -import { useProjectInfo, useServerProjects } from "../../src/queries/project" -import { useConnections } from "../../src/stores/connections" -import { useEvents } from "../../src/stores/events" -import { useSettings } from "../../src/stores/settings" +import { useSessionsList, useCreateSession, useDeleteSession, useRenameSession } from "@/queries/sessions" +import { useProjectInfo, useServerProjects } from "@/queries/project" +import { useConnections } from "@/stores/connections" +import { useEvents } from "@/stores/events" +import { useSettings } from "@/stores/settings" import { LanDiscoveryModal } from "@web2bizz/ui-native" import type { LanCandidate } from "@web2bizz/ui-native" import BottomSheet, { @@ -33,16 +33,16 @@ import BottomSheet, { BottomSheetScrollView, type BottomSheetBackdropProps, } from "@gorhom/bottom-sheet" -import type { Project } from "../../src/lib/sdk" +import type { Project } from "@/lib/sdk" import { DirectorySwitcher, DirectoryBrowserSheet } from "@web2bizz/ui-native" -import { CloneRepoSheet } from "../../src/components/chat/CloneRepoSheet" +import { CloneRepoSheet } from "@/components/chat/CloneRepoSheet" import { SheetHandle } from "@web2bizz/ui-native" -import { groupProjects } from "../../src/lib/session-grouping" -import { lanConnectionIds } from "../../src/lib/listed-session" -import type { ListedSession } from "../../src/lib/listed-session" -import { UpdateBanner } from "../../src/components/UpdateBanner" +import { groupProjects } from "@/lib/session-grouping" +import { lanConnectionIds } from "@/lib/listed-session" +import type { ListedSession } from "@/lib/listed-session" +import { UpdateBanner } from "@/components/UpdateBanner" import { nameOf } from "@web2bizz/ui-native" -import { useUi } from "../../src/stores/ui" +import { useUi } from "@/stores/ui" import { breakpoints, colors } from "@web2bizz/ui-native" import { useTablet } from "@web2bizz/ui-native" import { isLandscapeSize, shouldCapSheetContent, sheetContentCap } from "@web2bizz/ui-native" diff --git a/apps/mobile/app/(tabs)/settings.tsx b/apps/mobile/app/(tabs)/settings.tsx index 0ad599f..048d673 100644 --- a/apps/mobile/app/(tabs)/settings.tsx +++ b/apps/mobile/app/(tabs)/settings.tsx @@ -13,13 +13,13 @@ import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { SvgXml } from "react-native-svg" import { router } from "expo-router" -import { useAuth } from "../../src/stores/auth" -import { useSettings } from "../../src/stores/settings" -import { useConnections } from "../../src/stores/connections" -import { useEvents } from "../../src/stores/events" +import { useAuth } from "@/stores/auth" +import { useSettings } from "@/stores/settings" +import { useConnections } from "@/stores/connections" +import { useEvents } from "@/stores/events" import { LanDiscoveryModal } from "@web2bizz/ui-native" import type { LanCandidate } from "@web2bizz/ui-native" -import type { ServerConnection } from "../../src/lib/types" +import type { ServerConnection } from "@/lib/types" const logoXml = `` import { @@ -27,11 +27,11 @@ import { categoryMeta, setup as setupNotifications, granted as notificationsGranted, -} from "../../src/lib/notifications" -import type { Category } from "../../src/lib/notifications" -import { CURRENT_VERSION } from "../../src/lib/update-check" +} from "@/lib/notifications" +import type { Category } from "@/lib/notifications" +import { CURRENT_VERSION } from "@/lib/update-check" import { colors, layout } from "@web2bizz/ui-native" -import type { LocalePreference } from "../../src/lib/i18n/locale-resolve" +import type { LocalePreference } from "@/lib/i18n/locale-resolve" function SettingRow({ icon, diff --git a/apps/mobile/app/(tabs)/tasks.tsx b/apps/mobile/app/(tabs)/tasks.tsx index 57a9ed8..7599e29 100644 --- a/apps/mobile/app/(tabs)/tasks.tsx +++ b/apps/mobile/app/(tabs)/tasks.tsx @@ -3,12 +3,12 @@ import { View, Text, FlatList, TouchableOpacity, StyleSheet, useColorScheme } fr import { router } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useSessions } from "../../src/stores/sessions" -import { useSessionsList } from "../../src/queries/sessions" -import { useEvents } from "../../src/stores/events" -import { selectActiveSessions } from "../../src/lib/active-tasks" +import { useSessions } from "@/stores/sessions" +import { useSessionsList } from "@/queries/sessions" +import { useEvents } from "@/stores/events" +import { selectActiveSessions } from "@/lib/active-tasks" import { colors } from "@web2bizz/ui-native" -import type { ListedSession } from "../../src/lib/listed-session" +import type { ListedSession } from "@/lib/listed-session" // Tasks = sessions where the agent is currently doing something: // SSE sessionStatus busy/retry, plus optimistic sending (tap → SSE busy gap). diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index b9bc3c0..c13b099 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -3,21 +3,21 @@ import { Stack, router, useSegments } from "expo-router" import { StatusBar } from "expo-status-bar" import { useColorScheme, View, ActivityIndicator, AppState } from "react-native" import { QueryClientProvider } from "@tanstack/react-query" -import { queryClient, setupQueryFocusManager } from "../src/lib/query-client" -import { queryKeys } from "../src/lib/query-keys" -import { fetchCatalogData } from "../src/queries/catalog" +import { queryClient, setupQueryFocusManager } from "@/lib/query-client" +import { queryKeys } from "@/lib/query-keys" +import { fetchCatalogData } from "@/queries/catalog" import { GestureHandlerRootView } from "react-native-gesture-handler" import { BottomSheetModalProvider } from "@gorhom/bottom-sheet" import { I18nextProvider, useTranslation } from "react-i18next" -import i18n from "../src/lib/i18n/config" -import { useAuth } from "../src/stores/auth" -import { useConnections } from "../src/stores/connections" -import { useEvents } from "../src/stores/events" -import { useSettings } from "../src/stores/settings" -import { AuthGate } from "../src/components/AuthGate" -import { ErrorBoundary } from "../src/components/ErrorBoundary" -import * as notifications from "../src/lib/notifications" -import { flushPendingSignups } from "../src/lib/waitlist-queue-storage" +import i18n from "@/lib/i18n/config" +import { useAuth } from "@/stores/auth" +import { useConnections } from "@/stores/connections" +import { useEvents } from "@/stores/events" +import { useSettings } from "@/stores/settings" +import { AuthGate } from "@/components/AuthGate" +import { ErrorBoundary } from "@/components/ErrorBoundary" +import * as notifications from "@/lib/notifications" +import { flushPendingSignups } from "@/lib/waitlist-queue-storage" import * as SplashScreen from "expo-splash-screen" SplashScreen.preventAutoHideAsync().catch(() => {}) diff --git a/apps/mobile/app/connection/add.tsx b/apps/mobile/app/connection/add.tsx index 70ea1f5..30f7f1b 100644 --- a/apps/mobile/app/connection/add.tsx +++ b/apps/mobile/app/connection/add.tsx @@ -14,17 +14,17 @@ import { import { router } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useConnections } from "../../src/stores/connections" -import type { ConnectionType } from "../../src/lib/types" -import { probeConnection, shareReport } from "../../src/lib/diagnostics" -import { parseUrl } from "../../src/lib/diagnostics-classify" -import { buildAuth } from "../../src/lib/auth" -import { submitWaitlistSignup, buildWaitlistMailtoUrl, needsManualEscapeHatch, type QueuedSignup } from "../../src/lib/waitlist" -import { flushPendingSignups, queuePendingSignup, readPendingSignups, dropPendingSignup } from "../../src/lib/waitlist-queue-storage" -import { HARDCODED_SERVER_URL } from "../../src/lib/server-config" -import { buildManualLanUrl } from "../../src/lib/lan-manual" +import { useConnections } from "@/stores/connections" +import type { ConnectionType } from "@/lib/types" +import { probeConnection, shareReport } from "@/lib/diagnostics" +import { parseUrl } from "@/lib/diagnostics-classify" +import { buildAuth } from "@/lib/auth" +import { submitWaitlistSignup, buildWaitlistMailtoUrl, needsManualEscapeHatch, type QueuedSignup } from "@/lib/waitlist" +import { flushPendingSignups, queuePendingSignup, readPendingSignups, dropPendingSignup } from "@/lib/waitlist-queue-storage" +import { HARDCODED_SERVER_URL } from "@/lib/server-config" +import { buildManualLanUrl } from "@/lib/lan-manual" import { colors } from "@web2bizz/ui-native" -import { APP_VERSION } from "../../src/lib/app-version" +import { APP_VERSION } from "@/lib/app-version" export default function AddConnectionScreen() { const colorScheme = useColorScheme() diff --git a/apps/mobile/app/demo.tsx b/apps/mobile/app/demo.tsx index a4d7143..1a2c4fd 100644 --- a/apps/mobile/app/demo.tsx +++ b/apps/mobile/app/demo.tsx @@ -4,7 +4,7 @@ import { Stack, useRouter } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { MessageBubble, PermissionPrompt } from "@web2bizz/ui-native" -import { buildDemoScript, buildDemoCompletionMessage, buildDemoDenialMessage } from "../src/lib/demo-script" +import { buildDemoScript, buildDemoCompletionMessage, buildDemoDenialMessage } from "@/lib/demo-script" import { colors } from "@web2bizz/ui-native" // Reply values of PermissionPrompt's `onReply` (see diff --git a/apps/mobile/app/login.tsx b/apps/mobile/app/login.tsx index 8f302b7..2458578 100644 --- a/apps/mobile/app/login.tsx +++ b/apps/mobile/app/login.tsx @@ -17,13 +17,13 @@ import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { SvgXml } from "react-native-svg" import { useSafeAreaInsets } from "react-native-safe-area-context" -import { useConnections } from "../src/stores/connections" -import { useSettings } from "../src/stores/settings" -import { useEvents } from "../src/stores/events" +import { useConnections } from "@/stores/connections" +import { useSettings } from "@/stores/settings" +import { useEvents } from "@/stores/events" import { LanDiscoveryModal } from "@web2bizz/ui-native" import type { LanCandidate } from "@web2bizz/ui-native" -import type { ServerConnection } from "../src/lib/types" -import { HARDCODED_SERVER_URL } from "../src/lib/server-config" +import type { ServerConnection } from "@/lib/types" +import { HARDCODED_SERVER_URL } from "@/lib/server-config" const logoXml = `` diff --git a/apps/mobile/app/project/[directory].tsx b/apps/mobile/app/project/[directory].tsx index fd5b941..4c34ffd 100644 --- a/apps/mobile/app/project/[directory].tsx +++ b/apps/mobile/app/project/[directory].tsx @@ -3,10 +3,10 @@ import { View, Text, FlatList, TouchableOpacity, StyleSheet, useColorScheme, Act import { Stack, useLocalSearchParams, router } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useSessionsList, useCreateSession, useDeleteSession } from "../../src/queries/sessions" -import { useProjectRemotes } from "../../src/queries/project" -import { useConnections } from "../../src/stores/connections" -import { RepoLinkRow } from "../../src/components/RepoLinkRow" +import { useSessionsList, useCreateSession, useDeleteSession } from "@/queries/sessions" +import { useProjectRemotes } from "@/queries/project" +import { useConnections } from "@/stores/connections" +import { RepoLinkRow } from "@/components/RepoLinkRow" import { colors } from "@web2bizz/ui-native" // How many remotes the header card shows before collapsing the rest behind diff --git a/apps/mobile/app/project/remotes.tsx b/apps/mobile/app/project/remotes.tsx index e9453b5..c283b63 100644 --- a/apps/mobile/app/project/remotes.tsx +++ b/apps/mobile/app/project/remotes.tsx @@ -2,8 +2,8 @@ import { View, Text, FlatList, StyleSheet, useColorScheme, ActivityIndicator } f import { Stack, useLocalSearchParams } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useProjectRemotes } from "../../src/queries/project" -import { RepoLinkRow } from "../../src/components/RepoLinkRow" +import { useProjectRemotes } from "@/queries/project" +import { RepoLinkRow } from "@/components/RepoLinkRow" // Full remote list of a project (the header card shows the first 3). // Params mirror the project screen: encoded directory + origin connectionId. diff --git a/apps/mobile/app/session/[id].tsx b/apps/mobile/app/session/[id].tsx index b0af4f5..9cd7fcf 100644 --- a/apps/mobile/app/session/[id].tsx +++ b/apps/mobile/app/session/[id].tsx @@ -1,106 +1,17 @@ -import { useEffect, useRef, useState, useCallback, useMemo } from "react" -import { - View, - Text, - FlatList, - TextInput, - TouchableOpacity, - Pressable, - ScrollView, - StyleSheet, - useColorScheme, - KeyboardAvoidingView, - Platform, - ActivityIndicator, - Alert, - Keyboard, - useWindowDimensions, -} from "react-native" -import { useLocalSearchParams, Stack, useRouter, useFocusEffect } from "expo-router" -import type BottomSheet from "@gorhom/bottom-sheet" -import { Ionicons } from "@expo/vector-icons" +import { View, ActivityIndicator, KeyboardAvoidingView, Platform, useColorScheme } from "react-native" +import { useLocalSearchParams } from "expo-router" import { useSafeAreaInsets } from "react-native-safe-area-context" -import { LinearGradient } from "expo-linear-gradient" import { useTranslation } from "react-i18next" -import * as ImagePicker from "expo-image-picker" -import * as ImageManipulator from "expo-image-manipulator" -import * as Clipboard from "expo-clipboard" -import { - MessageBubble, - PermissionPrompt, - QuestionPrompt, - StatusIndicator, - SlashPopover, - AiSettingsModal, - ImageAttachments, - MessageQueueSheet, - SessionInfo, - type SlashCommand, - type Attachment, - colors, -} from "@web2bizz/ui-native" -import { useSessions } from "../../src/stores/sessions" -import type { QueuedDraft } from "../../src/stores/sessions" -import { useEvents, refreshPending } from "../../src/stores/events" -import { useCatalogData } from "../../src/queries/catalog" -import { - useAbortSession, - useRevertSession, - useUnrevertSession, - usePermissionReply, - useQuestionReply, - useQuestionReject, - type RevertResult, -} from "../../src/queries/session-ops" -import { useConnections } from "../../src/stores/connections" -import { useAuth } from "../../src/stores/auth" -import { useCatalog } from "../../src/stores/catalog" -import { useSpeech } from "../../src/lib/speech" -import { composerMaxHeight, keyboardVerticalOffset, COMPOSER_MIN_HEIGHT } from "@web2bizz/ui-native" - -// --- Builtin slash commands --- -// Hard input cap, mirrored in the TextInput's maxLength below. Pastes that -// would overflow it are still applied (the native field truncates) but warn -// first — otherwise long logs silently lose their tail. -const MAX_COMPOSER_LENGTH = 10000 -const BUILTIN_COMMANDS: SlashCommand[] = [ - { - trigger: "new", - title: "New Session", - description: "Start a new session", - icon: "add-circle-outline", - type: "builtin", - }, - { - trigger: "model", - title: "Switch Model", - description: "Choose a different model", - icon: "hardware-chip-outline", - type: "builtin", - }, - { - trigger: "agent", - title: "Switch Agent", - description: "Cycle to next agent", - icon: "person-outline", - type: "builtin", - }, -] - -// Quick actions offered on an empty (new) chat. Tapping one prefills the -// composer — it never sends by itself. -const SUGGESTIONS = [ - { key: "fixBug", icon: "bug-outline", labelKey: "session.empty.suggestions.fixBug", promptKey: "session.empty.prompts.fixBug" }, - { key: "newTask", icon: "list-outline", labelKey: "session.empty.suggestions.newTask", promptKey: "session.empty.prompts.newTask" }, - { key: "writeTest", icon: "flask-outline", labelKey: "session.empty.suggestions.writeTest", promptKey: "session.empty.prompts.writeTest" }, - { key: "reviewCode", icon: "eye-outline", labelKey: "session.empty.suggestions.reviewCode", promptKey: "session.empty.prompts.reviewCode" }, - { key: "checkCicd", icon: "git-branch-outline", labelKey: "session.empty.suggestions.checkCicd", promptKey: "session.empty.prompts.checkCicd" }, -] as const - -// Shared stable empty queue: the per-session selector below must not mint a -// fresh `[]` on every store notification (new reference = re-render and new -// downstream props on every unrelated update, e.g. per streamed token). -const EMPTY_QUEUE: QueuedDraft[] = [] +import { SessionInfo, keyboardVerticalOffset } from "@web2bizz/ui-native" +import { useSessionBinding } from "@/lib/session-binding" +import { useSessionController } from "@/lib/use-session-screen" +import { SessionHeader } from "@/components/session/SessionHeader" +import { SessionBanners } from "@/components/session/SessionBanners" +import { MessageList } from "@/components/session/MessageList" +import { ComposerDock } from "@/components/session/ComposerDock" +import { PromptOverlay } from "@/components/session/PromptOverlay" +import { SessionSheets } from "@/components/session/SessionSheets" +import { s } from "./styles" export default function SessionScreen() { const { id, directory, connectionId } = useLocalSearchParams<{ @@ -108,289 +19,11 @@ export default function SessionScreen() { directory?: string connectionId?: string }>() - const router = useRouter() const colorScheme = useColorScheme() const isDark = colorScheme === "dark" const insets = useSafeAreaInsets() - const { height: windowHeight, fontScale } = useWindowDimensions() const { t } = useTranslation() - const flatListRef = useRef(null) - const aiSheetRef = useRef(null) - const queueSheetRef = useRef(null) - const [input, setInput] = useState("") - const [attachments, setAttachments] = useState([]) - // Explicit composer height: the native multiline measurement doesn't reliably - // shrink back after a programmatic clear on Android, so track content height - // and drive the field height ourselves (clamped to [minHeight, maxHeight]). - // null = natural height (floor applies). - const [composerHeight, setComposerHeight] = useState(null) - // Native handle for scroll resets (see clearComposer below). - const fieldRef = useRef(null) - const [showInfo, setShowInfo] = useState(false) - const [keyboardY, setKeyboardY] = useState(null) - // Высота клавиатуры — нижний док (overlay) поднимается над ней вручную: - // KeyboardAvoidingView своим padding двигает только in-flow контент, - // абсолютно спозиционированный док его игнорирует. - const [keyboardH, setKeyboardH] = useState(0) - // Замеренная высота нижнего дока (квик-действия + ввод + аттачменты; - // промпты — absolute-оверлей и в замер не входят): - // уходит в нижний отступ списка сообщений, чтобы не проваливались под overlay. - const [dockHeight, setDockHeight] = useState(0) - - useEffect(() => { - const show = Keyboard.addListener(Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow", (event) => { - setKeyboardY(event.endCoordinates.screenY) - setKeyboardH(event.endCoordinates.height ?? 0) - }) - const hide = Keyboard.addListener(Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide", () => { - setKeyboardY(null) - setKeyboardH(0) - }) - return () => { - show.remove() - hide.remove() - } - }, []) - - const inputMaxHeight = composerMaxHeight(Platform.OS, windowHeight, keyboardY, insets.top, fontScale) - // Controlled field height: grow with content, snap back to the floor on reset. - // The floor is COMPOSER_MIN_HEIGHT (88 = one text line + the input's vertical - // padding), NOT 80: a lower floor clips the first line inside the fixed box - // (paddingTop 12 + line ~24 + paddingBottom 52 for the overlay buttons), and - // the field only looked right again once a newline grew the measurement past - // the deficit. Must mirror s.input.minHeight. - const composerFieldHeight = Math.max( - COMPOSER_MIN_HEIGHT, - Math.min(composerHeight ?? COMPOSER_MIN_HEIGHT, inputMaxHeight), - ) - - const { - currentSession, - messages, - parts, - isLoading, - loadingMore, - hasMore, - selectSession, - sendMessage, - loadOlderMessages, - } = useSessions() - // Discrete server ops as React Query mutations (optimistic UI + rollback - // inside, alerts stay at the call sites). - const abortMutation = useAbortSession() - const revertMutation = useRevertSession() - const unrevertMutation = useUnrevertSession() - const permissionMutation = usePermissionReply() - const questionMutation = useQuestionReply() - const questionRejectMutation = useQuestionReject() - - // Busy = optimistic sending flag OR SSE-reported status. The optimistic - // flag alone is not enough: it only bridges the gap between tap and SSE - // busy, and a re-entry (useFocusEffect → selectSession) used to clear it — - // so after leaving and returning to a running chat the Stop button - // disappeared even though the server was still busy. SSE status persists - // globally across navigation, so it keeps the button visible. - const optimisticSending = useSessions((s) => !!(currentSession && s.sending[currentSession.id])) - const queuedForSession = useSessions((s) => (currentSession ? (s.queue[currentSession.id] ?? EMPTY_QUEUE) : EMPTY_QUEUE)) - const enqueueMessage = useSessions((s) => s.enqueueMessage) - const sseBusy = useEvents( - (s) => !!currentSession && !!s.sessionStatus[currentSession.id] && s.sessionStatus[currentSession.id].type !== "idle", - ) - const isSending = optimisticSending || sseBusy - - const { authenticateForMessage } = useAuth() - const { client, clientForDirectory } = useConnections() - - // Origin-aware client: the open session's own server (cloud or LAN), never - // just the active connection. - const sessionClient = useMemo( - () => - currentSession?.directory - ? (clientForDirectory(currentSession.directory, currentSession.connectionId) ?? client) - : currentSession - ? (clientForDirectory(undefined, currentSession.connectionId) ?? client) - : client, - [currentSession?.directory, currentSession?.connectionId, clientForDirectory, client], - ) - - // Catalog lists from the React Query cache, scoped to the open session's - // server; the agent/model/variant SELECTIONS stay local (Zustand) and are - // seeded from each fresh snapshot. - const { data: catalogData } = useCatalogData(currentSession?.connectionId) - useEffect(() => { - // Skip empty snapshots (e.g. a server that answered 401): reseeding from - // nothing would wipe a still-valid selection. - if (catalogData && (catalogData.agents.length > 0 || catalogData.providers.length > 0)) { - useCatalog.getState().reseed(catalogData) - } - }, [catalogData]) - const agents = catalogData?.agents ?? [] - const serverCommands = catalogData?.commands ?? [] - const providers = catalogData?.providers ?? [] - const agent = useCatalog((s) => s.agent) || "" - const model = useCatalog((s) => s.model) - const setModel = useCatalog((s) => s.setModel) - const variant = useCatalog((s) => s.variant) - const setVariant = useCatalog((s) => s.setVariant) - const setAgentInStore = useCatalog((s) => s.setAgent) - const setAgent = useCallback((name: string) => setAgentInStore(name, agents), [setAgentInStore, agents]) - - // Permission & question state - const sessionID = currentSession?.id - const permissions = useEvents((s) => (sessionID ? s.permissions[sessionID] : undefined)) || [] - const questions = useEvents((s) => (sessionID ? s.questions[sessionID] : undefined)) || [] - - const [showScrollButton, setShowScrollButton] = useState(false) - - // SSE reconnect banner - const reconnectAttempts = useEvents((s) => s.reconnectAttempts) - const [showConnectedFlash, setShowConnectedFlash] = useState(false) - const prevReconnecting = useRef(false) - - // Voice input — transcript appends to the text input on completion - const speech = useSpeech( - useCallback((text: string) => { - setInput((prev) => (prev ? prev + " " + text : text)) - }, []), - ) - - // Surface speech recognition failures with the native error detail - // (e.g. "not-allowed", "service-not-allowed") so the alert is diagnosable. - // Keyed on the error value itself so it only fires once per distinct error, - // not on every re-render while it remains set. - useEffect(() => { - if (!speech.error) return - Alert.alert(t("session.alerts.speechErrorTitle"), `${t("session.alerts.speechErrorMessage")}\n\n${speech.error}`) - }, [speech.error, t]) - - // One-time surface for store-level action failures that have no call-site - // alert (abort, unrevert). Send/revert failures alert at their call sites - // and never write the store flag, so this can't double-alert. - const sessionError = useSessions((s) => s.error) - const clearSessionError = useSessions((s) => s.clearError) - useEffect(() => { - if (!sessionError) return - Alert.alert(t("common.error"), sessionError) - clearSessionError() - }, [sessionError, clearSessionError, t]) - - // Slash command state. slashHidden закрывает палитру тапом мимо неё - // (текст сохраняется); любой ввод открывает заново. - const [slashHidden, setSlashHidden] = useState(false) - const slashActive = input.startsWith("/") && !input.includes(" ") && !slashHidden - const slashQuery = slashActive ? input.slice(1) : "" - - const allCommands = useMemo(() => { - const custom: SlashCommand[] = serverCommands.map((cmd) => ({ - trigger: cmd.name, - title: cmd.name, - description: cmd.description, - icon: "code-slash-outline", - type: "custom", - })) - return [...custom, ...BUILTIN_COMMANDS] - }, [serverCommands]) - - // While a revert is pending, the reverted message and everything after it - // still exist server-side (cleanup only runs on the next prompt/unrevert) - // — hide them client-side so editing feels immediate. Message IDs are - // lexicographically sortable, same comparison the TUI uses. Optimistic - // "temp-" IDs (assigned client-side before the server responds, see - // sendMessage) aren't part of that sort order — always keep them so a - // message sent concurrently with a revert isn't hidden. - const revertMessageID = currentSession?.revert?.messageID - - // Inverted FlatList: data is reversed (newest first) so newest renders at bottom - const messageData = useMemo( - () => - (messages || []) - .filter((msg) => !revertMessageID || msg.id.startsWith("temp-") || msg.id < revertMessageID) - .map((msg) => ({ - message: msg, - parts: (parts && parts[msg.id]) || [], - })) - .reverse(), - [messages, parts, revertMessageID], - ) - - // Tracks the latest composer text without pulling `input` into - // handleMessageLongPress's deps — kept as a plain ref assignment (not - // state) so the callback below stays referentially stable across - // keystrokes for MessageBubble's custom memo comparator. - const inputRef = useRef(input) - inputRef.current = input - - const applyRevertResult = useCallback( - (result: RevertResult) => { - if (!result.ok) { - if (result.reason === "unsupported") { - Alert.alert(t("session.alerts.notSupportedTitle"), t("session.alerts.notSupportedMessage")) - } else if (result.reason === "auth") { - Alert.alert(t("session.alerts.revertAuthFailedTitle"), t("session.alerts.revertAuthFailedMessage")) - } else { - Alert.alert(t("session.alerts.editFailedTitle"), t("session.alerts.editFailedMessage")) - } - return - } - setInput(result.text) - // Restore attachments in the same shape the composer's own picker - // functions (pickFromLibrary/pickFromCamera/pasteFromClipboard) use. - setAttachments( - result.files - .filter((f): f is typeof f & { url: string; mime: string } => !!f.url && !!f.mime) - .map((f) => ({ uri: f.url, mime: f.mime, filename: f.filename })), - ) - }, - [t], - ) - - // Stable across renders (reads fresh state via getState() rather than - // closing over props) so MessageBubble's custom memo comparator can bail - // safely without risking a stale handler. - const handleMessageLongPress = useCallback((messageID: string) => { - Alert.alert(t("session.alerts.messageActionsTitle"), undefined, [ - { text: t("common.cancel"), style: "cancel" }, - { - text: t("session.actions.editMessage"), - onPress: () => { - const doRevert = async () => { - const result = await revertMutation.mutateAsync(messageID) - applyRevertResult(result) - } - // Editing overwrites the composer — don't silently clobber an - // in-progress unsent draft. - if (inputRef.current.trim()) { - Alert.alert( - t("session.alerts.replaceDraftTitle"), - t("session.alerts.replaceDraftMessage"), - [ - { text: t("common.cancel"), style: "cancel" }, - { text: t("session.actions.replace"), style: "destructive", onPress: doRevert }, - ], - { cancelable: false }, - ) - return - } - doRevert() - }, - }, - ]) - }, [applyRevertResult, revertMutation, t]) - - const scrollToBottom = useCallback((animated = true) => { - flatListRef.current?.scrollToOffset({ offset: 0, animated }) - }, []) - - // Auto-scroll when status appears at bottom of messages (fixed in list) - const statusForScroll = useEvents((s) => (currentSession ? s.sessionStatus[currentSession.id] : undefined)) - const statusTextForScroll = useEvents((s) => (currentSession ? s.statusText[currentSession.id] : undefined)) - useEffect(() => { - if (statusForScroll && statusForScroll.type !== "idle") { - scrollToBottom(true) - } - }, [statusForScroll, statusTextForScroll]) - // Re-select on every focus, not just mount. currentSession/messages/ // permissions are a single global store, and the native stack keeps screens // underneath a pushed one mounted. Without re-selecting on focus, navigating @@ -398,531 +31,15 @@ export default function SessionScreen() { // session's data (and its permission/question prompts) — so a user could // approve the wrong session's tool call. useFocusEffect re-binds this screen // to its own session whenever it becomes visible again. - useFocusEffect( - useCallback(() => { - if (!id) return - selectSession(id, directory, connectionId).then(() => { - // Re-fetch pending permissions/questions from the server to recover from - // missed SSE events or failed optimistic removals - const connState = useConnections.getState() - const c = directory - ? (connState.clientForDirectory(directory, connectionId) ?? connState.client) - : connectionId - ? (connState.clientForConnection(connectionId) ?? connState.client) - : connState.client - if (c) refreshPending(c, id) - }) - }, [id, directory, connectionId]), - ) - - // Sync model chip from latest assistant message - useEffect(() => { - if (!messages || messages.length === 0) return - for (let i = messages.length - 1; i >= 0; i--) { - const msg = messages[i] - if (msg.role === "assistant" && msg.providerID && msg.modelID) { - setModel({ providerID: msg.providerID, modelID: msg.modelID }) - return - } - if (msg.role === "user" && msg.model) { - setModel(msg.model) - return - } - } - }, [currentSession?.id, messages?.length]) - - // Clear the composer back to its resting geometry: empty text, floor - // height, native scroll at the top. All three must move together: - // - setInput("") alone is not enough: on Android a contentSize event for - // the pre-clear text can land AFTER the reset (see the gate in - // onContentSizeChange) and resurrect a tall box, and the native scroll - // offset survives the clear — the next typed line then paints shifted - // over the top padding; - // - setComposerHeight(null) alone snaps the box but not the scroll. - // Selection 0 forces the native scroll to the top synchronously, before - // the async clear lands — either order ends at offset 0. - // clearedRef marks the stale-measurement window opened here: while it is - // set AND the committed text is still empty, contentSize events are - // pre-clear echoes and must be ignored. Any real text — user-typed (which - // clears the flag via handleChangeText even before its render commits) or - // programmatic (prefill/paste/restore, which never fire onChangeText but - // land in inputRef) — takes the normal path, so fresh measurements for - // long inserted text are never swallowed and the box can't get stuck at - // the floor with scrolled content. - const clearedRef = useRef(false) - const clearComposer = useCallback(() => { - clearedRef.current = true - setInput("") - setComposerHeight(null) - fieldRef.current?.setNativeProps({ selection: { start: 0, end: 0 } }) - }, []) - - // AI sheet must open AFTER the keyboard is gone: expanding while the - // composer holds focus leaves only the backdrop visible (the sheet never - // measures against the keyboard-resized layout). Blur + dismiss first, - // then expand once keyboardDidHide lands — with a fallback timer (~150ms - // Android / ~100ms iOS) and a next-tick fast path when the keyboard is - // already hidden. Pending flag guards double-tap; timer/listener are - // cleaned on unmount. Keeps the parent-owned sheetRef contract untouched. - const aiSheetPendingRef = useRef(false) - const aiSheetTimerRef = useRef | null>(null) - const aiSheetKbSubRef = useRef<{ remove: () => void } | null>(null) - - useEffect( - () => () => { - if (aiSheetTimerRef.current) clearTimeout(aiSheetTimerRef.current) - aiSheetTimerRef.current = null - aiSheetKbSubRef.current?.remove() - aiSheetKbSubRef.current = null - aiSheetPendingRef.current = false - }, - [], - ) - - const openAiSheet = useCallback(() => { - if (aiSheetPendingRef.current) return - aiSheetPendingRef.current = true - fieldRef.current?.blur() - Keyboard.dismiss() - let settled = false - const finish = () => { - if (settled) return - settled = true - if (aiSheetTimerRef.current) { - clearTimeout(aiSheetTimerRef.current) - aiSheetTimerRef.current = null - } - aiSheetKbSubRef.current?.remove() - aiSheetKbSubRef.current = null - aiSheetPendingRef.current = false - aiSheetRef.current?.expand() - } - const keyboardVisible = - typeof Keyboard.isVisible === "function" ? Keyboard.isVisible() : keyboardY !== null - if (!keyboardVisible) { - // Keyboard already hidden — expand on the next tick so blur/dismiss - // commits before measuring. - if (typeof requestAnimationFrame === "function") { - requestAnimationFrame(finish) - } else { - aiSheetTimerRef.current = setTimeout(finish, 0) - } - return - } - const sub = Keyboard.addListener("keyboardDidHide", finish) - aiSheetKbSubRef.current = sub - aiSheetTimerRef.current = setTimeout(finish, Platform.OS === "android" ? 150 : 100) - }, [keyboardY]) - - // User-typed text closes the stale-measurement window immediately (even - // before its render commits, so a contentSize racing ahead of the render - // still takes the normal path). Clearing to empty keeps it open — the - // manual backspace-to-empty case behaves like a programmatic clear. - const handleChangeText = useCallback((text: string) => { - clearedRef.current = text.length === 0 - setSlashHidden(false) - setInput(text) - }, []) - - // Outbox auto-flush bookkeeping (see the effect below): refs live next to - // the queue callbacks since handleUpdateQueued resets the parked head. - // wasBusyRef tracks the busy → idle transition — the only moment a flush - // may start. settledHeadRef parks the last attempted head so a failed - // send is NOT retried in a tight setState loop; it waits for the next - // busy → idle cycle, a new head, or an explicit edit. - const wasBusyRef = useRef(false) - const settledHeadRef = useRef(null) - - // Outbox sheet: dismiss the keyboard first (same reason as openAiSheet — - // expanding against a keyboard-resized layout leaves only the backdrop). - const openQueueSheet = useCallback(() => { - fieldRef.current?.blur() - Keyboard.dismiss() - requestAnimationFrame(() => queueSheetRef.current?.expand()) - }, []) - - // Stable sheet props: fresh arrays/closures every render would re-render - // the BottomSheetFlatList on each unrelated update (per streamed token). - const queueItems = useMemo( - () => queuedForSession.map((d) => ({ id: d.id, text: d.text || t("session.queue.attachmentFallback") })), - [queuedForSession, t], - ) - const handleRemoveQueued = useCallback( - (queueId: string) => { - const id = useSessions.getState().currentSession?.id - if (id) useSessions.getState().removeQueuedMessage(id, queueId) - }, - [], - ) - const handleUpdateQueued = useCallback( - (queueId: string, text: string) => { - const id = useSessions.getState().currentSession?.id - if (id) { - useSessions.getState().updateQueuedMessage(id, queueId, text) - // The head may have changed content while idle after a failed flush - // (which parks that head) — allow the fixed text to flush. - settledHeadRef.current = null - } - }, - [], - ) - - // Empty-chat quick action: prefill the composer with the suggestion prompt - // and focus the field so the user can complete it. Never sends by itself. - const handleSuggestionPress = useCallback( - (promptKey: string) => { - handleChangeText(t(promptKey)) - fieldRef.current?.focus() - }, - [handleChangeText, t], - ) - - // Slash command handler - const handleSlashSelect = useCallback( - (cmd: SlashCommand) => { - if (cmd.type === "builtin") { - switch (cmd.trigger) { - case "new": - router.back() - return - case "model": - case "agent": - clearComposer() - openAiSheet() - return - } - } - setInput(`/${cmd.trigger} `) - }, - [clearComposer, openAiSheet, router], - ) - - // --- Image picking --- - - // Convert any image (including HEIC/HEIF from iOS) to guaranteed JPEG bytes - const MAX_DIMENSION = 1568 // Anthropic recommended max - async function toJpeg(uri: string, width: number, height: number): Promise { - const actions: ImageManipulator.Action[] = [] - if (width > MAX_DIMENSION || height > MAX_DIMENSION) { - const scale = MAX_DIMENSION / Math.max(width, height) - actions.push({ resize: { width: Math.round(width * scale), height: Math.round(height * scale) } }) - } - const result = await ImageManipulator.manipulateAsync(uri, actions, { - format: ImageManipulator.SaveFormat.JPEG, - compress: 0.8, - base64: true, - }) - return { - uri: result.uri, - mime: "image/jpeg", - filename: "image.jpg", - width: result.width, - height: result.height, - base64: result.base64 || undefined, - } - } - - const pickFromLibrary = useCallback(async () => { - const result = await ImagePicker.launchImageLibraryAsync({ - mediaTypes: ["images"], - allowsMultipleSelection: true, - selectionLimit: 10, - quality: 1, // full quality - we compress in manipulator - }) - if (result.canceled) return - const settled = await Promise.allSettled(result.assets.map((a) => toJpeg(a.uri, a.width, a.height))) - const items = settled.filter((r) => r.status === "fulfilled").map((r) => r.value) - if (items.length) setAttachments((prev) => [...prev, ...items]) - if (settled.some((r) => r.status === "rejected")) { - console.error( - "Failed to process image(s):", - settled.filter((r) => r.status === "rejected").map((r) => r.reason), - ) - Alert.alert(t("session.alerts.imageFailedTitle"), t("session.alerts.imageFailedMessage")) - } - }, [t]) + useSessionBinding(id, directory, connectionId) - const pickFromCamera = useCallback(async () => { - const perm = await ImagePicker.requestCameraPermissionsAsync() - if (!perm.granted) { - Alert.alert(t("session.alerts.cameraPermissionTitle"), t("session.alerts.cameraPermissionMessage")) - return - } - const result = await ImagePicker.launchCameraAsync({ quality: 1 }) - if (result.canceled) return - const a = result.assets[0] - try { - const item = await toJpeg(a.uri, a.width, a.height) - setAttachments((prev) => [...prev, item]) - } catch (err) { - console.error("Failed to process photo:", err) - Alert.alert(t("session.alerts.imageFailedTitle"), t("session.alerts.imageFailedMessage")) - } - }, [t]) - - const pasteFromClipboard = useCallback(async () => { - // Try image first - const hasImage = await Clipboard.hasImageAsync() - if (hasImage) { - const img = await Clipboard.getImageAsync({ format: "png" }) - if (img?.data) { - const uri = img.data.startsWith("data:") ? img.data : `data:image/png;base64,${img.data}` - const item = await toJpeg(uri, img.size.width, img.size.height) - setAttachments((prev) => [...prev, item]) - return - } - } - // Fall back to text - const hasText = await Clipboard.hasStringAsync() - if (hasText) { - const text = await Clipboard.getStringAsync() - if (text) { - if (input.length + text.length > MAX_COMPOSER_LENGTH) { - Alert.alert(t("session.alerts.pasteTruncatedTitle"), t("session.alerts.pasteTruncatedMessage")) - } - setInput((prev) => prev + text) - return - } - } - Alert.alert(t("session.alerts.emptyClipboardTitle"), t("session.alerts.emptyClipboardMessage")) - }, [input, t]) - - const removeAttachment = useCallback((index: number) => { - setAttachments((prev) => prev.filter((_, i) => i !== index)) - }, []) - - // --- Send --- - const handleSend = async () => { - if (!input.trim() && attachments.length === 0) return - const authenticated = await authenticateForMessage() - if (!authenticated) { - Alert.alert(t("session.alerts.authRequiredTitle"), t("session.alerts.authRequiredMessage")) - return - } - - const text = input.trim() - const files = [...attachments] - setAttachments([]) - // Reset the controlled geometry together with the text — the native - // measurement doesn't reliably shrink on its own after a clear. - clearComposer() - - // Server slash commands (no attachments for commands) - if (text.startsWith("/") && files.length === 0) { - const [cmdName, ...args] = text.split(" ") - const name = cmdName.slice(1) - const match = serverCommands.find((c) => c.name === name) - if (!match) { - // Not a known server command — keep the text instead of firing it - // as a literal prompt. - setInput(text) - Alert.alert(t("session.alerts.unknownCommandTitle"), t("session.alerts.unknownCommandMessage")) - return - } - if (sessionClient && currentSession) { - try { - await sessionClient.session.command(currentSession.id, { - command: name, - arguments: args.join(" "), - agent, - model: model ? `${model.providerID}/${model.modelID}` : undefined, - }) - } catch (err) { - console.error("Command failed:", err) - setInput(text) - Alert.alert(t("session.alerts.sendFailedTitle"), t("session.alerts.sendFailedMessage")) - } - return - } - } - - // While the agent is busy, follow-ups wait in the client-side outbox - // and flush FIFO when the session goes idle (see the auto-flush effect - // below) — instead of hitting the server concurrently. - if (isSending && currentSession) { - enqueueMessage(currentSession.id, text, { - ...(files.length ? { files } : {}), - ...(model ? { model } : {}), - ...(agent ? { agent } : {}), - ...(variant ? { variant } : {}), - }) - return - } - - // Messages are queued server-side when the session is busy. - // No need to abort - just send and it will be processed after current response. - try { - await sendMessage(text, model || undefined, agent || undefined, files, variant || undefined) - } catch (err) { - console.error("Send failed:", err) - // Restore the user's text and attachments so their input isn't lost. - setInput((prev) => (prev ? prev : text)) - setAttachments((prev) => (prev.length ? prev : files)) - Alert.alert(t("session.alerts.sendFailedTitle"), t("session.alerts.sendFailedMessage")) - } - } - - // Auto-flush the outbox: when the session turns idle and something is - // queued, send the head. Strictly one at a time, in order: the send flips - // isSending back on, so the next item waits for the following idle. - // - // Two guards against update loops (see "Maximum update depth exceeded"): - // - flush ONLY on the busy → idle transition or when a NEW head appears - // (never on every render while idle with a non-empty queue); - // - a failed head is parked (settledHeadRef) and re-queued at the FRONT - // to preserve order, but NOT retried until the next cycle — otherwise a - // persistently failing send retries forever, spamming setState + Alert. - useEffect(() => { - if (!currentSession) return - if (isSending) { - wasBusyRef.current = true - return - } - if (queuedForSession.length === 0) { - wasBusyRef.current = false - settledHeadRef.current = null - return - } - const head = queuedForSession[0] - const shouldFlush = wasBusyRef.current || head.id !== settledHeadRef.current - wasBusyRef.current = false - if (!shouldFlush) return - settledHeadRef.current = head.id - const next = useSessions.getState().takeNextQueued(currentSession.id) - if (!next) return - const sessionID = currentSession.id - sendMessage(next.text, next.model ?? model ?? undefined, next.agent ?? agent ?? undefined, next.files, next.variant ?? variant ?? undefined) - .catch((err) => { - console.error("Queued send failed:", err) - // Put it back at the FRONT so order is preserved and nothing is lost. - // No immediate retry: settledHeadRef already parks this head, so the - // effect above skips it until the next busy → idle cycle. - useSessions.setState((state) => ({ - queue: { ...state.queue, [sessionID]: [next, ...(state.queue[sessionID] ?? [])] }, - })) - Alert.alert(t("session.alerts.sendFailedTitle"), t("session.alerts.sendFailedMessage")) - }) - // sendMessage/model/agent/variant are stable enough per render; the flush - // re-runs when isSending flips or the queue identity changes. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isSending, currentSession?.id, queuedForSession, t]) - - // In inverted mode, offset 0 = bottom. Show scroll button when scrolled away from bottom. - const handleScroll = useCallback((event: any) => { - const { contentOffset } = event.nativeEvent - setShowScrollButton(contentOffset.y > 200) - }, []) - - // Debounce: onEndReached can fire multiple times during a single scroll gesture - const loadingTriggered = useRef(false) - const handleLoadMore = useCallback(() => { - if (hasMore && !loadingMore && !loadingTriggered.current) { - loadingTriggered.current = true - loadOlderMessages() - } - }, [hasMore, loadingMore, loadOlderMessages]) - - // Reset trigger when loading finishes - useEffect(() => { - if (!loadingMore) loadingTriggered.current = false - }, [loadingMore]) - - // Detect reconnecting → stable transition for the "Connected ✓" flash. - // reconnectAttempts and lastDisconnectAt reset in the same set() call, so we - // can't use lastDisconnectAt alone; a useRef tracks the prior reconnecting state. - useEffect(() => { - const isReconnecting = reconnectAttempts > 0 - if (prevReconnecting.current && !isReconnecting) { - setShowConnectedFlash(true) - const t = setTimeout(() => setShowConnectedFlash(false), 2000) - return () => clearTimeout(t) - } - prevReconnecting.current = isReconnecting - }, [reconnectAttempts]) - - const handlePermissionReply = async (requestID: string, reply: "once" | "always" | "reject") => { - if (!sessionClient || !sessionID) return - // Optimistic removal + rollback live inside the mutation; a rejection - // here only surfaces the retry alert. - try { - await permissionMutation.mutateAsync({ client: sessionClient, sessionID, requestID, reply }) - } catch (err) { - console.error("Permission reply failed:", err) - Alert.alert(t("session.alerts.replyFailedTitle"), t("session.alerts.replyFailedMessage")) - } - } - - const handleQuestionReply = async (requestID: string, answers: string[][]) => { - if (!sessionClient || !sessionID) return - try { - await questionMutation.mutateAsync({ client: sessionClient, sessionID, requestID, answers }) - } catch (err) { - console.error("Question reply failed:", err) - Alert.alert(t("session.alerts.replyFailedTitle"), t("session.alerts.replyFailedMessage")) - } - } - - const handleQuestionReject = async (requestID: string) => { - if (!sessionClient || !sessionID) return - try { - await questionRejectMutation.mutateAsync({ client: sessionClient, sessionID, requestID }) - } catch (err) { - console.error("Question reject failed:", err) - Alert.alert(t("session.alerts.rejectFailedTitle"), t("session.alerts.rejectFailedMessage")) - } - } - - // Summary label for the single AI settings button ("agent • model") - const aiSummary = `${agent || "build"} • ${model?.modelID ? model.modelID.split("/").pop() || model.modelID : "default"}` - - // Follow-up quick actions: same items/style as the empty-chat suggestions, - // but as a 45px horizontal strip above the composer. Visible when the chat - // is non-empty and the agent is idle — i.e. right after it finishes working - // (isSending flips back to false) — hidden while it is busy or loading. - const showFollowUps = !isLoading && !isSending && messageData.length > 0 - - // Active permission/question prompts cover the composer via the dock - // overlay (see promptOverlay below) instead of unmounting it: the input, - // quick actions and drafts stay mounted underneath and come back - // automatically once the prompt is answered/dismissed. - const hasActivePrompt = permissions.length > 0 || questions.length > 0 - - // Variants for current model (for reasoning effort picker) - const currentModelVariants = useMemo(() => { - if (!model) return undefined - const provider = providers.find((p) => p.id === model.providerID) - const found = provider?.models.find((m) => m.id === model.modelID) - return found?.variants - }, [model, providers]) - - // Memoized header options: expo-router's StackScreen forwards `options` by - // identity into a layout-effect setOptions call — an inline literal would - // fire setOptions on EVERY render (e.g. per streamed token), and the - // resulting navigation-state update re-renders this screen with fresh - // options again ("Maximum update depth exceeded", Screen → setOptions). - // Only real changes (title/dir/focus/theme) may produce a new object. - const screenTitle = currentSession?.title || t("session.titleFallback") - const headerRight = useCallback(() => { - return ( - - setShowInfo((v) => !v)} hitSlop={8}> - - - - ) - }, [showInfo, isDark]) - const screenOptions = useMemo( - () => ({ title: screenTitle, headerRight }), - [screenTitle, headerRight], - ) + // Вся компоновка (composer, speech, мутации, outbox, slash, send, промпты) + // живёт в контроллере — здесь только раскладка групп пропсов по виджетам. + const c = useSessionController(t, isDark, insets) return ( <> - + {/* Session info pulldown */} - { - if (hasMore && !loadingMore) loadOlderMessages() - }} - onScrollToTop={() => { - flatListRef.current?.scrollToEnd({ animated: true }) - }} - onClose={() => setShowInfo(false)} - /> + - {/* SSE reconnect/connected banner */} - {reconnectAttempts > 0 && ( - - {t("session.banners.reconnecting", { attempt: reconnectAttempts })} - - )} - {showConnectedFlash && reconnectAttempts === 0 && ( - - {t("session.banners.connected")} - - )} + - {/* Pending revert (from "Edit message") — offer a way back before it's - cleaned up by the next prompt. */} - {revertMessageID && ( - - {t("session.banners.reverted")} - { - // Clear the composer only after the server confirms the - // unrevert — on failure the prefilled draft must survive. - unrevertMutation.mutate(undefined, { - onSuccess: () => { - // The composer was prefilled with the reverted message's text/ - // attachments (see applyRevertResult) — clear it so Undo doesn't - // leave a stale draft that could be sent as a duplicate. - setAttachments([]) - clearComposer() - }, - }) - }} - hitSlop={8} - > - {t("session.banners.undo")} - - - )} - - {isLoading ? ( + {c.isLoading ? ( ) : ( - - item.message.id} - renderItem={({ item }) => ( - - )} - // Список инвертирован: верх контентных координат = визуальный низ, - // поэтому запас под док даём через paddingTop. - contentContainerStyle={[s.messageList, { paddingTop: 16 + dockHeight }]} - onScroll={handleScroll} - scrollEventThrottle={100} - onEndReached={handleLoadMore} - onEndReachedThreshold={0.5} - // Prevent jump when older messages are prepended - maintainVisibleContentPosition={{ minIndexForVisible: 0 }} - ListHeaderComponent={ - currentSession ? ( - - ) : null - } - ListFooterComponent={ - loadingMore ? ( - - - {t("session.loadingOlder")} - - ) : null - } - /> - {/* Empty state rendered OUTSIDE the inverted list to avoid the - inverted transform mirroring its text/icon (see #ui-mirror). - box-none: taps pass through the overlay itself, chips stay tappable. */} - {messageData.length === 0 && ( - - - {t("session.empty.suggestionsTitle")} - - {SUGGESTIONS.map((item) => ( - handleSuggestionPress(item.promptKey)} - testID={`suggestion-${item.key}`} - accessibilityRole="button" - accessibilityLabel={t(item.labelKey)} - > - - {t(item.labelKey)} - - ))} - - {t("session.empty.hint")} - - )} - {showScrollButton && ( - scrollToBottom(true)} - > - - - )} - {/* Подложка палитры команд: пока палитра открыта, перехватывает - все тапы/скроллы мимо неё — иначе скроллится список сообщений - под палитрой. Тап закрывает палитру (текст цел), палитра в доке - рисуется выше (zIndex дока 2), скролл внутри неё работает. */} - {slashActive && ( - setSlashHidden(true)} - testID="slash-backdrop" - accessibilityRole="button" - accessibilityLabel={t("session.actions.closeCommands")} - /> - )} - + )} - {/* Нижний док: квик-действия + ввод (+ аттачменты, когда видны) — - fixed overlay поверх чата. Высота замеряется (onLayout) и уходит - в отступ списка, клавиатура поднимает док через bottom. - Промпты (permission/question) — absolute-оверлей поверх дока. */} - setDockHeight(e.nativeEvent.layout.height)} - > - {/* Затемнение под доком: полупрозрачный градиент сверху вниз - (прозрачный → 55% чёрного в тёмной теме / 90% белого в светлой, - в цвет фона). Лежит absolute-подложкой: контент дока - рисуется поверх, тапы сквозь (pointerEvents none), на layout не влияет. */} - : null} /> - {/* Промпты поверх ввода: absolute-overlay на весь док (zIndex/elevation 5 - выше поля и кнопок) со сплошным фоном в цвет экрана — поле ввода, - квик-действия и поповеры остаются смонтированы под ним, но не видны - и недоступны для тапов. После ответа/отклонения оверлей исчезает и - ввод «возвращается» сам (драфт цел, размонтирования не было). - Absolute-позиция не участвует в замере dockHeight — список не прыгает. */} - {hasActivePrompt && ( - - {permissions.map((perm) => ( - handlePermissionReply(perm.id, reply)} - /> - ))} - {questions.map((q) => ( - handleQuestionReply(q.id, answers)} - onReject={() => handleQuestionReject(q.id)} - /> - ))} - - )} - - {/* Attachment preview */} - - - {/* Outbox: queued follow-ups waiting for idle */} - {queuedForSession.length > 0 && ( - - - - - {t("session.queue.button", { count: queuedForSession.length })} - - - - )} - - {/* Follow-up quick actions (after the agent finishes) */} - {showFollowUps && ( - - - {SUGGESTIONS.map((item) => ( - handleSuggestionPress(item.promptKey)} - testID={`followup-${item.key}`} - accessibilityRole="button" - accessibilityLabel={t(item.labelKey)} - > - - {t(item.labelKey)} - - ))} - - - )} - - {/* Input */} - - - {/* Список команд: absolute-оверлей, заходит за поле ввода - (низ палитры прячется под полем — выходит из-под блока ввода), - растёт вверх поверх быстрых действий. В замере dockHeight не участвует. */} - {slashActive && ( - - - - )} - { - // Stale-window gate (see clearComposer): a contentSize event - // landing after a clear while the committed text is still - // empty is a pre-clear echo — ignore it so it can't resurrect - // a tall box or poison the floor. Empty then always means the - // minimum height (the null set below bails out without a - // render when already null, so this can't loop). - // Voice transcripts render through `value` while `input` stays - // empty, so listening mode is exempt — the transcript must - // keep growing the box. - if (!speech.listening && clearedRef.current && !inputRef.current) { - setComposerHeight(null) - return - } - setComposerHeight(e.nativeEvent.contentSize.height) - }} - editable={!speech.listening} - multiline - scrollEnabled - maxLength={MAX_COMPOSER_LENGTH} - testID="chat-message-input" - /> - {/* Overlay control bar: bottom row over the input. - box-none lets taps outside the buttons fall through to the field. */} - - - {!speech.listening && ( - - - - )} - {!speech.listening && ( - - - - )} - - - {!isSending && !input.trim() && attachments.length === 0 && !speech.listening && ( - - - - )} - {speech.listening && ( - - - - )} - {/* Stop button: only when busy and no input */} - {isSending && !input.trim() && attachments.length === 0 && !speech.listening && ( - abortMutation.mutate()} - accessibilityLabel={t("session.actions.stop")} - > - - - )} - {/* Send button: when there's input */} - {!speech.listening && (input.trim() || attachments.length > 0) && ( - - - - )} - - - - - - {/* AI settings dialog (agent + model + reasoning effort). - Layer wrapper: gorhom renders inline (not a portal), so without an - explicit stacking level the composer overlay buttons (zIndex: 1) and - the scroll-to-bottom button (Android elevation 4) bleed through the - open sheet and its backdrop. box-none keeps list touches working - while the sheet is closed (index -1). */} - - setModel({ providerID, modelID })} - onSelectVariant={setVariant} - /> - - + ) } - -// Uniform composer spacing: container padding and the input's top/side insets. -const COMPOSER_PADDING = 12 - -const s = StyleSheet.create({ - container: { flex: 1, backgroundColor: "#ffffff" }, - containerDark: { backgroundColor: "#0a0a0a" }, - loading: { flex: 1, justifyContent: "center", alignItems: "center" }, - listWrap: { flex: 1, position: "relative" }, - - // Messages - messageList: { padding: 16, paddingBottom: 8 }, - - // Scroll button - scrollBtn: { - position: "absolute", - bottom: 16, - right: 16, - width: 44, - height: 44, - borderRadius: 22, - backgroundColor: "#ffffff", - justifyContent: "center", - alignItems: "center", - shadowColor: "#000", - shadowOffset: { width: 0, height: 2 }, - shadowOpacity: 0.2, - shadowRadius: 4, - elevation: 4, - }, - scrollBtnDark: { backgroundColor: "#2a2a2a" }, - - // Loading more (appears at top in inverted list = ListFooterComponent) - loadingMore: { - flexDirection: "row", - justifyContent: "center", - alignItems: "center", - gap: 8, - paddingVertical: 16, - }, - loadingMoreText: { fontSize: 13, color: "#999999" }, - - // Empty state overlay — sits on top of the (empty) inverted list, untransformed, - // so its text/icon render upright and un-mirrored on Android. - emptyOverlay: { - ...StyleSheet.absoluteFill, - justifyContent: "center", - alignItems: "center", - paddingVertical: 64, - paddingHorizontal: 24, - }, - - // Empty - empty: { flex: 1, justifyContent: "center", alignItems: "center", paddingVertical: 64 }, - emptyText: { fontSize: 16, color: "#999999", marginTop: 12 }, - // Quick-action chips: web flex-wrap analog — row + wrap so chips flow onto - // the next line instead of stacking vertically. - suggestionsWrap: { - flexDirection: "row", - flexWrap: "wrap", - justifyContent: "center", - gap: 8, - marginTop: 16, - }, - suggestionChip: { - flexDirection: "row", - alignItems: "center", - gap: 6, - paddingHorizontal: 14, - paddingVertical: 10, - borderRadius: 20, - borderWidth: 1, - borderColor: "#e5e5e5", - backgroundColor: "#f5f5f5", - }, - suggestionChipDark: { borderColor: "#2a2a2a", backgroundColor: "#1a1a1a" }, - suggestionText: { fontSize: 14, fontWeight: "500", color: "#444444" }, - suggestionTextDark: { color: colors.textPlaceholder }, - // Follow-up strip above the composer: fixed 45px block, horizontal scroll. - // Chips mirror suggestionChip (border + background) in a compact form to - // fit the 45px height. - // No dividers, transparent background — the strip floats over the list. - followUpBar: { - height: 45, - justifyContent: "center", - // Same inset as the composer field; chips start flush at the bar edge — - // spacing lives only between chips (gap in followUpContent), not around. - marginHorizontal: COMPOSER_PADDING, - backgroundColor: "transparent", - }, - followUpBarDark: { backgroundColor: "transparent" }, - followUpScroll: { height: 45 }, - followUpContent: { - flexDirection: "row", - alignItems: "center", - // Только gap между чипами — без полей вокруг кнопок по краям скролла. - gap: 8, - height: 45, - }, - followUpChip: { - flexDirection: "row", - alignItems: "center", - gap: 6, - paddingHorizontal: 12, - height: 34, - borderRadius: 17, - borderWidth: 1, - borderColor: "#e5e5e5", - backgroundColor: "#f5f5f5", - }, - followUpChipDark: { borderColor: "#2a2a2a", backgroundColor: "#1a1a1a" }, - followUpText: { fontSize: 12, fontWeight: "500", color: "#444444" }, - followUpTextDark: { color: colors.textPlaceholder }, - // Outbox button row above the composer: compact, same chip language. - queueBar: { - flexDirection: "row", - justifyContent: "center", - marginHorizontal: COMPOSER_PADDING, - marginBottom: 8, - }, - queueBtn: { - flexDirection: "row", - alignItems: "center", - gap: 6, - paddingHorizontal: 14, - paddingVertical: 8, - borderRadius: 17, - borderWidth: 1, - borderColor: "#e5e5e5", - backgroundColor: "#f5f5f5", - }, - queueBtnDark: { borderColor: "#2a2a2a", backgroundColor: "#1a1a1a" }, - queueBtnText: { fontSize: 13, fontWeight: "600", color: "#444444" }, - queueBtnTextDark: { color: colors.textPlaceholder }, - emptyHint: { fontSize: 13, color: colors.textPlaceholder, marginTop: 12 }, - metaDark: { color: "#666666" }, - textWhite: { color: "#ffffff" }, - - // Input - // Нижний док — fixed overlay поверх чата (квик-действия + ввод). - // Фон прозрачный: черты нет, контейнеры не перекрывают список плашкой. - // Высота дока замеряется (onLayout) и уходит в отступ списка. - dock: { - position: "absolute", - left: 0, - right: 0, - bottom: 0, - backgroundColor: "transparent", - zIndex: 2, - elevation: 0, - }, - dockDark: { backgroundColor: "transparent" }, - // Оверлей промптов (permission/question): перекрывает весь док поверх ввода - // и квик-действий. Сплошной фон в цвет экрана прячет поле под собой, тапы - // ловит сам (контент под ним недоступен, но не размонтирован). maxHeight - // задаётся инлайном от высоты окна — длинные вопросы скроллятся внутри - // QuestionPrompt, а не разъезжаются на весь экран. - promptOverlay: { - position: "absolute", - top: 0, - left: 0, - right: 0, - bottom: 0, - zIndex: 5, - elevation: 5, - justifyContent: "flex-end", - backgroundColor: "#ffffff", - borderTopWidth: 1, - borderColor: "#e5e5e5", - }, - promptOverlayDark: { backgroundColor: "#0a0a0a", borderColor: "#2a2a2a" }, - dockGradient: { - position: "absolute", - left: 0, - right: 0, - bottom: 0, - // Тянем градиент выше верхней кромки дока, чтобы затемнение начиналось - // плавно над квик-действиями, а не резкой чертой по их верху. - top: -40, - }, - inputContainer: { - padding: COMPOSER_PADDING, - backgroundColor: "transparent", - }, - inputContainerDark: { backgroundColor: "transparent" }, - inputRow: { - flexDirection: "row", - alignItems: "flex-end", - }, - // Список команд: обёртка якорится к низу строки ввода (bottom: 0) и - // продлена вниз на высоту поля (paddingBottom = высота поля − 16): - // блок заходит за поле ввода, а палитра выходит из-под него — низ - // поповера (~16px) прячется за непрозрачным полем (поле выше по z). - // Растёт вверх поверх быстрых действий. В замере dockHeight не участвует. - slashWrap: { - position: "absolute", - left: 0, - right: 0, - bottom: 0, - maxHeight: 340, - zIndex: 0, - elevation: 0, - }, - // Подложка открытой палитры: прозрачная, на весь список (zIndex 1 выше - // FlatList, ниже дока zIndex 2) — перехватывает тапы/скроллы мимо палитры. - slashBackdrop: { - ...StyleSheet.absoluteFill, - zIndex: 1, - }, - overlayBtns: { - position: "absolute", - left: 8, - right: 8, - bottom: 8, - flexDirection: "row", - alignItems: "center", - justifyContent: "space-between", - zIndex: 2, - }, - overlayGroup: { - flexDirection: "row", - alignItems: "center", - gap: 4, - }, - overlayBtn: { - width: 36, - height: 36, - justifyContent: "center", - alignItems: "center", - }, - // Composer spacing — single value for container padding and the input's - // top/side insets so the field spans full width uniformly. - input: { - flex: 1, - backgroundColor: "#f5f5f5", - borderRadius: 20, - // Обводка как у карточек проекта (projectCard): синхронно с дизайном. - borderWidth: 1, - borderColor: "#e5e5e5", - // Поле непрозрачно перекрывает низ палитры команд (slashWrap zIndex 0): - // так палитра визуально выходит из-под блока ввода. - zIndex: 1, - elevation: 1, - paddingTop: COMPOSER_PADDING, - paddingBottom: 52, - paddingLeft: COMPOSER_PADDING, - paddingRight: COMPOSER_PADDING, - fontSize: 16, - minHeight: COMPOSER_MIN_HEIGHT, - maxHeight: 240, - color: "#0a0a0a", - }, - inputDark: { backgroundColor: "#1a1a1a", color: "#ffffff", borderColor: "#2a2a2a" }, - inputListening: { borderWidth: 1, borderColor: "#ef4444" }, - - // Header - headerRight: { flexDirection: "row", alignItems: "center", gap: 8 }, - - // SSE reconnect/connected banner - banner: { - paddingHorizontal: 16, - paddingVertical: 6, - alignItems: "center", - }, - bannerReconnecting: { backgroundColor: "#92400e" }, - bannerConnected: { backgroundColor: "#065f46" }, - bannerText: { color: "#ffffff", fontSize: 13, fontWeight: "500" }, - - // Pending revert (edit message) banner - bannerRevert: { - backgroundColor: colors.accentBannerBg, - flexDirection: "row", - justifyContent: "space-between", - }, - bannerAction: { color: "#FFB199", fontSize: 13, fontWeight: "700" }, - - // Bottom-sheet layer: must sit above the composer overlay buttons and the - // scroll button (see wrapper comment at the AiSettingsModal usage). No - // backgroundColor — so Android draws no shadow from the elevation. - sheetLayer: { - ...StyleSheet.absoluteFill, - zIndex: 10, - elevation: 10, - }, -}) diff --git a/apps/mobile/app/session/styles.ts b/apps/mobile/app/session/styles.ts new file mode 100644 index 0000000..119ea67 --- /dev/null +++ b/apps/mobile/app/session/styles.ts @@ -0,0 +1,286 @@ +import { StyleSheet } from "react-native" +import { colors, COMPOSER_MIN_HEIGHT } from "@web2bizz/ui-native" + +export const COMPOSER_PADDING = 12 + +export const s = StyleSheet.create({ + container: { flex: 1, backgroundColor: "#ffffff" }, + containerDark: { backgroundColor: "#0a0a0a" }, + loading: { flex: 1, justifyContent: "center", alignItems: "center" }, + listWrap: { flex: 1, position: "relative" }, + + // Messages + messageList: { padding: 16, paddingBottom: 8 }, + + // Scroll button + scrollBtn: { + position: "absolute", + bottom: 16, + right: 16, + width: 44, + height: 44, + borderRadius: 22, + backgroundColor: "#ffffff", + justifyContent: "center", + alignItems: "center", + shadowColor: "#000", + shadowOffset: { width: 0, height: 2 }, + shadowOpacity: 0.2, + shadowRadius: 4, + elevation: 4, + }, + scrollBtnDark: { backgroundColor: "#2a2a2a" }, + + // Loading more (appears at top in inverted list = ListFooterComponent) + loadingMore: { + flexDirection: "row", + justifyContent: "center", + alignItems: "center", + gap: 8, + paddingVertical: 16, + }, + loadingMoreText: { fontSize: 13, color: "#999999" }, + + // Empty state overlay — sits on top of the (empty) inverted list, untransformed, + // so its text/icon render upright and un-mirrored on Android. + emptyOverlay: { + ...StyleSheet.absoluteFill, + justifyContent: "center", + alignItems: "center", + paddingVertical: 64, + paddingHorizontal: 24, + }, + + // Empty + empty: { flex: 1, justifyContent: "center", alignItems: "center", paddingVertical: 64 }, + emptyText: { fontSize: 16, color: "#999999", marginTop: 12 }, + // Quick-action chips: web flex-wrap analog — row + wrap so chips flow onto + // the next line instead of stacking vertically. + suggestionsWrap: { + flexDirection: "row", + flexWrap: "wrap", + justifyContent: "center", + gap: 8, + marginTop: 16, + }, + suggestionChip: { + flexDirection: "row", + alignItems: "center", + gap: 6, + paddingHorizontal: 14, + paddingVertical: 10, + borderRadius: 20, + borderWidth: 1, + borderColor: "#e5e5e5", + backgroundColor: "#f5f5f5", + }, + suggestionChipDark: { borderColor: "#2a2a2a", backgroundColor: "#1a1a1a" }, + suggestionText: { fontSize: 14, fontWeight: "500", color: "#444444" }, + suggestionTextDark: { color: colors.textPlaceholder }, + // Follow-up strip above the composer: fixed 45px block, horizontal scroll. + // Chips mirror suggestionChip (border + background) in a compact form to + // fit the 45px height. + // No dividers, transparent background — the strip floats over the list. + followUpBar: { + height: 45, + justifyContent: "center", + // Same inset as the composer field; chips start flush at the bar edge — + // spacing lives only between chips (gap in followUpContent), not around. + marginHorizontal: COMPOSER_PADDING, + backgroundColor: "transparent", + }, + followUpBarDark: { backgroundColor: "transparent" }, + followUpScroll: { height: 45 }, + followUpContent: { + flexDirection: "row", + alignItems: "center", + // Только gap между чипами — без полей вокруг кнопок по краям скролла. + gap: 8, + height: 45, + }, + followUpChip: { + flexDirection: "row", + alignItems: "center", + gap: 6, + paddingHorizontal: 12, + height: 34, + borderRadius: 17, + borderWidth: 1, + borderColor: "#e5e5e5", + backgroundColor: "#f5f5f5", + }, + followUpChipDark: { borderColor: "#2a2a2a", backgroundColor: "#1a1a1a" }, + followUpText: { fontSize: 12, fontWeight: "500", color: "#444444" }, + followUpTextDark: { color: colors.textPlaceholder }, + // Outbox button row above the composer: compact, same chip language. + queueBar: { + flexDirection: "row", + justifyContent: "center", + marginHorizontal: COMPOSER_PADDING, + marginBottom: 8, + }, + queueBtn: { + flexDirection: "row", + alignItems: "center", + gap: 6, + paddingHorizontal: 14, + paddingVertical: 8, + borderRadius: 17, + borderWidth: 1, + borderColor: "#e5e5e5", + backgroundColor: "#f5f5f5", + }, + queueBtnDark: { borderColor: "#2a2a2a", backgroundColor: "#1a1a1a" }, + queueBtnText: { fontSize: 13, fontWeight: "600", color: "#444444" }, + queueBtnTextDark: { color: colors.textPlaceholder }, + emptyHint: { fontSize: 13, color: colors.textPlaceholder, marginTop: 12 }, + metaDark: { color: "#666666" }, + textWhite: { color: "#ffffff" }, + + // Input + // Нижний док — fixed overlay поверх чата (квик-действия + ввод). + // Фон прозрачный: черты нет, контейнеры не перекрывают список плашкой. + // Высота дока замеряется (onLayout) и уходит в отступ списка. + dock: { + position: "absolute", + left: 0, + right: 0, + bottom: 0, + backgroundColor: "transparent", + zIndex: 2, + elevation: 0, + }, + dockDark: { backgroundColor: "transparent" }, + // Оверлей промптов (permission/question): перекрывает весь док поверх ввода + // и квик-действий. Сплошной фон в цвет экрана прячет поле под собой, тапы + // ловит сам (контент под ним недоступен, но не размонтирован). maxHeight + // задаётся инлайном от высоты окна — длинные вопросы скроллятся внутри + // QuestionPrompt, а не разъезжаются на весь экран. + promptOverlay: { + position: "absolute", + top: 0, + left: 0, + right: 0, + bottom: 0, + zIndex: 5, + elevation: 5, + justifyContent: "flex-end", + backgroundColor: "#ffffff", + borderTopWidth: 1, + borderColor: "#e5e5e5", + }, + promptOverlayDark: { backgroundColor: "#0a0a0a", borderColor: "#2a2a2a" }, + dockGradient: { + position: "absolute", + left: 0, + right: 0, + bottom: 0, + // Тянем градиент выше верхней кромки дока, чтобы затемнение начиналось + // плавно над квик-действиями, а не резкой чертой по их верху. + top: -40, + }, + inputContainer: { + padding: COMPOSER_PADDING, + backgroundColor: "transparent", + }, + inputContainerDark: { backgroundColor: "transparent" }, + inputRow: { + flexDirection: "row", + alignItems: "flex-end", + }, + // Список команд: обёртка якорится к низу строки ввода (bottom: 0) и + // продлена вниз на высоту поля (paddingBottom = высота поля − 16): + // блок заходит за поле ввода, а палитра выходит из-под него — низ + // поповера (~16px) прячется за непрозрачным полем (поле выше по z). + // Растёт вверх поверх быстрых действий. В замере dockHeight не участвует. + slashWrap: { + position: "absolute", + left: 0, + right: 0, + bottom: 0, + maxHeight: 340, + zIndex: 0, + elevation: 0, + }, + // Подложка открытой палитры: прозрачная, на весь список (zIndex 1 выше + // FlatList, ниже дока zIndex 2) — перехватывает тапы/скроллы мимо палитры. + slashBackdrop: { + ...StyleSheet.absoluteFill, + zIndex: 1, + }, + overlayBtns: { + position: "absolute", + left: 8, + right: 8, + bottom: 8, + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", + zIndex: 2, + }, + overlayGroup: { + flexDirection: "row", + alignItems: "center", + gap: 4, + }, + overlayBtn: { + width: 36, + height: 36, + justifyContent: "center", + alignItems: "center", + }, + // Composer spacing — single value for container padding and the input's + // top/side insets so the field spans full width uniformly. + input: { + flex: 1, + backgroundColor: "#f5f5f5", + borderRadius: 20, + // Обводка как у карточек проекта (projectCard): синхронно с дизайном. + borderWidth: 1, + borderColor: "#e5e5e5", + // Поле непрозрачно перекрывает низ палитры команд (slashWrap zIndex 0): + // так палитра визуально выходит из-под блока ввода. + zIndex: 1, + elevation: 1, + paddingTop: COMPOSER_PADDING, + paddingBottom: 52, + paddingLeft: COMPOSER_PADDING, + paddingRight: COMPOSER_PADDING, + fontSize: 16, + minHeight: COMPOSER_MIN_HEIGHT, + maxHeight: 240, + color: "#0a0a0a", + }, + inputDark: { backgroundColor: "#1a1a1a", color: "#ffffff", borderColor: "#2a2a2a" }, + inputListening: { borderWidth: 1, borderColor: "#ef4444" }, + + // Header + headerRight: { flexDirection: "row", alignItems: "center", gap: 8 }, + + // SSE reconnect/connected banner + banner: { + paddingHorizontal: 16, + paddingVertical: 6, + alignItems: "center", + }, + bannerReconnecting: { backgroundColor: "#92400e" }, + bannerConnected: { backgroundColor: "#065f46" }, + bannerText: { color: "#ffffff", fontSize: 13, fontWeight: "500" }, + + // Pending revert (edit message) banner + bannerRevert: { + backgroundColor: colors.accentBannerBg, + flexDirection: "row", + justifyContent: "space-between", + }, + bannerAction: { color: "#FFB199", fontSize: 13, fontWeight: "700" }, + + // Bottom-sheet layer: must sit above the composer overlay buttons and the + // scroll button (see wrapper comment at the AiSettingsModal usage). No + // backgroundColor — so Android draws no shadow from the elevation. + sheetLayer: { + ...StyleSheet.absoluteFill, + zIndex: 10, + elevation: 10, + }, +}) diff --git a/apps/mobile/babel.config.js b/apps/mobile/babel.config.js new file mode 100644 index 0000000..b529da2 --- /dev/null +++ b/apps/mobile/babel.config.js @@ -0,0 +1,21 @@ +// Babel config — expo preset + `@`/`@app` aliases (mirrors tsconfig paths + +// metro extraNodeModules). Keeps expo-router/entry working; restart with +// `npx expo start --clear` after changes so the cache picks up the new resolver. +module.exports = function (api) { + api.cache(true) + return { + presets: ["babel-preset-expo"], + plugins: [ + [ + "module-resolver", + { + root: ["."], + alias: { + "@": "./src", + "@app": "./app", + }, + }, + ], + ], + } +} diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js index d7eb75d..3afe0e8 100644 --- a/apps/mobile/metro.config.js +++ b/apps/mobile/metro.config.js @@ -17,6 +17,9 @@ config.resolver.extraNodeModules = { "@web2bizz/ui-native": path.resolve(__dirname, "packages/uikit"), // TODO: deprecated alias @opencode-ai/uikit — удалить через 1 релиз. "@opencode-ai/uikit": path.resolve(__dirname, "packages/uikit"), + // `@` → src, `@app` → app (mirrors tsconfig paths + babel module-resolver). + "@": path.resolve(__dirname, "src"), + "@app": path.resolve(__dirname, "app"), } module.exports = config diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 7f5bf0d..2db95cb 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -65,6 +65,7 @@ "devDependencies": { "@types/node": "^26.6.2", "@types/react": "~19.2.4", + "babel-plugin-module-resolver": "^5.0.2", "typescript": "~6.0.3" }, "expo": { diff --git a/apps/mobile/src/components/AuthGate.tsx b/apps/mobile/src/components/AuthGate.tsx index 4ec40b2..c93d250 100644 --- a/apps/mobile/src/components/AuthGate.tsx +++ b/apps/mobile/src/components/AuthGate.tsx @@ -2,7 +2,7 @@ import { useEffect, type ReactNode } from "react" import { View, Text, TouchableOpacity, StyleSheet, useColorScheme } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useAuth } from "../stores/auth" +import { useAuth } from "@/stores/auth" interface Props { children: ReactNode diff --git a/apps/mobile/src/components/ConnectionBadge.tsx b/apps/mobile/src/components/ConnectionBadge.tsx index 77207d3..4ec027d 100644 --- a/apps/mobile/src/components/ConnectionBadge.tsx +++ b/apps/mobile/src/components/ConnectionBadge.tsx @@ -4,9 +4,9 @@ import { useFocusEffect } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { colors } from "@web2bizz/ui-native" -import { useConnections } from "../stores/connections" -import { useEvents } from "../stores/events" -import { HARDCODED_SERVER_URL } from "../lib/server-config" +import { useConnections } from "@/stores/connections" +import { useEvents } from "@/stores/events" +import { HARDCODED_SERVER_URL } from "@/lib/server-config" // How often the badge re-validates the server health in the background, so // the dot/text/ping stay fresh without reopening the modal. 30s is a single diff --git a/apps/mobile/src/components/ErrorBoundary.tsx b/apps/mobile/src/components/ErrorBoundary.tsx index 50c9ef8..1a6b246 100644 --- a/apps/mobile/src/components/ErrorBoundary.tsx +++ b/apps/mobile/src/components/ErrorBoundary.tsx @@ -9,12 +9,12 @@ import React from "react" import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native" import { colors } from "@web2bizz/ui-native" -import { buildCrashReport, shareReport } from "../lib/diagnostics" -import { log } from "../lib/logbuffer" +import { buildCrashReport, shareReport } from "@/lib/diagnostics" +import { log } from "@/lib/logbuffer" // Class component — can't use the useTranslation() hook, so resolve strings // via the shared i18next instance directly (already initialized by the time // this can render, since app/_layout.tsx imports it before mounting). -import i18n from "../lib/i18n/config" +import i18n from "@/lib/i18n/config" interface Props { children: React.ReactNode diff --git a/apps/mobile/src/components/RepoLinkRow.tsx b/apps/mobile/src/components/RepoLinkRow.tsx index 8e52e21..7c0a39d 100644 --- a/apps/mobile/src/components/RepoLinkRow.tsx +++ b/apps/mobile/src/components/RepoLinkRow.tsx @@ -1,6 +1,6 @@ import { View, Text, TouchableOpacity, StyleSheet, Linking } from "react-native" import { Ionicons } from "@expo/vector-icons" -import type { RepoLink, GitProvider } from "../lib/git-remotes" +import type { RepoLink, GitProvider } from "@/lib/git-remotes" import { colors } from "@web2bizz/ui-native" // Ionicons brand glyph per git host; self-hosted/unknown fall back to a diff --git a/apps/mobile/src/components/UpdateBanner.tsx b/apps/mobile/src/components/UpdateBanner.tsx index db96571..364f1ae 100644 --- a/apps/mobile/src/components/UpdateBanner.tsx +++ b/apps/mobile/src/components/UpdateBanner.tsx @@ -15,7 +15,7 @@ import { View, Text, TouchableOpacity, StyleSheet, Linking } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { colors } from "@web2bizz/ui-native" -import { checkForUpdate, dismissUpdate, CURRENT_VERSION, type AvailableUpdate } from "../lib/update-check" +import { checkForUpdate, dismissUpdate, CURRENT_VERSION, type AvailableUpdate } from "@/lib/update-check" export function UpdateBanner({ isDark }: { isDark: boolean }) { const { t } = useTranslation() diff --git a/apps/mobile/src/components/chat/CloneRepoSheet.tsx b/apps/mobile/src/components/chat/CloneRepoSheet.tsx index fb9f955..c969ebd 100644 --- a/apps/mobile/src/components/chat/CloneRepoSheet.tsx +++ b/apps/mobile/src/components/chat/CloneRepoSheet.tsx @@ -10,9 +10,9 @@ import BottomSheet, { import { useTranslation } from "react-i18next" import { shouldCapSheetContent, sheetContentCap, SheetHandle } from "@web2bizz/ui-native" import { colors } from "@web2bizz/ui-native" -import { filterMockRepos, type MockRepo } from "../../lib/github-mock" -import { useClonedProjects } from "../../stores/cloned-projects" -import { useConnections } from "../../stores/connections" +import { filterMockRepos, type MockRepo } from "@/lib/github-mock" +import { useClonedProjects } from "@/stores/cloned-projects" +import { useConnections } from "@/stores/connections" interface Props { // Parent-owned ref — the sheet is UNCONTROLLED (no `visible` prop): the diff --git a/apps/mobile/src/components/session/ComposerDock.tsx b/apps/mobile/src/components/session/ComposerDock.tsx new file mode 100644 index 0000000..0706539 --- /dev/null +++ b/apps/mobile/src/components/session/ComposerDock.tsx @@ -0,0 +1,265 @@ +import type { ReactNode } from "react" +import { View, Text, TextInput, TouchableOpacity, ScrollView } from "react-native" +import { Ionicons } from "@expo/vector-icons" +import { LinearGradient } from "expo-linear-gradient" +import type { TFunction } from "i18next" +import { + SlashPopover, + ImageAttachments, + colors, + type Attachment, + type SlashCommand, +} from "@web2bizz/ui-native" +import { MAX_COMPOSER_LENGTH } from "@/lib/composer" +import { s } from "@app/session/styles" +import { SUGGESTIONS } from "./EmptyState" + +export interface ComposerDockProps { + isDark: boolean + keyboardH: number + bottomInset: number + onDockLayout: (height: number) => void + attachments: Attachment[] + onRemoveAttachment: (index: number) => void + queueCount: number + onOpenQueue: () => void + showFollowUps: boolean + onSuggestion: (promptKey: string) => void + slashActive: boolean + slashQuery: string + slashCommands: SlashCommand[] + onSlashSelect: (cmd: SlashCommand) => void + composerFieldHeight: number + fieldRef: React.RefObject + input: string + onChangeText: (text: string) => void + clearedRef: React.MutableRefObject + inputRef: React.MutableRefObject + onMeasureHeight: (height: number | null) => void + speechListening: boolean + speechTranscript: string + onMicStart: () => void + onMicStop: () => void + isSending: boolean + onPickLibrary: () => void + onPickCamera: () => void + onOpenAiSheet: () => void + aiSummary: string + onAbort: () => void + onSend: () => void + promptOverlay?: ReactNode + t: TFunction +} + +// Нижний док: квик-действия + ввод (+ аттачменты, когда видны) — +// fixed overlay поверх чата. Высота замеряется (onLayout) и уходит +// в отступ списка, клавиатура поднимает док через bottom. +// Промпты (permission/question) — absolute-оверлей поверх дока (prop promptOverlay). +export function ComposerDock({ + isDark, + keyboardH, + bottomInset, + onDockLayout, + attachments, + onRemoveAttachment, + queueCount, + onOpenQueue, + showFollowUps, + onSuggestion, + slashActive, + slashQuery, + slashCommands, + onSlashSelect, + composerFieldHeight, + fieldRef, + input, + onChangeText, + clearedRef, + inputRef, + onMeasureHeight, + speechListening, + speechTranscript, + onMicStart, + onMicStop, + isSending, + onPickLibrary, + onPickCamera, + onOpenAiSheet, + aiSummary, + onAbort, + onSend, + promptOverlay, + t, +}: ComposerDockProps) { + return ( + onDockLayout(e.nativeEvent.layout.height)} + > + {/* Затемнение под доком: полупрозрачный градиент сверху вниз + (прозрачный → 55% чёрного в тёмной теме / 90% белого в светлой, + в цвет фона). Лежит absolute-подложкой: контент дока + рисуется поверх, тапы сквозь (pointerEvents none), на layout не влияет. */} + + {promptOverlay} + + {/* Attachment preview */} + + + {/* Outbox: queued follow-ups waiting for idle */} + {queueCount > 0 && ( + + + + + {t("session.queue.button", { count: queueCount })} + + + + )} + + {/* Follow-up quick actions (after the agent finishes) */} + {showFollowUps && ( + + + {SUGGESTIONS.map((item) => ( + onSuggestion(item.promptKey)} + testID={`followup-${item.key}`} + accessibilityRole="button" + accessibilityLabel={t(item.labelKey)} + > + + {t(item.labelKey)} + + ))} + + + )} + + {/* Input */} + + + {/* Список команд: absolute-оверлей, заходит за поле ввода + (низ палитры прячется под полем — выходит из-под блока ввода), + растёт вверх поверх быстрых действий. В замере dockHeight не участвует. */} + {slashActive && ( + + + + )} + { + // Stale-window gate (see clearComposer): a contentSize event + // landing after a clear while the committed text is still + // empty is a pre-clear echo — ignore it so it can't resurrect + // a tall box or poison the floor. Empty then always means the + // minimum height (the null set below bails out without a + // render when already null, so this can't loop). + // Voice transcripts render through `value` while `input` stays + // empty, so listening mode is exempt — the transcript must + // keep growing the box. + if (!speechListening && clearedRef.current && !inputRef.current) { + onMeasureHeight(null) + return + } + onMeasureHeight(e.nativeEvent.contentSize.height) + }} + editable={!speechListening} + multiline + scrollEnabled + maxLength={MAX_COMPOSER_LENGTH} + testID="chat-message-input" + /> + {/* Overlay control bar: bottom row over the input. + box-none lets taps outside the buttons fall through to the field. */} + + + {!speechListening && ( + + + + )} + {!speechListening && ( + + + + )} + + + {!isSending && !input.trim() && attachments.length === 0 && !speechListening && ( + + + + )} + {speechListening && ( + + + + )} + {/* Stop button: only when busy and no input */} + {isSending && !input.trim() && attachments.length === 0 && !speechListening && ( + + + + )} + {/* Send button: when there's input */} + {!speechListening && (input.trim() || attachments.length > 0) && ( + + + + )} + + + + + + ) +} diff --git a/apps/mobile/src/components/session/EmptyState.tsx b/apps/mobile/src/components/session/EmptyState.tsx new file mode 100644 index 0000000..5b00568 --- /dev/null +++ b/apps/mobile/src/components/session/EmptyState.tsx @@ -0,0 +1,45 @@ +import { View, Text, TouchableOpacity, StyleSheet } from "react-native" +import { Ionicons } from "@expo/vector-icons" +import { useTranslation } from "react-i18next" +import { colors } from "@web2bizz/ui-native" +import { s } from "@app/session/styles" + +export const SUGGESTIONS = [ + { key: "fixBug", icon: "bug-outline", labelKey: "session.empty.suggestions.fixBug", promptKey: "session.empty.prompts.fixBug" }, + { key: "newTask", icon: "list-outline", labelKey: "session.empty.suggestions.newTask", promptKey: "session.empty.prompts.newTask" }, + { key: "writeTest", icon: "flask-outline", labelKey: "session.empty.suggestions.writeTest", promptKey: "session.empty.prompts.writeTest" }, + { key: "reviewCode", icon: "eye-outline", labelKey: "session.empty.suggestions.reviewCode", promptKey: "session.empty.prompts.reviewCode" }, + { key: "checkCicd", icon: "git-branch-outline", labelKey: "session.empty.suggestions.checkCicd", promptKey: "session.empty.prompts.checkCicd" }, +] as const + +export function EmptyState({ isDark, onSuggestion }: { isDark: boolean; onSuggestion: (promptKey: string) => void }) { + const { t } = useTranslation() + return ( + + + {t("session.empty.suggestionsTitle")} + + {SUGGESTIONS.map((item) => ( + onSuggestion(item.promptKey)} + testID={`suggestion-${item.key}`} + accessibilityRole="button" + accessibilityLabel={t(item.labelKey)} + > + + {t(item.labelKey)} + + ))} + + {t("session.empty.hint")} + + ) +} +EOF +echo done \ No newline at end of file diff --git a/apps/mobile/src/components/session/MessageList.tsx b/apps/mobile/src/components/session/MessageList.tsx new file mode 100644 index 0000000..99d2e77 --- /dev/null +++ b/apps/mobile/src/components/session/MessageList.tsx @@ -0,0 +1,150 @@ +import { useCallback, useEffect, useRef, useState } from "react" +import { View, Text, FlatList, TouchableOpacity, Pressable, ActivityIndicator } from "react-native" +import { Ionicons } from "@expo/vector-icons" +import { useTranslation } from "react-i18next" +import { MessageBubble, StatusIndicator, type StatusSnapshot } from "@web2bizz/ui-native" +import type { Message, Part } from "@/lib/sdk" +import { s } from "@app/session/styles" +import { EmptyState } from "./EmptyState" + +export interface MessageListItem { + message: Message + parts: Part[] +} + +export interface MessageListProps { + messageData: MessageListItem[] + status: StatusSnapshot | undefined + statusText: string | undefined + optimisticSending: boolean + isDark: boolean + hasMore: boolean + loadingMore: boolean + dockHeight: number + slashActive: boolean + showStatus: boolean + listRef: React.RefObject + onLongPress: (messageID: string) => void + onSuggestion: (promptKey: string) => void + onCloseSlash: () => void + onLoadMore: () => void +} + +// Инвертированный список сообщений + статус + empty state + кнопка скролла + +// подложка палитры команд. Скролл-логика (кнопка, debounce догрузки, +// авто-скролл за статусом) живёт здесь, рядом со списком. +export function MessageList({ + messageData, + status, + statusText, + optimisticSending, + isDark, + hasMore, + loadingMore, + dockHeight, + slashActive, + showStatus, + listRef, + onLongPress, + onSuggestion, + onCloseSlash, + onLoadMore, +}: MessageListProps) { + const { t } = useTranslation() + const [showScrollButton, setShowScrollButton] = useState(false) + + const scrollToBottom = useCallback( + (animated = true) => { + listRef.current?.scrollToOffset({ offset: 0, animated }) + }, + [listRef], + ) + + // Auto-scroll when status appears at bottom of messages (fixed in list) + useEffect(() => { + if (status && status.type !== "idle") { + scrollToBottom(true) + } + }, [status, statusText]) + + // In inverted mode, offset 0 = bottom. Show scroll button when scrolled away from bottom. + const handleScroll = useCallback((event: any) => { + const { contentOffset } = event.nativeEvent + setShowScrollButton(contentOffset.y > 200) + }, []) + + // Debounce: onEndReached can fire multiple times during a single scroll gesture + const loadingTriggered = useRef(false) + const handleLoadMore = useCallback(() => { + if (hasMore && !loadingMore && !loadingTriggered.current) { + loadingTriggered.current = true + onLoadMore() + } + }, [hasMore, loadingMore, onLoadMore]) + + // Reset trigger when loading finishes + useEffect(() => { + if (!loadingMore) loadingTriggered.current = false + }, [loadingMore]) + + return ( + + item.message.id} + renderItem={({ item }) => ( + + )} + // Список инвертирован: верх контентных координат = визуальный низ, + // поэтому запас под док даём через paddingTop. + contentContainerStyle={[s.messageList, { paddingTop: 16 + dockHeight }]} + onScroll={handleScroll} + scrollEventThrottle={100} + onEndReached={handleLoadMore} + onEndReachedThreshold={0.5} + // Prevent jump when older messages are prepended + maintainVisibleContentPosition={{ minIndexForVisible: 0 }} + ListHeaderComponent={ + showStatus ? ( + + ) : null + } + ListFooterComponent={ + loadingMore ? ( + + + {t("session.loadingOlder")} + + ) : null + } + /> + {/* Empty state rendered OUTSIDE the inverted list to avoid the + inverted transform mirroring its text/icon (see #ui-mirror). + box-none: taps pass through the overlay itself, chips stay tappable. */} + {messageData.length === 0 && } + {showScrollButton && ( + scrollToBottom(true)} + > + + + )} + {/* Подложка палитры команд: пока палитра открыта, перехватывает + все тапы/скроллы мимо неё — иначе скроллится список сообщений + под палитрой. Тап закрывает палитру (текст цел), палитра в доке + рисуется выше (zIndex дока 2), скролл внутри неё работает. */} + {slashActive && ( + + )} + + ) +} diff --git a/apps/mobile/src/components/session/PromptOverlay.tsx b/apps/mobile/src/components/session/PromptOverlay.tsx new file mode 100644 index 0000000..e674a79 --- /dev/null +++ b/apps/mobile/src/components/session/PromptOverlay.tsx @@ -0,0 +1,63 @@ +import { View, useWindowDimensions } from "react-native" +import { useSafeAreaInsets } from "react-native-safe-area-context" +import { PermissionPrompt, QuestionPrompt } from "@web2bizz/ui-native" +import type { PermissionRequest, QuestionRequest } from "@/stores/events" +import { s } from "@app/session/styles" + +export interface PromptOverlayProps { + permissions: PermissionRequest[] + questions: QuestionRequest[] + isDark: boolean + onPermissionReply: (requestID: string, reply: "once" | "always" | "reject") => void + onQuestionReply: (requestID: string, answers: string[][]) => void + onQuestionReject: (requestID: string) => void +} + +// Промпты поверх ввода: absolute-overlay на весь док (zIndex/elevation 5 +// выше поля и кнопок) со сплошным фоном в цвет экрана — поле ввода, +// квик-действия и поповеры остаются смонтированы под ним, но не видны +// и недоступны для тапов. После ответа/отклонения оверлей исчезает и +// ввод «возвращается» сам (драфт цел, размонтирования не было). +// Absolute-позиция не участвует в замере dockHeight — список не прыгает. +export function PromptOverlay({ + permissions, + questions, + isDark, + onPermissionReply, + onQuestionReply, + onQuestionReject, +}: PromptOverlayProps) { + const insets = useSafeAreaInsets() + const { height: windowHeight } = useWindowDimensions() + + return ( + + {permissions.map((perm) => ( + onPermissionReply(perm.id, reply)} + /> + ))} + {questions.map((q) => ( + onQuestionReply(q.id, answers)} + onReject={() => onQuestionReject(q.id)} + /> + ))} + + ) +} diff --git a/apps/mobile/src/components/session/SessionBanners.tsx b/apps/mobile/src/components/session/SessionBanners.tsx new file mode 100644 index 0000000..ec05248 --- /dev/null +++ b/apps/mobile/src/components/session/SessionBanners.tsx @@ -0,0 +1,47 @@ +import { View, Text, TouchableOpacity } from "react-native" +import type { TFunction } from "i18next" +import { s } from "@app/session/styles" + +export interface SessionBannersProps { + reconnectAttempts: number + showConnectedFlash: boolean + revertMessageID: string | undefined + onUndoRevert: () => void + t: TFunction +} + +// Баннеры сессии: SSE reconnect/connected + pending revert (из "Edit message"). +export function SessionBanners({ + reconnectAttempts, + showConnectedFlash, + revertMessageID, + onUndoRevert, + t, +}: SessionBannersProps) { + return ( + <> + {/* SSE reconnect/connected banner */} + {reconnectAttempts > 0 && ( + + {t("session.banners.reconnecting", { attempt: reconnectAttempts })} + + )} + {showConnectedFlash && reconnectAttempts === 0 && ( + + {t("session.banners.connected")} + + )} + + {/* Pending revert (from "Edit message") — offer a way back before it's + cleaned up by the next prompt. */} + {revertMessageID && ( + + {t("session.banners.reverted")} + + {t("session.banners.undo")} + + + )} + + ) +} diff --git a/apps/mobile/src/components/session/SessionHeader.tsx b/apps/mobile/src/components/session/SessionHeader.tsx new file mode 100644 index 0000000..f3b5dc0 --- /dev/null +++ b/apps/mobile/src/components/session/SessionHeader.tsx @@ -0,0 +1,37 @@ +import { useCallback, useMemo } from "react" +import { View, TouchableOpacity } from "react-native" +import { Stack } from "expo-router" +import { Ionicons } from "@expo/vector-icons" +import { s } from "@app/session/styles" + +export interface SessionHeaderProps { + title: string + showInfo: boolean + isDark: boolean + onToggleInfo: () => void +} + +// Заголовок сессии: expo-router прокидывает `options` по identity в +// layout-effect setOptions — инлайн-литерал вызывал бы setOptions на КАЖДЫЙ +// рендер (например, per streamed token), а обновление navigation-state +// ре-рендерило экран со свежими options снова ("Maximum update depth +// exceeded", Screen → setOptions). Новый объект — только при реальном +// изменении (title/фокус/тема). +export function SessionHeader({ title, showInfo, isDark, onToggleInfo }: SessionHeaderProps) { + const headerRight = useCallback(() => { + return ( + + + + + + ) + }, [showInfo, isDark, onToggleInfo]) + const screenOptions = useMemo(() => ({ title, headerRight }), [title, headerRight]) + + return +} diff --git a/apps/mobile/src/components/session/SessionSheets.tsx b/apps/mobile/src/components/session/SessionSheets.tsx new file mode 100644 index 0000000..07e231d --- /dev/null +++ b/apps/mobile/src/components/session/SessionSheets.tsx @@ -0,0 +1,78 @@ +import { View } from "react-native" +import type BottomSheet from "@gorhom/bottom-sheet" +import { + AiSettingsModal, + MessageQueueSheet, + type QueuedItem, +} from "@web2bizz/ui-native" +import type { Agent } from "@/lib/sdk" +import type { Provider } from "@/lib/catalog-parse" +import { s } from "@app/session/styles" + +export interface SessionSheetsProps { + aiSheetRef: React.RefObject + queueSheetRef: React.RefObject + agents: Agent[] + selectedAgent: string + providers: Provider[] + selectedModel: { providerID: string; modelID: string } | null + variants: Record | undefined + selectedVariant: string | null + isDark: boolean + onSelectAgent: (name: string) => void + onSelectModel: (providerID: string, modelID: string) => void + onSelectVariant: (variant: string | null) => void + queueItems: QueuedItem[] + onRemoveQueued: (id: string) => void + onUpdateQueued: (id: string, text: string) => void +} + +// AI settings dialog (agent + model + reasoning effort) + outbox sheet. +// Layer wrapper: gorhom renders inline (not a portal), so without an +// explicit stacking level the composer overlay buttons (zIndex: 1) and +// the scroll-to-bottom button (Android elevation 4) bleed through the +// open sheet and its backdrop. box-none keeps list touches working +// while the sheet is closed (index -1). +export function SessionSheets({ + aiSheetRef, + queueSheetRef, + agents, + selectedAgent, + providers, + selectedModel, + variants, + selectedVariant, + isDark, + onSelectAgent, + onSelectModel, + onSelectVariant, + queueItems, + onRemoveQueued, + onUpdateQueued, +}: SessionSheetsProps) { + return ( + + + + + ) +} diff --git a/apps/mobile/src/lib/app-version.ts b/apps/mobile/src/lib/app-version.ts index 5cf4643..7fe7184 100644 --- a/apps/mobile/src/lib/app-version.ts +++ b/apps/mobile/src/lib/app-version.ts @@ -5,6 +5,9 @@ // requiring package.json itself, so a version bump in package.json (plus // `node scripts/sync-version.mjs` for the native shells) propagates // everywhere with no code edits. +// +// NOTE: intentionally relative — package.json lives at the mobile root, +// outside the `@` (= src) and `@app` (= app) alias roots, so no alias covers it. import pkg from "../../package.json" export const APP_VERSION: string = (pkg as { version?: string }).version ?? "unknown" diff --git a/apps/mobile/src/lib/composer.ts b/apps/mobile/src/lib/composer.ts new file mode 100644 index 0000000..66781c7 --- /dev/null +++ b/apps/mobile/src/lib/composer.ts @@ -0,0 +1,169 @@ +import { useState, useRef, useCallback } from "react" +import { Alert, Keyboard, TextInput } from "react-native" +import * as ImagePicker from "expo-image-picker" +import * as ImageManipulator from "expo-image-manipulator" +import * as Clipboard from "expo-clipboard" +import type { TFunction } from "i18next" +import type { Attachment } from "@web2bizz/ui-native" + +// Hard input cap, mirrored in the TextInput's maxLength. Pastes that would +// overflow it are still applied (the native field truncates) but warn first. +export const MAX_COMPOSER_LENGTH = 10000 + +const MAX_DIMENSION = 1568 // Anthropic recommended max + +async function toJpeg(uri: string, width: number, height: number): Promise { + const actions: ImageManipulator.Action[] = [] + if (width > MAX_DIMENSION || height > MAX_DIMENSION) { + const scale = MAX_DIMENSION / Math.max(width, height) + actions.push({ resize: { width: Math.round(width * scale), height: Math.round(height * scale) } }) + } + const result = await ImageManipulator.manipulateAsync(uri, actions, { + format: ImageManipulator.SaveFormat.JPEG, + compress: 0.8, + base64: true, + }) + return { + uri: result.uri, + mime: "image/jpeg", + filename: "image.jpg", + width: result.width, + height: result.height, + base64: result.base64 || undefined, + } +} + +export interface ComposerState { + input: string + setInput: (v: string | ((prev: string) => string)) => void + attachments: Attachment[] + setAttachments: (v: Attachment[] | ((prev: Attachment[]) => Attachment[])) => void + composerHeight: number | null + setComposerHeight: (v: number | null) => void + clearedRef: React.MutableRefObject + fieldRef: React.RefObject + inputRef: React.MutableRefObject + clearComposer: () => void + handleChangeText: (text: string) => void + handleSuggestionPress: (promptKey: string) => void + pickFromLibrary: () => Promise + pickFromCamera: () => Promise + pasteFromClipboard: () => Promise + removeAttachment: (index: number) => void +} + +export function useComposer(t: TFunction): ComposerState { + const [input, setInput] = useState("") + const [attachments, setAttachments] = useState([]) + const [composerHeight, setComposerHeight] = useState(null) + const clearedRef = useRef(false) + const fieldRef = useRef(null) + const inputRef = useRef(input) + inputRef.current = input + + const clearComposer = useCallback(() => { + clearedRef.current = true + setInput("") + setComposerHeight(null) + fieldRef.current?.setNativeProps({ selection: { start: 0, end: 0 } }) + }, []) + + const handleChangeText = useCallback((text: string) => { + clearedRef.current = text.length === 0 + setInput(text) + }, []) + + const pickFromLibrary = useCallback(async () => { + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ["images"], + allowsMultipleSelection: true, + selectionLimit: 10, + quality: 1, + }) + if (result.canceled) return + const settled = await Promise.allSettled(result.assets.map((a) => toJpeg(a.uri, a.width, a.height))) + const items = settled.filter((r) => r.status === "fulfilled").map((r) => r.value) + if (items.length) setAttachments((prev) => [...prev, ...items]) + if (settled.some((r) => r.status === "rejected")) { + console.error( + "Failed to process image(s):", + settled.filter((r) => r.status === "rejected").map((r) => r.reason), + ) + Alert.alert(t("session.alerts.imageFailedTitle"), t("session.alerts.imageFailedMessage")) + } + }, [t]) + + const pickFromCamera = useCallback(async () => { + const perm = await ImagePicker.requestCameraPermissionsAsync() + if (!perm.granted) { + Alert.alert(t("session.alerts.cameraPermissionTitle"), t("session.alerts.cameraPermissionMessage")) + return + } + const result = await ImagePicker.launchCameraAsync({ quality: 1 }) + if (result.canceled) return + const a = result.assets[0] + try { + const item = await toJpeg(a.uri, a.width, a.height) + setAttachments((prev) => [...prev, item]) + } catch (err) { + console.error("Failed to process photo:", err) + Alert.alert(t("session.alerts.imageFailedTitle"), t("session.alerts.imageFailedMessage")) + } + }, [t]) + + const pasteFromClipboard = useCallback(async () => { + const hasImage = await Clipboard.hasImageAsync() + if (hasImage) { + const img = await Clipboard.getImageAsync({ format: "png" }) + if (img?.data) { + const uri = img.data.startsWith("data:") ? img.data : `data:image/png;base64,${img.data}` + const item = await toJpeg(uri, img.size.width, img.size.height) + setAttachments((prev) => [...prev, item]) + return + } + } + const hasText = await Clipboard.hasStringAsync() + if (hasText) { + const text = await Clipboard.getStringAsync() + if (text) { + if (inputRef.current.length + text.length > MAX_COMPOSER_LENGTH) { + Alert.alert(t("session.alerts.pasteTruncatedTitle"), t("session.alerts.pasteTruncatedMessage")) + } + setInput((prev) => prev + text) + return + } + } + Alert.alert(t("session.alerts.emptyClipboardTitle"), t("session.alerts.emptyClipboardMessage")) + }, [t]) + + const removeAttachment = useCallback((index: number) => { + setAttachments((prev) => prev.filter((_, i) => i !== index)) + }, []) + + const handleSuggestionPress = useCallback( + (promptKey: string) => { + handleChangeText(t(promptKey)) + fieldRef.current?.focus() + }, + [handleChangeText, t], + ) + + return { + input, + setInput, + attachments, + setAttachments, + composerHeight, + setComposerHeight, + clearedRef, + fieldRef, + inputRef, + clearComposer, + handleChangeText, + handleSuggestionPress, + pickFromLibrary, + pickFromCamera, + pasteFromClipboard, + removeAttachment, + } +} diff --git a/apps/mobile/src/lib/outbox-flush.ts b/apps/mobile/src/lib/outbox-flush.ts new file mode 100644 index 0000000..a452774 --- /dev/null +++ b/apps/mobile/src/lib/outbox-flush.ts @@ -0,0 +1,60 @@ +import { useRef, useEffect, useCallback } from "react" +import { Alert } from "react-native" +import type { TFunction } from "i18next" +import type { QueuedDraft } from "@/stores/sessions" +import { useSessions } from "@/stores/sessions" + +export interface OutboxFlushParams { + currentSession: { id: string } | null + isSending: boolean + queuedForSession: QueuedDraft[] + sendMessage: (text: string, model?: any, agent?: any, files?: any, variant?: any) => Promise + model: any + agent: string + variant: any + t: TFunction +} + +export function useOutboxFlush(params: OutboxFlushParams) { + const { currentSession, isSending, queuedForSession, sendMessage, model, agent, variant, t } = params + const wasBusyRef = useRef(false) + const settledHeadRef = useRef(null) + + useEffect(() => { + if (!currentSession) return + if (isSending) { + wasBusyRef.current = true + return + } + if (queuedForSession.length === 0) { + wasBusyRef.current = false + settledHeadRef.current = null + return + } + const head = queuedForSession[0] + const shouldFlush = wasBusyRef.current || head.id !== settledHeadRef.current + wasBusyRef.current = false + if (!shouldFlush) return + settledHeadRef.current = head.id + const next = head + // takeNextQueued is handled by caller? We replicate: remove head from queue via store. + // To keep store in sync, call takeNextQueued through sessions store. + const drafted = useSessions.getState().takeNextQueued(currentSession.id) + const toSend = drafted ?? next + const sessionID = currentSession.id + sendMessage(toSend.text, toSend.model ?? model ?? undefined, toSend.agent ?? agent ?? undefined, toSend.files, toSend.variant ?? variant ?? undefined).catch((err) => { + console.error("Queued send failed:", err) + useSessions.setState((state: any) => ({ + queue: { ...state.queue, [sessionID]: [toSend, ...(state.queue[sessionID] ?? [])] }, + })) + Alert.alert(t("session.alerts.sendFailedTitle"), t("session.alerts.sendFailedMessage")) + }) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isSending, currentSession?.id, queuedForSession, t]) + + const resetSettled = useCallback(() => { + settledHeadRef.current = null + }, []) + + return { wasBusyRef, settledHeadRef, resetSettled } +} diff --git a/apps/mobile/src/lib/reconnect-flash.ts b/apps/mobile/src/lib/reconnect-flash.ts new file mode 100644 index 0000000..e2b016a --- /dev/null +++ b/apps/mobile/src/lib/reconnect-flash.ts @@ -0,0 +1,14 @@ +import { useRef, useEffect } from "react" + +export function useReconnectFlash(reconnectAttempts: number, setShowConnectedFlash: (v: boolean) => void) { + const prevReconnecting = useRef(false) + useEffect(() => { + const isReconnecting = reconnectAttempts > 0 + if (prevReconnecting.current && !isReconnecting) { + setShowConnectedFlash(true) + const t = setTimeout(() => setShowConnectedFlash(false), 2000) + return () => clearTimeout(t) + } + prevReconnecting.current = isReconnecting + }, [reconnectAttempts, setShowConnectedFlash]) +} diff --git a/apps/mobile/src/lib/revert-flow.ts b/apps/mobile/src/lib/revert-flow.ts new file mode 100644 index 0000000..eb7298a --- /dev/null +++ b/apps/mobile/src/lib/revert-flow.ts @@ -0,0 +1,72 @@ +import { useCallback } from "react" +import { Alert } from "react-native" +import type { TFunction } from "i18next" +import type { RevertResult } from "@/queries/session-ops" + +export interface RevertFlowDeps { + t: TFunction + revertMutation: { mutateAsync: (id: string) => Promise } + setInput: (v: string) => void + setAttachments: (v: any) => void + clearComposer: () => void + inputRef: { current: string } +} + +export function useRevertFlow(deps: RevertFlowDeps) { + const { t, revertMutation, setInput, setAttachments, clearComposer, inputRef } = deps + + const applyRevertResult = useCallback( + (result: RevertResult) => { + if (!result.ok) { + if (result.reason === "unsupported") { + Alert.alert(t("session.alerts.notSupportedTitle"), t("session.alerts.notSupportedMessage")) + } else if (result.reason === "auth") { + Alert.alert(t("session.alerts.revertAuthFailedTitle"), t("session.alerts.revertAuthFailedMessage")) + } else { + Alert.alert(t("session.alerts.editFailedTitle"), t("session.alerts.editFailedMessage")) + } + return + } + setInput(result.text) + setAttachments( + result.files + .filter((f): f is typeof f & { url: string; mime: string } => !!f.url && !!f.mime) + .map((f) => ({ uri: f.url, mime: f.mime, filename: f.filename })), + ) + }, + [t, setInput, setAttachments], + ) + + const handleMessageLongPress = useCallback( + (messageID: string) => { + Alert.alert(t("session.alerts.messageActionsTitle"), undefined, [ + { text: t("common.cancel"), style: "cancel" }, + { + text: t("session.actions.editMessage"), + onPress: () => { + const doRevert = async () => { + const result = await revertMutation.mutateAsync(messageID) + applyRevertResult(result) + } + if (inputRef.current.trim()) { + Alert.alert( + t("session.alerts.replaceDraftTitle"), + t("session.alerts.replaceDraftMessage"), + [ + { text: t("common.cancel"), style: "cancel" }, + { text: t("session.actions.replace"), style: "destructive", onPress: doRevert }, + ], + { cancelable: false }, + ) + return + } + doRevert() + }, + }, + ]) + }, + [applyRevertResult, revertMutation, t, inputRef], + ) + + return { applyRevertResult, handleMessageLongPress } +} diff --git a/apps/mobile/src/lib/session-alerts.ts b/apps/mobile/src/lib/session-alerts.ts new file mode 100644 index 0000000..87b2ce2 --- /dev/null +++ b/apps/mobile/src/lib/session-alerts.ts @@ -0,0 +1,16 @@ +import { useEffect } from "react" +import { Alert } from "react-native" +import type { TFunction } from "i18next" + +export function useSessionAlerts(speechError: string | null, sessionError: string | null, clearSessionError: () => void, t: TFunction) { + useEffect(() => { + if (!speechError) return + Alert.alert(t("session.alerts.speechErrorTitle"), `${t("session.alerts.speechErrorMessage")}\n\n${speechError}`) + }, [speechError, t]) + + useEffect(() => { + if (!sessionError) return + Alert.alert(t("common.error"), sessionError) + clearSessionError() + }, [sessionError, clearSessionError, t]) +} diff --git a/apps/mobile/src/lib/session-binding.ts b/apps/mobile/src/lib/session-binding.ts new file mode 100644 index 0000000..c061083 --- /dev/null +++ b/apps/mobile/src/lib/session-binding.ts @@ -0,0 +1,23 @@ +import { useFocusEffect } from "expo-router" +import { useCallback } from "react" +import { useConnections } from "@/stores/connections" +import { useSessions } from "@/stores/sessions" +import { refreshPending } from "@/stores/events" + +export function useSessionBinding(id: string | undefined, directory: string | undefined, connectionId: string | undefined) { + useFocusEffect( + useCallback(() => { + if (!id) return + const { selectSession } = useSessions.getState() + selectSession(id, directory, connectionId).then(() => { + const connState = useConnections.getState() + const c = directory + ? (connState.clientForDirectory(directory, connectionId) ?? connState.client) + : connectionId + ? (connState.clientForConnection(connectionId) ?? connState.client) + : connState.client + if (c) refreshPending(c, id) + }) + }, [id, directory, connectionId]), + ) +} diff --git a/apps/mobile/src/lib/slash-state.ts b/apps/mobile/src/lib/slash-state.ts new file mode 100644 index 0000000..cd8e598 --- /dev/null +++ b/apps/mobile/src/lib/slash-state.ts @@ -0,0 +1,59 @@ +import { useState, useMemo, useCallback } from "react" +import { useRouter } from "expo-router" +import type { SlashCommand } from "@web2bizz/ui-native" + +export interface ServerCommand { + name: string + description?: string +} + +export function useSlashState( + input: string, + serverCommands: ServerCommand[], + clearComposer: () => void, + openAiSheet: () => void, + setInput: (v: string) => void, +) { + const router = useRouter() + const [slashHidden, setSlashHidden] = useState(false) + + const slashActive = input.startsWith("/") && !input.includes(" ") && !slashHidden + const slashQuery = slashActive ? input.slice(1) : "" + + const allCommands = useMemo(() => { + const custom: SlashCommand[] = serverCommands.map((cmd) => ({ + trigger: cmd.name, + title: cmd.name, + description: cmd.description ?? "", + icon: "code-slash-outline", + type: "custom", + })) + const builtin: SlashCommand[] = [ + { trigger: "new", title: "New Session", description: "Start a new session", icon: "add-circle-outline", type: "builtin" }, + { trigger: "model", title: "Switch Model", description: "Choose a different model", icon: "hardware-chip-outline", type: "builtin" }, + { trigger: "agent", title: "Switch Agent", description: "Cycle to next agent", icon: "person-outline", type: "builtin" }, + ] + return [...custom, ...builtin] + }, [serverCommands]) + + const handleSlashSelect = useCallback( + (cmd: SlashCommand) => { + if (cmd.type === "builtin") { + switch (cmd.trigger) { + case "new": + router.back() + return + case "model": + case "agent": + clearComposer() + openAiSheet() + return + } + } + setInput(`/${cmd.trigger} `) + }, + [clearComposer, openAiSheet, router, setInput], + ) + + return { slashHidden, setSlashHidden, slashActive, slashQuery, allCommands, handleSlashSelect } +} diff --git a/apps/mobile/src/lib/use-ai-sheet.ts b/apps/mobile/src/lib/use-ai-sheet.ts new file mode 100644 index 0000000..3f0a56b --- /dev/null +++ b/apps/mobile/src/lib/use-ai-sheet.ts @@ -0,0 +1,68 @@ +import { useCallback, useEffect, useRef } from "react" +import { Keyboard, Platform, type TextInput } from "react-native" +import type BottomSheet from "@gorhom/bottom-sheet" + +// AI sheet must open AFTER the keyboard is gone: expanding while the +// composer holds focus leaves only the backdrop visible (the sheet never +// measures against the keyboard-resized layout). Blur + dismiss first, +// then expand once keyboardDidHide lands — with a fallback timer (~150ms +// Android / ~100ms iOS) and a next-tick fast path when the keyboard is +// already hidden. Pending flag guards double-tap; timer/listener are +// cleaned on unmount. Keeps the parent-owned sheetRef contract untouched. +export function useAiSheet( + aiSheetRef: React.RefObject, + fieldRef: React.RefObject, + keyboardY: number | null, +): () => void { + const aiSheetPendingRef = useRef(false) + const aiSheetTimerRef = useRef | null>(null) + const aiSheetKbSubRef = useRef<{ remove: () => void } | null>(null) + + useEffect( + () => () => { + if (aiSheetTimerRef.current) clearTimeout(aiSheetTimerRef.current) + aiSheetTimerRef.current = null + aiSheetKbSubRef.current?.remove() + aiSheetKbSubRef.current = null + aiSheetPendingRef.current = false + }, + [], + ) + + const openAiSheet = useCallback(() => { + if (aiSheetPendingRef.current) return + aiSheetPendingRef.current = true + fieldRef.current?.blur() + Keyboard.dismiss() + let settled = false + const finish = () => { + if (settled) return + settled = true + if (aiSheetTimerRef.current) { + clearTimeout(aiSheetTimerRef.current) + aiSheetTimerRef.current = null + } + aiSheetKbSubRef.current?.remove() + aiSheetKbSubRef.current = null + aiSheetPendingRef.current = false + aiSheetRef.current?.expand() + } + const keyboardVisible = + typeof Keyboard.isVisible === "function" ? Keyboard.isVisible() : keyboardY !== null + if (!keyboardVisible) { + // Keyboard already hidden — expand on the next tick so blur/dismiss + // commits before measuring. + if (typeof requestAnimationFrame === "function") { + requestAnimationFrame(finish) + } else { + aiSheetTimerRef.current = setTimeout(finish, 0) + } + return + } + const sub = Keyboard.addListener("keyboardDidHide", finish) + aiSheetKbSubRef.current = sub + aiSheetTimerRef.current = setTimeout(finish, Platform.OS === "android" ? 150 : 100) + }, [keyboardY]) + + return openAiSheet +} diff --git a/apps/mobile/src/lib/use-keyboard-dock.ts b/apps/mobile/src/lib/use-keyboard-dock.ts new file mode 100644 index 0000000..43e4a75 --- /dev/null +++ b/apps/mobile/src/lib/use-keyboard-dock.ts @@ -0,0 +1,61 @@ +import { useEffect, useState } from "react" +import { Keyboard, Platform, useWindowDimensions } from "react-native" +import { useSafeAreaInsets } from "react-native-safe-area-context" +import { composerMaxHeight, COMPOSER_MIN_HEIGHT } from "@web2bizz/ui-native" + +export interface KeyboardDock { + keyboardY: number | null + keyboardH: number + dockHeight: number + setDockHeight: (height: number) => void + inputMaxHeight: number + composerFieldHeight: number +} + +// Клавиатура + геометрия дока: keyboardH вручную поднимает absolute-док +// (KeyboardAvoidingView своим padding двигает только in-flow контент, +// абсолютно спозиционированный док его игнорирует), dockHeight уходит в +// нижний отступ списка сообщений, чтобы не проваливались под overlay. +export function useKeyboardDock(composerHeight: number | null): KeyboardDock { + const [keyboardY, setKeyboardY] = useState(null) + // Высота клавиатуры — нижний док (overlay) поднимается над ней вручную: + // KeyboardAvoidingView своим padding двигает только in-flow контент, + // абсолютно спозиционированный док его игнорирует. + const [keyboardH, setKeyboardH] = useState(0) + // Замеренная высота нижнего дока (квик-действия + ввод + аттачменты; + // промпты — absolute-оверлей и в замер не входят): + // уходит в нижний отступ списка сообщений, чтобы не проваливались под overlay. + const [dockHeight, setDockHeight] = useState(0) + + const insets = useSafeAreaInsets() + const { height: windowHeight, fontScale } = useWindowDimensions() + + useEffect(() => { + const show = Keyboard.addListener(Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow", (event) => { + setKeyboardY(event.endCoordinates.screenY) + setKeyboardH(event.endCoordinates.height ?? 0) + }) + const hide = Keyboard.addListener(Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide", () => { + setKeyboardY(null) + setKeyboardH(0) + }) + return () => { + show.remove() + hide.remove() + } + }, []) + + const inputMaxHeight = composerMaxHeight(Platform.OS, windowHeight, keyboardY, insets.top, fontScale) + // Controlled field height: grow with content, snap back to the floor on reset. + // The floor is COMPOSER_MIN_HEIGHT (88 = one text line + the input's vertical + // padding), NOT 80: a lower floor clips the first line inside the fixed box + // (paddingTop 12 + line ~24 + paddingBottom 52 for the overlay buttons), and + // the field only looked right again once a newline grew the measurement past + // the deficit. Must mirror s.input.minHeight. + const composerFieldHeight = Math.max( + COMPOSER_MIN_HEIGHT, + Math.min(composerHeight ?? COMPOSER_MIN_HEIGHT, inputMaxHeight), + ) + + return { keyboardY, keyboardH, dockHeight, setDockHeight, inputMaxHeight, composerFieldHeight } +} diff --git a/apps/mobile/src/lib/use-session-prompts.ts b/apps/mobile/src/lib/use-session-prompts.ts new file mode 100644 index 0000000..5960457 --- /dev/null +++ b/apps/mobile/src/lib/use-session-prompts.ts @@ -0,0 +1,68 @@ +import { Alert } from "react-native" +import type { TFunction } from "i18next" +import type { Client } from "./sdk" + +export interface SessionPromptDeps { + sessionClient: Client | null + sessionID: string | undefined + permissionMutation: { + mutateAsync: (vars: { + client: Client + sessionID: string + requestID: string + reply: "once" | "always" | "reject" + }) => Promise + } + questionMutation: { + mutateAsync: (vars: { + client: Client + sessionID: string + requestID: string + answers: string[][] + }) => Promise + } + questionRejectMutation: { + mutateAsync: (vars: { client: Client; sessionID: string; requestID: string }) => Promise + } + t: TFunction +} + +// Ответы на permission/question промпты: optimistic removal + rollback живут +// внутри мутаций, здесь только вызов + alert при ошибке. Поведение 1:1. +export function useSessionPrompts(deps: SessionPromptDeps) { + const { sessionClient, sessionID, permissionMutation, questionMutation, questionRejectMutation, t } = deps + + const handlePermissionReply = async (requestID: string, reply: "once" | "always" | "reject") => { + if (!sessionClient || !sessionID) return + // Optimistic removal + rollback live inside the mutation; a rejection + // here only surfaces the retry alert. + try { + await permissionMutation.mutateAsync({ client: sessionClient, sessionID, requestID, reply }) + } catch (err) { + console.error("Permission reply failed:", err) + Alert.alert(t("session.alerts.replyFailedTitle"), t("session.alerts.replyFailedMessage")) + } + } + + const handleQuestionReply = async (requestID: string, answers: string[][]) => { + if (!sessionClient || !sessionID) return + try { + await questionMutation.mutateAsync({ client: sessionClient, sessionID, requestID, answers }) + } catch (err) { + console.error("Question reply failed:", err) + Alert.alert(t("session.alerts.replyFailedTitle"), t("session.alerts.replyFailedMessage")) + } + } + + const handleQuestionReject = async (requestID: string) => { + if (!sessionClient || !sessionID) return + try { + await questionRejectMutation.mutateAsync({ client: sessionClient, sessionID, requestID }) + } catch (err) { + console.error("Question reject failed:", err) + Alert.alert(t("session.alerts.rejectFailedTitle"), t("session.alerts.rejectFailedMessage")) + } + } + + return { handlePermissionReply, handleQuestionReply, handleQuestionReject } +} diff --git a/apps/mobile/src/lib/use-session-screen.ts b/apps/mobile/src/lib/use-session-screen.ts new file mode 100644 index 0000000..47ea3e5 --- /dev/null +++ b/apps/mobile/src/lib/use-session-screen.ts @@ -0,0 +1,569 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react" +import { Keyboard, type FlatList } from "react-native" +import type BottomSheet from "@gorhom/bottom-sheet" +import type { TFunction } from "i18next" +import type { EdgeInsets } from "react-native-safe-area-context" +import { useSessions, type QueuedDraft } from "@/stores/sessions" +import { useAuth } from "@/stores/auth" +import { useEvents, type PermissionRequest, type QuestionRequest } from "@/stores/events" +import { useConnections } from "@/stores/connections" +import { useCatalog } from "@/stores/catalog" +import { useCatalogData } from "@/queries/catalog" +import { useComposer } from "./composer" +import { useRevertFlow } from "./revert-flow" +import { useSessionAlerts } from "./session-alerts" +import { useReconnectFlash } from "./reconnect-flash" +import { useOutboxFlush } from "./outbox-flush" +import { useSlashState } from "./slash-state" +import { useSpeech } from "./speech" +import { useAiSheet } from "./use-ai-sheet" +import { useKeyboardDock } from "./use-keyboard-dock" +import { useSessionSend } from "./use-session-send" +import { useSessionPrompts } from "./use-session-prompts" +import { + useAbortSession, + useRevertSession, + useUnrevertSession, + usePermissionReply, + useQuestionReply, + useQuestionReject, +} from "@/queries/session-ops" +import type { Agent, Client, Message, Part } from "./sdk" +import type { Provider } from "./catalog-parse" +import type { ListedSession } from "./listed-session" +import type { StatusSnapshot } from "@web2bizz/ui-native" +import type { SessionHeaderProps } from "@/components/session/SessionHeader" +import type { SessionBannersProps } from "@/components/session/SessionBanners" +import type { MessageListProps } from "@/components/session/MessageList" +import type { ComposerDockProps } from "@/components/session/ComposerDock" +import type { PromptOverlayProps } from "@/components/session/PromptOverlay" +import type { SessionSheetsProps } from "@/components/session/SessionSheets" + +export interface SessionScreenData { + currentSession: ListedSession | null + messages: Message[] + parts: Record + isLoading: boolean + loadingMore: boolean + hasMore: boolean + sendMessage: ( + text: string, + model?: { providerID: string; modelID: string }, + agent?: string, + files?: Array<{ uri: string; mime: string; filename?: string; base64?: string }>, + variant?: string, + ) => Promise + loadOlderMessages: () => Promise + optimisticSending: boolean + queuedForSession: QueuedDraft[] + enqueueMessage: ( + sessionID: string, + text: string, + opts?: Pick, + ) => QueuedDraft + isSending: boolean + statusForScroll: StatusSnapshot | undefined + statusTextForScroll: string | undefined + sessionClient: Client | null + agents: Agent[] + serverCommands: { name: string; description?: string }[] + providers: Provider[] + agent: string + model: { providerID: string; modelID: string } | null + variant: string | null + setModel: (selection: { providerID: string; modelID: string } | null) => void + setVariant: (variant: string | null) => void + setAgent: (name: string) => void + sessionID: string | undefined + permissions: PermissionRequest[] + questions: QuestionRequest[] + revertMessageID: string | undefined + messageData: { message: Message; parts: Part[] }[] + reconnectAttempts: number + currentModelVariants: Record | undefined + aiSummary: string + showFollowUps: boolean + hasActivePrompt: boolean +} + +// Shared stable empty queue: the per-session selector below must not mint a +// fresh `[]` on every store notification (new reference = re-render and new +// downstream props on every unrelated update, e.g. per streamed token). +const EMPTY_QUEUE: QueuedDraft[] = [] + +// Экранные данные сессии: селекторы sending/queue/status, origin-aware +// sessionClient, catalog reseed + селекции, производные messageData/variants/ +// aiSummary/showFollowUps/hasActivePrompt. Чистые данные без JSX. +export function useSessionScreenData(): SessionScreenData { + const { + currentSession, + messages, + parts, + isLoading, + loadingMore, + hasMore, + sendMessage, + loadOlderMessages, + } = useSessions() + + // Busy = optimistic sending flag OR SSE-reported status. The optimistic + // flag alone is not enough: it only bridges the gap between tap and SSE + // busy, and a re-entry (useFocusEffect → selectSession) used to clear it — + // so after leaving and returning to a running chat the Stop button + // disappeared even though the server was still busy. SSE status persists + // globally across navigation, so it keeps the button visible. + const optimisticSending = useSessions((s) => !!(currentSession && s.sending[currentSession.id])) + const queuedForSession = useSessions((s) => + currentSession ? (s.queue[currentSession.id] ?? EMPTY_QUEUE) : EMPTY_QUEUE, + ) + const enqueueMessage = useSessions((s) => s.enqueueMessage) + const sseBusy = useEvents( + (s) => !!currentSession && !!s.sessionStatus[currentSession.id] && s.sessionStatus[currentSession.id].type !== "idle", + ) + const isSending = optimisticSending || sseBusy + + const { client, clientForDirectory } = useConnections() + + // Origin-aware client: the open session's own server (cloud or LAN), never + // just the active connection. + const sessionClient = useMemo( + () => + currentSession?.directory + ? (clientForDirectory(currentSession.directory, currentSession.connectionId) ?? client) + : currentSession + ? (clientForDirectory(undefined, currentSession.connectionId) ?? client) + : client, + [currentSession?.directory, currentSession?.connectionId, clientForDirectory, client], + ) + + // Catalog lists from the React Query cache, scoped to the open session's + // server; the agent/model/variant SELECTIONS stay local (Zustand) and are + // seeded from each fresh snapshot. + const { data: catalogData } = useCatalogData(currentSession?.connectionId) + useEffect(() => { + // Skip empty snapshots (e.g. a server that answered 401): reseeding from + // nothing would wipe a still-valid selection. + if (catalogData && (catalogData.agents.length > 0 || catalogData.providers.length > 0)) { + useCatalog.getState().reseed(catalogData) + } + }, [catalogData]) + const agents = catalogData?.agents ?? [] + const serverCommands = catalogData?.commands ?? [] + const providers = catalogData?.providers ?? [] + const agent = useCatalog((s) => s.agent) || "" + const model = useCatalog((s) => s.model) + const setModel = useCatalog((s) => s.setModel) + const variant = useCatalog((s) => s.variant) + const setVariant = useCatalog((s) => s.setVariant) + const setAgentInStore = useCatalog((s) => s.setAgent) + const setAgent = useCallback((name: string) => setAgentInStore(name, agents), [setAgentInStore, agents]) + + // Permission & question state + const sessionID = currentSession?.id + const permissions = useEvents((s) => (sessionID ? s.permissions[sessionID] : undefined)) || [] + const questions = useEvents((s) => (sessionID ? s.questions[sessionID] : undefined)) || [] + + // SSE reconnect banner + const reconnectAttempts = useEvents((s) => s.reconnectAttempts) + + // Auto-scroll when status appears at bottom of messages (fixed in list) + const statusForScroll = useEvents((s) => (currentSession ? s.sessionStatus[currentSession.id] : undefined)) + const statusTextForScroll = useEvents((s) => (currentSession ? s.statusText[currentSession.id] : undefined)) + + // While a revert is pending, the reverted message and everything after it + // still exist server-side (cleanup only runs on the next prompt/unrevert) + // — hide them client-side so editing feels immediate. Message IDs are + // lexicographically sortable, same comparison the TUI uses. Optimistic + // "temp-" IDs (assigned client-side before the server responds, see + // sendMessage) aren't part of that sort order — always keep them so a + // message sent concurrently with a revert isn't hidden. + const revertMessageID = currentSession?.revert?.messageID + + // Inverted FlatList: data is reversed (newest first) so newest renders at bottom + const messageData = useMemo( + () => + (messages || []) + .filter((msg) => !revertMessageID || msg.id.startsWith("temp-") || msg.id < revertMessageID) + .map((msg) => ({ + message: msg, + parts: (parts && parts[msg.id]) || [], + })) + .reverse(), + [messages, parts, revertMessageID], + ) + + // Sync model chip from latest assistant message + useEffect(() => { + if (!messages || messages.length === 0) return + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i] + if (msg.role === "assistant" && msg.providerID && msg.modelID) { + setModel({ providerID: msg.providerID, modelID: msg.modelID }) + return + } + if (msg.role === "user" && msg.model) { + setModel(msg.model) + return + } + } + }, [currentSession?.id, messages?.length]) + + // Summary label for the single AI settings button ("agent • model") + const aiSummary = `${agent || "build"} • ${model?.modelID ? model.modelID.split("/").pop() || model.modelID : "default"}` + + // Follow-up quick actions: same items/style as the empty-chat suggestions, + // but as a 45px horizontal strip above the composer. Visible when the chat + // is non-empty and the agent is idle — i.e. right after it finishes working + // (isSending flips back to false) — hidden while it is busy or loading. + const showFollowUps = !isLoading && !isSending && messageData.length > 0 + + // Active permission/question prompts cover the composer via the dock + // overlay (see PromptOverlay) instead of unmounting it: the input, + // quick actions and drafts stay mounted underneath and come back + // automatically once the prompt is answered/dismissed. + const hasActivePrompt = permissions.length > 0 || questions.length > 0 + + // Variants for current model (for reasoning effort picker) + const currentModelVariants = useMemo(() => { + if (!model) return undefined + const provider = providers.find((p) => p.id === model.providerID) + const found = provider?.models.find((m) => m.id === model.modelID) + return found?.variants + }, [model, providers]) + + return { + currentSession, + messages, + parts, + isLoading, + loadingMore, + hasMore, + sendMessage, + loadOlderMessages, + optimisticSending, + queuedForSession, + enqueueMessage, + isSending, + statusForScroll, + statusTextForScroll, + sessionClient, + agents, + serverCommands, + providers, + agent, + model, + variant, + setModel, + setVariant, + setAgent, + sessionID, + permissions, + questions, + revertMessageID, + messageData, + reconnectAttempts, + currentModelVariants, + aiSummary, + showFollowUps, + hasActivePrompt, + } +} + +// Props SessionInfo (uikit): структурный тип для группы info контроллера. +export interface SessionInfoProps { + session: ListedSession | null + messages: Message[] + providers: Provider[] + visible: boolean + isDark: boolean + hasMore: boolean + loadingAll: boolean + onLoadAll: () => void + onScrollToTop: () => void + onClose: () => void +} + +export interface SessionController { + isLoading: boolean + hasActivePrompt: boolean + header: SessionHeaderProps + info: SessionInfoProps + banners: SessionBannersProps + list: MessageListProps + dock: Omit + prompts: PromptOverlayProps + sheets: SessionSheetsProps +} + +// Контроллер экрана: владеет единичными инстансами (composer, speech, +// мутации, рефы, outbox-бухгалтерия) и собирает готовые группы пропсов для +// виджетов. Роут только раскладывает их по JSX. +export function useSessionController(t: TFunction, isDark: boolean, insets: EdgeInsets): SessionController { + const flatListRef = useRef(null) + const aiSheetRef = useRef(null) + const queueSheetRef = useRef(null) + // Composer state (input/attachments/height/clear) extracted to a hook. + const composer = useComposer(t) + const { input, setInput, attachments, setAttachments, composerHeight, setComposerHeight, clearedRef, fieldRef, inputRef, clearComposer } = composer + const [showInfo, setShowInfo] = useState(false) + const toggleInfo = useCallback(() => setShowInfo((v) => !v), []) + const [showConnectedFlash, setShowConnectedFlash] = useState(false) + + // Экранные данные: sending/queue/status, sessionClient, catalog, messageData. + const screen = useSessionScreenData() + const { keyboardY, keyboardH, dockHeight, setDockHeight, composerFieldHeight } = useKeyboardDock(composerHeight) + + // Discrete server ops as React Query mutations (optimistic UI + rollback + // inside, alerts stay at the call sites). + const abortMutation = useAbortSession() + const revertMutation = useRevertSession() + const unrevertMutation = useUnrevertSession() + const permissionMutation = usePermissionReply() + const questionMutation = useQuestionReply() + const questionRejectMutation = useQuestionReject() + + const { authenticateForMessage } = useAuth() + + // Voice input — transcript appends to the text input on completion + const speech = useSpeech( + useCallback((text: string) => { + setInput((prev) => (prev ? prev + " " + text : text)) + }, []), + ) + + const sessionError = useSessions((s) => s.error) + const clearSessionError = useSessions((s) => s.clearError) + useSessionAlerts(speech.error ?? null, sessionError, clearSessionError, t) + + const openAiSheet = useAiSheet(aiSheetRef, fieldRef, keyboardY) + + // Slash commands (allCommands + handleSlashSelect) — needs openAiSheet. + // Единый источник slash-состояния (вместо бывшего локального slashHidden): + // handleChangeText сбрасывает его, чтобы палитра открывалась заново. + const { slashActive, slashQuery, allCommands, handleSlashSelect, setSlashHidden } = useSlashState( + input, + screen.serverCommands, + clearComposer, + openAiSheet, + setInput, + ) + const handleChangeText = useCallback( + (text: string) => { + setSlashHidden(false) + composer.handleChangeText(text) + }, + [composer], + ) + const closeSlash = useCallback(() => setSlashHidden(true), [setSlashHidden]) + + // Revert (edit message) flow extracted to a hook. + const { handleMessageLongPress } = useRevertFlow({ + t, + revertMutation, + setInput, + setAttachments, + clearComposer, + inputRef, + }) + + // Outbox sheet: dismiss the keyboard first (same reason as openAiSheet — + // expanding against a keyboard-resized layout leaves only the backdrop). + const openQueueSheet = useCallback(() => { + fieldRef.current?.blur() + Keyboard.dismiss() + requestAnimationFrame(() => queueSheetRef.current?.expand()) + }, []) + + // Outbox auto-flush bookkeeping (see the effect below): refs live next to + // the queue callbacks since handleUpdateQueued resets the parked head. + // wasBusyRef tracks the busy → idle transition — the only moment a flush + // may start. settledHeadRef parks the last attempted head so a failed + // send is NOT retried in a tight setState loop; it waits for the next + // busy → idle cycle, a new head, or an explicit edit. + // Outbox flush state lives in useOutboxFlush (called below); this ref + // lets handleUpdateQueued reset the parked head before the hook is wired. + const resetSettledRef = useRef<() => void>(() => {}) + + // Stable sheet props: fresh arrays/closures every render would re-render + // the BottomSheetFlatList on each unrelated update (per streamed token). + const queueItems = useMemo( + () => screen.queuedForSession.map((d) => ({ id: d.id, text: d.text || t("session.queue.attachmentFallback") })), + [screen.queuedForSession, t], + ) + const handleRemoveQueued = useCallback((queueId: string) => { + const id = useSessions.getState().currentSession?.id + if (id) useSessions.getState().removeQueuedMessage(id, queueId) + }, []) + const handleUpdateQueued = useCallback((queueId: string, text: string) => { + const id = useSessions.getState().currentSession?.id + if (id) { + useSessions.getState().updateQueuedMessage(id, queueId, text) + // The head may have changed content while idle after a failed flush + // (which parks that head) — allow the fixed text to flush. + resetSettledRef.current() + } + }, []) + + // Outbox auto-flush extracted to a hook. + const outbox = useOutboxFlush({ + currentSession: screen.currentSession, + isSending: screen.isSending, + queuedForSession: screen.queuedForSession, + sendMessage: screen.sendMessage, + model: screen.model, + agent: screen.agent, + variant: screen.variant, + t, + }) + resetSettledRef.current = outbox.resetSettled + + const { handlePermissionReply, handleQuestionReply, handleQuestionReject } = useSessionPrompts({ + sessionClient: screen.sessionClient, + sessionID: screen.sessionID, + permissionMutation, + questionMutation, + questionRejectMutation, + t, + }) + + const handleSend = useSessionSend({ + input, + attachments, + setAttachments, + clearComposer, + setInput, + serverCommands: screen.serverCommands, + sessionClient: screen.sessionClient, + currentSession: screen.currentSession, + agent: screen.agent, + model: screen.model, + variant: screen.variant, + isSending: screen.isSending, + enqueueMessage: screen.enqueueMessage, + sendMessage: screen.sendMessage, + authenticateForMessage, + t, + }) + + useReconnectFlash(screen.reconnectAttempts, setShowConnectedFlash) + + const screenTitle = screen.currentSession?.title || t("session.titleFallback") + + return { + isLoading: screen.isLoading, + hasActivePrompt: screen.hasActivePrompt, + header: { title: screenTitle, showInfo, isDark, onToggleInfo: toggleInfo }, + info: { + session: screen.currentSession, + messages: screen.messages || [], + providers: screen.providers, + visible: showInfo, + isDark, + hasMore: screen.hasMore, + loadingAll: screen.loadingMore, + onLoadAll: () => { + if (screen.hasMore && !screen.loadingMore) screen.loadOlderMessages() + }, + onScrollToTop: () => { + flatListRef.current?.scrollToEnd({ animated: true }) + }, + onClose: () => setShowInfo(false), + }, + banners: { + reconnectAttempts: screen.reconnectAttempts, + showConnectedFlash, + revertMessageID: screen.revertMessageID, + onUndoRevert: () => { + // Clear the composer only after the server confirms the + // unrevert — on failure the prefilled draft must survive. + unrevertMutation.mutate(undefined, { + onSuccess: () => { + // The composer was prefilled with the reverted message's text/ + // attachments (see applyRevertResult) — clear it so Undo doesn't + // leave a stale draft that could be sent as a duplicate. + setAttachments([]) + clearComposer() + }, + }) + }, + t, + }, + list: { + messageData: screen.messageData, + status: screen.statusForScroll, + statusText: screen.statusTextForScroll, + optimisticSending: screen.optimisticSending, + isDark, + hasMore: screen.hasMore, + loadingMore: screen.loadingMore, + dockHeight, + slashActive, + showStatus: !!screen.currentSession, + listRef: flatListRef, + onLongPress: handleMessageLongPress, + onSuggestion: composer.handleSuggestionPress, + onCloseSlash: closeSlash, + onLoadMore: screen.loadOlderMessages, + }, + dock: { + isDark, + keyboardH, + bottomInset: insets.bottom, + onDockLayout: setDockHeight, + attachments, + onRemoveAttachment: composer.removeAttachment, + queueCount: screen.queuedForSession.length, + onOpenQueue: openQueueSheet, + showFollowUps: screen.showFollowUps, + onSuggestion: composer.handleSuggestionPress, + slashActive, + slashQuery, + slashCommands: allCommands, + onSlashSelect: handleSlashSelect, + composerFieldHeight, + fieldRef, + input, + onChangeText: handleChangeText, + clearedRef, + inputRef, + onMeasureHeight: setComposerHeight, + speechListening: speech.listening, + speechTranscript: speech.transcript, + onMicStart: speech.start, + onMicStop: speech.stop, + isSending: screen.isSending, + onPickLibrary: composer.pickFromLibrary, + onPickCamera: composer.pickFromCamera, + onOpenAiSheet: openAiSheet, + aiSummary: screen.aiSummary, + onAbort: () => abortMutation.mutate(), + onSend: handleSend, + t, + }, + prompts: { + permissions: screen.permissions, + questions: screen.questions, + isDark, + onPermissionReply: handlePermissionReply, + onQuestionReply: handleQuestionReply, + onQuestionReject: handleQuestionReject, + }, + sheets: { + aiSheetRef, + queueSheetRef, + agents: screen.agents, + selectedAgent: screen.agent, + providers: screen.providers, + selectedModel: screen.model, + variants: screen.currentModelVariants, + selectedVariant: screen.variant, + isDark, + onSelectAgent: screen.setAgent, + onSelectModel: (providerID, modelID) => screen.setModel({ providerID, modelID }), + onSelectVariant: screen.setVariant, + queueItems, + onRemoveQueued: handleRemoveQueued, + onUpdateQueued: handleUpdateQueued, + }, + } +} diff --git a/apps/mobile/src/lib/use-session-send.ts b/apps/mobile/src/lib/use-session-send.ts new file mode 100644 index 0000000..10afd09 --- /dev/null +++ b/apps/mobile/src/lib/use-session-send.ts @@ -0,0 +1,131 @@ +import { Alert } from "react-native" +import type { TFunction } from "i18next" +import type { Attachment } from "@web2bizz/ui-native" +import type { Client } from "./sdk" +import type { ListedSession } from "./listed-session" +import type { ServerCommand } from "./slash-state" +import type { QueuedDraft } from "@/stores/sessions" + +export interface SessionSendParams { + input: string + attachments: Attachment[] + setAttachments: (v: Attachment[] | ((prev: Attachment[]) => Attachment[])) => void + clearComposer: () => void + setInput: (v: string | ((prev: string) => string)) => void + serverCommands: ServerCommand[] + sessionClient: Client | null + currentSession: ListedSession | null + agent: string + model: { providerID: string; modelID: string } | null + variant: string | null + isSending: boolean + enqueueMessage: ( + sessionID: string, + text: string, + opts?: Pick, + ) => QueuedDraft + sendMessage: ( + text: string, + model?: { providerID: string; modelID: string }, + agent?: string, + files?: Array<{ uri: string; mime: string; filename?: string; base64?: string }>, + variant?: string, + ) => Promise + authenticateForMessage: () => Promise + t: TFunction +} + +// Отправка: auth → server slash commands → outbox (пока busy) → send +// с восстановлением драфта при ошибке. Поведение 1:1 с инлайн-версией. +export function useSessionSend(params: SessionSendParams): () => Promise { + const { + input, + attachments, + setAttachments, + clearComposer, + setInput, + serverCommands, + sessionClient, + currentSession, + agent, + model, + variant, + isSending, + enqueueMessage, + sendMessage, + authenticateForMessage, + t, + } = params + + const handleSend = async () => { + if (!input.trim() && attachments.length === 0) return + const authenticated = await authenticateForMessage() + if (!authenticated) { + Alert.alert(t("session.alerts.authRequiredTitle"), t("session.alerts.authRequiredMessage")) + return + } + + const text = input.trim() + const files = [...attachments] + setAttachments([]) + // Reset the controlled geometry together with the text — the native + // measurement doesn't reliably shrink on its own after a clear. + clearComposer() + + // Server slash commands (no attachments for commands) + if (text.startsWith("/") && files.length === 0) { + const [cmdName, ...args] = text.split(" ") + const name = cmdName.slice(1) + const match = serverCommands.find((c) => c.name === name) + if (!match) { + // Not a known server command — keep the text instead of firing it + // as a literal prompt. + setInput(text) + Alert.alert(t("session.alerts.unknownCommandTitle"), t("session.alerts.unknownCommandMessage")) + return + } + if (sessionClient && currentSession) { + try { + await sessionClient.session.command(currentSession.id, { + command: name, + arguments: args.join(" "), + agent, + model: model ? `${model.providerID}/${model.modelID}` : undefined, + }) + } catch (err) { + console.error("Command failed:", err) + setInput(text) + Alert.alert(t("session.alerts.sendFailedTitle"), t("session.alerts.sendFailedMessage")) + } + return + } + } + + // While the agent is busy, follow-ups wait in the client-side outbox + // and flush FIFO when the session goes idle (see the auto-flush effect + // below) — instead of hitting the server concurrently. + if (isSending && currentSession) { + enqueueMessage(currentSession.id, text, { + ...(files.length ? { files } : {}), + ...(model ? { model } : {}), + ...(agent ? { agent } : {}), + ...(variant ? { variant } : {}), + }) + return + } + + // Messages are queued server-side when the session is busy. + // No need to abort - just send and it will be processed after current response. + try { + await sendMessage(text, model || undefined, agent || undefined, files, variant || undefined) + } catch (err) { + console.error("Send failed:", err) + // Restore the user's text and attachments so their input isn't lost. + setInput((prev) => (prev ? prev : text)) + setAttachments((prev) => (prev.length ? prev : files)) + Alert.alert(t("session.alerts.sendFailedTitle"), t("session.alerts.sendFailedMessage")) + } + } + + return handleSend +} diff --git a/apps/mobile/src/queries/catalog.ts b/apps/mobile/src/queries/catalog.ts index eee694c..90fda93 100644 --- a/apps/mobile/src/queries/catalog.ts +++ b/apps/mobile/src/queries/catalog.ts @@ -8,10 +8,10 @@ // seeded from the snapshot via reseed() — selections are client state, // React Query must not own them. import { useQuery } from "@tanstack/react-query" -import { useConnections } from "../stores/connections" -import { queryKeys } from "../lib/query-keys" -import { parseCatalogResponse, type ParsedCatalog, type RawProviderList } from "../lib/catalog-parse" -import type { Agent, Command } from "../lib/sdk" +import { useConnections } from "@/stores/connections" +import { queryKeys } from "@/lib/query-keys" +import { parseCatalogResponse, type ParsedCatalog, type RawProviderList } from "@/lib/catalog-parse" +import type { Agent, Command } from "@/lib/sdk" // Shared fetcher behind both useCatalogData() and the connect-time prefetch // in app/_layout.tsx — reads the current client lazily so it never closes diff --git a/apps/mobile/src/queries/project.ts b/apps/mobile/src/queries/project.ts index 8191188..5d61c3b 100644 --- a/apps/mobile/src/queries/project.ts +++ b/apps/mobile/src/queries/project.ts @@ -6,10 +6,10 @@ // The Zustand connections store no longer mirrors this data: hooks below are // the single source of truth. import { useQuery } from "@tanstack/react-query" -import { useConnections } from "../stores/connections" -import { queryKeys } from "../lib/query-keys" -import { ApiError, type Project } from "../lib/sdk" -import { parseGitConfigRemotes, toRepoLinks, type RepoLink } from "../lib/git-remotes" +import { useConnections } from "@/stores/connections" +import { queryKeys } from "@/lib/query-keys" +import { ApiError, type Project } from "@/lib/sdk" +import { parseGitConfigRemotes, toRepoLinks, type RepoLink } from "@/lib/git-remotes" export interface ProjectInfo { project: Project | null diff --git a/apps/mobile/src/queries/session-ops.ts b/apps/mobile/src/queries/session-ops.ts index 3af9102..d322b50 100644 --- a/apps/mobile/src/queries/session-ops.ts +++ b/apps/mobile/src/queries/session-ops.ts @@ -8,13 +8,13 @@ // HTTP response) and message history merging is subscription state, not a // snapshot. See the sessions store. import { useMutation, useQueryClient } from "@tanstack/react-query" -import { ApiError, type Client } from "../lib/sdk" -import { extractPromptFromParts, type PromptFromParts } from "../lib/prompt-from-parts" -import { useConnections } from "../stores/connections" -import { useEvents, type PermissionRequest, type QuestionRequest } from "../stores/events" -import { abortedSessions, useSessions } from "../stores/sessions" -import { queryKeys } from "../lib/query-keys" -import type { ListedSession } from "../lib/listed-session" +import { ApiError, type Client } from "@/lib/sdk" +import { extractPromptFromParts, type PromptFromParts } from "@/lib/prompt-from-parts" +import { useConnections } from "@/stores/connections" +import { useEvents, type PermissionRequest, type QuestionRequest } from "@/stores/events" +import { abortedSessions, useSessions } from "@/stores/sessions" +import { queryKeys } from "@/lib/query-keys" +import type { ListedSession } from "@/lib/listed-session" export type RevertResult = ({ ok: true } & PromptFromParts) | { ok: false; reason: "unsupported" | "auth" | "error" } diff --git a/apps/mobile/src/queries/sessions.ts b/apps/mobile/src/queries/sessions.ts index e6f6f82..7b0eebb 100644 --- a/apps/mobile/src/queries/sessions.ts +++ b/apps/mobile/src/queries/sessions.ts @@ -10,13 +10,13 @@ // which all read this one cache, can never diverge again. import { useEffect } from "react" import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" -import { useConnections } from "../stores/connections" -import { useEvents } from "../stores/events" -import { useSessions } from "../stores/sessions" -import { queryClient } from "../lib/query-client" -import { queryKeys } from "../lib/query-keys" -import { mergeSessionLists, type ListedSession } from "../lib/listed-session" -import type { Client, Session } from "../lib/sdk" +import { useConnections } from "@/stores/connections" +import { useEvents } from "@/stores/events" +import { useSessions } from "@/stores/sessions" +import { queryClient } from "@/lib/query-client" +import { queryKeys } from "@/lib/query-keys" +import { mergeSessionLists, type ListedSession } from "@/lib/listed-session" +import type { Client, Session } from "@/lib/sdk" async function fetchSessionsList(): Promise { const conn = useConnections.getState() diff --git a/apps/mobile/src/stores/catalog.ts b/apps/mobile/src/stores/catalog.ts index 11e2532..523338b 100644 --- a/apps/mobile/src/stores/catalog.ts +++ b/apps/mobile/src/stores/catalog.ts @@ -1,7 +1,7 @@ import { create } from "zustand" -import type { Agent } from "../lib/sdk" -import { chooseModelSelection } from "../lib/model-selection" -import { type ParsedCatalog, type Provider, type ProviderModel } from "../lib/catalog-parse" +import type { Agent } from "@/lib/sdk" +import { chooseModelSelection } from "@/lib/model-selection" +import { type ParsedCatalog, type Provider, type ProviderModel } from "@/lib/catalog-parse" // Re-exported so existing `import type { Provider } from "../stores/catalog"` // call sites (SessionInfo) keep working. diff --git a/apps/mobile/src/stores/cloned-projects.ts b/apps/mobile/src/stores/cloned-projects.ts index dfadc50..7f9956b 100644 --- a/apps/mobile/src/stores/cloned-projects.ts +++ b/apps/mobile/src/stores/cloned-projects.ts @@ -1,5 +1,5 @@ import { create } from "zustand" -import type { MockRepo } from "../lib/github-mock" +import type { MockRepo } from "@/lib/github-mock" // UI-only stub. Backend will later replace addCloned() with a real // clone call; the shape { id, name, fullName, path } is kept stable diff --git a/apps/mobile/src/stores/connections.ts b/apps/mobile/src/stores/connections.ts index 9dcd328..34c5128 100644 --- a/apps/mobile/src/stores/connections.ts +++ b/apps/mobile/src/stores/connections.ts @@ -1,12 +1,12 @@ import { create } from "zustand" import * as SecureStore from "expo-secure-store" import * as Crypto from "expo-crypto" -import type { ServerConnection, ConnectionType } from "../lib/types" -import { createClient, type Client } from "../lib/sdk" -import { buildAuth } from "../lib/auth" +import type { ServerConnection, ConnectionType } from "@/lib/types" +import { createClient, type Client } from "@/lib/sdk" +import { buildAuth } from "@/lib/auth" import { stripTrailingSlash } from "@web2bizz/ui-native" -import { HARDCODED_SERVER_URL } from "../lib/server-config" -import { invalidateConnectionScopeQueries } from "../lib/query-invalidate" +import { HARDCODED_SERVER_URL } from "@/lib/server-config" +import { invalidateConnectionScopeQueries } from "@/lib/query-invalidate" import { useEvents } from "./events" const CONNECTIONS_KEY = "opencode_connections" diff --git a/apps/mobile/src/stores/events.ts b/apps/mobile/src/stores/events.ts index e0bde15..070204f 100644 --- a/apps/mobile/src/stores/events.ts +++ b/apps/mobile/src/stores/events.ts @@ -1,16 +1,16 @@ import { create } from "zustand" import { useConnections } from "./connections" import { useSessions, abortedSessions } from "./sessions" -import { send as notify } from "../lib/notifications" -import { sanitizeBody } from "../lib/notify-format" -import { statusFromPart } from "../lib/status-labels" -import { recordSuccessfulSession } from "../lib/store-review" -import { isAuthError } from "../lib/api-error" -import { isSessionActuallyIdle } from "../lib/session-status-reconcile" -import { queryClient } from "../lib/query-client" -import { queryKeys } from "../lib/query-keys" -import type { ListedSession } from "../lib/listed-session" -import type { Client, Part, Session, Message } from "../lib/sdk" +import { send as notify } from "@/lib/notifications" +import { sanitizeBody } from "@/lib/notify-format" +import { statusFromPart } from "@/lib/status-labels" +import { recordSuccessfulSession } from "@/lib/store-review" +import { isAuthError } from "@/lib/api-error" +import { isSessionActuallyIdle } from "@/lib/session-status-reconcile" +import { queryClient } from "@/lib/query-client" +import { queryKeys } from "@/lib/query-keys" +import type { ListedSession } from "@/lib/listed-session" +import type { Client, Part, Session, Message } from "@/lib/sdk" // Session status from the server type SessionStatus = { type: "idle" } | { type: "busy" } | { type: "retry"; attempt: number; message: string } diff --git a/apps/mobile/src/stores/sessions.ts b/apps/mobile/src/stores/sessions.ts index 09b9c6b..d114902 100644 --- a/apps/mobile/src/stores/sessions.ts +++ b/apps/mobile/src/stores/sessions.ts @@ -1,9 +1,9 @@ import { create } from "zustand" -import { type Session, type Message, type Part, type Event, type MessageWithParts, type Client } from "../lib/sdk" +import { type Session, type Message, type Part, type Event, type MessageWithParts, type Client } from "@/lib/sdk" import { useConnections } from "./connections" import { useSettings } from "./settings" -import { mergeIncomingMessage } from "../lib/message-merge" -import { applyIncomingParts } from "../lib/part-merge" +import { mergeIncomingMessage } from "@/lib/message-merge" +import { applyIncomingParts } from "@/lib/part-merge" import { createQueuedDraft, dequeueDraft, @@ -11,12 +11,12 @@ import { removeDraft, updateDraftText, type QueuedDraft, -} from "../lib/message-queue" -import { pruneRevertedTail } from "../lib/revert-prune" -import { isColdSessionLoad, isLiveEventForSession } from "../lib/session-load-reconcile" -import { queryClient } from "../lib/query-client" -import { queryKeys } from "../lib/query-keys" -import type { ListedSession } from "../lib/listed-session" +} from "@/lib/message-queue" +import { pruneRevertedTail } from "@/lib/revert-prune" +import { isColdSessionLoad, isLiveEventForSession } from "@/lib/session-load-reconcile" +import { queryClient } from "@/lib/query-client" +import { queryKeys } from "@/lib/query-keys" +import type { ListedSession } from "@/lib/listed-session" // State split with React Query (see src/queries/): // - React Query owns SERVER SNAPSHOTS: the session list, catalogs, project diff --git a/apps/mobile/src/stores/settings.ts b/apps/mobile/src/stores/settings.ts index 1e87e61..f0d8a44 100644 --- a/apps/mobile/src/stores/settings.ts +++ b/apps/mobile/src/stores/settings.ts @@ -1,9 +1,9 @@ import { create } from "zustand" import * as SecureStore from "expo-secure-store" -import { type Category, defaultPreferences } from "../lib/notifications" -import { clampPageSize, mergeStoredSettings } from "../lib/settings-merge" -import { setAppLocale } from "../lib/i18n/config" -import type { LocalePreference } from "../lib/i18n/locale-resolve" +import { type Category, defaultPreferences } from "@/lib/notifications" +import { clampPageSize, mergeStoredSettings } from "@/lib/settings-merge" +import { setAppLocale } from "@/lib/i18n/config" +import type { LocalePreference } from "@/lib/i18n/locale-resolve" const SETTINGS_KEY = "opencode_settings" diff --git a/apps/mobile/tsconfig.json b/apps/mobile/tsconfig.json index f432b60..465f651 100644 --- a/apps/mobile/tsconfig.json +++ b/apps/mobile/tsconfig.json @@ -5,6 +5,7 @@ "types": ["node"], "paths": { "@/*": ["./src/*"], + "@app/*": ["./app/*"], "@web2bizz/ui-native": ["./packages/uikit/src/index.ts"], "@web2bizz/ui-native/*": ["./packages/uikit/src/*"], // TODO: deprecated alias @opencode-ai/uikit — удалить через 1 релиз (rename → @web2bizz/ui-native). From c6121924d30cee461b94b35f9a672683d8782052 Mon Sep 17 00:00:00 2001 From: alwoo Date: Tue, 20 Oct 2026 01:30:24 +0400 Subject: [PATCH 009/315] refactor(mobile): normalize structure to kebab-case and shared layout --- apps/mobile/app/(tabs)/_layout.tsx | 4 +- apps/mobile/app/(tabs)/index.tsx | 12 +- apps/mobile/app/(tabs)/settings.tsx | 10 +- apps/mobile/app/(tabs)/tasks.tsx | 6 +- apps/mobile/app/_layout.tsx | 12 +- apps/mobile/app/connection/add.tsx | 18 +- apps/mobile/app/demo.tsx | 2 +- apps/mobile/app/login.tsx | 4 +- apps/mobile/app/project/[directory].tsx | 4 +- apps/mobile/app/project/remotes.tsx | 2 +- apps/mobile/app/session/[id].tsx | 17 +- apps/mobile/babel.config.js | 4 + apps/mobile/metro.config.js | 4 + .../src/components/chat/StatusIndicator.tsx | 223 ------------------ .../index.tsx} | 16 +- .../components/chat/braille-spinner/index.tsx | 27 +++ .../__tests__}/diff-compute.test.ts | 2 +- .../index.ts} | 2 +- .../{DiffView.tsx => diff-view/index.tsx} | 8 +- .../index.tsx} | 16 +- .../index.tsx} | 8 +- .../src/components/chat/frame-glyph/index.tsx | 25 ++ .../index.tsx} | 6 +- .../uikit/src/components/chat/index.ts | 19 ++ .../index.tsx} | 12 +- .../index.tsx} | 10 +- .../index.tsx} | 4 +- .../index.tsx} | 10 +- .../index.tsx} | 10 +- .../index.tsx} | 4 +- .../chat/{Select.tsx => select/index.tsx} | 6 +- .../index.tsx} | 6 +- .../index.tsx} | 2 +- .../index.tsx} | 6 +- .../chat/status-indicator/index.tsx | 105 +++++++++ .../chat/status-indicator/styles.ts | 45 ++++ .../index.tsx} | 6 +- .../container/index.tsx} | 2 +- .../index.tsx} | 4 +- .../{CodeBlock.tsx => code-block/index.tsx} | 6 +- .../{CopyLink.tsx => copy-link/index.tsx} | 0 .../uikit/src/components/markdown/index.tsx | 6 +- .../{Markdown.tsx => markdown/index.tsx} | 8 +- .../wide-content-scroll.regression.test.ts | 12 +- apps/mobile/packages/uikit/src/index.ts | 44 ++-- apps/mobile/packages/uikit/src/types.ts | 18 +- .../__tests__}/file-roots.test.ts | 2 +- .../{file-roots.ts => file-roots/index.ts} | 2 +- .../{ => fs-mock/__tests__}/fs-mock.test.ts | 2 +- .../utils/{fs-mock.ts => fs-mock/index.ts} | 2 +- .../__tests__}/github-links.test.ts | 2 +- .../index.ts} | 0 apps/mobile/packages/uikit/src/utils/index.ts | 8 + .../__tests__}/lan-discover.test.ts | 2 +- .../index.ts} | 8 +- .../__tests__}/breadcrumbs.test.ts | 2 +- .../__tests__}/path-utils.test.ts | 2 +- .../{path-utils.ts => path-utils/index.ts} | 2 +- .../__tests__}/scroll-config.test.ts | 2 +- .../index.ts} | 2 +- .../__tests__}/session-layout.test.ts | 2 +- .../index.ts} | 0 .../__tests__}/sheet-layout.test.ts | 2 +- .../index.ts} | 0 apps/mobile/src/components/AuthGate.tsx | 2 +- .../mobile/src/components/ConnectionBadge.tsx | 2 +- apps/mobile/src/components/ErrorBoundary.tsx | 10 +- apps/mobile/src/components/RepoLinkRow.tsx | 2 +- apps/mobile/src/components/UpdateBanner.tsx | 2 +- .../src/components/chat/CloneRepoSheet.tsx | 4 +- .../container-layout.regression.test.ts | 2 +- .../index.tsx} | 6 +- .../{EmptyState.tsx => empty-state/index.tsx} | 4 +- apps/mobile/src/components/session/index.ts | 7 + .../index.tsx} | 8 +- .../index.tsx} | 2 +- .../index.tsx} | 2 +- .../index.tsx} | 2 +- .../index.tsx} | 6 +- .../src/{queries => shared/api}/catalog.ts | 6 +- .../src/{queries => shared/api}/project.ts | 8 +- .../{queries => shared/api}/session-ops.ts | 10 +- .../src/{queries => shared/api}/sessions.ts | 8 +- apps/mobile/src/{ => shared}/stores/auth.ts | 4 +- .../mobile/src/{ => shared}/stores/catalog.ts | 10 +- .../{ => shared}/stores/cloned-projects.ts | 6 +- .../src/{ => shared}/stores/connections.ts | 16 +- apps/mobile/src/{ => shared}/stores/events.ts | 26 +- .../src/{ => shared}/stores/sessions.ts | 20 +- .../src/{ => shared}/stores/settings.ts | 12 +- apps/mobile/src/{ => shared}/stores/ui.ts | 2 +- .../utils}/active-tasks.test.ts | 0 .../src/{lib => shared/utils}/active-tasks.ts | 4 +- .../{lib => shared/utils}/api-error.test.ts | 0 .../src/{lib => shared/utils}/api-error.ts | 0 .../{lib => shared/utils}/app-version.test.ts | 6 +- .../src/{lib => shared/utils}/app-version.ts | 2 +- .../src/{lib => shared/utils}/auth.test.ts | 0 apps/mobile/src/{lib => shared/utils}/auth.ts | 2 +- .../utils}/catalog-parse.test.ts | 0 .../{lib => shared/utils}/catalog-parse.ts | 8 +- .../src/{lib => shared/utils}/composer.ts | 2 +- .../{lib => shared/utils}/demo-script.test.ts | 0 .../src/{lib => shared/utils}/demo-script.ts | 4 +- .../utils}/diagnostics-classify.test.ts | 0 .../utils}/diagnostics-classify.ts | 4 +- .../src/{lib => shared/utils}/diagnostics.ts | 2 +- .../{lib => shared/utils}/git-remotes.test.ts | 0 .../src/{lib => shared/utils}/git-remotes.ts | 4 +- .../{lib => shared/utils}/github-mock.test.ts | 0 .../src/{lib => shared/utils}/github-mock.ts | 2 +- .../src/{lib => shared/utils}/headers.test.ts | 0 .../src/{lib => shared/utils}/headers.ts | 2 +- .../utils}/i18n/catalog-parity.test.ts | 0 .../src/{lib => shared/utils}/i18n/config.ts | 0 .../src/{lib => shared/utils}/i18n/en.json | 0 .../utils}/i18n/locale-resolve.test.ts | 0 .../utils}/i18n/locale-resolve.ts | 0 .../src/{lib => shared/utils}/i18n/ru.json | 0 .../src/{lib => shared/utils}/lan-manual.ts | 0 .../utils}/lan-projects.test.ts | 0 .../mobile/src/{lib => shared/utils}/links.ts | 0 .../utils}/listed-session.test.ts | 0 .../{lib => shared/utils}/listed-session.ts | 2 +- .../{lib => shared/utils}/logbuffer.test.ts | 0 .../src/{lib => shared/utils}/logbuffer.ts | 2 +- .../utils}/message-merge.test.ts | 0 .../{lib => shared/utils}/message-merge.ts | 0 .../utils}/message-queue.test.ts | 0 .../{lib => shared/utils}/message-queue.ts | 2 +- .../utils}/model-selection.test.ts | 0 .../{lib => shared/utils}/model-selection.ts | 6 +- .../{lib => shared/utils}/notifications.ts | 4 +- .../utils}/notify-format.test.ts | 0 .../{lib => shared/utils}/notify-format.ts | 0 .../src/{lib => shared/utils}/outbox-flush.ts | 2 +- .../{lib => shared/utils}/part-merge.test.ts | 0 .../src/{lib => shared/utils}/part-merge.ts | 0 .../utils}/persisted-keys.test.ts | 0 .../utils}/prompt-from-parts.test.ts | 0 .../utils}/prompt-from-parts.ts | 2 +- .../src/{lib => shared/utils}/query-client.ts | 0 .../{lib => shared/utils}/query-invalidate.ts | 0 .../{lib => shared/utils}/query-keys.test.ts | 0 .../src/{lib => shared/utils}/query-keys.ts | 0 .../{lib => shared/utils}/reconnect-flash.ts | 0 .../src/{lib => shared/utils}/revert-flow.ts | 4 +- .../utils}/revert-prune.test.ts | 0 .../src/{lib => shared/utils}/revert-prune.ts | 0 apps/mobile/src/{lib => shared/utils}/sdk.ts | 24 +- .../{lib => shared/utils}/server-config.ts | 0 .../{lib => shared/utils}/session-alerts.ts | 0 .../{lib => shared/utils}/session-binding.ts | 0 .../utils}/session-grouping.test.ts | 0 .../{lib => shared/utils}/session-grouping.ts | 4 +- .../utils}/session-list.integration.test.ts | 2 +- .../utils}/session-list.test.ts | 0 .../src/{lib => shared/utils}/session-list.ts | 4 +- .../utils}/session-load-reconcile.test.ts | 0 .../utils}/session-load-reconcile.ts | 0 .../utils}/session-status-reconcile.test.ts | 0 .../utils}/session-status-reconcile.ts | 0 apps/mobile/src/shared/utils/session/index.ts | 2 + .../utils}/settings-merge.test.ts | 0 .../{lib => shared/utils}/settings-merge.ts | 0 .../src/{lib => shared/utils}/slash-state.ts | 2 +- .../src/{lib => shared/utils}/speech.ts | 4 +- .../src/{lib => shared/utils}/sse.test.ts | 0 apps/mobile/src/{lib => shared/utils}/sse.ts | 0 .../utils}/status-labels.test.ts | 0 .../{lib => shared/utils}/status-labels.ts | 0 .../utils}/store-review-policy.test.ts | 0 .../utils}/store-review-policy.ts | 0 .../src/{lib => shared/utils}/store-review.ts | 0 .../mobile/src/{lib => shared/utils}/types.ts | 4 +- .../utils}/update-check-policy.test.ts | 0 .../utils}/update-check-policy.ts | 0 .../src/{lib => shared/utils}/update-check.ts | 0 .../src/{lib => shared/utils}/use-ai-sheet.ts | 0 .../utils}/use-keyboard-dock.ts | 2 +- .../utils}/use-session-prompts.ts | 2 +- .../utils}/use-session-screen.ts | 26 +- .../{lib => shared/utils}/use-session-send.ts | 2 +- .../utils}/waitlist-queue-storage.ts | 0 .../utils}/waitlist-queue.test.ts | 0 .../{lib => shared/utils}/waitlist.test.ts | 0 .../src/{lib => shared/utils}/waitlist.ts | 8 +- apps/mobile/tsconfig.json | 8 + 188 files changed, 601 insertions(+), 567 deletions(-) delete mode 100644 apps/mobile/packages/uikit/src/components/chat/StatusIndicator.tsx rename apps/mobile/packages/uikit/src/components/chat/{AiSettingsModal.tsx => ai-settings-modal/index.tsx} (97%) create mode 100644 apps/mobile/packages/uikit/src/components/chat/braille-spinner/index.tsx rename apps/mobile/packages/uikit/src/components/chat/{ => diff-compute/__tests__}/diff-compute.test.ts (98%) rename apps/mobile/packages/uikit/src/components/chat/{diff-compute.ts => diff-compute/index.ts} (99%) rename apps/mobile/packages/uikit/src/components/chat/{DiffView.tsx => diff-view/index.tsx} (92%) rename apps/mobile/packages/uikit/src/components/chat/{DirectoryBrowserSheet.tsx => directory-browser-sheet/index.tsx} (97%) rename apps/mobile/packages/uikit/src/components/chat/{DirectorySwitcher.tsx => directory-switcher/index.tsx} (98%) create mode 100644 apps/mobile/packages/uikit/src/components/chat/frame-glyph/index.tsx rename apps/mobile/packages/uikit/src/components/chat/{ImageAttachments.tsx => image-attachments/index.tsx} (96%) create mode 100644 apps/mobile/packages/uikit/src/components/chat/index.ts rename apps/mobile/packages/uikit/src/components/chat/{MessageBubble.tsx => message-bubble/index.tsx} (97%) rename apps/mobile/packages/uikit/src/components/chat/{MessageQueueSheet.tsx => message-queue-sheet/index.tsx} (97%) rename apps/mobile/packages/uikit/src/components/chat/{PermissionPrompt.tsx => permission-prompt/index.tsx} (97%) rename apps/mobile/packages/uikit/src/components/chat/{PickerSheet.tsx => picker-sheet/index.tsx} (97%) rename apps/mobile/packages/uikit/src/components/chat/{QuestionPrompt.tsx => question-prompt/index.tsx} (97%) rename apps/mobile/packages/uikit/src/components/chat/{ReasoningBlock.tsx => reasoning-block/index.tsx} (96%) rename apps/mobile/packages/uikit/src/components/chat/{Select.tsx => select/index.tsx} (98%) rename apps/mobile/packages/uikit/src/components/chat/{SessionInfo.tsx => session-info/index.tsx} (98%) rename apps/mobile/packages/uikit/src/components/chat/{SheetHandle.tsx => sheet-handle/index.tsx} (96%) rename apps/mobile/packages/uikit/src/components/chat/{SlashPopover.tsx => slash-popover/index.tsx} (97%) create mode 100644 apps/mobile/packages/uikit/src/components/chat/status-indicator/index.tsx create mode 100644 apps/mobile/packages/uikit/src/components/chat/status-indicator/styles.ts rename apps/mobile/packages/uikit/src/components/chat/{ToolCallCard.tsx => tool-call-card/index.tsx} (99%) rename apps/mobile/packages/uikit/src/{Container.tsx => components/container/index.tsx} (98%) rename apps/mobile/packages/uikit/src/components/{LanDiscoveryModal.tsx => lan-discovery-modal/index.tsx} (99%) rename apps/mobile/packages/uikit/src/components/markdown/{CodeBlock.tsx => code-block/index.tsx} (94%) rename apps/mobile/packages/uikit/src/components/markdown/{CopyLink.tsx => copy-link/index.tsx} (100%) rename apps/mobile/packages/uikit/src/components/markdown/{Markdown.tsx => markdown/index.tsx} (97%) rename apps/mobile/packages/uikit/src/utils/{ => file-roots/__tests__}/file-roots.test.ts (97%) rename apps/mobile/packages/uikit/src/utils/{file-roots.ts => file-roots/index.ts} (98%) rename apps/mobile/packages/uikit/src/utils/{ => fs-mock/__tests__}/fs-mock.test.ts (92%) rename apps/mobile/packages/uikit/src/utils/{fs-mock.ts => fs-mock/index.ts} (96%) rename apps/mobile/packages/uikit/src/utils/{ => github-links/__tests__}/github-links.test.ts (97%) rename apps/mobile/packages/uikit/src/utils/{github-links.ts => github-links/index.ts} (100%) create mode 100644 apps/mobile/packages/uikit/src/utils/index.ts rename apps/mobile/packages/uikit/src/utils/{ => lan-discover/__tests__}/lan-discover.test.ts (99%) rename apps/mobile/packages/uikit/src/utils/{lan-discover.ts => lan-discover/index.ts} (97%) rename apps/mobile/packages/uikit/src/utils/{ => path-utils/__tests__}/breadcrumbs.test.ts (91%) rename apps/mobile/packages/uikit/src/utils/{ => path-utils/__tests__}/path-utils.test.ts (97%) rename apps/mobile/packages/uikit/src/utils/{path-utils.ts => path-utils/index.ts} (98%) rename apps/mobile/packages/uikit/src/utils/{ => scroll-config/__tests__}/scroll-config.test.ts (95%) rename apps/mobile/packages/uikit/src/utils/{scroll-config.ts => scroll-config/index.ts} (95%) rename apps/mobile/packages/uikit/src/utils/{ => session-layout/__tests__}/session-layout.test.ts (98%) rename apps/mobile/packages/uikit/src/utils/{session-layout.ts => session-layout/index.ts} (100%) rename apps/mobile/packages/uikit/src/utils/{ => sheet-layout/__tests__}/sheet-layout.test.ts (93%) rename apps/mobile/packages/uikit/src/utils/{sheet-layout.ts => sheet-layout/index.ts} (100%) rename apps/mobile/src/components/session/{ComposerDock.tsx => composer-dock/index.tsx} (98%) rename apps/mobile/src/components/session/{EmptyState.tsx => empty-state/index.tsx} (99%) create mode 100644 apps/mobile/src/components/session/index.ts rename apps/mobile/src/components/session/{MessageList.tsx => message-list/index.tsx} (97%) rename apps/mobile/src/components/session/{PromptOverlay.tsx => prompt-overlay/index.tsx} (98%) rename apps/mobile/src/components/session/{SessionBanners.tsx => session-banners/index.tsx} (97%) rename apps/mobile/src/components/session/{SessionHeader.tsx => session-header/index.tsx} (97%) rename apps/mobile/src/components/session/{SessionSheets.tsx => session-sheets/index.tsx} (94%) rename apps/mobile/src/{queries => shared/api}/catalog.ts (93%) rename apps/mobile/src/{queries => shared/api}/project.ts (96%) rename apps/mobile/src/{queries => shared/api}/session-ops.ts (97%) rename apps/mobile/src/{queries => shared/api}/sessions.ts (97%) rename apps/mobile/src/{ => shared}/stores/auth.ts (98%) rename apps/mobile/src/{ => shared}/stores/catalog.ts (94%) rename apps/mobile/src/{ => shared}/stores/cloned-projects.ts (89%) rename apps/mobile/src/{ => shared}/stores/connections.ts (98%) rename apps/mobile/src/{ => shared}/stores/events.ts (97%) rename apps/mobile/src/{ => shared}/stores/sessions.ts (97%) rename apps/mobile/src/{ => shared}/stores/settings.ts (89%) rename apps/mobile/src/{ => shared}/stores/ui.ts (93%) rename apps/mobile/src/{lib => shared/utils}/active-tasks.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/active-tasks.ts (97%) rename apps/mobile/src/{lib => shared/utils}/api-error.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/api-error.ts (100%) rename apps/mobile/src/{lib => shared/utils}/app-version.test.ts (90%) rename apps/mobile/src/{lib => shared/utils}/app-version.ts (94%) rename apps/mobile/src/{lib => shared/utils}/auth.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/auth.ts (97%) rename apps/mobile/src/{lib => shared/utils}/catalog-parse.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/catalog-parse.ts (95%) rename apps/mobile/src/{lib => shared/utils}/composer.ts (99%) rename apps/mobile/src/{lib => shared/utils}/demo-script.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/demo-script.ts (98%) rename apps/mobile/src/{lib => shared/utils}/diagnostics-classify.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/diagnostics-classify.ts (98%) rename apps/mobile/src/{lib => shared/utils}/diagnostics.ts (99%) rename apps/mobile/src/{lib => shared/utils}/git-remotes.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/git-remotes.ts (98%) rename apps/mobile/src/{lib => shared/utils}/github-mock.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/github-mock.ts (98%) rename apps/mobile/src/{lib => shared/utils}/headers.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/headers.ts (98%) rename apps/mobile/src/{lib => shared/utils}/i18n/catalog-parity.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/i18n/config.ts (100%) rename apps/mobile/src/{lib => shared/utils}/i18n/en.json (100%) rename apps/mobile/src/{lib => shared/utils}/i18n/locale-resolve.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/i18n/locale-resolve.ts (100%) rename apps/mobile/src/{lib => shared/utils}/i18n/ru.json (100%) rename apps/mobile/src/{lib => shared/utils}/lan-manual.ts (100%) rename apps/mobile/src/{lib => shared/utils}/lan-projects.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/links.ts (100%) rename apps/mobile/src/{lib => shared/utils}/listed-session.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/listed-session.ts (96%) rename apps/mobile/src/{lib => shared/utils}/logbuffer.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/logbuffer.ts (98%) rename apps/mobile/src/{lib => shared/utils}/message-merge.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/message-merge.ts (100%) rename apps/mobile/src/{lib => shared/utils}/message-queue.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/message-queue.ts (98%) rename apps/mobile/src/{lib => shared/utils}/model-selection.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/model-selection.ts (94%) rename apps/mobile/src/{lib => shared/utils}/notifications.ts (99%) rename apps/mobile/src/{lib => shared/utils}/notify-format.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/notify-format.ts (100%) rename apps/mobile/src/{lib => shared/utils}/outbox-flush.ts (98%) rename apps/mobile/src/{lib => shared/utils}/part-merge.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/part-merge.ts (100%) rename apps/mobile/src/{lib => shared/utils}/persisted-keys.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/prompt-from-parts.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/prompt-from-parts.ts (94%) rename apps/mobile/src/{lib => shared/utils}/query-client.ts (100%) rename apps/mobile/src/{lib => shared/utils}/query-invalidate.ts (100%) rename apps/mobile/src/{lib => shared/utils}/query-keys.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/query-keys.ts (100%) rename apps/mobile/src/{lib => shared/utils}/reconnect-flash.ts (100%) rename apps/mobile/src/{lib => shared/utils}/revert-flow.ts (96%) rename apps/mobile/src/{lib => shared/utils}/revert-prune.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/revert-prune.ts (100%) rename apps/mobile/src/{lib => shared/utils}/sdk.ts (98%) rename apps/mobile/src/{lib => shared/utils}/server-config.ts (100%) rename apps/mobile/src/{lib => shared/utils}/session-alerts.ts (100%) rename apps/mobile/src/{lib => shared/utils}/session-binding.ts (100%) rename apps/mobile/src/{lib => shared/utils}/session-grouping.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/session-grouping.ts (96%) rename apps/mobile/src/{lib => shared/utils}/session-list.integration.test.ts (98%) rename apps/mobile/src/{lib => shared/utils}/session-list.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/session-list.ts (97%) rename apps/mobile/src/{lib => shared/utils}/session-load-reconcile.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/session-load-reconcile.ts (100%) rename apps/mobile/src/{lib => shared/utils}/session-status-reconcile.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/session-status-reconcile.ts (100%) create mode 100644 apps/mobile/src/shared/utils/session/index.ts rename apps/mobile/src/{lib => shared/utils}/settings-merge.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/settings-merge.ts (100%) rename apps/mobile/src/{lib => shared/utils}/slash-state.ts (98%) rename apps/mobile/src/{lib => shared/utils}/speech.ts (98%) rename apps/mobile/src/{lib => shared/utils}/sse.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/sse.ts (100%) rename apps/mobile/src/{lib => shared/utils}/status-labels.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/status-labels.ts (100%) rename apps/mobile/src/{lib => shared/utils}/store-review-policy.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/store-review-policy.ts (100%) rename apps/mobile/src/{lib => shared/utils}/store-review.ts (100%) rename apps/mobile/src/{lib => shared/utils}/types.ts (94%) rename apps/mobile/src/{lib => shared/utils}/update-check-policy.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/update-check-policy.ts (100%) rename apps/mobile/src/{lib => shared/utils}/update-check.ts (100%) rename apps/mobile/src/{lib => shared/utils}/use-ai-sheet.ts (100%) rename apps/mobile/src/{lib => shared/utils}/use-keyboard-dock.ts (99%) rename apps/mobile/src/{lib => shared/utils}/use-session-prompts.ts (98%) rename apps/mobile/src/{lib => shared/utils}/use-session-screen.ts (97%) rename apps/mobile/src/{lib => shared/utils}/use-session-send.ts (99%) rename apps/mobile/src/{lib => shared/utils}/waitlist-queue-storage.ts (100%) rename apps/mobile/src/{lib => shared/utils}/waitlist-queue.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/waitlist.test.ts (100%) rename apps/mobile/src/{lib => shared/utils}/waitlist.ts (99%) diff --git a/apps/mobile/app/(tabs)/_layout.tsx b/apps/mobile/app/(tabs)/_layout.tsx index 57a6968..2385cfc 100644 --- a/apps/mobile/app/(tabs)/_layout.tsx +++ b/apps/mobile/app/(tabs)/_layout.tsx @@ -4,8 +4,8 @@ import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { useEvents } from "@/stores/events" import { useSessions } from "@/stores/sessions" -import { useSessionsList } from "@/queries/sessions" -import { countActiveTasks } from "@/lib/active-tasks" +import { useSessionsList } from "@/api/sessions" +import { countActiveTasks } from "@/utils/active-tasks" import { ConnectionBadge } from "@/components/ConnectionBadge" import { layout } from "@web2bizz/ui-native" diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/index.tsx index e6ddfa5..d62ae07 100644 --- a/apps/mobile/app/(tabs)/index.tsx +++ b/apps/mobile/app/(tabs)/index.tsx @@ -21,8 +21,8 @@ import { import { router } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useSessionsList, useCreateSession, useDeleteSession, useRenameSession } from "@/queries/sessions" -import { useProjectInfo, useServerProjects } from "@/queries/project" +import { useSessionsList, useCreateSession, useDeleteSession, useRenameSession } from "@/api/sessions" +import { useProjectInfo, useServerProjects } from "@/api/project" import { useConnections } from "@/stores/connections" import { useEvents } from "@/stores/events" import { useSettings } from "@/stores/settings" @@ -33,13 +33,13 @@ import BottomSheet, { BottomSheetScrollView, type BottomSheetBackdropProps, } from "@gorhom/bottom-sheet" -import type { Project } from "@/lib/sdk" +import type { Project } from "@/utils/sdk" import { DirectorySwitcher, DirectoryBrowserSheet } from "@web2bizz/ui-native" import { CloneRepoSheet } from "@/components/chat/CloneRepoSheet" import { SheetHandle } from "@web2bizz/ui-native" -import { groupProjects } from "@/lib/session-grouping" -import { lanConnectionIds } from "@/lib/listed-session" -import type { ListedSession } from "@/lib/listed-session" +import { groupProjects } from "@/utils/session-grouping" +import { lanConnectionIds } from "@/utils/listed-session" +import type { ListedSession } from "@/utils/listed-session" import { UpdateBanner } from "@/components/UpdateBanner" import { nameOf } from "@web2bizz/ui-native" import { useUi } from "@/stores/ui" diff --git a/apps/mobile/app/(tabs)/settings.tsx b/apps/mobile/app/(tabs)/settings.tsx index 048d673..2c47514 100644 --- a/apps/mobile/app/(tabs)/settings.tsx +++ b/apps/mobile/app/(tabs)/settings.tsx @@ -19,7 +19,7 @@ import { useConnections } from "@/stores/connections" import { useEvents } from "@/stores/events" import { LanDiscoveryModal } from "@web2bizz/ui-native" import type { LanCandidate } from "@web2bizz/ui-native" -import type { ServerConnection } from "@/lib/types" +import type { ServerConnection } from "@/utils/types" const logoXml = `` import { @@ -27,11 +27,11 @@ import { categoryMeta, setup as setupNotifications, granted as notificationsGranted, -} from "@/lib/notifications" -import type { Category } from "@/lib/notifications" -import { CURRENT_VERSION } from "@/lib/update-check" +} from "@/utils/notifications" +import type { Category } from "@/utils/notifications" +import { CURRENT_VERSION } from "@/utils/update-check" import { colors, layout } from "@web2bizz/ui-native" -import type { LocalePreference } from "@/lib/i18n/locale-resolve" +import type { LocalePreference } from "@/utils/i18n/locale-resolve" function SettingRow({ icon, diff --git a/apps/mobile/app/(tabs)/tasks.tsx b/apps/mobile/app/(tabs)/tasks.tsx index 7599e29..7fe5eaa 100644 --- a/apps/mobile/app/(tabs)/tasks.tsx +++ b/apps/mobile/app/(tabs)/tasks.tsx @@ -4,11 +4,11 @@ import { router } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { useSessions } from "@/stores/sessions" -import { useSessionsList } from "@/queries/sessions" +import { useSessionsList } from "@/api/sessions" import { useEvents } from "@/stores/events" -import { selectActiveSessions } from "@/lib/active-tasks" +import { selectActiveSessions } from "@/utils/active-tasks" import { colors } from "@web2bizz/ui-native" -import type { ListedSession } from "@/lib/listed-session" +import type { ListedSession } from "@/utils/listed-session" // Tasks = sessions where the agent is currently doing something: // SSE sessionStatus busy/retry, plus optimistic sending (tap → SSE busy gap). diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index c13b099..e64c1e8 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -3,21 +3,21 @@ import { Stack, router, useSegments } from "expo-router" import { StatusBar } from "expo-status-bar" import { useColorScheme, View, ActivityIndicator, AppState } from "react-native" import { QueryClientProvider } from "@tanstack/react-query" -import { queryClient, setupQueryFocusManager } from "@/lib/query-client" -import { queryKeys } from "@/lib/query-keys" -import { fetchCatalogData } from "@/queries/catalog" +import { queryClient, setupQueryFocusManager } from "@/utils/query-client" +import { queryKeys } from "@/utils/query-keys" +import { fetchCatalogData } from "@/api/catalog" import { GestureHandlerRootView } from "react-native-gesture-handler" import { BottomSheetModalProvider } from "@gorhom/bottom-sheet" import { I18nextProvider, useTranslation } from "react-i18next" -import i18n from "@/lib/i18n/config" +import i18n from "@/utils/i18n/config" import { useAuth } from "@/stores/auth" import { useConnections } from "@/stores/connections" import { useEvents } from "@/stores/events" import { useSettings } from "@/stores/settings" import { AuthGate } from "@/components/AuthGate" import { ErrorBoundary } from "@/components/ErrorBoundary" -import * as notifications from "@/lib/notifications" -import { flushPendingSignups } from "@/lib/waitlist-queue-storage" +import * as notifications from "@/utils/notifications" +import { flushPendingSignups } from "@/utils/waitlist-queue-storage" import * as SplashScreen from "expo-splash-screen" SplashScreen.preventAutoHideAsync().catch(() => {}) diff --git a/apps/mobile/app/connection/add.tsx b/apps/mobile/app/connection/add.tsx index 30f7f1b..0a26b91 100644 --- a/apps/mobile/app/connection/add.tsx +++ b/apps/mobile/app/connection/add.tsx @@ -15,16 +15,16 @@ import { router } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { useConnections } from "@/stores/connections" -import type { ConnectionType } from "@/lib/types" -import { probeConnection, shareReport } from "@/lib/diagnostics" -import { parseUrl } from "@/lib/diagnostics-classify" -import { buildAuth } from "@/lib/auth" -import { submitWaitlistSignup, buildWaitlistMailtoUrl, needsManualEscapeHatch, type QueuedSignup } from "@/lib/waitlist" -import { flushPendingSignups, queuePendingSignup, readPendingSignups, dropPendingSignup } from "@/lib/waitlist-queue-storage" -import { HARDCODED_SERVER_URL } from "@/lib/server-config" -import { buildManualLanUrl } from "@/lib/lan-manual" +import type { ConnectionType } from "@/utils/types" +import { probeConnection, shareReport } from "@/utils/diagnostics" +import { parseUrl } from "@/utils/diagnostics-classify" +import { buildAuth } from "@/utils/auth" +import { submitWaitlistSignup, buildWaitlistMailtoUrl, needsManualEscapeHatch, type QueuedSignup } from "@/utils/waitlist" +import { flushPendingSignups, queuePendingSignup, readPendingSignups, dropPendingSignup } from "@/utils/waitlist-queue-storage" +import { HARDCODED_SERVER_URL } from "@/utils/server-config" +import { buildManualLanUrl } from "@/utils/lan-manual" import { colors } from "@web2bizz/ui-native" -import { APP_VERSION } from "@/lib/app-version" +import { APP_VERSION } from "@/utils/app-version" export default function AddConnectionScreen() { const colorScheme = useColorScheme() diff --git a/apps/mobile/app/demo.tsx b/apps/mobile/app/demo.tsx index 1a2c4fd..94f169e 100644 --- a/apps/mobile/app/demo.tsx +++ b/apps/mobile/app/demo.tsx @@ -4,7 +4,7 @@ import { Stack, useRouter } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { MessageBubble, PermissionPrompt } from "@web2bizz/ui-native" -import { buildDemoScript, buildDemoCompletionMessage, buildDemoDenialMessage } from "@/lib/demo-script" +import { buildDemoScript, buildDemoCompletionMessage, buildDemoDenialMessage } from "@/utils/demo-script" import { colors } from "@web2bizz/ui-native" // Reply values of PermissionPrompt's `onReply` (see diff --git a/apps/mobile/app/login.tsx b/apps/mobile/app/login.tsx index 2458578..d287028 100644 --- a/apps/mobile/app/login.tsx +++ b/apps/mobile/app/login.tsx @@ -22,8 +22,8 @@ import { useSettings } from "@/stores/settings" import { useEvents } from "@/stores/events" import { LanDiscoveryModal } from "@web2bizz/ui-native" import type { LanCandidate } from "@web2bizz/ui-native" -import type { ServerConnection } from "@/lib/types" -import { HARDCODED_SERVER_URL } from "@/lib/server-config" +import type { ServerConnection } from "@/utils/types" +import { HARDCODED_SERVER_URL } from "@/utils/server-config" const logoXml = `` diff --git a/apps/mobile/app/project/[directory].tsx b/apps/mobile/app/project/[directory].tsx index 4c34ffd..239b629 100644 --- a/apps/mobile/app/project/[directory].tsx +++ b/apps/mobile/app/project/[directory].tsx @@ -3,8 +3,8 @@ import { View, Text, FlatList, TouchableOpacity, StyleSheet, useColorScheme, Act import { Stack, useLocalSearchParams, router } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useSessionsList, useCreateSession, useDeleteSession } from "@/queries/sessions" -import { useProjectRemotes } from "@/queries/project" +import { useSessionsList, useCreateSession, useDeleteSession } from "@/api/sessions" +import { useProjectRemotes } from "@/api/project" import { useConnections } from "@/stores/connections" import { RepoLinkRow } from "@/components/RepoLinkRow" import { colors } from "@web2bizz/ui-native" diff --git a/apps/mobile/app/project/remotes.tsx b/apps/mobile/app/project/remotes.tsx index c283b63..7673204 100644 --- a/apps/mobile/app/project/remotes.tsx +++ b/apps/mobile/app/project/remotes.tsx @@ -2,7 +2,7 @@ import { View, Text, FlatList, StyleSheet, useColorScheme, ActivityIndicator } f import { Stack, useLocalSearchParams } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { useProjectRemotes } from "@/queries/project" +import { useProjectRemotes } from "@/api/project" import { RepoLinkRow } from "@/components/RepoLinkRow" // Full remote list of a project (the header card shows the first 3). diff --git a/apps/mobile/app/session/[id].tsx b/apps/mobile/app/session/[id].tsx index 9cd7fcf..b190cbe 100644 --- a/apps/mobile/app/session/[id].tsx +++ b/apps/mobile/app/session/[id].tsx @@ -3,14 +3,15 @@ import { useLocalSearchParams } from "expo-router" import { useSafeAreaInsets } from "react-native-safe-area-context" import { useTranslation } from "react-i18next" import { SessionInfo, keyboardVerticalOffset } from "@web2bizz/ui-native" -import { useSessionBinding } from "@/lib/session-binding" -import { useSessionController } from "@/lib/use-session-screen" -import { SessionHeader } from "@/components/session/SessionHeader" -import { SessionBanners } from "@/components/session/SessionBanners" -import { MessageList } from "@/components/session/MessageList" -import { ComposerDock } from "@/components/session/ComposerDock" -import { PromptOverlay } from "@/components/session/PromptOverlay" -import { SessionSheets } from "@/components/session/SessionSheets" +import { useSessionBinding, useSessionController } from "@/utils/session" +import { + SessionHeader, + SessionBanners, + MessageList, + ComposerDock, + PromptOverlay, + SessionSheets, +} from "@/components/session" import { s } from "./styles" export default function SessionScreen() { diff --git a/apps/mobile/babel.config.js b/apps/mobile/babel.config.js index b529da2..9f1a96b 100644 --- a/apps/mobile/babel.config.js +++ b/apps/mobile/babel.config.js @@ -13,6 +13,10 @@ module.exports = function (api) { alias: { "@": "./src", "@app": "./app", + "@/utils": "./src/shared/utils", + "@/api": "./src/shared/api", + "@/stores": "./src/shared/stores", + "@/shared": "./src/shared", }, }, ], diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js index 3afe0e8..0fc1e6d 100644 --- a/apps/mobile/metro.config.js +++ b/apps/mobile/metro.config.js @@ -20,6 +20,10 @@ config.resolver.extraNodeModules = { // `@` → src, `@app` → app (mirrors tsconfig paths + babel module-resolver). "@": path.resolve(__dirname, "src"), "@app": path.resolve(__dirname, "app"), + "@/utils": path.resolve(__dirname, "src/shared/utils"), + "@/api": path.resolve(__dirname, "src/shared/api"), + "@/stores": path.resolve(__dirname, "src/shared/stores"), + "@/shared": path.resolve(__dirname, "src/shared"), } module.exports = config diff --git a/apps/mobile/packages/uikit/src/components/chat/StatusIndicator.tsx b/apps/mobile/packages/uikit/src/components/chat/StatusIndicator.tsx deleted file mode 100644 index a218738..0000000 --- a/apps/mobile/packages/uikit/src/components/chat/StatusIndicator.tsx +++ /dev/null @@ -1,223 +0,0 @@ -import { memo, useEffect } from "react" -import { View, Text, StyleSheet, type StyleProp, type TextStyle } from "react-native" -import MaskedView from "@react-native-masked-view/masked-view" -import { LinearGradient } from "expo-linear-gradient" -import Animated, { - Easing, - cancelAnimation, - useAnimatedStyle, - useSharedValue, - withRepeat, - withTiming, - type SharedValue, -} from "react-native-reanimated" -import { useTranslation } from "react-i18next" - -// Классический терминальный спиннер точками Брайля — вместо системного -// кружка показывает, что агент работает. -// -// Никакого React-состояния: и кадры, и шиммер едут на UI-потоке через shared -// values, JS-поток их не дёргает даже под нагрузкой стриминга. -// (Раньше тик шёл через setInterval+setState — под ререндерами списка кадров -// интервал плыл; а шиммер гнался через animatedProps start/end градиента, -// которые expo-linear-gradient не анимирует — полоса стояла за кадром.) -const BRAILLE_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const -const BRAILLE_INTERVAL_MS = 80 -const TICK_LOOP_MS = BRAILLE_FRAMES.length * BRAILLE_INTERVAL_MS - -// Шиммер подписи как у ИИ-чатов: сплошная серая база + бегущая белая полоса -// фиксированной ширины с мягкими краями. Движется только transform (translateX) -// пинг-понгом — разворота нет, обёртка значения не нужна. -const SHIMMER_DURATION_MS = 1600 -const BAND_W = 48 - -// Один кадр спиннера: видимость — из UI-потокового счётчика, без ререндеров. -// Первый кадр в потоке задаёт размер бокса, остальные лежат поверх absolute. -const FrameGlyph = memo(function FrameGlyph({ - glyph, - index, - tick, - textStyle, -}: { - glyph: string - index: number - tick: SharedValue - textStyle: StyleProp -}) { - const frameStyle = useAnimatedStyle(() => ({ - opacity: Math.floor(tick.value / BRAILLE_INTERVAL_MS) % BRAILLE_FRAMES.length === index ? 1 : 0, - })) - return ( - 0 && s.glyphOverlay, frameStyle]}> - {glyph} - - ) -}) - -const BrailleSpinner = memo(function BrailleSpinner({ - tick, - isDark, -}: { - tick: SharedValue - isDark: boolean -}) { - return ( - - {BRAILLE_FRAMES.map((glyph, index) => ( - - ))} - - ) -}) - -// Server-reported session status, read by the parent from its own store and -// passed in — the kit never imports app zustand stores (which do not exist -// in the package). Extra fields on the caller's status object are fine. -export interface StatusSnapshot { - type: string - attempt?: number -} - -interface Props { - status?: StatusSnapshot - statusText?: string - optimistic?: boolean - isDark: boolean -} - -export function StatusIndicator({ status, statusText, optimistic, isDark }: Props) { - const { t } = useTranslation() - - // Server status is the source of truth, but the optimistic `sending` flag - // must also count on its own: it bridges the gap between the user tapping - // send and the server confirming busy (including a stale `idle` left over - // from the previous run). Once the server reports idle for the current - // run, the parent clears `sending` too, so `sseBusy || optimistic` can't - // get stuck. - const sseBusy = !!status && status.type !== "idle" - const busy = sseBusy || optimistic - - // Счётчик кадров спиннера — пила 0→800ms на UI-потоке, ререндеров нет. - // Маунтится только пока busy (в простое — плейсхолдер ниже). - const tick = useSharedValue(0) - useEffect(() => { - if (!busy) return - tick.value = withRepeat( - withTiming(TICK_LOOP_MS, { duration: TICK_LOOP_MS, easing: Easing.linear }), - -1, - false, - ) - return () => cancelAnimation(tick) - }, [busy, tick]) - - // Прогон шиммера пинг-понгом 0→1 на UI-потоке; ширина подписи снимается - // один раз через onLayout в shared value (без ререндера). - const sweep = useSharedValue(0) - const labelW = useSharedValue(0) - useEffect(() => { - if (!busy) return - sweep.value = withRepeat( - withTiming(1, { duration: SHIMMER_DURATION_MS, easing: Easing.linear }), - -1, - true, - ) - return () => cancelAnimation(sweep) - }, [busy, sweep]) - const bandStyle = useAnimatedStyle(() => ({ - transform: [{ translateX: -BAND_W + sweep.value * (labelW.value + BAND_W) }], - })) - - if (!busy) return - - const label = - status?.type === "retry" && typeof status.attempt === "number" - ? t("chat.statusIndicator.retrying", { attempt: status.attempt }) - : statusText || t("chat.statusIndicator.working") - // База шиммера — цвет подписи в текущей теме, полоса — белая. - const shimmerBase = isDark ? "#888888" : "#666666" - - return ( - - - {/* Маска вырезает слои строго по форме букв — полоса бежит - только по тексту, а не прямоугольником поверх строки. */} - - {label} - - } - > - { - labelW.value = e.nativeEvent.layout.width - }} - > - - - - - - - - ) -} - -const s = StyleSheet.create({ - bar: { - flexDirection: "row", - alignItems: "center", - gap: 8, - // Без собственных горизонтальных отступов: бар — ListHeaderComponent - // внутри списка, у которого уже есть padding 16. Свои paddingHorizontal - // давали двойной отступ (32) и выбивали текст из сетки пузырей. - height: 36, - backgroundColor: "transparent", - }, - barPlaceholder: { height: 36 }, - barDark: { backgroundColor: "transparent" }, - // Брайлевский спиннер: кегль крупнее подписи, цвет — как у неё. - // Кадры лежат стопкой: первый задаёт размер, остальные поверх. - spinner: { fontSize: 16, color: "#666666", textAlign: "center" }, - spinnerBox: { justifyContent: "center", alignItems: "center" }, - glyphOverlay: { - position: "absolute", - left: 0, - right: 0, - top: 0, - bottom: 0, - textAlign: "center", - textAlignVertical: "center", - }, - textDark: { color: "#888888" }, - // Шиммер подписи: маска занимает остаток строки; внутри — сплошная база - // в цвет подписи и absolute-полоса, едущая по UI-потоку. - labelMask: { flex: 1, height: 36 }, - labelMaskInner: { flex: 1, justifyContent: "center" }, - // Метрики бывшей подписи (13px/500); цвет любой непрозрачный — - // маска смотрит только на альфу. - maskText: { fontSize: 13, fontWeight: "500", color: "#000000" }, - labelFill: { flex: 1 }, - labelBase: { flex: 1 }, - band: { - position: "absolute", - left: 0, - top: 0, - bottom: 0, - width: BAND_W, - }, - bandGradient: { flex: 1 }, -}) diff --git a/apps/mobile/packages/uikit/src/components/chat/AiSettingsModal.tsx b/apps/mobile/packages/uikit/src/components/chat/ai-settings-modal/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/chat/AiSettingsModal.tsx rename to apps/mobile/packages/uikit/src/components/chat/ai-settings-modal/index.tsx index 0423adc..af523e2 100644 --- a/apps/mobile/packages/uikit/src/components/chat/AiSettingsModal.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/ai-settings-modal/index.tsx @@ -7,25 +7,25 @@ import BottomSheet, { type BottomSheetBackdropProps, } from "@gorhom/bottom-sheet" import { useTranslation } from "react-i18next" -import { colors, breakpoints } from "../../theme" -import { isLandscapeSize, shouldCapSheetContent, sheetContentCap } from "../../utils/sheet-layout" -import { Select, type SelectOption } from "./Select" -import { PickerSheet } from "./PickerSheet" -import { SheetHandle } from "./SheetHandle" +import { colors, breakpoints } from "../../../theme" +import { isLandscapeSize, shouldCapSheetContent, sheetContentCap } from "../../../utils/sheet-layout" +import { Select, type SelectOption } from "../select" +import { PickerSheet } from "../picker-sheet" +import { SheetHandle } from "../sheet-handle" -interface AgentItem { +type AgentItem = { name: string color?: string description?: string } -interface Provider { +type Provider = { id: string name: string models: Array<{ id: string; name: string }> } -interface Props { +type Props = { agents: AgentItem[] selectedAgent: string providers: Provider[] diff --git a/apps/mobile/packages/uikit/src/components/chat/braille-spinner/index.tsx b/apps/mobile/packages/uikit/src/components/chat/braille-spinner/index.tsx new file mode 100644 index 0000000..784c4b4 --- /dev/null +++ b/apps/mobile/packages/uikit/src/components/chat/braille-spinner/index.tsx @@ -0,0 +1,27 @@ +import { memo } from "react" +import { View } from "react-native" +import { type SharedValue } from "react-native-reanimated" +import { BRAILLE_FRAMES, s } from "../status-indicator/styles" +import { FrameGlyph } from "../frame-glyph" + +export const BrailleSpinner = memo(function BrailleSpinner({ + tick, + isDark, +}: { + tick: SharedValue + isDark: boolean +}) { + return ( + + {BRAILLE_FRAMES.map((glyph, index) => ( + + ))} + + ) +}) diff --git a/apps/mobile/packages/uikit/src/components/chat/diff-compute.test.ts b/apps/mobile/packages/uikit/src/components/chat/diff-compute/__tests__/diff-compute.test.ts similarity index 98% rename from apps/mobile/packages/uikit/src/components/chat/diff-compute.test.ts rename to apps/mobile/packages/uikit/src/components/chat/diff-compute/__tests__/diff-compute.test.ts index 5e9e8b0..8b5f1d0 100644 --- a/apps/mobile/packages/uikit/src/components/chat/diff-compute.test.ts +++ b/apps/mobile/packages/uikit/src/components/chat/diff-compute/__tests__/diff-compute.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { computeDiff } from "./diff-compute.ts" +import { computeDiff } from "../index.ts" // GitHub bug: computeDiff split on a literal "\n", so a CRLF `before` diffed // against an LF `after` treated every line as changed (each "line\r" !== diff --git a/apps/mobile/packages/uikit/src/components/chat/diff-compute.ts b/apps/mobile/packages/uikit/src/components/chat/diff-compute/index.ts similarity index 99% rename from apps/mobile/packages/uikit/src/components/chat/diff-compute.ts rename to apps/mobile/packages/uikit/src/components/chat/diff-compute/index.ts index 83e2dd8..e4a15dc 100644 --- a/apps/mobile/packages/uikit/src/components/chat/diff-compute.ts +++ b/apps/mobile/packages/uikit/src/components/chat/diff-compute/index.ts @@ -5,7 +5,7 @@ // runtime logic it renders, so the test and the real component can't drift // apart. -export interface DiffLine { +export type DiffLine = { type: "add" | "remove" | "context" text: string } diff --git a/apps/mobile/packages/uikit/src/components/chat/DiffView.tsx b/apps/mobile/packages/uikit/src/components/chat/diff-view/index.tsx similarity index 92% rename from apps/mobile/packages/uikit/src/components/chat/DiffView.tsx rename to apps/mobile/packages/uikit/src/components/chat/diff-view/index.tsx index 3a81899..5743455 100644 --- a/apps/mobile/packages/uikit/src/components/chat/DiffView.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/diff-view/index.tsx @@ -1,11 +1,11 @@ import { View, Text, StyleSheet, Platform, ScrollView } from "react-native" -import { WIDE_CONTENT_SCROLL_CONFIG } from "../../utils/scroll-config" -import { computeDiff } from "./diff-compute" -import { colors } from "../../theme" +import { WIDE_CONTENT_SCROLL_CONFIG } from "../../../utils/scroll-config" +import { computeDiff } from "../diff-compute/index" +import { colors } from "../../../theme" const mono = Platform.OS === "ios" ? "Menlo" : "monospace" -interface Props { +type Props = { before: string after: string isDark: boolean diff --git a/apps/mobile/packages/uikit/src/components/chat/DirectoryBrowserSheet.tsx b/apps/mobile/packages/uikit/src/components/chat/directory-browser-sheet/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/chat/DirectoryBrowserSheet.tsx rename to apps/mobile/packages/uikit/src/components/chat/directory-browser-sheet/index.tsx index 85389fa..e285563 100644 --- a/apps/mobile/packages/uikit/src/components/chat/DirectoryBrowserSheet.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/directory-browser-sheet/index.tsx @@ -8,18 +8,18 @@ import BottomSheet, { type BottomSheetBackdropProps, } from "@gorhom/bottom-sheet" import { useTranslation } from "react-i18next" -import type { DirectoryClient, FileEntry } from "../../types" -import { parentOf, nameOf, breadcrumbsOf } from "../../utils/path-utils" -import { normalizeRoots, type FileRoot } from "../../utils/file-roots" -import { colors } from "../../theme" -import { shouldCapSheetContent, sheetContentCap } from "../../utils/sheet-layout" -import { MOCK_HOME, MOCK_ROOTS, listMockDir } from "../../utils/fs-mock" -import { SheetHandle } from "./SheetHandle" +import type { DirectoryClient, FileEntry } from "../../../types" +import { parentOf, nameOf, breadcrumbsOf } from "../../../utils/path-utils" +import { normalizeRoots, type FileRoot } from "../../../utils/file-roots" +import { colors } from "../../../theme" +import { shouldCapSheetContent, sheetContentCap } from "../../../utils/sheet-layout" +import { MOCK_HOME, MOCK_ROOTS, listMockDir } from "../../../utils/fs-mock" +import { SheetHandle } from "../sheet-handle" // Fake latency so the mock mode feels like the real API during UI review. const MOCK_DELAY_MS = 350 -interface Props { +type Props = { sheetRef: React.RefObject // Directory to start browsing from whenever the sheet opens (project root, server home, etc). // When null, the sheet resolves the server home itself so the user never diff --git a/apps/mobile/packages/uikit/src/components/chat/DirectorySwitcher.tsx b/apps/mobile/packages/uikit/src/components/chat/directory-switcher/index.tsx similarity index 98% rename from apps/mobile/packages/uikit/src/components/chat/DirectorySwitcher.tsx rename to apps/mobile/packages/uikit/src/components/chat/directory-switcher/index.tsx index 3253e13..a749105 100644 --- a/apps/mobile/packages/uikit/src/components/chat/DirectorySwitcher.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/directory-switcher/index.tsx @@ -8,11 +8,11 @@ import BottomSheet, { type BottomSheetBackdropProps, } from "@gorhom/bottom-sheet" import { useTranslation } from "react-i18next" -import { colors } from "../../theme" -import { shouldCapSheetContent, sheetContentCap } from "../../utils/sheet-layout" -import { SheetHandle } from "./SheetHandle" +import { colors } from "../../../theme" +import { shouldCapSheetContent, sheetContentCap } from "../../../utils/sheet-layout" +import { SheetHandle } from "../sheet-handle" -interface Props { +type Props = { sheetRef: React.RefObject current?: string recents: string[] diff --git a/apps/mobile/packages/uikit/src/components/chat/frame-glyph/index.tsx b/apps/mobile/packages/uikit/src/components/chat/frame-glyph/index.tsx new file mode 100644 index 0000000..f226a23 --- /dev/null +++ b/apps/mobile/packages/uikit/src/components/chat/frame-glyph/index.tsx @@ -0,0 +1,25 @@ +import { memo } from "react" +import { type StyleProp, type TextStyle } from "react-native" +import Animated, { useAnimatedStyle, type SharedValue } from "react-native-reanimated" +import { BRAILLE_FRAMES, BRAILLE_INTERVAL_MS, s } from "../status-indicator/styles" + +export const FrameGlyph = memo(function FrameGlyph({ + glyph, + index, + tick, + textStyle, +}: { + glyph: string + index: number + tick: SharedValue + textStyle: StyleProp +}) { + const frameStyle = useAnimatedStyle(() => ({ + opacity: Math.floor(tick.value / BRAILLE_INTERVAL_MS) % BRAILLE_FRAMES.length === index ? 1 : 0, + })) + return ( + 0 && s.glyphOverlay, frameStyle]}> + {glyph} + + ) +}) diff --git a/apps/mobile/packages/uikit/src/components/chat/ImageAttachments.tsx b/apps/mobile/packages/uikit/src/components/chat/image-attachments/index.tsx similarity index 96% rename from apps/mobile/packages/uikit/src/components/chat/ImageAttachments.tsx rename to apps/mobile/packages/uikit/src/components/chat/image-attachments/index.tsx index 5ff066e..bd58f2f 100644 --- a/apps/mobile/packages/uikit/src/components/chat/ImageAttachments.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/image-attachments/index.tsx @@ -1,8 +1,8 @@ import { View, Text, Image, TouchableOpacity, StyleSheet, ScrollView } from "react-native" import { Ionicons } from "@expo/vector-icons" -import { colors } from "../../theme" +import { colors } from "../../../theme" -export interface Attachment { +export type Attachment = { uri: string mime: string filename?: string @@ -11,7 +11,7 @@ export interface Attachment { base64?: string } -interface Props { +type Props = { attachments: Attachment[] isDark: boolean onRemove: (index: number) => void diff --git a/apps/mobile/packages/uikit/src/components/chat/index.ts b/apps/mobile/packages/uikit/src/components/chat/index.ts new file mode 100644 index 0000000..43473b9 --- /dev/null +++ b/apps/mobile/packages/uikit/src/components/chat/index.ts @@ -0,0 +1,19 @@ +export * from "./ai-settings-modal" +export * from "./braille-spinner" +export * from "./diff-view" +export * from "./directory-browser-sheet" +export * from "./directory-switcher" +export * from "./frame-glyph" +export * from "./image-attachments" +export * from "./message-bubble" +export * from "./message-queue-sheet" +export * from "./permission-prompt" +export * from "./picker-sheet" +export * from "./question-prompt" +export * from "./reasoning-block" +export * from "./select" +export * from "./session-info" +export * from "./sheet-handle" +export * from "./slash-popover" +export * from "./status-indicator" +export * from "./tool-call-card" diff --git a/apps/mobile/packages/uikit/src/components/chat/MessageBubble.tsx b/apps/mobile/packages/uikit/src/components/chat/message-bubble/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/chat/MessageBubble.tsx rename to apps/mobile/packages/uikit/src/components/chat/message-bubble/index.tsx index d4dfbbc..4ba15ab 100644 --- a/apps/mobile/packages/uikit/src/components/chat/MessageBubble.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/message-bubble/index.tsx @@ -2,11 +2,11 @@ import { memo } from "react" import { View, Text, Image, StyleSheet, ScrollView, TouchableOpacity, Dimensions, Linking } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { Markdown } from "../markdown" -import { ToolCallCard } from "./ToolCallCard" -import { ReasoningBlock } from "./ReasoningBlock" -import { extractGitHubUrls } from "../../utils/github-links" -import type { Message, Part } from "../../types" +import { Markdown } from "../../markdown" +import { ToolCallCard } from "../tool-call-card" +import { ReasoningBlock } from "../reasoning-block" +import { extractGitHubUrls } from "../../../utils/github-links" +import type { Message, Part } from "../../../types" const SCREEN_WIDTH = Dimensions.get("window").width @@ -14,7 +14,7 @@ function isImageMime(mime?: string): boolean { return !!mime && mime.startsWith("image/") } -interface Props { +type Props = { message: Message parts: Part[] isDark: boolean diff --git a/apps/mobile/packages/uikit/src/components/chat/MessageQueueSheet.tsx b/apps/mobile/packages/uikit/src/components/chat/message-queue-sheet/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/chat/MessageQueueSheet.tsx rename to apps/mobile/packages/uikit/src/components/chat/message-queue-sheet/index.tsx index b48c2fb..f67ec0a 100644 --- a/apps/mobile/packages/uikit/src/components/chat/MessageQueueSheet.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/message-queue-sheet/index.tsx @@ -8,17 +8,17 @@ import BottomSheet, { type BottomSheetBackdropProps, } from "@gorhom/bottom-sheet" import { useTranslation } from "react-i18next" -import { colors } from "../../theme" -import { shouldCapSheetContent, sheetContentCap } from "../../utils/sheet-layout" -import { SheetHandle } from "./SheetHandle" +import { colors } from "../../../theme" +import { shouldCapSheetContent, sheetContentCap } from "../../../utils/sheet-layout" +import { SheetHandle } from "../sheet-handle" // One queued follow-up prompt waiting for the session to go idle. -export interface QueuedItem { +export type QueuedItem = { id: string text: string } -interface Props { +type Props = { // Parent-owned ref — UNCONTROLLED sheet opened imperatively via expand(), // same recipe as AiSettingsModal/PickerSheet (index -1, no visible prop). sheetRef: React.RefObject diff --git a/apps/mobile/packages/uikit/src/components/chat/PermissionPrompt.tsx b/apps/mobile/packages/uikit/src/components/chat/permission-prompt/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/chat/PermissionPrompt.tsx rename to apps/mobile/packages/uikit/src/components/chat/permission-prompt/index.tsx index c2de94b..5afb0f1 100644 --- a/apps/mobile/packages/uikit/src/components/chat/PermissionPrompt.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/permission-prompt/index.tsx @@ -1,9 +1,9 @@ import { View, Text, TouchableOpacity, StyleSheet } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { colors } from "../../theme" +import { colors } from "../../../theme" -interface Props { +type Props = { permission: { id: string; permission: string; patterns: string[] } isDark: boolean onReply: (reply: "once" | "always" | "reject") => void diff --git a/apps/mobile/packages/uikit/src/components/chat/PickerSheet.tsx b/apps/mobile/packages/uikit/src/components/chat/picker-sheet/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/chat/PickerSheet.tsx rename to apps/mobile/packages/uikit/src/components/chat/picker-sheet/index.tsx index 55e3eb7..1f2443a 100644 --- a/apps/mobile/packages/uikit/src/components/chat/PickerSheet.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/picker-sheet/index.tsx @@ -7,12 +7,12 @@ import BottomSheet, { BottomSheetTextInput, type BottomSheetBackdropProps, } from "@gorhom/bottom-sheet" -import { colors } from "../../theme" -import { shouldCapSheetContent, sheetContentCap } from "../../utils/sheet-layout" -import { SheetHandle } from "./SheetHandle" -import type { SelectOption } from "./Select" +import { colors } from "../../../theme" +import { shouldCapSheetContent, sheetContentCap } from "../../../utils/sheet-layout" +import { SheetHandle } from "../sheet-handle" +import type { SelectOption } from "../select" -interface Props { +type Props = { // Parent-owned ref — the sheet is UNCONTROLLED (no `visible` prop): the // caller opens it imperatively via expand(), exactly like the folder // sheets and AiSettingsModal. No open/close state of its own. diff --git a/apps/mobile/packages/uikit/src/components/chat/QuestionPrompt.tsx b/apps/mobile/packages/uikit/src/components/chat/question-prompt/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/chat/QuestionPrompt.tsx rename to apps/mobile/packages/uikit/src/components/chat/question-prompt/index.tsx index 9cec34d..8d2858c 100644 --- a/apps/mobile/packages/uikit/src/components/chat/QuestionPrompt.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/question-prompt/index.tsx @@ -2,15 +2,15 @@ import { useRef, useState } from "react" import { View, Text, TextInput, TouchableOpacity, ScrollView, StyleSheet } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { QUESTION_BODY_SCROLL_PROPS } from "../../utils/session-layout" -import { colors } from "../../theme" +import { QUESTION_BODY_SCROLL_PROPS } from "../../../utils/session-layout" +import { colors } from "../../../theme" -interface QuestionOption { +type QuestionOption = { label: string description: string } -interface Question { +type Question = { question: string header: string options: QuestionOption[] @@ -18,7 +18,7 @@ interface Question { custom?: boolean } -interface Props { +type Props = { request: { id: string questions: Question[] diff --git a/apps/mobile/packages/uikit/src/components/chat/ReasoningBlock.tsx b/apps/mobile/packages/uikit/src/components/chat/reasoning-block/index.tsx similarity index 96% rename from apps/mobile/packages/uikit/src/components/chat/ReasoningBlock.tsx rename to apps/mobile/packages/uikit/src/components/chat/reasoning-block/index.tsx index f7e797e..328f86c 100644 --- a/apps/mobile/packages/uikit/src/components/chat/ReasoningBlock.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/reasoning-block/index.tsx @@ -2,9 +2,9 @@ import { useState } from "react" import { View, Text, TouchableOpacity, StyleSheet } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { colors } from "../../theme" +import { colors } from "../../../theme" -interface Props { +type Props = { text: string isDark: boolean } diff --git a/apps/mobile/packages/uikit/src/components/chat/Select.tsx b/apps/mobile/packages/uikit/src/components/chat/select/index.tsx similarity index 98% rename from apps/mobile/packages/uikit/src/components/chat/Select.tsx rename to apps/mobile/packages/uikit/src/components/chat/select/index.tsx index ccd011f..d2f45d3 100644 --- a/apps/mobile/packages/uikit/src/components/chat/Select.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/select/index.tsx @@ -2,9 +2,9 @@ import { useMemo, useState } from "react" import { View, Text, TouchableOpacity, StyleSheet } from "react-native" import { BottomSheetFlatList, BottomSheetTextInput } from "@gorhom/bottom-sheet" import { Ionicons } from "@expo/vector-icons" -import { colors } from "../../theme" +import { colors } from "../../../theme" -export interface SelectOption { +export type SelectOption = { id: string | null label: string description?: string @@ -12,7 +12,7 @@ export interface SelectOption { group?: string } -interface Props { +type Props = { label: string options: SelectOption[] selectedId: string | null diff --git a/apps/mobile/packages/uikit/src/components/chat/SessionInfo.tsx b/apps/mobile/packages/uikit/src/components/chat/session-info/index.tsx similarity index 98% rename from apps/mobile/packages/uikit/src/components/chat/SessionInfo.tsx rename to apps/mobile/packages/uikit/src/components/chat/session-info/index.tsx index c71ecdd..7e96724 100644 --- a/apps/mobile/packages/uikit/src/components/chat/SessionInfo.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/session-info/index.tsx @@ -2,10 +2,10 @@ import { useMemo } from "react" import { View, Text, StyleSheet, TouchableOpacity, ActivityIndicator } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import type { Session, Message, Provider } from "../../types" -import { colors } from "../../theme" +import type { Session, Message, Provider } from "../../../types" +import { colors } from "../../../theme" -interface Props { +type Props = { session: Session | null messages: Message[] providers: Provider[] diff --git a/apps/mobile/packages/uikit/src/components/chat/SheetHandle.tsx b/apps/mobile/packages/uikit/src/components/chat/sheet-handle/index.tsx similarity index 96% rename from apps/mobile/packages/uikit/src/components/chat/SheetHandle.tsx rename to apps/mobile/packages/uikit/src/components/chat/sheet-handle/index.tsx index edc01dd..f11367e 100644 --- a/apps/mobile/packages/uikit/src/components/chat/SheetHandle.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/sheet-handle/index.tsx @@ -1,5 +1,5 @@ import { StyleSheet, View, useColorScheme } from "react-native" -import { colors } from "../../theme" +import { colors } from "../../../theme" // Shared drag handle for all bottom sheets: a full-width, 28px-tall grab zone // with a centered pill (the stock handle's ~24px zone is hard to catch, and diff --git a/apps/mobile/packages/uikit/src/components/chat/SlashPopover.tsx b/apps/mobile/packages/uikit/src/components/chat/slash-popover/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/chat/SlashPopover.tsx rename to apps/mobile/packages/uikit/src/components/chat/slash-popover/index.tsx index afdb1e5..f9b7503 100644 --- a/apps/mobile/packages/uikit/src/components/chat/SlashPopover.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/slash-popover/index.tsx @@ -2,9 +2,9 @@ import { useMemo } from "react" import { View, Text, TouchableOpacity, ScrollView, StyleSheet, Keyboard, Platform } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import { colors } from "../../theme" +import { colors } from "../../../theme" -export interface SlashCommand { +export type SlashCommand = { trigger: string title: string description?: string @@ -12,7 +12,7 @@ export interface SlashCommand { type: "builtin" | "custom" } -interface Props { +type Props = { query: string commands: SlashCommand[] isDark: boolean diff --git a/apps/mobile/packages/uikit/src/components/chat/status-indicator/index.tsx b/apps/mobile/packages/uikit/src/components/chat/status-indicator/index.tsx new file mode 100644 index 0000000..f1f0447 --- /dev/null +++ b/apps/mobile/packages/uikit/src/components/chat/status-indicator/index.tsx @@ -0,0 +1,105 @@ +import { useEffect } from "react" +import { View, Text } from "react-native" +import MaskedView from "@react-native-masked-view/masked-view" +import { LinearGradient } from "expo-linear-gradient" +import Animated, { + Easing, + cancelAnimation, + useAnimatedStyle, + useSharedValue, + withRepeat, + withTiming, +} from "react-native-reanimated" +import { useTranslation } from "react-i18next" + +import { BrailleSpinner } from "../braille-spinner" +import { + BAND_W, + SHIMMER_DURATION_MS, + TICK_LOOP_MS, + s, +} from "./styles" + +export type StatusSnapshot = { + type: string + attempt?: number +} + +type Props = { + status?: StatusSnapshot + statusText?: string + optimistic?: boolean + isDark: boolean +} + +export function StatusIndicator({ status, statusText, optimistic, isDark }: Props) { + const { t } = useTranslation() + + const sseBusy = !!status && status.type !== "idle" + const busy = sseBusy || optimistic + + const tick = useSharedValue(0) + useEffect(() => { + if (!busy) return + tick.value = withRepeat( + withTiming(TICK_LOOP_MS, { duration: TICK_LOOP_MS, easing: Easing.linear }), + -1, + false, + ) + return () => cancelAnimation(tick) + }, [busy, tick]) + + const sweep = useSharedValue(0) + const labelW = useSharedValue(0) + useEffect(() => { + if (!busy) return + sweep.value = withRepeat( + withTiming(1, { duration: SHIMMER_DURATION_MS, easing: Easing.linear }), + -1, + true, + ) + return () => cancelAnimation(sweep) + }, [busy, sweep]) + const bandStyle = useAnimatedStyle(() => ({ + transform: [{ translateX: -BAND_W + sweep.value * (labelW.value + BAND_W) }], + })) + + if (!busy) return + + const label = + status?.type === "retry" && typeof status.attempt === "number" + ? t("chat.statusIndicator.retrying", { attempt: status.attempt }) + : statusText || t("chat.statusIndicator.working") + const shimmerBase = isDark ? "#888888" : "#666666" + + return ( + + + + {label} + + } + > + { + labelW.value = e.nativeEvent.layout.width + }} + > + + + + + + + + ) +} diff --git a/apps/mobile/packages/uikit/src/components/chat/status-indicator/styles.ts b/apps/mobile/packages/uikit/src/components/chat/status-indicator/styles.ts new file mode 100644 index 0000000..478163f --- /dev/null +++ b/apps/mobile/packages/uikit/src/components/chat/status-indicator/styles.ts @@ -0,0 +1,45 @@ +import { StyleSheet } from "react-native" + +export const BRAILLE_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const +export const BRAILLE_INTERVAL_MS = 80 +export const TICK_LOOP_MS = BRAILLE_FRAMES.length * BRAILLE_INTERVAL_MS + +export const SHIMMER_DURATION_MS = 1600 +export const BAND_W = 48 + +export const s = StyleSheet.create({ + bar: { + flexDirection: "row", + alignItems: "center", + gap: 8, + height: 36, + backgroundColor: "transparent", + }, + barPlaceholder: { height: 36 }, + barDark: { backgroundColor: "transparent" }, + spinner: { fontSize: 16, color: "#666666", textAlign: "center" }, + spinnerBox: { justifyContent: "center", alignItems: "center" }, + glyphOverlay: { + position: "absolute", + left: 0, + right: 0, + top: 0, + bottom: 0, + textAlign: "center", + textAlignVertical: "center", + }, + textDark: { color: "#888888" }, + labelMask: { flex: 1, height: 36 }, + labelMaskInner: { flex: 1, justifyContent: "center" }, + maskText: { fontSize: 13, fontWeight: "500", color: "#000000" }, + labelFill: { flex: 1 }, + labelBase: { flex: 1 }, + band: { + position: "absolute", + left: 0, + top: 0, + bottom: 0, + width: BAND_W, + }, + bandGradient: { flex: 1 }, +}) diff --git a/apps/mobile/packages/uikit/src/components/chat/ToolCallCard.tsx b/apps/mobile/packages/uikit/src/components/chat/tool-call-card/index.tsx similarity index 99% rename from apps/mobile/packages/uikit/src/components/chat/ToolCallCard.tsx rename to apps/mobile/packages/uikit/src/components/chat/tool-call-card/index.tsx index c156067..2ff2ef6 100644 --- a/apps/mobile/packages/uikit/src/components/chat/ToolCallCard.tsx +++ b/apps/mobile/packages/uikit/src/components/chat/tool-call-card/index.tsx @@ -2,8 +2,8 @@ import { useState, useCallback } from "react" import { View, Text, TouchableOpacity, StyleSheet, ScrollView, Platform } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" -import type { Part } from "../../types" -import { DiffView } from "./DiffView" +import type { Part } from "../../../types" +import { DiffView } from "../diff-view" const TOOL_ICONS: Record = { read: "glasses-outline", @@ -307,7 +307,7 @@ function duration(start?: number, end?: number): string | null { } // --- Main component --- -interface Props { +type Props = { tool: Part isDark: boolean } diff --git a/apps/mobile/packages/uikit/src/Container.tsx b/apps/mobile/packages/uikit/src/components/container/index.tsx similarity index 98% rename from apps/mobile/packages/uikit/src/Container.tsx rename to apps/mobile/packages/uikit/src/components/container/index.tsx index c9da4e4..7e13adf 100644 --- a/apps/mobile/packages/uikit/src/Container.tsx +++ b/apps/mobile/packages/uikit/src/components/container/index.tsx @@ -1,5 +1,5 @@ import { View, StyleSheet, type ViewProps } from "react-native" -import { layout } from "./theme" +import { layout } from "../../theme" /** * Container — единый горизонтальный контейнер для всего приложения. diff --git a/apps/mobile/packages/uikit/src/components/LanDiscoveryModal.tsx b/apps/mobile/packages/uikit/src/components/lan-discovery-modal/index.tsx similarity index 99% rename from apps/mobile/packages/uikit/src/components/LanDiscoveryModal.tsx rename to apps/mobile/packages/uikit/src/components/lan-discovery-modal/index.tsx index 07bb137..f78ffef 100644 --- a/apps/mobile/packages/uikit/src/components/LanDiscoveryModal.tsx +++ b/apps/mobile/packages/uikit/src/components/lan-discovery-modal/index.tsx @@ -11,7 +11,7 @@ import { import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import * as Network from "expo-network" -import { colors } from "../theme" +import { colors } from "../../theme" // NOTE: lib/lan-discover is not vendored into uikit yet (cards 3-5). // Resolves once `src/lib` moves under `packages/uikit/src/lib`. import { @@ -20,7 +20,7 @@ import { isPrivateLanIpv4, scanLanHosts, type LanCandidate, -} from "../utils/lan-discover" +} from "../../utils/lan-discover" // Modal that sweeps the local /24 for opencode servers. Rendered (but hidden) // only when the user enabled settings.lanDiscovery — the sweep itself starts diff --git a/apps/mobile/packages/uikit/src/components/markdown/CodeBlock.tsx b/apps/mobile/packages/uikit/src/components/markdown/code-block/index.tsx similarity index 94% rename from apps/mobile/packages/uikit/src/components/markdown/CodeBlock.tsx rename to apps/mobile/packages/uikit/src/components/markdown/code-block/index.tsx index a5add4e..98bbcd7 100644 --- a/apps/mobile/packages/uikit/src/components/markdown/CodeBlock.tsx +++ b/apps/mobile/packages/uikit/src/components/markdown/code-block/index.tsx @@ -1,10 +1,10 @@ import { useState } from "react" import { View, Text, TouchableOpacity, StyleSheet, useColorScheme, Platform, ScrollView } from "react-native" import * as Clipboard from "expo-clipboard" -import { WIDE_CONTENT_SCROLL_CONFIG } from "../../utils/scroll-config" -import { colors } from "../../theme" +import { WIDE_CONTENT_SCROLL_CONFIG } from "../../../utils/scroll-config" +import { colors } from "../../../theme" -interface Props { +type Props = { code: string language?: string } diff --git a/apps/mobile/packages/uikit/src/components/markdown/CopyLink.tsx b/apps/mobile/packages/uikit/src/components/markdown/copy-link/index.tsx similarity index 100% rename from apps/mobile/packages/uikit/src/components/markdown/CopyLink.tsx rename to apps/mobile/packages/uikit/src/components/markdown/copy-link/index.tsx diff --git a/apps/mobile/packages/uikit/src/components/markdown/index.tsx b/apps/mobile/packages/uikit/src/components/markdown/index.tsx index deb9bc2..74a3f3b 100644 --- a/apps/mobile/packages/uikit/src/components/markdown/index.tsx +++ b/apps/mobile/packages/uikit/src/components/markdown/index.tsx @@ -1,3 +1,3 @@ -export { Markdown } from "./Markdown" -export { CodeBlock } from "./CodeBlock" -export { CopyLink } from "./CopyLink" +export * from "./code-block" +export * from "./copy-link" +export * from "./markdown" diff --git a/apps/mobile/packages/uikit/src/components/markdown/Markdown.tsx b/apps/mobile/packages/uikit/src/components/markdown/markdown/index.tsx similarity index 97% rename from apps/mobile/packages/uikit/src/components/markdown/Markdown.tsx rename to apps/mobile/packages/uikit/src/components/markdown/markdown/index.tsx index c4ae1fc..9279b1a 100644 --- a/apps/mobile/packages/uikit/src/components/markdown/Markdown.tsx +++ b/apps/mobile/packages/uikit/src/components/markdown/markdown/index.tsx @@ -1,9 +1,9 @@ import { useMemo, type ReactNode } from "react" import { View, Text, useColorScheme, Platform, type StyleProp, type ViewStyle, type TextStyle } from "react-native" import { useMarkdown, Renderer } from "react-native-marked" -import { CodeBlock } from "./CodeBlock" -import { CopyLink } from "./CopyLink" -import { colors } from "../../theme" +import { CodeBlock } from "../code-block" +import { CopyLink } from "../copy-link" +import { colors } from "../../../theme" // react-native-marked's base Renderer hardcodes `selectable` on every plain // text node it produces (text/strong/em/del/heading/codespan). On Android, @@ -135,7 +135,7 @@ const darkTheme = { hr: { ...lightTheme.hr, backgroundColor: "#2a2a2a" }, } -interface Props { +type Props = { children: string } diff --git a/apps/mobile/packages/uikit/src/components/wide-content-scroll.regression.test.ts b/apps/mobile/packages/uikit/src/components/wide-content-scroll.regression.test.ts index 50d26a2..4884d66 100644 --- a/apps/mobile/packages/uikit/src/components/wide-content-scroll.regression.test.ts +++ b/apps/mobile/packages/uikit/src/components/wide-content-scroll.regression.test.ts @@ -26,20 +26,20 @@ function readComponent(relativePath: string): string { } test("DiffView wraps diff lines in the shared horizontal-scroll ScrollView", () => { - const src = readComponent("chat/DiffView.tsx") + const src = readComponent("chat/diff-view/index.tsx") assert.match(src, / { - const src = readComponent("markdown/CodeBlock.tsx") + const src = readComponent("markdown/code-block/index.tsx") assert.match(src, / { - const diffView = readComponent("chat/DiffView.tsx") - const codeBlock = readComponent("markdown/CodeBlock.tsx") - assert.match(diffView, /from ["']\.\.\/\.\.\/utils\/scroll-config["']/) - assert.match(codeBlock, /from ["']\.\.\/\.\.\/utils\/scroll-config["']/) + const diffView = readComponent("chat/diff-view/index.tsx") + const codeBlock = readComponent("markdown/code-block/index.tsx") + assert.match(diffView, /from ["']\.\.\/\.\.\/\.\.\/utils\/scroll-config["']/) + assert.match(codeBlock, /from ["']\.\.\/\.\.\/\.\.\/utils\/scroll-config["']/) }) diff --git a/apps/mobile/packages/uikit/src/index.ts b/apps/mobile/packages/uikit/src/index.ts index 5c4f1c6..ea8756a 100644 --- a/apps/mobile/packages/uikit/src/index.ts +++ b/apps/mobile/packages/uikit/src/index.ts @@ -6,30 +6,30 @@ */ export * from "./theme" -export * from "./Container" +export * from "./components/container" export * from "./hooks/use-tablet" -export { LanDiscoveryModal } from "./components/LanDiscoveryModal" +export { LanDiscoveryModal } from "./components/lan-discovery-modal" // Chat sheets and bubbles (props-driven; the kit never imports app stores). -export { Select, type SelectOption } from "./components/chat/Select" -export { SheetHandle } from "./components/chat/SheetHandle" -export { PickerSheet } from "./components/chat/PickerSheet" -export { AiSettingsModal } from "./components/chat/AiSettingsModal" -export { DirectorySwitcher } from "./components/chat/DirectorySwitcher" -export { DirectoryBrowserSheet } from "./components/chat/DirectoryBrowserSheet" -export { MessageBubble } from "./components/chat/MessageBubble" -export { ToolCallCard } from "./components/chat/ToolCallCard" -export { DiffView } from "./components/chat/DiffView" -export { ReasoningBlock } from "./components/chat/ReasoningBlock" -export { PermissionPrompt } from "./components/chat/PermissionPrompt" -export { QuestionPrompt } from "./components/chat/QuestionPrompt" -export { StatusIndicator, type StatusSnapshot } from "./components/chat/StatusIndicator" -export { SlashPopover, type SlashCommand } from "./components/chat/SlashPopover" -export { ImageAttachments, type Attachment } from "./components/chat/ImageAttachments" -export { SessionInfo } from "./components/chat/SessionInfo" -export { MessageQueueSheet, type QueuedItem } from "./components/chat/MessageQueueSheet" -export { CopyLink } from "./components/markdown/CopyLink" -export { Markdown } from "./components/markdown/Markdown" -export { CodeBlock } from "./components/markdown/CodeBlock" +export { Select, type SelectOption } from "./components/chat/select" +export { SheetHandle } from "./components/chat/sheet-handle" +export { PickerSheet } from "./components/chat/picker-sheet" +export { AiSettingsModal } from "./components/chat/ai-settings-modal" +export { DirectorySwitcher } from "./components/chat/directory-switcher" +export { DirectoryBrowserSheet } from "./components/chat/directory-browser-sheet" +export { MessageBubble } from "./components/chat/message-bubble" +export { ToolCallCard } from "./components/chat/tool-call-card" +export { DiffView } from "./components/chat/diff-view" +export { ReasoningBlock } from "./components/chat/reasoning-block" +export { PermissionPrompt } from "./components/chat/permission-prompt" +export { QuestionPrompt } from "./components/chat/question-prompt" +export { StatusIndicator, type StatusSnapshot } from "./components/chat/status-indicator" +export { SlashPopover, type SlashCommand } from "./components/chat/slash-popover" +export { ImageAttachments, type Attachment } from "./components/chat/image-attachments" +export { SessionInfo } from "./components/chat/session-info" +export { MessageQueueSheet, type QueuedItem } from "./components/chat/message-queue-sheet" +export { CopyLink } from "./components/markdown/copy-link" +export { Markdown } from "./components/markdown/markdown" +export { CodeBlock } from "./components/markdown/code-block" // Pure UI-support utils (unit-tested, no app imports). export { isLandscapeSize, shouldCapSheetContent, sheetContentCap } from "./utils/sheet-layout" export { parentOf, nameOf, breadcrumbsOf, stripTrailingSlash } from "./utils/path-utils" diff --git a/apps/mobile/packages/uikit/src/types.ts b/apps/mobile/packages/uikit/src/types.ts index 8f27606..3791e87 100644 --- a/apps/mobile/packages/uikit/src/types.ts +++ b/apps/mobile/packages/uikit/src/types.ts @@ -8,7 +8,7 @@ * directly. */ -export interface Message { +export type Message = { id: string sessionID: string role: "user" | "assistant" @@ -34,7 +34,7 @@ export interface Message { finish?: string } -export interface Part { +export type Part = { id: string sessionID?: string messageID: string @@ -77,13 +77,13 @@ export interface Part { // Message/Part above: values from the app store stay structurally // assignable, but uikit components never import ../../lib/*). -export interface SessionSummary { +export type SessionSummary = { additions: number deletions: number files: number } -export interface Session { +export type Session = { id: string title: string summary?: SessionSummary @@ -94,12 +94,12 @@ export interface Session { } } -export interface ProviderModel { +export type ProviderModel = { id: string limit?: { context: number; output: number } } -export interface Provider { +export type Provider = { id: string models: ProviderModel[] } @@ -107,7 +107,7 @@ export interface Provider { // --- Filesystem domain (mirrors src/lib/sdk.ts FileEntry and the FileRoot // shape for the fields the directory explorer reads). -export interface FileEntry { +export type FileEntry = { name: string path: string absolute: string @@ -115,14 +115,14 @@ export interface FileEntry { ignored: boolean } -export interface FileRoot { +export type FileRoot = { path: string label: string } // Minimal structural client for the directory explorer: only the calls // DirectoryBrowserSheet makes. The app's full Client stays assignable. -export interface DirectoryClient { +export type DirectoryClient = { file: { list: (params: { path?: string }) => Promise roots: () => Promise diff --git a/apps/mobile/packages/uikit/src/utils/file-roots.test.ts b/apps/mobile/packages/uikit/src/utils/file-roots/__tests__/file-roots.test.ts similarity index 97% rename from apps/mobile/packages/uikit/src/utils/file-roots.test.ts rename to apps/mobile/packages/uikit/src/utils/file-roots/__tests__/file-roots.test.ts index eb100ee..d45ba68 100644 --- a/apps/mobile/packages/uikit/src/utils/file-roots.test.ts +++ b/apps/mobile/packages/uikit/src/utils/file-roots/__tests__/file-roots.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { normalizeRoots } from "./file-roots.ts" +import { normalizeRoots } from "../index.ts" test("normalizeRoots: passes through well-formed entries", () => { const result = normalizeRoots([ diff --git a/apps/mobile/packages/uikit/src/utils/file-roots.ts b/apps/mobile/packages/uikit/src/utils/file-roots/index.ts similarity index 98% rename from apps/mobile/packages/uikit/src/utils/file-roots.ts rename to apps/mobile/packages/uikit/src/utils/file-roots/index.ts index b12cf65..1bc7aa7 100644 --- a/apps/mobile/packages/uikit/src/utils/file-roots.ts +++ b/apps/mobile/packages/uikit/src/utils/file-roots/index.ts @@ -6,7 +6,7 @@ // duplicate entries, so this module defends against all of that before the // directory browser renders anything. -export interface FileRoot { +export type FileRoot = { path: string label: string } diff --git a/apps/mobile/packages/uikit/src/utils/fs-mock.test.ts b/apps/mobile/packages/uikit/src/utils/fs-mock/__tests__/fs-mock.test.ts similarity index 92% rename from apps/mobile/packages/uikit/src/utils/fs-mock.test.ts rename to apps/mobile/packages/uikit/src/utils/fs-mock/__tests__/fs-mock.test.ts index 9b02f99..c885036 100644 --- a/apps/mobile/packages/uikit/src/utils/fs-mock.test.ts +++ b/apps/mobile/packages/uikit/src/utils/fs-mock/__tests__/fs-mock.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { listMockDir, MOCK_HOME, MOCK_ROOTS } from "./fs-mock.ts" +import { listMockDir, MOCK_HOME, MOCK_ROOTS } from "../index.ts" test("listMockDir: returns child directories as FileEntry-likes", () => { const entries = listMockDir(MOCK_HOME) diff --git a/apps/mobile/packages/uikit/src/utils/fs-mock.ts b/apps/mobile/packages/uikit/src/utils/fs-mock/index.ts similarity index 96% rename from apps/mobile/packages/uikit/src/utils/fs-mock.ts rename to apps/mobile/packages/uikit/src/utils/fs-mock/index.ts index a55c91d..25b1e05 100644 --- a/apps/mobile/packages/uikit/src/utils/fs-mock.ts +++ b/apps/mobile/packages/uikit/src/utils/fs-mock/index.ts @@ -6,7 +6,7 @@ // When the backend lands, drop `useMock` from DirectoryBrowserSheet callers — // the mock shapes below mirror the real API shapes so screens don't change. -import type { FileEntry, FileRoot } from "../types" +import type { FileEntry, FileRoot } from "../../types" export const MOCK_HOME = "/home/user" diff --git a/apps/mobile/packages/uikit/src/utils/github-links.test.ts b/apps/mobile/packages/uikit/src/utils/github-links/__tests__/github-links.test.ts similarity index 97% rename from apps/mobile/packages/uikit/src/utils/github-links.test.ts rename to apps/mobile/packages/uikit/src/utils/github-links/__tests__/github-links.test.ts index 6d9e103..836c725 100644 --- a/apps/mobile/packages/uikit/src/utils/github-links.test.ts +++ b/apps/mobile/packages/uikit/src/utils/github-links/__tests__/github-links.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { extractGitHubUrls } from "./github-links.ts" +import { extractGitHubUrls } from "../index.ts" // Bare URLs ------------------------------------------------------------------ diff --git a/apps/mobile/packages/uikit/src/utils/github-links.ts b/apps/mobile/packages/uikit/src/utils/github-links/index.ts similarity index 100% rename from apps/mobile/packages/uikit/src/utils/github-links.ts rename to apps/mobile/packages/uikit/src/utils/github-links/index.ts diff --git a/apps/mobile/packages/uikit/src/utils/index.ts b/apps/mobile/packages/uikit/src/utils/index.ts new file mode 100644 index 0000000..d1463a5 --- /dev/null +++ b/apps/mobile/packages/uikit/src/utils/index.ts @@ -0,0 +1,8 @@ +export * from "./file-roots" +export * from "./fs-mock" +export * from "./github-links" +export * from "./lan-discover" +export * from "./path-utils" +export * from "./scroll-config" +export * from "./session-layout" +export * from "./sheet-layout" diff --git a/apps/mobile/packages/uikit/src/utils/lan-discover.test.ts b/apps/mobile/packages/uikit/src/utils/lan-discover/__tests__/lan-discover.test.ts similarity index 99% rename from apps/mobile/packages/uikit/src/utils/lan-discover.test.ts rename to apps/mobile/packages/uikit/src/utils/lan-discover/__tests__/lan-discover.test.ts index 214c791..90d9f28 100644 --- a/apps/mobile/packages/uikit/src/utils/lan-discover.test.ts +++ b/apps/mobile/packages/uikit/src/utils/lan-discover/__tests__/lan-discover.test.ts @@ -6,7 +6,7 @@ import { probeServer, scanLanHosts, type LanCandidate, -} from "./lan-discover.ts" +} from "../index.ts" test("only RFC1918 IPv4 counts as LAN", () => { assert.equal(isPrivateLanIpv4("192.168.1.5"), true) diff --git a/apps/mobile/packages/uikit/src/utils/lan-discover.ts b/apps/mobile/packages/uikit/src/utils/lan-discover/index.ts similarity index 97% rename from apps/mobile/packages/uikit/src/utils/lan-discover.ts rename to apps/mobile/packages/uikit/src/utils/lan-discover/index.ts index 349cb40..648ce0d 100644 --- a/apps/mobile/packages/uikit/src/utils/lan-discover.ts +++ b/apps/mobile/packages/uikit/src/utils/lan-discover/index.ts @@ -9,7 +9,7 @@ // enters through parameters, so the whole sweep is unit-testable under plain // `node --test` without sockets. -export interface LanCandidate { +export type LanCandidate = { url: string // e.g. http://192.168.1.23:4096 host: string port: number @@ -62,7 +62,7 @@ export function hostsInSubnet24(ipv4: string): string[] { // Minimal fetch surface the probe needs — matches the real Response, so // production passes global fetch and tests pass a stub. -export interface ProbeFetch { +export type ProbeFetch = { (url: string, init?: { headers?: Record; signal?: AbortSignal }): Promise<{ ok: boolean status: number @@ -70,7 +70,7 @@ export interface ProbeFetch { }> } -export interface ProbeOptions { +export type ProbeOptions = { timeoutMs?: number signal?: AbortSignal fetchImpl?: ProbeFetch @@ -112,7 +112,7 @@ export async function probeServer( } } -export interface ScanOptions extends ProbeOptions { +export type ScanOptions = ProbeOptions & { concurrency?: number onCandidate?: (candidate: LanCandidate) => void onProgress?: (scanned: number, total: number) => void diff --git a/apps/mobile/packages/uikit/src/utils/breadcrumbs.test.ts b/apps/mobile/packages/uikit/src/utils/path-utils/__tests__/breadcrumbs.test.ts similarity index 91% rename from apps/mobile/packages/uikit/src/utils/breadcrumbs.test.ts rename to apps/mobile/packages/uikit/src/utils/path-utils/__tests__/breadcrumbs.test.ts index 6365e34..71142d8 100644 --- a/apps/mobile/packages/uikit/src/utils/breadcrumbs.test.ts +++ b/apps/mobile/packages/uikit/src/utils/path-utils/__tests__/breadcrumbs.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { breadcrumbsOf } from "./path-utils.ts" +import { breadcrumbsOf } from "../index.ts" test("breadcrumbsOf: splits absolute path into tappable segments", () => { assert.deepEqual(breadcrumbsOf("/home/user/proj"), [ diff --git a/apps/mobile/packages/uikit/src/utils/path-utils.test.ts b/apps/mobile/packages/uikit/src/utils/path-utils/__tests__/path-utils.test.ts similarity index 97% rename from apps/mobile/packages/uikit/src/utils/path-utils.test.ts rename to apps/mobile/packages/uikit/src/utils/path-utils/__tests__/path-utils.test.ts index 7b50892..6ca0f52 100644 --- a/apps/mobile/packages/uikit/src/utils/path-utils.test.ts +++ b/apps/mobile/packages/uikit/src/utils/path-utils/__tests__/path-utils.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { stripTrailingSlash, parentOf, nameOf } from "./path-utils.ts" +import { stripTrailingSlash, parentOf, nameOf } from "../index.ts" // stripTrailingSlash ------------------------------------------------------- diff --git a/apps/mobile/packages/uikit/src/utils/path-utils.ts b/apps/mobile/packages/uikit/src/utils/path-utils/index.ts similarity index 98% rename from apps/mobile/packages/uikit/src/utils/path-utils.ts rename to apps/mobile/packages/uikit/src/utils/path-utils/index.ts index adf7442..e78a565 100644 --- a/apps/mobile/packages/uikit/src/utils/path-utils.ts +++ b/apps/mobile/packages/uikit/src/utils/path-utils/index.ts @@ -37,7 +37,7 @@ export function nameOf(dir: string): string { return lastSlash >= 0 ? trimmed.slice(lastSlash + 1) || trimmed : trimmed } -export interface Crumb { +export type Crumb = { label: string path: string } diff --git a/apps/mobile/packages/uikit/src/utils/scroll-config.test.ts b/apps/mobile/packages/uikit/src/utils/scroll-config/__tests__/scroll-config.test.ts similarity index 95% rename from apps/mobile/packages/uikit/src/utils/scroll-config.test.ts rename to apps/mobile/packages/uikit/src/utils/scroll-config/__tests__/scroll-config.test.ts index 8e1739e..79d5eaa 100644 --- a/apps/mobile/packages/uikit/src/utils/scroll-config.test.ts +++ b/apps/mobile/packages/uikit/src/utils/scroll-config/__tests__/scroll-config.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { WIDE_CONTENT_SCROLL_CONFIG } from "./scroll-config.ts" +import { WIDE_CONTENT_SCROLL_CONFIG } from "../index.ts" // GitHub issue #21: DiffView + CodeBlock must render wide content in a // horizontally-scrollable container (not wrapped, not truncated). Both diff --git a/apps/mobile/packages/uikit/src/utils/scroll-config.ts b/apps/mobile/packages/uikit/src/utils/scroll-config/index.ts similarity index 95% rename from apps/mobile/packages/uikit/src/utils/scroll-config.ts rename to apps/mobile/packages/uikit/src/utils/scroll-config/index.ts index 16d9338..fe955a1 100644 --- a/apps/mobile/packages/uikit/src/utils/scroll-config.ts +++ b/apps/mobile/packages/uikit/src/utils/scroll-config/index.ts @@ -7,7 +7,7 @@ // one plain object lets that decision be unit-tested with node:test (no React // Native renderer needed) while both components spread the SAME object onto // their ScrollView, so the test and the real components can't drift apart. -export interface HorizontalScrollConfig { +export type HorizontalScrollConfig = { horizontal: true showsHorizontalScrollIndicator: boolean } diff --git a/apps/mobile/packages/uikit/src/utils/session-layout.test.ts b/apps/mobile/packages/uikit/src/utils/session-layout/__tests__/session-layout.test.ts similarity index 98% rename from apps/mobile/packages/uikit/src/utils/session-layout.test.ts rename to apps/mobile/packages/uikit/src/utils/session-layout/__tests__/session-layout.test.ts index fd42a00..a23bfd0 100644 --- a/apps/mobile/packages/uikit/src/utils/session-layout.test.ts +++ b/apps/mobile/packages/uikit/src/utils/session-layout/__tests__/session-layout.test.ts @@ -7,7 +7,7 @@ import { QUESTION_BODY_SCROLL_PROPS, composerMaxHeight, keyboardVerticalOffset, -} from "./session-layout.ts" +} from "../index.ts" test("Android keyboard offset reconciles edge-to-edge screen and window coordinates", () => { assert.equal(keyboardVerticalOffset("android", 48.857), 104.857) diff --git a/apps/mobile/packages/uikit/src/utils/session-layout.ts b/apps/mobile/packages/uikit/src/utils/session-layout/index.ts similarity index 100% rename from apps/mobile/packages/uikit/src/utils/session-layout.ts rename to apps/mobile/packages/uikit/src/utils/session-layout/index.ts diff --git a/apps/mobile/packages/uikit/src/utils/sheet-layout.test.ts b/apps/mobile/packages/uikit/src/utils/sheet-layout/__tests__/sheet-layout.test.ts similarity index 93% rename from apps/mobile/packages/uikit/src/utils/sheet-layout.test.ts rename to apps/mobile/packages/uikit/src/utils/sheet-layout/__tests__/sheet-layout.test.ts index f1a9933..2c16a14 100644 --- a/apps/mobile/packages/uikit/src/utils/sheet-layout.test.ts +++ b/apps/mobile/packages/uikit/src/utils/sheet-layout/__tests__/sheet-layout.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "node:test" import assert from "node:assert/strict" -import { isLandscapeSize, shouldCapSheetContent, SHEET_CONTENT_MAX_WIDTH, sheetContentCap } from "./sheet-layout.ts" +import { isLandscapeSize, shouldCapSheetContent, SHEET_CONTENT_MAX_WIDTH, sheetContentCap } from "../index.ts" describe("sheet-layout", () => { it("detects landscape by strict width > height", () => { diff --git a/apps/mobile/packages/uikit/src/utils/sheet-layout.ts b/apps/mobile/packages/uikit/src/utils/sheet-layout/index.ts similarity index 100% rename from apps/mobile/packages/uikit/src/utils/sheet-layout.ts rename to apps/mobile/packages/uikit/src/utils/sheet-layout/index.ts diff --git a/apps/mobile/src/components/AuthGate.tsx b/apps/mobile/src/components/AuthGate.tsx index c93d250..2243054 100644 --- a/apps/mobile/src/components/AuthGate.tsx +++ b/apps/mobile/src/components/AuthGate.tsx @@ -4,7 +4,7 @@ import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { useAuth } from "@/stores/auth" -interface Props { +type Props = { children: ReactNode } diff --git a/apps/mobile/src/components/ConnectionBadge.tsx b/apps/mobile/src/components/ConnectionBadge.tsx index 4ec027d..12c7690 100644 --- a/apps/mobile/src/components/ConnectionBadge.tsx +++ b/apps/mobile/src/components/ConnectionBadge.tsx @@ -6,7 +6,7 @@ import { useTranslation } from "react-i18next" import { colors } from "@web2bizz/ui-native" import { useConnections } from "@/stores/connections" import { useEvents } from "@/stores/events" -import { HARDCODED_SERVER_URL } from "@/lib/server-config" +import { HARDCODED_SERVER_URL } from "@/utils/server-config" // How often the badge re-validates the server health in the background, so // the dot/text/ping stay fresh without reopening the modal. 30s is a single diff --git a/apps/mobile/src/components/ErrorBoundary.tsx b/apps/mobile/src/components/ErrorBoundary.tsx index 1a6b246..3d3272b 100644 --- a/apps/mobile/src/components/ErrorBoundary.tsx +++ b/apps/mobile/src/components/ErrorBoundary.tsx @@ -9,18 +9,18 @@ import React from "react" import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native" import { colors } from "@web2bizz/ui-native" -import { buildCrashReport, shareReport } from "@/lib/diagnostics" -import { log } from "@/lib/logbuffer" +import { buildCrashReport, shareReport } from "@/utils/diagnostics" +import { log } from "@/utils/logbuffer" // Class component — can't use the useTranslation() hook, so resolve strings // via the shared i18next instance directly (already initialized by the time // this can render, since app/_layout.tsx imports it before mounting). -import i18n from "@/lib/i18n/config" +import i18n from "@/utils/i18n/config" -interface Props { +type Props = { children: React.ReactNode } -interface State { +type State = { error: Error | null componentStack: string | null } diff --git a/apps/mobile/src/components/RepoLinkRow.tsx b/apps/mobile/src/components/RepoLinkRow.tsx index 7c0a39d..67cc377 100644 --- a/apps/mobile/src/components/RepoLinkRow.tsx +++ b/apps/mobile/src/components/RepoLinkRow.tsx @@ -1,6 +1,6 @@ import { View, Text, TouchableOpacity, StyleSheet, Linking } from "react-native" import { Ionicons } from "@expo/vector-icons" -import type { RepoLink, GitProvider } from "@/lib/git-remotes" +import type { RepoLink, GitProvider } from "@/utils/git-remotes" import { colors } from "@web2bizz/ui-native" // Ionicons brand glyph per git host; self-hosted/unknown fall back to a diff --git a/apps/mobile/src/components/UpdateBanner.tsx b/apps/mobile/src/components/UpdateBanner.tsx index 364f1ae..b67bf50 100644 --- a/apps/mobile/src/components/UpdateBanner.tsx +++ b/apps/mobile/src/components/UpdateBanner.tsx @@ -15,7 +15,7 @@ import { View, Text, TouchableOpacity, StyleSheet, Linking } from "react-native" import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { colors } from "@web2bizz/ui-native" -import { checkForUpdate, dismissUpdate, CURRENT_VERSION, type AvailableUpdate } from "@/lib/update-check" +import { checkForUpdate, dismissUpdate, CURRENT_VERSION, type AvailableUpdate } from "@/utils/update-check" export function UpdateBanner({ isDark }: { isDark: boolean }) { const { t } = useTranslation() diff --git a/apps/mobile/src/components/chat/CloneRepoSheet.tsx b/apps/mobile/src/components/chat/CloneRepoSheet.tsx index c969ebd..3ad2a2a 100644 --- a/apps/mobile/src/components/chat/CloneRepoSheet.tsx +++ b/apps/mobile/src/components/chat/CloneRepoSheet.tsx @@ -10,11 +10,11 @@ import BottomSheet, { import { useTranslation } from "react-i18next" import { shouldCapSheetContent, sheetContentCap, SheetHandle } from "@web2bizz/ui-native" import { colors } from "@web2bizz/ui-native" -import { filterMockRepos, type MockRepo } from "@/lib/github-mock" +import { filterMockRepos, type MockRepo } from "@/utils/github-mock" import { useClonedProjects } from "@/stores/cloned-projects" import { useConnections } from "@/stores/connections" -interface Props { +type Props = { // Parent-owned ref — the sheet is UNCONTROLLED (no `visible` prop): the // parent opens it imperatively via expand(), exactly like the folder // sheets and AiSettingsModal. No open/close state of its own. diff --git a/apps/mobile/src/components/container-layout.regression.test.ts b/apps/mobile/src/components/container-layout.regression.test.ts index f3fc5ed..a8dac06 100644 --- a/apps/mobile/src/components/container-layout.regression.test.ts +++ b/apps/mobile/src/components/container-layout.regression.test.ts @@ -50,7 +50,7 @@ test("theme exposes tablet breakpoints and max-width layout tokens", () => { }) test("Container accepts an optional centered maxWidth", () => { - const src = readPackageSource("Container.tsx") + const src = readPackageSource("components/container/index.tsx") assert.match(src, /maxWidth\?:\s*number/, "Container must accept maxWidth?: number") assert.match(src, /alignSelf:\s*"center"/, "maxWidth container must center via alignSelf") assert.doesNotMatch(src, /Не навязывает maxWidth/, "old maxWidth ban docstring must be gone") diff --git a/apps/mobile/src/components/session/ComposerDock.tsx b/apps/mobile/src/components/session/composer-dock/index.tsx similarity index 98% rename from apps/mobile/src/components/session/ComposerDock.tsx rename to apps/mobile/src/components/session/composer-dock/index.tsx index 0706539..5f7ffa9 100644 --- a/apps/mobile/src/components/session/ComposerDock.tsx +++ b/apps/mobile/src/components/session/composer-dock/index.tsx @@ -10,11 +10,11 @@ import { type Attachment, type SlashCommand, } from "@web2bizz/ui-native" -import { MAX_COMPOSER_LENGTH } from "@/lib/composer" +import { MAX_COMPOSER_LENGTH } from "@/utils/composer" import { s } from "@app/session/styles" -import { SUGGESTIONS } from "./EmptyState" +import { SUGGESTIONS } from "../empty-state" -export interface ComposerDockProps { +export type ComposerDockProps = { isDark: boolean keyboardH: number bottomInset: number diff --git a/apps/mobile/src/components/session/EmptyState.tsx b/apps/mobile/src/components/session/empty-state/index.tsx similarity index 99% rename from apps/mobile/src/components/session/EmptyState.tsx rename to apps/mobile/src/components/session/empty-state/index.tsx index 5b00568..9ca09c3 100644 --- a/apps/mobile/src/components/session/EmptyState.tsx +++ b/apps/mobile/src/components/session/empty-state/index.tsx @@ -40,6 +40,4 @@ export function EmptyState({ isDark, onSuggestion }: { isDark: boolean; onSugges {t("session.empty.hint")} ) -} -EOF -echo done \ No newline at end of file +} \ No newline at end of file diff --git a/apps/mobile/src/components/session/index.ts b/apps/mobile/src/components/session/index.ts new file mode 100644 index 0000000..ceb8d78 --- /dev/null +++ b/apps/mobile/src/components/session/index.ts @@ -0,0 +1,7 @@ +export * from "./composer-dock" +export * from "./empty-state" +export * from "./message-list" +export * from "./prompt-overlay" +export * from "./session-banners" +export * from "./session-header" +export * from "./session-sheets" diff --git a/apps/mobile/src/components/session/MessageList.tsx b/apps/mobile/src/components/session/message-list/index.tsx similarity index 97% rename from apps/mobile/src/components/session/MessageList.tsx rename to apps/mobile/src/components/session/message-list/index.tsx index 99d2e77..d7e4be4 100644 --- a/apps/mobile/src/components/session/MessageList.tsx +++ b/apps/mobile/src/components/session/message-list/index.tsx @@ -3,16 +3,16 @@ import { View, Text, FlatList, TouchableOpacity, Pressable, ActivityIndicator } import { Ionicons } from "@expo/vector-icons" import { useTranslation } from "react-i18next" import { MessageBubble, StatusIndicator, type StatusSnapshot } from "@web2bizz/ui-native" -import type { Message, Part } from "@/lib/sdk" +import type { Message, Part } from "@/utils/sdk" import { s } from "@app/session/styles" -import { EmptyState } from "./EmptyState" +import { EmptyState } from "../empty-state" -export interface MessageListItem { +export type MessageListItem = { message: Message parts: Part[] } -export interface MessageListProps { +export type MessageListProps = { messageData: MessageListItem[] status: StatusSnapshot | undefined statusText: string | undefined diff --git a/apps/mobile/src/components/session/PromptOverlay.tsx b/apps/mobile/src/components/session/prompt-overlay/index.tsx similarity index 98% rename from apps/mobile/src/components/session/PromptOverlay.tsx rename to apps/mobile/src/components/session/prompt-overlay/index.tsx index e674a79..ddcc4a8 100644 --- a/apps/mobile/src/components/session/PromptOverlay.tsx +++ b/apps/mobile/src/components/session/prompt-overlay/index.tsx @@ -4,7 +4,7 @@ import { PermissionPrompt, QuestionPrompt } from "@web2bizz/ui-native" import type { PermissionRequest, QuestionRequest } from "@/stores/events" import { s } from "@app/session/styles" -export interface PromptOverlayProps { +export type PromptOverlayProps = { permissions: PermissionRequest[] questions: QuestionRequest[] isDark: boolean diff --git a/apps/mobile/src/components/session/SessionBanners.tsx b/apps/mobile/src/components/session/session-banners/index.tsx similarity index 97% rename from apps/mobile/src/components/session/SessionBanners.tsx rename to apps/mobile/src/components/session/session-banners/index.tsx index ec05248..0dbd707 100644 --- a/apps/mobile/src/components/session/SessionBanners.tsx +++ b/apps/mobile/src/components/session/session-banners/index.tsx @@ -2,7 +2,7 @@ import { View, Text, TouchableOpacity } from "react-native" import type { TFunction } from "i18next" import { s } from "@app/session/styles" -export interface SessionBannersProps { +export type SessionBannersProps = { reconnectAttempts: number showConnectedFlash: boolean revertMessageID: string | undefined diff --git a/apps/mobile/src/components/session/SessionHeader.tsx b/apps/mobile/src/components/session/session-header/index.tsx similarity index 97% rename from apps/mobile/src/components/session/SessionHeader.tsx rename to apps/mobile/src/components/session/session-header/index.tsx index f3b5dc0..5608d22 100644 --- a/apps/mobile/src/components/session/SessionHeader.tsx +++ b/apps/mobile/src/components/session/session-header/index.tsx @@ -4,7 +4,7 @@ import { Stack } from "expo-router" import { Ionicons } from "@expo/vector-icons" import { s } from "@app/session/styles" -export interface SessionHeaderProps { +export type SessionHeaderProps = { title: string showInfo: boolean isDark: boolean diff --git a/apps/mobile/src/components/session/SessionSheets.tsx b/apps/mobile/src/components/session/session-sheets/index.tsx similarity index 94% rename from apps/mobile/src/components/session/SessionSheets.tsx rename to apps/mobile/src/components/session/session-sheets/index.tsx index 07e231d..d7c9b3a 100644 --- a/apps/mobile/src/components/session/SessionSheets.tsx +++ b/apps/mobile/src/components/session/session-sheets/index.tsx @@ -5,11 +5,11 @@ import { MessageQueueSheet, type QueuedItem, } from "@web2bizz/ui-native" -import type { Agent } from "@/lib/sdk" -import type { Provider } from "@/lib/catalog-parse" +import type { Agent } from "@/utils/sdk" +import type { Provider } from "@/utils/catalog-parse" import { s } from "@app/session/styles" -export interface SessionSheetsProps { +export type SessionSheetsProps = { aiSheetRef: React.RefObject queueSheetRef: React.RefObject agents: Agent[] diff --git a/apps/mobile/src/queries/catalog.ts b/apps/mobile/src/shared/api/catalog.ts similarity index 93% rename from apps/mobile/src/queries/catalog.ts rename to apps/mobile/src/shared/api/catalog.ts index 90fda93..58fafb1 100644 --- a/apps/mobile/src/queries/catalog.ts +++ b/apps/mobile/src/shared/api/catalog.ts @@ -9,9 +9,9 @@ // React Query must not own them. import { useQuery } from "@tanstack/react-query" import { useConnections } from "@/stores/connections" -import { queryKeys } from "@/lib/query-keys" -import { parseCatalogResponse, type ParsedCatalog, type RawProviderList } from "@/lib/catalog-parse" -import type { Agent, Command } from "@/lib/sdk" +import { queryKeys } from "@/utils/query-keys" +import { parseCatalogResponse, type ParsedCatalog, type RawProviderList } from "@/utils/catalog-parse" +import type { Agent, Command } from "@/utils/sdk" // Shared fetcher behind both useCatalogData() and the connect-time prefetch // in app/_layout.tsx — reads the current client lazily so it never closes diff --git a/apps/mobile/src/queries/project.ts b/apps/mobile/src/shared/api/project.ts similarity index 96% rename from apps/mobile/src/queries/project.ts rename to apps/mobile/src/shared/api/project.ts index 5d61c3b..438267c 100644 --- a/apps/mobile/src/queries/project.ts +++ b/apps/mobile/src/shared/api/project.ts @@ -7,11 +7,11 @@ // the single source of truth. import { useQuery } from "@tanstack/react-query" import { useConnections } from "@/stores/connections" -import { queryKeys } from "@/lib/query-keys" -import { ApiError, type Project } from "@/lib/sdk" -import { parseGitConfigRemotes, toRepoLinks, type RepoLink } from "@/lib/git-remotes" +import { queryKeys } from "@/utils/query-keys" +import { ApiError, type Project } from "@/utils/sdk" +import { parseGitConfigRemotes, toRepoLinks, type RepoLink } from "@/utils/git-remotes" -export interface ProjectInfo { +export type ProjectInfo = { project: Project | null home: string | null } diff --git a/apps/mobile/src/queries/session-ops.ts b/apps/mobile/src/shared/api/session-ops.ts similarity index 97% rename from apps/mobile/src/queries/session-ops.ts rename to apps/mobile/src/shared/api/session-ops.ts index d322b50..7452859 100644 --- a/apps/mobile/src/queries/session-ops.ts +++ b/apps/mobile/src/shared/api/session-ops.ts @@ -8,13 +8,13 @@ // HTTP response) and message history merging is subscription state, not a // snapshot. See the sessions store. import { useMutation, useQueryClient } from "@tanstack/react-query" -import { ApiError, type Client } from "@/lib/sdk" -import { extractPromptFromParts, type PromptFromParts } from "@/lib/prompt-from-parts" +import { ApiError, type Client } from "@/utils/sdk" +import { extractPromptFromParts, type PromptFromParts } from "@/utils/prompt-from-parts" import { useConnections } from "@/stores/connections" import { useEvents, type PermissionRequest, type QuestionRequest } from "@/stores/events" import { abortedSessions, useSessions } from "@/stores/sessions" -import { queryKeys } from "@/lib/query-keys" -import type { ListedSession } from "@/lib/listed-session" +import { queryKeys } from "@/utils/query-keys" +import type { ListedSession } from "@/utils/listed-session" export type RevertResult = ({ ok: true } & PromptFromParts) | { ok: false; reason: "unsupported" | "auth" | "error" } @@ -110,7 +110,7 @@ export function useUnrevertSession() { }) } -interface ReplyVars { +type ReplyVars = { client: Client sessionID: string requestID: string diff --git a/apps/mobile/src/queries/sessions.ts b/apps/mobile/src/shared/api/sessions.ts similarity index 97% rename from apps/mobile/src/queries/sessions.ts rename to apps/mobile/src/shared/api/sessions.ts index 7b0eebb..cc75c40 100644 --- a/apps/mobile/src/queries/sessions.ts +++ b/apps/mobile/src/shared/api/sessions.ts @@ -13,10 +13,10 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" import { useConnections } from "@/stores/connections" import { useEvents } from "@/stores/events" import { useSessions } from "@/stores/sessions" -import { queryClient } from "@/lib/query-client" -import { queryKeys } from "@/lib/query-keys" -import { mergeSessionLists, type ListedSession } from "@/lib/listed-session" -import type { Client, Session } from "@/lib/sdk" +import { queryClient } from "@/utils/query-client" +import { queryKeys } from "@/utils/query-keys" +import { mergeSessionLists, type ListedSession } from "@/utils/listed-session" +import type { Client, Session } from "@/utils/sdk" async function fetchSessionsList(): Promise { const conn = useConnections.getState() diff --git a/apps/mobile/src/stores/auth.ts b/apps/mobile/src/shared/stores/auth.ts similarity index 98% rename from apps/mobile/src/stores/auth.ts rename to apps/mobile/src/shared/stores/auth.ts index 1f986a4..bb0beb8 100644 --- a/apps/mobile/src/stores/auth.ts +++ b/apps/mobile/src/shared/stores/auth.ts @@ -4,12 +4,12 @@ import * as SecureStore from "expo-secure-store" const AUTH_SETTINGS_KEY = "opencode_auth_settings" -interface AuthSettings { +type AuthSettings = { requireBiometric: boolean requireBiometricForMessages: boolean } -interface AuthState { +type AuthState = { isAuthenticated: boolean isLoading: boolean hasBiometrics: boolean diff --git a/apps/mobile/src/stores/catalog.ts b/apps/mobile/src/shared/stores/catalog.ts similarity index 94% rename from apps/mobile/src/stores/catalog.ts rename to apps/mobile/src/shared/stores/catalog.ts index 523338b..d289c4d 100644 --- a/apps/mobile/src/stores/catalog.ts +++ b/apps/mobile/src/shared/stores/catalog.ts @@ -1,13 +1,13 @@ import { create } from "zustand" -import type { Agent } from "@/lib/sdk" -import { chooseModelSelection } from "@/lib/model-selection" -import { type ParsedCatalog, type Provider, type ProviderModel } from "@/lib/catalog-parse" +import type { Agent } from "@/utils/sdk" +import { chooseModelSelection } from "@/utils/model-selection" +import { type ParsedCatalog, type Provider, type ProviderModel } from "@/utils/catalog-parse" // Re-exported so existing `import type { Provider } from "../stores/catalog"` // call sites (SessionInfo) keep working. export type { Provider, ProviderModel } -interface ModelSelection { +type ModelSelection = { providerID: string modelID: string } @@ -22,7 +22,7 @@ function sameModel(left: ModelSelection | null, right: ModelSelection | null) { // a still-valid user choice and otherwise falls back to connected defaults. // The old fetch-everything load() is gone: screens read lists straight from // the query cache, so the store never holds a second copy of server data. -interface CatalogState { +type CatalogState = { // Current selections agent: string // agent name, e.g. "build" model: ModelSelection | null diff --git a/apps/mobile/src/stores/cloned-projects.ts b/apps/mobile/src/shared/stores/cloned-projects.ts similarity index 89% rename from apps/mobile/src/stores/cloned-projects.ts rename to apps/mobile/src/shared/stores/cloned-projects.ts index 7f9956b..0786ff6 100644 --- a/apps/mobile/src/stores/cloned-projects.ts +++ b/apps/mobile/src/shared/stores/cloned-projects.ts @@ -1,10 +1,10 @@ import { create } from "zustand" -import type { MockRepo } from "@/lib/github-mock" +import type { MockRepo } from "@/utils/github-mock" // UI-only stub. Backend will later replace addCloned() with a real // clone call; the shape { id, name, fullName, path } is kept stable // so screens don't need to change when the backend lands. -export interface ClonedProject { +export type ClonedProject = { id: string name: string fullName: string @@ -12,7 +12,7 @@ export interface ClonedProject { clonedAt: number } -interface ClonedProjectsState { +type ClonedProjectsState = { projects: ClonedProject[] addCloned: (repo: MockRepo, baseDir?: string) => ClonedProject clear: () => void diff --git a/apps/mobile/src/stores/connections.ts b/apps/mobile/src/shared/stores/connections.ts similarity index 98% rename from apps/mobile/src/stores/connections.ts rename to apps/mobile/src/shared/stores/connections.ts index 34c5128..9ef6238 100644 --- a/apps/mobile/src/stores/connections.ts +++ b/apps/mobile/src/shared/stores/connections.ts @@ -1,12 +1,12 @@ import { create } from "zustand" import * as SecureStore from "expo-secure-store" import * as Crypto from "expo-crypto" -import type { ServerConnection, ConnectionType } from "@/lib/types" -import { createClient, type Client } from "@/lib/sdk" -import { buildAuth } from "@/lib/auth" +import type { ServerConnection, ConnectionType } from "@/utils/types" +import { createClient, type Client } from "@/utils/sdk" +import { buildAuth } from "@/utils/auth" import { stripTrailingSlash } from "@web2bizz/ui-native" -import { HARDCODED_SERVER_URL } from "@/lib/server-config" -import { invalidateConnectionScopeQueries } from "@/lib/query-invalidate" +import { HARDCODED_SERVER_URL } from "@/utils/server-config" +import { invalidateConnectionScopeQueries } from "@/utils/query-invalidate" import { useEvents } from "./events" const CONNECTIONS_KEY = "opencode_connections" @@ -21,10 +21,12 @@ const MAX_RECENT_DIRS = 10 const CONNECTION_TEST_TIMEOUT_MS = 12_000 // Cached auth so we can create directory-scoped clients without async SecureStore lookups -interface ClientBase { +type ClientBase = { baseUrl: string auth?: { username: string; password: string } -}interface ConnectionsState { +} + +type ConnectionsState = { connections: ServerConnection[] activeConnection: ServerConnection | null client: Client | null diff --git a/apps/mobile/src/stores/events.ts b/apps/mobile/src/shared/stores/events.ts similarity index 97% rename from apps/mobile/src/stores/events.ts rename to apps/mobile/src/shared/stores/events.ts index 070204f..9610892 100644 --- a/apps/mobile/src/stores/events.ts +++ b/apps/mobile/src/shared/stores/events.ts @@ -1,22 +1,22 @@ import { create } from "zustand" import { useConnections } from "./connections" import { useSessions, abortedSessions } from "./sessions" -import { send as notify } from "@/lib/notifications" -import { sanitizeBody } from "@/lib/notify-format" -import { statusFromPart } from "@/lib/status-labels" -import { recordSuccessfulSession } from "@/lib/store-review" -import { isAuthError } from "@/lib/api-error" -import { isSessionActuallyIdle } from "@/lib/session-status-reconcile" -import { queryClient } from "@/lib/query-client" -import { queryKeys } from "@/lib/query-keys" -import type { ListedSession } from "@/lib/listed-session" -import type { Client, Part, Session, Message } from "@/lib/sdk" +import { send as notify } from "@/utils/notifications" +import { sanitizeBody } from "@/utils/notify-format" +import { statusFromPart } from "@/utils/status-labels" +import { recordSuccessfulSession } from "@/utils/store-review" +import { isAuthError } from "@/utils/api-error" +import { isSessionActuallyIdle } from "@/utils/session-status-reconcile" +import { queryClient } from "@/utils/query-client" +import { queryKeys } from "@/utils/query-keys" +import type { ListedSession } from "@/utils/listed-session" +import type { Client, Part, Session, Message } from "@/utils/sdk" // Session status from the server type SessionStatus = { type: "idle" } | { type: "busy" } | { type: "retry"; attempt: number; message: string } // Pending tool-permission prompt for a session (mirrors the server shape). -export interface PermissionRequest { +export type PermissionRequest = { id: string sessionID: string permission: string @@ -26,7 +26,7 @@ export interface PermissionRequest { } // Pending clarifying question for a session (mirrors the server shape). -export interface QuestionRequest { +export type QuestionRequest = { id: string sessionID: string questions: Array<{ @@ -39,7 +39,7 @@ export interface QuestionRequest { tool?: { messageID: string; callID: string } } -interface EventsState { +type EventsState = { connected: boolean // Set when the last connection attempt failed with 401/403 — the server // rejected our credentials, not a transient network issue. The reconnect diff --git a/apps/mobile/src/stores/sessions.ts b/apps/mobile/src/shared/stores/sessions.ts similarity index 97% rename from apps/mobile/src/stores/sessions.ts rename to apps/mobile/src/shared/stores/sessions.ts index d114902..d323d90 100644 --- a/apps/mobile/src/stores/sessions.ts +++ b/apps/mobile/src/shared/stores/sessions.ts @@ -1,9 +1,9 @@ import { create } from "zustand" -import { type Session, type Message, type Part, type Event, type MessageWithParts, type Client } from "@/lib/sdk" +import { type Session, type Message, type Part, type Event, type MessageWithParts, type Client } from "@/utils/sdk" import { useConnections } from "./connections" import { useSettings } from "./settings" -import { mergeIncomingMessage } from "@/lib/message-merge" -import { applyIncomingParts } from "@/lib/part-merge" +import { mergeIncomingMessage } from "@/utils/message-merge" +import { applyIncomingParts } from "@/utils/part-merge" import { createQueuedDraft, dequeueDraft, @@ -11,12 +11,12 @@ import { removeDraft, updateDraftText, type QueuedDraft, -} from "@/lib/message-queue" -import { pruneRevertedTail } from "@/lib/revert-prune" -import { isColdSessionLoad, isLiveEventForSession } from "@/lib/session-load-reconcile" -import { queryClient } from "@/lib/query-client" -import { queryKeys } from "@/lib/query-keys" -import type { ListedSession } from "@/lib/listed-session" +} from "@/utils/message-queue" +import { pruneRevertedTail } from "@/utils/revert-prune" +import { isColdSessionLoad, isLiveEventForSession } from "@/utils/session-load-reconcile" +import { queryClient } from "@/utils/query-client" +import { queryKeys } from "@/utils/query-keys" +import type { ListedSession } from "@/utils/listed-session" // State split with React Query (see src/queries/): // - React Query owns SERVER SNAPSHOTS: the session list, catalogs, project @@ -44,7 +44,7 @@ function pageSize(): number { return useSettings.getState().pageSize } -interface SessionsState { +type SessionsState = { // The open session, tagged with its origin server — every follow-up op // (prompt/abort/revert/messages) routes through that connection. currentSession: ListedSession | null diff --git a/apps/mobile/src/stores/settings.ts b/apps/mobile/src/shared/stores/settings.ts similarity index 89% rename from apps/mobile/src/stores/settings.ts rename to apps/mobile/src/shared/stores/settings.ts index f0d8a44..d375b02 100644 --- a/apps/mobile/src/stores/settings.ts +++ b/apps/mobile/src/shared/stores/settings.ts @@ -1,13 +1,13 @@ import { create } from "zustand" import * as SecureStore from "expo-secure-store" -import { type Category, defaultPreferences } from "@/lib/notifications" -import { clampPageSize, mergeStoredSettings } from "@/lib/settings-merge" -import { setAppLocale } from "@/lib/i18n/config" -import type { LocalePreference } from "@/lib/i18n/locale-resolve" +import { type Category, defaultPreferences } from "@/utils/notifications" +import { clampPageSize, mergeStoredSettings } from "@/utils/settings-merge" +import { setAppLocale } from "@/utils/i18n/config" +import type { LocalePreference } from "@/utils/i18n/locale-resolve" const SETTINGS_KEY = "opencode_settings" -interface Settings { +type Settings = { pageSize: number notifications: Record locale: LocalePreference @@ -23,7 +23,7 @@ const DEFAULTS: Settings = { lanDiscovery: false, } -interface SettingsState extends Settings { +type SettingsState = Settings & { loaded: boolean load: () => Promise setPageSize: (size: number) => Promise diff --git a/apps/mobile/src/stores/ui.ts b/apps/mobile/src/shared/stores/ui.ts similarity index 93% rename from apps/mobile/src/stores/ui.ts rename to apps/mobile/src/shared/stores/ui.ts index 60714ff..769c520 100644 --- a/apps/mobile/src/stores/ui.ts +++ b/apps/mobile/src/shared/stores/ui.ts @@ -1,6 +1,6 @@ import { create } from "zustand" -interface UiState { +type UiState = { showNewProject: boolean openNewProject: () => void closeNewProject: () => void diff --git a/apps/mobile/src/lib/active-tasks.test.ts b/apps/mobile/src/shared/utils/active-tasks.test.ts similarity index 100% rename from apps/mobile/src/lib/active-tasks.test.ts rename to apps/mobile/src/shared/utils/active-tasks.test.ts diff --git a/apps/mobile/src/lib/active-tasks.ts b/apps/mobile/src/shared/utils/active-tasks.ts similarity index 97% rename from apps/mobile/src/lib/active-tasks.ts rename to apps/mobile/src/shared/utils/active-tasks.ts index 3119991..a54026a 100644 --- a/apps/mobile/src/lib/active-tasks.ts +++ b/apps/mobile/src/shared/utils/active-tasks.ts @@ -14,11 +14,11 @@ // the status/sending maps. Stale entries for unknown session IDs are ignored // here (and separately pruned at the store level — see events.ts // pruneStaleSessionStates / removeSessionState). -export interface TaskStatusLike { +export type TaskStatusLike = { type: string } -export interface SessionLike { +export type SessionLike = { id: string } diff --git a/apps/mobile/src/lib/api-error.test.ts b/apps/mobile/src/shared/utils/api-error.test.ts similarity index 100% rename from apps/mobile/src/lib/api-error.test.ts rename to apps/mobile/src/shared/utils/api-error.test.ts diff --git a/apps/mobile/src/lib/api-error.ts b/apps/mobile/src/shared/utils/api-error.ts similarity index 100% rename from apps/mobile/src/lib/api-error.ts rename to apps/mobile/src/shared/utils/api-error.ts diff --git a/apps/mobile/src/lib/app-version.test.ts b/apps/mobile/src/shared/utils/app-version.test.ts similarity index 90% rename from apps/mobile/src/lib/app-version.test.ts rename to apps/mobile/src/shared/utils/app-version.test.ts index 3e83574..763baaf 100644 --- a/apps/mobile/src/lib/app-version.test.ts +++ b/apps/mobile/src/shared/utils/app-version.test.ts @@ -12,9 +12,9 @@ import path from "node:path" // resolve, so this invariant is checked statically, same pattern as // persisted-keys.test.ts). A second direct `package.json` import in app/ // or src/ would silently fork the source of truth on the next bump. -const ROOT = path.join(import.meta.dirname, "..", "..") +const ROOT = path.join(import.meta.dirname, "..", "..", "..") const APP_DIRS = [path.join(ROOT, "app"), path.join(ROOT, "src")] -const OWNER = path.join("src", "lib", "app-version.ts") +const OWNER = path.join("src", "shared", "utils", "app-version.ts") function sourceFiles(dir: string): string[] { return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { @@ -33,7 +33,7 @@ test("package.json carries a dotted release version", () => { test("app-version.ts re-exports the package.json version", () => { const code = fs.readFileSync(path.join(ROOT, OWNER), "utf8") - assert.match(code, /from "\.\.\/\.\.\/package\.json"/, "must import the root package.json") + assert.match(code, /from "\.\.\/\.\.\/\.\.\/package\.json"/, "must import the root package.json") assert.match(code, /export const APP_VERSION/, "must export APP_VERSION") }) diff --git a/apps/mobile/src/lib/app-version.ts b/apps/mobile/src/shared/utils/app-version.ts similarity index 94% rename from apps/mobile/src/lib/app-version.ts rename to apps/mobile/src/shared/utils/app-version.ts index 7fe7184..8ece4e9 100644 --- a/apps/mobile/src/lib/app-version.ts +++ b/apps/mobile/src/shared/utils/app-version.ts @@ -8,6 +8,6 @@ // // NOTE: intentionally relative — package.json lives at the mobile root, // outside the `@` (= src) and `@app` (= app) alias roots, so no alias covers it. -import pkg from "../../package.json" +import pkg from "../../../package.json" export const APP_VERSION: string = (pkg as { version?: string }).version ?? "unknown" diff --git a/apps/mobile/src/lib/auth.test.ts b/apps/mobile/src/shared/utils/auth.test.ts similarity index 100% rename from apps/mobile/src/lib/auth.test.ts rename to apps/mobile/src/shared/utils/auth.test.ts diff --git a/apps/mobile/src/lib/auth.ts b/apps/mobile/src/shared/utils/auth.ts similarity index 97% rename from apps/mobile/src/lib/auth.ts rename to apps/mobile/src/shared/utils/auth.ts index 005615c..a251899 100644 --- a/apps/mobile/src/lib/auth.ts +++ b/apps/mobile/src/shared/utils/auth.ts @@ -2,7 +2,7 @@ // Extracted from stores/connections.ts so the username-defaulting rule is unit-testable // without pulling in zustand/expo (which have no resolver outside Metro). -export interface BasicAuth { +export type BasicAuth = { username: string password: string } diff --git a/apps/mobile/src/lib/catalog-parse.test.ts b/apps/mobile/src/shared/utils/catalog-parse.test.ts similarity index 100% rename from apps/mobile/src/lib/catalog-parse.test.ts rename to apps/mobile/src/shared/utils/catalog-parse.test.ts diff --git a/apps/mobile/src/lib/catalog-parse.ts b/apps/mobile/src/shared/utils/catalog-parse.ts similarity index 95% rename from apps/mobile/src/lib/catalog-parse.ts rename to apps/mobile/src/shared/utils/catalog-parse.ts index d96009e..4bed798 100644 --- a/apps/mobile/src/lib/catalog-parse.ts +++ b/apps/mobile/src/shared/utils/catalog-parse.ts @@ -6,7 +6,7 @@ // server payload (see chooseModelSelection). import type { Agent, Command } from "./sdk" -export interface ProviderModel { +export type ProviderModel = { id: string name: string reasoning: boolean @@ -15,7 +15,7 @@ export interface ProviderModel { variants?: Record } -export interface Provider { +export type Provider = { id: string name: string connected: boolean @@ -25,13 +25,13 @@ export interface Provider { // Raw GET /provider payload: { all: [...], default: {...}, connected: [...] }. // Typed loosely — older servers may omit fields, and every fetch site already // tolerates nulls (see the queryFn in src/queries/catalog.ts). -export interface RawProviderList { +export type RawProviderList = { all?: unknown default?: Record connected?: unknown } -export interface ParsedCatalog { +export type ParsedCatalog = { agents: Agent[] commands: Command[] providers: Provider[] diff --git a/apps/mobile/src/lib/composer.ts b/apps/mobile/src/shared/utils/composer.ts similarity index 99% rename from apps/mobile/src/lib/composer.ts rename to apps/mobile/src/shared/utils/composer.ts index 66781c7..56edad9 100644 --- a/apps/mobile/src/lib/composer.ts +++ b/apps/mobile/src/shared/utils/composer.ts @@ -33,7 +33,7 @@ async function toJpeg(uri: string, width: number, height: number): Promise string)) => void attachments: Attachment[] diff --git a/apps/mobile/src/lib/demo-script.test.ts b/apps/mobile/src/shared/utils/demo-script.test.ts similarity index 100% rename from apps/mobile/src/lib/demo-script.test.ts rename to apps/mobile/src/shared/utils/demo-script.test.ts diff --git a/apps/mobile/src/lib/demo-script.ts b/apps/mobile/src/shared/utils/demo-script.ts similarity index 98% rename from apps/mobile/src/lib/demo-script.ts rename to apps/mobile/src/shared/utils/demo-script.ts index 9b2ef0d..cd45b70 100644 --- a/apps/mobile/src/lib/demo-script.ts +++ b/apps/mobile/src/shared/utils/demo-script.ts @@ -14,13 +14,13 @@ const ASSISTANT_MESSAGE_ID = "demo-msg-assistant" const COMPLETION_MESSAGE_ID = "demo-msg-completion" const DENIAL_MESSAGE_ID = "demo-msg-denial" -export interface DemoPermission { +export type DemoPermission = { id: string permission: string patterns: string[] } -export interface DemoScript { +export type DemoScript = { messages: [Message, Message] parts: Record permission: DemoPermission diff --git a/apps/mobile/src/lib/diagnostics-classify.test.ts b/apps/mobile/src/shared/utils/diagnostics-classify.test.ts similarity index 100% rename from apps/mobile/src/lib/diagnostics-classify.test.ts rename to apps/mobile/src/shared/utils/diagnostics-classify.test.ts diff --git a/apps/mobile/src/lib/diagnostics-classify.ts b/apps/mobile/src/shared/utils/diagnostics-classify.ts similarity index 98% rename from apps/mobile/src/lib/diagnostics-classify.ts rename to apps/mobile/src/shared/utils/diagnostics-classify.ts index 4eb0c47..042bcf4 100644 --- a/apps/mobile/src/lib/diagnostics-classify.ts +++ b/apps/mobile/src/shared/utils/diagnostics-classify.ts @@ -13,7 +13,7 @@ export type Classification = | "timeout" | "unknown" -export interface ProbeAttempt { +export type ProbeAttempt = { name: string target: string ok: boolean @@ -23,7 +23,7 @@ export interface ProbeAttempt { errorCause?: string } -export interface ParsedUrl { +export type ParsedUrl = { valid: boolean scheme?: string host?: string diff --git a/apps/mobile/src/lib/diagnostics.ts b/apps/mobile/src/shared/utils/diagnostics.ts similarity index 99% rename from apps/mobile/src/lib/diagnostics.ts rename to apps/mobile/src/shared/utils/diagnostics.ts index ec3686a..5bb5f30 100644 --- a/apps/mobile/src/lib/diagnostics.ts +++ b/apps/mobile/src/shared/utils/diagnostics.ts @@ -14,7 +14,7 @@ const PROBE_TIMEOUT_MS = 8_000 // Public 204 endpoints used purely as an "is the internet reachable at all" check. const INTERNET_CHECK_URL = "https://www.gstatic.com/generate_204" -export interface DiagnosticReport { +export type DiagnosticReport = { classification: Classification summary: string url: string diff --git a/apps/mobile/src/lib/git-remotes.test.ts b/apps/mobile/src/shared/utils/git-remotes.test.ts similarity index 100% rename from apps/mobile/src/lib/git-remotes.test.ts rename to apps/mobile/src/shared/utils/git-remotes.test.ts diff --git a/apps/mobile/src/lib/git-remotes.ts b/apps/mobile/src/shared/utils/git-remotes.ts similarity index 98% rename from apps/mobile/src/lib/git-remotes.ts rename to apps/mobile/src/shared/utils/git-remotes.ts index 47aad2a..dc6cc11 100644 --- a/apps/mobile/src/lib/git-remotes.ts +++ b/apps/mobile/src/shared/utils/git-remotes.ts @@ -8,13 +8,13 @@ // https://github.com/owner/repo.git // The UI links out to the https web page, so every form is normalized here. -export interface GitRemote { +export type GitRemote = { name: string url: string } /** One remote with its tappable web URL, provider and display slug. */ -export interface RepoLink extends GitRemote { +export type RepoLink = GitRemote & { webUrl: string provider: GitProvider /** "owner/repo" (or the full nested path for groups/subgroups). */ diff --git a/apps/mobile/src/lib/github-mock.test.ts b/apps/mobile/src/shared/utils/github-mock.test.ts similarity index 100% rename from apps/mobile/src/lib/github-mock.test.ts rename to apps/mobile/src/shared/utils/github-mock.test.ts diff --git a/apps/mobile/src/lib/github-mock.ts b/apps/mobile/src/shared/utils/github-mock.ts similarity index 98% rename from apps/mobile/src/lib/github-mock.ts rename to apps/mobile/src/shared/utils/github-mock.ts index e02a84b..6372517 100644 --- a/apps/mobile/src/lib/github-mock.ts +++ b/apps/mobile/src/shared/utils/github-mock.ts @@ -1,7 +1,7 @@ // UI stub for GitHub clone flow. No backend — static mock data only. // Real list/clone calls will replace filterMockRepos/useMockRepos later. -export interface MockRepo { +export type MockRepo = { id: string name: string fullName: string diff --git a/apps/mobile/src/lib/headers.test.ts b/apps/mobile/src/shared/utils/headers.test.ts similarity index 100% rename from apps/mobile/src/lib/headers.test.ts rename to apps/mobile/src/shared/utils/headers.test.ts diff --git a/apps/mobile/src/lib/headers.ts b/apps/mobile/src/shared/utils/headers.ts similarity index 98% rename from apps/mobile/src/lib/headers.ts rename to apps/mobile/src/shared/utils/headers.ts index 03ae2c5..8c3dbc0 100644 --- a/apps/mobile/src/lib/headers.ts +++ b/apps/mobile/src/shared/utils/headers.ts @@ -4,7 +4,7 @@ // // Relies only on `btoa`, which is available in both Hermes (RN) and Node >= 16. -export interface HeaderConfig { +export type HeaderConfig = { directory?: string auth?: { username: string; password: string } } diff --git a/apps/mobile/src/lib/i18n/catalog-parity.test.ts b/apps/mobile/src/shared/utils/i18n/catalog-parity.test.ts similarity index 100% rename from apps/mobile/src/lib/i18n/catalog-parity.test.ts rename to apps/mobile/src/shared/utils/i18n/catalog-parity.test.ts diff --git a/apps/mobile/src/lib/i18n/config.ts b/apps/mobile/src/shared/utils/i18n/config.ts similarity index 100% rename from apps/mobile/src/lib/i18n/config.ts rename to apps/mobile/src/shared/utils/i18n/config.ts diff --git a/apps/mobile/src/lib/i18n/en.json b/apps/mobile/src/shared/utils/i18n/en.json similarity index 100% rename from apps/mobile/src/lib/i18n/en.json rename to apps/mobile/src/shared/utils/i18n/en.json diff --git a/apps/mobile/src/lib/i18n/locale-resolve.test.ts b/apps/mobile/src/shared/utils/i18n/locale-resolve.test.ts similarity index 100% rename from apps/mobile/src/lib/i18n/locale-resolve.test.ts rename to apps/mobile/src/shared/utils/i18n/locale-resolve.test.ts diff --git a/apps/mobile/src/lib/i18n/locale-resolve.ts b/apps/mobile/src/shared/utils/i18n/locale-resolve.ts similarity index 100% rename from apps/mobile/src/lib/i18n/locale-resolve.ts rename to apps/mobile/src/shared/utils/i18n/locale-resolve.ts diff --git a/apps/mobile/src/lib/i18n/ru.json b/apps/mobile/src/shared/utils/i18n/ru.json similarity index 100% rename from apps/mobile/src/lib/i18n/ru.json rename to apps/mobile/src/shared/utils/i18n/ru.json diff --git a/apps/mobile/src/lib/lan-manual.ts b/apps/mobile/src/shared/utils/lan-manual.ts similarity index 100% rename from apps/mobile/src/lib/lan-manual.ts rename to apps/mobile/src/shared/utils/lan-manual.ts diff --git a/apps/mobile/src/lib/lan-projects.test.ts b/apps/mobile/src/shared/utils/lan-projects.test.ts similarity index 100% rename from apps/mobile/src/lib/lan-projects.test.ts rename to apps/mobile/src/shared/utils/lan-projects.test.ts diff --git a/apps/mobile/src/lib/links.ts b/apps/mobile/src/shared/utils/links.ts similarity index 100% rename from apps/mobile/src/lib/links.ts rename to apps/mobile/src/shared/utils/links.ts diff --git a/apps/mobile/src/lib/listed-session.test.ts b/apps/mobile/src/shared/utils/listed-session.test.ts similarity index 100% rename from apps/mobile/src/lib/listed-session.test.ts rename to apps/mobile/src/shared/utils/listed-session.test.ts diff --git a/apps/mobile/src/lib/listed-session.ts b/apps/mobile/src/shared/utils/listed-session.ts similarity index 96% rename from apps/mobile/src/lib/listed-session.ts rename to apps/mobile/src/shared/utils/listed-session.ts index edf4397..e483c61 100644 --- a/apps/mobile/src/lib/listed-session.ts +++ b/apps/mobile/src/shared/utils/listed-session.ts @@ -5,7 +5,7 @@ import type { Session } from "./sdk" import type { ServerConnection } from "./types" /** A session snapshot tagged with its origin connection. */ -export interface ListedSession extends Session { +export type ListedSession = Session & { connectionId: string } diff --git a/apps/mobile/src/lib/logbuffer.test.ts b/apps/mobile/src/shared/utils/logbuffer.test.ts similarity index 100% rename from apps/mobile/src/lib/logbuffer.test.ts rename to apps/mobile/src/shared/utils/logbuffer.test.ts diff --git a/apps/mobile/src/lib/logbuffer.ts b/apps/mobile/src/shared/utils/logbuffer.ts similarity index 98% rename from apps/mobile/src/lib/logbuffer.ts rename to apps/mobile/src/shared/utils/logbuffer.ts index 6fa0cfe..1cf0ea6 100644 --- a/apps/mobile/src/lib/logbuffer.ts +++ b/apps/mobile/src/shared/utils/logbuffer.ts @@ -3,7 +3,7 @@ export type LogLevel = "debug" | "info" | "warn" | "error" -export interface LogEntry { +export type LogEntry = { ts: number level: LogLevel tag: string diff --git a/apps/mobile/src/lib/message-merge.test.ts b/apps/mobile/src/shared/utils/message-merge.test.ts similarity index 100% rename from apps/mobile/src/lib/message-merge.test.ts rename to apps/mobile/src/shared/utils/message-merge.test.ts diff --git a/apps/mobile/src/lib/message-merge.ts b/apps/mobile/src/shared/utils/message-merge.ts similarity index 100% rename from apps/mobile/src/lib/message-merge.ts rename to apps/mobile/src/shared/utils/message-merge.ts diff --git a/apps/mobile/src/lib/message-queue.test.ts b/apps/mobile/src/shared/utils/message-queue.test.ts similarity index 100% rename from apps/mobile/src/lib/message-queue.test.ts rename to apps/mobile/src/shared/utils/message-queue.test.ts diff --git a/apps/mobile/src/lib/message-queue.ts b/apps/mobile/src/shared/utils/message-queue.ts similarity index 98% rename from apps/mobile/src/lib/message-queue.ts rename to apps/mobile/src/shared/utils/message-queue.ts index a967727..d21390e 100644 --- a/apps/mobile/src/lib/message-queue.ts +++ b/apps/mobile/src/shared/utils/message-queue.ts @@ -3,7 +3,7 @@ // idle — instead of hitting the server concurrently. Pure helpers so the // ordering/removal logic is unit-testable without the Zustand store. -export interface QueuedDraft { +export type QueuedDraft = { id: string text: string createdAt: number diff --git a/apps/mobile/src/lib/model-selection.test.ts b/apps/mobile/src/shared/utils/model-selection.test.ts similarity index 100% rename from apps/mobile/src/lib/model-selection.test.ts rename to apps/mobile/src/shared/utils/model-selection.test.ts diff --git a/apps/mobile/src/lib/model-selection.ts b/apps/mobile/src/shared/utils/model-selection.ts similarity index 94% rename from apps/mobile/src/lib/model-selection.ts rename to apps/mobile/src/shared/utils/model-selection.ts index 1d8e3ee..dc29f1c 100644 --- a/apps/mobile/src/lib/model-selection.ts +++ b/apps/mobile/src/shared/utils/model-selection.ts @@ -1,13 +1,13 @@ -export interface ProviderModelRef { +export type ProviderModelRef = { id: string } -export interface ProviderRef { +export type ProviderRef = { id: string models: ProviderModelRef[] } -export interface ModelSelection { +export type ModelSelection = { providerID: string modelID: string } diff --git a/apps/mobile/src/lib/notifications.ts b/apps/mobile/src/shared/utils/notifications.ts similarity index 99% rename from apps/mobile/src/lib/notifications.ts rename to apps/mobile/src/shared/utils/notifications.ts index 650a794..20a4c61 100644 --- a/apps/mobile/src/lib/notifications.ts +++ b/apps/mobile/src/shared/utils/notifications.ts @@ -75,7 +75,7 @@ export const defaultPreferences: Record = { // Notification payload — what callers pass in // --------------------------------------------------------------------------- -export interface Payload { +export type Payload = { category: Category title: string body: string @@ -85,7 +85,7 @@ export interface Payload { } // Data embedded in the notification for tap handling -interface NotificationData { +type NotificationData = { category: Category sessionId: string } diff --git a/apps/mobile/src/lib/notify-format.test.ts b/apps/mobile/src/shared/utils/notify-format.test.ts similarity index 100% rename from apps/mobile/src/lib/notify-format.test.ts rename to apps/mobile/src/shared/utils/notify-format.test.ts diff --git a/apps/mobile/src/lib/notify-format.ts b/apps/mobile/src/shared/utils/notify-format.ts similarity index 100% rename from apps/mobile/src/lib/notify-format.ts rename to apps/mobile/src/shared/utils/notify-format.ts diff --git a/apps/mobile/src/lib/outbox-flush.ts b/apps/mobile/src/shared/utils/outbox-flush.ts similarity index 98% rename from apps/mobile/src/lib/outbox-flush.ts rename to apps/mobile/src/shared/utils/outbox-flush.ts index a452774..77c757a 100644 --- a/apps/mobile/src/lib/outbox-flush.ts +++ b/apps/mobile/src/shared/utils/outbox-flush.ts @@ -4,7 +4,7 @@ import type { TFunction } from "i18next" import type { QueuedDraft } from "@/stores/sessions" import { useSessions } from "@/stores/sessions" -export interface OutboxFlushParams { +export type OutboxFlushParams = { currentSession: { id: string } | null isSending: boolean queuedForSession: QueuedDraft[] diff --git a/apps/mobile/src/lib/part-merge.test.ts b/apps/mobile/src/shared/utils/part-merge.test.ts similarity index 100% rename from apps/mobile/src/lib/part-merge.test.ts rename to apps/mobile/src/shared/utils/part-merge.test.ts diff --git a/apps/mobile/src/lib/part-merge.ts b/apps/mobile/src/shared/utils/part-merge.ts similarity index 100% rename from apps/mobile/src/lib/part-merge.ts rename to apps/mobile/src/shared/utils/part-merge.ts diff --git a/apps/mobile/src/lib/persisted-keys.test.ts b/apps/mobile/src/shared/utils/persisted-keys.test.ts similarity index 100% rename from apps/mobile/src/lib/persisted-keys.test.ts rename to apps/mobile/src/shared/utils/persisted-keys.test.ts diff --git a/apps/mobile/src/lib/prompt-from-parts.test.ts b/apps/mobile/src/shared/utils/prompt-from-parts.test.ts similarity index 100% rename from apps/mobile/src/lib/prompt-from-parts.test.ts rename to apps/mobile/src/shared/utils/prompt-from-parts.test.ts diff --git a/apps/mobile/src/lib/prompt-from-parts.ts b/apps/mobile/src/shared/utils/prompt-from-parts.ts similarity index 94% rename from apps/mobile/src/lib/prompt-from-parts.ts rename to apps/mobile/src/shared/utils/prompt-from-parts.ts index a9a7b71..e4c3b96 100644 --- a/apps/mobile/src/lib/prompt-from-parts.ts +++ b/apps/mobile/src/shared/utils/prompt-from-parts.ts @@ -4,7 +4,7 @@ // dependency-free so it's testable under plain `node --test`. import type { Part } from "./sdk" -export interface PromptFromParts { +export type PromptFromParts = { text: string files: Part[] } diff --git a/apps/mobile/src/lib/query-client.ts b/apps/mobile/src/shared/utils/query-client.ts similarity index 100% rename from apps/mobile/src/lib/query-client.ts rename to apps/mobile/src/shared/utils/query-client.ts diff --git a/apps/mobile/src/lib/query-invalidate.ts b/apps/mobile/src/shared/utils/query-invalidate.ts similarity index 100% rename from apps/mobile/src/lib/query-invalidate.ts rename to apps/mobile/src/shared/utils/query-invalidate.ts diff --git a/apps/mobile/src/lib/query-keys.test.ts b/apps/mobile/src/shared/utils/query-keys.test.ts similarity index 100% rename from apps/mobile/src/lib/query-keys.test.ts rename to apps/mobile/src/shared/utils/query-keys.test.ts diff --git a/apps/mobile/src/lib/query-keys.ts b/apps/mobile/src/shared/utils/query-keys.ts similarity index 100% rename from apps/mobile/src/lib/query-keys.ts rename to apps/mobile/src/shared/utils/query-keys.ts diff --git a/apps/mobile/src/lib/reconnect-flash.ts b/apps/mobile/src/shared/utils/reconnect-flash.ts similarity index 100% rename from apps/mobile/src/lib/reconnect-flash.ts rename to apps/mobile/src/shared/utils/reconnect-flash.ts diff --git a/apps/mobile/src/lib/revert-flow.ts b/apps/mobile/src/shared/utils/revert-flow.ts similarity index 96% rename from apps/mobile/src/lib/revert-flow.ts rename to apps/mobile/src/shared/utils/revert-flow.ts index eb7298a..e7fcb0d 100644 --- a/apps/mobile/src/lib/revert-flow.ts +++ b/apps/mobile/src/shared/utils/revert-flow.ts @@ -1,9 +1,9 @@ import { useCallback } from "react" import { Alert } from "react-native" import type { TFunction } from "i18next" -import type { RevertResult } from "@/queries/session-ops" +import type { RevertResult } from "@/api/session-ops" -export interface RevertFlowDeps { +export type RevertFlowDeps = { t: TFunction revertMutation: { mutateAsync: (id: string) => Promise } setInput: (v: string) => void diff --git a/apps/mobile/src/lib/revert-prune.test.ts b/apps/mobile/src/shared/utils/revert-prune.test.ts similarity index 100% rename from apps/mobile/src/lib/revert-prune.test.ts rename to apps/mobile/src/shared/utils/revert-prune.test.ts diff --git a/apps/mobile/src/lib/revert-prune.ts b/apps/mobile/src/shared/utils/revert-prune.ts similarity index 100% rename from apps/mobile/src/lib/revert-prune.ts rename to apps/mobile/src/shared/utils/revert-prune.ts diff --git a/apps/mobile/src/lib/sdk.ts b/apps/mobile/src/shared/utils/sdk.ts similarity index 98% rename from apps/mobile/src/lib/sdk.ts rename to apps/mobile/src/shared/utils/sdk.ts index 705547d..8d5e9b6 100644 --- a/apps/mobile/src/lib/sdk.ts +++ b/apps/mobile/src/shared/utils/sdk.ts @@ -11,7 +11,7 @@ import type { FileRoot } from "@web2bizz/ui-native" export { ApiAuthError, isAuthError } from "./api-error" -export interface ClientConfig { +export type ClientConfig = { baseUrl: string directory?: string auth?: { @@ -20,7 +20,7 @@ export interface ClientConfig { } } -export interface Session { +export type Session = { id: string slug: string projectID: string @@ -49,7 +49,7 @@ export interface Session { } } -export interface Message { +export type Message = { id: string sessionID: string role: "user" | "assistant" @@ -76,12 +76,12 @@ export interface Message { } // API returns messages with parts embedded -export interface MessageWithParts { +export type MessageWithParts = { info: Message parts: Part[] } -export interface Part { +export type Part = { id: string sessionID?: string messageID: string @@ -119,7 +119,7 @@ export interface Part { filename?: string } -export interface Agent { +export type Agent = { name: string description?: string mode: "subagent" | "primary" | "all" @@ -134,7 +134,7 @@ export interface Agent { steps?: number } -export interface Command { +export type Command = { name: string description?: string agent?: string @@ -145,7 +145,7 @@ export interface Command { hints: string[] } -export interface Project { +export type Project = { id: string name?: string path: { @@ -155,7 +155,7 @@ export interface Project { } } -export interface FileEntry { +export type FileEntry = { name: string path: string absolute: string @@ -166,17 +166,17 @@ export interface FileEntry { // GET /file/content — mirrors upstream FileRead. Throws ApiError (404 when // the server build lacks the route or the path doesn't exist), so callers // that treat "no file" as empty must catch, like file.roots() does. -export interface FileContent { +export type FileContent = { type: "text" | "binary" content: string } -export interface Event { +export type Event = { type: string properties: Record } -export interface HealthResponse { +export type HealthResponse = { healthy: boolean version: string } diff --git a/apps/mobile/src/lib/server-config.ts b/apps/mobile/src/shared/utils/server-config.ts similarity index 100% rename from apps/mobile/src/lib/server-config.ts rename to apps/mobile/src/shared/utils/server-config.ts diff --git a/apps/mobile/src/lib/session-alerts.ts b/apps/mobile/src/shared/utils/session-alerts.ts similarity index 100% rename from apps/mobile/src/lib/session-alerts.ts rename to apps/mobile/src/shared/utils/session-alerts.ts diff --git a/apps/mobile/src/lib/session-binding.ts b/apps/mobile/src/shared/utils/session-binding.ts similarity index 100% rename from apps/mobile/src/lib/session-binding.ts rename to apps/mobile/src/shared/utils/session-binding.ts diff --git a/apps/mobile/src/lib/session-grouping.test.ts b/apps/mobile/src/shared/utils/session-grouping.test.ts similarity index 100% rename from apps/mobile/src/lib/session-grouping.test.ts rename to apps/mobile/src/shared/utils/session-grouping.test.ts diff --git a/apps/mobile/src/lib/session-grouping.ts b/apps/mobile/src/shared/utils/session-grouping.ts similarity index 96% rename from apps/mobile/src/lib/session-grouping.ts rename to apps/mobile/src/shared/utils/session-grouping.ts index 7f801ac..3970bf5 100644 --- a/apps/mobile/src/lib/session-grouping.ts +++ b/apps/mobile/src/shared/utils/session-grouping.ts @@ -2,7 +2,7 @@ // No React Native imports — unit-testable with node --test. /** A contiguous-by-directory bucket of items, in first-seen order. */ -export interface DirectoryGroup { +export type DirectoryGroup = { directory: string items: T[] } @@ -32,7 +32,7 @@ export function groupByDirectory(items: T[]): D /** A project card bucket: one directory on ONE server. Same path on two * servers is two cards (keyed by connection), never merged. */ -export interface ProjectGroup { +export type ProjectGroup = { key: string directory: string connectionId: string diff --git a/apps/mobile/src/lib/session-list.integration.test.ts b/apps/mobile/src/shared/utils/session-list.integration.test.ts similarity index 98% rename from apps/mobile/src/lib/session-list.integration.test.ts rename to apps/mobile/src/shared/utils/session-list.integration.test.ts index 2858370..906f554 100644 --- a/apps/mobile/src/lib/session-list.integration.test.ts +++ b/apps/mobile/src/shared/utils/session-list.integration.test.ts @@ -11,7 +11,7 @@ import { test, before, after } from "node:test" import assert from "node:assert/strict" -import { createMockOpencodeServer } from "../../tests/fixtures/mock-opencode-server.ts" +import { createMockOpencodeServer } from "../../../tests/fixtures/mock-opencode-server.ts" import { loadSessionList, legacySessionQuery, type SessionListTransport } from "./session-list.ts" const PORT = 45071 diff --git a/apps/mobile/src/lib/session-list.test.ts b/apps/mobile/src/shared/utils/session-list.test.ts similarity index 100% rename from apps/mobile/src/lib/session-list.test.ts rename to apps/mobile/src/shared/utils/session-list.test.ts diff --git a/apps/mobile/src/lib/session-list.ts b/apps/mobile/src/shared/utils/session-list.ts similarity index 97% rename from apps/mobile/src/lib/session-list.ts rename to apps/mobile/src/shared/utils/session-list.ts index 051e2e1..a303068 100644 --- a/apps/mobile/src/lib/session-list.ts +++ b/apps/mobile/src/shared/utils/session-list.ts @@ -10,13 +10,13 @@ // 404 (older servers without the experimental route). import type { Session } from "./sdk" -export interface SessionListParams { +export type SessionListParams = { roots?: boolean limit?: number search?: string } -export interface SessionListTransport { +export type SessionListTransport = { // GET /experimental/session with NO query params — the server applies `limit` // BEFORE we can filter to roots, so limiting server-side would truncate the // pool and yield too few root sessions. We fetch the full global list and diff --git a/apps/mobile/src/lib/session-load-reconcile.test.ts b/apps/mobile/src/shared/utils/session-load-reconcile.test.ts similarity index 100% rename from apps/mobile/src/lib/session-load-reconcile.test.ts rename to apps/mobile/src/shared/utils/session-load-reconcile.test.ts diff --git a/apps/mobile/src/lib/session-load-reconcile.ts b/apps/mobile/src/shared/utils/session-load-reconcile.ts similarity index 100% rename from apps/mobile/src/lib/session-load-reconcile.ts rename to apps/mobile/src/shared/utils/session-load-reconcile.ts diff --git a/apps/mobile/src/lib/session-status-reconcile.test.ts b/apps/mobile/src/shared/utils/session-status-reconcile.test.ts similarity index 100% rename from apps/mobile/src/lib/session-status-reconcile.test.ts rename to apps/mobile/src/shared/utils/session-status-reconcile.test.ts diff --git a/apps/mobile/src/lib/session-status-reconcile.ts b/apps/mobile/src/shared/utils/session-status-reconcile.ts similarity index 100% rename from apps/mobile/src/lib/session-status-reconcile.ts rename to apps/mobile/src/shared/utils/session-status-reconcile.ts diff --git a/apps/mobile/src/shared/utils/session/index.ts b/apps/mobile/src/shared/utils/session/index.ts new file mode 100644 index 0000000..7c3ac54 --- /dev/null +++ b/apps/mobile/src/shared/utils/session/index.ts @@ -0,0 +1,2 @@ +export * from "../session-binding" +export * from "../use-session-screen" diff --git a/apps/mobile/src/lib/settings-merge.test.ts b/apps/mobile/src/shared/utils/settings-merge.test.ts similarity index 100% rename from apps/mobile/src/lib/settings-merge.test.ts rename to apps/mobile/src/shared/utils/settings-merge.test.ts diff --git a/apps/mobile/src/lib/settings-merge.ts b/apps/mobile/src/shared/utils/settings-merge.ts similarity index 100% rename from apps/mobile/src/lib/settings-merge.ts rename to apps/mobile/src/shared/utils/settings-merge.ts diff --git a/apps/mobile/src/lib/slash-state.ts b/apps/mobile/src/shared/utils/slash-state.ts similarity index 98% rename from apps/mobile/src/lib/slash-state.ts rename to apps/mobile/src/shared/utils/slash-state.ts index cd8e598..e910933 100644 --- a/apps/mobile/src/lib/slash-state.ts +++ b/apps/mobile/src/shared/utils/slash-state.ts @@ -2,7 +2,7 @@ import { useState, useMemo, useCallback } from "react" import { useRouter } from "expo-router" import type { SlashCommand } from "@web2bizz/ui-native" -export interface ServerCommand { +export type ServerCommand = { name: string description?: string } diff --git a/apps/mobile/src/lib/speech.ts b/apps/mobile/src/shared/utils/speech.ts similarity index 98% rename from apps/mobile/src/lib/speech.ts rename to apps/mobile/src/shared/utils/speech.ts index 4c3da69..342cb66 100644 --- a/apps/mobile/src/lib/speech.ts +++ b/apps/mobile/src/shared/utils/speech.ts @@ -31,13 +31,13 @@ function recognitionLang(): string { } } -interface SpeechState { +type SpeechState = { listening: boolean transcript: string error: string | null } -interface SpeechActions { +type SpeechActions = { start: () => Promise stop: () => void cancel: () => void diff --git a/apps/mobile/src/lib/sse.test.ts b/apps/mobile/src/shared/utils/sse.test.ts similarity index 100% rename from apps/mobile/src/lib/sse.test.ts rename to apps/mobile/src/shared/utils/sse.test.ts diff --git a/apps/mobile/src/lib/sse.ts b/apps/mobile/src/shared/utils/sse.ts similarity index 100% rename from apps/mobile/src/lib/sse.ts rename to apps/mobile/src/shared/utils/sse.ts diff --git a/apps/mobile/src/lib/status-labels.test.ts b/apps/mobile/src/shared/utils/status-labels.test.ts similarity index 100% rename from apps/mobile/src/lib/status-labels.test.ts rename to apps/mobile/src/shared/utils/status-labels.test.ts diff --git a/apps/mobile/src/lib/status-labels.ts b/apps/mobile/src/shared/utils/status-labels.ts similarity index 100% rename from apps/mobile/src/lib/status-labels.ts rename to apps/mobile/src/shared/utils/status-labels.ts diff --git a/apps/mobile/src/lib/store-review-policy.test.ts b/apps/mobile/src/shared/utils/store-review-policy.test.ts similarity index 100% rename from apps/mobile/src/lib/store-review-policy.test.ts rename to apps/mobile/src/shared/utils/store-review-policy.test.ts diff --git a/apps/mobile/src/lib/store-review-policy.ts b/apps/mobile/src/shared/utils/store-review-policy.ts similarity index 100% rename from apps/mobile/src/lib/store-review-policy.ts rename to apps/mobile/src/shared/utils/store-review-policy.ts diff --git a/apps/mobile/src/lib/store-review.ts b/apps/mobile/src/shared/utils/store-review.ts similarity index 100% rename from apps/mobile/src/lib/store-review.ts rename to apps/mobile/src/shared/utils/store-review.ts diff --git a/apps/mobile/src/lib/types.ts b/apps/mobile/src/shared/utils/types.ts similarity index 94% rename from apps/mobile/src/lib/types.ts rename to apps/mobile/src/shared/utils/types.ts index a3856e7..f035652 100644 --- a/apps/mobile/src/lib/types.ts +++ b/apps/mobile/src/shared/utils/types.ts @@ -1,7 +1,7 @@ // Connection types for multiple server support export type ConnectionType = "local" | "tunnel" | "cloud" -export interface ServerConnection { +export type ServerConnection = { id: string name: string type: ConnectionType @@ -22,7 +22,7 @@ export interface ServerConnection { discoveredOnLan?: boolean } -export interface AppSettings { +export type AppSettings = { // Require biometric auth to open app requireBiometric: boolean // Require biometric to send messages diff --git a/apps/mobile/src/lib/update-check-policy.test.ts b/apps/mobile/src/shared/utils/update-check-policy.test.ts similarity index 100% rename from apps/mobile/src/lib/update-check-policy.test.ts rename to apps/mobile/src/shared/utils/update-check-policy.test.ts diff --git a/apps/mobile/src/lib/update-check-policy.ts b/apps/mobile/src/shared/utils/update-check-policy.ts similarity index 100% rename from apps/mobile/src/lib/update-check-policy.ts rename to apps/mobile/src/shared/utils/update-check-policy.ts diff --git a/apps/mobile/src/lib/update-check.ts b/apps/mobile/src/shared/utils/update-check.ts similarity index 100% rename from apps/mobile/src/lib/update-check.ts rename to apps/mobile/src/shared/utils/update-check.ts diff --git a/apps/mobile/src/lib/use-ai-sheet.ts b/apps/mobile/src/shared/utils/use-ai-sheet.ts similarity index 100% rename from apps/mobile/src/lib/use-ai-sheet.ts rename to apps/mobile/src/shared/utils/use-ai-sheet.ts diff --git a/apps/mobile/src/lib/use-keyboard-dock.ts b/apps/mobile/src/shared/utils/use-keyboard-dock.ts similarity index 99% rename from apps/mobile/src/lib/use-keyboard-dock.ts rename to apps/mobile/src/shared/utils/use-keyboard-dock.ts index 43e4a75..e8dff4c 100644 --- a/apps/mobile/src/lib/use-keyboard-dock.ts +++ b/apps/mobile/src/shared/utils/use-keyboard-dock.ts @@ -3,7 +3,7 @@ import { Keyboard, Platform, useWindowDimensions } from "react-native" import { useSafeAreaInsets } from "react-native-safe-area-context" import { composerMaxHeight, COMPOSER_MIN_HEIGHT } from "@web2bizz/ui-native" -export interface KeyboardDock { +export type KeyboardDock = { keyboardY: number | null keyboardH: number dockHeight: number diff --git a/apps/mobile/src/lib/use-session-prompts.ts b/apps/mobile/src/shared/utils/use-session-prompts.ts similarity index 98% rename from apps/mobile/src/lib/use-session-prompts.ts rename to apps/mobile/src/shared/utils/use-session-prompts.ts index 5960457..dc87e29 100644 --- a/apps/mobile/src/lib/use-session-prompts.ts +++ b/apps/mobile/src/shared/utils/use-session-prompts.ts @@ -2,7 +2,7 @@ import { Alert } from "react-native" import type { TFunction } from "i18next" import type { Client } from "./sdk" -export interface SessionPromptDeps { +export type SessionPromptDeps = { sessionClient: Client | null sessionID: string | undefined permissionMutation: { diff --git a/apps/mobile/src/lib/use-session-screen.ts b/apps/mobile/src/shared/utils/use-session-screen.ts similarity index 97% rename from apps/mobile/src/lib/use-session-screen.ts rename to apps/mobile/src/shared/utils/use-session-screen.ts index 47ea3e5..d6a951e 100644 --- a/apps/mobile/src/lib/use-session-screen.ts +++ b/apps/mobile/src/shared/utils/use-session-screen.ts @@ -8,7 +8,7 @@ import { useAuth } from "@/stores/auth" import { useEvents, type PermissionRequest, type QuestionRequest } from "@/stores/events" import { useConnections } from "@/stores/connections" import { useCatalog } from "@/stores/catalog" -import { useCatalogData } from "@/queries/catalog" +import { useCatalogData } from "@/api/catalog" import { useComposer } from "./composer" import { useRevertFlow } from "./revert-flow" import { useSessionAlerts } from "./session-alerts" @@ -27,19 +27,21 @@ import { usePermissionReply, useQuestionReply, useQuestionReject, -} from "@/queries/session-ops" +} from "@/api/session-ops" import type { Agent, Client, Message, Part } from "./sdk" import type { Provider } from "./catalog-parse" import type { ListedSession } from "./listed-session" import type { StatusSnapshot } from "@web2bizz/ui-native" -import type { SessionHeaderProps } from "@/components/session/SessionHeader" -import type { SessionBannersProps } from "@/components/session/SessionBanners" -import type { MessageListProps } from "@/components/session/MessageList" -import type { ComposerDockProps } from "@/components/session/ComposerDock" -import type { PromptOverlayProps } from "@/components/session/PromptOverlay" -import type { SessionSheetsProps } from "@/components/session/SessionSheets" - -export interface SessionScreenData { +import type { + SessionHeaderProps, + SessionBannersProps, + MessageListProps, + ComposerDockProps, + PromptOverlayProps, + SessionSheetsProps, +} from "@/components/session" + +export type SessionScreenData = { currentSession: ListedSession | null messages: Message[] parts: Record @@ -270,7 +272,7 @@ export function useSessionScreenData(): SessionScreenData { } // Props SessionInfo (uikit): структурный тип для группы info контроллера. -export interface SessionInfoProps { +export type SessionInfoProps = { session: ListedSession | null messages: Message[] providers: Provider[] @@ -283,7 +285,7 @@ export interface SessionInfoProps { onClose: () => void } -export interface SessionController { +export type SessionController = { isLoading: boolean hasActivePrompt: boolean header: SessionHeaderProps diff --git a/apps/mobile/src/lib/use-session-send.ts b/apps/mobile/src/shared/utils/use-session-send.ts similarity index 99% rename from apps/mobile/src/lib/use-session-send.ts rename to apps/mobile/src/shared/utils/use-session-send.ts index 10afd09..0a2a4bb 100644 --- a/apps/mobile/src/lib/use-session-send.ts +++ b/apps/mobile/src/shared/utils/use-session-send.ts @@ -6,7 +6,7 @@ import type { ListedSession } from "./listed-session" import type { ServerCommand } from "./slash-state" import type { QueuedDraft } from "@/stores/sessions" -export interface SessionSendParams { +export type SessionSendParams = { input: string attachments: Attachment[] setAttachments: (v: Attachment[] | ((prev: Attachment[]) => Attachment[])) => void diff --git a/apps/mobile/src/lib/waitlist-queue-storage.ts b/apps/mobile/src/shared/utils/waitlist-queue-storage.ts similarity index 100% rename from apps/mobile/src/lib/waitlist-queue-storage.ts rename to apps/mobile/src/shared/utils/waitlist-queue-storage.ts diff --git a/apps/mobile/src/lib/waitlist-queue.test.ts b/apps/mobile/src/shared/utils/waitlist-queue.test.ts similarity index 100% rename from apps/mobile/src/lib/waitlist-queue.test.ts rename to apps/mobile/src/shared/utils/waitlist-queue.test.ts diff --git a/apps/mobile/src/lib/waitlist.test.ts b/apps/mobile/src/shared/utils/waitlist.test.ts similarity index 100% rename from apps/mobile/src/lib/waitlist.test.ts rename to apps/mobile/src/shared/utils/waitlist.test.ts diff --git a/apps/mobile/src/lib/waitlist.ts b/apps/mobile/src/shared/utils/waitlist.ts similarity index 99% rename from apps/mobile/src/lib/waitlist.ts rename to apps/mobile/src/shared/utils/waitlist.ts index 375d4a1..62031cf 100644 --- a/apps/mobile/src/lib/waitlist.ts +++ b/apps/mobile/src/shared/utils/waitlist.ts @@ -78,7 +78,7 @@ type FetchLike = ( init: { method: string; headers: Record; body: string; signal: AbortSignal }, ) => Promise<{ ok: boolean; status: number; json(): Promise }> -export interface WaitlistDeps { +export type WaitlistDeps = { fetchFn?: FetchLike timeoutMs?: number } @@ -161,7 +161,7 @@ export const WAITLIST_QUEUE_ATTEMPTS_BEFORE_MANUAL = 3 /** Entries older than this are dropped: the address is stale, the user moved on. */ export const WAITLIST_QUEUE_TTL_MS = 30 * 24 * 60 * 60 * 1000 // 30 days -export interface QueuedSignup { +export type QueuedSignup = { /** Already normalized (trimmed/lowercased) by normalizeWaitlistEmail. */ email: string /** Epoch ms of the first attempt. */ @@ -179,7 +179,7 @@ export interface QueuedSignup { * plain Map in tests. Deliberately not typed against AsyncStorage so this file * stays importable by `node --test`. */ -export interface QueueStorage { +export type QueueStorage = { getItem(key: string): Promise setItem(key: string, value: string): Promise removeItem(key: string): Promise @@ -282,7 +282,7 @@ export async function removeFromQueue(storage: QueueStorage, email: string): Pro } } -export interface FlushOutcome { +export type FlushOutcome = { /** Entries that reached the server (Brevo list 4). */ synced: string[] /** Entries the server permanently rejected (4xx) — dropped, retrying can't help. */ diff --git a/apps/mobile/tsconfig.json b/apps/mobile/tsconfig.json index 465f651..89c0882 100644 --- a/apps/mobile/tsconfig.json +++ b/apps/mobile/tsconfig.json @@ -5,6 +5,14 @@ "types": ["node"], "paths": { "@/*": ["./src/*"], + "@/utils/*": ["./src/shared/utils/*"], + "@/api/*": ["./src/shared/api/*"], + "@/stores/*": ["./src/shared/stores/*"], + "@/shared/*": ["./src/shared/*"], + "@shared/*": ["./src/shared/*"], + "@utils/*": ["./src/shared/utils/*"], + "@api/*": ["./src/shared/api/*"], + "@stores/*": ["./src/shared/stores/*"], "@app/*": ["./app/*"], "@web2bizz/ui-native": ["./packages/uikit/src/index.ts"], "@web2bizz/ui-native/*": ["./packages/uikit/src/*"], From 5ae441fcfe9dd3e068e4b4309447fd98179a752d Mon Sep 17 00:00:00 2001 From: alwoo Date: Tue, 20 Oct 2026 01:30:34 +0400 Subject: [PATCH 010/315] refactor(frontend): migrate data hooks to react-query with shared query keys --- apps/frontend/app/(auth)/layout.tsx | 2 +- apps/frontend/app/(auth)/login/page.test.tsx | 4 +- apps/frontend/app/(auth)/login/page.tsx | 12 +- .../app/(dashboard)/ai-providers/page.tsx | 10 +- apps/frontend/app/(dashboard)/chat/layout.tsx | 4 +- apps/frontend/app/(dashboard)/layout.tsx | 2 +- .../(dashboard)/organizations/[id]/page.tsx | 18 +- .../organizations/invites/accept/page.tsx | 6 +- .../app/(dashboard)/organizations/page.tsx | 8 +- .../frontend/app/(dashboard)/profile/page.tsx | 273 +--------------- .../app/(dashboard)/projects/[id]/page.tsx | 10 +- .../[id]/sessions/[sessionId]/page.tsx | 12 +- .../app/(dashboard)/projects/page.tsx | 10 +- .../app/(dashboard)/registry/docker/page.tsx | 8 +- .../app/(dashboard)/registry/npm/page.tsx | 8 +- .../app/(dashboard)/registry/page.tsx | 4 +- .../frontend/app/(dashboard)/secrets/page.tsx | 6 +- .../app/(dashboard)/users/[id]/page.tsx | 6 +- apps/frontend/app/error.tsx | 4 +- apps/frontend/app/layout.tsx | 6 +- apps/frontend/app/loading.tsx | 2 +- apps/frontend/next-env.d.ts | 4 +- apps/frontend/src/api/client.ts | 44 ++- .../__tests__/profile-dropdown.test.tsx | 23 +- .../usage/__tests__/usage-status.test.ts | 122 +++++++ .../src/features/usage/api-key-dialog.tsx | 163 ++++++++++ .../src/features/usage/usage-section.tsx | 135 ++++++++ .../src/features/usage/usage-status.ts | 84 +++++ .../src/hooks/__tests__/query-keys.test.ts | 66 ++++ .../hooks/__tests__/useAiProviders.test.tsx | 283 ++++++++++++++++ .../src/hooks/__tests__/useNpm.test.tsx | 87 ++++- .../src/hooks/__tests__/useProfile.test.tsx | 302 ++++++++++++++++++ .../hooks/__tests__/useRegistries.test.tsx | 89 +++++- .../src/hooks/__tests__/useUsage.test.tsx | 301 +++++++++++++++++ apps/frontend/src/hooks/query-keys.ts | 44 +++ apps/frontend/src/hooks/useAiProviders.ts | 188 ++++++----- apps/frontend/src/hooks/useNpm.ts | 122 +++---- apps/frontend/src/hooks/useProfile.ts | 281 ++++++++-------- apps/frontend/src/hooks/useRegistries.ts | 123 +++---- apps/frontend/src/hooks/useUsage.ts | 221 +++++-------- 40 files changed, 2257 insertions(+), 840 deletions(-) create mode 100644 apps/frontend/src/features/usage/__tests__/usage-status.test.ts create mode 100644 apps/frontend/src/features/usage/api-key-dialog.tsx create mode 100644 apps/frontend/src/features/usage/usage-section.tsx create mode 100644 apps/frontend/src/features/usage/usage-status.ts create mode 100644 apps/frontend/src/hooks/__tests__/query-keys.test.ts create mode 100644 apps/frontend/src/hooks/__tests__/useAiProviders.test.tsx create mode 100644 apps/frontend/src/hooks/__tests__/useProfile.test.tsx create mode 100644 apps/frontend/src/hooks/__tests__/useUsage.test.tsx create mode 100644 apps/frontend/src/hooks/query-keys.ts diff --git a/apps/frontend/app/(auth)/layout.tsx b/apps/frontend/app/(auth)/layout.tsx index 490cbe5..66c8006 100644 --- a/apps/frontend/app/(auth)/layout.tsx +++ b/apps/frontend/app/(auth)/layout.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from 'react'; -import { AuthHeader } from '../../src/components/auth-header'; +import { AuthHeader } from '@/components/auth-header'; /** * Route-group layout for (auth): flat URL /login. diff --git a/apps/frontend/app/(auth)/login/page.test.tsx b/apps/frontend/app/(auth)/login/page.test.tsx index c559219..05f78ab 100644 --- a/apps/frontend/app/(auth)/login/page.test.tsx +++ b/apps/frontend/app/(auth)/login/page.test.tsx @@ -7,8 +7,8 @@ * "Unexpected error" for 400, 409 email_taken stays in the top Alert). */ import { describe, expect, test } from 'bun:test'; -import { parseRegisterFieldErrors } from '../../../src/lib/register-field-errors'; -import { loginSchema, registerSchema } from '../../../src/lib/auth-schemas'; +import { parseRegisterFieldErrors } from '@/lib/register-field-errors'; +import { loginSchema, registerSchema } from '@/lib/auth-schemas'; describe('parseRegisterFieldErrors', () => { test('maps invalid email to the email field', () => { diff --git a/apps/frontend/app/(auth)/login/page.tsx b/apps/frontend/app/(auth)/login/page.tsx index fa561b9..32a60c5 100644 --- a/apps/frontend/app/(auth)/login/page.tsx +++ b/apps/frontend/app/(auth)/login/page.tsx @@ -21,12 +21,12 @@ import { FieldLabel, Input, } from '@web2bizz/ui/components'; -import { ApiClientError, api } from '../../../src/api/client'; -import { parseRegisterFieldErrors } from '../../../src/lib/register-field-errors'; -import { loginSchema, registerSchema, type LoginInput, type RegisterInput } from '../../../src/lib/auth-schemas'; -import { setSession } from '../../../src/lib/auth-store'; -import { formatApiError } from '../../../src/lib/format-error'; -import { useI18n } from '../../../src/i18n'; +import { ApiClientError, api } from '@/api/client'; +import { parseRegisterFieldErrors } from '@/lib/register-field-errors'; +import { loginSchema, registerSchema, type LoginInput, type RegisterInput } from '@/lib/auth-schemas'; +import { setSession } from '@/lib/auth-store'; +import { formatApiError } from '@/lib/format-error'; +import { useI18n } from '@/i18n'; function LoginForm({ onSuccess }: { onSuccess: () => void }) { const { t } = useI18n(); diff --git a/apps/frontend/app/(dashboard)/ai-providers/page.tsx b/apps/frontend/app/(dashboard)/ai-providers/page.tsx index 48e3d88..94bbc26 100644 --- a/apps/frontend/app/(dashboard)/ai-providers/page.tsx +++ b/apps/frontend/app/(dashboard)/ai-providers/page.tsx @@ -14,11 +14,11 @@ import { CardTitle, Switch, } from '@web2bizz/ui/components'; -import { EmptyState, ErrorState, LoadingState } from '../../../src/components/states'; -import { useAiProviders } from '../../../src/hooks/useAiProviders'; -import { useOpencodeEvents } from '../../../src/hooks/useOpencodeEvents'; -import { useI18n } from '../../../src/i18n'; -import type { AiProviderStatus } from '../../../src/lib/types'; +import { EmptyState, ErrorState, LoadingState } from '@/components/states'; +import { useAiProviders } from '@/hooks/useAiProviders'; +import { useOpencodeEvents } from '@/hooks/useOpencodeEvents'; +import { useI18n } from '@/i18n'; +import type { AiProviderStatus } from '@/lib/types'; function statusColor(status: AiProviderStatus) { if (status === 'connected') return 'success' as const; diff --git a/apps/frontend/app/(dashboard)/chat/layout.tsx b/apps/frontend/app/(dashboard)/chat/layout.tsx index 74504d3..d564d05 100644 --- a/apps/frontend/app/(dashboard)/chat/layout.tsx +++ b/apps/frontend/app/(dashboard)/chat/layout.tsx @@ -1,8 +1,8 @@ import type { Metadata } from 'next'; import type { ReactNode } from 'react'; import { cookies } from 'next/headers'; -import { en } from '../../../src/i18n/dictionaries/en'; -import { ru } from '../../../src/i18n/dictionaries/ru'; +import { en } from '@/i18n/dictionaries/en'; +import { ru } from '@/i18n/dictionaries/ru'; /** * Segment metadata for /chat: localized via the `devbox-locale` cookie diff --git a/apps/frontend/app/(dashboard)/layout.tsx b/apps/frontend/app/(dashboard)/layout.tsx index 7213c7f..fcd745d 100644 --- a/apps/frontend/app/(dashboard)/layout.tsx +++ b/apps/frontend/app/(dashboard)/layout.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from 'react'; -import { DashboardShell } from '../../src/components/dashboard-shell'; +import { DashboardShell } from '@/components/dashboard-shell'; /** * Route-group layout: flat URLs (/projects, /secrets, …) wrapped in the shell. diff --git a/apps/frontend/app/(dashboard)/organizations/[id]/page.tsx b/apps/frontend/app/(dashboard)/organizations/[id]/page.tsx index 253158b..ee98083 100644 --- a/apps/frontend/app/(dashboard)/organizations/[id]/page.tsx +++ b/apps/frontend/app/(dashboard)/organizations/[id]/page.tsx @@ -16,15 +16,15 @@ import { EmptyState, ErrorState, ProjectDetailSkeleton, -} from '../../../../src/components/states'; -import { useOrganization } from '../../../../src/hooks/useOrganization'; -import { useOrgMembers } from '../../../../src/hooks/useOrgMembers'; -import { useInvite } from '../../../../src/hooks/useInvite'; -import { useProfile } from '../../../../src/hooks/useProfile'; -import { ApiClientError, api } from '../../../../src/api/client'; -import { getValidAccessToken } from '../../../../src/lib/auth-store'; -import type { OrgRole } from '../../../../src/api/types'; -import { useI18n } from '../../../../src/i18n'; +} from '@/components/states'; +import { useOrganization } from '@/hooks/useOrganization'; +import { useOrgMembers } from '@/hooks/useOrgMembers'; +import { useInvite } from '@/hooks/useInvite'; +import { useProfile } from '@/hooks/useProfile'; +import { ApiClientError, api } from '@/api/client'; +import { getValidAccessToken } from '@/lib/auth-store'; +import type { OrgRole } from '@/api/types'; +import { useI18n } from '@/i18n'; function shortId(id: string): string { return id.length > 8 ? `${id.slice(0, 8)}…` : id; diff --git a/apps/frontend/app/(dashboard)/organizations/invites/accept/page.tsx b/apps/frontend/app/(dashboard)/organizations/invites/accept/page.tsx index 9c0c81e..3c4f361 100644 --- a/apps/frontend/app/(dashboard)/organizations/invites/accept/page.tsx +++ b/apps/frontend/app/(dashboard)/organizations/invites/accept/page.tsx @@ -3,9 +3,9 @@ import Link from 'next/link'; import { useRouter, useSearchParams } from 'next/navigation'; import { Suspense, useEffect, useRef } from 'react'; -import { ErrorState, ProjectDetailSkeleton } from '../../../../../src/components/states'; -import { useInvite } from '../../../../../src/hooks/useInvite'; -import { useI18n } from '../../../../../src/i18n'; +import { ErrorState, ProjectDetailSkeleton } from '@/components/states'; +import { useInvite } from '@/hooks/useInvite'; +import { useI18n } from '@/i18n'; /** * Route: /organizations/invites/accept?token=… — single-use invite accept. diff --git a/apps/frontend/app/(dashboard)/organizations/page.tsx b/apps/frontend/app/(dashboard)/organizations/page.tsx index f07aec3..67eedae 100644 --- a/apps/frontend/app/(dashboard)/organizations/page.tsx +++ b/apps/frontend/app/(dashboard)/organizations/page.tsx @@ -12,10 +12,10 @@ import { CardHeader, CardTitle, } from '@web2bizz/ui/components'; -import { EmptyState, ErrorState, LoadingState } from '../../../src/components/states'; -import { CreateOrganizationDialog } from '../../../src/components/organizations/create-organization-dialog'; -import { useOrganizations } from '../../../src/hooks/useOrganizations'; -import { useI18n } from '../../../src/i18n'; +import { EmptyState, ErrorState, LoadingState } from '@/components/states'; +import { CreateOrganizationDialog } from '@/components/organizations/create-organization-dialog'; +import { useOrganizations } from '@/hooks/useOrganizations'; +import { useI18n } from '@/i18n'; /** * Route: /organizations — membership-scoped list + create. diff --git a/apps/frontend/app/(dashboard)/profile/page.tsx b/apps/frontend/app/(dashboard)/profile/page.tsx index d6982b2..a53a993 100644 --- a/apps/frontend/app/(dashboard)/profile/page.tsx +++ b/apps/frontend/app/(dashboard)/profile/page.tsx @@ -6,89 +6,29 @@ import { AlertDescription, AlertTitle, Button, - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, Field, - FieldDescription, - FieldError, FieldLabel, Input, - Progress, Separator, - Skeleton, } from '@web2bizz/ui/components'; -import { EmptyState, ErrorState, ProjectDetailSkeleton } from '../../../src/components/states'; -import { useProfile } from '../../../src/hooks/useProfile'; -import { useUsage } from '../../../src/hooks/useUsage'; -import { ApiClientError, api } from '../../../src/api/client'; -import { formatApiError } from '../../../src/lib/format-error'; -import { getValidAccessToken, refreshAccessToken } from '../../../src/lib/auth-store'; -import { useI18n } from '../../../src/i18n'; -import type { OpencodeLimitBucket } from '../../../src/api/types'; - -/** - * Real bucket guard — finite used/limit with a positive limit. - * Non-finite or missing buckets are not renderable (no fake 0% bars). - */ -function isUsableBucket(bucket: OpencodeLimitBucket | undefined): bucket is OpencodeLimitBucket { - return ( - !!bucket && - Number.isFinite(bucket.used) && - Number.isFinite(bucket.limit) && - bucket.limit > 0 - ); -} - -/** Percent from a REAL used/limit pair only (never from the usage total). */ -function toPercent(used: number, limit: number): number { - const raw = (used / limit) * 100; - if (!Number.isFinite(raw)) return 0; - return Math.min(100, Math.max(0, Math.round(raw))); -} - -/** - * Indicator tone via kit Progress className only (no hex, no gradients, - * no shadows/transforms in this block; radii stay var(--radius*)). - * Kit Indicator is hardcoded bg-primary — the child selector recolors it - * through the kit className API (direct child + data-slot fallback). - */ -function toneClass(pct: number): string { - if (pct > 85) return '[&>div]:bg-destructive [&_[data-slot=progress-indicator]]:bg-destructive'; - if (pct >= 60) return '[&>div]:bg-amber-500 [&_[data-slot=progress-indicator]]:bg-amber-500'; - return '[&>div]:bg-emerald-500 [&_[data-slot=progress-indicator]]:bg-emerald-500'; -} +import { ErrorState, ProjectDetailSkeleton } from '@/components/states'; +import { UsageSection } from '@/features/usage/usage-section'; +import { useProfile } from '@/hooks/useProfile'; +import { useI18n } from '@/i18n'; /** * Route: /profile — flat Content (§7: no nested Cards, h2 + Separator). * Real API: GET/PATCH /api/v1/auth/me via useProfile. Email is read-only * (backend PATCH accepts only firstName/lastName) — displayed as text * plus a disabled input with a hint, never sent. - * Limits: live GET /api/v1/usage via useUsage — percentages ONLY from real - * used/limit pairs (rolling 5h / daily legacy / weekly / monthly, additive - * backend breakdown; Zen Go percent is exposed as { used: percent, limit: 100 }). - * No breakdown → Empty (never 0% fake bars, never derived from the total). + * Limits live in the usage feature module (`src/features/usage/`: + * `useUsage` + `UsageSection` + `ApiKeyDialog`) — this page only composes + * `` and owns no usage business logic. */ export default function ProfilePage() { const { t } = useI18n(); const { profile, loading, error, saved, saving, update, reload } = useProfile(); - const { - usage, - loading: usageLoading, - error: usageError, - noKeyMissing, - noKeyInvalid, - upstreamDown, - reload: reloadUsage, - } = useUsage(); const [name, setName] = useState(''); - const [keyDialogOpen, setKeyDialogOpen] = useState(false); - const [apiKey, setApiKey] = useState(''); - const [savingKey, setSavingKey] = useState(false); - const [saveError, setSaveError] = useState(null); useEffect(() => { if (profile) { @@ -96,74 +36,11 @@ export default function ProfilePage() { } }, [profile]); - useEffect(() => { - if (!keyDialogOpen) { - setSaveError(null); - setSavingKey(false); - } - }, [keyDialogOpen]); - const submit = async (e: React.FormEvent) => { e.preventDefault(); await update({ name }); }; - const openKeyDialog = () => { - setApiKey(''); - setSaveError(null); - setKeyDialogOpen(true); - }; - - /** - * Save the OpenCode API key via PUT /api/v1/key, then reload usage - * (which re-resolves both the key status and the limits: 404 no-key / - * 401 rejected key inline, 5xx section ErrorState, 200 live). The raw key - * is never logged. - */ - const saveKey = async (e: React.FormEvent) => { - e.preventDefault(); - const trimmed = apiKey.trim(); - if (!trimmed) { - setSaveError(t.limits.required); - return; - } - if (trimmed.length < 20) { - setSaveError(t.limits.tooShort); - return; - } - setSavingKey(true); - setSaveError(null); - try { - let token = await getValidAccessToken(); - if (!token) { - setSaveError(t.errors.sessionExpired); - return; - } - try { - await api.putKey(token, { apiKey: trimmed }); - } catch (err) { - if (err instanceof ApiClientError && err.status === 401) { - token = await refreshAccessToken(); - if (!token) { - setSaveError(t.errors.sessionExpired); - return; - } - await api.putKey(token, { apiKey: trimmed }); - } else { - throw err; - } - } - setApiKey(''); - setKeyDialogOpen(false); - reloadUsage(); - } catch (err) { - const formatted = formatApiError(err); - setSaveError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - } finally { - setSavingKey(false); - } - }; - return (
@@ -255,141 +132,7 @@ export default function ProfilePage() { -
-

- {t.limits.title} -

-

{t.limits.desc}

- {usageLoading && ( -
- - - - - - -
- )} - {!usageLoading && upstreamDown && ( - - )} - {!usageLoading && !upstreamDown && usageError && ( - - )} - {!usageLoading && !upstreamDown && !usageError && noKeyMissing && ( - - )} - {!usageLoading && !upstreamDown && !usageError && !noKeyMissing && noKeyInvalid && ( - - )} - {!usageLoading && - !upstreamDown && - !usageError && - !noKeyMissing && - !noKeyInvalid && - !usage && ( - - )} - {!usageLoading && !upstreamDown && !usageError && !noKeyMissing && !noKeyInvalid && usage && (() => { - const rows = [ - { key: 'rolling', label: t.limits.rolling, bucket: usage.rolling }, - { key: 'daily', label: t.limits.daily, bucket: usage.daily }, - { key: 'weekly', label: t.limits.weekly, bucket: usage.weekly }, - { key: 'monthly', label: t.limits.monthly, bucket: usage.monthly }, - ].filter((row): row is { key: string; label: string; bucket: OpencodeLimitBucket } => - isUsableBucket(row.bucket), - ); - if (rows.length === 0) { - return ; - } - return ( -
    - {rows.map((row) => { - const pct = toPercent(row.bucket.used, row.bucket.limit); - return ( -
  • -
    - {row.label} - - {row.bucket.used}/{row.bucket.limit} - -
    - -
  • - ); - })} -
- ); - })()} -
- - { - if (!savingKey) setKeyDialogOpen(open); - }} - > - - - {t.limits.dialogTitle} - {t.limits.dialogDesc} - - -
- - {t.limits.keyLabel} - setApiKey(e.target.value)} - /> - {t.limits.keyHint} - {saveError && {saveError}} - -
- - - - - -
-
+
)}
diff --git a/apps/frontend/app/(dashboard)/projects/[id]/page.tsx b/apps/frontend/app/(dashboard)/projects/[id]/page.tsx index da4cd1b..68db547 100644 --- a/apps/frontend/app/(dashboard)/projects/[id]/page.tsx +++ b/apps/frontend/app/(dashboard)/projects/[id]/page.tsx @@ -16,11 +16,11 @@ import { EmptyState, ErrorState, ProjectDetailSkeleton, -} from '../../../../src/components/states'; -import { SessionsTab } from '../../../../src/components/projects/sessions-tab'; -import { RunningSessionsTab } from '../../../../src/components/projects/running-sessions-tab'; -import { useProject } from '../../../../src/hooks/useProject'; -import { useI18n } from '../../../../src/i18n'; +} from '@/components/states'; +import { SessionsTab } from '@/components/projects/sessions-tab'; +import { RunningSessionsTab } from '@/components/projects/running-sessions-tab'; +import { useProject } from '@/hooks/useProject'; +import { useI18n } from '@/i18n'; /** * Route: /projects/[id] — single project (live API via `useProject`). diff --git a/apps/frontend/app/(dashboard)/projects/[id]/sessions/[sessionId]/page.tsx b/apps/frontend/app/(dashboard)/projects/[id]/sessions/[sessionId]/page.tsx index f5f2f86..cff770b 100644 --- a/apps/frontend/app/(dashboard)/projects/[id]/sessions/[sessionId]/page.tsx +++ b/apps/frontend/app/(dashboard)/projects/[id]/sessions/[sessionId]/page.tsx @@ -3,12 +3,12 @@ import Link from 'next/link'; import { useParams, useRouter } from 'next/navigation'; import { Button } from '@web2bizz/ui/components'; -import { ChatInput } from '../../../../../../src/components/chat/chat-input'; -import { ChatWindow } from '../../../../../../src/components/chat/chat-window'; -import { EmptyState, ErrorState, LoadingState } from '../../../../../../src/components/states'; -import { useChat } from '../../../../../../src/hooks/useChat'; -import { useProject } from '../../../../../../src/hooks/useProject'; -import { useI18n } from '../../../../../../src/i18n'; +import { ChatInput } from '@/components/chat/chat-input'; +import { ChatWindow } from '@/components/chat/chat-window'; +import { EmptyState, ErrorState, LoadingState } from '@/components/states'; +import { useChat } from '@/hooks/useChat'; +import { useProject } from '@/hooks/useProject'; +import { useI18n } from '@/i18n'; /** * Route: /projects/[id]/sessions/[sessionId] — session = chat. diff --git a/apps/frontend/app/(dashboard)/projects/page.tsx b/apps/frontend/app/(dashboard)/projects/page.tsx index 88c20bb..bd441f0 100644 --- a/apps/frontend/app/(dashboard)/projects/page.tsx +++ b/apps/frontend/app/(dashboard)/projects/page.tsx @@ -15,11 +15,11 @@ import { CardHeader, CardTitle, } from '@web2bizz/ui/components'; -import { EmptyState, ErrorState, LoadingState } from '../../../src/components/states'; -import { CreateProjectDialog } from '../../../src/components/projects/create-project-dialog'; -import { useProjects } from '../../../src/hooks/useProjects'; -import { useI18n } from '../../../src/i18n'; -import type { ProjectStatus } from '../../../src/lib/types'; +import { EmptyState, ErrorState, LoadingState } from '@/components/states'; +import { CreateProjectDialog } from '@/components/projects/create-project-dialog'; +import { useProjects } from '@/hooks/useProjects'; +import { useI18n } from '@/i18n'; +import type { ProjectStatus } from '@/lib/types'; function statusColor(status: ProjectStatus) { if (status === 'active') return 'success' as const; diff --git a/apps/frontend/app/(dashboard)/registry/docker/page.tsx b/apps/frontend/app/(dashboard)/registry/docker/page.tsx index fbf197c..db4203f 100644 --- a/apps/frontend/app/(dashboard)/registry/docker/page.tsx +++ b/apps/frontend/app/(dashboard)/registry/docker/page.tsx @@ -7,10 +7,10 @@ import { Label, Separator, } from '@web2bizz/ui/components'; -import { EmptyState, ErrorState, LoadingState } from '../../../../src/components/states'; -import { useRegistries } from '../../../../src/hooks/useRegistries'; -import { useI18n } from '../../../../src/i18n'; -import type { RegistryStatus } from '../../../../src/lib/types'; +import { EmptyState, ErrorState, LoadingState } from '@/components/states'; +import { useRegistries } from '@/hooks/useRegistries'; +import { useI18n } from '@/i18n'; +import type { RegistryStatus } from '@/lib/types'; function statusColor(status: RegistryStatus) { if (status === 'up') return 'success' as const; diff --git a/apps/frontend/app/(dashboard)/registry/npm/page.tsx b/apps/frontend/app/(dashboard)/registry/npm/page.tsx index 06b8bc5..26f70fc 100644 --- a/apps/frontend/app/(dashboard)/registry/npm/page.tsx +++ b/apps/frontend/app/(dashboard)/registry/npm/page.tsx @@ -7,10 +7,10 @@ import { Label, Separator, } from '@web2bizz/ui/components'; -import { EmptyState, ErrorState, LoadingState } from '../../../../src/components/states'; -import { useNpm } from '../../../../src/hooks/useNpm'; -import { useI18n } from '../../../../src/i18n'; -import type { NpmStatus } from '../../../../src/lib/types'; +import { EmptyState, ErrorState, LoadingState } from '@/components/states'; +import { useNpm } from '@/hooks/useNpm'; +import { useI18n } from '@/i18n'; +import type { NpmStatus } from '@/lib/types'; function statusColor(status: NpmStatus) { if (status === 'up') return 'success' as const; diff --git a/apps/frontend/app/(dashboard)/registry/page.tsx b/apps/frontend/app/(dashboard)/registry/page.tsx index 80fd6bd..1f6782e 100644 --- a/apps/frontend/app/(dashboard)/registry/page.tsx +++ b/apps/frontend/app/(dashboard)/registry/page.tsx @@ -1,7 +1,7 @@ 'use client'; -import { RegistryHub } from '../../../src/components/registry-hub'; -import { useI18n } from '../../../src/i18n'; +import { RegistryHub } from '@/components/registry-hub'; +import { useI18n } from '@/i18n'; /** * Route: /registry — hub with two Card links (Docker → /registry/docker, diff --git a/apps/frontend/app/(dashboard)/secrets/page.tsx b/apps/frontend/app/(dashboard)/secrets/page.tsx index ed08b4d..3e70c90 100644 --- a/apps/frontend/app/(dashboard)/secrets/page.tsx +++ b/apps/frontend/app/(dashboard)/secrets/page.tsx @@ -24,9 +24,9 @@ import { Input, Label, } from '@web2bizz/ui/components'; -import { EmptyState, ErrorState, LoadingState } from '../../../src/components/states'; -import { useSecrets } from '../../../src/hooks/useSecrets'; -import { useI18n } from '../../../src/i18n'; +import { EmptyState, ErrorState, LoadingState } from '@/components/states'; +import { useSecrets } from '@/hooks/useSecrets'; +import { useI18n } from '@/i18n'; /** * Route: /secrets — masked list with reveal/copy + confirm before delete. diff --git a/apps/frontend/app/(dashboard)/users/[id]/page.tsx b/apps/frontend/app/(dashboard)/users/[id]/page.tsx index 3793bf2..64490ff 100644 --- a/apps/frontend/app/(dashboard)/users/[id]/page.tsx +++ b/apps/frontend/app/(dashboard)/users/[id]/page.tsx @@ -7,9 +7,9 @@ import { EmptyState, ErrorState, ProjectDetailSkeleton, -} from '../../../../src/components/states'; -import { useUser } from '../../../../src/hooks/useUser'; -import { useI18n } from '../../../../src/i18n'; +} from '@/components/states'; +import { useUser } from '@/hooks/useUser'; +import { useI18n } from '@/i18n'; /** * Route: /users/[id] — private single profile (GET /api/v1/users/:id). diff --git a/apps/frontend/app/error.tsx b/apps/frontend/app/error.tsx index d665608..4cbf24f 100644 --- a/apps/frontend/app/error.tsx +++ b/apps/frontend/app/error.tsx @@ -2,8 +2,8 @@ import { useEffect } from 'react'; import { Alert, AlertDescription, AlertTitle, Button } from '@web2bizz/ui/components'; -import { formatApiError } from '../src/lib/format-error'; -import { useI18n } from '../src/i18n'; +import { formatApiError } from '@/lib/format-error'; +import { useI18n } from '@/i18n'; export default function RootError({ error, diff --git a/apps/frontend/app/layout.tsx b/apps/frontend/app/layout.tsx index 6c689c8..63bdd1f 100644 --- a/apps/frontend/app/layout.tsx +++ b/apps/frontend/app/layout.tsx @@ -3,9 +3,9 @@ import type { ReactNode } from 'react'; import { cookies } from 'next/headers'; import '@web2bizz/ui/styles.css'; import './globals.css'; -import { Providers } from '../src/providers'; -import { en } from '../src/i18n/dictionaries/en'; -import { ru } from '../src/i18n/dictionaries/ru'; +import { Providers } from '@/providers'; +import { en } from '@/i18n/dictionaries/en'; +import { ru } from '@/i18n/dictionaries/ru'; /** * Localized metadata without breaking flat URLs: the `devbox-locale` diff --git a/apps/frontend/app/loading.tsx b/apps/frontend/app/loading.tsx index 0f9b130..3408844 100644 --- a/apps/frontend/app/loading.tsx +++ b/apps/frontend/app/loading.tsx @@ -1,7 +1,7 @@ 'use client'; import { Skeleton } from '@web2bizz/ui/components'; -import { useI18n } from '../src/i18n'; +import { useI18n } from '@/i18n'; export default function RootLoading() { const { t } = useI18n(); diff --git a/apps/frontend/next-env.d.ts b/apps/frontend/next-env.d.ts index a419cbe..ce4e94a 100644 --- a/apps/frontend/next-env.d.ts +++ b/apps/frontend/next-env.d.ts @@ -1,7 +1,7 @@ /// /// -import "./.next/dev/types/routes.d.ts"; -import "./.next/dev/types/root-params.d.ts"; +import "./.next/types/routes.d.ts"; +import "./.next/types/root-params.d.ts"; // NOTE: This file should not be edited // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/apps/frontend/src/api/client.ts b/apps/frontend/src/api/client.ts index bd4df30..768fef7 100644 --- a/apps/frontend/src/api/client.ts +++ b/apps/frontend/src/api/client.ts @@ -66,12 +66,32 @@ export class ApiClientError extends Error { } async function request(path: string, init: RequestInit = {}, timeoutMs = DEFAULT_TIMEOUT_MS): Promise { + const externalSignal = init.signal as AbortSignal | null | undefined; const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), timeoutMs); const correlationId = crypto.randomUUID(); + const onExternalAbort = () => { + try { + ctrl.abort((externalSignal as AbortSignal).reason); + } catch { + ctrl.abort(); + } + }; + if (externalSignal) { + if (externalSignal.aborted) { + clearTimeout(timer); + const reason = (externalSignal as AbortSignal).reason; + throw reason instanceof Error + ? reason + : new DOMException('The operation was aborted.', 'AbortError'); + } + externalSignal.addEventListener('abort', onExternalAbort, { once: true }); + } try { + const { signal: _externalIgnored, ...restInit } = init; + void _externalIgnored; const res = await fetch(`${BASE_URL}${path}`, { - ...init, + ...restInit, signal: ctrl.signal, headers: { 'content-type': 'application/json', @@ -97,6 +117,9 @@ async function request(path: string, init: RequestInit = {}, timeoutMs = DEFA } catch (e) { if (e instanceof ApiClientError) throw e; if ((e as Error).name === 'AbortError') { + // React Query cancellation (queryFn signal) must stay an AbortError so + // the cancelled query does not surface as a timeout error in the UI. + if (externalSignal?.aborted) throw e; throw new ApiClientError({ code: 'timeout', message: `Request timed out after ${timeoutMs}ms`, @@ -112,6 +135,7 @@ async function request(path: string, init: RequestInit = {}, timeoutMs = DEFA }); } finally { clearTimeout(timer); + externalSignal?.removeEventListener('abort', onExternalAbort); } } @@ -147,15 +171,25 @@ export const api = { // data. Unconfigured/unreachable answers 503 EXTERNAL_UNAVAILABLE // («сервис временно недоступен, повторите позже») with Retry-After — // surfaced here as ApiClientError (no mock payloads, never 200). - getRegistryCatalog: () => - requestV1('/registry/catalog'), + // No token: catalog is public reachability, auth lives server-side. + // Optional `signal` forwards React Query cancellation (queryFn signal) + // into the timeout controller — no local AbortController in hooks. + getRegistryCatalog: (opts?: { signal?: AbortSignal }) => + requestV1( + '/registry/catalog', + opts?.signal ? { signal: opts.signal } : {}, + ), // npm surface: 200 always means live Verdaccio /-/ping reachability // ({ status: 'up', url, scope }); unconfigured/unreachable answers 503 // EXTERNAL_UNAVAILABLE («сервис временно недоступен, повторите позже») // with Retry-After — surfaced here as ApiClientError (no mock payloads, // token never in payload). - getNpmStatus: () => - requestV1('/registry/npm/status'), + // Optional `signal` forwards React Query cancellation (queryFn signal). + getNpmStatus: (opts?: { signal?: AbortSignal }) => + requestV1( + '/registry/npm/status', + opts?.signal ? { signal: opts.signal } : {}, + ), // Auth surface (internal accounts): register/login issue the access + // rotating refresh pair; refresh/logout carry `credentials: 'include'` so // the httpOnly `devbox-refresh` cookie travels cross-origin (frontend diff --git a/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx b/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx index 3db920b..9ceac68 100644 --- a/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx +++ b/apps/frontend/src/components/__tests__/profile-dropdown.test.tsx @@ -125,12 +125,24 @@ mock.module('../../api/client', () => ({ })); const { cleanup, render, screen, waitFor } = await import('@testing-library/react'); -const userEvent = (await import('@testing-library/user-event')).default; +const { QueryClientProvider } = await import('@tanstack/react-query'); +const { createElement, useState } = await import('react'); +const { createQueryClient } = await import('../../lib/query-client'); const { I18nProvider } = await import('../../i18n'); +const userEvent = (await import('@testing-library/user-event')).default; const { HeaderProfileDropdown } = await import('../profile-dropdown'); const { ProfileDropdownUserTrigger } = await import('@web2bizz/ui/widgets'); const { setSession, clearSession } = await import('../../lib/auth-store'); +// useHeaderProfile is useQuery-backed now (same PROFILE_QUERY_KEY as the +// /profile page) — every render needs a QueryClientProvider. Fresh client +// per render keeps tests isolated; within one render concurrent mounts +// share the entry (dedup 2→1 is covered in useProfile.test.tsx). +function wrapper({ children }: { children: React.ReactNode }) { + const [client] = useState(() => createQueryClient()); + return createElement(QueryClientProvider, { client }, children); +} + // Network seam stub (offline fallback; the module mock above is primary). // Seeded per test (sign-out clears the store, so beforeEach re-seeds). (globalThis as Record).fetch = async (input: unknown) => { @@ -206,7 +218,7 @@ describe('ProfileDropdownUserTrigger rest/ref forward (0.25.9 regression)', () = describe('HeaderProfileDropdown (pure kit AuthorizedUserProfile)', () => { test('closed trigger exposes menu semantics; click opens with profile + sign-out', async () => { const user = userEvent.setup(); - render(); + render(, { wrapper }); const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); // Radix Slot props must reach the kit trigger (the 0.25.9 bug: they did not). @@ -229,7 +241,7 @@ describe('HeaderProfileDropdown (pure kit AuthorizedUserProfile)', () => { test('sign-out pushes /login', async () => { const user = userEvent.setup(); - render(); + render(, { wrapper }); const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); await user.click(trigger); @@ -241,7 +253,7 @@ describe('HeaderProfileDropdown (pure kit AuthorizedUserProfile)', () => { test('Escape closes the menu and returns focus to the trigger', async () => { const user = userEvent.setup(); - render(); + render(, { wrapper }); const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); await user.click(trigger); @@ -256,7 +268,7 @@ describe('HeaderProfileDropdown (pure kit AuthorizedUserProfile)', () => { test('keyboard: Tab moves focus into the open menu (arrows roving pending kit fix)', async () => { const user = userEvent.setup(); - render(); + render(, { wrapper }); const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); await user.click(trigger); @@ -285,6 +297,7 @@ describe('HeaderProfileDropdown (pure kit AuthorizedUserProfile)', () => { , + { wrapper }, ); const trigger = await screen.findByRole('button', { name: TRIGGER_NAME }, { timeout: FIND_TIMEOUT }); diff --git a/apps/frontend/src/features/usage/__tests__/usage-status.test.ts b/apps/frontend/src/features/usage/__tests__/usage-status.test.ts new file mode 100644 index 0000000..f1377fb --- /dev/null +++ b/apps/frontend/src/features/usage/__tests__/usage-status.test.ts @@ -0,0 +1,122 @@ +/** + * mapUsageStatus — unified usage error model (single source for Limits). + * Null → ready; 404 missing-key / 401 invalid-key → user branches (no + * error text); session 401 / dead session → session-expired; 429/5xx/0 → + * failed upstream; any other failure → failed non-upstream with the raw + * `code: message` confined to `diagnostic` + `shortId` (never UI text). + */ +import { describe, expect, test } from 'bun:test'; +import { ApiClientError } from '../../../api/client'; +import { + SessionExpiredError, + isMissingKeyError, + isRejectedKeyError, + isUpstreamDownError, + mapUsageStatus, +} from '../usage-status'; + +const STRINGS = { sessionExpired: 'Session expired', unexpected: 'Unexpected error' }; + +function apiError(args: { code: string; message: string; status: number; correlationId: string }) { + return new ApiClientError(args); +} + +describe('mapUsageStatus', () => { + test('nullish input is ready', () => { + expect(mapUsageStatus(null, STRINGS)).toEqual({ kind: 'ready' }); + expect(mapUsageStatus(undefined, STRINGS)).toEqual({ kind: 'ready' }); + }); + + test('404 opencode_key_missing → missing-key', () => { + const err = apiError({ + code: 'opencode_key_missing', + message: 'no stored key', + status: 404, + correlationId: 'corr-404', + }); + expect(isMissingKeyError(err)).toBe(true); + expect(mapUsageStatus(err, STRINGS)).toEqual({ kind: 'missing-key' }); + }); + + test('401 opencode_key_invalid → invalid-key (never a refresh)', () => { + const err = apiError({ + code: 'opencode_key_invalid', + message: 'rejected upstream', + status: 401, + correlationId: 'corr-401k', + }); + expect(isRejectedKeyError(err)).toBe(true); + expect(mapUsageStatus(err, STRINGS)).toEqual({ kind: 'invalid-key' }); + }); + + test('plain 401 → session-expired', () => { + const err = apiError({ + code: 'unauthorized', + message: 'Unauthorized', + status: 401, + correlationId: 'corr-401', + }); + expect(isRejectedKeyError(err)).toBe(false); + expect(mapUsageStatus(err, STRINGS)).toEqual({ + kind: 'session-expired', + message: 'Session expired', + }); + }); + + test('dead session → session-expired', () => { + expect(mapUsageStatus(new SessionExpiredError(), STRINGS)).toEqual({ + kind: 'session-expired', + message: 'Session expired', + }); + }); + + test('503 / 429 / 0 → failed upstream with diagnostic + shortId', () => { + for (const [status, code] of [ + [503, 'EXTERNAL_UNAVAILABLE'], + [429, 'rate_limited'], + [0, 'network_error'], + ] as const) { + const err = apiError({ code, message: 'down', status, correlationId: 'abcdef12-xyz' }); + expect(isUpstreamDownError(err)).toBe(true); + const out = mapUsageStatus(err, STRINGS); + expect(out).toEqual({ + kind: 'failed', + message: 'Unexpected error', + upstream: true, + diagnostic: `${code}: down (ID: abcdef12)`, + shortId: 'abcdef12', + }); + } + }); + + test('generic 404 / 403 → failed non-upstream, code confined to diagnostic', () => { + const err = apiError({ + code: 'forbidden', + message: 'forbidden', + status: 403, + correlationId: 'corr-403-xyz', + }); + expect(isUpstreamDownError(err)).toBe(false); + const out = mapUsageStatus(err, STRINGS); + expect(out.kind).toBe('failed'); + if (out.kind === 'failed') { + expect(out.message).toBe('Unexpected error'); + expect(out.upstream).toBe(false); + expect(out.diagnostic).toContain('forbidden'); + expect(out.shortId).toBe('corr-403'); + // UI text carries no raw code:message. + expect(out.message).not.toContain('forbidden'); + } + }); + + test('plain Error → failed non-upstream without shortId', () => { + const out = mapUsageStatus(new Error('boom'), STRINGS); + expect(out).toEqual({ + kind: 'failed', + message: 'Unexpected error', + upstream: false, + diagnostic: 'boom', + shortId: '', + }); + }); +}); diff --git a/apps/frontend/src/features/usage/api-key-dialog.tsx b/apps/frontend/src/features/usage/api-key-dialog.tsx new file mode 100644 index 0000000..845bead --- /dev/null +++ b/apps/frontend/src/features/usage/api-key-dialog.tsx @@ -0,0 +1,163 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { + Button, + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + Field, + FieldDescription, + FieldError, + FieldLabel, + Input, +} from '@web2bizz/ui/components'; +import { ApiClientError, api } from '../../api/client'; +import { getValidAccessToken, refreshAccessToken } from '../../lib/auth-store'; +import { useI18n } from '../../i18n'; +import { SessionExpiredError, mapUsageStatus } from './usage-status'; + +const MIN_KEY_LENGTH = 20; + +async function saveApiKey(rawKey: string): Promise { + const token = await getValidAccessToken(); + if (!token) throw new SessionExpiredError(); + try { + await api.putKey(token, { apiKey: rawKey }); + } catch (err) { + if (err instanceof ApiClientError && err.status === 401) { + const retryToken = await refreshAccessToken(); + if (!retryToken) throw new SessionExpiredError(); + await api.putKey(retryToken, { apiKey: rawKey }); + return; + } + throw err; + } +} + +export function ApiKeyDialog({ + open, + onOpenChange, + onSaved, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + onSaved: () => void; +}) { + const { t } = useI18n(); + const [apiKey, setApiKey] = useState(''); + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(null); + const [saveShortId, setSaveShortId] = useState(''); + + useEffect(() => { + if (open) { + setApiKey(''); + setSaveError(null); + setSaveShortId(''); + setSaving(false); + } + }, [open]); + + const fail = (message: string, shortId = '') => { + setSaveError(message); + setSaveShortId(shortId); + }; + + const submit = async (e: React.FormEvent) => { + e.preventDefault(); + const trimmed = apiKey.trim(); + if (!trimmed) { + fail(t.limits.required); + return; + } + if (trimmed.length < MIN_KEY_LENGTH) { + fail(t.limits.tooShort); + return; + } + setSaving(true); + setSaveError(null); + setSaveShortId(''); + try { + await saveApiKey(trimmed); + setApiKey(''); + onOpenChange(false); + onSaved(); + } catch (err) { + const status = mapUsageStatus(err, { + sessionExpired: t.errors.sessionExpired, + unexpected: t.errors.unexpected, + }); + if (status.kind === 'session-expired' || status.kind === 'failed') { + fail(status.message, status.kind === 'failed' ? status.shortId : ''); + } else { + fail(t.errors.unexpected); + } + } finally { + setSaving(false); + } + }; + + return ( + { + if (!saving) onOpenChange(next); + }} + > + + + {t.limits.dialogTitle} + {t.limits.dialogDesc} + + +
+ + {t.limits.keyLabel} + setApiKey(e.target.value)} + /> + {t.limits.keyHint} + {saveError && ( + + {saveError} + {saveShortId && ` (${t.errors.diagnosticId}: ${saveShortId})`} + + )} + +
+ + + + + +
+
+ ); +} diff --git a/apps/frontend/src/features/usage/usage-section.tsx b/apps/frontend/src/features/usage/usage-section.tsx new file mode 100644 index 0000000..bb5eb22 --- /dev/null +++ b/apps/frontend/src/features/usage/usage-section.tsx @@ -0,0 +1,135 @@ +'use client'; + +import { useState } from 'react'; +import { Progress, Skeleton } from '@web2bizz/ui/components'; +import { EmptyState, ErrorState } from '../../components/states'; +import type { OpencodeLimitBucket } from '../../api/types'; +import { useI18n } from '../../i18n'; +import { useUsage } from '../../hooks/useUsage'; +import { ApiKeyDialog } from './api-key-dialog'; + +function isUsableBucket(bucket: OpencodeLimitBucket | undefined): bucket is OpencodeLimitBucket { + return ( + !!bucket && + Number.isFinite(bucket.used) && + Number.isFinite(bucket.limit) && + bucket.limit > 0 + ); +} + +function toPercent(used: number, limit: number): number { + const raw = (used / limit) * 100; + if (!Number.isFinite(raw)) return 0; + return Math.min(100, Math.max(0, Math.round(raw))); +} + +function toneClass(pct: number): string { + if (pct > 85) return '[&>div]:bg-destructive [&_[data-slot=progress-indicator]]:bg-destructive'; + if (pct >= 60) return '[&>div]:bg-amber-500 [&_[data-slot=progress-indicator]]:bg-amber-500'; + return '[&>div]:bg-emerald-500 [&_[data-slot=progress-indicator]]:bg-emerald-500'; +} + +export function UsageSection() { + const { t } = useI18n(); + const { usage, loading, status, reload } = useUsage(); + const [dialogOpen, setDialogOpen] = useState(false); + + const openDialog = () => setDialogOpen(true); + + const skeleton = ( +
+ + + + + + +
+ ); + + let body: React.ReactNode = null; + + if (loading) { + body = skeleton; + } else if (status.kind === 'missing-key') { + body = ( + + ); + } else if (status.kind === 'invalid-key') { + body = ( + + ); + } else if (status.kind === 'session-expired' || status.kind === 'failed') { + body = ( +
+ + {status.kind === 'failed' && status.shortId && ( +

+ {t.errors.diagnosticId}: {status.shortId} +

+ )} +
+ ); + } else if (!usage) { + body = ( + + ); + } else { + const rows = [ + { key: 'rolling', label: t.limits.rolling, bucket: usage.rolling }, + { key: 'daily', label: t.limits.daily, bucket: usage.daily }, + { key: 'weekly', label: t.limits.weekly, bucket: usage.weekly }, + { key: 'monthly', label: t.limits.monthly, bucket: usage.monthly }, + ].filter((row): row is { key: string; label: string; bucket: OpencodeLimitBucket } => + isUsableBucket(row.bucket), + ); + if (rows.length === 0) { + body = ; + } else { + body = ( +
    + {rows.map((row) => { + const pct = toPercent(row.bucket.used, row.bucket.limit); + return ( +
  • +
    + {row.label} + + {row.bucket.used}/{row.bucket.limit} + +
    + +
  • + ); + })} +
+ ); + } + } + + return ( +
+

+ {t.limits.title} +

+

{t.limits.desc}

+ {body} + +
+ ); +} diff --git a/apps/frontend/src/features/usage/usage-status.ts b/apps/frontend/src/features/usage/usage-status.ts new file mode 100644 index 0000000..d94d464 --- /dev/null +++ b/apps/frontend/src/features/usage/usage-status.ts @@ -0,0 +1,84 @@ +'use client'; + +import { ApiClientError } from '../../api/client'; +import { formatApiErrorWithId } from '../../lib/format-error'; + +export interface UsageStrings { + sessionExpired: string; + unexpected: string; +} + +export type UsageStatus = + | { kind: 'ready' } + | { kind: 'missing-key' } + | { kind: 'invalid-key' } + | { kind: 'session-expired'; message: string } + | { + kind: 'failed'; + message: string; + upstream: boolean; + diagnostic: string; + shortId: string; + }; + +export class SessionExpiredError extends Error { + constructor() { + super('session-expired'); + this.name = 'SessionExpiredError'; + } +} + +export function isMissingKeyError(e: unknown): boolean { + return e instanceof ApiClientError && e.status === 404 && e.code === 'opencode_key_missing'; +} + +export function isRejectedKeyError(e: unknown): boolean { + return e instanceof ApiClientError && e.status === 401 && e.code === 'opencode_key_invalid'; +} + +export function isUpstreamDownError(e: unknown): boolean { + if (!(e instanceof ApiClientError)) return false; + return e.status === 429 || e.status >= 500 || e.status === 0; +} + +export function mapUsageStatus(error: unknown, strings: UsageStrings): UsageStatus { + if (!error) return { kind: 'ready' }; + + if (error instanceof SessionExpiredError) { + return { kind: 'session-expired', message: strings.sessionExpired }; + } + + if (error instanceof ApiClientError) { + if (isMissingKeyError(error)) return { kind: 'missing-key' }; + if (isRejectedKeyError(error)) return { kind: 'invalid-key' }; + if (error.status === 401) { + return { kind: 'session-expired', message: strings.sessionExpired }; + } + const detailed = formatApiErrorWithId(error); + return { + kind: 'failed', + message: strings.unexpected, + upstream: isUpstreamDownError(error), + diagnostic: detailed.display, + shortId: detailed.shortId, + }; + } + + if (error instanceof Error) { + return { + kind: 'failed', + message: strings.unexpected, + upstream: false, + diagnostic: error.message, + shortId: '', + }; + } + + return { + kind: 'failed', + message: strings.unexpected, + upstream: false, + diagnostic: strings.unexpected, + shortId: '', + }; +} diff --git a/apps/frontend/src/hooks/__tests__/query-keys.test.ts b/apps/frontend/src/hooks/__tests__/query-keys.test.ts new file mode 100644 index 0000000..7243610 --- /dev/null +++ b/apps/frontend/src/hooks/__tests__/query-keys.test.ts @@ -0,0 +1,66 @@ +/** + * query-keys — centralized React Query cache identity (P0 single source). + * + * Covers: frozen key shapes (profile/usage/registries/npm), aiProviders + * scope (`?? 'all'`, empty string stays), re-export identity (same + * reference as the source hook module, no duplication drift), stability + * (same input → deep-equal key). + */ +import { describe, expect, test } from 'bun:test'; + +import { + NPM_QUERY_KEY, + PROFILE_QUERY_KEY, + REGISTRIES_QUERY_KEY, + USAGE_QUERY_KEY, + aiProvidersQueryKey, + ORGANIZATIONS_QUERY_KEY, + PROJECTS_QUERY_KEY, + organizationQueryKey, + orgMembersQueryKey, + projectQueryKey, + userQueryKey, +} from '../query-keys'; + +import { ORGANIZATIONS_QUERY_KEY as ORGS_SOURCE } from '../useOrganizations'; +import { PROJECTS_QUERY_KEY as PROJECTS_SOURCE } from '../useProjects'; +import { projectQueryKey as projectKeySource } from '../useProject'; +import { organizationQueryKey as orgKeySource } from '../useOrganization'; +import { orgMembersQueryKey as membersKeySource } from '../useOrgMembers'; +import { userQueryKey as userKeySource } from '../useUser'; + +describe('query-keys', () => { + test('frozen shapes: profile/usage/registries/npm', () => { + expect(PROFILE_QUERY_KEY).toEqual(['profile']); + expect(USAGE_QUERY_KEY).toEqual(['usage']); + expect(REGISTRIES_QUERY_KEY).toEqual(['registries']); + expect(NPM_QUERY_KEY).toEqual(['npm', 'status']); + }); + + test('aiProviders scope: nullish → all, empty string stays', () => { + expect(aiProvidersQueryKey()).toEqual(['ai-providers', 'all']); + expect(aiProvidersQueryKey(undefined)).toEqual(['ai-providers', 'all']); + expect(aiProvidersQueryKey('/proj/web')).toEqual(['ai-providers', '/proj/web']); + // `??` (not `||`): empty string is a real scope, stays as-is. + expect(aiProvidersQueryKey('')).toEqual(['ai-providers', '']); + }); + + test('re-exports: same reference as source modules (no drift)', () => { + expect(ORGANIZATIONS_QUERY_KEY).toBe(ORGS_SOURCE); + expect(PROJECTS_QUERY_KEY).toBe(PROJECTS_SOURCE); + expect(projectQueryKey).toBe(projectKeySource); + expect(organizationQueryKey).toBe(orgKeySource); + expect(orgMembersQueryKey).toBe(membersKeySource); + expect(userQueryKey).toBe(userKeySource); + }); + + test('stability: same input → deep-equal keys', () => { + expect(aiProvidersQueryKey('/a')).toEqual(aiProvidersQueryKey('/a')); + expect(projectQueryKey('id-1')).toEqual(projectQueryKey('id-1')); + expect(organizationQueryKey('org-1')).toEqual(organizationQueryKey('org-1')); + expect(orgMembersQueryKey('org-1')).toEqual(orgMembersQueryKey('org-1')); + expect(userQueryKey('user-1')).toEqual(userQueryKey('user-1')); + // Different scopes split the cache. + expect(aiProvidersQueryKey('/a')).not.toEqual(aiProvidersQueryKey('/b')); + }); +}); diff --git a/apps/frontend/src/hooks/__tests__/useAiProviders.test.tsx b/apps/frontend/src/hooks/__tests__/useAiProviders.test.tsx new file mode 100644 index 0000000..178b672 --- /dev/null +++ b/apps/frontend/src/hooks/__tests__/useAiProviders.test.tsx @@ -0,0 +1,283 @@ +/** + * useAiProviders — provider list via GET /api/opencode/config/providers + * (P2 migration). + * + * Covers: success (providers land, no skeleton flash), empty (isEmpty), + * directory scope (queryKey per directory, `?? 'all'`), toggle + * (setQueryData flip, no extra GET), configure (setQueryData + notice + + * error dismiss, no extra GET), 503 (error surfaces, bounded retry), + * 404/403 (bounded retry, loading false, error surfaces), reload + * (invalidate refetches, no skeleton flash), dismiss (clears error + + * notice locally, no refetch). + */ +import { afterEach, describe, expect, mock, test } from 'bun:test'; +import { GlobalRegistrator } from '@happy-dom/global-registrator'; + +try { + GlobalRegistrator.register({ url: 'http://localhost/' }); +} catch { + // bun runs test files in one process — second register() throws, ignore. +} + +const PROVIDERS = [ + { + id: 'openai', + name: 'OpenAI', + source: 'api', + env: ['OPENAI_API_KEY'], + models: { 'gpt-4o': {}, 'gpt-4o-mini': {} }, + }, + { + id: 'anthropic', + name: '', + source: 'api', + env: [], + models: { 'claude-3': {} }, + }, +]; + +let providersImpl: (directory?: string) => Promise = async () => ({ + data: { providers: PROVIDERS }, + error: undefined, +}); +const providersMock = mock((opts?: unknown) => { + const query = (opts as { query?: { directory?: string } } | undefined)?.query; + return providersImpl(query?.directory); +}); + +function toErrorMessageLocal(error: unknown): string { + if (error === undefined || error === null) return 'Unexpected error'; + if (typeof error === 'string') return error || 'Unexpected error'; + if (error instanceof Error) return error.message || 'Unexpected error'; + if (typeof error === 'object') { + const obj = error as Record; + if (typeof obj.message === 'string' && obj.message) return obj.message; + } + return 'Unexpected error'; +} + +mock.module('../../api/opencode-client', () => ({ + opencode: { config: { providers: providersMock } }, + toErrorMessage: toErrorMessageLocal, +})); + +const { cleanup, renderHook, act } = await import('@testing-library/react'); +const { QueryClientProvider } = await import('@tanstack/react-query'); +const { createElement, useState } = await import('react'); +const { createQueryClient } = await import('../../lib/query-client'); +const { useAiProviders } = await import('../useAiProviders'); +const { aiProvidersQueryKey } = await import('../query-keys'); + +function wrapper({ children }: { children: React.ReactNode }) { + const [client] = useState(() => createQueryClient()); + return createElement(QueryClientProvider, { client }, children); +} + +afterEach(() => { + cleanup(); + providersMock.mockClear(); + providersImpl = async () => ({ data: { providers: PROVIDERS }, error: undefined }); +}); + +async function settle(rounds = 6) { + await act(async () => { + for (let i = 0; i < rounds; i++) { + await Promise.resolve(); + await new Promise((r) => setTimeout(r, 0)); + } + }); +} + +describe('useAiProviders', () => { + test('success: providers land with mapped fields, no error', async () => { + const { result } = renderHook(() => useAiProviders(), { wrapper }); + await settle(); + + expect(providersMock).toHaveBeenCalledTimes(1); + expect(result.current.loading).toBe(false); + expect(result.current.error).toBeNull(); + expect(result.current.providers.length).toBe(2); + expect(result.current.providers[0]).toMatchObject({ + id: 'openai', + name: 'OpenAI', + enabled: true, + status: 'connected', + modelsCount: 2, + }); + // Empty name falls back to id. + expect(result.current.providers[1].name).toBe('anthropic'); + expect(result.current.isEmpty).toBe(false); + }); + + test('empty: zero providers → isEmpty without error', async () => { + providersImpl = async () => ({ data: { providers: [] }, error: undefined }); + const { result } = renderHook(() => useAiProviders(), { wrapper }); + await settle(); + + expect(result.current.loading).toBe(false); + expect(result.current.error).toBeNull(); + expect(result.current.isEmpty).toBe(true); + }); + + test('directory scope: query carries directory, key splits per scope', async () => { + const seen: Array = []; + providersImpl = async (directory?: string) => { + seen.push(directory); + return { data: { providers: PROVIDERS }, error: undefined }; + }; + const { result } = renderHook(() => useAiProviders('/proj/web'), { wrapper }); + await settle(); + + expect(providersMock).toHaveBeenCalledTimes(1); + const call = providersMock.mock.calls[0]?.[0] as + | { query?: { directory?: string } } + | undefined; + expect(call?.query?.directory).toBe('/proj/web'); + expect(result.current.providers.length).toBe(2); + // Key identity: nullish → 'all', empty string stays as-is. + expect(aiProvidersQueryKey()).toEqual(['ai-providers', 'all']); + expect(aiProvidersQueryKey(undefined)).toEqual(['ai-providers', 'all']); + expect(aiProvidersQueryKey('')).toEqual(['ai-providers', '']); + expect(aiProvidersQueryKey('/proj/web')).toEqual(['ai-providers', '/proj/web']); + expect(seen).toEqual(['/proj/web']); + }); + + test('toggle: setQueryData flips enabled, no extra GET', async () => { + const { result } = renderHook(() => useAiProviders(), { wrapper }); + await settle(); + expect(providersMock).toHaveBeenCalledTimes(1); + expect(result.current.providers[0].enabled).toBe(true); + + act(() => { + result.current.toggle('openai'); + }); + + expect(result.current.providers[0].enabled).toBe(false); + expect(result.current.notice).toBeNull(); + expect(providersMock).toHaveBeenCalledTimes(1); + + act(() => { + result.current.toggle('openai'); + }); + expect(result.current.providers[0].enabled).toBe(true); + expect(providersMock).toHaveBeenCalledTimes(1); + }); + + test('configure: setQueryData + notice, error dismissed, no extra GET', async () => { + providersImpl = async () => ({ data: undefined, error: { message: 'boom' } }); + const { result } = renderHook(() => useAiProviders(), { wrapper }); + await settle(8); + expect(result.current.error).not.toBeNull(); + + // Seed success then configure — configure hides the query error locally. + providersImpl = async () => ({ data: { providers: PROVIDERS }, error: undefined }); + act(() => { + result.current.reload(); + }); + await settle(); + expect(result.current.error).toBeNull(); + + act(() => { + result.current.configure('openai'); + }); + + expect(result.current.providers[0].enabled).toBe(true); + expect(result.current.providers[0].status).toBe('connected'); + expect(result.current.notice).not.toBeNull(); + expect(result.current.notice).toContain('OpenAI'); + }); + + test('503: surfaces as error with bounded retry, no mock rows', async () => { + providersImpl = async () => { + throw new Error('upstream down'); + }; + const { result } = renderHook(() => useAiProviders(), { wrapper }); + await settle(8); + + expect(result.current.loading).toBe(false); + expect(result.current.providers).toEqual([]); + expect(result.current.error).not.toBeNull(); + expect(result.current.isEmpty).toBe(false); + // retry: 1 → at most 2 attempts, never a storm. + expect(providersMock.mock.calls.length).toBeLessThanOrEqual(2); + }); + + test('404/403: bounded retry (no storm), loading false, error surfaces', async () => { + for (const status of [404, 403]) { + providersImpl = async () => { + const err = new Error(status === 404 ? 'not found' : 'forbidden'); + (err as unknown as Record).status = status; + throw err; + }; + const scoped = renderHook(() => useAiProviders(`scope-${status}`), { wrapper }); + await settle(8); + + expect(scoped.result.current.loading).toBe(false); + expect(scoped.result.current.providers).toEqual([]); + expect(scoped.result.current.error).not.toBeNull(); + expect(providersMock.mock.calls.length).toBeLessThanOrEqual(4); + scoped.unmount(); + cleanup(); + providersMock.mockClear(); + providersImpl = async () => ({ data: { providers: PROVIDERS }, error: undefined }); + } + }); + + test('sdk error tuple: { error } maps to error text', async () => { + providersImpl = async () => ({ data: undefined, error: { message: 'sdk boom' } }); + const { result } = renderHook(() => useAiProviders(), { wrapper }); + await settle(8); + + expect(result.current.loading).toBe(false); + expect(result.current.providers).toEqual([]); + expect(result.current.error).toContain('sdk boom'); + }); + + test('reload: invalidate refetches without skeleton flash', async () => { + const { result } = renderHook(() => useAiProviders(), { wrapper }); + await settle(); + expect(providersMock).toHaveBeenCalledTimes(1); + expect(result.current.loading).toBe(false); + + act(() => { + result.current.reload(); + }); + // Background refetch keeps previous data — no skeleton flash. + expect(result.current.loading).toBe(false); + expect(result.current.providers.length).toBe(2); + await settle(); + + expect(providersMock).toHaveBeenCalledTimes(2); + }); + + test('dismiss: clears error + notice locally, no refetch', async () => { + providersImpl = async () => ({ data: undefined, error: { message: 'boom' } }); + const { result } = renderHook(() => useAiProviders(), { wrapper }); + await settle(8); + expect(result.current.error).not.toBeNull(); + const calls = providersMock.mock.calls.length; + + act(() => { + result.current.dismiss(); + }); + + expect(result.current.error).toBeNull(); + expect(result.current.notice).toBeNull(); + expect(providersMock.mock.calls.length).toBe(calls); + }); + + test('dedup: two observers share one GET on a shared client', async () => { + const client = createQueryClient(); + const shared = ({ children }: { children: React.ReactNode }) => + createElement(QueryClientProvider, { client }, children); + + const a = renderHook(() => useAiProviders(), { wrapper: shared }); + const b = renderHook(() => useAiProviders(), { wrapper: shared }); + await settle(); + + expect(providersMock).toHaveBeenCalledTimes(1); + expect(a.result.current.providers).toEqual(b.result.current.providers); + a.unmount(); + b.unmount(); + }); +}); diff --git a/apps/frontend/src/hooks/__tests__/useNpm.test.tsx b/apps/frontend/src/hooks/__tests__/useNpm.test.tsx index 02d137a..56bf25d 100644 --- a/apps/frontend/src/hooks/__tests__/useNpm.test.tsx +++ b/apps/frontend/src/hooks/__tests__/useNpm.test.tsx @@ -1,9 +1,10 @@ /** - * useNpm — live status through GET /api/v1/registry/npm/status. + * useNpm — live status through GET /api/v1/registry/npm/status + * via TanStack Query (P3 migration). * * Covers: success (status/up + url/scope → single up package), * 503 (EXTERNAL_UNAVAILABLE surfaces as error with retry, no mock rows), - * reload (nonce refetch). + * reload (invalidate refetch). */ import { afterEach, describe, expect, mock, test } from 'bun:test'; import { GlobalRegistrator } from '@happy-dom/global-registrator'; @@ -40,8 +41,16 @@ mock.module('../../api/client', () => ({ })); const { cleanup, renderHook, act } = await import('@testing-library/react'); +const { QueryClientProvider } = await import('@tanstack/react-query'); +const { createElement, useState } = await import('react'); +const { createQueryClient } = await import('../../lib/query-client'); const { useNpm } = await import('../useNpm'); +function wrapper({ children }: { children: React.ReactNode }) { + const [client] = useState(() => createQueryClient()); + return createElement(QueryClientProvider, { client }, children); +} + afterEach(() => { cleanup(); statusMock.mockClear(); @@ -52,17 +61,18 @@ afterEach(() => { }); }); -async function settle() { +async function settle(rounds = 4) { await act(async () => { - await Promise.resolve(); - await new Promise((r) => setTimeout(r, 0)); - await new Promise((r) => setTimeout(r, 0)); + for (let i = 0; i < rounds; i++) { + await Promise.resolve(); + await new Promise((r) => setTimeout(r, 0)); + } }); } describe('useNpm', () => { test('200: live status lands on a single up package', async () => { - const { result } = renderHook(() => useNpm()); + const { result } = renderHook(() => useNpm(), { wrapper }); await settle(); expect(statusMock).toHaveBeenCalledTimes(1); @@ -87,7 +97,7 @@ describe('useNpm', () => { correlationId: 'corr-1', }); }; - const { result } = renderHook(() => useNpm()); + const { result } = renderHook(() => useNpm(), { wrapper }); await settle(); expect(result.current.loading).toBe(false); @@ -97,7 +107,7 @@ describe('useNpm', () => { expect(result.current.isEmpty).toBe(false); }); - test('reload: retry refetches the status', async () => { + test('reload: invalidate refetches the status', async () => { statusImpl = async () => { throw new FakeApiClientError({ code: 'EXTERNAL_UNAVAILABLE', @@ -106,7 +116,7 @@ describe('useNpm', () => { correlationId: 'corr-1', }); }; - const { result } = renderHook(() => useNpm()); + const { result } = renderHook(() => useNpm(), { wrapper }); await settle(); expect(result.current.error).not.toBeNull(); expect(statusMock).toHaveBeenCalledTimes(1); @@ -125,4 +135,61 @@ describe('useNpm', () => { expect(result.current.error).toBeNull(); expect(result.current.packages[0].scope).toBe('@web2bizz'); }); + + test('404: bounded retry (no storm), error surfaces, loading false', async () => { + statusImpl = async () => { + throw new FakeApiClientError({ + code: 'not_found', + message: 'not found', + status: 404, + correlationId: 'corr-404', + }); + }; + const { result } = renderHook(() => useNpm(), { wrapper }); + await settle(8); + + // retry: 1 → at most 2 attempts, never a storm. + expect(statusMock.mock.calls.length).toBeLessThanOrEqual(2); + expect(result.current.loading).toBe(false); + expect(result.current.packages).toEqual([]); + expect(result.current.error).not.toBeNull(); + expect(result.current.error).toContain('not_found'); + expect(result.current.isEmpty).toBe(false); + }); + + test('403: bounded retry (no storm), error surfaces (forbidden)', async () => { + statusImpl = async () => { + throw new FakeApiClientError({ + code: 'forbidden', + message: 'forbidden', + status: 403, + correlationId: 'corr-403', + }); + }; + const { result } = renderHook(() => useNpm(), { wrapper }); + await settle(8); + + expect(statusMock.mock.calls.length).toBeLessThanOrEqual(2); + expect(result.current.loading).toBe(false); + expect(result.current.error).not.toBeNull(); + expect(result.current.error).toContain('forbidden'); + }); + + test('reload keeps data (no skeleton flash, background refetch)', async () => { + const { result } = renderHook(() => useNpm(), { wrapper }); + await settle(); + expect(result.current.packages.length).toBe(1); + expect(result.current.loading).toBe(false); + + act(() => { + result.current.reload(); + }); + // placeholderData keeps previous data — no skeleton flash. + expect(result.current.loading).toBe(false); + expect(result.current.packages.length).toBe(1); + await settle(); + + expect(statusMock).toHaveBeenCalledTimes(2); + expect(result.current.error).toBeNull(); + }); }); diff --git a/apps/frontend/src/hooks/__tests__/useProfile.test.tsx b/apps/frontend/src/hooks/__tests__/useProfile.test.tsx new file mode 100644 index 0000000..14f1552 --- /dev/null +++ b/apps/frontend/src/hooks/__tests__/useProfile.test.tsx @@ -0,0 +1,302 @@ +/** + * useProfile / useHeaderProfile — TanStack Query migration (P1). + * + * Covers: success (GET lands, no skeleton flash), header+page dedup (one + * GET /auth/me for both observers on a shared client), update (PATCH + + * setQueryData, no extra GET, saved flag), validation (blank name → false), + * 401 refresh retry (one silent retry, then profile), dead session (401 + + * spent refresh → sessionExpired, no react-query retry), reload (invalidate). + */ +import { afterEach, describe, expect, mock, test } from 'bun:test'; +import { GlobalRegistrator } from '@happy-dom/global-registrator'; + +try { + GlobalRegistrator.register({ url: 'http://localhost/' }); +} catch { + // bun runs test files in one process — second register() throws, ignore. +} + +class FakeApiClientError extends Error { + code: string; + status: number; + correlationId: string; + constructor(args: { code: string; message: string; status: number; correlationId: string }) { + super(args.message); + this.name = 'ApiClientError'; + this.code = args.code; + this.status = args.status; + this.correlationId = args.correlationId; + } +} + +const ME_USER = { + id: 'mock-user-1', + firstName: 'Devbox', + lastName: 'Developer', + email: 'dev@devbox.local', + provider: 'local' as const, + createdAt: '2026-01-15T09:00:00.000Z', +}; + +let meImpl: () => Promise = async () => ({ ...ME_USER }); +const meMock = mock(() => meImpl()); +const updateMeMock = mock(async (_token: string, patch: { firstName?: string; lastName?: string }) => ({ + ...ME_USER, + firstName: patch.firstName ?? ME_USER.firstName, + lastName: patch.lastName ?? ME_USER.lastName, +})); + +let tokenImpl: () => Promise = async () => 'test-token'; +let refreshImpl: () => Promise = async () => 'test-token'; +const getValidAccessTokenMock = mock(() => tokenImpl()); +const refreshAccessTokenMock = mock(() => refreshImpl()); + +mock.module('../../api/client', () => ({ + ApiClientError: FakeApiClientError, + api: { me: meMock, updateMe: updateMeMock }, +})); + +mock.module('../../lib/auth-store', () => ({ + getValidAccessToken: getValidAccessTokenMock, + refreshAccessToken: refreshAccessTokenMock, +})); + +const { cleanup, renderHook, act } = await import('@testing-library/react'); +const { QueryClientProvider } = await import('@tanstack/react-query'); +const { createElement, useState } = await import('react'); +const { createQueryClient } = await import('../../lib/query-client'); +const { useProfile, useHeaderProfile } = await import('../useProfile'); + +function wrapper({ children }: { children: React.ReactNode }) { + const [client] = useState(() => createQueryClient()); + return createElement(QueryClientProvider, { client }, children); +} + +afterEach(() => { + cleanup(); + meMock.mockClear(); + updateMeMock.mockClear(); + getValidAccessTokenMock.mockClear(); + refreshAccessTokenMock.mockClear(); + meImpl = async () => ({ ...ME_USER }); + tokenImpl = async () => 'test-token'; + refreshImpl = async () => 'test-token'; +}); + +async function settle(rounds = 4) { + await act(async () => { + for (let i = 0; i < rounds; i++) { + await Promise.resolve(); + await new Promise((r) => setTimeout(r, 0)); + } + }); +} + +describe('useProfile', () => { + test('success: GET /auth/me lands as Profile, no error', async () => { + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(); + + expect(meMock).toHaveBeenCalledTimes(1); + expect(meMock).toHaveBeenCalledWith('test-token'); + expect(result.current.loading).toBe(false); + expect(result.current.error).toBeNull(); + expect(result.current.profile).toEqual({ + id: 'mock-user-1', + name: 'Devbox Developer', + email: 'dev@devbox.local', + createdAt: '2026-01-15T09:00:00.000Z', + }); + expect(result.current.saved).toBe(false); + expect(result.current.saving).toBe(false); + }); + + test('dedup: header + page observers share one GET on a shared client', async () => { + const client = createQueryClient(); + const shared = ({ children }: { children: React.ReactNode }) => + createElement(QueryClientProvider, { client }, children); + + const page = renderHook(() => useProfile(), { wrapper: shared }); + const header = renderHook(() => useHeaderProfile(), { wrapper: shared }); + await settle(); + + // Two observers, one cache entry, one network request. + expect(meMock).toHaveBeenCalledTimes(1); + expect(page.result.current.profile).toEqual(header.result.current.profile); + expect(header.result.current.profile?.name).toBe('Devbox Developer'); + expect(header.result.current.loading).toBe(false); + page.unmount(); + header.unmount(); + }); + + test('update: PATCH + setQueryData (no extra GET), saved flag', async () => { + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(); + expect(meMock).toHaveBeenCalledTimes(1); + + let ok = false; + await act(async () => { + ok = await result.current.update({ name: 'Jane Doe' }); + }); + await settle(); + + expect(ok).toBe(true); + expect(updateMeMock).toHaveBeenCalledTimes(1); + expect(updateMeMock).toHaveBeenCalledWith('test-token', { + firstName: 'Jane', + lastName: 'Doe', + }); + expect(result.current.profile?.name).toBe('Jane Doe'); + expect(result.current.saved).toBe(true); + expect(result.current.saving).toBe(false); + expect(result.current.error).toBeNull(); + // Cache patched directly — no background GET after update. + expect(meMock).toHaveBeenCalledTimes(1); + }); + + test('validation: blank name → false, no PATCH', async () => { + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(); + + let ok = true; + await act(async () => { + ok = await result.current.update({ name: ' ' }); + }); + + expect(ok).toBe(false); + expect(updateMeMock).not.toHaveBeenCalled(); + expect(result.current.error).toBe('Name must not be empty.'); + expect(result.current.saved).toBe(false); + }); + + test('401: one silent refresh retry, then profile', async () => { + let calls = 0; + meImpl = async () => { + calls += 1; + if (calls === 1) { + throw new FakeApiClientError({ + code: 'unauthorized', + message: 'Unauthorized', + status: 401, + correlationId: 'corr-1', + }); + } + return { ...ME_USER }; + }; + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(); + + expect(refreshAccessTokenMock).toHaveBeenCalled(); + expect(meMock).toHaveBeenCalledTimes(2); + expect(result.current.profile?.name).toBe('Devbox Developer'); + expect(result.current.error).toBeNull(); + }); + + test('dead session: 401 + spent refresh → sessionExpired, no retry storm', async () => { + meImpl = async () => { + throw new FakeApiClientError({ + code: 'unauthorized', + message: 'Unauthorized', + status: 401, + correlationId: 'corr-2', + }); + }; + refreshImpl = async () => null; + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(); + + expect(meMock).toHaveBeenCalledTimes(1); + expect(result.current.loading).toBe(false); + expect(result.current.profile).toBeNull(); + expect(result.current.error).toBe('Session expired — please sign in again.'); + }); + + test('reload: invalidate refetches the profile', async () => { + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(); + expect(meMock).toHaveBeenCalledTimes(1); + + act(() => { + result.current.reload(); + }); + await settle(); + + expect(meMock).toHaveBeenCalledTimes(2); + }); + + test('dismiss: clears mutation error locally, cache untouched', async () => { + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(); + + await act(async () => { + await result.current.update({ name: ' ' }); + }); + expect(result.current.error).not.toBeNull(); + + act(() => { + result.current.dismiss(); + }); + + expect(result.current.error).toBeNull(); + expect(result.current.saved).toBe(false); + // No refetch on dismiss — cache entry stays, single initial GET. + expect(meMock).toHaveBeenCalledTimes(1); + }); + + test('404: bounded retry (no storm), error surfaces, loading false', async () => { + meImpl = async () => { + throw new FakeApiClientError({ + code: 'not_found', + message: 'not found', + status: 404, + correlationId: 'corr-404', + }); + }; + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(8); + + // profileRetry allows at most one retry for non-terminal states. + expect(meMock.mock.calls.length).toBeLessThanOrEqual(2); + expect(result.current.loading).toBe(false); + expect(result.current.profile).toBeNull(); + expect(result.current.error).not.toBeNull(); + expect(result.current.error).toContain('not_found'); + }); + + test('403: bounded retry (no storm), error surfaces, loading false', async () => { + meImpl = async () => { + throw new FakeApiClientError({ + code: 'forbidden', + message: 'forbidden', + status: 403, + correlationId: 'corr-403', + }); + }; + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(8); + + expect(meMock.mock.calls.length).toBeLessThanOrEqual(2); + expect(result.current.loading).toBe(false); + expect(result.current.profile).toBeNull(); + expect(result.current.error).not.toBeNull(); + expect(result.current.error).toContain('forbidden'); + }); + + test('reload keeps data (no skeleton flash, background refetch)', async () => { + const { result } = renderHook(() => useProfile(), { wrapper }); + await settle(); + expect(result.current.profile?.name).toBe('Devbox Developer'); + expect(result.current.loading).toBe(false); + + act(() => { + result.current.reload(); + }); + // placeholderData keeps previous data — no skeleton flash. + expect(result.current.loading).toBe(false); + expect(result.current.profile?.name).toBe('Devbox Developer'); + await settle(); + + expect(meMock).toHaveBeenCalledTimes(2); + expect(result.current.error).toBeNull(); + }); +}); diff --git a/apps/frontend/src/hooks/__tests__/useRegistries.test.tsx b/apps/frontend/src/hooks/__tests__/useRegistries.test.tsx index 5a22a7c..99009dc 100644 --- a/apps/frontend/src/hooks/__tests__/useRegistries.test.tsx +++ b/apps/frontend/src/hooks/__tests__/useRegistries.test.tsx @@ -1,9 +1,10 @@ /** - * useRegistries — live catalog through GET /api/v1/registry/catalog. + * useRegistries — live catalog through GET /api/v1/registry/catalog + * via TanStack Query (P3 migration). * * Covers: success (repositories → single up registry), empty catalog * (registry with zero repos), 503 (EXTERNAL_UNAVAILABLE surfaces as - * error with retry, no mock payloads), reload (nonce refetch). + * error with retry, no mock payloads), reload (invalidate refetch). */ import { afterEach, describe, expect, mock, test } from 'bun:test'; import { GlobalRegistrator } from '@happy-dom/global-registrator'; @@ -38,25 +39,34 @@ mock.module('../../api/client', () => ({ })); const { cleanup, renderHook, act } = await import('@testing-library/react'); +const { QueryClientProvider } = await import('@tanstack/react-query'); +const { createElement, useState } = await import('react'); +const { createQueryClient } = await import('../../lib/query-client'); const { useRegistries } = await import('../useRegistries'); +function wrapper({ children }: { children: React.ReactNode }) { + const [client] = useState(() => createQueryClient()); + return createElement(QueryClientProvider, { client }, children); +} + afterEach(() => { cleanup(); catalogMock.mockClear(); catalogImpl = async () => ({ repositories: ['library/nginx', 'team/app'] }); }); -async function settle() { +async function settle(rounds = 4) { await act(async () => { - await Promise.resolve(); - await new Promise((r) => setTimeout(r, 0)); - await new Promise((r) => setTimeout(r, 0)); + for (let i = 0; i < rounds; i++) { + await Promise.resolve(); + await new Promise((r) => setTimeout(r, 0)); + } }); } describe('useRegistries', () => { test('success: live repositories land on a single up registry', async () => { - const { result } = renderHook(() => useRegistries()); + const { result } = renderHook(() => useRegistries(), { wrapper }); await settle(); expect(catalogMock).toHaveBeenCalledTimes(1); @@ -73,7 +83,7 @@ describe('useRegistries', () => { test('empty: catalog without repos keeps the registry with zero repos', async () => { catalogImpl = async () => ({ repositories: [] }); - const { result } = renderHook(() => useRegistries()); + const { result } = renderHook(() => useRegistries(), { wrapper }); await settle(); expect(result.current.loading).toBe(false); @@ -92,7 +102,7 @@ describe('useRegistries', () => { correlationId: 'corr-1', }); }; - const { result } = renderHook(() => useRegistries()); + const { result } = renderHook(() => useRegistries(), { wrapper }); await settle(); expect(result.current.loading).toBe(false); @@ -102,7 +112,7 @@ describe('useRegistries', () => { expect(result.current.isEmpty).toBe(false); }); - test('reload: retry refetches the catalog', async () => { + test('reload: invalidate refetches the catalog', async () => { catalogImpl = async () => { throw new FakeApiClientError({ code: 'EXTERNAL_UNAVAILABLE', @@ -111,7 +121,7 @@ describe('useRegistries', () => { correlationId: 'corr-1', }); }; - const { result } = renderHook(() => useRegistries()); + const { result } = renderHook(() => useRegistries(), { wrapper }); await settle(); expect(result.current.error).not.toBeNull(); expect(catalogMock).toHaveBeenCalledTimes(1); @@ -126,4 +136,61 @@ describe('useRegistries', () => { expect(result.current.error).toBeNull(); expect(result.current.registries[0].repositories).toEqual(['library/redis']); }); + + test('404: bounded retry (no storm), error surfaces, loading false', async () => { + catalogImpl = async () => { + throw new FakeApiClientError({ + code: 'not_found', + message: 'not found', + status: 404, + correlationId: 'corr-404', + }); + }; + const { result } = renderHook(() => useRegistries(), { wrapper }); + await settle(8); + + // retry: 1 → at most 2 attempts, never a storm. + expect(catalogMock.mock.calls.length).toBeLessThanOrEqual(2); + expect(result.current.loading).toBe(false); + expect(result.current.registries).toEqual([]); + expect(result.current.error).not.toBeNull(); + expect(result.current.error).toContain('not_found'); + expect(result.current.isEmpty).toBe(false); + }); + + test('403: bounded retry (no storm), error surfaces (forbidden)', async () => { + catalogImpl = async () => { + throw new FakeApiClientError({ + code: 'forbidden', + message: 'forbidden', + status: 403, + correlationId: 'corr-403', + }); + }; + const { result } = renderHook(() => useRegistries(), { wrapper }); + await settle(8); + + expect(catalogMock.mock.calls.length).toBeLessThanOrEqual(2); + expect(result.current.loading).toBe(false); + expect(result.current.error).not.toBeNull(); + expect(result.current.error).toContain('forbidden'); + }); + + test('reload keeps data (no skeleton flash, background refetch)', async () => { + const { result } = renderHook(() => useRegistries(), { wrapper }); + await settle(); + expect(result.current.registries.length).toBe(1); + expect(result.current.loading).toBe(false); + + act(() => { + result.current.reload(); + }); + // placeholderData keeps previous data — no skeleton flash. + expect(result.current.loading).toBe(false); + expect(result.current.registries.length).toBe(1); + await settle(); + + expect(catalogMock).toHaveBeenCalledTimes(2); + expect(result.current.error).toBeNull(); + }); }); diff --git a/apps/frontend/src/hooks/__tests__/useUsage.test.tsx b/apps/frontend/src/hooks/__tests__/useUsage.test.tsx new file mode 100644 index 0000000..752d823 --- /dev/null +++ b/apps/frontend/src/hooks/__tests__/useUsage.test.tsx @@ -0,0 +1,301 @@ +/** + * useUsage — live quota/usage via GET /api/v1/usage (P2 migration). + * + * Covers: success (data lands, no skeleton flash), 401 session refresh + * (one silent retry, then data), dead session (401 + spent refresh → + * sessionExpired, no retry storm), 404 missing-key (noKeyMissing, error + * null, no refresh, no retry), 401 invalid-key (noKeyInvalid, error null, + * no refresh), 404/403 terminal shape (bounded retry, loading false, + * error surfaces), 503/429 upstreamDown (error + upstreamDown, no fake + * 0% bars), reload (invalidate refetches, no skeleton flash with + * placeholderData). + */ +import { afterEach, describe, expect, mock, test } from 'bun:test'; +import { GlobalRegistrator } from '@happy-dom/global-registrator'; + +try { + GlobalRegistrator.register({ url: 'http://localhost/' }); +} catch { + // bun runs test files in one process — second register() throws, ignore. +} + +class FakeApiClientError extends Error { + code: string; + status: number; + correlationId: string; + constructor(args: { code: string; message: string; status: number; correlationId: string }) { + super(args.message); + this.name = 'ApiClientError'; + this.code = args.code; + this.status = args.status; + this.correlationId = args.correlationId; + } +} + +const USAGE = { + updatedAt: '2026-10-19T00:00:00.000Z', + rolling: { used: 42, limit: 100 }, + weekly: { used: 10, limit: 100 }, +}; + +let usageImpl: () => Promise = async () => ({ ...USAGE }); +const getUsageMock = mock(() => usageImpl()); + +let tokenImpl: () => Promise = async () => 'test-token'; +let refreshImpl: () => Promise = async () => 'test-token'; +const getValidAccessTokenMock = mock(() => tokenImpl()); +const refreshAccessTokenMock = mock(() => refreshImpl()); + +mock.module('../../api/client', () => ({ + ApiClientError: FakeApiClientError, + api: { getUsage: getUsageMock }, +})); + +mock.module('../../lib/auth-store', () => ({ + getValidAccessToken: getValidAccessTokenMock, + refreshAccessToken: refreshAccessTokenMock, +})); + +const { cleanup, renderHook, act } = await import('@testing-library/react'); +const { QueryClientProvider } = await import('@tanstack/react-query'); +const { createElement, useState } = await import('react'); +const { createQueryClient } = await import('../../lib/query-client'); +const { useUsage } = await import('../useUsage'); + +function wrapper({ children }: { children: React.ReactNode }) { + const [client] = useState(() => { + const c = createQueryClient(); + // The hook passes a function `retry` (one retry on transient failures), + // which overrides the test default `retry: false`. Collapse the + // production backoff so the single retry settles inside `settle()`. + c.setDefaultOptions({ queries: { retryDelay: 0 } }); + return c; + }); + return createElement(QueryClientProvider, { client }, children); +} + +afterEach(() => { + cleanup(); + getUsageMock.mockClear(); + getValidAccessTokenMock.mockClear(); + refreshAccessTokenMock.mockClear(); + usageImpl = async () => ({ ...USAGE }); + tokenImpl = async () => 'test-token'; + refreshImpl = async () => 'test-token'; +}); + +async function settle(rounds = 6) { + await act(async () => { + for (let i = 0; i < rounds; i++) { + await Promise.resolve(); + await new Promise((r) => setTimeout(r, 0)); + } + }); +} + +describe('useUsage', () => { + test('success: usage lands, no error, no skeleton flash', async () => { + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(); + + expect(getUsageMock).toHaveBeenCalledTimes(1); + expect(getUsageMock).toHaveBeenCalledWith('test-token'); + expect(result.current.loading).toBe(false); + expect(result.current.error).toBeNull(); + expect(result.current.usage).toMatchObject({ rolling: { used: 42, limit: 100 } }); + expect(result.current.noKey).toBe(false); + expect(result.current.noKeyMissing).toBe(false); + expect(result.current.noKeyInvalid).toBe(false); + expect(result.current.upstreamDown).toBe(false); + expect(result.current.upstreamUnavailable).toBe(false); + }); + + test('401 session: one silent refresh retry, then data', async () => { + let calls = 0; + usageImpl = async () => { + calls += 1; + if (calls === 1) { + throw new FakeApiClientError({ + code: 'unauthorized', + message: 'Unauthorized', + status: 401, + correlationId: 'corr-401', + }); + } + return { ...USAGE }; + }; + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(); + + expect(refreshAccessTokenMock).toHaveBeenCalled(); + expect(getUsageMock).toHaveBeenCalledTimes(2); + expect(result.current.usage).not.toBeNull(); + expect(result.current.error).toBeNull(); + expect(result.current.noKeyInvalid).toBe(false); + }); + + test('dead session: 401 + spent refresh → sessionExpired, no retry storm', async () => { + usageImpl = async () => { + throw new FakeApiClientError({ + code: 'unauthorized', + message: 'Unauthorized', + status: 401, + correlationId: 'corr-dead', + }); + }; + refreshImpl = async () => null; + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(); + + // Single attempt — terminal session state never retries. + expect(getUsageMock).toHaveBeenCalledTimes(1); + expect(result.current.loading).toBe(false); + expect(result.current.usage).toBeNull(); + expect(result.current.error).toBe('Session expired — please sign in again.'); + }); + + test('404 missing-key: noKeyMissing, error null, no refresh, no retry', async () => { + usageImpl = async () => { + throw new FakeApiClientError({ + code: 'opencode_key_missing', + message: 'no stored key', + status: 404, + correlationId: 'corr-404', + }); + }; + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(); + + expect(refreshAccessTokenMock).not.toHaveBeenCalled(); + expect(getUsageMock).toHaveBeenCalledTimes(1); + expect(result.current.noKey).toBe(true); + expect(result.current.noKeyMissing).toBe(true); + expect(result.current.noKeyInvalid).toBe(false); + expect(result.current.upstreamDown).toBe(false); + expect(result.current.error).toBeNull(); + expect(result.current.usage).toBeNull(); + expect(result.current.loading).toBe(false); + }); + + test('401 invalid-key: noKeyInvalid, error null, no refresh loop', async () => { + usageImpl = async () => { + throw new FakeApiClientError({ + code: 'opencode_key_invalid', + message: 'stored key rejected upstream', + status: 401, + correlationId: 'corr-401k', + }); + }; + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(); + + expect(refreshAccessTokenMock).not.toHaveBeenCalled(); + expect(getUsageMock).toHaveBeenCalledTimes(1); + expect(result.current.noKey).toBe(true); + expect(result.current.noKeyInvalid).toBe(true); + expect(result.current.noKeyMissing).toBe(false); + expect(result.current.error).toBeNull(); + expect(result.current.usage).toBeNull(); + }); + + test('404 generic: bounded retry (no storm), unexpected + diagnostic', async () => { + usageImpl = async () => { + throw new FakeApiClientError({ + code: 'not_found', + message: 'missing', + status: 404, + correlationId: 'corr-g404', + }); + }; + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(8); + + // usageRetry only exempts the missing-key 404 — generic 404 gets at + // most one retry, never an infinite storm. + expect(getUsageMock.mock.calls.length).toBeLessThanOrEqual(2); + expect(result.current.loading).toBe(false); + // Raw `code: message` never reaches the UI — only unexpected + diagnostic. + expect(result.current.error).toBe('Unexpected error'); + expect(result.current.diagnostic).toContain('not_found'); + expect(result.current.shortId).toBe('corr-g40'); + expect(result.current.noKeyMissing).toBe(false); + expect(result.current.upstreamDown).toBe(false); + }); + + test('403 forbidden: bounded retry (no storm), unexpected + diagnostic', async () => { + usageImpl = async () => { + throw new FakeApiClientError({ + code: 'forbidden', + message: 'forbidden', + status: 403, + correlationId: 'corr-403', + }); + }; + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(8); + + expect(getUsageMock.mock.calls.length).toBeLessThanOrEqual(2); + expect(result.current.loading).toBe(false); + expect(result.current.error).toBe('Unexpected error'); + expect(result.current.diagnostic).toContain('forbidden'); + expect(result.current.shortId).toBe('corr-403'); + expect(result.current.usage).toBeNull(); + }); + + test('503: upstreamDown with unexpected + diagnostic, usage nulled (no fake 0% bars)', async () => { + usageImpl = async () => { + throw new FakeApiClientError({ + code: 'EXTERNAL_UNAVAILABLE', + message: 'upstream down', + status: 503, + correlationId: 'corr-503', + }); + }; + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(8); + + expect(result.current.loading).toBe(false); + expect(result.current.usage).toBeNull(); + expect(result.current.upstreamDown).toBe(true); + expect(result.current.upstreamUnavailable).toBe(true); + expect(result.current.error).toBe('Unexpected error'); + expect(result.current.diagnostic).toContain('EXTERNAL_UNAVAILABLE'); + expect(result.current.shortId).toBe('corr-503'); + }); + + test('429: throttled counts as upstreamDown', async () => { + usageImpl = async () => { + throw new FakeApiClientError({ + code: 'rate_limited', + message: 'too many requests', + status: 429, + correlationId: 'corr-429', + }); + }; + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(8); + + expect(result.current.upstreamDown).toBe(true); + expect(result.current.error).toBe('Unexpected error'); + expect(result.current.diagnostic).toContain('rate_limited'); + expect(result.current.usage).toBeNull(); + }); + + test('reload: invalidate refetches without skeleton flash', async () => { + const { result } = renderHook(() => useUsage(), { wrapper }); + await settle(); + expect(getUsageMock).toHaveBeenCalledTimes(1); + expect(result.current.loading).toBe(false); + + act(() => { + result.current.reload(); + }); + // Background refetch keeps previous data — no skeleton flash. + expect(result.current.loading).toBe(false); + expect(result.current.usage).not.toBeNull(); + await settle(); + + expect(getUsageMock).toHaveBeenCalledTimes(2); + expect(result.current.error).toBeNull(); + }); +}); diff --git a/apps/frontend/src/hooks/query-keys.ts b/apps/frontend/src/hooks/query-keys.ts new file mode 100644 index 0000000..7d0f176 --- /dev/null +++ b/apps/frontend/src/hooks/query-keys.ts @@ -0,0 +1,44 @@ +/** + * Centralized React Query keys — single source for cache identity. + * + * Cache contract (unchanged, lives in `lib/query-client.ts`): + * - staleTime 30s, gcTime 5m, retry 1 with exponential backoff. + * - `refetchOnWindowFocus: false`, `refetchOnReconnect: true`. + * - Auth refresh contract unchanged: `getValidAccessToken()` inside + * `queryFn`, one silent `refreshAccessToken()` retry on 401, then + * the session-expired message (see `lib/auth-store.ts`). + * + * Hook rule (enforced by P1–P3 migrations, not by this module): + * - `queryFn` throws the raw backend envelope on failure (never formats). + * - `formatApiError(error) + t` mapping lives in `useMemo` outside `queryFn`. + * + * Reused keys below are re-exported (not duplicated) so P1–P3 can migrate + * hook imports here without changing cache identity. + */ + +export { PROJECTS_QUERY_KEY } from './useProjects'; +export { ORGANIZATIONS_QUERY_KEY } from './useOrganizations'; +export { projectQueryKey } from './useProject'; +export { organizationQueryKey } from './useOrganization'; +export { orgMembersQueryKey } from './useOrgMembers'; +export { userQueryKey } from './useUser'; + +/** GET /api/v1/auth/me — header + profile identity. */ +export const PROFILE_QUERY_KEY = ['profile'] as const; + +/** GET /api/v1/usage — opencode quota/usage breakdown. */ +export const USAGE_QUERY_KEY = ['usage'] as const; + +/** GET /api/v1/registry/catalog — live Docker Registry catalog. */ +export const REGISTRIES_QUERY_KEY = ['registries'] as const; + +/** Live npm reachability probe (single-row status list). */ +export const NPM_QUERY_KEY = ['npm', 'status'] as const; + +/** + * GET /api/opencode/config/providers — per-directory provider list. + * Nullish directory maps to the shared `'all'` scope so the + * default view has one stable cache entry (`??`, empty string stays as-is). + */ +export const aiProvidersQueryKey = (directory?: string) => + ['ai-providers', directory ?? 'all'] as const; diff --git a/apps/frontend/src/hooks/useAiProviders.ts b/apps/frontend/src/hooks/useAiProviders.ts index ee30f05..fe82351 100644 --- a/apps/frontend/src/hooks/useAiProviders.ts +++ b/apps/frontend/src/hooks/useAiProviders.ts @@ -1,10 +1,12 @@ 'use client'; -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useMemo, useState } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; import { opencode, toErrorMessage } from '../api/opencode-client'; import { formatApiError } from '../lib/format-error'; import type { AiProvider } from '../lib/types'; import { useI18n } from '../i18n'; +import { aiProvidersQueryKey } from './query-keys'; export interface UseAiProvidersResult { providers: AiProvider[]; @@ -19,91 +21,129 @@ export interface UseAiProvidersResult { } /** - * Live provider list through the backend reverse-proxy - * (`GET /api/opencode/config/providers`, same sdk 1.18.33 as the backend). - * Toggle/configure stay local-only (no backend write endpoints yet); - * keep loading/error/notice contract. A 503 (upstream down) surfaces as - * `error` with retry — no silent mock payloads. + * Shared fetch — GET /api/opencode/config/providers without auth (the + * backend reverse-proxy injects server-side auth; nothing auth-related + * travels in the browser bundle). Throws a plain Error carrying the sdk + * message on `{ error }` tuples (never formats beyond the message); + * `formatApiError + t` mapping lives in `useMemo` in `useAiProviders`. + * Module-level (no `t` closure) so concurrent mounts share one cache + * entry AND one queryFn identity per directory scope — dedup to a single + * GET /config/providers. Query cancellation arrives via the `signal` + * argument (no local AbortController). + */ +async function fetchAiProviders(directory?: string, signal?: AbortSignal): Promise { + const res = await opencode.config.providers( + directory ? { query: { directory }, signal } : { signal }, + ); + if (res.error !== undefined || res.data === undefined) { + throw new Error(toErrorMessage(res.error)); + } + return (res.data.providers ?? []).map((p) => ({ + id: p.id, + name: p.name || p.id, + description: `${p.source}${p.env?.length ? ` · ${p.env.join(', ')}` : ''}`, + enabled: true, + status: 'connected' as const, + modelsCount: Object.keys(p.models ?? {}).length, + })); +} + +/** + * Live provider list hook — GET /api/opencode/config/providers via + * TanStack Query (contract unchanged: UseAiProvidersResult shape is + * frozen, only the body swaps useEffect+nonce → useQuery). + * - Cache: aiProvidersQueryKey(directory) (P0 single source, `?? 'all'` + * scope so the default view has one stable entry), staleTime 60s + * (provider list is quasi-static — longer than the shared 30s + * default), gcTime from the shared QueryClient (no override). + * - Deduplication: module-level fetchAiProviders (no `t` closure) so + * concurrent mounts share one in-flight GET per directory scope. + * - Skeleton: `isLoading && !data` (initial only, refetch keeps data via + * placeholderData). + * - 503 (upstream down) surfaces as `error` with retry — no silent mock + * payloads. + * - Toggle/configure stay local-only (no backend write endpoints yet): + * they patch the cache via `setQueryData`, never a server write. */ export function useAiProviders(directory?: string): UseAiProvidersResult { const { t } = useI18n(); - const [providers, setProviders] = useState([]); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); + const queryClient = useQueryClient(); + const queryKey = useMemo(() => aiProvidersQueryKey(directory), [directory]); const [notice, setNotice] = useState(null); - const [nonce, setNonce] = useState(0); + const [errorDismissed, setErrorDismissed] = useState(false); - useEffect(() => { - let cancelled = false; - const ctrl = new AbortController(); - setLoading(true); - setError(null); - opencode.config - .providers(directory ? { query: { directory }, signal: ctrl.signal } : { signal: ctrl.signal }) - .then((res) => { - if (cancelled) return; - if (res.error !== undefined || res.data === undefined) { - const formatted = toErrorMessage(res.error); - setProviders([]); - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - return; - } - const live = (res.data.providers ?? []).map((p) => ({ - id: p.id, - name: p.name || p.id, - description: `${p.source}${p.env?.length ? ` · ${p.env.join(', ')}` : ''}`, - enabled: true, - status: 'connected' as const, - modelsCount: Object.keys(p.models ?? {}).length, - })); - setProviders(live); - }) - .catch((e: unknown) => { - if (cancelled || (e as Error)?.name === 'AbortError') return; - try { - const formatted = formatApiError(e); - setProviders([]); - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - } catch { - const formatted = toErrorMessage(e); - setProviders([]); - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - } - }) - .finally(() => { - if (!cancelled) setLoading(false); - }); - return () => { - cancelled = true; - ctrl.abort(); - }; - }, [directory, nonce, t]); + const { data, isLoading, error: queryError } = useQuery({ + queryKey, + queryFn: ({ signal }) => fetchAiProviders(directory, signal), + // Provider list is quasi-static — refetch less often than default. + staleTime: 60_000, + // Keep previous data during refetch to avoid skeleton flash + placeholderData: (prev) => prev, + retry: 1, + }); - const toggle = useCallback((id: string) => { - setNotice(null); - setProviders((prev) => prev.map((p) => (p.id === id ? { ...p, enabled: !p.enabled } : p))); - }, []); + const queryErrorText = useMemo(() => { + if (!queryError) return null; + let formatted: string; + try { + formatted = formatApiError(queryError); + } catch { + formatted = toErrorMessage(queryError); + } + if (formatted === 'Unexpected error') { + const alt = toErrorMessage(queryError); + formatted = alt; + } + return formatted === 'Unexpected error' ? t.errors.unexpected : formatted; + }, [queryError, t]); - const configure = useCallback((id: string) => { - setNotice(null); - setError(null); - // Local-only until backend write endpoints exist (no POST/PATCH for - // providers upstream yet) — flip the row on and surface the notice. - const target = providers.find((p) => p.id === id); - setProviders((prev) => - prev.map((p) => - p.id === id ? { ...p, enabled: true, status: 'connected' as const } : p, - ), - ); - setNotice(t.aiProviders.connectedNotice(target?.name ?? id)); - }, [providers, t]); + const error = errorDismissed ? null : queryErrorText; + + const providers = data ?? []; + + const toggle = useCallback( + (id: string) => { + setNotice(null); + queryClient.setQueryData(queryKey, (old) => + (old ?? []).map((p) => (p.id === id ? { ...p, enabled: !p.enabled } : p)), + ); + }, + [queryClient, queryKey], + ); + + const configure = useCallback( + (id: string) => { + setNotice(null); + // Local-only until backend write endpoints exist (no POST/PATCH for + // providers upstream yet) — flip the row on and surface the notice. + // Hide the query error like the legacy setError(null) did. + setErrorDismissed(true); + const target = queryClient.getQueryData(queryKey)?.find((p) => p.id === id); + queryClient.setQueryData(queryKey, (old) => + (old ?? []).map((p) => + p.id === id ? { ...p, enabled: true, status: 'connected' as const } : p, + ), + ); + setNotice(t.aiProviders.connectedNotice(target?.name ?? id)); + }, + [queryClient, queryKey, t], + ); + + const reload = useCallback(() => { + setErrorDismissed(false); + void queryClient.invalidateQueries({ queryKey }); + }, [queryClient, queryKey]); - const reload = useCallback(() => setNonce((n) => n + 1), []); const dismiss = useCallback(() => { - setError(null); + // Local-only: clears the visible error + notice. Never touches the + // query cache (no invalidate/clear — observers stay consistent). + setErrorDismissed(true); setNotice(null); }, []); + // Initial skeleton only; background refetch keeps previous data visible + const loading = isLoading && !data; + return { providers, loading, diff --git a/apps/frontend/src/hooks/useNpm.ts b/apps/frontend/src/hooks/useNpm.ts index 76dcf4f..e1584c4 100644 --- a/apps/frontend/src/hooks/useNpm.ts +++ b/apps/frontend/src/hooks/useNpm.ts @@ -1,10 +1,12 @@ 'use client'; -import { useCallback, useEffect, useState } from 'react'; -import { ApiClientError, api } from '../api/client'; +import { useCallback, useMemo } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import type { NpmPackageItem } from '../lib/types'; import { useI18n } from '../i18n'; +import { NPM_QUERY_KEY } from './query-keys'; export interface UseNpmResult { packages: NpmPackageItem[]; @@ -15,67 +17,71 @@ export interface UseNpmResult { } /** - * Live npm status through the backend (live reachability only). - * - * v1 shape: one live-status probe mapped to a single-row list - * (name/url/scope/status, no secrets — auth lives server-side, - * never logged, never shipped to the browser). - * Unreachable surfaces as `error` with retry — no silent mock payloads. - * Flat /npm route (not nested). + * Shared fetch — GET /api/v1/registry/npm/status without a token (public + * reachability; auth lives server-side in NPM_REGISTRY_* env, never + * logged, never shipped to the browser). Throws the raw envelope on + * failure (never formats); `formatApiError + t` mapping lives in + * `useMemo` in `useNpm`. Module-level (no `t` closure) so concurrent + * mounts share one cache entry AND one queryFn identity — dedup to a + * single GET /registry/npm/status. Query cancellation arrives via the + * `signal` argument (no local AbortController). + */ +async function fetchNpmStatus(signal?: AbortSignal): Promise { + const data = await api.getNpmStatus(signal ? { signal } : undefined); + const url = typeof data?.url === 'string' ? data.url : ''; + const scope = typeof data?.scope === 'string' ? data.scope : ''; + return [ + { + id: 'default', + name: scope || 'npm', + url, + scope, + status: 'up', + }, + ]; +} + +/** + * Live npm status hook — GET /api/v1/registry/npm/status via TanStack + * Query (contract unchanged: UseNpmResult shape is frozen, only the body + * swaps useEffect+nonce → useQuery). + * - Cache: NPM_QUERY_KEY (P0 single source), staleTime 60s (reachability + * probe is quasi-static — longer than the shared 30s default), gcTime + * from the shared QueryClient (no override). + * - Deduplication: module-level fetchNpmStatus (no `t` closure) so + * concurrent mounts share one in-flight GET. + * - Skeleton: `isLoading && !data` (initial only, refetch keeps data via + * placeholderData). + * - Unreachable surfaces as `error` with retry — no silent mock payloads. */ export function useNpm(): UseNpmResult { const { t } = useI18n(); - const [packages, setPackages] = useState([]); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - const [nonce, setNonce] = useState(0); + const queryClient = useQueryClient(); + + const { data, isLoading, error: queryError } = useQuery({ + queryKey: NPM_QUERY_KEY, + queryFn: ({ signal }) => fetchNpmStatus(signal), + // Reachability probe is quasi-static — refetch less often than default. + staleTime: 60_000, + // Keep previous data during refetch to avoid skeleton flash + placeholderData: (prev) => prev, + retry: 1, + }); + + const error = useMemo(() => { + if (!queryError) return null; + const formatted = formatApiError(queryError); + return formatted === 'Unexpected error' ? t.errors.unexpected : formatted; + }, [queryError, t]); + + const packages = data ?? []; - useEffect(() => { - let cancelled = false; - const ctrl = new AbortController(); - setLoading(true); - setError(null); - api - .getNpmStatus() - .then((data) => { - if (cancelled) return; - const url = typeof data?.url === 'string' ? data.url : ''; - const scope = typeof data?.scope === 'string' ? data.scope : ''; - setPackages([ - { - id: 'default', - name: scope || 'npm', - url, - scope, - status: 'up', - }, - ]); - }) - .catch((e: unknown) => { - if (cancelled || (e as Error)?.name === 'AbortError') return; - try { - const formatted = formatApiError(e); - setPackages([]); - if (e instanceof ApiClientError && e.status === 503) { - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - return; - } - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - } catch { - setPackages([]); - setError(t.errors.unexpected); - } - }) - .finally(() => { - if (!cancelled) setLoading(false); - }); - return () => { - cancelled = true; - ctrl.abort(); - }; - }, [nonce, t]); + const reload = useCallback(() => { + void queryClient.invalidateQueries({ queryKey: NPM_QUERY_KEY }); + }, [queryClient]); - const reload = useCallback(() => setNonce((n) => n + 1), []); + // Initial skeleton only; background refetch keeps previous data visible + const loading = isLoading && !data; return { packages, diff --git a/apps/frontend/src/hooks/useProfile.ts b/apps/frontend/src/hooks/useProfile.ts index b752001..2214c9a 100644 --- a/apps/frontend/src/hooks/useProfile.ts +++ b/apps/frontend/src/hooks/useProfile.ts @@ -1,10 +1,12 @@ 'use client'; -import { useCallback, useEffect, useRef, useState } from 'react'; -import { useRouter } from 'next/navigation'; +import { useCallback, useMemo, useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; +import type { AuthUser } from '../api/types'; import { formatApiError } from '../lib/format-error'; -import { getValidAccessToken, refreshAccessToken, signOutAndRedirect } from '../lib/auth-store'; +import { getValidAccessToken, refreshAccessToken } from '../lib/auth-store'; +import { PROFILE_QUERY_KEY } from './query-keys'; import type { Profile } from '../lib/types'; import { useI18n } from '../i18n'; @@ -19,7 +21,7 @@ export interface UseProfileResult { dismiss: () => void; } -function toProfile(user: { id: string; email: string; firstName: string; lastName: string; createdAt: string }): Profile { +function toProfile(user: AuthUser): Profile { return { id: user.id, name: `${user.firstName} ${user.lastName}`.trim(), @@ -35,118 +37,164 @@ function splitName(name: string): { firstName: string; lastName: string } { } /** - * Real profile hook — GET/PATCH /api/v1/auth/me (contract unchanged: - * UseProfileResult shape is frozen, only the body swapped mock → api). - * 401 → one silent refresh retry, then the session-expired message. + * Dead-session marker — thrown when both tokens are gone (no backend + * envelope to throw). Mapped to `t.errors.sessionExpired` in `useMemo` + * outside `queryFn`, so the fetch itself stays locale-free: language + * switches neither refetch nor re-render identity consumers. + */ +class SessionExpiredError extends Error { + constructor() { + super('session-expired'); + this.name = 'SessionExpiredError'; + } +} + +/** + * Shared fetch — token → api.me → toProfile with one silent 401 refresh + * retry (same auth contract `lib/auth-store.ts` documents). Throws the raw + * envelope on failure (never formats); `formatApiError + t` mapping lives + * in `useMemo` in `useProfile`. Module-level (no `t` closure) so header and + * page observers share one cache entry AND one queryFn identity — concurrent + * mounts dedup to a single GET /auth/me. + */ +async function fetchProfile(): Promise { + const token = await getValidAccessToken(); + if (!token) throw new SessionExpiredError(); + try { + return toProfile(await api.me(token)); + } catch (e) { + if (e instanceof ApiClientError && e.status === 401) { + const retryToken = await refreshAccessToken(); + if (!retryToken) throw new SessionExpiredError(); + return toProfile(await api.me(retryToken)); + } + throw e; + } +} + +/** + * No retry on terminal auth states (dead session / session 401 — a retry + * would only hammer /auth/me); one retry otherwise (shared-client contract). + */ +function profileRetry(failureCount: number, error: unknown): boolean { + if (error instanceof ApiClientError && error.status === 401) return false; + if (error instanceof SessionExpiredError) return false; + return failureCount < 1; +} + +/** + * Profile hook — GET/PATCH /api/v1/auth/me via TanStack Query (contract + * unchanged: UseProfileResult shape is frozen, only the body swapped + * useEffect+nonce → useQuery + useMutation). + * - Cache: staleTime 30s, gcTime 5m from the shared QueryClient (no override). + * - Deduplication: same PROFILE_QUERY_KEY as useHeaderProfile → header + + * /profile + org-page mounts share one in-flight request. + * - Skeleton: `isLoading && !data` (initial only, refetch keeps data via + * placeholderData). + * - Update: PATCH via useMutation, cache patched via setQueryData (no extra + * GET); saving = isPending, saved is local UI state. */ export function useProfile(): UseProfileResult { const { t } = useI18n(); - // Стабильная ссылка на router: next/navigation гарантирует стабильность, - // но тестовые стабы отдают новый объект каждый рендер — через ref эффект - // не уходит в бесконечный рефакт, deps эффекта не меняются ([nonce, t]). - const router = useRouter(); - const routerRef = useRef(router); - routerRef.current = router; - const [profile, setProfile] = useState(null); - const [loading, setLoading] = useState(true); - const [saving, setSaving] = useState(false); - const [error, setError] = useState(null); + const queryClient = useQueryClient(); const [saved, setSaved] = useState(false); - const [nonce, setNonce] = useState(0); - useEffect(() => { - let cancelled = false; - setLoading(true); - setError(null); - (async () => { + const { data, isLoading, error: queryError } = useQuery({ + queryKey: PROFILE_QUERY_KEY, + queryFn: fetchProfile, + // Keep previous data during refetch to avoid skeleton flash + placeholderData: (prev) => prev, + retry: profileRetry, + }); + + const profile = data ?? null; + + const queryErrorText = useMemo(() => { + if (!queryError) return null; + if (queryError instanceof SessionExpiredError) return t.errors.sessionExpired; + const formatted = formatApiError(queryError); + return formatted === 'Unexpected error' ? t.errors.unexpected : formatted; + }, [queryError, t]); + + const mutation = useMutation({ + mutationFn: async ( + patch: Pick & Partial>, + ): Promise => { + if (!patch.name.trim()) throw new Error(t.validation.nameRequired); + // Email is read-only: backend PATCH /auth/me accepts only + // firstName/lastName — patch.email (if passed by legacy callers) + // is intentionally ignored, never validated nor sent. + const token = await getValidAccessToken(); + if (!token) throw new SessionExpiredError(); + const attempt = (accessToken: string) => { + const { firstName, lastName } = splitName(patch.name); + return api.updateMe(accessToken, { firstName, lastName }); + }; try { - let token = await getValidAccessToken(); - if (!token) { - // Сессия мертва (оба токена протухли): единый sign-out + /login. - void signOutAndRedirect({ router: routerRef.current }); - if (!cancelled) setError(t.errors.sessionExpired); - return; - } - try { - const user = await api.me(token); - if (!cancelled) setProfile(toProfile(user)); - } catch (e) { - if (e instanceof ApiClientError && e.status === 401) { - token = await refreshAccessToken(); - if (!token) { - void signOutAndRedirect({ router: routerRef.current }); - if (!cancelled) setError(t.errors.sessionExpired); - return; - } - const user = await api.me(token); - if (!cancelled) setProfile(toProfile(user)); - } else { - throw e; - } - } + return toProfile(await attempt(token)); } catch (e) { - if (!cancelled) { - const formatted = formatApiError(e); - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); + if (e instanceof ApiClientError && e.status === 401) { + const retryToken = await refreshAccessToken(); + if (!retryToken) throw new SessionExpiredError(); + return toProfile(await attempt(retryToken)); } - } finally { - if (!cancelled) setLoading(false); + throw e; } - })(); - return () => { - cancelled = true; - }; - }, [nonce, t]); + }, + onSuccess: (updated) => { + // Patch the cache directly — no extra GET roundtrip; header + page + // observers re-render from the same PROFILE_QUERY_KEY entry. + queryClient.setQueryData(PROFILE_QUERY_KEY, updated); + setSaved(true); + }, + onError: () => { + setSaved(false); + }, + }); + + const mutationErrorText = useMemo(() => { + if (!mutation.error) return null; + if (mutation.error instanceof SessionExpiredError) return t.errors.sessionExpired; + const formatted = formatApiError(mutation.error); + return formatted === 'Unexpected error' ? t.errors.unexpected : formatted; + }, [mutation.error, t]); + + const error = mutationErrorText ?? queryErrorText; const update = useCallback( async (patch: Pick & Partial>) => { - setSaving(true); - setError(null); setSaved(false); try { - if (!patch.name.trim()) throw new Error(t.validation.nameRequired); - // Email is read-only: backend PATCH /auth/me accepts only - // firstName/lastName — patch.email (if passed by legacy callers) - // is intentionally ignored, never validated nor sent. - const token = await getValidAccessToken(); - if (!token) { - void signOutAndRedirect({ router: routerRef.current }); - setError(t.errors.sessionExpired); - return false; - } - const { firstName, lastName } = splitName(patch.name); - const user = await api.updateMe(token, { firstName, lastName }); - setProfile(toProfile(user)); - setSaved(true); + await mutation.mutateAsync(patch); return true; - } catch (e) { - if (e instanceof ApiClientError && e.status === 401) { - void signOutAndRedirect({ router: routerRef.current }); - setError(t.errors.sessionExpired); - } else { - const formatted = formatApiError(e); - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - } + } catch { return false; - } finally { - setSaving(false); } }, - [t], + [mutation], ); - const reload = useCallback(() => setNonce((n) => n + 1), []); + const reload = useCallback(() => { + void queryClient.invalidateQueries({ queryKey: PROFILE_QUERY_KEY }); + }, [queryClient]); + const dismiss = useCallback(() => { - setError(null); + // Local-only: clears the mutation error + saved flag. Never touches the + // query cache (no invalidate/clear — header + page stay consistent). + mutation.reset(); setSaved(false); - }, []); + }, [mutation]); - return { profile, loading, error, saved, saving, update, reload, dismiss }; + // Initial skeleton only; background refetch keeps previous data visible + const loading = isLoading && !profile; + + return { profile, loading, error, saved, saving: mutation.isPending, update, reload, dismiss }; } /** - * Header-only identity hook — same GET /api/v1/auth/me fetch (one silent - * 401 refresh retry) as useProfile, but with NO useI18n subscription: + * Header-only identity hook — same PROFILE_QUERY_KEY (same cache entry and + * queryFn as useProfile, so header + page dedup to one GET /auth/me), sliced + * via `select` to the data the header renders. NO useI18n subscription: * locale switches neither refetch /auth/me nor re-render * HeaderProfileDropdown (its userMenu labels are a mount snapshot there). * No translated error strings — the header only renders skeleton / @@ -154,47 +202,18 @@ export function useProfile(): UseProfileResult { * for the /profile page, whose error translations are untouched. */ export function useHeaderProfile(): { profile: Profile | null; loading: boolean } { - // Стабильная ссылка на router — см. комментарий в useProfile. - const router = useRouter(); - const routerRef = useRef(router); - routerRef.current = router; - const [profile, setProfile] = useState(null); - const [loading, setLoading] = useState(true); - - useEffect(() => { - let cancelled = false; - setLoading(true); - (async () => { - try { - let token = await getValidAccessToken(); - if (!token) { - // Сессия мертва (оба токена протухли): единый sign-out + /login. - void signOutAndRedirect({ router: routerRef.current }); - return; - } - try { - const user = await api.me(token); - if (!cancelled) setProfile(toProfile(user)); - } catch (e) { - if (e instanceof ApiClientError && e.status === 401) { - token = await refreshAccessToken(); - if (!token) { - void signOutAndRedirect({ router: routerRef.current }); - return; - } - const user = await api.me(token); - if (!cancelled) setProfile(toProfile(user)); - } - // Non-401: у шапки нет error-UI — остаёмся в unauthorized (login CTA). - } - } finally { - if (!cancelled) setLoading(false); - } - })(); - return () => { - cancelled = true; - }; - }, []); + const { data, isLoading } = useQuery({ + queryKey: PROFILE_QUERY_KEY, + queryFn: fetchProfile, + placeholderData: (prev) => prev, + retry: profileRetry, + // Slice: the header observes data only — error/saved/mutation updates + // (translated in useProfile) never remap this observer. + select: (fetched) => fetched, + }); + + const profile = data ?? null; + const loading = isLoading && !profile; return { profile, loading }; } diff --git a/apps/frontend/src/hooks/useRegistries.ts b/apps/frontend/src/hooks/useRegistries.ts index 7dc6182..dbb9fe5 100644 --- a/apps/frontend/src/hooks/useRegistries.ts +++ b/apps/frontend/src/hooks/useRegistries.ts @@ -1,10 +1,12 @@ 'use client'; -import { useCallback, useEffect, useState } from 'react'; -import { ApiClientError, api } from '../api/client'; +import { useCallback, useMemo } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import type { RegistryItem } from '../lib/types'; import { useI18n } from '../i18n'; +import { REGISTRIES_QUERY_KEY } from './query-keys'; export interface UseRegistriesResult { registries: RegistryItem[]; @@ -15,68 +17,71 @@ export interface UseRegistriesResult { } /** - * Live registry catalog through the backend proxy - * (`GET /api/v1/registry/catalog` → `{ repositories }`, live - * Docker Registry /v2/_catalog only). - * - * v1 shape: one live-catalog proxy + a local list of several registries - * in the frontend (name/url/status, no secrets — auth lives server-side - * in DOCKER_REGISTRY_* env, never logged, never shipped to the browser). - * A 503 (unconfigured/unreachable) surfaces as `error` with retry — - * no silent mock payloads. `[id]` detail route is deferred. + * Shared fetch — GET /api/v1/registry/catalog without a token (public + * reachability; auth lives server-side in DOCKER_REGISTRY_* env, never + * logged, never shipped to the browser). Throws the raw envelope on + * failure (never formats); `formatApiError + t` mapping lives in + * `useMemo` in `useRegistries`. Module-level (no `t` closure) so + * concurrent mounts share one cache entry AND one queryFn identity — + * dedup to a single GET /registry/catalog. Query cancellation arrives + * via the `signal` argument (no local AbortController). + */ +async function fetchRegistries(signal?: AbortSignal): Promise { + const data = await api.getRegistryCatalog(signal ? { signal } : undefined); + const repos = Array.isArray(data?.repositories) ? data.repositories : []; + return [ + { + id: 'default', + name: 'default', + url: '', + status: 'up', + repositories: repos, + }, + ]; +} + +/** + * Live registry catalog hook — GET /api/v1/registry/catalog via TanStack + * Query (contract unchanged: UseRegistriesResult shape is frozen, only the + * body swaps useEffect+nonce → useQuery). + * - Cache: REGISTRIES_QUERY_KEY (P0 single source), staleTime 60s + * (catalog is quasi-static — longer than the shared 30s default), + * gcTime from the shared QueryClient (no override). + * - Deduplication: module-level fetchRegistries (no `t` closure) so + * concurrent mounts share one in-flight GET. + * - Skeleton: `isLoading && !data` (initial only, refetch keeps data via + * placeholderData). + * - 503 (unconfigured/unreachable) surfaces as `error` with retry — + * no silent mock payloads. */ export function useRegistries(): UseRegistriesResult { const { t } = useI18n(); - const [registries, setRegistries] = useState([]); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - const [nonce, setNonce] = useState(0); + const queryClient = useQueryClient(); + + const { data, isLoading, error: queryError } = useQuery({ + queryKey: REGISTRIES_QUERY_KEY, + queryFn: ({ signal }) => fetchRegistries(signal), + // Catalog is quasi-static — refetch less often than the shared default. + staleTime: 60_000, + // Keep previous data during refetch to avoid skeleton flash + placeholderData: (prev) => prev, + retry: 1, + }); + + const error = useMemo(() => { + if (!queryError) return null; + const formatted = formatApiError(queryError); + return formatted === 'Unexpected error' ? t.errors.unexpected : formatted; + }, [queryError, t]); + + const registries = data ?? []; - useEffect(() => { - let cancelled = false; - const ctrl = new AbortController(); - setLoading(true); - setError(null); - api - .getRegistryCatalog() - .then((data) => { - if (cancelled) return; - const repos = Array.isArray(data?.repositories) ? data.repositories : []; - setRegistries([ - { - id: 'default', - name: 'default', - url: '', - status: 'up', - repositories: repos, - }, - ]); - }) - .catch((e: unknown) => { - if (cancelled || (e as Error)?.name === 'AbortError') return; - try { - const formatted = formatApiError(e); - setRegistries([]); - if (e instanceof ApiClientError && e.status === 503) { - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - return; - } - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - } catch { - setRegistries([]); - setError(t.errors.unexpected); - } - }) - .finally(() => { - if (!cancelled) setLoading(false); - }); - return () => { - cancelled = true; - ctrl.abort(); - }; - }, [nonce, t]); + const reload = useCallback(() => { + void queryClient.invalidateQueries({ queryKey: REGISTRIES_QUERY_KEY }); + }, [queryClient]); - const reload = useCallback(() => setNonce((n) => n + 1), []); + // Initial skeleton only; background refetch keeps previous data visible + const loading = isLoading && !data; return { registries, diff --git a/apps/frontend/src/hooks/useUsage.ts b/apps/frontend/src/hooks/useUsage.ts index 5406f2e..d1163ea 100644 --- a/apps/frontend/src/hooks/useUsage.ts +++ b/apps/frontend/src/hooks/useUsage.ts @@ -1,183 +1,106 @@ 'use client'; -import { useCallback, useEffect, useRef, useState } from 'react'; -import { useRouter } from 'next/navigation'; +import { useCallback, useMemo } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; import type { OpencodeUsage } from '../api/types'; -import { formatApiError } from '../lib/format-error'; -import { getValidAccessToken, refreshAccessToken, signOutAndRedirect } from '../lib/auth-store'; +import { getValidAccessToken, refreshAccessToken } from '../lib/auth-store'; +import { USAGE_QUERY_KEY } from './query-keys'; import { useI18n } from '../i18n'; +import { + SessionExpiredError, + isMissingKeyError, + isRejectedKeyError, + mapUsageStatus, + type UsageStatus, +} from '../features/usage/usage-status'; export interface UseUsageResult { usage: OpencodeUsage | null; loading: boolean; error: string | null; - /** - * True when the backend answers 404 opencode_key_missing (no stored key). - * User-side state — the Limits section renders the inline Add API key - * CTA (no ErrorBoundary, no unavailable wording). - */ + status: UsageStatus; + diagnostic: string | null; + shortId: string; noKey: boolean; - /** 404 opencode_key_missing — same as noKey (explicit 4xx branch). */ noKeyMissing: boolean; - /** - * True when the backend answers 401 opencode_key_invalid (the stored key - * was rejected upstream). User-side state — inline Add API key CTA like - * the missing-key branch, never a session refresh loop. - */ noKeyInvalid: boolean; - /** - * True when the upstream is down or throttled: any 5xx (502/503/504…), - * 429, or a network/timeout failure talking to the backend. Critical - * state — the Limits section renders the section-local ErrorState - * (destructive Alert + Retry), no inline unavailable texts. - */ upstreamDown: boolean; - /** - * Deprecated alias of upstreamDown (kept for compat, prefer upstreamDown). - */ upstreamUnavailable: boolean; reload: () => void; } -/** 401 carrying the rejected-key code (user-side) vs a session 401 (refresh). */ -function isRejectedKeyError(e: unknown): boolean { - return e instanceof ApiClientError && e.status === 401 && e.code === 'opencode_key_invalid'; +async function fetchUsage(): Promise { + const token = await getValidAccessToken(); + if (!token) throw new SessionExpiredError(); + try { + return await api.getUsage(token); + } catch (e) { + if (isMissingKeyError(e) || isRejectedKeyError(e)) throw e; + if (e instanceof ApiClientError && e.status === 401) { + const retryToken = await refreshAccessToken(); + if (!retryToken) throw new SessionExpiredError(); + return await api.getUsage(retryToken); + } + throw e; + } } -/** 404 carrying the missing-key code (user-side, never an error). */ -function isMissingKeyError(e: unknown): boolean { - return e instanceof ApiClientError && e.status === 404 && e.code === 'opencode_key_missing'; +function usageRetry(failureCount: number, error: unknown): boolean { + if (error instanceof SessionExpiredError) return false; + if (error instanceof ApiClientError) { + if (error.status === 404 && error.code === 'opencode_key_missing') return false; + if (error.status === 401) return false; + } + return failureCount < 1; } -/** - * Critical (downstream-of-the-user) failure: throttled, upstream 5xx, or the - * request never reached the backend (network/timeout, status 0). - */ -function isUpstreamDownError(e: unknown): boolean { - if (!(e instanceof ApiClientError)) return false; - return e.status === 429 || e.status >= 500 || e.status === 0; -} - -/** - * Live usage hook — GET /api/v1/usage (contract: { updatedAt } - * + optional legacy { balance, usage } + additive rolling/daily/weekly/monthly - * { used, limit } breakdown; Zen Go percent is exposed as { used: percent, limit: 100 }). - * Session 401 → one silent refresh retry, then the session-expired message. - * 404 opencode_key_missing / 401 opencode_key_invalid → 4xx user branches - * (usage null, error null — never fake 0% bars, never ErrorBoundary). - * 429 / 5xx / network → upstreamDown + error for the section ErrorState. - * Percentages are derived by the caller ONLY from real used/limit pairs; - * derivation from the `usage` total is forbidden. - */ export function useUsage(): UseUsageResult { const { t } = useI18n(); - const router = useRouter(); - const routerRef = useRef(router); - routerRef.current = router; - const [usage, setUsage] = useState(null); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - const [noKeyMissing, setNoKeyMissing] = useState(false); - const [noKeyInvalid, setNoKeyInvalid] = useState(false); - const [upstreamDown, setUpstreamDown] = useState(false); - const [nonce, setNonce] = useState(0); + const queryClient = useQueryClient(); + + const { data, isLoading, error: queryError } = useQuery({ + queryKey: USAGE_QUERY_KEY, + queryFn: fetchUsage, + staleTime: 10_000, + placeholderData: (prev) => prev, + retry: usageRetry, + }); + + const status = useMemo( + () => + mapUsageStatus(queryError, { + sessionExpired: t.errors.sessionExpired, + unexpected: t.errors.unexpected, + }), + [queryError, t], + ); + + const noKeyMissing = status.kind === 'missing-key'; + const noKeyInvalid = status.kind === 'invalid-key'; + const upstreamDown = status.kind === 'failed' && status.upstream; + const error = + status.kind === 'session-expired' || status.kind === 'failed' ? status.message : null; + const diagnostic = status.kind === 'failed' ? status.diagnostic : null; + const shortId = status.kind === 'failed' ? status.shortId : ''; + + const usage = + noKeyMissing || noKeyInvalid || upstreamDown ? null : (data ?? null); - useEffect(() => { - let cancelled = false; - setLoading(true); - setError(null); - setNoKeyMissing(false); - setNoKeyInvalid(false); - setUpstreamDown(false); - (async () => { - try { - let token = await getValidAccessToken(); - if (!token) { - void signOutAndRedirect({ router: routerRef.current }); - if (!cancelled) setError(t.errors.sessionExpired); - return; - } - const fetchUsage = (accessToken: string) => api.getUsage(accessToken); - const applyUserBranch = (e: unknown): boolean => { - if (isMissingKeyError(e)) { - if (!cancelled) { - setUsage(null); - setNoKeyMissing(true); - setNoKeyInvalid(false); - setUpstreamDown(false); - setError(null); - } - return true; - } - if (isRejectedKeyError(e)) { - if (!cancelled) { - setUsage(null); - setNoKeyMissing(false); - setNoKeyInvalid(true); - setUpstreamDown(false); - setError(null); - } - return true; - } - return false; - }; - try { - const data = await fetchUsage(token); - if (!cancelled) { - setUsage(data); - setNoKeyMissing(false); - setNoKeyInvalid(false); - } - } catch (e) { - if (applyUserBranch(e)) return; - if (e instanceof ApiClientError && e.status === 401) { - token = await refreshAccessToken(); - if (!token) { - void signOutAndRedirect({ router: routerRef.current }); - if (!cancelled) setError(t.errors.sessionExpired); - return; - } - try { - const data = await fetchUsage(token); - if (!cancelled) { - setUsage(data); - setNoKeyMissing(false); - setNoKeyInvalid(false); - } - } catch (retryErr) { - if (applyUserBranch(retryErr)) return; - throw retryErr; - } - } else { - throw e; - } - } - } catch (e) { - if (!cancelled) { - const formatted = formatApiError(e); - setError(formatted === 'Unexpected error' ? t.errors.unexpected : formatted); - const down = isUpstreamDownError(e); - setUpstreamDown(down); - if (down) setUsage(null); - } - } finally { - if (!cancelled) setLoading(false); - } - })(); - return () => { - cancelled = true; - }; - }, [nonce, t]); + const reload = useCallback(() => { + void queryClient.invalidateQueries({ queryKey: USAGE_QUERY_KEY }); + }, [queryClient]); - const reload = useCallback(() => setNonce((n) => n + 1), []); + const loading = isLoading && !data; - const noKey = noKeyMissing || noKeyInvalid; return { usage, loading, error, - noKey, + status, + diagnostic, + shortId, + noKey: noKeyMissing || noKeyInvalid, noKeyMissing, noKeyInvalid, upstreamDown, From 81ef262bafdf9f2e5c2cf564dd25c270250eee9d Mon Sep 17 00:00:00 2001 From: alwoo Date: Tue, 20 Oct 2026 01:30:39 +0400 Subject: [PATCH 011/315] docs: document frontend layers and shared mobile paths --- AGENTS.md | 23 +++++++++++++++++++++++ apps/frontend/DESIGN.md | 8 +++++++- apps/mobile/AGENTS.md | 6 +++--- apps/mobile/CONTRIBUTING.md | 4 ++-- 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 791d1c0..280638a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,29 @@ package.json, не Nx-проект, вне bun workspaces). (`tsc --noEmit`) + `bun --filter frontend build` (`next build --turbopack`). После правок mobile — гейты из `apps/mobile/AGENTS.md` (npm, не bun). +## Frontend — слои (apps/frontend) + +- `apps/frontend/AGENTS.md` отсутствует — правило слоёв живёт здесь. +- Источники: `apps/frontend/tsconfig.json` (`@/*` → `./src/*`, `./app/*`; + на 2026-10-20 `@/` использует только `app/(dashboard)/profile/page.tsx` + (4 импорта), остальной код — на относительных), + `apps/frontend/next.config.mjs` (слоёв не задаёт), фактическая структура + `app/` + `src/{api,components,features,hooks,i18n,lib}`. Каталогов + `entities/` и `shared/` нет — не выдумывать. `src/providers.tsx` — файл + в корне `src/` (DESIGN §3.4 пишет `src/providers` исторически). +- Правило: `app/` — только тонкая композиция (страница владеет + `<ФичаСекция />`, бизнес-логика — в `features/` + `hooks/`). + +| Слой | Путь | Что класть | Алиас (`@/*`) | Пример импорта | +| ---- | ---- | ---------- | ------------- | -------------- | +| Маршруты | `app/` | `page.tsx`, `layout.tsx`, `loading.tsx`, `error.tsx`; `globals.css` | `@/*` → `./app/*` | маршруты резолвит роутер, не импорты | +| Фичи | `src/features/<имя>/` | фича-модуль целиком: UI-секция + диалоги + локальный статус (`usage/`: `usage-section.tsx`, `api-key-dialog.tsx`, `usage-status.ts`, `__tests__/`) | `@/features/*` | `@/features/usage/usage-section` (из `app/(dashboard)/profile/page.tsx`) | +| Компоненты | `src/components/` | общие презентационные компоненты (`states`, `layout/`, `profile/`, `projects/`, …) | `@/components/*` | `../../components/states` (из `src/features/usage/`) | +| Хуки | `src/hooks/` | data-хуки (`useUsage`, `useProfile`, …) + `query-keys.ts` | `@/hooks/*` | `../../hooks/useUsage` (из `src/features/usage/`) | +| API | `src/api/` | HTTP-клиент, типы контрактов (`client.ts`, `types.ts`) | `@/api/*` | `../../api/types` (из `src/features/usage/`) | +| Lib | `src/lib/` | утилиты, схемы, сторы (`auth-store`, `format-error`) | `@/lib/*` | `../../lib/auth-store` (из `src/features/usage/`) | +| i18n | `src/i18n/` | словарь en/ru, провайдер | `@/i18n/*` | `../../i18n` (из `src/features/usage/`) | + ## Фолбэки запрещены по умолчанию - Никаких тихих фолбэков (дефолтные пути вроде `/...`, захардкоженные хосты/порты, подмена отсутствующего значения «удобным») без явного указания пользователя. Не задано → ошибка, а не додумывание. diff --git a/apps/frontend/DESIGN.md b/apps/frontend/DESIGN.md index df08c53..96f8b02 100644 --- a/apps/frontend/DESIGN.md +++ b/apps/frontend/DESIGN.md @@ -113,7 +113,12 @@ frontend. Новый компонент **не считается зарегис - `ProjectDetailSkeleton` - `ProjectsHeaderSkeleton` -### 3.3 Инфраструктура (`src/i18n`, `src/providers`) +### 3.3 Фичи (`src/features/`) + +- `ApiKeyDialog` +- `UsageSection` + +### 3.4 Инфраструктура (`src/i18n`, `src/providers`) - `I18nProvider` - `Providers` @@ -284,3 +289,4 @@ h2-строки + `Separator` + `Badge`). | 2026-10-11 | Из-за вставки реестра перенумерованы секции: правило радиусов §3 → §4 (запреты декора §3.1 → §4.1), структура шелла §4 → §5, бренд §5 → §6, плоский Content §6 → §7; внутренняя ссылка «§6 без исключений» → «§7» | Guard ожидает реестр в §3; нумерация держится сплошной без разрывов | | 2026-10-11 | Зафиксирован токен `--overlay-scrim: rgb(0 0 0 / 0.5)` (затемнение под мобильным drawer, `.app-sidebar-overlay`) в §2; объявление в `:root`/`globals.css` и замена литерала в коде — отдельная задача | Единственный оставшийся magic-color в `app/globals.css:355`; hex/rgba законны только внутри блока палитры `:root` / `.dark` | | 2026-10-11 | `I18nContext` НЕ внесён в реестр: это объект `createContext`, а не компонент; срабатывание guard на нём — известный false positive | Реестр описывает объявления компонентов; мусорные сущности в дизайн-документ не вносятся | +| 2026-10-20 | usage переехал `src/components/usage/` → `src/features/usage/` без смены логики: `ApiKeyDialog` + `UsageSection` перенесены из §3.2 в новый §3.3 «Фичи», инфраструктура §3.3 → §3.4 | Первый фича-модуль; page `/profile` остаётся тонкой композицией `` | diff --git a/apps/mobile/AGENTS.md b/apps/mobile/AGENTS.md index 5a2114b..2729570 100644 --- a/apps/mobile/AGENTS.md +++ b/apps/mobile/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md — opencode-mobile -Expo 57 + React Native 0.86.3 + React 19.2.3 + Expo Router. Single app, no monorepo. Entry `expo-router/entry`, screens in `app/` (file-based routing), business logic in `src/lib/`, Zustand stores in `src/stores/`. +Expo 57 + React Native 0.86.3 + React 19.2.3 + Expo Router. Single app, no monorepo. Entry `expo-router/entry`, screens in `app/` (file-based routing), business logic in `src/shared/utils/`, Zustand stores in `src/shared/stores/`. > `.opencode/` is a separate git repo (the portable opencode pack). Its `AGENTS.md` describes pack internals — don't confuse with this file. @@ -42,9 +42,9 @@ No `lint`/`format` scripts despite `CONTRIBUTING.md` mentioning `npm run lint` - `app/` — Expo Router screens. `_layout.tsx` is root (auth gate, SSE, notifications, telemetry consent). `(tabs)/` holds tab group, `session/[id].tsx`, `connection/`, `project/`. - `src/lib/sdk.ts` — custom lightweight opencode client over `expo/fetch` (not generated `@opencode-ai/sdk`). All API calls go through here; SSE via `src/lib/sse.ts`. -- `src/lib/` — pure utils with colocated `*.test.ts`. Each module is independently testable. +- `src/shared/utils/` — pure utils with colocated `*.test.ts`. Each module is independently testable. - `packages/uikit/` — `@web2bizz/ui-native`: the SINGLE home for reusable UI (components, theme, tablet hook, UI-support utils in `src/utils/`). Never duplicate a component in `src/components/` — app-bound components (stores, server clients, release checks: `AuthGate`, `CloneRepoSheet`, `ConnectionBadge`, `UpdateBanner`, `ErrorBoundary`) live in `src/components/` instead. Utils moved here keep their colocated tests; `npm test` covers `packages/uikit/src/**/*.test.ts` too. -- `src/stores/` — Zustand stores (`auth`, `connections`, `events`, `catalog`, `settings`). +- `src/shared/stores/` — Zustand stores (`auth`, `connections`, `events`, `catalog`, `settings`). - `src/components/` — shared UI (`AuthGate`, `ErrorBoundary`, etc.). - `scripts/*.mjs` — release/product scripts, each with `*.test.mjs` run by `npm test`. - `android/` — generated by `expo prebuild`, not hand-edited (except signing). Don't edit directly; re-run prebuild. diff --git a/apps/mobile/CONTRIBUTING.md b/apps/mobile/CONTRIBUTING.md index e01fba1..19fa9be 100644 --- a/apps/mobile/CONTRIBUTING.md +++ b/apps/mobile/CONTRIBUTING.md @@ -110,8 +110,8 @@ There is no auto-formatter enforced by CI yet (Prettier is configured but option Key conventions: - Components: functional, with typed props via TypeScript `interface` -- State: Zustand stores in `src/stores/` -- API calls: through the SDK client in `src/lib/` +- State: Zustand stores in `src/shared/stores/` +- API calls: through the SDK client in `src/shared/utils/` - Screens: file-based routing via Expo Router under `app/` --- From ded5b0afa77f1b6e461de2dedf42435c33b63146 Mon Sep 17 00:00:00 2001 From: alwoo Date: Tue, 20 Oct 2026 15:22:35 +0400 Subject: [PATCH 012/315] feat(contracts): add @devbox/contracts wire-contract package Single source of truth for backend/frontend: 8 entity type+schema pairs (health, session, repo-entry, api-error, auth, project, organization, opencode-key) mirroring contracts/openapi.yaml field-for-field. Includes types-over-interfaces code of conduct. --- CODE_OF_CONDUCT.md | 61 ++++++++++++ packages/contracts/package.json | 33 +++++++ packages/contracts/src/api-error.schema.ts | 5 + packages/contracts/src/api-error.ts | 5 + .../src/api-error/api-error.schema.ts | 16 ++++ packages/contracts/src/api-error/api-error.ts | 22 +++++ packages/contracts/src/auth.schema.ts | 5 + packages/contracts/src/auth.ts | 5 + packages/contracts/src/auth/auth.schema.ts | 92 ++++++++++++++++++ packages/contracts/src/auth/auth.ts | 34 +++++++ packages/contracts/src/health.schema.ts | 5 + packages/contracts/src/health.ts | 5 + .../contracts/src/health/health.schema.ts | 32 +++++++ packages/contracts/src/health/health.ts | 35 +++++++ packages/contracts/src/index.ts | 28 ++++++ packages/contracts/src/opencode-key.schema.ts | 5 + packages/contracts/src/opencode-key.ts | 5 + .../src/opencode-key/opencode-key.schema.ts | 59 ++++++++++++ .../src/opencode-key/opencode-key.ts | 55 +++++++++++ packages/contracts/src/organization.schema.ts | 5 + packages/contracts/src/organization.ts | 5 + .../src/organization/organization.schema.ts | 95 +++++++++++++++++++ .../src/organization/organization.ts | 42 ++++++++ packages/contracts/src/project.schema.ts | 5 + packages/contracts/src/project.ts | 5 + .../contracts/src/project/project.schema.ts | 68 +++++++++++++ packages/contracts/src/project/project.ts | 38 ++++++++ packages/contracts/src/repo-entry.schema.ts | 5 + packages/contracts/src/repo-entry.ts | 5 + .../src/repo-entry/repo-entry.schema.ts | 27 ++++++ .../contracts/src/repo-entry/repo-entry.ts | 18 ++++ packages/contracts/src/session.schema.ts | 5 + packages/contracts/src/session.ts | 5 + .../contracts/src/session/session.schema.ts | 58 +++++++++++ packages/contracts/src/session/session.ts | 50 ++++++++++ packages/contracts/tsconfig.json | 11 +++ 36 files changed, 954 insertions(+) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 packages/contracts/package.json create mode 100644 packages/contracts/src/api-error.schema.ts create mode 100644 packages/contracts/src/api-error.ts create mode 100644 packages/contracts/src/api-error/api-error.schema.ts create mode 100644 packages/contracts/src/api-error/api-error.ts create mode 100644 packages/contracts/src/auth.schema.ts create mode 100644 packages/contracts/src/auth.ts create mode 100644 packages/contracts/src/auth/auth.schema.ts create mode 100644 packages/contracts/src/auth/auth.ts create mode 100644 packages/contracts/src/health.schema.ts create mode 100644 packages/contracts/src/health.ts create mode 100644 packages/contracts/src/health/health.schema.ts create mode 100644 packages/contracts/src/health/health.ts create mode 100644 packages/contracts/src/index.ts create mode 100644 packages/contracts/src/opencode-key.schema.ts create mode 100644 packages/contracts/src/opencode-key.ts create mode 100644 packages/contracts/src/opencode-key/opencode-key.schema.ts create mode 100644 packages/contracts/src/opencode-key/opencode-key.ts create mode 100644 packages/contracts/src/organization.schema.ts create mode 100644 packages/contracts/src/organization.ts create mode 100644 packages/contracts/src/organization/organization.schema.ts create mode 100644 packages/contracts/src/organization/organization.ts create mode 100644 packages/contracts/src/project.schema.ts create mode 100644 packages/contracts/src/project.ts create mode 100644 packages/contracts/src/project/project.schema.ts create mode 100644 packages/contracts/src/project/project.ts create mode 100644 packages/contracts/src/repo-entry.schema.ts create mode 100644 packages/contracts/src/repo-entry.ts create mode 100644 packages/contracts/src/repo-entry/repo-entry.schema.ts create mode 100644 packages/contracts/src/repo-entry/repo-entry.ts create mode 100644 packages/contracts/src/session.schema.ts create mode 100644 packages/contracts/src/session.ts create mode 100644 packages/contracts/src/session/session.schema.ts create mode 100644 packages/contracts/src/session/session.ts create mode 100644 packages/contracts/tsconfig.json diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..701d8cb --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,61 @@ +# Code of Conduct — types-over-interfaces + +## Scope + +Whole monorepo — `packages/contracts/src/**`, `apps/backend/src/**`, +`apps/frontend/src/**`, `apps/frontend/app/**`, `apps/mobile/src/**`. +Mandatory in `@devbox/contracts` (the wire-contract etalon). + +## Rule + +New entities are declared only as `export type`. Extension is done via +intersection (`&`). The `interface` keyword is forbidden for our own code. + +```ts +// do +export type Project = { + id: string; + corrupted: boolean; +}; + +// do — extension via intersection +export type AuthSession = AuthTokens & { + user: AuthUser; +}; +``` + +```ts +// don't +export interface Project { + id: string; + corrupted: boolean; +} + +// don't +export interface AuthSession extends AuthTokens { + user: AuthUser; +} +``` + +Etalon: [`packages/contracts/src`](packages/contracts/src) — every domain +(`health/`, `session/`, `repo-entry/`, `api-error/`, `auth/`, `project/`, +`organization/`, `opencode-key/`) declares `.ts` entities as types +and mirrors `contracts/openapi.yaml` field-for-field. + +## Exceptions (require justification in the PR) + +- External library types that require `interface` (e.g. `declare module` + shims where the upstream API mandates it). +- `class` declarations (NestJS providers, DTO classes for `@nestjs/swagger`) + — never touched by this rule. +- Global declaration merging (`declare global`) — only with a comment + explaining why a `type` cannot express it. + +## Control + +```sh +# must print nothing outside the exceptions above +rg -g '*.ts' -g '*.tsx' '(export )?interface \w+' \ + packages/contracts/src apps/backend/src \ + apps/frontend/src apps/frontend/app apps/mobile/src +``` diff --git a/packages/contracts/package.json b/packages/contracts/package.json new file mode 100644 index 0000000..b57bc35 --- /dev/null +++ b/packages/contracts/package.json @@ -0,0 +1,33 @@ +{ + "name": "@devbox/contracts", + "version": "0.1.0", + "description": "Shared DevBox wire contracts — entity types + zod v4 boundary schemas. Single source of truth for backend/frontend; mirrors contracts/openapi.yaml.", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "scripts": { + "build": "tsc -p tsconfig.json", + "lint": "tsc --noEmit -p tsconfig.json", + "test": "bun test --isolate --pass-with-no-tests src" + }, + "dependencies": { + "zod": "^4.6.5" + }, + "peerDependencies": { + "zod": "^4.6.5" + }, + "engines": { + "node": ">=22", + "bun": ">=1.4.2" + } +} diff --git a/packages/contracts/src/api-error.schema.ts b/packages/contracts/src/api-error.schema.ts new file mode 100644 index 0000000..fe1a96e --- /dev/null +++ b/packages/contracts/src/api-error.schema.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./api-error/api-error.schema.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './api-error/api-error.schema'; diff --git a/packages/contracts/src/api-error.ts b/packages/contracts/src/api-error.ts new file mode 100644 index 0000000..b2c75ea --- /dev/null +++ b/packages/contracts/src/api-error.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./api-error/api-error.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './api-error/api-error'; diff --git a/packages/contracts/src/api-error/api-error.schema.ts b/packages/contracts/src/api-error/api-error.schema.ts new file mode 100644 index 0000000..23678b6 --- /dev/null +++ b/packages/contracts/src/api-error/api-error.schema.ts @@ -0,0 +1,16 @@ +import { z } from 'zod'; + +import type { ApiError } from './api-error'; + +/** + * Boundary schema for api-error.ts. + * Field set is frozen (code/message/correlationId only, mirroring + * contracts/openapi.yaml ApiError); min(1) rejects empty envelopes at + * the boundary without constraining the open code value set. + */ + +export const apiErrorSchema = z.object({ + code: z.string().min(1), + message: z.string().min(1), + correlationId: z.string().min(1), +}) satisfies z.ZodType; diff --git a/packages/contracts/src/api-error/api-error.ts b/packages/contracts/src/api-error/api-error.ts new file mode 100644 index 0000000..c3f22ef --- /dev/null +++ b/packages/contracts/src/api-error/api-error.ts @@ -0,0 +1,22 @@ +/** + * Unified error envelope for all /api/v1/* routes. + * + * Mirrors contracts/openapi.yaml components/schemas ApiError. + * Shape is FROZEN — only new `code` VALUES are added, never new fields. + * Known code values (non-exhaustive): legacy lowercase (`bad_request` | + * `unauthorized` | `forbidden` | `not_found` | `payload_too_large` | + * `request_failed` | `internal_error`), typed upstream codes + * (`EXTERNAL_TIMEOUT` | `EXTERNAL_UNAVAILABLE` | `EXTERNAL_RATE_LIMITED` | + * `EXTERNAL_UPSTREAM_5XX` | `GITHUB_AUTH` | `GITHUB_NOT_INSTALLED`), auth + * codes (`invalid_credentials` | `email_taken` | `provider_not_configured`), + * key codes (`opencode_key_invalid` | `opencode_key_missing` | + * `opencode_keys_unconfigured`). + */ +export type ApiError = { + /** machine-readable code (see above — frozen shape, values only) */ + code: string; + /** human-readable message (no secrets) */ + message: string; + /** echo of x-correlation-id / generated uuid for log tracing */ + correlationId: string; +}; diff --git a/packages/contracts/src/auth.schema.ts b/packages/contracts/src/auth.schema.ts new file mode 100644 index 0000000..1251d80 --- /dev/null +++ b/packages/contracts/src/auth.schema.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./auth/auth.schema.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './auth/auth.schema'; diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts new file mode 100644 index 0000000..f298544 --- /dev/null +++ b/packages/contracts/src/auth.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./auth/auth.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './auth/auth'; diff --git a/packages/contracts/src/auth/auth.schema.ts b/packages/contracts/src/auth/auth.schema.ts new file mode 100644 index 0000000..a718860 --- /dev/null +++ b/packages/contracts/src/auth/auth.schema.ts @@ -0,0 +1,92 @@ +import { z } from 'zod'; + +import type { AuthSession, AuthTokens, AuthUser } from './auth'; + +/** + * Boundary schemas for auth.ts. + * Input schemas are verbatim apps/backend/src/auth/dto.ts (same trims, + * min/max, email regex + error strings) so backend/frontend validation + * stays identical after consumer migration. The email regex is intentionally + * copied — not z.email() — to preserve trim-first semantics and the exact + * backend message on every input. Response schemas mirror + * contracts/openapi.yaml (AuthUser/AuthTokens/AuthSession). + */ + +const nameField = z + .string() + .trim() + .min(1, { error: 'must not be empty' }) + .max(100, { error: 'must be ≤ 100 chars' }); + +const emailField = z + .string() + .trim() + .min(1, { error: 'must not be empty' }) + .max(320, { error: 'must be ≤ 320 chars' }) + .refine((v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), { + error: 'must be a valid email', + }); + +const passwordField = z + .string() + .min(8, { error: 'must be at least 8 characters' }) + .max(256, { error: 'must be ≤ 256 chars' }); + +/** POST /api/v1/auth/register — firstName/lastName/email/password. */ +export const registerSchema = z.object({ + firstName: nameField, + lastName: nameField, + email: emailField, + password: passwordField, +}); + +export type RegisterInput = z.infer; + +/** POST /api/v1/auth/login — email+password. */ +export const loginSchema = z.object({ + email: emailField, + password: passwordField, +}); + +export type LoginInput = z.infer; + +/** POST /api/v1/auth/refresh — single-use refresh token rotation. */ +export const refreshSchema = z.object({ + refreshToken: z.string().trim().min(1, { error: 'must not be empty' }), +}); + +export type RefreshInput = z.infer; + +/** PATCH /api/v1/auth/me — profile update (firstName/lastName only). */ +export const updateMeSchema = z + .object({ + firstName: nameField.optional(), + lastName: nameField.optional(), + }) + .refine((v) => v.firstName !== undefined || v.lastName !== undefined, { + error: 'at least one of firstName/lastName is required', + }); + +export type UpdateMeInput = z.infer; + +export const authUserSchema = z.object({ + id: z.uuid(), + firstName: nameField, + lastName: nameField, + email: emailField, + provider: z.enum(['local', 'sso-oauth', 'github-app']), + /** ISO-8601 timestamp */ + createdAt: z.string().min(1), +}) satisfies z.ZodType; + +export const authTokensSchema = z.object({ + accessToken: z.string().min(1), + refreshToken: z.string().min(1), + tokenType: z.literal('bearer'), + /** Access lifetime in seconds. */ + expiresIn: z.number().int().min(0), +}) satisfies z.ZodType; + +export const authSessionSchema = authTokensSchema.extend({ + user: authUserSchema, +}) satisfies z.ZodType; diff --git a/packages/contracts/src/auth/auth.ts b/packages/contracts/src/auth/auth.ts new file mode 100644 index 0000000..d424c75 --- /dev/null +++ b/packages/contracts/src/auth/auth.ts @@ -0,0 +1,34 @@ +/** + * Auth account contracts. + * + * Mirrors contracts/openapi.yaml components/schemas: AuthUser, AuthTokens, + * AuthSession (field-for-field). Request input types live in auth.schema.ts + * (inferred from the backend-verbatim zod schemas). + * Previously duplicated in apps/backend/src/contracts.ts and + * apps/frontend/src/api/types.ts — this package is the single source. + */ + +/** POST /api/v1/auth/register + login response user (never carries passwordHash) */ +export type AuthUser = { + id: string; + firstName: string; + lastName: string; + email: string; + provider: 'local' | 'sso-oauth' | 'github-app'; + /** ISO-8601 timestamp */ + createdAt: string; +}; + +/** Token pair (short-lived access + rotating refresh). */ +export type AuthTokens = { + accessToken: string; + refreshToken: string; + tokenType: 'bearer'; + /** Access lifetime in seconds. */ + expiresIn: number; +}; + +/** POST /api/v1/auth/register + login response (user + tokens). */ +export type AuthSession = AuthTokens & { + user: AuthUser; +}; diff --git a/packages/contracts/src/health.schema.ts b/packages/contracts/src/health.schema.ts new file mode 100644 index 0000000..c895dad --- /dev/null +++ b/packages/contracts/src/health.schema.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./health/health.schema.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './health/health.schema'; diff --git a/packages/contracts/src/health.ts b/packages/contracts/src/health.ts new file mode 100644 index 0000000..fdf2365 --- /dev/null +++ b/packages/contracts/src/health.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./health/health.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './health/health'; diff --git a/packages/contracts/src/health/health.schema.ts b/packages/contracts/src/health/health.schema.ts new file mode 100644 index 0000000..02e4539 --- /dev/null +++ b/packages/contracts/src/health/health.schema.ts @@ -0,0 +1,32 @@ +import { z } from 'zod'; + +import type { + HealthResponse, + NpmRegistryStatusResponse, + RegistryCatalogResponse, +} from './health'; + +/** + * Boundary schemas for health.ts. + * Enums mirror contracts/openapi.yaml exactly (Health, RegistryCatalog, + * NpmRegistryStatus). Scalar strings carry min(1): wire values are never + * empty, so empty strings fail fast at the boundary. + */ + +export const healthResponseSchema = z.object({ + status: z.literal('ok'), + db: z.enum(['up', 'down', 'skipped']), + opencode: z.enum(['up', 'down']), + registry: z.enum(['up', 'down', 'skipped']), + npmRegistry: z.enum(['up', 'down', 'skipped']), +}) satisfies z.ZodType; + +export const registryCatalogResponseSchema = z.object({ + repositories: z.array(z.string().min(1)), +}) satisfies z.ZodType; + +export const npmRegistryStatusResponseSchema = z.object({ + status: z.literal('up'), + url: z.string().min(1), + scope: z.string().min(1), +}) satisfies z.ZodType; diff --git a/packages/contracts/src/health/health.ts b/packages/contracts/src/health/health.ts new file mode 100644 index 0000000..12437a8 --- /dev/null +++ b/packages/contracts/src/health/health.ts @@ -0,0 +1,35 @@ +/** + * Health + registry status contracts. + * + * Mirrors contracts/openapi.yaml components/schemas: Health, + * RegistryCatalog, NpmRegistryStatus (field-for-field). + * Previously duplicated in apps/backend/src/contracts.ts and + * apps/frontend/src/api/types.ts — this package is the single source. + */ + +/** GET /health (unversioned liveness probe) */ +export type HealthResponse = { + status: 'ok'; + /** postgres reachability: up | down | skipped (no DATABASE_URL / MVP boot without pg) */ + db: 'up' | 'down' | 'skipped'; + /** opencode server reachability: up (any HTTP response) | down (timeout/network) */ + opencode: 'up' | 'down'; + /** docker registry reachability: up | down | skipped (no DOCKER_REGISTRY_URL) */ + registry: 'up' | 'down' | 'skipped'; + /** npm registry (Verdaccio) reachability: up | down | skipped (no NPM_REGISTRY_URL) */ + npmRegistry: 'up' | 'down' | 'skipped'; +}; + +/** GET /api/v1/registry/catalog — live Docker Registry /v2/_catalog (503 when unreachable) */ +export type RegistryCatalogResponse = { + repositories: string[]; +}; + +/** GET /api/v1/registry/npm/status — live Verdaccio /-/ping reachability (503 when unreachable) */ +export type NpmRegistryStatusResponse = { + status: 'up'; + /** Canonical registry base URL, no trailing slash (never carries the token) */ + url: string; + /** Observed npm scope, e.g. '@web2bizz' */ + scope: string; +}; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts new file mode 100644 index 0000000..472f608 --- /dev/null +++ b/packages/contracts/src/index.ts @@ -0,0 +1,28 @@ +/** + * @devbox/contracts — shared DevBox wire contracts. + * + * Entity types + zod v4 boundary schemas, single source of truth for + * backend/frontend (replaces the backend/frontend contracts.ts + lib + * *-schemas.ts duplications). Every module mirrors + * contracts/openapi.yaml components/schemas field-for-field and reuses + * the backend dto constraints verbatim (min/max/email/uuid + messages); + * the ApiError envelope stays frozen (new code VALUES only, never fields). + * Types only + schemas — no runtime logic, no console output. + */ + +export * from './health/health'; +export * from './health/health.schema'; +export * from './session/session'; +export * from './session/session.schema'; +export * from './repo-entry/repo-entry'; +export * from './repo-entry/repo-entry.schema'; +export * from './api-error/api-error'; +export * from './api-error/api-error.schema'; +export * from './auth/auth'; +export * from './auth/auth.schema'; +export * from './project/project'; +export * from './project/project.schema'; +export * from './organization/organization'; +export * from './organization/organization.schema'; +export * from './opencode-key/opencode-key'; +export * from './opencode-key/opencode-key.schema'; diff --git a/packages/contracts/src/opencode-key.schema.ts b/packages/contracts/src/opencode-key.schema.ts new file mode 100644 index 0000000..d39619c --- /dev/null +++ b/packages/contracts/src/opencode-key.schema.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./opencode-key/opencode-key.schema.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './opencode-key/opencode-key.schema'; diff --git a/packages/contracts/src/opencode-key.ts b/packages/contracts/src/opencode-key.ts new file mode 100644 index 0000000..ae04329 --- /dev/null +++ b/packages/contracts/src/opencode-key.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./opencode-key/opencode-key.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './opencode-key/opencode-key'; diff --git a/packages/contracts/src/opencode-key/opencode-key.schema.ts b/packages/contracts/src/opencode-key/opencode-key.schema.ts new file mode 100644 index 0000000..923429a --- /dev/null +++ b/packages/contracts/src/opencode-key/opencode-key.schema.ts @@ -0,0 +1,59 @@ +import { z } from 'zod'; + +import type { + OpencodeKeyDeleteResult, + OpencodeKeyResult, + OpencodeKeyStatus, + OpencodeLimitBucket, + OpencodeUsage, +} from './opencode-key'; + +/** + * Boundary schemas for opencode-key.ts. + * opencodeKeySchema is verbatim apps/backend/src/opencode-keys/dto.ts + * (same trim/min/max + error strings): short strings are almost certainly + * a paste mistake, so min 20 fails fast. Response schemas mirror + * contracts/openapi.yaml (OpencodeKeyResult/Status/Usage/LimitBucket). + */ + +export const opencodeKeySchema = z.object({ + apiKey: z + .string() + .trim() + .min(20, { error: 'must be at least 20 characters' }) + .max(1024, { error: 'must be ≤ 1024 chars' }), +}); + +export type OpencodeKeyInput = z.infer; + +export const opencodeKeyResultSchema = z.object({ + ok: z.boolean(), + /** ISO-8601 timestamp */ + updatedAt: z.string().min(1), +}) satisfies z.ZodType; + +export const opencodeKeyDeleteResultSchema = z.object({ + ok: z.boolean(), +}) satisfies z.ZodType; + +export const opencodeKeyStatusSchema = z.object({ + configured: z.boolean(), + /** ISO-8601 timestamp (present only when configured). */ + updatedAt: z.string().min(1).optional(), +}) satisfies z.ZodType; + +export const opencodeLimitBucketSchema = z.object({ + used: z.number(), + limit: z.number(), +}) satisfies z.ZodType; + +export const opencodeUsageSchema = z.object({ + balance: z.number().optional(), + usage: z.number().optional(), + /** ISO-8601 time of the upstream response */ + updatedAt: z.string().min(1), + rolling: opencodeLimitBucketSchema.optional(), + daily: opencodeLimitBucketSchema.optional(), + weekly: opencodeLimitBucketSchema.optional(), + monthly: opencodeLimitBucketSchema.optional(), +}) satisfies z.ZodType; diff --git a/packages/contracts/src/opencode-key/opencode-key.ts b/packages/contracts/src/opencode-key/opencode-key.ts new file mode 100644 index 0000000..7eff203 --- /dev/null +++ b/packages/contracts/src/opencode-key/opencode-key.ts @@ -0,0 +1,55 @@ +/** + * Per-user OpenCode key + usage contracts. + * + * Mirrors contracts/openapi.yaml components/schemas: OpencodeKeyResult, + * OpencodeKeyDeleteResult, OpencodeKeyStatus, OpencodeUsage, + * OpencodeLimitBucket (+ OpencodeKeyBody input). Key input type lives in + * opencode-key.schema.ts (inferred from the backend-verbatim zod schema). + * The key value itself is never returned or logged — only existence + + * timestamps cross the wire. + */ + +/** PUT /api/v1/key result (carries no secret). */ +export type OpencodeKeyResult = { + ok: boolean; + /** ISO-8601 timestamp */ + updatedAt: string; +}; + +/** DELETE /api/v1/key result (idempotent, no timestamp). */ +export type OpencodeKeyDeleteResult = { + ok: boolean; +}; + +/** GET /api/v1/key — whether the caller has a key stored. */ +export type OpencodeKeyStatus = { + configured: boolean; + /** ISO-8601 timestamp (present only when configured). */ + updatedAt?: string; +}; + +/** Single usage bucket — real `used/limit` pair from upstream (no derivation). */ +export type OpencodeLimitBucket = { + used: number; + limit: number; +}; + +/** GET /api/v1/usage — live Zen Go usage (percent windows mapped to used/limit 100). */ +export type OpencodeUsage = { + /** Legacy pay-as-you-go fields — present only for legacy upstream payloads. */ + balance?: number; + /** Legacy pay-as-you-go total — present only for legacy upstream payloads. */ + usage?: number; + /** ISO-8601 time of the upstream response */ + updatedAt: string; + /** + * Zen Go windows mapped to used/limit (`percent` → `{ used: percent, limit: 100 }`). + * `rolling` is the Zen 5-hour window (20% of monthly); legacy `daily` has + * no Zen equivalent and is kept for old payloads. Present only when the + * upstream payload carries finite numbers — never derived from a total. + */ + rolling?: OpencodeLimitBucket; + daily?: OpencodeLimitBucket; + weekly?: OpencodeLimitBucket; + monthly?: OpencodeLimitBucket; +}; diff --git a/packages/contracts/src/organization.schema.ts b/packages/contracts/src/organization.schema.ts new file mode 100644 index 0000000..3e14e29 --- /dev/null +++ b/packages/contracts/src/organization.schema.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./organization/organization.schema.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './organization/organization.schema'; diff --git a/packages/contracts/src/organization.ts b/packages/contracts/src/organization.ts new file mode 100644 index 0000000..fe88664 --- /dev/null +++ b/packages/contracts/src/organization.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./organization/organization.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './organization/organization'; diff --git a/packages/contracts/src/organization/organization.schema.ts b/packages/contracts/src/organization/organization.schema.ts new file mode 100644 index 0000000..db97933 --- /dev/null +++ b/packages/contracts/src/organization/organization.schema.ts @@ -0,0 +1,95 @@ +import { z } from 'zod'; + +import type { + Organization, + OrganizationInvite, + OrganizationMember, + OrgRole, +} from './organization'; + +/** + * Boundary schemas for organization.ts. + * Input schemas are verbatim apps/backend/src/organizations/dto.ts (same + * min/max, uuid shapes, defaults + error strings) so backend/frontend + * validation stays identical after consumer migration. Response schemas + * mirror contracts/openapi.yaml. + */ + +export const orgRoleSchema = z.enum(['maintainer', 'user'], { + error: 'role must be maintainer or user', +}) satisfies z.ZodType; + +/** uuid with distinct missing/invalid messages (backend dto parity). */ +const requiredUuid = (requiredError: string, invalidError: string) => + z.uuid({ + error: (iss) => (iss.code === 'invalid_type' ? requiredError : invalidError), + }); + +export const createOrganizationSchema = z.object({ + name: z.string({ error: 'Field "name" is required' }).min(1).max(200), + description: z.string().max(2000).optional(), + isPrivate: z.boolean().optional().default(true), +}); + +export type CreateOrganizationInput = z.input; + +export const updateOrganizationSchema = z.object({ + name: z.string().min(1).max(200).optional(), + description: z.string().max(2000).nullable().optional(), + isPrivate: z.boolean().optional(), +}); + +export type UpdateOrganizationInput = z.infer; + +export const addMemberSchema = z.object({ + userId: requiredUuid('Field "userId" is required', 'userId must be a uuid'), + role: orgRoleSchema.optional().default('user'), +}); + +export type AddMemberInput = z.input; + +export const updateMemberRoleSchema = z.object({ + role: orgRoleSchema, +}); + +export type UpdateMemberRoleInput = z.infer; + +export const createInviteSchema = z.object({ + role: orgRoleSchema.optional().default('user'), +}); + +export type CreateInviteInput = z.input; + +export const acceptInviteSchema = z.object({ + token: z.string({ error: 'Field "token" is required' }).min(1).max(500), +}); + +export type AcceptInviteInput = z.infer; + +export const organizationSchema = z.object({ + id: z.uuid(), + name: z.string().min(1), + description: z.string().nullable(), + ownerId: z.uuid().nullable(), + isPrivate: z.boolean(), + /** ISO-8601 timestamp */ + createdAt: z.string().min(1), + /** ISO-8601 timestamp */ + updatedAt: z.string().min(1), +}) satisfies z.ZodType; + +export const organizationMemberSchema = z.object({ + orgId: z.uuid(), + userId: z.uuid(), + role: orgRoleSchema, + /** ISO-8601 timestamp */ + createdAt: z.string().min(1), +}) satisfies z.ZodType; + +export const organizationInviteSchema = z.object({ + token: z.string().min(1), + orgId: z.uuid(), + role: orgRoleSchema, + /** ISO-8601 timestamp */ + expiresAt: z.string().min(1), +}) satisfies z.ZodType; diff --git a/packages/contracts/src/organization/organization.ts b/packages/contracts/src/organization/organization.ts new file mode 100644 index 0000000..2e7fae1 --- /dev/null +++ b/packages/contracts/src/organization/organization.ts @@ -0,0 +1,42 @@ +/** + * Organization contracts. + * + * Mirrors contracts/openapi.yaml components/schemas: Organization, + * OrganizationMember, OrganizationInvite, OrgRole (+ CreateOrganization, + * UpdateOrganization, AddMember, UpdateMemberRole, CreateInvite, + * AcceptInvite inputs). Request input types live in organization.schema.ts + * (inferred from the backend-verbatim zod schemas). All contracts here were + * introduced additively — no existing schema is modified. + */ + +export type OrgRole = 'maintainer' | 'user'; + +export type Organization = { + id: string; + name: string; + description: string | null; + /** creator (SET NULL — the org outlives its creator) */ + ownerId: string | null; + isPrivate: boolean; + /** ISO-8601 timestamp */ + createdAt: string; + /** ISO-8601 timestamp */ + updatedAt: string; +}; + +export type OrganizationMember = { + orgId: string; + userId: string; + role: OrgRole; + /** ISO-8601 timestamp */ + createdAt: string; +}; + +/** Single-use bearer token — returned ONCE, never logged, TTL ORG_INVITE_TTL_SEC. */ +export type OrganizationInvite = { + token: string; + orgId: string; + role: OrgRole; + /** ISO-8601 timestamp */ + expiresAt: string; +}; diff --git a/packages/contracts/src/project.schema.ts b/packages/contracts/src/project.schema.ts new file mode 100644 index 0000000..4037bee --- /dev/null +++ b/packages/contracts/src/project.schema.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./project/project.schema.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './project/project.schema'; diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts new file mode 100644 index 0000000..f2f700a --- /dev/null +++ b/packages/contracts/src/project.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./project/project.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './project/project'; diff --git a/packages/contracts/src/project/project.schema.ts b/packages/contracts/src/project/project.schema.ts new file mode 100644 index 0000000..d29abee --- /dev/null +++ b/packages/contracts/src/project/project.schema.ts @@ -0,0 +1,68 @@ +import { z } from 'zod'; + +import type { Project, ProjectScope } from './project'; + +/** + * Boundary schemas for project.ts. + * Input schemas are verbatim apps/backend/src/projects/dto.ts (same + * regexes, min/max + error strings, partial-update derivation, link + * default) so backend/frontend validation stays identical after consumer + * migration. Response schema mirrors contracts/openapi.yaml Project. + */ + +export const projectScopeSchema = z.enum(['user', 'org']) satisfies z.ZodType; + +const ownerSchema = z + .string() + .regex(/^[A-Za-z0-9_.-]+$/, { error: 'githubOwner has invalid format' }) + .max(100); +const repoSchema = z + .string() + .regex(/^[A-Za-z0-9_.-]+$/, { error: 'githubRepo has invalid format' }) + .max(100); +const branchSchema = z + .string() + .regex(/^[A-Za-z0-9_./-]+$/, { error: 'githubBranch has invalid format' }) + .max(100); + +export const createProjectSchema = z.object({ + name: z.string({ error: 'Field "name" is required' }).min(1).max(200), + description: z.string().max(2000).optional(), + githubOwner: ownerSchema.optional(), + githubRepo: repoSchema.optional(), + githubBranch: branchSchema.optional(), + githubUrl: z.string().max(500).optional(), + ownerId: z.string().max(200).optional(), +}); + +export type CreateProjectInput = z.infer; + +export const updateProjectSchema = createProjectSchema.partial(); + +export type UpdateProjectInput = z.infer; + +export const githubLinkSchema = z.object({ + owner: ownerSchema, + repo: repoSchema, + branch: branchSchema.optional().default('main'), +}); + +export type GithubLinkInput = z.infer; + +export const projectSchema = z.object({ + id: z.uuid(), + name: z.string().min(1), + description: z.string().nullable(), + githubOwner: z.string().nullable(), + githubRepo: z.string().nullable(), + githubBranch: z.string().nullable(), + githubUrl: z.string().nullable(), + ownerId: z.string().nullable(), + /** ISO-8601 timestamp */ + createdAt: z.string().min(1), + /** ISO-8601 timestamp */ + updatedAt: z.string().min(1), + corrupted: z.boolean(), + corruptedReason: z.string().nullable(), + scope: projectScopeSchema.optional(), +}) satisfies z.ZodType; diff --git a/packages/contracts/src/project/project.ts b/packages/contracts/src/project/project.ts new file mode 100644 index 0000000..fad620d --- /dev/null +++ b/packages/contracts/src/project/project.ts @@ -0,0 +1,38 @@ +/** + * Project contracts. + * + * Mirrors contracts/openapi.yaml components/schemas: Project, + * CreateProject (+ ProjectScope, reused for the disk-home scope). + * Request input types live in project.schema.ts (inferred from the + * backend-verbatim zod schemas). + */ + +/** Disk-home scope (REPOS_ROOT users//… vs orgs//…). */ +export type ProjectScope = 'user' | 'org'; + +export type Project = { + id: string; + name: string; + description: string | null; + githubOwner: string | null; + githubRepo: string | null; + githubBranch: string | null; + githubUrl: string | null; + ownerId: string | null; + /** ISO-8601 timestamp */ + createdAt: string; + /** ISO-8601 timestamp */ + updatedAt: string; + /** Computed flag (no DB column): true when the on-disk git repo is missing/invalid. */ + corrupted: boolean; + /** + * Machine reason when corrupted (missing-dir, no-git, rev-parse-failed, + * fsck-failed, timeout, storage-unconfigured, …). + */ + corruptedReason: string | null; + /** + * Disk-home scope — frontend-additive (older caches stay valid without it). + * Linking a project to an org is metadata-only (no disk move). + */ + scope?: ProjectScope; +}; diff --git a/packages/contracts/src/repo-entry.schema.ts b/packages/contracts/src/repo-entry.schema.ts new file mode 100644 index 0000000..280379e --- /dev/null +++ b/packages/contracts/src/repo-entry.schema.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./repo-entry/repo-entry.schema.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './repo-entry/repo-entry.schema'; diff --git a/packages/contracts/src/repo-entry.ts b/packages/contracts/src/repo-entry.ts new file mode 100644 index 0000000..657e740 --- /dev/null +++ b/packages/contracts/src/repo-entry.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./repo-entry/repo-entry.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './repo-entry/repo-entry'; diff --git a/packages/contracts/src/repo-entry/repo-entry.schema.ts b/packages/contracts/src/repo-entry/repo-entry.schema.ts new file mode 100644 index 0000000..0fd3a73 --- /dev/null +++ b/packages/contracts/src/repo-entry/repo-entry.schema.ts @@ -0,0 +1,27 @@ +import { z } from 'zod'; + +import type { RepoEntry } from './repo-entry'; + +/** + * Boundary schema for repo-entry.ts. + * userSpace mirrors apps/backend/src/repos/dto.ts userSpaceSchema verbatim + * (same length/charset constraints + error strings — the openapi path param + * requires the same /^[a-zA-Z0-9_-]+$/ segment). Remaining scalars carry + * min(1) so empty strings fail fast; no max/charset on name/path — the + * registry lists hand-dropped dirs and must never reject live data. + */ + +export const repoEntrySchema = z.object({ + userSpace: z + .string() + .min(1, { error: 'userSpace must be a non-empty [a-zA-Z0-9_-] segment' }) + .max(64, { error: 'userSpace must be at most 64 chars' }) + .regex(/^[a-zA-Z0-9_-]+$/, { + error: 'userSpace must match /^[a-zA-Z0-9_-]+$/', + }), + name: z.string().min(1), + /** Path relative to REPOS_ROOT, e.g. "alice/workspace/demo" */ + path: z.string().min(1), + /** ISO-8601 mtime of the repo directory */ + updatedAt: z.string().min(1), +}) satisfies z.ZodType; diff --git a/packages/contracts/src/repo-entry/repo-entry.ts b/packages/contracts/src/repo-entry/repo-entry.ts new file mode 100644 index 0000000..c6725db --- /dev/null +++ b/packages/contracts/src/repo-entry/repo-entry.ts @@ -0,0 +1,18 @@ +/** + * Readonly git-repo registry entry. + * + * Mirrors contracts/openapi.yaml components/schemas Repo (field-for-field) + * plus apps/backend/src/contracts.ts RepoEntry. + * Previously duplicated in apps/backend/src/contracts.ts and + * apps/frontend/src/api/types.ts — this package is the single source. + */ + +/** GET /api/v1/repos + GET /api/v1/repos/:userSpace — readonly git-repo registry */ +export type RepoEntry = { + userSpace: string; + name: string; + /** Path relative to REPOS_ROOT, e.g. "alice/workspace/demo" */ + path: string; + /** ISO-8601 mtime of the repo directory */ + updatedAt: string; +}; diff --git a/packages/contracts/src/session.schema.ts b/packages/contracts/src/session.schema.ts new file mode 100644 index 0000000..fb4c113 --- /dev/null +++ b/packages/contracts/src/session.schema.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./session/session.schema.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './session/session.schema'; diff --git a/packages/contracts/src/session.ts b/packages/contracts/src/session.ts new file mode 100644 index 0000000..ad02a17 --- /dev/null +++ b/packages/contracts/src/session.ts @@ -0,0 +1,5 @@ +/** + * @deprecated Import from `@devbox/contracts` (or `./session/session.js`) instead. + * Forward-Only re-export shim — do not add new exports here. + */ +export * from './session/session'; diff --git a/packages/contracts/src/session/session.schema.ts b/packages/contracts/src/session/session.schema.ts new file mode 100644 index 0000000..f959185 --- /dev/null +++ b/packages/contracts/src/session/session.schema.ts @@ -0,0 +1,58 @@ +import { z } from 'zod'; + +import type { + ChatMessage, + ChatRole, + MessagesResponse, + SendChatRequest, + SendChatResponse, + Session, +} from './session'; + +/** + * Boundary schemas for session.ts. + * sendChatSchema is verbatim apps/backend/src/api/dto.ts (same field + * constraints + error strings) so backend/frontend validation stays + * identical after consumer migration. Response schemas mirror + * contracts/openapi.yaml; scalar ids/timestamps carry min(1) so empty + * strings fail fast (content stays unconstrained — upstream may send + * empty deltas). + */ + +export const sendChatSchema = z.object({ + sessionId: z.string().optional(), + message: z + .string({ error: 'Field "message" is required' }) + .min(1, { error: 'Field "message" is required' }), +}) satisfies z.ZodType; + +export type SendChatInput = z.infer; + +export const chatRoleSchema = z.enum(['user', 'assistant', 'system']) satisfies z.ZodType; + +export const sessionSchema = z.object({ + id: z.string().min(1), + title: z.string().min(1), + /** ISO-8601 timestamp */ + createdAt: z.string().min(1), + model: z.string().min(1).optional(), +}) satisfies z.ZodType; + +export const chatMessageSchema = z.object({ + id: z.string().min(1), + sessionId: z.string().min(1), + role: chatRoleSchema, + content: z.string(), + /** ISO-8601 timestamp */ + createdAt: z.string().min(1), +}) satisfies z.ZodType; + +export const sendChatResponseSchema = z.object({ + sessionId: z.string().min(1), + message: chatMessageSchema, +}) satisfies z.ZodType; + +export const messagesResponseSchema = z.object({ + sessionId: z.string().min(1), + messages: z.array(chatMessageSchema), +}) satisfies z.ZodType; diff --git a/packages/contracts/src/session/session.ts b/packages/contracts/src/session/session.ts new file mode 100644 index 0000000..b050ad9 --- /dev/null +++ b/packages/contracts/src/session/session.ts @@ -0,0 +1,50 @@ +/** + * Session + chat contracts. + * + * Mirrors contracts/openapi.yaml components/schemas: Session, ChatMessage, + * SendChatRequest, SendChatResponse, MessagesResponse (field-for-field). + * Previously duplicated in apps/backend/src/contracts.ts and + * apps/frontend/src/api/types.ts — this package is the single source. + */ + +/** GET /api/v1/session — live upstream session (503 when opencode unreachable) */ +export type Session = { + id: string; + title: string; + /** ISO-8601 timestamp */ + createdAt: string; + /** model name when known */ + model?: string; +}; + +/** Single chat message */ +export type ChatRole = 'user' | 'assistant' | 'system'; + +export type ChatMessage = { + id: string; + sessionId: string; + role: ChatRole; + content: string; + /** ISO-8601 timestamp */ + createdAt: string; +}; + +/** POST /api/v1/chat request body */ +export type SendChatRequest = { + /** omit to let the backend use the active upstream session */ + sessionId?: string; + message: string; +}; + +/** POST /api/v1/chat response (live upstream reply; 503 when unreachable) */ +export type SendChatResponse = { + sessionId: string; + /** assistant reply */ + message: ChatMessage; +}; + +/** GET /api/v1/messages?sessionId=… */ +export type MessagesResponse = { + sessionId: string; + messages: ChatMessage[]; +}; diff --git a/packages/contracts/tsconfig.json b/packages/contracts/tsconfig.json new file mode 100644 index 0000000..753199d --- /dev/null +++ b/packages/contracts/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "types": ["node"], + "lib": ["ES2022"] + }, + "include": ["src"], + "exclude": ["node_modules", "dist"] +} From 0a639db84bedd79cca02dc79f57fb6570b94c8ab Mon Sep 17 00:00:00 2001 From: alwoo Date: Tue, 20 Oct 2026 15:22:45 +0400 Subject: [PATCH 013/315] refactor(contracts): consume @devbox/contracts in backend and frontend Replace duplicated DTO/type definitions with Forward-Only deprecated re-exports of the shared package. Align contracts/openapi.yaml (Health.status enum, Project.scope). Warns from guards (unvalidated-input/form) are pre-existing and non-blocking. --- apps/backend/README.md | 2 +- apps/backend/package.json | 1 + apps/backend/src/api/api.controller.ts | 8 +- apps/backend/src/api/api.module.ts | 6 +- apps/backend/src/api/dto.ts | 16 +- apps/backend/src/api/proxy.service.ts | 10 +- apps/backend/src/api/versioning.e2e.ts | 8 +- apps/backend/src/app.module.ts | 28 +- apps/backend/src/app.setup.ts | 8 +- apps/backend/src/auth/auth-provider.ts | 12 +- apps/backend/src/auth/auth.controller.ts | 26 +- apps/backend/src/auth/auth.e2e.ts | 12 +- apps/backend/src/auth/auth.module.ts | 18 +- apps/backend/src/auth/dto.ts | 74 +--- apps/backend/src/auth/identity.service.ts | 4 +- apps/backend/src/auth/jwt-auth.guard.ts | 10 +- apps/backend/src/auth/password.service.ts | 6 +- apps/backend/src/auth/req-user.decorator.ts | 4 +- apps/backend/src/auth/token.service.ts | 10 +- apps/backend/src/auth/users.controller.ts | 14 +- apps/backend/src/auth/users.service.ts | 12 +- apps/backend/src/common/api-error.filter.ts | 6 +- apps/backend/src/common/app-logger.service.ts | 2 +- apps/backend/src/common/common.module.ts | 4 +- .../common/external/external-client.e2e.ts | 8 +- .../src/common/external/external-client.ts | 12 +- .../common/external/external-error.spec.ts | 2 +- .../src/common/external/external-error.ts | 4 +- .../backend/src/common/external/retry.spec.ts | 4 +- apps/backend/src/common/external/retry.ts | 10 +- apps/backend/src/contracts.ts | 202 ++--------- apps/backend/src/db/db.module.ts | 2 +- apps/backend/src/db/db.service.ts | 6 +- apps/backend/src/db/e2e-db.ts | 4 +- .../docker-registry/docker-registry.config.ts | 10 +- .../docker-registry.controller.ts | 8 +- .../docker-registry/docker-registry.e2e.ts | 4 +- .../docker-registry/docker-registry.module.ts | 4 +- .../docker-registry.service.spec.ts | 16 +- .../docker-registry.service.ts | 12 +- apps/backend/src/env-failfast.spec.ts | 4 +- apps/backend/src/env.spec.ts | 2 +- apps/backend/src/env.ts | 8 +- apps/backend/src/health/health.controller.ts | 12 +- apps/backend/src/health/health.module.ts | 10 +- apps/backend/src/main.ts | 8 +- .../src/npm-registry/npm-registry.config.ts | 10 +- .../npm-registry/npm-registry.controller.ts | 8 +- .../src/npm-registry/npm-registry.e2e.ts | 8 +- .../src/npm-registry/npm-registry.module.ts | 4 +- .../npm-registry/npm-registry.service.spec.ts | 16 +- .../src/npm-registry/npm-registry.service.ts | 12 +- .../crypto.service.hardening.spec.ts | 6 +- .../src/opencode-keys/crypto.service.spec.ts | 2 +- .../src/opencode-keys/crypto.service.ts | 20 +- apps/backend/src/opencode-keys/dto.ts | 21 +- .../opencode-keys/opencode-billing.service.ts | 18 +- .../opencode-keys/opencode-keys.controller.ts | 22 +- .../src/opencode-keys/opencode-keys.e2e.ts | 18 +- .../src/opencode-keys/opencode-keys.module.ts | 10 +- .../opencode-keys/opencode-keys.service.ts | 10 +- .../src/opencode-keys/reencrypt-keys.ts | 18 +- apps/backend/src/opencode/opencode-client.ts | 8 +- .../src/opencode/opencode.controller.ts | 12 +- apps/backend/src/opencode/opencode.e2e.ts | 8 +- apps/backend/src/opencode/opencode.module.ts | 6 +- apps/backend/src/opencode/opencode.service.ts | 6 +- apps/backend/src/organizations/dto.ts | 65 ++-- .../organizations/organizations.controller.ts | 16 +- .../src/organizations/organizations.e2e.ts | 16 +- .../src/organizations/organizations.module.ts | 8 +- .../organizations.service.spec.ts | 4 +- .../organizations/organizations.service.ts | 30 +- .../src/projects/chats/chats.controller.ts | 18 +- .../src/projects/chats/chats.module.ts | 12 +- .../src/projects/chats/chats.service.ts | 16 +- apps/backend/src/projects/dto.ts | 51 +-- .../files/project-files.controller.ts | 16 +- .../projects/files/project-files.module.ts | 10 +- .../projects/files/project-files.service.ts | 16 +- .../src/projects/github-link.service.ts | 6 +- .../src/projects/github/github-app.service.ts | 10 +- .../github/github-installations.service.ts | 14 +- .../projects/github/github-webhook.util.ts | 4 +- .../src/projects/github/github.controller.ts | 24 +- .../backend/src/projects/github/github.e2e.ts | 12 +- .../src/projects/github/github.module.ts | 12 +- .../src/projects/github/github.service.ts | 20 +- .../src/projects/project-disk-mapping.spec.ts | 4 +- .../src/projects/project-strict-root.spec.ts | 4 +- .../src/projects/projects.controller.ts | 14 +- apps/backend/src/projects/projects.e2e.ts | 22 +- apps/backend/src/projects/projects.module.ts | 18 +- apps/backend/src/projects/projects.service.ts | 16 +- .../projects/sessions/sessions.controller.ts | 16 +- .../src/projects/sessions/sessions.module.ts | 12 +- .../src/projects/sessions/sessions.service.ts | 18 +- apps/backend/src/repos/repos-git.util.ts | 8 +- apps/backend/src/repos/repos.controller.ts | 8 +- apps/backend/src/repos/repos.e2e.ts | 4 +- apps/backend/src/repos/repos.module.ts | 4 +- apps/backend/src/repos/repos.service.spec.ts | 10 +- apps/backend/src/repos/repos.service.ts | 16 +- .../src/storage/storage-unavailable.spec.ts | 14 +- .../src/storage/storage-unavailable.ts | 4 +- .../src/workspaces/clone-jobs.repository.ts | 6 +- .../src/workspaces/workspace-clone.service.ts | 14 +- .../src/workspaces/workspace-path.service.ts | 10 +- .../src/workspaces/workspace-path.spec.ts | 2 +- .../workspaces/workspace-submodules.util.ts | 10 +- .../src/workspaces/workspaces.controller.ts | 22 +- .../src/workspaces/workspaces.module.ts | 12 +- .../src/workspaces/workspaces.service.ts | 14 +- apps/backend/tsconfig.json | 3 +- apps/backend/tsconfig.lint.json | 7 + .../(dashboard)/organizations/[id]/page.tsx | 2 +- apps/frontend/package.json | 1 + apps/frontend/src/App.tsx | 2 +- apps/frontend/src/api/client.ts | 25 +- apps/frontend/src/api/types.ts | 325 ++++-------------- .../src/components/chat/chat-input.tsx | 4 +- .../src/components/chat/chat-message.tsx | 4 +- .../src/components/chat/chat-window.tsx | 4 +- .../src/components/dashboard-shell.tsx | 8 +- .../src/components/layout/Content.tsx | 8 +- .../src/components/layout/Sidebar.tsx | 8 +- .../create-organization-dialog.tsx | 4 +- .../projects/create-project-dialog.tsx | 4 +- apps/frontend/src/components/registry-hub.tsx | 4 +- .../src/features/usage/usage-section.tsx | 2 +- .../src/features/usage/usage-status.ts | 4 +- .../hooks/__tests__/orgScopeMapping.test.ts | 2 +- apps/frontend/src/hooks/useAiProviders.ts | 4 +- apps/frontend/src/hooks/useChat.ts | 12 +- apps/frontend/src/hooks/useInvite.ts | 6 +- apps/frontend/src/hooks/useLogin.ts | 4 +- apps/frontend/src/hooks/useNpm.ts | 4 +- apps/frontend/src/hooks/useOpencodeChat.ts | 4 +- apps/frontend/src/hooks/useOpencodeEvents.ts | 4 +- .../frontend/src/hooks/useOpencodeSessions.ts | 4 +- apps/frontend/src/hooks/useOrgMembers.ts | 6 +- apps/frontend/src/hooks/useOrganization.ts | 6 +- apps/frontend/src/hooks/useOrganizations.ts | 6 +- apps/frontend/src/hooks/useProfile.ts | 6 +- apps/frontend/src/hooks/useProject.ts | 6 +- apps/frontend/src/hooks/useProjects.ts | 6 +- apps/frontend/src/hooks/useRegistries.ts | 4 +- apps/frontend/src/hooks/useSecrets.ts | 4 +- apps/frontend/src/hooks/useUsage.ts | 6 +- apps/frontend/src/hooks/useUser.ts | 6 +- apps/frontend/src/i18n/dictionaries/types.ts | 4 +- apps/frontend/src/i18n/index.tsx | 4 +- apps/frontend/src/lib/auth-schemas.ts | 40 +-- apps/frontend/src/lib/auth-store.ts | 6 +- apps/frontend/src/lib/format-error.ts | 4 +- apps/frontend/src/lib/mocks/auth.ts | 4 +- apps/frontend/src/lib/organization-schemas.ts | 10 +- apps/frontend/src/lib/project-schemas.ts | 11 +- apps/frontend/src/lib/types.ts | 31 +- contracts/openapi.yaml | 3 + 160 files changed, 882 insertions(+), 1312 deletions(-) create mode 100644 apps/backend/tsconfig.lint.json diff --git a/apps/backend/README.md b/apps/backend/README.md index 734fe24..be7f7b0 100644 --- a/apps/backend/README.md +++ b/apps/backend/README.md @@ -3,7 +3,7 @@ NestJS 12 API that fronts the live opencode server (migrated from `node:http`). Contract: [`contracts/openapi.yaml`](../../contracts/openapi.yaml) · -DTOs: [`src/contracts.ts`](./src/contracts.ts) (duplicated in frontend, no cross-imports). +DTOs: [`@devbox/contracts`](../../packages/contracts/src/index.ts) (single source of truth; [`src/contracts.ts`](./src/contracts.ts) is a deprecated re-export). ## Stack (pinned) diff --git a/apps/backend/package.json b/apps/backend/package.json index 1994f78..d34190e 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -19,6 +19,7 @@ "test:e2e:repos": "bun run build && bun dist/repos/repos.service.spec.js && bun dist/repos/repos.e2e.js" }, "dependencies": { + "@devbox/contracts": "workspace:*", "@nestjs/common": "^12.1.0", "@nestjs/config": "^12.0.1", "@nestjs/core": "^12.1.0", diff --git a/apps/backend/src/api/api.controller.ts b/apps/backend/src/api/api.controller.ts index aaf67ac..18b838c 100644 --- a/apps/backend/src/api/api.controller.ts +++ b/apps/backend/src/api/api.controller.ts @@ -16,8 +16,8 @@ import { ApiResponse, ApiTags, } from '@nestjs/swagger'; -import { ProxyService } from './proxy.service.js'; -import { ZodValidationPipe } from '../common/zod-validation.pipe.js'; +import { ProxyService } from './proxy.service'; +import { ZodValidationPipe } from '../common/zod-validation.pipe'; import { ApiErrorDto, MessagesResponseDto, @@ -25,11 +25,11 @@ import { SendChatResponseDto, SessionDto, sendChatSchema, -} from './dto.js'; +} from './dto'; import { DEFAULT_API_VERSION, V1Endpoint, -} from './version.js'; +} from './version'; /** * Proxy endpoints. diff --git a/apps/backend/src/api/api.module.ts b/apps/backend/src/api/api.module.ts index 628cf92..97b55bc 100644 --- a/apps/backend/src/api/api.module.ts +++ b/apps/backend/src/api/api.module.ts @@ -1,7 +1,7 @@ import { Module } from '@nestjs/common'; -import { ApiController } from './api.controller.js'; -import { ProxyService } from './proxy.service.js'; -import { OpencodeModule } from '../opencode/opencode.module.js'; +import { ApiController } from './api.controller'; +import { ProxyService } from './proxy.service'; +import { OpencodeModule } from '../opencode/opencode.module'; @Module({ imports: [OpencodeModule], diff --git a/apps/backend/src/api/dto.ts b/apps/backend/src/api/dto.ts index a52b37f..16207b9 100644 --- a/apps/backend/src/api/dto.ts +++ b/apps/backend/src/api/dto.ts @@ -2,19 +2,13 @@ import { ApiProperty } from '@nestjs/swagger'; import { z } from 'zod'; /** - * POST /api/v1/chat body — zod@4 source of truth (Standard Schema), - * DTO class carries @ApiProperty for @nestjs/swagger parity - * with contracts/openapi.yaml. Runtime validation goes through + * POST /api/v1/chat body — single source of truth is @devbox/contracts + * (verbatim constraints + error strings, Standard Schema compatible). + * SendChatRequestDto below stays as the thin @nestjs/swagger wrapper for + * contracts/openapi.yaml parity. Runtime validation via * ZodValidationPipe(sendChatSchema). */ -export const sendChatSchema = z.object({ - sessionId: z.string().optional(), - message: z - .string({ error: 'Field "message" is required' }) - .min(1, { error: 'Field "message" is required' }), -}); - -export type SendChatInput = z.infer; +export { sendChatSchema, type SendChatInput } from '@devbox/contracts'; /** * POST /api/opencode/session/:id/message body — passthrough shape for the diff --git a/apps/backend/src/api/proxy.service.ts b/apps/backend/src/api/proxy.service.ts index 9c124e5..82dbfb1 100644 --- a/apps/backend/src/api/proxy.service.ts +++ b/apps/backend/src/api/proxy.service.ts @@ -4,11 +4,11 @@ import type { MessagesResponse, SendChatResponse, Session, -} from '../contracts.js'; -import { OpencodeService } from '../opencode/opencode.service.js'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ExternalClient } from '../common/external/external-client.js'; -import { fromStatus, fromUnknown } from '../common/external/external-error.js'; +} from '@devbox/contracts'; +import { OpencodeService } from '../opencode/opencode.service'; +import { AppLogger } from '../common/app-logger.service'; +import { ExternalClient } from '../common/external/external-client'; +import { fromStatus, fromUnknown } from '../common/external/external-error'; /** * ProxyService — forwards /api/v1/* to the opencode server. diff --git a/apps/backend/src/api/versioning.e2e.ts b/apps/backend/src/api/versioning.e2e.ts index e82eb00..dc11eea 100644 --- a/apps/backend/src/api/versioning.e2e.ts +++ b/apps/backend/src/api/versioning.e2e.ts @@ -28,16 +28,16 @@ for (const key of ['POSTGRES_USER', 'POSTGRES_PASSWORD', 'POSTGRES_DB', 'POSTGRE delete process.env[key]; } -interface CheckResult { +type CheckResult = { name: string; ok: boolean; detail?: string; -} +}; async function main(): Promise { const { NestFactory } = await import('@nestjs/core'); - const { AppModule } = await import('../app.module.js'); - const { configureApp, setupSwagger } = await import('../app.setup.js'); + const { AppModule } = await import('../app.module'); + const { configureApp, setupSwagger } = await import('../app.setup'); const app = await NestFactory.create(AppModule, { logger: false }); configureApp(app); diff --git a/apps/backend/src/app.module.ts b/apps/backend/src/app.module.ts index 460b51d..5f4f234 100644 --- a/apps/backend/src/app.module.ts +++ b/apps/backend/src/app.module.ts @@ -1,19 +1,19 @@ import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; -import { DbModule } from './db/db.module.js'; -import { HealthModule } from './health/health.module.js'; -import { ApiModule } from './api/api.module.js'; -import { CommonModule } from './common/common.module.js'; -import { DockerRegistryModule } from './docker-registry/docker-registry.module.js'; -import { NpmRegistryModule } from './npm-registry/npm-registry.module.js'; -import { OpencodeModule } from './opencode/opencode.module.js'; -import { OpencodeKeysModule } from './opencode-keys/opencode-keys.module.js'; -import { OrganizationsModule } from './organizations/organizations.module.js'; -import { ProjectsModule } from './projects/projects.module.js'; -import { ReposModule } from './repos/repos.module.js'; -import { WorkspacesModule } from './workspaces/workspaces.module.js'; -import { AuthModule } from './auth/auth.module.js'; -import { validateConfigForNest } from './env.js'; +import { DbModule } from './db/db.module'; +import { HealthModule } from './health/health.module'; +import { ApiModule } from './api/api.module'; +import { CommonModule } from './common/common.module'; +import { DockerRegistryModule } from './docker-registry/docker-registry.module'; +import { NpmRegistryModule } from './npm-registry/npm-registry.module'; +import { OpencodeModule } from './opencode/opencode.module'; +import { OpencodeKeysModule } from './opencode-keys/opencode-keys.module'; +import { OrganizationsModule } from './organizations/organizations.module'; +import { ProjectsModule } from './projects/projects.module'; +import { ReposModule } from './repos/repos.module'; +import { WorkspacesModule } from './workspaces/workspaces.module'; +import { AuthModule } from './auth/auth.module'; +import { validateConfigForNest } from './env'; @Module({ imports: [ diff --git a/apps/backend/src/app.setup.ts b/apps/backend/src/app.setup.ts index 61a6da8..7b78192 100644 --- a/apps/backend/src/app.setup.ts +++ b/apps/backend/src/app.setup.ts @@ -5,10 +5,10 @@ import { } from '@nestjs/common'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { json } from 'express'; -import { ApiErrorFilter } from './common/api-error.filter.js'; -import { CorrelationInterceptor } from './common/correlation.interceptor.js'; -import { validateEnv } from './env.js'; -import { DEFAULT_API_VERSION } from './api/version.js'; +import { ApiErrorFilter } from './common/api-error.filter'; +import { CorrelationInterceptor } from './common/correlation.interceptor'; +import { validateEnv } from './env'; +import { DEFAULT_API_VERSION } from './api/version'; /** * Shared Nest application wiring — used by main.ts AND the versioning e2e diff --git a/apps/backend/src/auth/auth-provider.ts b/apps/backend/src/auth/auth-provider.ts index 9c6ade5..57f1d94 100644 --- a/apps/backend/src/auth/auth-provider.ts +++ b/apps/backend/src/auth/auth-provider.ts @@ -1,11 +1,11 @@ import { Injectable, UnauthorizedException } from "@nestjs/common"; -import { AppLogger } from "../common/app-logger.service.js"; -import { PasswordService } from "./password.service.js"; -import { UsersService, type StoredUser } from "./users.service.js"; -import type { AuthProviderId } from "./users.service.js"; +import { AppLogger } from "../common/app-logger.service"; +import { PasswordService } from "./password.service"; +import { UsersService, type StoredUser } from "./users.service"; +import type { AuthProviderId } from "./users.service"; /** Strategy seam for external identity providers (local + future stubs). */ -export interface AuthProvider { +export type AuthProvider = { readonly id: AuthProviderId; /** Returns the user on success, null on bad credentials (caller answers 401/409). */ verify( @@ -13,7 +13,7 @@ export interface AuthProvider { password: string, correlationId?: string, ): Promise; -} +}; export type { AuthProviderId }; diff --git a/apps/backend/src/auth/auth.controller.ts b/apps/backend/src/auth/auth.controller.ts index 212a5d1..2a733b8 100644 --- a/apps/backend/src/auth/auth.controller.ts +++ b/apps/backend/src/auth/auth.controller.ts @@ -15,12 +15,12 @@ import { } from "@nestjs/common"; import { ApiBearerAuth, ApiResponse, ApiTags } from "@nestjs/swagger"; import type { Response } from "express"; -import { V1Endpoint } from "../api/version.js"; -import { AppLogger } from "../common/app-logger.service.js"; -import { ExternalServiceError } from "../common/external/external-error.js"; -import { ZodValidationPipe } from "../common/zod-validation.pipe.js"; -import { validateEnv } from "../env.js"; -import { LocalAuthProvider } from "./auth-provider.js"; +import { V1Endpoint } from "../api/version"; +import { AppLogger } from "../common/app-logger.service"; +import { ExternalServiceError } from "../common/external/external-error"; +import { ZodValidationPipe } from "../common/zod-validation.pipe"; +import { validateEnv } from "../env"; +import { LocalAuthProvider } from "./auth-provider"; import { AuthSessionDto, AuthTokensDto, @@ -29,7 +29,7 @@ import { RefreshBodyDto, RegisterBodyDto, UpdateMeBodyDto, -} from "./auth.dto.js"; +} from "./auth.dto"; import { loginSchema, refreshSchema, @@ -39,12 +39,12 @@ import { type RefreshInput, type RegisterInput, type UpdateMeInput, -} from "./dto.js"; -import { JwtAuthGuard } from "./jwt-auth.guard.js"; -import { ReqUser } from "./req-user.decorator.js"; -import type { RequestIdentity } from "./identity.service.js"; -import { TokenService } from "./token.service.js"; -import { UsersService, toPublicUser } from "./users.service.js"; +} from "./dto"; +import { JwtAuthGuard } from "./jwt-auth.guard"; +import { ReqUser } from "./req-user.decorator"; +import type { RequestIdentity } from "./identity.service"; +import { TokenService } from "./token.service"; +import { UsersService, toPublicUser } from "./users.service"; /** httpOnly refresh cookie (read by POST /auth/refresh via body or cookie). */ export const REFRESH_COOKIE = "devbox-refresh"; diff --git a/apps/backend/src/auth/auth.e2e.ts b/apps/backend/src/auth/auth.e2e.ts index d3b0183..40e8d75 100644 --- a/apps/backend/src/auth/auth.e2e.ts +++ b/apps/backend/src/auth/auth.e2e.ts @@ -26,7 +26,7 @@ process.env.AUTH_LEGACY_MOCK_FALLBACK = "false"; async function main(): Promise { const { resolveTestDb, applyTestMigrations } = - await import("../db/e2e-db.js"); + await import("../db/e2e-db"); const testDb = await resolveTestDb( process.env.TEST_DATABASE_URL ?? process.env.DATABASE_URL ?? "", ); @@ -45,10 +45,10 @@ async function main(): Promise { console.log(`[auth e2e] db mode: ${testDb.mode}`); const { NestFactory } = await import("@nestjs/core"); - const { AppModule } = await import("../app.module.js"); - const { configureApp } = await import("../app.setup.js"); - const { UsersService } = await import("./users.service.js"); - const { TokenService } = await import("./token.service.js"); + const { AppModule } = await import("../app.module"); + const { configureApp } = await import("../app.setup"); + const { UsersService } = await import("./users.service"); + const { TokenService } = await import("./token.service"); let passed = 0; let failed = 0; @@ -232,7 +232,7 @@ async function main(): Promise { await check( "register duplicate logs warn with correlationId (no secrets)", async () => { - const { AppLogger } = await import("../common/app-logger.service.js"); + const { AppLogger } = await import("../common/app-logger.service"); const seen: Array<{ msg: unknown; cid?: string }> = []; const origWarn = AppLogger.prototype.warn; ( diff --git a/apps/backend/src/auth/auth.module.ts b/apps/backend/src/auth/auth.module.ts index 3375f14..602b08b 100644 --- a/apps/backend/src/auth/auth.module.ts +++ b/apps/backend/src/auth/auth.module.ts @@ -1,17 +1,17 @@ import { Global, Module } from '@nestjs/common'; -import { DbModule } from '../db/db.module.js'; -import { AuthController } from './auth.controller.js'; +import { DbModule } from '../db/db.module'; +import { AuthController } from './auth.controller'; import { GithubAppProviderStub, LocalAuthProvider, SsoOauthProviderStub, -} from './auth-provider.js'; -import { IdentityService } from './identity.service.js'; -import { JwtAuthGuard } from './jwt-auth.guard.js'; -import { PasswordService } from './password.service.js'; -import { TokenService } from './token.service.js'; -import { UsersService } from './users.service.js'; -import { UsersController } from './users.controller.js'; +} from './auth-provider'; +import { IdentityService } from './identity.service'; +import { JwtAuthGuard } from './jwt-auth.guard'; +import { PasswordService } from './password.service'; +import { TokenService } from './token.service'; +import { UsersService } from './users.service'; +import { UsersController } from './users.controller'; /** * AuthModule — internal accounts (email+password, argon2id + HS256 JWT). diff --git a/apps/backend/src/auth/dto.ts b/apps/backend/src/auth/dto.ts index ce9d51e..ba63891 100644 --- a/apps/backend/src/auth/dto.ts +++ b/apps/backend/src/auth/dto.ts @@ -1,58 +1,16 @@ -import { z } from 'zod'; - -const nameField = z - .string() - .trim() - .min(1, { error: 'must not be empty' }) - .max(100, { error: 'must be ≤ 100 chars' }); - -const emailField = z - .string() - .trim() - .min(1, { error: 'must not be empty' }) - .max(320, { error: 'must be ≤ 320 chars' }) - .refine((v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), { - error: 'must be a valid email', - }); - -const passwordField = z - .string() - .min(8, { error: 'must be at least 8 characters' }) - .max(256, { error: 'must be ≤ 256 chars' }); - -/** POST /api/v1/auth/register — firstName/lastName/email/password. */ -export const registerSchema = z.object({ - firstName: nameField, - lastName: nameField, - email: emailField, - password: passwordField, -}); - -export type RegisterInput = z.infer; - -/** POST /api/v1/auth/login — email+password. */ -export const loginSchema = z.object({ - email: emailField, - password: passwordField, -}); - -export type LoginInput = z.infer; - -/** POST /api/v1/auth/refresh — single-use refresh token rotation. */ -export const refreshSchema = z.object({ - refreshToken: z.string().trim().min(1, { error: 'must not be empty' }), -}); - -export type RefreshInput = z.infer; - -/** PATCH /api/v1/auth/me — profile update (firstName/lastName only). */ -export const updateMeSchema = z - .object({ - firstName: nameField.optional(), - lastName: nameField.optional(), - }) - .refine((v) => v.firstName !== undefined || v.lastName !== undefined, { - error: 'at least one of firstName/lastName is required', - }); - -export type UpdateMeInput = z.infer; +/** + * Auth DTO — single source of truth is @devbox/contracts (verbatim trims, + * min/max, email regex + error strings; trim-first semantics preserved). + * Controllers keep importing from './dto' — the runtime objects are + * the package schemas. Swagger body DTOs live in ./auth.dto.ts. + */ +export { + loginSchema, + refreshSchema, + registerSchema, + updateMeSchema, + type LoginInput, + type RefreshInput, + type RegisterInput, + type UpdateMeInput, +} from '@devbox/contracts'; diff --git a/apps/backend/src/auth/identity.service.ts b/apps/backend/src/auth/identity.service.ts index f116937..9160fc3 100644 --- a/apps/backend/src/auth/identity.service.ts +++ b/apps/backend/src/auth/identity.service.ts @@ -8,13 +8,13 @@ import { Injectable } from '@nestjs/common'; export const DEFAULT_MOCK_USER_ID = 'default'; /** Authenticated request identity (JWT user or legacy mock fallback). */ -export interface RequestIdentity { +export type RequestIdentity = { /** User key — real uuid from JWT, or the mock key under legacy fallback. */ id: string; email: string | null; /** True only for the x-user-id / ?userId fallback path. */ mock: boolean; -} +}; /** * Resolves the MVP mock user key: x-user-id header wins, then ?userId query, diff --git a/apps/backend/src/auth/jwt-auth.guard.ts b/apps/backend/src/auth/jwt-auth.guard.ts index 64dfd59..446c3c1 100644 --- a/apps/backend/src/auth/jwt-auth.guard.ts +++ b/apps/backend/src/auth/jwt-auth.guard.ts @@ -4,11 +4,11 @@ import { Injectable, UnauthorizedException, } from "@nestjs/common"; -import { AppLogger } from "../common/app-logger.service.js"; -import { validateEnv } from "../env.js"; -import { resolveIdentityUserId } from "./identity.service.js"; -import { TokenService } from "./token.service.js"; -import { UsersService } from "./users.service.js"; +import { AppLogger } from "../common/app-logger.service"; +import { validateEnv } from "../env"; +import { resolveIdentityUserId } from "./identity.service"; +import { TokenService } from "./token.service"; +import { UsersService } from "./users.service"; function bearerToken(req: unknown): string | null { if (typeof req !== "object" || req === null) return null; diff --git a/apps/backend/src/auth/password.service.ts b/apps/backend/src/auth/password.service.ts index 3c86848..8e490d2 100644 --- a/apps/backend/src/auth/password.service.ts +++ b/apps/backend/src/auth/password.service.ts @@ -1,11 +1,11 @@ import { Injectable } from '@nestjs/common'; -import { AppLogger } from '../common/app-logger.service.js'; +import { AppLogger } from '../common/app-logger.service'; /** Minimal Bun.password shape (bun-native argon2id; no npm dependency). */ -interface BunPassword { +type BunPassword = { hash: (password: string, options?: Record) => Promise; verify: (password: string, hash: string) => Promise; -} +}; function bunPassword(): BunPassword { const bun = (globalThis as unknown as { Bun?: { password?: BunPassword } }).Bun; diff --git a/apps/backend/src/auth/req-user.decorator.ts b/apps/backend/src/auth/req-user.decorator.ts index 704fa54..6ac4052 100644 --- a/apps/backend/src/auth/req-user.decorator.ts +++ b/apps/backend/src/auth/req-user.decorator.ts @@ -1,6 +1,6 @@ import { createParamDecorator, type ExecutionContext } from '@nestjs/common'; -import { readIdentity } from './identity.service.js'; -import type { RequestIdentity } from './identity.service.js'; +import { readIdentity } from './identity.service'; +import type { RequestIdentity } from './identity.service'; export type { RequestIdentity }; diff --git a/apps/backend/src/auth/token.service.ts b/apps/backend/src/auth/token.service.ts index c71f2db..f78ee0e 100644 --- a/apps/backend/src/auth/token.service.ts +++ b/apps/backend/src/auth/token.service.ts @@ -1,25 +1,25 @@ import { Injectable } from '@nestjs/common'; import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'; -import { AppLogger } from '../common/app-logger.service.js'; +import { AppLogger } from '../common/app-logger.service'; export type TokenType = 'access' | 'refresh'; -export interface AccessClaims { +export type AccessClaims = { sub: string; email: string; typ: 'access'; jti: string; iat: number; exp: number; -} +}; -export interface RefreshClaims { +export type RefreshClaims = { sub: string; typ: 'refresh'; jti: string; iat: number; exp: number; -} +}; /** Ephemeral dev fallback secrets (unset JWT_*_SECRET → WARN + random per boot). Never logged. */ const devSecrets = new Map(); diff --git a/apps/backend/src/auth/users.controller.ts b/apps/backend/src/auth/users.controller.ts index fd3875c..ce54908 100644 --- a/apps/backend/src/auth/users.controller.ts +++ b/apps/backend/src/auth/users.controller.ts @@ -10,13 +10,13 @@ import { Version, } from "@nestjs/common"; import { ApiBearerAuth, ApiResponse, ApiTags } from "@nestjs/swagger"; -import { V1Endpoint } from "../api/version.js"; -import { NoIndexInterceptor } from "../common/noindex.interceptor.js"; -import { AuthUserDto } from "./auth.dto.js"; -import { ReqUser } from "./req-user.decorator.js"; -import type { RequestIdentity } from "./identity.service.js"; -import { JwtAuthGuard } from "./jwt-auth.guard.js"; -import { UsersService, toPublicUser } from "./users.service.js"; +import { V1Endpoint } from "../api/version"; +import { NoIndexInterceptor } from "../common/noindex.interceptor"; +import { AuthUserDto } from "./auth.dto"; +import { ReqUser } from "./req-user.decorator"; +import type { RequestIdentity } from "./identity.service"; +import { JwtAuthGuard } from "./jwt-auth.guard"; +import { UsersService, toPublicUser } from "./users.service"; /** * UsersController — minimal private profile read (Card 6 privacy). diff --git a/apps/backend/src/auth/users.service.ts b/apps/backend/src/auth/users.service.ts index 527d0db..3205223 100644 --- a/apps/backend/src/auth/users.service.ts +++ b/apps/backend/src/auth/users.service.ts @@ -1,15 +1,15 @@ import { Injectable } from "@nestjs/common"; import { eq, sql } from "drizzle-orm"; -import { AppLogger } from "../common/app-logger.service.js"; -import { DbService, dbUnavailable, type DbClient } from "../db/db.service.js"; -import { users, type UserRow } from "../db/schema.js"; -import { PasswordService } from "./password.service.js"; +import { AppLogger } from "../common/app-logger.service"; +import { DbService, dbUnavailable, type DbClient } from "../db/db.service"; +import { users, type UserRow } from "../db/schema"; +import { PasswordService } from "./password.service"; /** Auth provider ids — `local` is live; the rest are 501 stubs (no integration). */ export type AuthProviderId = "local" | "sso-oauth" | "github-app"; /** Stored user (durable contract = `users` drizzle table, drizzle/0003_users.sql). */ -export interface StoredUser { +export type StoredUser = { id: string; firstName: string; lastName: string; @@ -18,7 +18,7 @@ export interface StoredUser { provider: AuthProviderId; createdAt: string; updatedAt: string; -} +}; /** Public shape — never carries passwordHash (never logged, never serialized). */ export function toPublicUser(u: StoredUser): { diff --git a/apps/backend/src/common/api-error.filter.ts b/apps/backend/src/common/api-error.filter.ts index ac1a368..9c6b571 100644 --- a/apps/backend/src/common/api-error.filter.ts +++ b/apps/backend/src/common/api-error.filter.ts @@ -6,9 +6,9 @@ import { HttpStatus, } from '@nestjs/common'; import { randomUUID } from 'node:crypto'; -import type { ApiError } from '../contracts.js'; -import { AppLogger } from './app-logger.service.js'; -import { ExternalServiceError } from './external/external-error.js'; +import type { ApiError } from '@devbox/contracts'; +import { AppLogger } from './app-logger.service'; +import { ExternalServiceError } from './external/external-error'; function isAbortError(err: unknown): boolean { if (!err || typeof err !== 'object') return false; diff --git a/apps/backend/src/common/app-logger.service.ts b/apps/backend/src/common/app-logger.service.ts index 998ff9b..5ff0937 100644 --- a/apps/backend/src/common/app-logger.service.ts +++ b/apps/backend/src/common/app-logger.service.ts @@ -1,5 +1,5 @@ import { Injectable, Logger, Optional, type LogLevel } from '@nestjs/common'; -import { validateEnv } from '../env.js'; +import { validateEnv } from '../env'; export type AppLogLevel = 'debug' | 'info' | 'warn' | 'error'; diff --git a/apps/backend/src/common/common.module.ts b/apps/backend/src/common/common.module.ts index 9778a90..b13431f 100644 --- a/apps/backend/src/common/common.module.ts +++ b/apps/backend/src/common/common.module.ts @@ -1,6 +1,6 @@ import { Global, Module } from '@nestjs/common'; -import { AppLogger } from './app-logger.service.js'; -import { ExternalClient } from './external/external-client.js'; +import { AppLogger } from './app-logger.service'; +import { ExternalClient } from './external/external-client'; /** * Global logger module — AppLogger is injectable in any provider diff --git a/apps/backend/src/common/external/external-client.e2e.ts b/apps/backend/src/common/external/external-client.e2e.ts index 474a2bf..64685b9 100644 --- a/apps/backend/src/common/external/external-client.e2e.ts +++ b/apps/backend/src/common/external/external-client.e2e.ts @@ -40,12 +40,12 @@ const LIVE_SESSION = { model: 'live', }; -interface Flaky { +type Flaky = { server: Server; url: string; hits: (path: string) => number; close: () => Promise; -} +}; function startFlaky(): Promise { const counts = new Map(); @@ -104,8 +104,8 @@ async function main(): Promise { process.env.OPENCODE_URL = flaky.url; const { NestFactory } = await import('@nestjs/core'); - const { AppModule } = await import('../../app.module.js'); - const { configureApp } = await import('../../app.setup.js'); + const { AppModule } = await import('../../app.module'); + const { configureApp } = await import('../../app.setup'); const app = await NestFactory.create(AppModule, { logger: false }); configureApp(app); diff --git a/apps/backend/src/common/external/external-client.ts b/apps/backend/src/common/external/external-client.ts index 1de1bd1..eb559be 100644 --- a/apps/backend/src/common/external/external-client.ts +++ b/apps/backend/src/common/external/external-client.ts @@ -18,20 +18,20 @@ * secrets scrubbed). */ import { Injectable } from '@nestjs/common'; -import { AppLogger } from '../app-logger.service.js'; -import { validateEnv } from '../../env.js'; +import { AppLogger } from '../app-logger.service'; +import { validateEnv } from '../../env'; import { ExternalServiceError, fromStatus, fromUnknown, isRetryableStatus, timeoutError, -} from './external-error.js'; -import { DEFAULT_MAX_DELAY_MS, withRetry, type RetryOptions } from './retry.js'; +} from './external-error'; +import { DEFAULT_MAX_DELAY_MS, withRetry, type RetryOptions } from './retry'; export const FALLBACK_REQUEST_TIMEOUT_MS = 10000; -export interface ExternalFetchOptions { +export type ExternalFetchOptions = { /** Logical upstream, e.g. 'opencode' | 'github'. */ service: string; /** Logical operation, e.g. 'getSession' | 'sendChat'. */ @@ -44,7 +44,7 @@ export interface ExternalFetchOptions { allowNonIdempotentRetry?: boolean; /** Traced through every attempt log line. */ correlationId?: string; -} +}; function resolveTimeoutMs(explicit?: number): number { if (explicit !== undefined && Number.isInteger(explicit) && explicit >= 0) { diff --git a/apps/backend/src/common/external/external-error.spec.ts b/apps/backend/src/common/external/external-error.spec.ts index 1e68dfd..6ee4494 100644 --- a/apps/backend/src/common/external/external-error.spec.ts +++ b/apps/backend/src/common/external/external-error.spec.ts @@ -16,7 +16,7 @@ import { isRetryableStatus, isTimeoutError, timeoutError, -} from './external-error.js'; +} from './external-error'; const checks: Array<{ name: string; run: () => void }> = [ { diff --git a/apps/backend/src/common/external/external-error.ts b/apps/backend/src/common/external/external-error.ts index a9d8a18..4db7aa3 100644 --- a/apps/backend/src/common/external/external-error.ts +++ b/apps/backend/src/common/external/external-error.ts @@ -17,7 +17,7 @@ export type ExternalErrorCode = | 'EXTERNAL_UPSTREAM_5XX' | 'GITHUB_AUTH'; -export interface ExternalErrorOptions { +export type ExternalErrorOptions = { code: ExternalErrorCode; /** Logical upstream, e.g. 'opencode' | 'github' | 'db'. */ service: string; @@ -33,7 +33,7 @@ export interface ExternalErrorOptions { isRetryable?: boolean; /** Original cause (kept off the wire, never serialized to the envelope). */ cause?: unknown; -} +}; const FIXED_MESSAGES: Record = { EXTERNAL_TIMEOUT: 'Upstream request timed out', diff --git a/apps/backend/src/common/external/retry.spec.ts b/apps/backend/src/common/external/retry.spec.ts index db3a1ed..c5032cb 100644 --- a/apps/backend/src/common/external/retry.spec.ts +++ b/apps/backend/src/common/external/retry.spec.ts @@ -15,12 +15,12 @@ import { isRetryableError, resolveRetryOptions, withRetry, -} from './retry.js'; +} from './retry'; import { ExternalServiceError, fromStatus, timeoutError, -} from './external-error.js'; +} from './external-error'; const noSleep = () => Promise.resolve(); const checks: Array<{ name: string; run: () => Promise | void }> = [ diff --git a/apps/backend/src/common/external/retry.ts b/apps/backend/src/common/external/retry.ts index 7a29cb4..59e8539 100644 --- a/apps/backend/src/common/external/retry.ts +++ b/apps/backend/src/common/external/retry.ts @@ -17,7 +17,7 @@ import { ExternalServiceError, isRetryableStatus, isTimeoutError, -} from './external-error.js'; +} from './external-error'; export const DEFAULT_MAX_ATTEMPTS = 3; export const DEFAULT_BASE_DELAY_MS = 200; @@ -33,7 +33,7 @@ export const NON_IDEMPOTENT_METHODS: ReadonlySet = new Set([ 'DELETE', ]); -export interface RetryOptions { +export type RetryOptions = { /** Total attempts including the first (1 = no retry). Default 3. */ maxAttempts?: number; /** Base backoff in ms (doubles per attempt). Default 200. */ @@ -53,14 +53,14 @@ export interface RetryOptions { sleep?: (ms: number) => Promise; /** Custom retry predicate (default: isRetryableError). */ shouldRetry?: (err: unknown, attempt: number) => boolean; -} +}; -export interface ResolvedRetryOptions { +export type ResolvedRetryOptions = { maxAttempts: number; baseDelayMs: number; maxDelayMs: number; jitter: boolean; -} +}; /** True for GET/HEAD/OPTIONS (and anything outside the non-idempotent set). */ export function isIdempotentMethod(method?: string): boolean { diff --git a/apps/backend/src/contracts.ts b/apps/backend/src/contracts.ts index 3c4d6dc..3d728f8 100644 --- a/apps/backend/src/contracts.ts +++ b/apps/backend/src/contracts.ts @@ -1,177 +1,29 @@ /** - * Shared DTO contracts for the opencode proxy layer. - * - * NOTE: intentionally duplicated in apps/frontend/src/api/types.ts - * (no cross-workspace imports — npm workspaces apps/* have no shared package). - * No business logic here, only types + comments. Zod omitted on purpose: - * not in dependencies, TS types are enough for the contract stage. + * @deprecated Import from '@devbox/contracts' instead — this module is a + * thin Forward-Only re-export kept for one release so existing imports keep + * compiling. It carries types only (no runtime schemas); the single source + * of truth for entities + zod boundary schemas is + * packages/contracts (mirrors contracts/openapi.yaml field-for-field). + * Will be removed in the next release — do not add new exports here. */ - -/** GET /health (unversioned liveness probe) */ -export interface HealthResponse { - status: 'ok'; - /** postgres reachability: up | down | skipped (no DATABASE_URL / MVP boot without pg) */ - db: 'up' | 'down' | 'skipped'; - /** opencode server reachability: up (any HTTP response) | down (timeout/network) */ - opencode: 'up' | 'down'; - /** docker registry reachability: up | down | skipped (no DOCKER_REGISTRY_URL) */ - registry: 'up' | 'down' | 'skipped'; - /** npm registry (Verdaccio) reachability: up | down | skipped (no NPM_REGISTRY_URL) */ - npmRegistry: 'up' | 'down' | 'skipped'; -} - -/** GET /api/v1/registry/catalog — live Docker Registry /v2/_catalog (503 when unreachable) */ -export interface RegistryCatalogResponse { - repositories: string[]; -} - -/** GET /api/v1/registry/npm/status — live Verdaccio /-/ping reachability (503 when unreachable) */ -export interface NpmRegistryStatusResponse { - status: 'up'; - /** Canonical registry base URL, no trailing slash (never carries the token) */ - url: string; - /** Observed npm scope, e.g. '@web2bizz' */ - scope: string; -} - -/** GET /api/v1/session — live upstream session (503 when opencode unreachable) */ -export interface Session { - id: string; - title: string; - /** ISO-8601 timestamp */ - createdAt: string; - /** model name when known */ - model?: string; -} - -/** Single chat message */ -export type ChatRole = 'user' | 'assistant' | 'system'; - -export interface ChatMessage { - id: string; - sessionId: string; - role: ChatRole; - content: string; - /** ISO-8601 timestamp */ - createdAt: string; -} - -/** POST /api/v1/chat request body */ -export interface SendChatRequest { - /** omit to let backend use the active upstream session */ - sessionId?: string; - message: string; -} - -/** POST /api/v1/chat response (live upstream reply; 503 when unreachable) */ -export interface SendChatResponse { - sessionId: string; - /** assistant reply */ - message: ChatMessage; -} - -/** GET /api/v1/messages?sessionId=… */ -export interface MessagesResponse { - sessionId: string; - messages: ChatMessage[]; -} - -/** GET /api/v1/repos + GET /api/v1/repos/:userSpace — readonly git-repo registry */ -export interface RepoEntry { - userSpace: string; - name: string; - /** Path relative to REPOS_ROOT, e.g. "alice/workspace/demo" */ - path: string; - /** ISO-8601 mtime of the repo directory */ - updatedAt: string; -} - -/** Unified error envelope for all /api/v1/* routes */ -export interface ApiError { - /** - * machine-readable code: legacy lowercase (`bad_request` | `unauthorized` | - * `forbidden` | `not_found` | `internal_error` | …) plus typed upstream - * codes (`EXTERNAL_TIMEOUT` | `EXTERNAL_UNAVAILABLE` | - * `EXTERNAL_RATE_LIMITED` | `EXTERNAL_UPSTREAM_5XX` | `GITHUB_AUTH`) plus - * auth codes (`invalid_credentials` | `email_taken` | `provider_not_configured`). - * Shape is frozen — only new code VALUES are added, never new fields. - */ - code: string; - /** human-readable message (no secrets) */ - message: string; - /** echo of x-correlation-id / generated uuid for log tracing */ - correlationId: string; -} - -/** POST /api/v1/auth/register + login response user (never carries passwordHash) */ -export interface AuthUser { - id: string; - firstName: string; - lastName: string; - email: string; - provider: 'local' | 'sso-oauth' | 'github-app'; - /** ISO-8601 timestamp */ - createdAt: string; -} - -/** Token pair (short-lived access + rotating refresh). */ -export interface AuthTokens { - accessToken: string; - refreshToken: string; - tokenType: 'bearer'; - /** Access lifetime in seconds. */ - expiresIn: number; -} - -/** POST /api/v1/auth/register + login response (user + tokens). */ -export interface AuthSession extends AuthTokens { - user: AuthUser; -} - -/** PUT /api/v1/key result (carries no secret). */ -export interface OpencodeKeyResult { - ok: boolean; - /** ISO-8601 timestamp */ - updatedAt: string; -} - -/** DELETE /api/v1/key result (idempotent, no timestamp). */ -export interface OpencodeKeyDeleteResult { - ok: boolean; -} - -/** GET /api/v1/key — whether the caller has a key stored. */ -export interface OpencodeKeyStatus { - configured: boolean; - /** ISO-8601 timestamp (present only when configured). */ - updatedAt?: string; -} - -/** Single usage bucket — real `used/limit` pair from upstream (no derivation). */ -export interface OpencodeLimitBucket { - used: number; - limit: number; -} - -/** GET /api/v1/usage — live Zen Go usage (percent windows mapped to used/limit 100). */ -export interface OpencodeUsage { - /** Legacy pay-as-you-go fields — present only for legacy upstream payloads. */ - balance?: number; - /** Legacy pay-as-you-go total — present only for legacy upstream payloads. */ - usage?: number; - /** ISO-8601 time of the upstream response */ - updatedAt: string; - /** - * Zen Go windows mapped to used/limit (`percent` → `{ used: percent, limit: 100 }`). - * `rolling` is the Zen 5-hour window (20% of monthly); legacy `daily` has - * no Zen equivalent and is kept for old payloads. Present only when the - * upstream payload carries finite numbers — never derived from a total. - * Upstream shape is the Zen Go endpoint (module OPENCODE_BILLING_URL - * constant = https://opencode.ai/zen/go/v1/usage) — the billing service - * maps percent windows and passes legacy buckets through when finite. - */ - rolling?: OpencodeLimitBucket; - daily?: OpencodeLimitBucket; - weekly?: OpencodeLimitBucket; - monthly?: OpencodeLimitBucket; -} +export type { + ApiError, + AuthSession, + AuthTokens, + AuthUser, + ChatMessage, + ChatRole, + HealthResponse, + MessagesResponse, + NpmRegistryStatusResponse, + OpencodeKeyDeleteResult, + OpencodeKeyResult, + OpencodeKeyStatus, + OpencodeLimitBucket, + OpencodeUsage, + RegistryCatalogResponse, + RepoEntry, + SendChatRequest, + SendChatResponse, + Session, +} from '@devbox/contracts'; diff --git a/apps/backend/src/db/db.module.ts b/apps/backend/src/db/db.module.ts index c3d2f7c..962409e 100644 --- a/apps/backend/src/db/db.module.ts +++ b/apps/backend/src/db/db.module.ts @@ -1,5 +1,5 @@ import { Module } from '@nestjs/common'; -import { DbService } from './db.service.js'; +import { DbService } from './db.service'; @Module({ providers: [DbService], diff --git a/apps/backend/src/db/db.service.ts b/apps/backend/src/db/db.service.ts index 31cb80b..1ee75fb 100644 --- a/apps/backend/src/db/db.service.ts +++ b/apps/backend/src/db/db.service.ts @@ -3,9 +3,9 @@ import { ConfigService } from "@nestjs/config"; import { drizzle } from "drizzle-orm/node-postgres"; import { sql } from "drizzle-orm"; import { Pool } from "pg"; -import { validateEnv } from "../env.js"; -import { AppLogger } from "../common/app-logger.service.js"; -import { ExternalServiceError } from "../common/external/external-error.js"; +import { validateEnv } from "../env"; +import { AppLogger } from "../common/app-logger.service"; +import { ExternalServiceError } from "../common/external/external-error"; export type DbClient = ReturnType; diff --git a/apps/backend/src/db/e2e-db.ts b/apps/backend/src/db/e2e-db.ts index 72fe9f4..72026f5 100644 --- a/apps/backend/src/db/e2e-db.ts +++ b/apps/backend/src/db/e2e-db.ts @@ -20,10 +20,10 @@ import { Pool } from "pg"; export type TestDbMode = "live" | "unreachable"; -export interface TestDb { +export type TestDb = { mode: TestDbMode; url: string; -} +}; /** Dead-port URL for 503-surface assertions (refused fast, no secrets). */ export const UNREACHABLE_TEST_DB_URL = diff --git a/apps/backend/src/docker-registry/docker-registry.config.ts b/apps/backend/src/docker-registry/docker-registry.config.ts index b5b58a4..241ccfa 100644 --- a/apps/backend/src/docker-registry/docker-registry.config.ts +++ b/apps/backend/src/docker-registry/docker-registry.config.ts @@ -1,17 +1,17 @@ -import type { AppEnv } from '../env.js'; +import type { AppEnv } from '../env'; /** * Typed docker-registry config (resolved from AppEnv, never read from * process.env directly). Mirrors the EXTERNAL_RETRY_* tuning shape so the * startup probe reuses the shared withRetry backoff+jitter policy. */ -export interface DockerRegistryRetryConfig { +export type DockerRegistryRetryConfig = { maxAttempts: number; baseDelayMs: number; maxDelayMs: number; -} +}; -export interface DockerRegistryConfig { +export type DockerRegistryConfig = { /** Base URL, no trailing slash; '' = unconfigured (health 'skipped'). */ url: string; /** Basic-auth username ('' when unset/token mode; never logged). */ @@ -23,7 +23,7 @@ export interface DockerRegistryConfig { /** Per-attempt budget ms for GET /v2/* calls. */ timeoutMs: number; retry: DockerRegistryRetryConfig; -} +}; export function resolveDockerRegistryConfig(env: AppEnv): DockerRegistryConfig { return { diff --git a/apps/backend/src/docker-registry/docker-registry.controller.ts b/apps/backend/src/docker-registry/docker-registry.controller.ts index 308a217..5266e99 100644 --- a/apps/backend/src/docker-registry/docker-registry.controller.ts +++ b/apps/backend/src/docker-registry/docker-registry.controller.ts @@ -1,9 +1,9 @@ import { Controller, Get, Headers, Version } from '@nestjs/common'; import { ApiResponse, ApiTags } from '@nestjs/swagger'; -import { V1Endpoint } from '../api/version.js'; -import { ApiErrorDto } from '../api/dto.js'; -import { DockerRegistryService } from './docker-registry.service.js'; -import { RegistryCatalogDto } from './dto.js'; +import { V1Endpoint } from '../api/version'; +import { ApiErrorDto } from '../api/dto'; +import { DockerRegistryService } from './docker-registry.service'; +import { RegistryCatalogDto } from './dto'; /** * Docker Registry HTTP API v2 — minimal read surface (GET only). diff --git a/apps/backend/src/docker-registry/docker-registry.e2e.ts b/apps/backend/src/docker-registry/docker-registry.e2e.ts index ead9cb4..5b72a03 100644 --- a/apps/backend/src/docker-registry/docker-registry.e2e.ts +++ b/apps/backend/src/docker-registry/docker-registry.e2e.ts @@ -60,8 +60,8 @@ function startStubRegistry(): Promise<{ server: Server; url: string }> { async function main(): Promise { const { NestFactory } = await import('@nestjs/core'); - const { AppModule } = await import('../app.module.js'); - const { configureApp } = await import('../app.setup.js'); + const { AppModule } = await import('../app.module'); + const { configureApp } = await import('../app.setup'); let passed = 0; let failed = 0; diff --git a/apps/backend/src/docker-registry/docker-registry.module.ts b/apps/backend/src/docker-registry/docker-registry.module.ts index a067279..7de540e 100644 --- a/apps/backend/src/docker-registry/docker-registry.module.ts +++ b/apps/backend/src/docker-registry/docker-registry.module.ts @@ -1,6 +1,6 @@ import { Global, Module } from '@nestjs/common'; -import { DockerRegistryService } from './docker-registry.service.js'; -import { DockerRegistryController } from './docker-registry.controller.js'; +import { DockerRegistryService } from './docker-registry.service'; +import { DockerRegistryController } from './docker-registry.controller'; /** * Global docker-registry module (mirrors OpencodeModule) — diff --git a/apps/backend/src/docker-registry/docker-registry.service.spec.ts b/apps/backend/src/docker-registry/docker-registry.service.spec.ts index 3502191..5c93981 100644 --- a/apps/backend/src/docker-registry/docker-registry.service.spec.ts +++ b/apps/backend/src/docker-registry/docker-registry.service.spec.ts @@ -13,17 +13,17 @@ * Also executes under `bun test dist` (top-level run, throws on failure). */ import assert from 'node:assert/strict'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ApiErrorFilter } from '../common/api-error.filter.js'; -import { ExternalClient } from '../common/external/external-client.js'; -import { ExternalServiceError } from '../common/external/external-error.js'; -import { computeBackoffDelay, withRetry } from '../common/external/retry.js'; +import { AppLogger } from '../common/app-logger.service'; +import { ApiErrorFilter } from '../common/api-error.filter'; +import { ExternalClient } from '../common/external/external-client'; +import { ExternalServiceError } from '../common/external/external-error'; +import { computeBackoffDelay, withRetry } from '../common/external/retry'; import { dockerRegistryAuthHeaders, resolveDockerRegistryConfig, -} from './docker-registry.config.js'; -import { DockerRegistryService } from './docker-registry.service.js'; -import { validateEnv } from '../env.js'; +} from './docker-registry.config'; +import { DockerRegistryService } from './docker-registry.service'; +import { validateEnv } from '../env'; const SECRET_TOKEN = 'super-secret-token-xyz-never-log'; const SECRET_PASS = 'super-secret-pass-xyz-never-log'; diff --git a/apps/backend/src/docker-registry/docker-registry.service.ts b/apps/backend/src/docker-registry/docker-registry.service.ts index 90d009d..4d49fe0 100644 --- a/apps/backend/src/docker-registry/docker-registry.service.ts +++ b/apps/backend/src/docker-registry/docker-registry.service.ts @@ -1,19 +1,19 @@ import { Injectable, OnModuleInit, Optional } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; -import { validateEnv, type AppEnv } from '../env.js'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ExternalClient } from '../common/external/external-client.js'; +import { validateEnv, type AppEnv } from '../env'; +import { AppLogger } from '../common/app-logger.service'; +import { ExternalClient } from '../common/external/external-client'; import { ExternalServiceError, fromStatus, fromUnknown, -} from '../common/external/external-error.js'; -import { withRetry } from '../common/external/retry.js'; +} from '../common/external/external-error'; +import { withRetry } from '../common/external/retry'; import { dockerRegistryAuthHeaders, resolveDockerRegistryConfig, type DockerRegistryConfig, -} from './docker-registry.config.js'; +} from './docker-registry.config'; export type DockerRegistryStatus = 'up' | 'down' | 'skipped'; diff --git a/apps/backend/src/env-failfast.spec.ts b/apps/backend/src/env-failfast.spec.ts index 8f8f728..bf3833f 100644 --- a/apps/backend/src/env-failfast.spec.ts +++ b/apps/backend/src/env-failfast.spec.ts @@ -20,8 +20,8 @@ * - PROJECTS_ROOT с NUL-байтом → throw (невалидный путь записи). */ import assert from 'node:assert/strict'; -import { validateEnv } from './env.js'; -import { WorkspacePathService } from './workspaces/workspace-path.service.js'; +import { validateEnv } from './env'; +import { WorkspacePathService } from './workspaces/workspace-path.service'; type Source = NodeJS.ProcessEnv; diff --git a/apps/backend/src/env.spec.ts b/apps/backend/src/env.spec.ts index 22fe6ff..5b64bf6 100644 --- a/apps/backend/src/env.spec.ts +++ b/apps/backend/src/env.spec.ts @@ -18,7 +18,7 @@ import { urlSchema, validateEnv, validateEnvWithWarnings, -} from './env.js'; +} from './env'; type Source = NodeJS.ProcessEnv; diff --git a/apps/backend/src/env.ts b/apps/backend/src/env.ts index 53201ed..35a794d 100644 --- a/apps/backend/src/env.ts +++ b/apps/backend/src/env.ts @@ -16,7 +16,7 @@ import { resolve as resolvePath, } from "node:path"; -export interface AppEnv { +export type AppEnv = { backendPort: number; backendHost: string; backendProtocol: "http" | "https"; @@ -160,7 +160,7 @@ export interface AppEnv { * intentionally unsupported (one server-wide policy, auditable). */ orgInviteTtlSec: number; -} +}; // --- zod@4 primitive schemas (Standard Schema compatible) -------------------- @@ -597,7 +597,7 @@ export function findSuspiciousUnknownKeys(source: NodeJS.ProcessEnv): string[] { return out.sort(); } -export interface EnvValidation { +export type EnvValidation = { env: AppEnv; /** * Non-fatal notices (`[env] WARN ...`, never fatal, never secret-bearing). @@ -605,7 +605,7 @@ export interface EnvValidation { * main.ts logs them once at boot via AppLogger. */ warnings: string[]; -} +}; export function validateEnvWithWarnings( source: NodeJS.ProcessEnv = process.env, diff --git a/apps/backend/src/health/health.controller.ts b/apps/backend/src/health/health.controller.ts index cd14875..c836661 100644 --- a/apps/backend/src/health/health.controller.ts +++ b/apps/backend/src/health/health.controller.ts @@ -1,17 +1,17 @@ import { Controller, Get, Optional, Version, VERSION_NEUTRAL } from '@nestjs/common'; import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; -import { DbService } from '../db/db.service.js'; -import { OpencodeService } from '../opencode/opencode.service.js'; +import { DbService } from '../db/db.service'; +import { OpencodeService } from '../opencode/opencode.service'; import { DockerRegistryService, type DockerRegistryStatus, -} from '../docker-registry/docker-registry.service.js'; +} from '../docker-registry/docker-registry.service'; import { NpmRegistryService, type NpmRegistryStatus, -} from '../npm-registry/npm-registry.service.js'; -import { HealthDto } from '../api/dto.js'; -import type { HealthResponse } from '../contracts.js'; +} from '../npm-registry/npm-registry.service'; +import { HealthDto } from '../api/dto'; +import type { HealthResponse } from '@devbox/contracts'; /** * Liveness probe — deliberately VERSION_NEUTRAL and excluded from the global diff --git a/apps/backend/src/health/health.module.ts b/apps/backend/src/health/health.module.ts index 066e343..facf7fe 100644 --- a/apps/backend/src/health/health.module.ts +++ b/apps/backend/src/health/health.module.ts @@ -1,9 +1,9 @@ import { Module } from '@nestjs/common'; -import { DbModule } from '../db/db.module.js'; -import { OpencodeModule } from '../opencode/opencode.module.js'; -import { DockerRegistryModule } from '../docker-registry/docker-registry.module.js'; -import { NpmRegistryModule } from '../npm-registry/npm-registry.module.js'; -import { HealthController } from './health.controller.js'; +import { DbModule } from '../db/db.module'; +import { OpencodeModule } from '../opencode/opencode.module'; +import { DockerRegistryModule } from '../docker-registry/docker-registry.module'; +import { NpmRegistryModule } from '../npm-registry/npm-registry.module'; +import { HealthController } from './health.controller'; @Module({ imports: [DbModule, OpencodeModule, DockerRegistryModule, NpmRegistryModule], diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts index cedfa19..1f69a57 100644 --- a/apps/backend/src/main.ts +++ b/apps/backend/src/main.ts @@ -8,10 +8,10 @@ expand(dotenvResult); import 'reflect-metadata'; import { NestFactory } from '@nestjs/core'; -import { AppModule } from './app.module.js'; -import { AppLogger, nestLogLevels } from './common/app-logger.service.js'; -import { configureApp, setupSwagger } from './app.setup.js'; -import { validateEnvWithWarnings } from './env.js'; +import { AppModule } from './app.module'; +import { AppLogger, nestLogLevels } from './common/app-logger.service'; +import { configureApp, setupSwagger } from './app.setup'; +import { validateEnvWithWarnings } from './env'; function isAbortLike(e: unknown): boolean { const v = e as { diff --git a/apps/backend/src/npm-registry/npm-registry.config.ts b/apps/backend/src/npm-registry/npm-registry.config.ts index c98273b..88deebb 100644 --- a/apps/backend/src/npm-registry/npm-registry.config.ts +++ b/apps/backend/src/npm-registry/npm-registry.config.ts @@ -1,17 +1,17 @@ -import type { AppEnv } from '../env.js'; +import type { AppEnv } from '../env'; /** * Typed npm-registry config (resolved from AppEnv, never read from * process.env directly). Mirrors the EXTERNAL_RETRY_* tuning shape so the * startup probe reuses the shared withRetry backoff+jitter policy. */ -export interface NpmRegistryRetryConfig { +export type NpmRegistryRetryConfig = { maxAttempts: number; baseDelayMs: number; maxDelayMs: number; -} +}; -export interface NpmRegistryConfig { +export type NpmRegistryConfig = { /** Base URL, no trailing slash; '' = unconfigured (health 'skipped'). */ url: string; /** Bearer token — wins over the basic pair when set (never logged). */ @@ -25,7 +25,7 @@ export interface NpmRegistryConfig { /** Per-attempt budget ms for GET /-/ping calls. */ timeoutMs: number; retry: NpmRegistryRetryConfig; -} +}; export function resolveNpmRegistryConfig(env: AppEnv): NpmRegistryConfig { return { diff --git a/apps/backend/src/npm-registry/npm-registry.controller.ts b/apps/backend/src/npm-registry/npm-registry.controller.ts index 484b3f8..9ae6d96 100644 --- a/apps/backend/src/npm-registry/npm-registry.controller.ts +++ b/apps/backend/src/npm-registry/npm-registry.controller.ts @@ -1,9 +1,9 @@ import { Controller, Get, Headers, Version } from '@nestjs/common'; import { ApiResponse, ApiTags } from '@nestjs/swagger'; -import { V1Endpoint } from '../api/version.js'; -import { ApiErrorDto } from '../api/dto.js'; -import { NpmRegistryService } from './npm-registry.service.js'; -import { NpmRegistryStatusDto } from './dto.js'; +import { V1Endpoint } from '../api/version'; +import { ApiErrorDto } from '../api/dto'; +import { NpmRegistryService } from './npm-registry.service'; +import { NpmRegistryStatusDto } from './dto'; /** * npm registry (Verdaccio) — observe-only read surface (GET only). diff --git a/apps/backend/src/npm-registry/npm-registry.e2e.ts b/apps/backend/src/npm-registry/npm-registry.e2e.ts index c56ca5c..c20c827 100644 --- a/apps/backend/src/npm-registry/npm-registry.e2e.ts +++ b/apps/backend/src/npm-registry/npm-registry.e2e.ts @@ -59,12 +59,12 @@ function secretsLeaked(payload: unknown): boolean { ); } -interface StubOptions { +type StubOptions = { /** Fixed status for /-/ping (used for the 401/403 phases). */ pingStatus?: number; /** When set, /-/ping answers 200 only with this exact Authorization value, else 401. */ expectAuth?: string; -} +}; function startStubVerdaccio(options: StubOptions = {}): Promise<{ server: Server; url: string }> { const { pingStatus, expectAuth } = options; @@ -101,8 +101,8 @@ function startStubVerdaccio(options: StubOptions = {}): Promise<{ server: Server async function main(): Promise { const { NestFactory } = await import('@nestjs/core'); - const { AppModule } = await import('../app.module.js'); - const { configureApp } = await import('../app.setup.js'); + const { AppModule } = await import('../app.module'); + const { configureApp } = await import('../app.setup'); let passed = 0; let failed = 0; diff --git a/apps/backend/src/npm-registry/npm-registry.module.ts b/apps/backend/src/npm-registry/npm-registry.module.ts index c91a2b9..9f9333e 100644 --- a/apps/backend/src/npm-registry/npm-registry.module.ts +++ b/apps/backend/src/npm-registry/npm-registry.module.ts @@ -1,6 +1,6 @@ import { Global, Module } from '@nestjs/common'; -import { NpmRegistryService } from './npm-registry.service.js'; -import { NpmRegistryController } from './npm-registry.controller.js'; +import { NpmRegistryService } from './npm-registry.service'; +import { NpmRegistryController } from './npm-registry.controller'; /** * Global npm-registry module (mirrors DockerRegistryModule/OpencodeModule) — diff --git a/apps/backend/src/npm-registry/npm-registry.service.spec.ts b/apps/backend/src/npm-registry/npm-registry.service.spec.ts index b37efbb..475a0ac 100644 --- a/apps/backend/src/npm-registry/npm-registry.service.spec.ts +++ b/apps/backend/src/npm-registry/npm-registry.service.spec.ts @@ -18,19 +18,19 @@ */ import assert from 'node:assert/strict'; import { createServer, type Server } from 'node:http'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ApiErrorFilter } from '../common/api-error.filter.js'; -import { ExternalClient } from '../common/external/external-client.js'; -import { ExternalServiceError } from '../common/external/external-error.js'; -import { computeBackoffDelay, withRetry } from '../common/external/retry.js'; +import { AppLogger } from '../common/app-logger.service'; +import { ApiErrorFilter } from '../common/api-error.filter'; +import { ExternalClient } from '../common/external/external-client'; +import { ExternalServiceError } from '../common/external/external-error'; +import { computeBackoffDelay, withRetry } from '../common/external/retry'; import { hasNpmBasicPair, npmRegistryAuthHeaders, npmRegistryAuthMode, resolveNpmRegistryConfig, -} from './npm-registry.config.js'; -import { NpmRegistryService } from './npm-registry.service.js'; -import { validateEnv } from '../env.js'; +} from './npm-registry.config'; +import { NpmRegistryService } from './npm-registry.service'; +import { validateEnv } from '../env'; const SECRET_TOKEN = 'super-secret-npm-token-xyz-never-log'; const SECRET_USER = 'super-secret-npm-user-never-log'; diff --git a/apps/backend/src/npm-registry/npm-registry.service.ts b/apps/backend/src/npm-registry/npm-registry.service.ts index 33dd0e6..bb0d7f7 100644 --- a/apps/backend/src/npm-registry/npm-registry.service.ts +++ b/apps/backend/src/npm-registry/npm-registry.service.ts @@ -4,21 +4,21 @@ import { DEFAULT_NPM_REGISTRY_SCOPE, validateEnv, type AppEnv, -} from '../env.js'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ExternalClient } from '../common/external/external-client.js'; +} from '../env'; +import { AppLogger } from '../common/app-logger.service'; +import { ExternalClient } from '../common/external/external-client'; import { ExternalServiceError, fromStatus, fromUnknown, -} from '../common/external/external-error.js'; -import { withRetry } from '../common/external/retry.js'; +} from '../common/external/external-error'; +import { withRetry } from '../common/external/retry'; import { npmRegistryAuthHeaders, npmRegistryAuthMode, resolveNpmRegistryConfig, type NpmRegistryConfig, -} from './npm-registry.config.js'; +} from './npm-registry.config'; export type NpmRegistryStatus = 'up' | 'down' | 'skipped'; diff --git a/apps/backend/src/opencode-keys/crypto.service.hardening.spec.ts b/apps/backend/src/opencode-keys/crypto.service.hardening.spec.ts index fe99293..3f7667a 100644 --- a/apps/backend/src/opencode-keys/crypto.service.hardening.spec.ts +++ b/apps/backend/src/opencode-keys/crypto.service.hardening.spec.ts @@ -94,9 +94,9 @@ async function main(): Promise { const saved = saveEnv(); setKeyring(ACTIVE_A); - const { CryptoService } = await import("./crypto.service.js"); - const { OpencodeBillingService } = await import("./opencode-billing.service.js"); - const { AppLogger } = await import("../common/app-logger.service.js"); + const { CryptoService } = await import("./crypto.service"); + const { OpencodeBillingService } = await import("./opencode-billing.service"); + const { AppLogger } = await import("../common/app-logger.service"); let passed = 0; const check = async (name: string, fn: () => void | Promise): Promise => { diff --git a/apps/backend/src/opencode-keys/crypto.service.spec.ts b/apps/backend/src/opencode-keys/crypto.service.spec.ts index 6500863..1214e54 100644 --- a/apps/backend/src/opencode-keys/crypto.service.spec.ts +++ b/apps/backend/src/opencode-keys/crypto.service.spec.ts @@ -29,7 +29,7 @@ function setKeyring(active: string, previous?: string): void { async function main(): Promise { setKeyring(KEY_A); - const { CryptoService } = await import("./crypto.service.js"); + const { CryptoService } = await import("./crypto.service"); const codeOf = (fn: () => unknown): string => { try { diff --git a/apps/backend/src/opencode-keys/crypto.service.ts b/apps/backend/src/opencode-keys/crypto.service.ts index f818fc9..9ee269d 100644 --- a/apps/backend/src/opencode-keys/crypto.service.ts +++ b/apps/backend/src/opencode-keys/crypto.service.ts @@ -1,12 +1,12 @@ import { Injectable, InternalServerErrorException } from "@nestjs/common"; import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto"; -import { AppLogger } from "../common/app-logger.service.js"; +import { AppLogger } from "../common/app-logger.service"; import { DEFAULT_OPENCODE_KEYS_ACTIVE_KEY_ID, DEFAULT_OPENCODE_KEYS_PREVIOUS_KEY_ID, MIN_OPENCODE_KEYS_ENCRYPTION_KEY_LENGTH, OPENCODE_KEYS_KEY_ID_PATTERN, -} from "../env.js"; +} from "../env"; /** AES-256-GCM params: 12-byte IV, 16-byte auth tag (both base64 at rest). */ const IV_BYTES = 12; @@ -20,34 +20,34 @@ const TAG_BYTES = 16; * id (`undefined`/empty) and decrypt via the dual-read fallback. * - `iv` is base64(12-byte random IV), `data` is base64(ciphertext || tag). */ -export interface EncryptedOpencodeKey { +export type EncryptedOpencodeKey = { /** KEK version id (e.g. "v1"); never a secret, stored in plaintext. */ keyId: string; /** base64(12-byte random IV) */ iv: string; /** base64(ciphertext || 16-byte auth tag) */ data: string; -} +}; /** Decrypt input — `keyId` is optional so pre-versioning rows stay readable. */ -export interface EncryptedOpencodeKeyInput { +export type EncryptedOpencodeKeyInput = { /** KEK version id, or missing/empty for legacy rows. */ keyId?: string | null; /** base64(12-byte random IV) */ iv: string; /** base64(ciphertext || 16-byte auth tag) */ data: string; -} +}; -interface KeyEntry { +type KeyEntry = { id: string; key: Buffer; -} +}; -interface Keyring { +type Keyring = { active: KeyEntry; previous?: KeyEntry; -} +}; function unconfigured(): InternalServerErrorException { return new InternalServerErrorException({ diff --git a/apps/backend/src/opencode-keys/dto.ts b/apps/backend/src/opencode-keys/dto.ts index 0f4bd85..8e0f2f6 100644 --- a/apps/backend/src/opencode-keys/dto.ts +++ b/apps/backend/src/opencode-keys/dto.ts @@ -1,17 +1,8 @@ -import { z } from "zod"; - /** - * PUT /api/v1/key — the caller's own OpenCode API key. - * Min 20 chars (real keys are long opaque tokens; short strings are almost - * certainly a paste mistake), max 1024, trimmed. The value is encrypted with - * CryptoService before storage and is never returned or logged. + * PUT /api/v1/key — single source of truth is @devbox/contracts + * (verbatim trim/min/max + error strings: short strings are almost + * certainly a paste mistake, so min 20 fails fast). Controllers keep + * importing from './dto' — the runtime object is the package schema. + * Swagger DTOs live in ./opencode-keys.dto.ts. */ -export const opencodeKeySchema = z.object({ - apiKey: z - .string() - .trim() - .min(20, { error: "must be at least 20 characters" }) - .max(1024, { error: "must be ≤ 1024 chars" }), -}); - -export type OpencodeKeyInput = z.infer; +export { opencodeKeySchema, type OpencodeKeyInput } from '@devbox/contracts'; diff --git a/apps/backend/src/opencode-keys/opencode-billing.service.ts b/apps/backend/src/opencode-keys/opencode-billing.service.ts index 27f3575..df7332c 100644 --- a/apps/backend/src/opencode-keys/opencode-billing.service.ts +++ b/apps/backend/src/opencode-keys/opencode-billing.service.ts @@ -1,21 +1,21 @@ import { HttpException, Injectable, NotFoundException, UnauthorizedException } from "@nestjs/common"; -import { AppLogger } from "../common/app-logger.service.js"; -import { ExternalClient } from "../common/external/external-client.js"; +import { AppLogger } from "../common/app-logger.service"; +import { ExternalClient } from "../common/external/external-client"; import { ExternalServiceError, fromStatus, fromUnknown, -} from "../common/external/external-error.js"; -import { CryptoService } from "./crypto.service.js"; -import { OpencodeKeysService } from "./opencode-keys.service.js"; +} from "../common/external/external-error"; +import { CryptoService } from "./crypto.service"; +import { OpencodeKeysService } from "./opencode-keys.service"; /** GET /api/v1/usage response (Zen Go contract + legacy backward-compat). */ -export interface OpencodeLimitBucket { +export type OpencodeLimitBucket = { used: number; limit: number; -} +}; -export interface OpencodeUsage { +export type OpencodeUsage = { /** Legacy pay-as-you-go fields — present only for legacy upstream payloads. */ balance?: number; /** Legacy pay-as-you-go total — present only for legacy upstream payloads. */ @@ -35,7 +35,7 @@ export interface OpencodeUsage { daily?: OpencodeLimitBucket; weekly?: OpencodeLimitBucket; monthly?: OpencodeLimitBucket; -} +}; function isFiniteNumber(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value); diff --git a/apps/backend/src/opencode-keys/opencode-keys.controller.ts b/apps/backend/src/opencode-keys/opencode-keys.controller.ts index 3c4f017..5e9df0e 100644 --- a/apps/backend/src/opencode-keys/opencode-keys.controller.ts +++ b/apps/backend/src/opencode-keys/opencode-keys.controller.ts @@ -11,23 +11,23 @@ import { Version, } from "@nestjs/common"; import { ApiBearerAuth, ApiResponse, ApiTags } from "@nestjs/swagger"; -import { V1Endpoint } from "../api/version.js"; -import { JwtAuthGuard } from "../auth/jwt-auth.guard.js"; -import type { RequestIdentity } from "../auth/identity.service.js"; -import { ReqUser } from "../auth/req-user.decorator.js"; -import { AppLogger } from "../common/app-logger.service.js"; -import { ZodValidationPipe } from "../common/zod-validation.pipe.js"; -import { CryptoService } from "./crypto.service.js"; -import { opencodeKeySchema, type OpencodeKeyInput } from "./dto.js"; -import { OpencodeBillingService } from "./opencode-billing.service.js"; +import { V1Endpoint } from "../api/version"; +import { JwtAuthGuard } from "../auth/jwt-auth.guard"; +import type { RequestIdentity } from "../auth/identity.service"; +import { ReqUser } from "../auth/req-user.decorator"; +import { AppLogger } from "../common/app-logger.service"; +import { ZodValidationPipe } from "../common/zod-validation.pipe"; +import { CryptoService } from "./crypto.service"; +import { opencodeKeySchema, type OpencodeKeyInput } from "./dto"; +import { OpencodeBillingService } from "./opencode-billing.service"; import { OpencodeKeyBodyDto, OpencodeKeyDeleteResultDto, OpencodeKeyResultDto, OpencodeKeyStatusDto, OpencodeUsageDto, -} from "./opencode-keys.dto.js"; -import { OpencodeKeysService } from "./opencode-keys.service.js"; +} from "./opencode-keys.dto"; +import { OpencodeKeysService } from "./opencode-keys.service"; function isUserId(value: string): boolean { return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value); diff --git a/apps/backend/src/opencode-keys/opencode-keys.e2e.ts b/apps/backend/src/opencode-keys/opencode-keys.e2e.ts index f1c62c1..16390e0 100644 --- a/apps/backend/src/opencode-keys/opencode-keys.e2e.ts +++ b/apps/backend/src/opencode-keys/opencode-keys.e2e.ts @@ -99,7 +99,7 @@ async function main(): Promise { let billingTarget = `http://127.0.0.1:${billingPort}/usage`; const { resolveTestDb, applyTestMigrations } = - await import("../db/e2e-db.js"); + await import("../db/e2e-db"); const testDb = await resolveTestDb( process.env.TEST_DATABASE_URL ?? process.env.DATABASE_URL ?? "", ); @@ -118,8 +118,8 @@ async function main(): Promise { console.log(`[opencode-keys e2e] db mode: ${testDb.mode}`); const { NestFactory } = await import("@nestjs/core"); - const { AppModule } = await import("../app.module.js"); - const { configureApp } = await import("../app.setup.js"); + const { AppModule } = await import("../app.module"); + const { configureApp } = await import("../app.setup"); let passed = 0; let failed = 0; @@ -146,8 +146,8 @@ async function main(): Promise { const app = await NestFactory.create(AppModule, { logger: false }); configureApp(app); if (testDb.mode === "live") { - const { UsersService } = await import("../auth/users.service.js"); - const { TokenService } = await import("../auth/token.service.js"); + const { UsersService } = await import("../auth/users.service"); + const { TokenService } = await import("../auth/token.service"); const users = app.get(UsersService, { strict: false }) as { clearAllForTests: () => Promise; }; @@ -163,7 +163,7 @@ async function main(): Promise { // Reroute the hard-coded billing constant to the mock above through the // live ExternalClient (keeps timeout/retry mapping identical to prod). const { OPENCODE_BILLING_URL, OpencodeBillingService } = await import( - "./opencode-billing.service.js" + "./opencode-billing.service" ); const billingSvc = app.get(OpencodeBillingService, { strict: false }) as unknown as { external: { @@ -188,7 +188,7 @@ async function main(): Promise { // Captures { method, args } so the final scans can prove both never-log // secrets AND normal-path shape: warn/error are one-liners with // operation/status/code and no stack (`\n at ` only ever appears on debug). - const { AppLogger } = await import("../common/app-logger.service.js"); + const { AppLogger } = await import("../common/app-logger.service"); const captured: Array<{ method: string; args: unknown[] }> = []; const methods = ["debug", "info", "warn", "error"] as const; const originals = methods.map((m) => AppLogger.prototype[m]); @@ -344,7 +344,7 @@ async function main(): Promise { assert.ok(!row.iv.includes(TEST_API_KEY)); // KEK version envelope: fresh rows are wrapped with the active id. assert.equal(row.key_id, "v1"); - const { CryptoService } = await import("./crypto.service.js"); + const { CryptoService } = await import("./crypto.service"); const svc = new CryptoService(); assert.equal( svc.decrypt({ keyId: row.key_id, iv: row.iv, data: row.encrypted_key }), @@ -461,7 +461,7 @@ async function main(): Promise { ); const row = rows[0] as { encrypted_key: string; iv: string; key_id: string }; assert.equal(row.key_id, "v1"); - const { CryptoService } = await import("./crypto.service.js"); + const { CryptoService } = await import("./crypto.service"); const svc = new CryptoService(); assert.equal( svc.decrypt({ keyId: row.key_id, iv: row.iv, data: row.encrypted_key }), diff --git a/apps/backend/src/opencode-keys/opencode-keys.module.ts b/apps/backend/src/opencode-keys/opencode-keys.module.ts index 3e05a1b..f320f02 100644 --- a/apps/backend/src/opencode-keys/opencode-keys.module.ts +++ b/apps/backend/src/opencode-keys/opencode-keys.module.ts @@ -1,9 +1,9 @@ import { Module } from "@nestjs/common"; -import { DbModule } from "../db/db.module.js"; -import { CryptoService } from "./crypto.service.js"; -import { OpencodeBillingService } from "./opencode-billing.service.js"; -import { OpencodeKeysController } from "./opencode-keys.controller.js"; -import { OpencodeKeysService } from "./opencode-keys.service.js"; +import { DbModule } from "../db/db.module"; +import { CryptoService } from "./crypto.service"; +import { OpencodeBillingService } from "./opencode-billing.service"; +import { OpencodeKeysController } from "./opencode-keys.controller"; +import { OpencodeKeysService } from "./opencode-keys.service"; /** * OpencodeKeysModule — per-user OpenCode API keys (encrypted at rest) + diff --git a/apps/backend/src/opencode-keys/opencode-keys.service.ts b/apps/backend/src/opencode-keys/opencode-keys.service.ts index 8f03329..9fc45f7 100644 --- a/apps/backend/src/opencode-keys/opencode-keys.service.ts +++ b/apps/backend/src/opencode-keys/opencode-keys.service.ts @@ -1,21 +1,21 @@ import { Injectable } from "@nestjs/common"; import { eq, ne } from "drizzle-orm"; -import { AppLogger } from "../common/app-logger.service.js"; -import { DbService, dbUnavailable, type DbClient } from "../db/db.service.js"; -import { userOpencodeKeys, type UserOpencodeKeyRow } from "../db/schema.js"; +import { AppLogger } from "../common/app-logger.service"; +import { DbService, dbUnavailable, type DbClient } from "../db/db.service"; +import { userOpencodeKeys, type UserOpencodeKeyRow } from "../db/schema"; /** * Stored per-user key row (ciphertext only — plaintext never persisted). * `keyId` names the wrapping KEK version ('' = legacy pre-versioning row). */ -export interface StoredOpencodeKey { +export type StoredOpencodeKey = { userId: string; encryptedKey: string; iv: string; keyId: string; /** ISO-8601 timestamp */ updatedAt: string; -} +}; function toStored(row: UserOpencodeKeyRow): StoredOpencodeKey { return { diff --git a/apps/backend/src/opencode-keys/reencrypt-keys.ts b/apps/backend/src/opencode-keys/reencrypt-keys.ts index 3778d51..e74d093 100644 --- a/apps/backend/src/opencode-keys/reencrypt-keys.ts +++ b/apps/backend/src/opencode-keys/reencrypt-keys.ts @@ -22,9 +22,9 @@ */ async function main(): Promise { const { NestFactory } = await import("@nestjs/core"); - const { AppModule } = await import("../app.module.js"); - const { CryptoService } = await import("./crypto.service.js"); - const { OpencodeKeysService } = await import("./opencode-keys.service.js"); + const { AppModule } = await import("../app.module"); + const { CryptoService } = await import("./crypto.service"); + const { OpencodeKeysService } = await import("./opencode-keys.service"); const app = await NestFactory.createApplicationContext(AppModule, { logger: false, @@ -40,7 +40,7 @@ async function main(): Promise { const code = (err as { getResponse?: () => { code?: string } }).getResponse?.()?.code ?? "opencode_keys_unconfigured"; - console.error(`keys:reencrypt refused: ${code} (storage unconfigured)`); + process.stderr.write(`keys:reencrypt refused: ${code} (storage unconfigured)\n`); process.exitCode = 1; return; } @@ -85,13 +85,13 @@ async function main(): Promise { } if (!progressed || stale.length < PAGE) break; } - console.log( - `keys:reencrypt done: ${JSON.stringify({ scanned, reencrypted, unreadable, activeKeyId })}`, + process.stdout.write( + `keys:reencrypt done: ${JSON.stringify({ scanned, reencrypted, unreadable, activeKeyId })}\n`, ); if (unreadable > 0) { - console.error( + process.stderr.write( `keys:reencrypt: ${unreadable} row(s) unreadable with the configured KEKs — ` + - "restore the wrapping KEK as OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS and rerun", + "restore the wrapping KEK as OPENCODE_KEYS_ENCRYPTION_KEY_PREVIOUS and rerun\n", ); process.exitCode = 1; } @@ -101,6 +101,6 @@ async function main(): Promise { } void main().catch((err: unknown) => { - console.error(`keys:reencrypt failed to run: ${(err as Error).message}`); + process.stderr.write(`keys:reencrypt failed to run: ${(err as Error).message}\n`); process.exitCode = 1; }); diff --git a/apps/backend/src/opencode/opencode-client.ts b/apps/backend/src/opencode/opencode-client.ts index b1d829e..943d2e9 100644 --- a/apps/backend/src/opencode/opencode-client.ts +++ b/apps/backend/src/opencode/opencode-client.ts @@ -5,10 +5,10 @@ import { Injectable } from '@nestjs/common'; // node 22+, and survives the CJS build thanks to `module.ignoreDynamic` // in `.swcrc`). Never add a value import here or dist/* breaks at boot. import type { OpencodeClient } from '@opencode-ai/sdk'; -import { OpencodeService } from './opencode.service.js'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ExternalClient } from '../common/external/external-client.js'; -import { validateEnv } from '../env.js'; +import { OpencodeService } from './opencode.service'; +import { AppLogger } from '../common/app-logger.service'; +import { ExternalClient } from '../common/external/external-client'; +import { validateEnv } from '../env'; type SdkModule = typeof import('@opencode-ai/sdk'); diff --git a/apps/backend/src/opencode/opencode.controller.ts b/apps/backend/src/opencode/opencode.controller.ts index 9266fe0..0d2b715 100644 --- a/apps/backend/src/opencode/opencode.controller.ts +++ b/apps/backend/src/opencode/opencode.controller.ts @@ -30,10 +30,10 @@ import type { SessionShellData, SessionUpdateData, } from '@opencode-ai/sdk'; -import { OpencodeSdkClient } from './opencode-client.js'; -import { OpencodeService } from './opencode.service.js'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ZodValidationPipe } from '../common/zod-validation.pipe.js'; +import { OpencodeSdkClient } from './opencode-client'; +import { OpencodeService } from './opencode.service'; +import { AppLogger } from '../common/app-logger.service'; +import { ZodValidationPipe } from '../common/zod-validation.pipe'; import { ApiErrorDto, opencodeCommandSchema, @@ -46,8 +46,8 @@ import { type OpencodePromptInput, type OpencodeSessionUpdateInput, type OpencodeShellInput, -} from '../api/dto.js'; -import { fromUnknown } from '../common/external/external-error.js'; +} from '../api/dto'; +import { fromUnknown } from '../common/external/external-error'; /** Upstream cursor headers passed through on GET message lists (when present). */ const CURSOR_PASSTHROUGH_HEADERS = ['x-next-cursor', 'link'] as const; diff --git a/apps/backend/src/opencode/opencode.e2e.ts b/apps/backend/src/opencode/opencode.e2e.ts index 96d8e11..75557e2 100644 --- a/apps/backend/src/opencode/opencode.e2e.ts +++ b/apps/backend/src/opencode/opencode.e2e.ts @@ -41,16 +41,16 @@ for (const key of ['POSTGRES_USER', 'POSTGRES_PASSWORD', 'POSTGRES_DB', 'POSTGRE delete process.env[key]; } -interface CheckResult { +type CheckResult = { name: string; ok: boolean; detail?: string; -} +}; async function main(): Promise { const { NestFactory } = await import('@nestjs/core'); - const { AppModule } = await import('../app.module.js'); - const { configureApp, setupSwagger } = await import('../app.setup.js'); + const { AppModule } = await import('../app.module'); + const { configureApp, setupSwagger } = await import('../app.setup'); const app = await NestFactory.create(AppModule, { logger: false }); configureApp(app); diff --git a/apps/backend/src/opencode/opencode.module.ts b/apps/backend/src/opencode/opencode.module.ts index 31a4434..f72303a 100644 --- a/apps/backend/src/opencode/opencode.module.ts +++ b/apps/backend/src/opencode/opencode.module.ts @@ -1,7 +1,7 @@ import { Global, Module } from '@nestjs/common'; -import { OpencodeService } from './opencode.service.js'; -import { OpencodeSdkClient } from './opencode-client.js'; -import { OpencodeController } from './opencode.controller.js'; +import { OpencodeService } from './opencode.service'; +import { OpencodeSdkClient } from './opencode-client'; +import { OpencodeController } from './opencode.controller'; /** * Global opencode module (mirrors CommonModule) — OpencodeService is diff --git a/apps/backend/src/opencode/opencode.service.ts b/apps/backend/src/opencode/opencode.service.ts index d4dc6d2..15982e0 100644 --- a/apps/backend/src/opencode/opencode.service.ts +++ b/apps/backend/src/opencode/opencode.service.ts @@ -1,8 +1,8 @@ import { Injectable, Optional } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; -import { validateEnv } from '../env.js'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ExternalClient } from '../common/external/external-client.js'; +import { validateEnv } from '../env'; +import { AppLogger } from '../common/app-logger.service'; +import { ExternalClient } from '../common/external/external-client'; export type OpencodeStatus = 'up' | 'down'; diff --git a/apps/backend/src/organizations/dto.ts b/apps/backend/src/organizations/dto.ts index 10a288b..8778df9 100644 --- a/apps/backend/src/organizations/dto.ts +++ b/apps/backend/src/organizations/dto.ts @@ -1,53 +1,28 @@ import { ApiProperty } from '@nestjs/swagger'; -import { z } from 'zod'; /** - * Organizations DTO — zod@4 source of truth, swagger DTOs for parity - * with contracts/openapi.yaml. Runtime validation via ZodValidationPipe. + * Organizations DTO — single source of truth is @devbox/contracts + * (verbatim min/max, uuid shapes, defaults + error strings). Swagger DTO + * classes below stay as thin @nestjs/swagger wrappers for + * contracts/openapi.yaml parity. Runtime validation via ZodValidationPipe. * All contracts here are NEW (additive): no existing schema is modified. */ - -export const orgRoleSchema = z.enum(['maintainer', 'user'], { - error: 'role must be maintainer or user', -}); - -export type OrgRole = z.infer; - -export const createOrganizationSchema = z.object({ - name: z.string({ error: 'Field "name" is required' }).min(1).max(200), - description: z.string().max(2000).optional(), - isPrivate: z.boolean().optional().default(true), -}); - -export const updateOrganizationSchema = z.object({ - name: z.string().min(1).max(200).optional(), - description: z.string().max(2000).nullable().optional(), - isPrivate: z.boolean().optional(), -}); - -export const addMemberSchema = z.object({ - userId: z.string({ error: 'Field "userId" is required' }).uuid({ error: 'userId must be a uuid' }), - role: orgRoleSchema.optional().default('user'), -}); - -export const updateMemberRoleSchema = z.object({ - role: orgRoleSchema, -}); - -export const createInviteSchema = z.object({ - role: orgRoleSchema.optional().default('user'), -}); - -export const acceptInviteSchema = z.object({ - token: z.string({ error: 'Field "token" is required' }).min(1).max(500), -}); - -export type CreateOrganizationInput = z.infer; -export type UpdateOrganizationInput = z.infer; -export type AddMemberInput = z.infer; -export type UpdateMemberRoleInput = z.infer; -export type CreateInviteInput = z.infer; -export type AcceptInviteInput = z.infer; +export { + acceptInviteSchema, + addMemberSchema, + createInviteSchema, + createOrganizationSchema, + orgRoleSchema, + updateMemberRoleSchema, + updateOrganizationSchema, + type AcceptInviteInput, + type AddMemberInput, + type CreateInviteInput, + type CreateOrganizationInput, + type OrgRole, + type UpdateMemberRoleInput, + type UpdateOrganizationInput, +} from '@devbox/contracts'; export class CreateOrganizationDto { @ApiProperty({ example: 'acme' }) diff --git a/apps/backend/src/organizations/organizations.controller.ts b/apps/backend/src/organizations/organizations.controller.ts index 9d65d0b..c41ab4a 100644 --- a/apps/backend/src/organizations/organizations.controller.ts +++ b/apps/backend/src/organizations/organizations.controller.ts @@ -14,12 +14,12 @@ import { Version, } from "@nestjs/common"; import { ApiBearerAuth, ApiResponse, ApiTags } from "@nestjs/swagger"; -import { JwtAuthGuard } from "../auth/jwt-auth.guard.js"; -import { ReqUser } from "../auth/req-user.decorator.js"; -import type { RequestIdentity } from "../auth/identity.service.js"; -import { NoIndexInterceptor } from "../common/noindex.interceptor.js"; -import { ZodValidationPipe } from "../common/zod-validation.pipe.js"; -import { V1Endpoint } from "../api/version.js"; +import { JwtAuthGuard } from "../auth/jwt-auth.guard"; +import { ReqUser } from "../auth/req-user.decorator"; +import type { RequestIdentity } from "../auth/identity.service"; +import { NoIndexInterceptor } from "../common/noindex.interceptor"; +import { ZodValidationPipe } from "../common/zod-validation.pipe"; +import { V1Endpoint } from "../api/version"; import { OrganizationDto, OrganizationInviteDto, @@ -36,8 +36,8 @@ import { type CreateOrganizationInput, type UpdateMemberRoleInput, type UpdateOrganizationInput, -} from "./dto.js"; -import { OrganizationsService } from "./organizations.service.js"; +} from "./dto"; +import { OrganizationsService } from "./organizations.service"; /** * Organizations CRUD + membership + single-use invites + project links. diff --git a/apps/backend/src/organizations/organizations.e2e.ts b/apps/backend/src/organizations/organizations.e2e.ts index 1c052b1..45e7b8f 100644 --- a/apps/backend/src/organizations/organizations.e2e.ts +++ b/apps/backend/src/organizations/organizations.e2e.ts @@ -33,7 +33,7 @@ process.env.ORG_INVITE_TTL_SEC = "86400"; async function main(): Promise { const { resolveTestDb, applyTestMigrations } = - await import("../db/e2e-db.js"); + await import("../db/e2e-db"); const testDb = await resolveTestDb( process.env.TEST_DATABASE_URL ?? process.env.DATABASE_URL ?? "", ); @@ -60,8 +60,8 @@ async function main(): Promise { console.log(`[organizations e2e] REPOS_ROOT: ${reposRoot}`); const { NestFactory } = await import("@nestjs/core"); - const { AppModule } = await import("../app.module.js"); - const { configureApp } = await import("../app.setup.js"); + const { AppModule } = await import("../app.module"); + const { configureApp } = await import("../app.setup"); const app = await NestFactory.create(AppModule, { logger: false }); configureApp(app); @@ -104,7 +104,7 @@ async function main(): Promise { // A hand-signed access token (TokenService.sign is pure, no DB) gets // past JwtAuthGuard so the 503 below proves the SERVICE denies with // EXTERNAL_UNAVAILABLE — not the guard with 401. - const { TokenService } = await import("../auth/token.service.js"); + const { TokenService } = await import("../auth/token.service"); const tokens = app.get(TokenService, { strict: false }) as { sign: ( claims: Record, @@ -184,10 +184,10 @@ async function main(): Promise { }); } else { // Live PG — full suite (tables migrated + cleared above). - const { OrganizationsService } = await import("./organizations.service.js"); - const { ProjectsService } = await import("../projects/projects.service.js"); - const { UsersService } = await import("../auth/users.service.js"); - const { TokenService } = await import("../auth/token.service.js"); + const { OrganizationsService } = await import("./organizations.service"); + const { ProjectsService } = await import("../projects/projects.service"); + const { UsersService } = await import("../auth/users.service"); + const { TokenService } = await import("../auth/token.service"); const orgs = app.get(OrganizationsService, { strict: false }) as { clearAllForTests: () => Promise; }; diff --git a/apps/backend/src/organizations/organizations.module.ts b/apps/backend/src/organizations/organizations.module.ts index 45b7a7e..e2d4eb8 100644 --- a/apps/backend/src/organizations/organizations.module.ts +++ b/apps/backend/src/organizations/organizations.module.ts @@ -1,8 +1,8 @@ import { Module } from "@nestjs/common"; -import { DbModule } from "../db/db.module.js"; -import { WorkspacePathService } from "../workspaces/workspace-path.service.js"; -import { OrganizationsController } from "./organizations.controller.js"; -import { OrganizationsService } from "./organizations.service.js"; +import { DbModule } from "../db/db.module"; +import { WorkspacePathService } from "../workspaces/workspace-path.service"; +import { OrganizationsController } from "./organizations.controller"; +import { OrganizationsService } from "./organizations.service"; /** * OrganizationsModule — org CRUD + membership + invites + project links. diff --git a/apps/backend/src/organizations/organizations.service.spec.ts b/apps/backend/src/organizations/organizations.service.spec.ts index 5d6823e..4b0fd3c 100644 --- a/apps/backend/src/organizations/organizations.service.spec.ts +++ b/apps/backend/src/organizations/organizations.service.spec.ts @@ -20,8 +20,8 @@ */ import assert from 'node:assert/strict'; import { GoneException, NotFoundException } from '@nestjs/common'; -import { DEFAULT_ORG_INVITE_TTL_SEC, validateEnvWithWarnings } from '../env.js'; -import { OrganizationsService } from './organizations.service.js'; +import { DEFAULT_ORG_INVITE_TTL_SEC, validateEnvWithWarnings } from '../env'; +import { OrganizationsService } from './organizations.service'; const SPEC_USER = '123e4567-e89b-12d3-a456-426614174001'; const SPEC_ORG = '123e4567-e89b-12d3-a456-426614174005'; diff --git a/apps/backend/src/organizations/organizations.service.ts b/apps/backend/src/organizations/organizations.service.ts index 7f7f9b7..d32370a 100644 --- a/apps/backend/src/organizations/organizations.service.ts +++ b/apps/backend/src/organizations/organizations.service.ts @@ -10,18 +10,18 @@ import { import { and, eq } from "drizzle-orm"; import { randomBytes } from "node:crypto"; import { rm } from "node:fs/promises"; -import { AppLogger } from "../common/app-logger.service.js"; -import { DbService, dbUnavailable, type DbClient } from "../db/db.service.js"; +import { AppLogger } from "../common/app-logger.service"; +import { DbService, dbUnavailable, type DbClient } from "../db/db.service"; import { organizationMembers, organizations, projectsAndOrganizations, type OrganizationMemberRow, type OrganizationRow, -} from "../db/schema.js"; -import { validateEnv } from "../env.js"; -import { UsersService } from "../auth/users.service.js"; -import { WorkspacePathService } from "../workspaces/workspace-path.service.js"; +} from "../db/schema"; +import { validateEnv } from "../env"; +import { UsersService } from "../auth/users.service"; +import { WorkspacePathService } from "../workspaces/workspace-path.service"; import type { AcceptInviteInput, AddMemberInput, @@ -29,11 +29,11 @@ import type { CreateOrganizationInput, UpdateMemberRoleInput, UpdateOrganizationInput, -} from "./dto.js"; +} from "./dto"; export type OrgRole = "maintainer" | "user"; -export interface Organization { +export type Organization = { id: string; name: string; description: string | null; @@ -41,28 +41,28 @@ export interface Organization { isPrivate: boolean; createdAt: string; updatedAt: string; -} +}; -export interface OrganizationMember { +export type OrganizationMember = { orgId: string; userId: string; role: OrgRole; createdAt: string; -} +}; -export interface OrganizationInvite { +export type OrganizationInvite = { token: string; orgId: string; role: OrgRole; expiresAt: string; -} +}; -interface StoredInvite { +type StoredInvite = { orgId: string; role: OrgRole; expiresAt: number; used: boolean; -} +}; function toOrganization(row: OrganizationRow): Organization { return { diff --git a/apps/backend/src/projects/chats/chats.controller.ts b/apps/backend/src/projects/chats/chats.controller.ts index 741829d..7b00be7 100644 --- a/apps/backend/src/projects/chats/chats.controller.ts +++ b/apps/backend/src/projects/chats/chats.controller.ts @@ -13,19 +13,19 @@ import { Version, } from "@nestjs/common"; import { ApiBearerAuth, ApiResponse, ApiTags } from "@nestjs/swagger"; -import { JwtAuthGuard } from "../../auth/jwt-auth.guard.js"; -import { ReqUser } from "../../auth/req-user.decorator.js"; -import type { RequestIdentity } from "../../auth/identity.service.js"; -import { NoIndexInterceptor } from "../../common/noindex.interceptor.js"; -import { ZodValidationPipe } from "../../common/zod-validation.pipe.js"; -import { V1Endpoint } from "../../api/version.js"; -import { ChatsService } from "./chats.service.js"; -import { SessionsService } from "../sessions/sessions.service.js"; +import { JwtAuthGuard } from "../../auth/jwt-auth.guard"; +import { ReqUser } from "../../auth/req-user.decorator"; +import type { RequestIdentity } from "../../auth/identity.service"; +import { NoIndexInterceptor } from "../../common/noindex.interceptor"; +import { ZodValidationPipe } from "../../common/zod-validation.pipe"; +import { V1Endpoint } from "../../api/version"; +import { ChatsService } from "./chats.service"; +import { SessionsService } from "../sessions/sessions.service"; import { ProjectChatDto, createChatSchema, type CreateChatInput, -} from "./dto.js"; +} from "./dto"; /** * Project chats — Bearer-guarded (JwtAuthGuard, legacy mock fallback in diff --git a/apps/backend/src/projects/chats/chats.module.ts b/apps/backend/src/projects/chats/chats.module.ts index 8a9f8ab..f98f26e 100644 --- a/apps/backend/src/projects/chats/chats.module.ts +++ b/apps/backend/src/projects/chats/chats.module.ts @@ -1,10 +1,10 @@ import { Module, forwardRef } from "@nestjs/common"; -import { DbModule } from "../../db/db.module.js"; -import { OrganizationsModule } from "../../organizations/organizations.module.js"; -import { ProjectsModule } from "../projects.module.js"; -import { SessionsModule } from "../sessions/sessions.module.js"; -import { ChatsController } from "./chats.controller.js"; -import { ChatsService } from "./chats.service.js"; +import { DbModule } from "../../db/db.module"; +import { OrganizationsModule } from "../../organizations/organizations.module"; +import { ProjectsModule } from "../projects.module"; +import { SessionsModule } from "../sessions/sessions.module"; +import { ChatsController } from "./chats.controller"; +import { ChatsService } from "./chats.service"; /** * Nested module — imported by ProjectsModule, never registered in AppModule directly. diff --git a/apps/backend/src/projects/chats/chats.service.ts b/apps/backend/src/projects/chats/chats.service.ts index f003a18..1b0adee 100644 --- a/apps/backend/src/projects/chats/chats.service.ts +++ b/apps/backend/src/projects/chats/chats.service.ts @@ -5,23 +5,23 @@ import { Inject, } from "@nestjs/common"; import { and, eq } from "drizzle-orm"; -import { AppLogger } from "../../common/app-logger.service.js"; +import { AppLogger } from "../../common/app-logger.service"; import { DbService, dbUnavailable, type DbClient, -} from "../../db/db.service.js"; -import { projectChats, type ProjectChatRow } from "../../db/schema.js"; -import { OrganizationsService } from "../../organizations/organizations.service.js"; -import { ProjectsService } from "../projects.service.js"; -import type { CreateChatInput } from "./dto.js"; +} from "../../db/db.service"; +import { projectChats, type ProjectChatRow } from "../../db/schema"; +import { OrganizationsService } from "../../organizations/organizations.service"; +import { ProjectsService } from "../projects.service"; +import type { CreateChatInput } from "./dto"; -export interface ProjectChat { +export type ProjectChat = { id: string; projectId: string; title: string; createdAt: string; -} +}; function toChat(row: ProjectChatRow): ProjectChat { return { diff --git a/apps/backend/src/projects/dto.ts b/apps/backend/src/projects/dto.ts index 847da94..e8a3127 100644 --- a/apps/backend/src/projects/dto.ts +++ b/apps/backend/src/projects/dto.ts @@ -1,45 +1,20 @@ import { ApiProperty } from '@nestjs/swagger'; -import { z } from 'zod'; /** - * Projects DTO — zod@4 source of truth, swagger DTOs for parity - * with contracts/openapi.yaml. Runtime validation via ZodValidationPipe. + * Projects DTO — single source of truth is @devbox/contracts (verbatim + * regexes, min/max + error strings, partial-update derivation, link + * default). Swagger DTO classes below stay as thin @nestjs/swagger + * wrappers for contracts/openapi.yaml parity. + * Runtime validation via ZodValidationPipe. */ - -const ownerSchema = z - .string() - .regex(/^[A-Za-z0-9_.-]+$/, { error: 'githubOwner has invalid format' }) - .max(100); -const repoSchema = z - .string() - .regex(/^[A-Za-z0-9_.-]+$/, { error: 'githubRepo has invalid format' }) - .max(100); -const branchSchema = z - .string() - .regex(/^[A-Za-z0-9_./-]+$/, { error: 'githubBranch has invalid format' }) - .max(100); - -export const createProjectSchema = z.object({ - name: z.string({ error: 'Field "name" is required' }).min(1).max(200), - description: z.string().max(2000).optional(), - githubOwner: ownerSchema.optional(), - githubRepo: repoSchema.optional(), - githubBranch: branchSchema.optional(), - githubUrl: z.string().max(500).optional(), - ownerId: z.string().max(200).optional(), -}); - -export const updateProjectSchema = createProjectSchema.partial(); - -export const githubLinkSchema = z.object({ - owner: ownerSchema, - repo: repoSchema, - branch: branchSchema.optional().default('main'), -}); - -export type CreateProjectInput = z.infer; -export type UpdateProjectInput = z.infer; -export type GithubLinkInput = z.infer; +export { + createProjectSchema, + githubLinkSchema, + updateProjectSchema, + type CreateProjectInput, + type GithubLinkInput, + type UpdateProjectInput, +} from '@devbox/contracts'; export class CreateProjectDto { @ApiProperty({ example: 'my-app' }) diff --git a/apps/backend/src/projects/files/project-files.controller.ts b/apps/backend/src/projects/files/project-files.controller.ts index 2ba7298..cbbb087 100644 --- a/apps/backend/src/projects/files/project-files.controller.ts +++ b/apps/backend/src/projects/files/project-files.controller.ts @@ -1,13 +1,13 @@ import { Controller, Get, Headers, Param, Query, UseGuards, UseInterceptors, Version } from '@nestjs/common'; import { ApiBearerAuth, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger'; -import { JwtAuthGuard } from '../../auth/jwt-auth.guard.js'; -import { ReqUser } from '../../auth/req-user.decorator.js'; -import type { RequestIdentity } from '../../auth/identity.service.js'; -import { NoIndexInterceptor } from '../../common/noindex.interceptor.js'; -import { ZodValidationPipe } from '../../common/zod-validation.pipe.js'; -import { V1Endpoint } from '../../api/version.js'; -import { FileNodeDto, filesQuerySchema, type FilesQuery } from './dto.js'; -import { ProjectFilesService, type FileNode } from './project-files.service.js'; +import { JwtAuthGuard } from '../../auth/jwt-auth.guard'; +import { ReqUser } from '../../auth/req-user.decorator'; +import type { RequestIdentity } from '../../auth/identity.service'; +import { NoIndexInterceptor } from '../../common/noindex.interceptor'; +import { ZodValidationPipe } from '../../common/zod-validation.pipe'; +import { V1Endpoint } from '../../api/version'; +import { FileNodeDto, filesQuerySchema, type FilesQuery } from './dto'; +import { ProjectFilesService, type FileNode } from './project-files.service'; /** * Readonly project file listing — Bearer-guarded (JwtAuthGuard, legacy diff --git a/apps/backend/src/projects/files/project-files.module.ts b/apps/backend/src/projects/files/project-files.module.ts index 1e4f516..569c613 100644 --- a/apps/backend/src/projects/files/project-files.module.ts +++ b/apps/backend/src/projects/files/project-files.module.ts @@ -1,9 +1,9 @@ import { Module, forwardRef } from '@nestjs/common'; -import { OrganizationsModule } from '../../organizations/organizations.module.js'; -import { WorkspacePathService } from '../../workspaces/workspace-path.service.js'; -import { ProjectsModule } from '../projects.module.js'; -import { ProjectFilesController } from './project-files.controller.js'; -import { ProjectFilesService } from './project-files.service.js'; +import { OrganizationsModule } from '../../organizations/organizations.module'; +import { WorkspacePathService } from '../../workspaces/workspace-path.service'; +import { ProjectsModule } from '../projects.module'; +import { ProjectFilesController } from './project-files.controller'; +import { ProjectFilesService } from './project-files.service'; /** * Nested readonly module — imported by ProjectsModule only. diff --git a/apps/backend/src/projects/files/project-files.service.ts b/apps/backend/src/projects/files/project-files.service.ts index 9d47f59..24006c2 100644 --- a/apps/backend/src/projects/files/project-files.service.ts +++ b/apps/backend/src/projects/files/project-files.service.ts @@ -1,18 +1,18 @@ import { ForbiddenException, Inject, Injectable, NotFoundException, forwardRef } from '@nestjs/common'; import { readdir } from 'node:fs/promises'; import path from 'node:path'; -import { AppLogger } from '../../common/app-logger.service.js'; -import { ExternalServiceError } from '../../common/external/external-error.js'; -import { storageUnavailable, throwStorageNotConfigured } from '../../storage/storage-unavailable.js'; -import { OrganizationsService } from '../../organizations/organizations.service.js'; -import { WorkspacePathService } from '../../workspaces/workspace-path.service.js'; -import { ProjectsService, ownerKeyOrThrow } from '../projects.service.js'; +import { AppLogger } from '../../common/app-logger.service'; +import { ExternalServiceError } from '../../common/external/external-error'; +import { storageUnavailable, throwStorageNotConfigured } from '../../storage/storage-unavailable'; +import { OrganizationsService } from '../../organizations/organizations.service'; +import { WorkspacePathService } from '../../workspaces/workspace-path.service'; +import { ProjectsService, ownerKeyOrThrow } from '../projects.service'; -export interface FileNode { +export type FileNode = { path: string; type: 'file' | 'dir'; children?: FileNode[]; -} +}; const MAX_DEPTH = 5; diff --git a/apps/backend/src/projects/github-link.service.ts b/apps/backend/src/projects/github-link.service.ts index 47c1ab8..4aee8a5 100644 --- a/apps/backend/src/projects/github-link.service.ts +++ b/apps/backend/src/projects/github-link.service.ts @@ -1,7 +1,7 @@ import { Injectable } from "@nestjs/common"; -import { AppLogger } from "../common/app-logger.service.js"; -import type { GithubLinkInput } from "./dto.js"; -import { ProjectsService } from "./projects.service.js"; +import { AppLogger } from "../common/app-logger.service"; +import type { GithubLinkInput } from "./dto"; +import { ProjectsService } from "./projects.service"; /** * GithubLinkService — pure validation + link assembly, lives inside diff --git a/apps/backend/src/projects/github/github-app.service.ts b/apps/backend/src/projects/github/github-app.service.ts index 06e25ce..4b21718 100644 --- a/apps/backend/src/projects/github/github-app.service.ts +++ b/apps/backend/src/projects/github/github-app.service.ts @@ -6,14 +6,14 @@ import { } from '@nestjs/common'; import { createAppAuth } from '@octokit/auth-app'; import { request as octokitRequest } from '@octokit/request'; -import { AppLogger } from '../../common/app-logger.service.js'; -import { fromUnknown } from '../../common/external/external-error.js'; -import { isGithubConfigured, validateEnv } from '../../env.js'; +import { AppLogger } from '../../common/app-logger.service'; +import { fromUnknown } from '../../common/external/external-error'; +import { isGithubConfigured, validateEnv } from '../../env'; -interface CachedToken { +type CachedToken = { token: string; expiresAtMs: number; -} +}; /** Refresh skew — never hand out a token expiring within the next minute. */ const EXPIRY_SKEW_MS = 60_000; diff --git a/apps/backend/src/projects/github/github-installations.service.ts b/apps/backend/src/projects/github/github-installations.service.ts index 13b6e64..3648124 100644 --- a/apps/backend/src/projects/github/github-installations.service.ts +++ b/apps/backend/src/projects/github/github-installations.service.ts @@ -1,15 +1,15 @@ import { Injectable } from "@nestjs/common"; import { desc, eq } from "drizzle-orm"; -import { AppLogger } from "../../common/app-logger.service.js"; +import { AppLogger } from "../../common/app-logger.service"; import { DbService, dbUnavailable, type DbClient, -} from "../../db/db.service.js"; +} from "../../db/db.service"; import { githubInstallations, type GithubInstallationRow, -} from "../../db/schema.js"; +} from "../../db/schema"; /** * Stored GitHub App installation (multi-tenant binding). @@ -17,7 +17,7 @@ import { * nullable until the users table exists. installationId is the GitHub * numeric id (unique). Tokens are NEVER stored here — only the binding. */ -export interface GithubInstallation { +export type GithubInstallation = { userId: string | null; installationId: number; accountLogin: string | null; @@ -25,15 +25,15 @@ export interface GithubInstallation { suspendedAt: string | null; createdAt: string; updatedAt: string; -} +}; -export interface UpsertInstallationInput { +export type UpsertInstallationInput = { installationId: number; userId?: string | null; accountLogin?: string | null; accountType?: string | null; suspendedAt?: string | null; -} +}; function toInstallation(row: GithubInstallationRow): GithubInstallation { return { diff --git a/apps/backend/src/projects/github/github-webhook.util.ts b/apps/backend/src/projects/github/github-webhook.util.ts index 93dffca..94347ac 100644 --- a/apps/backend/src/projects/github/github-webhook.util.ts +++ b/apps/backend/src/projects/github/github-webhook.util.ts @@ -48,14 +48,14 @@ export function verifyWebhookSignature( } /** Minimal shape of the `installation` webhook event we handle. */ -export interface InstallationWebhookPayload { +export type InstallationWebhookPayload = { action?: string; installation?: { id?: number; account?: { login?: string; type?: string }; suspended_at?: string | null; }; -} +}; /** Actions we act on; anything else (e.g. installation_repositories) is acked. */ export const INSTALLATION_ACTIONS = new Set([ diff --git a/apps/backend/src/projects/github/github.controller.ts b/apps/backend/src/projects/github/github.controller.ts index d05d553..9d6dc95 100644 --- a/apps/backend/src/projects/github/github.controller.ts +++ b/apps/backend/src/projects/github/github.controller.ts @@ -20,16 +20,16 @@ import { ApiResponse, ApiTags, } from "@nestjs/swagger"; -import { V1Endpoint } from "../../api/version.js"; +import { V1Endpoint } from "../../api/version"; import { DEFAULT_MOCK_USER_ID, resolveIdentityUserId, -} from "../../auth/identity.service.js"; -import { JwtAuthGuard } from "../../auth/jwt-auth.guard.js"; -import { ReqUser } from "../../auth/req-user.decorator.js"; -import type { RequestIdentity } from "../../auth/identity.service.js"; -import { ZodValidationPipe } from "../../common/zod-validation.pipe.js"; -import { validateEnv } from "../../env.js"; +} from "../../auth/identity.service"; +import { JwtAuthGuard } from "../../auth/jwt-auth.guard"; +import { ReqUser } from "../../auth/req-user.decorator"; +import type { RequestIdentity } from "../../auth/identity.service"; +import { ZodValidationPipe } from "../../common/zod-validation.pipe"; +import { validateEnv } from "../../env"; import { GithubCallbackResultDto, GithubInstallUrlDto, @@ -41,16 +41,16 @@ import { listReposQuerySchema, type InstallCallbackQueryInput, type ListReposQueryInput, -} from "./dto.js"; -import { GithubInstallationsService } from "./github-installations.service.js"; +} from "./dto"; +import { GithubInstallationsService } from "./github-installations.service"; import { INSTALLATION_ACTIONS, getRawBody, verifyWebhookSignature, type InstallationWebhookPayload, -} from "./github-webhook.util.js"; -import { GithubAppService } from "./github-app.service.js"; -import { GithubService } from "./github.service.js"; +} from "./github-webhook.util"; +import { GithubAppService } from "./github-app.service"; +import { GithubService } from "./github.service"; /** MVP mock user key when no identity is supplied (dev single-user). */ export { DEFAULT_MOCK_USER_ID }; diff --git a/apps/backend/src/projects/github/github.e2e.ts b/apps/backend/src/projects/github/github.e2e.ts index 5548822..1471e0f 100644 --- a/apps/backend/src/projects/github/github.e2e.ts +++ b/apps/backend/src/projects/github/github.e2e.ts @@ -69,7 +69,7 @@ function signWebhook(raw: string, secret: string): string { async function main(): Promise { const { resolveTestDb, applyTestMigrations } = - await import("../../db/e2e-db.js"); + await import("../../db/e2e-db"); const testDb = await resolveTestDb( process.env.TEST_DATABASE_URL ?? process.env.DATABASE_URL ?? "", ); @@ -88,12 +88,12 @@ async function main(): Promise { console.log(`[github e2e] db mode: ${testDb.mode}`); const { NestFactory } = await import("@nestjs/core"); - const { AppModule } = await import("../../app.module.js"); - const { configureApp } = await import("../../app.setup.js"); - const { GithubAppService } = await import("./github-app.service.js"); + const { AppModule } = await import("../../app.module"); + const { configureApp } = await import("../../app.setup"); + const { GithubAppService } = await import("./github-app.service"); const { GithubInstallationsService } = - await import("./github-installations.service.js"); - const { __setGithubFetchForTests } = await import("./github.service.js"); + await import("./github-installations.service"); + const { __setGithubFetchForTests } = await import("./github.service"); let passed = 0; let failed = 0; diff --git a/apps/backend/src/projects/github/github.module.ts b/apps/backend/src/projects/github/github.module.ts index 9f79b4d..a537e40 100644 --- a/apps/backend/src/projects/github/github.module.ts +++ b/apps/backend/src/projects/github/github.module.ts @@ -1,10 +1,10 @@ import { Module, forwardRef } from "@nestjs/common"; -import { DbModule } from "../../db/db.module.js"; -import { ProjectsModule } from "../projects.module.js"; -import { GithubAppService } from "./github-app.service.js"; -import { GithubInstallationsService } from "./github-installations.service.js"; -import { GithubController } from "./github.controller.js"; -import { GithubService } from "./github.service.js"; +import { DbModule } from "../../db/db.module"; +import { ProjectsModule } from "../projects.module"; +import { GithubAppService } from "./github-app.service"; +import { GithubInstallationsService } from "./github-installations.service"; +import { GithubController } from "./github.controller"; +import { GithubService } from "./github.service"; /** * Nested module — imported by ProjectsModule, never registered in AppModule directly. diff --git a/apps/backend/src/projects/github/github.service.ts b/apps/backend/src/projects/github/github.service.ts index 9afe11c..234df85 100644 --- a/apps/backend/src/projects/github/github.service.ts +++ b/apps/backend/src/projects/github/github.service.ts @@ -5,17 +5,17 @@ import { UnauthorizedException, } from '@nestjs/common'; import { Octokit } from 'octokit'; -import { AppLogger } from '../../common/app-logger.service.js'; -import { validateEnv } from '../../env.js'; +import { AppLogger } from '../../common/app-logger.service'; +import { validateEnv } from '../../env'; import { ExternalServiceError, fromUnknown, -} from '../../common/external/external-error.js'; -import { withRetry } from '../../common/external/retry.js'; -import { GithubAppService } from './github-app.service.js'; -import type { ListReposQueryInput } from './dto.js'; +} from '../../common/external/external-error'; +import { withRetry } from '../../common/external/retry'; +import { GithubAppService } from './github-app.service'; +import type { ListReposQueryInput } from './dto'; -export interface GithubRepo { +export type GithubRepo = { id: number; owner: string; name: string; @@ -23,7 +23,7 @@ export interface GithubRepo { private: boolean; defaultBranch: string; url: string; -} +}; /** * E2e seam: stub fetch used by Octokit (no network in tests). @@ -36,7 +36,7 @@ export function __setGithubFetchForTests(fn: typeof fetch | null): void { fetchImplForTests = fn; } -interface InstallationReposResponse { +type InstallationReposResponse = { total_count?: number; repositories?: Array<{ id?: number; @@ -47,7 +47,7 @@ interface InstallationReposResponse { html_url?: string; owner?: { login?: string }; }>; -} +}; /** * GithubService — lists repositories accessible to one GitHub App diff --git a/apps/backend/src/projects/project-disk-mapping.spec.ts b/apps/backend/src/projects/project-disk-mapping.spec.ts index 13eb7fb..4228bd7 100644 --- a/apps/backend/src/projects/project-disk-mapping.spec.ts +++ b/apps/backend/src/projects/project-disk-mapping.spec.ts @@ -17,8 +17,8 @@ import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; -import { WorkspacePathService } from '../workspaces/workspace-path.service.js'; -import { SYSTEM_OWNER_UUID, ownerKeyOrThrow } from './projects.service.js'; +import { WorkspacePathService } from '../workspaces/workspace-path.service'; +import { SYSTEM_OWNER_UUID, ownerKeyOrThrow } from './projects.service'; const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; diff --git a/apps/backend/src/projects/project-strict-root.spec.ts b/apps/backend/src/projects/project-strict-root.spec.ts index fa5d09c..330ec7a 100644 --- a/apps/backend/src/projects/project-strict-root.spec.ts +++ b/apps/backend/src/projects/project-strict-root.spec.ts @@ -20,8 +20,8 @@ import assert from 'node:assert/strict'; import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { WorkspacePathService } from '../workspaces/workspace-path.service.js'; -import { ProjectsService } from './projects.service.js'; +import { WorkspacePathService } from '../workspaces/workspace-path.service'; +import { ProjectsService } from './projects.service'; const silentLogger = { debug() {}, diff --git a/apps/backend/src/projects/projects.controller.ts b/apps/backend/src/projects/projects.controller.ts index 682fbb9..8d00c38 100644 --- a/apps/backend/src/projects/projects.controller.ts +++ b/apps/backend/src/projects/projects.controller.ts @@ -13,7 +13,7 @@ import { Version, } from "@nestjs/common"; import { ApiResponse, ApiTags } from "@nestjs/swagger"; -import { NoIndexInterceptor } from "../common/noindex.interceptor.js";import { ZodValidationPipe } from "../common/zod-validation.pipe.js"; +import { NoIndexInterceptor } from "../common/noindex.interceptor";import { ZodValidationPipe } from "../common/zod-validation.pipe"; import { GithubLinkStatusDto, ProjectDto, @@ -23,12 +23,12 @@ import { type CreateProjectInput, type GithubLinkInput, type UpdateProjectInput, -} from "./dto.js"; -import { V1Endpoint } from "../api/version.js"; -import { GithubLinkService } from "./github-link.service.js"; -import { ProjectsService } from "./projects.service.js"; -import { ChatsService } from "./chats/chats.service.js"; -import { SessionsService } from "./sessions/sessions.service.js"; +} from "./dto"; +import { V1Endpoint } from "../api/version"; +import { GithubLinkService } from "./github-link.service"; +import { ProjectsService } from "./projects.service"; +import { ChatsService } from "./chats/chats.service"; +import { SessionsService } from "./sessions/sessions.service"; /** * Projects CRUD + github link endpoints. diff --git a/apps/backend/src/projects/projects.e2e.ts b/apps/backend/src/projects/projects.e2e.ts index 94e436a..c7db349 100644 --- a/apps/backend/src/projects/projects.e2e.ts +++ b/apps/backend/src/projects/projects.e2e.ts @@ -24,7 +24,7 @@ process.env.OPENCODE_URL = "http://127.0.0.1:9"; async function main(): Promise { const { resolveTestDb, applyTestMigrations } = - await import("../db/e2e-db.js"); + await import("../db/e2e-db"); const testDb = await resolveTestDb( process.env.TEST_DATABASE_URL ?? process.env.DATABASE_URL ?? "", ); @@ -51,8 +51,8 @@ async function main(): Promise { console.log(`[projects e2e] REPOS_ROOT: ${reposRoot}`); const { NestFactory } = await import("@nestjs/core"); - const { AppModule } = await import("../app.module.js"); - const { configureApp } = await import("../app.setup.js"); + const { AppModule } = await import("../app.module"); + const { configureApp } = await import("../app.setup"); const app = await NestFactory.create(AppModule, { logger: false }); configureApp(app); @@ -130,7 +130,7 @@ async function main(): Promise { }); } else { // Live PG — full CRUD suite (tables migrated + cleared above). - const { ProjectsService } = await import("./projects.service.js"); + const { ProjectsService } = await import("./projects.service"); const registry = app.get(ProjectsService, { strict: false }) as { clearAllForTests: () => Promise; }; @@ -159,9 +159,9 @@ async function main(): Promise { await check("POST initializes a valid git repo on disk", async () => { const { WorkspacePathService } = - await import("../workspaces/workspace-path.service.js"); - const { SYSTEM_OWNER_UUID } = await import("./projects.service.js"); - const { isValidGitRepo } = await import("../repos/repos-git.util.js"); + await import("../workspaces/workspace-path.service"); + const { SYSTEM_OWNER_UUID } = await import("./projects.service"); + const { isValidGitRepo } = await import("../repos/repos-git.util"); const paths = new WorkspacePathService(); // No ownerId → SYSTEM_OWNER_UUID home (same mapping as ProjectsService). const resolved = await paths.resolveUser(SYSTEM_OWNER_UUID, projectId); @@ -192,8 +192,8 @@ async function main(): Promise { await check("missing repo dir → GET/list report corrupted:true", async () => { const { WorkspacePathService } = - await import("../workspaces/workspace-path.service.js"); - const { SYSTEM_OWNER_UUID } = await import("./projects.service.js"); + await import("../workspaces/workspace-path.service"); + const { SYSTEM_OWNER_UUID } = await import("./projects.service"); const paths = new WorkspacePathService(); const resolved = await paths.resolveUser(SYSTEM_OWNER_UUID, projectId); await rm(resolved.absRepo, { recursive: true, force: true }); @@ -356,8 +356,8 @@ async function main(): Promise { const probe = (await readJson(res)) as { id?: string }; const probeId = probe.id as string; const { WorkspacePathService } = - await import("../workspaces/workspace-path.service.js"); - const { SYSTEM_OWNER_UUID } = await import("./projects.service.js"); + await import("../workspaces/workspace-path.service"); + const { SYSTEM_OWNER_UUID } = await import("./projects.service"); const paths = new WorkspacePathService(); const resolved = await paths.resolveUser(SYSTEM_OWNER_UUID, probeId); assert.equal((await stat(resolved.absRepo)).isDirectory(), true); diff --git a/apps/backend/src/projects/projects.module.ts b/apps/backend/src/projects/projects.module.ts index e91f6ad..fad00f5 100644 --- a/apps/backend/src/projects/projects.module.ts +++ b/apps/backend/src/projects/projects.module.ts @@ -1,13 +1,13 @@ import { Module, forwardRef } from "@nestjs/common"; -import { DbModule } from "../db/db.module.js"; -import { WorkspacePathService } from "../workspaces/workspace-path.service.js"; -import { GithubLinkService } from "./github-link.service.js"; -import { ProjectsController } from "./projects.controller.js"; -import { ProjectsService } from "./projects.service.js"; -import { ChatsModule } from "./chats/chats.module.js"; -import { ProjectFilesModule } from "./files/project-files.module.js"; -import { GithubModule } from "./github/github.module.js"; -import { SessionsModule } from "./sessions/sessions.module.js"; +import { DbModule } from "../db/db.module"; +import { WorkspacePathService } from "../workspaces/workspace-path.service"; +import { GithubLinkService } from "./github-link.service"; +import { ProjectsController } from "./projects.controller"; +import { ProjectsService } from "./projects.service"; +import { ChatsModule } from "./chats/chats.module"; +import { ProjectFilesModule } from "./files/project-files.module"; +import { GithubModule } from "./github/github.module"; +import { SessionsModule } from "./sessions/sessions.module"; /** * ProjectsModule — module-in-module composition: diff --git a/apps/backend/src/projects/projects.service.ts b/apps/backend/src/projects/projects.service.ts index 81c08b1..cf7d474 100644 --- a/apps/backend/src/projects/projects.service.ts +++ b/apps/backend/src/projects/projects.service.ts @@ -9,16 +9,16 @@ import { execFile } from "node:child_process"; import { randomUUID } from "node:crypto"; import { mkdir, rm, stat } from "node:fs/promises"; import { promisify } from "node:util"; -import { AppLogger } from "../common/app-logger.service.js"; -import { DbService, dbUnavailable, type DbClient } from "../db/db.service.js"; -import { projects, type ProjectRow } from "../db/schema.js"; -import { isValidGitRepo } from "../repos/repos-git.util.js"; -import { WorkspacePathService } from "../workspaces/workspace-path.service.js"; +import { AppLogger } from "../common/app-logger.service"; +import { DbService, dbUnavailable, type DbClient } from "../db/db.service"; +import { projects, type ProjectRow } from "../db/schema"; +import { isValidGitRepo } from "../repos/repos-git.util"; +import { WorkspacePathService } from "../workspaces/workspace-path.service"; import type { CreateProjectInput, GithubLinkInput, UpdateProjectInput, -} from "./dto.js"; +} from "./dto"; const execFileAsync = promisify(execFile); @@ -48,7 +48,7 @@ export function ownerKeyOrThrow(ownerId: string | null): string { return raw; } -export interface Project { +export type Project = { id: string; name: string; description: string | null; @@ -71,7 +71,7 @@ export interface Project { * the row outlives usable storage config (additive, no migration). */ corruptedReason?: string | null; -} +}; function toProject(row: ProjectRow): Project { return { diff --git a/apps/backend/src/projects/sessions/sessions.controller.ts b/apps/backend/src/projects/sessions/sessions.controller.ts index 34f2845..27e0ec4 100644 --- a/apps/backend/src/projects/sessions/sessions.controller.ts +++ b/apps/backend/src/projects/sessions/sessions.controller.ts @@ -11,18 +11,18 @@ import { Version, } from "@nestjs/common"; import { ApiBearerAuth, ApiResponse, ApiTags } from "@nestjs/swagger"; -import { JwtAuthGuard } from "../../auth/jwt-auth.guard.js"; -import { ReqUser } from "../../auth/req-user.decorator.js"; -import type { RequestIdentity } from "../../auth/identity.service.js"; -import { NoIndexInterceptor } from "../../common/noindex.interceptor.js"; -import { ZodValidationPipe } from "../../common/zod-validation.pipe.js"; -import { V1Endpoint } from "../../api/version.js"; -import { SessionsService } from "./sessions.service.js"; +import { JwtAuthGuard } from "../../auth/jwt-auth.guard"; +import { ReqUser } from "../../auth/req-user.decorator"; +import type { RequestIdentity } from "../../auth/identity.service"; +import { NoIndexInterceptor } from "../../common/noindex.interceptor"; +import { ZodValidationPipe } from "../../common/zod-validation.pipe"; +import { V1Endpoint } from "../../api/version"; +import { SessionsService } from "./sessions.service"; import { ProjectSessionDto, createSessionSchema, type CreateSessionInput, -} from "./dto.js"; +} from "./dto"; /** * Project sessions — Bearer-guarded (JwtAuthGuard, legacy mock fallback in diff --git a/apps/backend/src/projects/sessions/sessions.module.ts b/apps/backend/src/projects/sessions/sessions.module.ts index 48eb7e7..de11223 100644 --- a/apps/backend/src/projects/sessions/sessions.module.ts +++ b/apps/backend/src/projects/sessions/sessions.module.ts @@ -1,10 +1,10 @@ import { Module, forwardRef } from "@nestjs/common"; -import { DbModule } from "../../db/db.module.js"; -import { OrganizationsModule } from "../../organizations/organizations.module.js"; -import { ChatsModule } from "../chats/chats.module.js"; -import { ProjectsModule } from "../projects.module.js"; -import { SessionsController } from "./sessions.controller.js"; -import { SessionsService } from "./sessions.service.js"; +import { DbModule } from "../../db/db.module"; +import { OrganizationsModule } from "../../organizations/organizations.module"; +import { ChatsModule } from "../chats/chats.module"; +import { ProjectsModule } from "../projects.module"; +import { SessionsController } from "./sessions.controller"; +import { SessionsService } from "./sessions.service"; /** * Nested module — imported by ProjectsModule, never registered in AppModule directly. diff --git a/apps/backend/src/projects/sessions/sessions.service.ts b/apps/backend/src/projects/sessions/sessions.service.ts index d9fe4f9..30e0f6e 100644 --- a/apps/backend/src/projects/sessions/sessions.service.ts +++ b/apps/backend/src/projects/sessions/sessions.service.ts @@ -6,19 +6,19 @@ import { Inject, } from "@nestjs/common"; import { and, eq } from "drizzle-orm"; -import { AppLogger } from "../../common/app-logger.service.js"; +import { AppLogger } from "../../common/app-logger.service"; import { DbService, dbUnavailable, type DbClient, -} from "../../db/db.service.js"; -import { projectSessions, type ProjectSessionRow } from "../../db/schema.js"; -import { ChatsService } from "../chats/chats.service.js"; -import { ProjectsService } from "../projects.service.js"; -import { OrganizationsService } from "../../organizations/organizations.service.js"; -import type { CreateSessionInput } from "./dto.js"; +} from "../../db/db.service"; +import { projectSessions, type ProjectSessionRow } from "../../db/schema"; +import { ChatsService } from "../chats/chats.service"; +import { ProjectsService } from "../projects.service"; +import { OrganizationsService } from "../../organizations/organizations.service"; +import type { CreateSessionInput } from "./dto"; -export interface ProjectSession { +export type ProjectSession = { id: string; projectId: string; chatId: string | null; @@ -26,7 +26,7 @@ export interface ProjectSession { metadata: Record | null; createdAt: string; updatedAt: string; -} +}; function toSession(row: ProjectSessionRow): ProjectSession { return { diff --git a/apps/backend/src/repos/repos-git.util.ts b/apps/backend/src/repos/repos-git.util.ts index ae7126f..730378c 100644 --- a/apps/backend/src/repos/repos-git.util.ts +++ b/apps/backend/src/repos/repos-git.util.ts @@ -10,14 +10,14 @@ export const GIT_PROBE_TIMEOUT_MS = 5000; export type GitInvalidReason = 'no-git' | 'rev-parse-failed' | 'fsck-failed' | 'timeout'; -export interface GitCheck { +export type GitCheck = { ok: boolean; reason?: GitInvalidReason; -} +}; -interface WarnLogger { +type WarnLogger = { warn(message: unknown): void; -} +}; function isTimeout(err: unknown): boolean { const e = err as { killed?: boolean; signal?: string; code?: string | number }; diff --git a/apps/backend/src/repos/repos.controller.ts b/apps/backend/src/repos/repos.controller.ts index 0e885f8..55dd4ce 100644 --- a/apps/backend/src/repos/repos.controller.ts +++ b/apps/backend/src/repos/repos.controller.ts @@ -1,9 +1,9 @@ import { BadRequestException, Controller, Get, Headers, Param, Query, Version } from '@nestjs/common'; import { ApiParam, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger'; -import { ZodValidationPipe } from '../common/zod-validation.pipe.js'; -import { V1Endpoint } from '../api/version.js'; -import { RepoDto, reposQuerySchema, userSpaceSchema, type ReposQuery } from './dto.js'; -import { ReposService } from './repos.service.js'; +import { ZodValidationPipe } from '../common/zod-validation.pipe'; +import { V1Endpoint } from '../api/version'; +import { RepoDto, reposQuerySchema, userSpaceSchema, type ReposQuery } from './dto'; +import { ReposService } from './repos.service'; /** * Readonly git-repo registry — GET only (no POST/PUT/DELETE by design). diff --git a/apps/backend/src/repos/repos.e2e.ts b/apps/backend/src/repos/repos.e2e.ts index abc3430..654db6d 100644 --- a/apps/backend/src/repos/repos.e2e.ts +++ b/apps/backend/src/repos/repos.e2e.ts @@ -41,8 +41,8 @@ for (const key of ['POSTGRES_USER', 'POSTGRES_PASSWORD', 'POSTGRES_DB', 'POSTGRE async function main(): Promise { const { NestFactory } = await import('@nestjs/core'); - const { AppModule } = await import('../app.module.js'); - const { configureApp } = await import('../app.setup.js'); + const { AppModule } = await import('../app.module'); + const { configureApp } = await import('../app.setup'); const app = await NestFactory.create(AppModule, { logger: false }); configureApp(app); diff --git a/apps/backend/src/repos/repos.module.ts b/apps/backend/src/repos/repos.module.ts index 6ee2ce9..ceecfb3 100644 --- a/apps/backend/src/repos/repos.module.ts +++ b/apps/backend/src/repos/repos.module.ts @@ -1,6 +1,6 @@ import { Module } from '@nestjs/common'; -import { ReposController } from './repos.controller.js'; -import { ReposService } from './repos.service.js'; +import { ReposController } from './repos.controller'; +import { ReposService } from './repos.service'; /** * ReposModule — readonly git-repo registry diff --git a/apps/backend/src/repos/repos.service.spec.ts b/apps/backend/src/repos/repos.service.spec.ts index bba1362..df0de18 100644 --- a/apps/backend/src/repos/repos.service.spec.ts +++ b/apps/backend/src/repos/repos.service.spec.ts @@ -16,13 +16,13 @@ import { execFileSync } from 'node:child_process'; import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { ReposService } from './repos.service.js'; -import { isValidGitRepo } from './repos-git.util.js'; +import { ReposService } from './repos.service'; +import { isValidGitRepo } from './repos-git.util'; -interface WarnCall { +type WarnCall = { path?: string; reason?: string; -} +}; function makeLogger() { const warns: WarnCall[] = []; @@ -32,7 +32,7 @@ function makeLogger() { warn: (msg: unknown) => { warns.push(msg as WarnCall); }, - } as unknown as import('../common/app-logger.service.js').AppLogger, + } as unknown as import('../common/app-logger.service').AppLogger, }; } diff --git a/apps/backend/src/repos/repos.service.ts b/apps/backend/src/repos/repos.service.ts index f7e939b..e082edd 100644 --- a/apps/backend/src/repos/repos.service.ts +++ b/apps/backend/src/repos/repos.service.ts @@ -1,15 +1,15 @@ import { BadRequestException, Injectable } from '@nestjs/common'; import { readdir, realpath, stat } from 'node:fs/promises'; import path from 'node:path'; -import { AppLogger } from '../common/app-logger.service.js'; +import { AppLogger } from '../common/app-logger.service'; import { storageUnavailable, throwStorageNotConfigured, -} from '../storage/storage-unavailable.js'; -import { userSpaceSchema, type ReposQuery } from './dto.js'; -import { isValidGitRepo } from './repos-git.util.js'; +} from '../storage/storage-unavailable'; +import { userSpaceSchema, type ReposQuery } from './dto'; +import { isValidGitRepo } from './repos-git.util'; -export interface RepoEntry { +export type RepoEntry = { /** Scope owner id (user uuid under users/, org uuid under orgs/). */ userSpace: string; /** Project id (uuid). */ @@ -17,15 +17,15 @@ export interface RepoEntry { /** Path relative to REPOS_ROOT, e.g. "users//projects//content". */ path: string; updatedAt: string; -} +}; -interface Candidate { +type Candidate = { scope: 'users' | 'orgs'; userSpace: string; name: string; absPath: string; updatedAt: string; -} +}; const SCOPE_DIR_PATTERN = /^[a-zA-Z0-9_-]+$/; diff --git a/apps/backend/src/storage/storage-unavailable.spec.ts b/apps/backend/src/storage/storage-unavailable.spec.ts index 0b16f83..c2013f6 100644 --- a/apps/backend/src/storage/storage-unavailable.spec.ts +++ b/apps/backend/src/storage/storage-unavailable.spec.ts @@ -19,13 +19,13 @@ import assert from 'node:assert/strict'; import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { validateEnvWithWarnings } from '../env.js'; -import { ReposService } from '../repos/repos.service.js'; -import { ProjectFilesService } from '../projects/files/project-files.service.js'; -import { WorkspaceCloneService } from '../workspaces/workspace-clone.service.js'; -import { CloneJobsRepository } from '../workspaces/clone-jobs.repository.js'; -import { WorkspacePathService } from '../workspaces/workspace-path.service.js'; -import { WorkspacesService } from '../workspaces/workspaces.service.js'; +import { validateEnvWithWarnings } from '../env'; +import { ReposService } from '../repos/repos.service'; +import { ProjectFilesService } from '../projects/files/project-files.service'; +import { WorkspaceCloneService } from '../workspaces/workspace-clone.service'; +import { CloneJobsRepository } from '../workspaces/clone-jobs.repository'; +import { WorkspacePathService } from '../workspaces/workspace-path.service'; +import { WorkspacesService } from '../workspaces/workspaces.service'; type Source = NodeJS.ProcessEnv; diff --git a/apps/backend/src/storage/storage-unavailable.ts b/apps/backend/src/storage/storage-unavailable.ts index 8dd10d8..3dfd367 100644 --- a/apps/backend/src/storage/storage-unavailable.ts +++ b/apps/backend/src/storage/storage-unavailable.ts @@ -1,5 +1,5 @@ -import { AppLogger } from "../common/app-logger.service.js"; -import { ExternalServiceError } from "../common/external/external-error.js"; +import { AppLogger } from "../common/app-logger.service"; +import { ExternalServiceError } from "../common/external/external-error"; /** Fixed 503 message for unconfigured storage (mirrors dbUnavailable). */ export const STORAGE_UNAVAILABLE_MESSAGE = diff --git a/apps/backend/src/workspaces/clone-jobs.repository.ts b/apps/backend/src/workspaces/clone-jobs.repository.ts index bf2ab22..ff0c024 100644 --- a/apps/backend/src/workspaces/clone-jobs.repository.ts +++ b/apps/backend/src/workspaces/clone-jobs.repository.ts @@ -1,9 +1,9 @@ import { Injectable } from '@nestjs/common'; -import { AppLogger } from '../common/app-logger.service.js'; +import { AppLogger } from '../common/app-logger.service'; export type CloneStatus = 'queued' | 'cloning' | 'ready' | 'failed'; -export interface CloneJob { +export type CloneJob = { userId: string; userSpace: string; repoName: string; @@ -13,7 +13,7 @@ export interface CloneJob { progress: number; error: string | null; updatedAt: string; -} +}; const TERMINAL_READY: CloneStatus = 'ready'; diff --git a/apps/backend/src/workspaces/workspace-clone.service.ts b/apps/backend/src/workspaces/workspace-clone.service.ts index 3c84e65..0a2015e 100644 --- a/apps/backend/src/workspaces/workspace-clone.service.ts +++ b/apps/backend/src/workspaces/workspace-clone.service.ts @@ -2,13 +2,13 @@ import { BadRequestException, Injectable } from '@nestjs/common'; import { execFile } from 'node:child_process'; import { mkdir, stat } from 'node:fs/promises'; import { promisify } from 'node:util'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ExternalServiceError } from '../common/external/external-error.js'; -import { storageUnavailable } from '../storage/storage-unavailable.js'; -import { isValidGitRepo } from '../repos/repos-git.util.js'; -import { CloneJobsRepository, type CloneJob } from './clone-jobs.repository.js'; -import { WorkspacePathService } from './workspace-path.service.js'; -import { readSubmodules } from './workspace-submodules.util.js'; +import { AppLogger } from '../common/app-logger.service'; +import { ExternalServiceError } from '../common/external/external-error'; +import { storageUnavailable } from '../storage/storage-unavailable'; +import { isValidGitRepo } from '../repos/repos-git.util'; +import { CloneJobsRepository, type CloneJob } from './clone-jobs.repository'; +import { WorkspacePathService } from './workspace-path.service'; +import { readSubmodules } from './workspace-submodules.util'; const execFileAsync = promisify(execFile); diff --git a/apps/backend/src/workspaces/workspace-path.service.ts b/apps/backend/src/workspaces/workspace-path.service.ts index e03859b..059007b 100644 --- a/apps/backend/src/workspaces/workspace-path.service.ts +++ b/apps/backend/src/workspaces/workspace-path.service.ts @@ -4,7 +4,7 @@ import { Injectable, InternalServerErrorException, } from '@nestjs/common'; -import { throwStorageNotConfigured } from '../storage/storage-unavailable.js'; +import { throwStorageNotConfigured } from '../storage/storage-unavailable'; import { mkdir, realpath } from 'node:fs/promises'; import path from 'node:path'; @@ -13,16 +13,16 @@ const UUID_RE = export type ProjectScope = 'user' | 'org'; -export interface OrgScopeResolved { +export type OrgScopeResolved = { /** Org id (validated uuid). */ orgId: string; /** Absolute org home: /orgs/. */ absHome: string; /** Absolute org-level reserved secrets dir (empty, never served). */ absSecrets: string; -} +}; -export interface ProjectResolved { +export type ProjectResolved = { /** 'user' → users//…, 'org' → orgs//… (no workspace segment). */ scope: ProjectScope; /** Scope owner id (user uuid or org uuid, as passed — validated uuid). */ @@ -41,7 +41,7 @@ export interface ProjectResolved { abs: string; /** Normalized posix-relative path inside content ('.' for root). */ rel: string; -} +}; /** * WorkspacePathService — scoped path jail for projects (organizations epic). diff --git a/apps/backend/src/workspaces/workspace-path.spec.ts b/apps/backend/src/workspaces/workspace-path.spec.ts index a1702ca..b506190 100644 --- a/apps/backend/src/workspaces/workspace-path.spec.ts +++ b/apps/backend/src/workspaces/workspace-path.spec.ts @@ -17,7 +17,7 @@ import { mkdtempSync, statSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; -import { WorkspacePathService } from './workspace-path.service.js'; +import { WorkspacePathService } from './workspace-path.service'; const UID = randomUUID(); const OID = randomUUID(); diff --git a/apps/backend/src/workspaces/workspace-submodules.util.ts b/apps/backend/src/workspaces/workspace-submodules.util.ts index cc59f0d..111a9ed 100644 --- a/apps/backend/src/workspaces/workspace-submodules.util.ts +++ b/apps/backend/src/workspaces/workspace-submodules.util.ts @@ -2,21 +2,21 @@ import { execFile } from 'node:child_process'; import { readFile } from 'node:fs/promises'; import path from 'node:path'; import { promisify } from 'node:util'; -import type { AppLogger } from '../common/app-logger.service.js'; +import type { AppLogger } from '../common/app-logger.service'; const execFileAsync = promisify(execFile); -export interface SubmoduleEntry { +export type SubmoduleEntry = { path: string; url: string | null; sha: string | null; /** Raw first column of `git submodule status` (' ', '+', '-', 'U'). */ status: string; -} +}; -interface WarnLogger { +type WarnLogger = { warn(message: unknown): void; -} +}; export const SUBMODULE_TIMEOUT_MS = 30000; diff --git a/apps/backend/src/workspaces/workspaces.controller.ts b/apps/backend/src/workspaces/workspaces.controller.ts index f214ec6..d62b63c 100644 --- a/apps/backend/src/workspaces/workspaces.controller.ts +++ b/apps/backend/src/workspaces/workspaces.controller.ts @@ -15,17 +15,17 @@ import { } from '@nestjs/common'; import { ApiBearerAuth, ApiHeader, ApiParam, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger'; import { Inject, Optional, forwardRef } from '@nestjs/common'; -import { V1Endpoint } from '../api/version.js'; +import { V1Endpoint } from '../api/version'; import { DEFAULT_MOCK_USER_ID as DEFAULT_WORKSPACE_USER_ID, resolveIdentityUserId as resolveUserId, -} from '../auth/identity.service.js'; -import { JwtAuthGuard } from '../auth/jwt-auth.guard.js'; -import { ReqUser } from '../auth/req-user.decorator.js'; -import type { RequestIdentity } from '../auth/identity.service.js'; -import { ZodValidationPipe } from '../common/zod-validation.pipe.js'; -import { GithubInstallationsService } from '../projects/github/github-installations.service.js'; -import { CloneJobsRepository } from './clone-jobs.repository.js'; +} from '../auth/identity.service'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { ReqUser } from '../auth/req-user.decorator'; +import type { RequestIdentity } from '../auth/identity.service'; +import { ZodValidationPipe } from '../common/zod-validation.pipe'; +import { GithubInstallationsService } from '../projects/github/github-installations.service'; +import { CloneJobsRepository } from './clone-jobs.repository'; import { CloneWorkspaceDto, WorkspaceCloneJobDto, @@ -36,9 +36,9 @@ import { workspaceTreeQuerySchema, type CloneWorkspaceInput, type WorkspaceTreeQuery, -} from './dto.js'; -import { WorkspaceCloneService } from './workspace-clone.service.js'; -import { WorkspacesService } from './workspaces.service.js'; +} from './dto'; +import { WorkspaceCloneService } from './workspace-clone.service'; +import { WorkspacesService } from './workspaces.service'; /** MVP mock user key (single copy lives in auth/identity.service.ts). */ export { DEFAULT_WORKSPACE_USER_ID }; diff --git a/apps/backend/src/workspaces/workspaces.module.ts b/apps/backend/src/workspaces/workspaces.module.ts index 3948b5f..a6884ce 100644 --- a/apps/backend/src/workspaces/workspaces.module.ts +++ b/apps/backend/src/workspaces/workspaces.module.ts @@ -1,10 +1,10 @@ import { Module, forwardRef } from '@nestjs/common'; -import { GithubModule } from '../projects/github/github.module.js'; -import { CloneJobsRepository } from './clone-jobs.repository.js'; -import { WorkspaceCloneService } from './workspace-clone.service.js'; -import { WorkspacePathService } from './workspace-path.service.js'; -import { WorkspacesController } from './workspaces.controller.js'; -import { WorkspacesService } from './workspaces.service.js'; +import { GithubModule } from '../projects/github/github.module'; +import { CloneJobsRepository } from './clone-jobs.repository'; +import { WorkspaceCloneService } from './workspace-clone.service'; +import { WorkspacePathService } from './workspace-path.service'; +import { WorkspacesController } from './workspaces.controller'; +import { WorkspacesService } from './workspaces.service'; /** * WorkspacesModule — per-user workspace surface. diff --git a/apps/backend/src/workspaces/workspaces.service.ts b/apps/backend/src/workspaces/workspaces.service.ts index d21fde9..8d556dd 100644 --- a/apps/backend/src/workspaces/workspaces.service.ts +++ b/apps/backend/src/workspaces/workspaces.service.ts @@ -1,17 +1,17 @@ import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common'; import { readdir, stat } from 'node:fs/promises'; import path from 'node:path'; -import { AppLogger } from '../common/app-logger.service.js'; -import { ExternalServiceError } from '../common/external/external-error.js'; -import { storageUnavailable } from '../storage/storage-unavailable.js'; -import { WorkspacePathService } from './workspace-path.service.js'; -import { readSubmodules, type SubmoduleEntry } from './workspace-submodules.util.js'; +import { AppLogger } from '../common/app-logger.service'; +import { ExternalServiceError } from '../common/external/external-error'; +import { storageUnavailable } from '../storage/storage-unavailable'; +import { WorkspacePathService } from './workspace-path.service'; +import { readSubmodules, type SubmoduleEntry } from './workspace-submodules.util'; -export interface WorkspaceTreeNode { +export type WorkspaceTreeNode = { path: string; type: 'file' | 'dir'; children?: WorkspaceTreeNode[]; -} +}; const MAX_DEPTH = 5; const MAX_ENTRIES = 200; diff --git a/apps/backend/tsconfig.json b/apps/backend/tsconfig.json index 84d47e3..89e2987 100644 --- a/apps/backend/tsconfig.json +++ b/apps/backend/tsconfig.json @@ -2,8 +2,7 @@ "extends": "../../tsconfig.base.json", "compilerOptions": { "target": "ES2023", - "module": "NodeNext", - "moduleResolution": "NodeNext", + "module": "CommonJS", "outDir": "dist", "rootDir": "src", "declaration": false, diff --git a/apps/backend/tsconfig.lint.json b/apps/backend/tsconfig.lint.json new file mode 100644 index 0000000..7d216d7 --- /dev/null +++ b/apps/backend/tsconfig.lint.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "../../" + }, + "include": ["src"] +} diff --git a/apps/frontend/app/(dashboard)/organizations/[id]/page.tsx b/apps/frontend/app/(dashboard)/organizations/[id]/page.tsx index ee98083..5c9fab9 100644 --- a/apps/frontend/app/(dashboard)/organizations/[id]/page.tsx +++ b/apps/frontend/app/(dashboard)/organizations/[id]/page.tsx @@ -23,7 +23,7 @@ import { useInvite } from '@/hooks/useInvite'; import { useProfile } from '@/hooks/useProfile'; import { ApiClientError, api } from '@/api/client'; import { getValidAccessToken } from '@/lib/auth-store'; -import type { OrgRole } from '@/api/types'; +import type { OrgRole } from '@devbox/contracts'; import { useI18n } from '@/i18n'; function shortId(id: string): string { diff --git a/apps/frontend/package.json b/apps/frontend/package.json index 83f45ec..e7ecfe8 100644 --- a/apps/frontend/package.json +++ b/apps/frontend/package.json @@ -15,6 +15,7 @@ "test": "bun test --isolate --pass-with-no-tests app src" }, "dependencies": { + "@devbox/contracts": "workspace:*", "@hookform/resolvers": "5.9.1", "@opencode-ai/sdk": "1.18.33", "@tanstack/react-query": "^5.104.1", diff --git a/apps/frontend/src/App.tsx b/apps/frontend/src/App.tsx index 527b686..e94d11e 100644 --- a/apps/frontend/src/App.tsx +++ b/apps/frontend/src/App.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; import { api, ApiClientError } from './api/client'; -import type { HealthResponse, SendChatResponse, Session } from './api/types'; +import type { HealthResponse, SendChatResponse, Session } from '@devbox/contracts'; export default function App() { const [health, setHealth] = useState(null); diff --git a/apps/frontend/src/api/client.ts b/apps/frontend/src/api/client.ts index 768fef7..1607481 100644 --- a/apps/frontend/src/api/client.ts +++ b/apps/frontend/src/api/client.ts @@ -1,29 +1,30 @@ import type { - AcceptInviteRequest, - AddMemberRequest, + AcceptInviteInput as AcceptInviteRequest, + AddMemberInput as AddMemberRequest, ApiError, AuthSession, AuthTokens, AuthUser, - CreateInviteRequest, - CreateOrganizationRequest, - CreateProjectRequest, + CreateInviteInput as CreateInviteRequest, + CreateOrganizationInput as CreateOrganizationRequest, + CreateProjectInput as CreateProjectRequest, HealthResponse, - InviteDto, - MemberDto, + Organization as OrganizationDto, + OrganizationInvite as InviteDto, + OrganizationMember as MemberDto, MessagesResponse, NpmRegistryStatusResponse, OpencodeKeyResult, OpencodeKeyStatus, OpencodeUsage, - OrganizationDto, - ProjectApiDto, + OrgRole, + Project as ProjectApiDto, RegistryCatalogResponse, SendChatResponse, Session, - UpdateMemberRoleRequest, - UpdateOrganizationRequest, -} from './types'; + UpdateMemberRoleInput as UpdateMemberRoleRequest, + UpdateOrganizationInput as UpdateOrganizationRequest, +} from '@devbox/contracts'; // Base URL resolution (Next.js App Router): // - process.env.NEXT_PUBLIC_API_URL is inlined at `next build` time. The literal diff --git a/apps/frontend/src/api/types.ts b/apps/frontend/src/api/types.ts index 6da320a..61ba045 100644 --- a/apps/frontend/src/api/types.ts +++ b/apps/frontend/src/api/types.ts @@ -1,260 +1,71 @@ /** - * Shared DTO contracts (frontend copy). - * Duplicated from apps/backend/src/contracts.ts — no cross-workspace imports. - * No business logic, only types. Zod omitted (not a dependency). + * @deprecated Import from '@devbox/contracts' instead — this module is a + * thin Forward-Only re-export kept for one release so existing imports keep + * compiling. It carries types only (no runtime schemas); the single source + * of truth for entities + zod v4 boundary schemas is packages/contracts + * (mirrors contracts/openapi.yaml field-for-field). + * Will be removed in the next release — do not add new exports here. + * + * Parity notes (frontend-additive preserved): + * - `ProjectApiDto` = package `Project` (includes optional `scope`: + * 'user' | 'org' — old caches without it stay valid). + * - `OrganizationDto` = package `Organization`, + * `MemberDto` = `OrganizationMember`, `InviteDto` = `OrganizationInvite`. + * - `*Request` aliases = package `*Input` (inferred from the + * backend-verbatim zod schemas, same shapes as the old local DTOs). */ -/** GET /health (unversioned liveness probe) */ -export interface HealthResponse { - status: 'ok'; - db: 'up' | 'down' | 'skipped'; - /** opencode server reachability: up | down */ - opencode: 'up' | 'down'; - /** docker registry reachability: up | down | skipped */ - registry: 'up' | 'down' | 'skipped'; - /** npm registry (Verdaccio) reachability: up | down | skipped */ - npmRegistry: 'up' | 'down' | 'skipped'; -} - -/** GET /api/v1/session */ -export interface Session { - id: string; - title: string; - /** ISO-8601 timestamp */ - createdAt: string; - model?: string; -} - -export type ChatRole = 'user' | 'assistant' | 'system'; - -export interface ChatMessage { - id: string; - sessionId: string; - role: ChatRole; - content: string; - /** ISO-8601 timestamp */ - createdAt: string; -} - -/** POST /api/v1/chat request body */ -export interface SendChatRequest { - sessionId?: string; - message: string; -} - -/** POST /api/v1/chat response */ -export interface SendChatResponse { - sessionId: string; - message: ChatMessage; -} - -/** GET /api/v1/messages?sessionId=… */ -export interface MessagesResponse { - sessionId: string; - messages: ChatMessage[]; -} - -/** GET /api/v1/repos + GET /api/v1/repos/:userSpace — readonly git-repo registry */ -export interface RepoEntry { - userSpace: string; - name: string; - /** Path relative to REPOS_ROOT, e.g. "alice/workspace/demo" */ - path: string; - /** ISO-8601 mtime of the repo directory */ - updatedAt: string; -} - -/** GET /api/v1/registry/catalog — live Docker Registry /v2/_catalog proxy. - * 200 → { repositories: string[] }; unconfigured/unreachable → 503 - * EXTERNAL_UNAVAILABLE + Retry-After (no mock 200s). */ -export interface RegistryCatalogResponse { - repositories: string[]; -} - -/** GET /api/v1/registry/npm/status — live Verdaccio /-/ping reachability. - * 200 → { status: 'up', url, scope }; unconfigured/unreachable → 503 - * EXTERNAL_UNAVAILABLE + Retry-After (no mock 200s, token never in payload). */ -export interface NpmRegistryStatusResponse { - status: 'up'; - url: string; - scope: string; -} - -/** Unified error envelope for all /api/v1/* routes */ -export interface ApiError { - code: string; - message: string; - correlationId: string; -} - -/** POST /api/v1/auth/register + login response user (never carries passwordHash) */ -export interface AuthUser { - id: string; - firstName: string; - lastName: string; - email: string; - provider: 'local' | 'sso-oauth' | 'github-app'; - /** ISO-8601 timestamp */ - createdAt: string; -} - -/** Token pair (short-lived access + rotating refresh). */ -export interface AuthTokens { - accessToken: string; - refreshToken: string; - tokenType: 'bearer'; - /** Access lifetime in seconds. */ - expiresIn: number; -} - -/** POST /api/v1/auth/register + login response (user + tokens). */ -export interface AuthSession extends AuthTokens { - user: AuthUser; -} - -/** Projects — mirrors backend `Project` + DTOs (apps/backend/src/projects/*) */ -export type ProjectScope = 'user' | 'org'; - -export interface ProjectApiDto { - id: string; - name: string; - description: string | null; - githubOwner: string | null; - githubRepo: string | null; - githubBranch: string | null; - githubUrl: string | null; - ownerId: string | null; - createdAt: string; - updatedAt: string; - /** Computed flag (no DB column): true when the on-disk git repo is missing/invalid. */ - corrupted: boolean; - /** Machine reason when corrupted (missing-dir, no-git, rev-parse-failed, storage-unconfigured, …). */ - corruptedReason: string | null; - /** Disk-home scope (REPOS_ROOT users//… vs orgs//…); optional — old caches stay valid. */ - scope?: ProjectScope; -} - -export interface CreateProjectRequest { - name: string; - description?: string; - githubOwner?: string; - githubRepo?: string; - githubBranch?: string; - githubUrl?: string; - ownerId?: string; -} - -/** - * Organizations — mirrors contracts/openapi.yaml (additive, verbatim). - * /api/v1/organizations (CRUD, members only), /organizations/:id/members - * (GET/POST; PATCH /members/:userId role; DELETE /members/:userId), - * POST /organizations/:id/invites (single-use token + TTL), - * POST /organizations/invites/accept {token}, - * POST/DELETE /organizations/:id/projects/:projectId. - */ -export interface OrganizationDto { - id: string; - name: string; - description: string | null; - ownerId: string | null; - isPrivate: boolean; - /** ISO-8601 timestamp */ - createdAt: string; - /** ISO-8601 timestamp */ - updatedAt: string; -} - -export interface CreateOrganizationRequest { - name: string; - description?: string; - isPrivate?: boolean; -} - -export interface UpdateOrganizationRequest { - name?: string; - description?: string | null; - isPrivate?: boolean; -} - -export type OrgRole = 'maintainer' | 'user'; - -export interface MemberDto { - orgId: string; - userId: string; - role: OrgRole; - /** ISO-8601 timestamp */ - createdAt: string; -} - -export interface AddMemberRequest { - userId: string; - role?: OrgRole; -} - -export interface UpdateMemberRoleRequest { - role: OrgRole; -} - -/** Single-use bearer token — returned ONCE, never logged, TTL ORG_INVITE_TTL_SEC. */ -export interface InviteDto { - token: string; - orgId: string; - role: OrgRole; - /** ISO-8601 timestamp */ - expiresAt: string; -} - -export interface CreateInviteRequest { - role?: OrgRole; -} - -export interface AcceptInviteRequest { - token: string; -} - -/** - * Per-user OpenCode keys — mirrors backend contracts.ts (additive, verbatim). - * PUT /api/v1/key (own key, encrypted at rest, never echoed), - * DELETE /api/v1/key (idempotent { ok }), - * GET /api/v1/key (existence only), GET /api/v1/usage - * (live upstream { balance, usage, updatedAt }). - */ -export interface OpencodeKeyResult { - ok: boolean; - /** ISO-8601 timestamp */ - updatedAt: string; -} - -export interface OpencodeKeyDeleteResult { - ok: boolean; -} - -export interface OpencodeKeyStatus { - configured: boolean; - /** ISO-8601 timestamp (present only when configured). */ - updatedAt?: string; -} - -export interface OpencodeUsage { - /** Legacy pay-as-you-go fields — present only for legacy upstream payloads. */ - balance?: number; - /** Legacy pay-as-you-go total — present only for legacy upstream payloads. */ - usage?: number; - /** ISO-8601 time of the upstream response */ - updatedAt: string; - /** - * Zen Go windows mapped to used/limit (`percent` → `{ used: percent, limit: 100 }`). - * `rolling` is the Zen 5-hour window; legacy `daily` has no Zen equivalent. - * Present only when upstream carries finite numbers — never derived. - */ - rolling?: OpencodeLimitBucket; - daily?: OpencodeLimitBucket; - weekly?: OpencodeLimitBucket; - monthly?: OpencodeLimitBucket; -} - -/** Single usage bucket — real `used/limit` pair from upstream (no derivation). */ -export interface OpencodeLimitBucket { - used: number; - limit: number; -} +export type { + AcceptInviteInput, + AddMemberInput, + ApiError, + AuthSession, + AuthTokens, + AuthUser, + ChatMessage, + ChatRole, + CreateInviteInput, + CreateOrganizationInput, + CreateProjectInput, + HealthResponse, + LoginInput, + MessagesResponse, + NpmRegistryStatusResponse, + OpencodeKeyDeleteResult, + OpencodeKeyInput, + OpencodeKeyResult, + OpencodeKeyStatus, + OpencodeLimitBucket, + OpencodeUsage, + Organization, + OrganizationInvite, + OrganizationMember, + OrgRole, + Project, + ProjectScope, + RefreshInput, + RegisterInput, + RegistryCatalogResponse, + RepoEntry, + SendChatRequest, + SendChatResponse, + Session, + UpdateMeInput, + UpdateMemberRoleInput, + UpdateOrganizationInput, + UpdateProjectInput, +} from '@devbox/contracts'; + +export type { + Project as ProjectApiDto, + CreateProjectInput as CreateProjectRequest, + Organization as OrganizationDto, + CreateOrganizationInput as CreateOrganizationRequest, + UpdateOrganizationInput as UpdateOrganizationRequest, + OrganizationMember as MemberDto, + AddMemberInput as AddMemberRequest, + UpdateMemberRoleInput as UpdateMemberRoleRequest, + OrganizationInvite as InviteDto, + CreateInviteInput as CreateInviteRequest, + AcceptInviteInput as AcceptInviteRequest, +} from '@devbox/contracts'; diff --git a/apps/frontend/src/components/chat/chat-input.tsx b/apps/frontend/src/components/chat/chat-input.tsx index 874e35d..b9270c8 100644 --- a/apps/frontend/src/components/chat/chat-input.tsx +++ b/apps/frontend/src/components/chat/chat-input.tsx @@ -4,12 +4,12 @@ import { useState, type FormEvent, type KeyboardEvent } from 'react'; import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@web2bizz/ui/components'; import { useI18n } from '../../i18n'; -export interface ChatInputProps { +export type ChatInputProps = { onSend: (text: string) => void | Promise; onStop?: () => void; sending?: boolean; placeholder?: string; -} +}; /** * Kit composer (`components` InputGroup): outward `ChatInputProps` diff --git a/apps/frontend/src/components/chat/chat-message.tsx b/apps/frontend/src/components/chat/chat-message.tsx index deb5ed5..ff7459c 100644 --- a/apps/frontend/src/components/chat/chat-message.tsx +++ b/apps/frontend/src/components/chat/chat-message.tsx @@ -5,11 +5,11 @@ import { Bubble, BubbleContent, Message, MessageContent, MessageHeader } from '@ import type { ChatMessage } from '../../hooks/useChat'; import { useI18n } from '../../i18n'; -interface TextBlock { +type TextBlock = { kind: 'text' | 'code'; lang: string; body: string; -} +}; /** Split ` ```lang … ``` ` fences — plain paragraphs stay

, code goes

. */
 function splitBlocks(text: string): TextBlock[] {
diff --git a/apps/frontend/src/components/chat/chat-window.tsx b/apps/frontend/src/components/chat/chat-window.tsx
index 40179f2..b15ed00 100644
--- a/apps/frontend/src/components/chat/chat-window.tsx
+++ b/apps/frontend/src/components/chat/chat-window.tsx
@@ -8,14 +8,14 @@ import type { ChatMessage } from '../../hooks/useChat';
 import { useI18n } from '../../i18n';
 import { ChatMessageRow } from './chat-message';
 
-export interface ChatWindowProps {
+export type ChatWindowProps = {
   messages: ChatMessage[];
   streamingText: string;
   loading?: boolean;
   sending?: boolean;
   error?: string | null;
   onRetry?: () => void;
-}
+};
 
 const STICK_THRESHOLD_PX = 48;
 
diff --git a/apps/frontend/src/components/dashboard-shell.tsx b/apps/frontend/src/components/dashboard-shell.tsx
index 486f961..d85a01a 100644
--- a/apps/frontend/src/components/dashboard-shell.tsx
+++ b/apps/frontend/src/components/dashboard-shell.tsx
@@ -10,12 +10,12 @@ import { useI18n } from '../i18n';
 import { LanguageSwitcher } from './language-switcher';
 import { HeaderProfileDropdown } from './profile-dropdown';
 
-export interface DashboardHeaderBreadcrumb {
+export type DashboardHeaderBreadcrumb = {
   label: string;
   href?: string;
-}
+};
 
-export interface DashboardHeaderProps {
+export type DashboardHeaderProps = {
   /** Optional page title rendered left of the controls. */
   title?: ReactNode;
   /** Optional breadcrumb trail (flat URLs, no locale segment). */
@@ -24,7 +24,7 @@ export interface DashboardHeaderProps {
   user?: ReactNode;
   /** Optional page-level actions rendered before theme/language controls. */
   actions?: ReactNode;
-}
+};
 
 export type DashboardShellProps = {
   children: ReactNode;
diff --git a/apps/frontend/src/components/layout/Content.tsx b/apps/frontend/src/components/layout/Content.tsx
index d14234a..1b265cc 100644
--- a/apps/frontend/src/components/layout/Content.tsx
+++ b/apps/frontend/src/components/layout/Content.tsx
@@ -3,14 +3,14 @@
 import type { ReactNode } from 'react';
 import { EmptyState, ErrorState, LoadingState } from '../states';
 
-export interface ContentEmpty {
+export type ContentEmpty = {
   title: string;
   description: string;
   actionLabel?: string;
   onAction?: () => void;
-}
+};
 
-export interface ContentProps {
+export type ContentProps = {
   children: ReactNode;
   /** When true — LoadingState skeleton grid (from states.tsx). */
   isLoading?: boolean;
@@ -23,7 +23,7 @@ export interface ContentProps {
   /** When true + `empty` provided — EmptyState card (from states.tsx). */
   isEmpty?: boolean;
   empty?: ContentEmpty;
-}
+};
 
 /**
  * Full-width page content: semantic 
+ full-width .page-inner diff --git a/apps/frontend/src/components/layout/Sidebar.tsx b/apps/frontend/src/components/layout/Sidebar.tsx index 1caa174..bce9c28 100644 --- a/apps/frontend/src/components/layout/Sidebar.tsx +++ b/apps/frontend/src/components/layout/Sidebar.tsx @@ -7,10 +7,10 @@ import { useState, type KeyboardEvent } from 'react'; import { Button } from '@web2bizz/ui/components'; import { useI18n } from '../../i18n'; -export interface SidebarNavItem { +export type SidebarNavItem = { href: string; label: string; -} +}; /** * Brand row: logo PNG + DevBox wordmark + console subtitle. @@ -194,11 +194,11 @@ export function SidebarNav({ onNavigate }: { onNavigate?: () => void }) { ); } -export interface SidebarProps { +export type SidebarProps = { /** Mobile drawer open state (desktop aside is always visible via CSS). */ open?: boolean; onClose?: () => void; -} +}; /** * Visible vertical sidebar: diff --git a/apps/frontend/src/components/organizations/create-organization-dialog.tsx b/apps/frontend/src/components/organizations/create-organization-dialog.tsx index 9696883..805dfda 100644 --- a/apps/frontend/src/components/organizations/create-organization-dialog.tsx +++ b/apps/frontend/src/components/organizations/create-organization-dialog.tsx @@ -21,13 +21,13 @@ import { import { createOrganizationSchema, type CreateOrganizationInput } from '../../lib/organization-schemas'; import { useI18n } from '../../i18n'; -export interface CreateOrganizationDialogProps { +export type CreateOrganizationDialogProps = { open: boolean; onOpenChange: (open: boolean) => void; onCreate: (name: string) => Promise; creating?: boolean; trigger?: React.ReactNode; -} +}; function getZodErrorMessage(code: string, t: ReturnType['t']): string { switch (code) { diff --git a/apps/frontend/src/components/projects/create-project-dialog.tsx b/apps/frontend/src/components/projects/create-project-dialog.tsx index 4ff5a70..3a5aee1 100644 --- a/apps/frontend/src/components/projects/create-project-dialog.tsx +++ b/apps/frontend/src/components/projects/create-project-dialog.tsx @@ -21,13 +21,13 @@ import { import { createProjectSchema, type CreateProjectInput } from '../../lib/project-schemas'; import { useI18n } from '../../i18n'; -export interface CreateProjectDialogProps { +export type CreateProjectDialogProps = { open: boolean; onOpenChange: (open: boolean) => void; onCreate: (name: string) => Promise; creating?: boolean; trigger?: React.ReactNode; -} +}; function getZodErrorMessage(code: string, t: ReturnType['t']): string { switch (code) { diff --git a/apps/frontend/src/components/registry-hub.tsx b/apps/frontend/src/components/registry-hub.tsx index 8191414..98d5bc3 100644 --- a/apps/frontend/src/components/registry-hub.tsx +++ b/apps/frontend/src/components/registry-hub.tsx @@ -8,11 +8,11 @@ import { CardTitle, } from '@web2bizz/ui/components'; -export interface RegistryHubItem { +export type RegistryHubItem = { href: string; title: string; description: string; -} +}; /** * Reusable hub grid: Card per entry with a direct Next Link. diff --git a/apps/frontend/src/features/usage/usage-section.tsx b/apps/frontend/src/features/usage/usage-section.tsx index bb5eb22..b3f81c4 100644 --- a/apps/frontend/src/features/usage/usage-section.tsx +++ b/apps/frontend/src/features/usage/usage-section.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { Progress, Skeleton } from '@web2bizz/ui/components'; import { EmptyState, ErrorState } from '../../components/states'; -import type { OpencodeLimitBucket } from '../../api/types'; +import type { OpencodeLimitBucket } from '@devbox/contracts'; import { useI18n } from '../../i18n'; import { useUsage } from '../../hooks/useUsage'; import { ApiKeyDialog } from './api-key-dialog'; diff --git a/apps/frontend/src/features/usage/usage-status.ts b/apps/frontend/src/features/usage/usage-status.ts index d94d464..b3962bb 100644 --- a/apps/frontend/src/features/usage/usage-status.ts +++ b/apps/frontend/src/features/usage/usage-status.ts @@ -3,10 +3,10 @@ import { ApiClientError } from '../../api/client'; import { formatApiErrorWithId } from '../../lib/format-error'; -export interface UsageStrings { +export type UsageStrings = { sessionExpired: string; unexpected: string; -} +}; export type UsageStatus = | { kind: 'ready' } diff --git a/apps/frontend/src/hooks/__tests__/orgScopeMapping.test.ts b/apps/frontend/src/hooks/__tests__/orgScopeMapping.test.ts index 2022fac..7f3e915 100644 --- a/apps/frontend/src/hooks/__tests__/orgScopeMapping.test.ts +++ b/apps/frontend/src/hooks/__tests__/orgScopeMapping.test.ts @@ -5,7 +5,7 @@ * scope (old caches) leaves scope undefined — old imports never break. */ import { describe, expect, test } from 'bun:test'; -import type { ProjectApiDto } from '../../api/types'; +import type { Project as ProjectApiDto } from '@devbox/contracts'; import { mapApiToProject as mapFromList } from '../useProjects'; import { mapApiToProject as mapFromDetail } from '../useProject'; diff --git a/apps/frontend/src/hooks/useAiProviders.ts b/apps/frontend/src/hooks/useAiProviders.ts index fe82351..7b086fc 100644 --- a/apps/frontend/src/hooks/useAiProviders.ts +++ b/apps/frontend/src/hooks/useAiProviders.ts @@ -8,7 +8,7 @@ import type { AiProvider } from '../lib/types'; import { useI18n } from '../i18n'; import { aiProvidersQueryKey } from './query-keys'; -export interface UseAiProvidersResult { +export type UseAiProvidersResult = { providers: AiProvider[]; loading: boolean; error: string | null; @@ -18,7 +18,7 @@ export interface UseAiProvidersResult { configure: (id: string) => void; reload: () => void; dismiss: () => void; -} +}; /** * Shared fetch — GET /api/opencode/config/providers without auth (the diff --git a/apps/frontend/src/hooks/useChat.ts b/apps/frontend/src/hooks/useChat.ts index fd080e8..73289ed 100644 --- a/apps/frontend/src/hooks/useChat.ts +++ b/apps/frontend/src/hooks/useChat.ts @@ -5,22 +5,22 @@ import { opencode, toErrorMessage } from '../api/opencode-client'; import type { OpencodeEvent } from '../api/opencode-client'; import { useI18n } from '../i18n'; -export interface ChatMessage { +export type ChatMessage = { id: string; role: 'user' | 'assistant'; text: string; -} +}; -export interface UseChatOptions { +export type UseChatOptions = { /** Existing opencode session to scope the chat to (session = chat). */ sessionId?: string; /** Opencode working directory, forwarded as `?directory=`. */ directory?: string; /** DevBox project id (prj-*) — UI-only until backend maps project → directory. */ projectId?: string; -} +}; -export interface UseChatResult { +export type UseChatResult = { messages: ChatMessage[]; streamingText: string; loading: boolean; @@ -32,7 +32,7 @@ export interface UseChatResult { send: (text: string) => Promise; stop: () => void; reload: () => void; -} +}; const BASE_DELAY_MS = 1000; const MAX_DELAY_MS = 15000; diff --git a/apps/frontend/src/hooks/useInvite.ts b/apps/frontend/src/hooks/useInvite.ts index 024ad78..ebac814 100644 --- a/apps/frontend/src/hooks/useInvite.ts +++ b/apps/frontend/src/hooks/useInvite.ts @@ -5,12 +5,12 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import { getValidAccessToken } from '../lib/auth-store'; -import type { InviteDto, MemberDto, OrgRole } from '../api/types'; +import type { OrganizationInvite as InviteDto, OrganizationMember as MemberDto, OrgRole } from '@devbox/contracts'; import { useI18n } from '../i18n'; import { ORGANIZATIONS_QUERY_KEY } from './useOrganizations'; import { orgMembersQueryKey } from './useOrgMembers'; -export interface UseInviteResult { +export type UseInviteResult = { minted: InviteDto | null; minting: boolean; mintError: string | null; @@ -23,7 +23,7 @@ export interface UseInviteResult { /** Accept by token. 404 (replay/unknown) and 410 (expired) map to i18n strings. */ accept: (token: string) => Promise; reset: () => void; -} +}; /** * Invite flow hook. diff --git a/apps/frontend/src/hooks/useLogin.ts b/apps/frontend/src/hooks/useLogin.ts index e519d49..42dc981 100644 --- a/apps/frontend/src/hooks/useLogin.ts +++ b/apps/frontend/src/hooks/useLogin.ts @@ -8,14 +8,14 @@ import { setSession, signOutAndRedirect } from '../lib/auth-store'; import type { MockUser } from '../lib/mocks/auth'; import { useI18n } from '../i18n'; -export interface UseLoginResult { +export type UseLoginResult = { user: MockUser | null; loading: boolean; error: string | null; login: (email: string, password: string) => Promise; logout: () => void; retry: () => void; -} +}; /** * Real login hook — POST /api/v1/auth/login (contract unchanged: diff --git a/apps/frontend/src/hooks/useNpm.ts b/apps/frontend/src/hooks/useNpm.ts index e1584c4..1b69a69 100644 --- a/apps/frontend/src/hooks/useNpm.ts +++ b/apps/frontend/src/hooks/useNpm.ts @@ -8,13 +8,13 @@ import type { NpmPackageItem } from '../lib/types'; import { useI18n } from '../i18n'; import { NPM_QUERY_KEY } from './query-keys'; -export interface UseNpmResult { +export type UseNpmResult = { packages: NpmPackageItem[]; loading: boolean; error: string | null; isEmpty: boolean; reload: () => void; -} +}; /** * Shared fetch — GET /api/v1/registry/npm/status without a token (public diff --git a/apps/frontend/src/hooks/useOpencodeChat.ts b/apps/frontend/src/hooks/useOpencodeChat.ts index 0c5a154..0d45e12 100644 --- a/apps/frontend/src/hooks/useOpencodeChat.ts +++ b/apps/frontend/src/hooks/useOpencodeChat.ts @@ -9,7 +9,7 @@ type MessagesData = NonNullable< >; export type OpencodeChatMessage = MessagesData[number]; -export interface UseOpencodeChatResult { +export type UseOpencodeChatResult = { messages: OpencodeChatMessage[]; loading: boolean; sending: boolean; @@ -17,7 +17,7 @@ export interface UseOpencodeChatResult { isEmpty: boolean; send: (text: string) => Promise; reload: () => void; -} +}; /** * Session messages + send through the backend reverse-proxy (same sdk). diff --git a/apps/frontend/src/hooks/useOpencodeEvents.ts b/apps/frontend/src/hooks/useOpencodeEvents.ts index 705ef36..6bf2a2b 100644 --- a/apps/frontend/src/hooks/useOpencodeEvents.ts +++ b/apps/frontend/src/hooks/useOpencodeEvents.ts @@ -6,12 +6,12 @@ import { useI18n } from '../i18n'; export type OpencodeStreamStatus = 'connecting' | 'live' | 'reconnecting' | 'error'; -export interface UseOpencodeEventsResult { +export type UseOpencodeEventsResult = { events: OpencodeEvent[]; status: OpencodeStreamStatus; error: string | null; reconnect: () => void; -} +}; const MAX_EVENTS = 50; const BASE_DELAY_MS = 1000; diff --git a/apps/frontend/src/hooks/useOpencodeSessions.ts b/apps/frontend/src/hooks/useOpencodeSessions.ts index d8b73de..b5ef197 100644 --- a/apps/frontend/src/hooks/useOpencodeSessions.ts +++ b/apps/frontend/src/hooks/useOpencodeSessions.ts @@ -5,7 +5,7 @@ import { opencode, toErrorMessage } from '../api/opencode-client'; import type { Session } from '@opencode-ai/sdk/client'; import { useI18n } from '../i18n'; -export interface UseOpencodeSessionsResult { +export type UseOpencodeSessionsResult = { sessions: Session[]; loading: boolean; error: string | null; @@ -15,7 +15,7 @@ export interface UseOpencodeSessionsResult { creating: boolean; abort: (id: string) => Promise; abortingId: string | null; -} +}; /** * Live session list through the backend reverse-proxy diff --git a/apps/frontend/src/hooks/useOrgMembers.ts b/apps/frontend/src/hooks/useOrgMembers.ts index 98b9243..8d11409 100644 --- a/apps/frontend/src/hooks/useOrgMembers.ts +++ b/apps/frontend/src/hooks/useOrgMembers.ts @@ -5,12 +5,12 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import { getValidAccessToken } from '../lib/auth-store'; -import type { MemberDto, OrgRole } from '../api/types'; +import type { OrganizationMember as MemberDto, OrgRole } from '@devbox/contracts'; import { useI18n } from '../i18n'; export const orgMembersQueryKey = (orgId: string) => ['organization-members', orgId] as const; -export interface UseOrgMembersResult { +export type UseOrgMembersResult = { members: MemberDto[]; loading: boolean; error: string | null; @@ -21,7 +21,7 @@ export interface UseOrgMembersResult { removeMember: (userId: string) => Promise; mutating: boolean; mutationError: string | null; -} +}; /** * Organization members hook (etalon: useProjects mutation pattern). diff --git a/apps/frontend/src/hooks/useOrganization.ts b/apps/frontend/src/hooks/useOrganization.ts index 158cb47..55bd310 100644 --- a/apps/frontend/src/hooks/useOrganization.ts +++ b/apps/frontend/src/hooks/useOrganization.ts @@ -5,13 +5,13 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import { getValidAccessToken } from '../lib/auth-store'; -import type { OrganizationDto, UpdateOrganizationRequest } from '../api/types'; +import type { Organization as OrganizationDto, UpdateOrganizationInput as UpdateOrganizationRequest } from '@devbox/contracts'; import { useI18n } from '../i18n'; import { ORGANIZATIONS_QUERY_KEY } from './useOrganizations'; export const organizationQueryKey = (id: string) => ['organization', id] as const; -export interface UseOrganizationResult { +export type UseOrganizationResult = { organization: OrganizationDto | null; loading: boolean; error: string | null; @@ -24,7 +24,7 @@ export interface UseOrganizationResult { remove: () => Promise; removing: boolean; removeError: string | null; -} +}; /** * Single-organization hook (etalon: useProject). diff --git a/apps/frontend/src/hooks/useOrganizations.ts b/apps/frontend/src/hooks/useOrganizations.ts index add9599..3bedbe2 100644 --- a/apps/frontend/src/hooks/useOrganizations.ts +++ b/apps/frontend/src/hooks/useOrganizations.ts @@ -5,12 +5,12 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import { getValidAccessToken } from '../lib/auth-store'; -import type { OrganizationDto } from '../api/types'; +import type { Organization as OrganizationDto } from '@devbox/contracts'; import { useI18n } from '../i18n'; export const ORGANIZATIONS_QUERY_KEY = ['organizations'] as const; -export interface UseOrganizationsResult { +export type UseOrganizationsResult = { organizations: OrganizationDto[]; loading: boolean; error: string | null; @@ -19,7 +19,7 @@ export interface UseOrganizationsResult { createOrganization: (name: string) => Promise; creating: boolean; createError: string | null; -} +}; /** * Organizations list hook (etalon: useProjects). diff --git a/apps/frontend/src/hooks/useProfile.ts b/apps/frontend/src/hooks/useProfile.ts index 2214c9a..7a92e21 100644 --- a/apps/frontend/src/hooks/useProfile.ts +++ b/apps/frontend/src/hooks/useProfile.ts @@ -3,14 +3,14 @@ import { useCallback, useMemo, useState } from 'react'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; -import type { AuthUser } from '../api/types'; +import type { AuthUser } from '@devbox/contracts'; import { formatApiError } from '../lib/format-error'; import { getValidAccessToken, refreshAccessToken } from '../lib/auth-store'; import { PROFILE_QUERY_KEY } from './query-keys'; import type { Profile } from '../lib/types'; import { useI18n } from '../i18n'; -export interface UseProfileResult { +export type UseProfileResult = { profile: Profile | null; loading: boolean; error: string | null; @@ -19,7 +19,7 @@ export interface UseProfileResult { update: (patch: Pick & Partial>) => Promise; reload: () => void; dismiss: () => void; -} +}; function toProfile(user: AuthUser): Profile { return { diff --git a/apps/frontend/src/hooks/useProject.ts b/apps/frontend/src/hooks/useProject.ts index 10c3471..38cef5e 100644 --- a/apps/frontend/src/hooks/useProject.ts +++ b/apps/frontend/src/hooks/useProject.ts @@ -5,7 +5,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import type { Project } from '../lib/types'; -import type { ProjectApiDto } from '../api/types'; +import type { Project as ProjectApiDto } from '@devbox/contracts'; import { useI18n } from '../i18n'; export function mapApiToProject(dto: ProjectApiDto): Project { @@ -28,13 +28,13 @@ export function mapApiToProject(dto: ProjectApiDto): Project { export const projectQueryKey = (id: string) => ['project', id] as const; -export interface UseProjectResult { +export type UseProjectResult = { project: Project | null; loading: boolean; error: string | null; notFound: boolean; reload: () => void; -} +}; /** * Production-ready single-project hook backed by TanStack Query. diff --git a/apps/frontend/src/hooks/useProjects.ts b/apps/frontend/src/hooks/useProjects.ts index 6ae3b1d..91f187d 100644 --- a/apps/frontend/src/hooks/useProjects.ts +++ b/apps/frontend/src/hooks/useProjects.ts @@ -5,7 +5,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import type { Project } from '../lib/types'; -import type { ProjectApiDto } from '../api/types'; +import type { Project as ProjectApiDto } from '@devbox/contracts'; import { useI18n } from '../i18n'; export const PROJECTS_QUERY_KEY = ['projects'] as const; @@ -28,7 +28,7 @@ export function mapApiToProject(dto: ProjectApiDto): Project { }; } -export interface UseProjectsResult { +export type UseProjectsResult = { projects: Project[]; loading: boolean; error: string | null; @@ -37,7 +37,7 @@ export interface UseProjectsResult { createProject: (name: string) => Promise; creating: boolean; createError: string | null; -} +}; /** * Production-ready list hook backed by TanStack Query. diff --git a/apps/frontend/src/hooks/useRegistries.ts b/apps/frontend/src/hooks/useRegistries.ts index dbb9fe5..f4f63a0 100644 --- a/apps/frontend/src/hooks/useRegistries.ts +++ b/apps/frontend/src/hooks/useRegistries.ts @@ -8,13 +8,13 @@ import type { RegistryItem } from '../lib/types'; import { useI18n } from '../i18n'; import { REGISTRIES_QUERY_KEY } from './query-keys'; -export interface UseRegistriesResult { +export type UseRegistriesResult = { registries: RegistryItem[]; loading: boolean; error: string | null; isEmpty: boolean; reload: () => void; -} +}; /** * Shared fetch — GET /api/v1/registry/catalog without a token (public diff --git a/apps/frontend/src/hooks/useSecrets.ts b/apps/frontend/src/hooks/useSecrets.ts index 35234cb..ce35513 100644 --- a/apps/frontend/src/hooks/useSecrets.ts +++ b/apps/frontend/src/hooks/useSecrets.ts @@ -7,7 +7,7 @@ import { MOCK_SECRETS, MOCK_SECRET_VALUES } from '../lib/mocks/secrets'; import type { SecretItem } from '../lib/types'; import { useI18n } from '../i18n'; -export interface UseSecretsResult { +export type UseSecretsResult = { secrets: SecretItem[]; loading: boolean; error: string | null; @@ -19,7 +19,7 @@ export interface UseSecretsResult { copy: (id: string) => Promise; remove: (id: string) => void; reload: () => void; -} +}; /** * Mock secrets hook: list + reveal/hide + copy + delete (local only). diff --git a/apps/frontend/src/hooks/useUsage.ts b/apps/frontend/src/hooks/useUsage.ts index d1163ea..69c3c81 100644 --- a/apps/frontend/src/hooks/useUsage.ts +++ b/apps/frontend/src/hooks/useUsage.ts @@ -3,7 +3,7 @@ import { useCallback, useMemo } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; -import type { OpencodeUsage } from '../api/types'; +import type { OpencodeUsage } from '@devbox/contracts'; import { getValidAccessToken, refreshAccessToken } from '../lib/auth-store'; import { USAGE_QUERY_KEY } from './query-keys'; import { useI18n } from '../i18n'; @@ -15,7 +15,7 @@ import { type UsageStatus, } from '../features/usage/usage-status'; -export interface UseUsageResult { +export type UseUsageResult = { usage: OpencodeUsage | null; loading: boolean; error: string | null; @@ -28,7 +28,7 @@ export interface UseUsageResult { upstreamDown: boolean; upstreamUnavailable: boolean; reload: () => void; -} +}; async function fetchUsage(): Promise { const token = await getValidAccessToken(); diff --git a/apps/frontend/src/hooks/useUser.ts b/apps/frontend/src/hooks/useUser.ts index 012016e..aca3a0b 100644 --- a/apps/frontend/src/hooks/useUser.ts +++ b/apps/frontend/src/hooks/useUser.ts @@ -5,12 +5,12 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'; import { ApiClientError, api } from '../api/client'; import { formatApiError } from '../lib/format-error'; import { getValidAccessToken } from '../lib/auth-store'; -import type { AuthUser } from '../api/types'; +import type { AuthUser } from '@devbox/contracts'; import { useI18n } from '../i18n'; export const userQueryKey = (id: string) => ['user', id] as const; -export interface UseUserResult { +export type UseUserResult = { user: AuthUser | null; loading: boolean; error: string | null; @@ -18,7 +18,7 @@ export interface UseUserResult { /** True when the backend refused with 403 (someone else's profile — never indexed). */ forbidden: boolean; reload: () => void; -} +}; /** * Single-user hook — GET /api/v1/users/:id (own profile only). diff --git a/apps/frontend/src/i18n/dictionaries/types.ts b/apps/frontend/src/i18n/dictionaries/types.ts index 2c31251..bbbc8b2 100644 --- a/apps/frontend/src/i18n/dictionaries/types.ts +++ b/apps/frontend/src/i18n/dictionaries/types.ts @@ -3,7 +3,7 @@ * Cookie-only approach: flat URLs (/login, /projects, …) stay untouched, * no `[locale]` segment, no middleware rewrite. Default locale `en`. */ -export interface Dictionary { +export type Dictionary = { metadata: { title: string; description: string; @@ -349,4 +349,4 @@ export interface Dictionary { notFoundDesc: string; back: string; }; -} +}; diff --git a/apps/frontend/src/i18n/index.tsx b/apps/frontend/src/i18n/index.tsx index 9455533..2ebea1e 100644 --- a/apps/frontend/src/i18n/index.tsx +++ b/apps/frontend/src/i18n/index.tsx @@ -73,11 +73,11 @@ function readStoredLocale(): Locale { return DEFAULT_LOCALE; } -interface I18nContextValue { +type I18nContextValue = { locale: Locale; setLocale: (next: Locale) => void; t: Dictionary; -} +}; const I18nContext = createContext({ locale: DEFAULT_LOCALE, diff --git a/apps/frontend/src/lib/auth-schemas.ts b/apps/frontend/src/lib/auth-schemas.ts index ab04f7b..2097076 100644 --- a/apps/frontend/src/lib/auth-schemas.ts +++ b/apps/frontend/src/lib/auth-schemas.ts @@ -1,31 +1,17 @@ -import { z } from 'zod'; - /** - * Client-side auth validation (mirrors backend register/login rules so - * typos are caught before the request; server 400/409 mapping in - * register-field-errors stays as the fallback for backend rejections). + * Client auth schemas — re-exported from '@devbox/contracts' (single source). + * + * Package `loginSchema`/`registerSchema` are backend-verbatim + * (trim-first email regex, name trim/min/max, password min/max) so + * client pre-submit checks match server 400s; `parseRegisterFieldErrors` + * stays as the server-fallback mapper. zod v4 + @hookform/resolvers 5.9.1 + * share the same zod 4.6.5 instance, so `zodResolver(loginSchema)` keeps + * working with no thin wrapper. * - * Call sites pass already-trimmed email (the page trims on submit and the - * hook trims defensively); firstName/lastName trim inside the schema so - * whitespace-only names fail `min(1)`. + * @deprecated Import from '@devbox/contracts' directly in new code — + * this module is a Forward-Only alias kept so `@/lib/auth-schemas` + * imports keep compiling. */ -export const loginSchema = z.object({ - email: z.email({ error: 'invalid_email' }), - password: z.string({ error: 'required' }).min(8, { error: 'password_min' }), -}); - -export const registerSchema = loginSchema.extend({ - firstName: z - .string({ error: 'required' }) - .trim() - .min(1, { error: 'name_required' }) - .max(100, { error: 'name_too_long' }), - lastName: z - .string({ error: 'required' }) - .trim() - .min(1, { error: 'name_required' }) - .max(100, { error: 'name_too_long' }), -}); -export type LoginInput = z.infer; -export type RegisterInput = z.infer; +export { loginSchema, registerSchema } from '@devbox/contracts'; +export type { LoginInput, RegisterInput } from '@devbox/contracts'; diff --git a/apps/frontend/src/lib/auth-store.ts b/apps/frontend/src/lib/auth-store.ts index ef275af..c5ec371 100644 --- a/apps/frontend/src/lib/auth-store.ts +++ b/apps/frontend/src/lib/auth-store.ts @@ -1,5 +1,5 @@ import { api } from '../api/client'; -import type { AuthSession } from '../api/types'; +import type { AuthSession } from '@devbox/contracts'; import { getActiveQueryClient } from './query-client'; const ACCESS_KEY = 'devbox-access-token'; @@ -211,10 +211,10 @@ export async function logoutEverywhere(): Promise { clearSession(); } -export interface SignOutRouter { +export type SignOutRouter = { replace?: (href: string) => void; push?: (href: string) => void; -} +}; /** * Единый путь sign-out: серверный revoke (best-effort, идемпотентный) → diff --git a/apps/frontend/src/lib/format-error.ts b/apps/frontend/src/lib/format-error.ts index f628e5c..3fd0556 100644 --- a/apps/frontend/src/lib/format-error.ts +++ b/apps/frontend/src/lib/format-error.ts @@ -13,7 +13,7 @@ export function formatApiError(error: unknown): string { return 'Unexpected error'; } -export interface FormattedApiError { +export type FormattedApiError = { code: string; message: string; correlationId: string; @@ -21,7 +21,7 @@ export interface FormattedApiError { shortId: string; /** `code: message (ID: shortId)` — additive display, envelope untouched. */ display: string; -} +}; /** * Full error detail with correlationId for the diagnostic Alert. diff --git a/apps/frontend/src/lib/mocks/auth.ts b/apps/frontend/src/lib/mocks/auth.ts index 7497e41..44906e5 100644 --- a/apps/frontend/src/lib/mocks/auth.ts +++ b/apps/frontend/src/lib/mocks/auth.ts @@ -6,11 +6,11 @@ * for offline demo/tests (never used by the hook anymore). */ -export interface MockUser { +export type MockUser = { id: string; email: string; name: string; -} +}; export const MOCK_USER: MockUser = { id: 'mock-user-1', diff --git a/apps/frontend/src/lib/organization-schemas.ts b/apps/frontend/src/lib/organization-schemas.ts index 936246e..5d6e774 100644 --- a/apps/frontend/src/lib/organization-schemas.ts +++ b/apps/frontend/src/lib/organization-schemas.ts @@ -1,7 +1,15 @@ import { z } from 'zod'; /** - * Organization-name validation — mirrors backend (name required) + UX trim. + * Organization-name validation — UX-strict superset of the wire contract. + * + * Wire source of truth is `@devbox/contracts` (`createOrganizationSchema`: + * backend-verbatim 1..200, no trim). This local schema stays intentionally + * STRICTER (trim + 2..100 + i18n codes `org_name_*` mapped in + * CreateOrganizationDialog) — replacing it with the package schema would + * LOOSEN form validation and break the dialog error mapping. Wire shape is + * frozen, so the local form schema must remain a subset of what the wire + * accepts. * Org names are free-form (any visible chars), only length-checked 2..100. */ export const createOrganizationSchema = z.object({ diff --git a/apps/frontend/src/lib/project-schemas.ts b/apps/frontend/src/lib/project-schemas.ts index 9d4a50a..3ad26d6 100644 --- a/apps/frontend/src/lib/project-schemas.ts +++ b/apps/frontend/src/lib/project-schemas.ts @@ -1,8 +1,15 @@ import { z } from 'zod'; /** - * Project-name validation — mirrors backend min/max (1..200) but adds - * charset restriction + UX-aware trimming. + * Project-name validation — UX-strict superset of the wire contract. + * + * Wire source of truth is `@devbox/contracts` (`createProjectSchema`: + * backend-verbatim 1..200, no trim/charset). This local schema stays + * intentionally STRICTER (trim + 2..100 + allowed-charset + i18n codes + * `project_name_*` mapped in CreateProjectDialog) — replacing it with the + * package schema would LOOSEN form validation and break the + * `getZodErrorMessage` mapping. Wire shape is frozen, so the local form + * schema must remain a subset of what the wire accepts. * * Разрешённые символы: * - буквы латиницы и кириллицы (A-Za-z, А-Яа-яЁё) diff --git a/apps/frontend/src/lib/types.ts b/apps/frontend/src/lib/types.ts index 8dbbb84..deb551a 100644 --- a/apps/frontend/src/lib/types.ts +++ b/apps/frontend/src/lib/types.ts @@ -1,15 +1,16 @@ /** * Shared domain types for mocked dashboard pages. - * Real API DTOs live in src/api/types.ts — these mirror the future - * backend contracts so hooks can swap mocks for `api.*` calls later. + * Real API DTOs live in '@devbox/contracts' (via src/api/types.ts + * re-export) — these mirror the backend contracts so hooks can swap + * mocks for `api.*` calls later. * TODO REAL-API: replace mock sources inside hooks with ApiClient calls. */ -import type { ProjectScope } from '../api/types'; +import type { ProjectScope } from '@devbox/contracts'; export type ProjectStatus = 'active' | 'draft' | 'archived'; -export interface Project { +export type Project = { id: string; name: string; description: string; @@ -23,9 +24,9 @@ export interface Project { corruptedReason: string | null; /** Disk-home scope (user|org); optional — old caches/imports stay valid. */ scope?: ProjectScope; -} +}; -export interface SecretItem { +export type SecretItem = { id: string; name: string; projectId: string; @@ -33,26 +34,26 @@ export interface SecretItem { maskedPreview: string; /** ISO-8601 */ updatedAt: string; -} +}; -export interface Profile { +export type Profile = { id: string; name: string; email: string; /** ISO-8601 */ createdAt: string; -} +}; export type AiProviderStatus = 'connected' | 'disconnected' | 'error'; -export interface AiProvider { +export type AiProvider = { id: string; name: string; description: string; enabled: boolean; status: AiProviderStatus; modelsCount: number; -} +}; /** * Docker-registry surface (mirrors GET /health `registry` flag). @@ -62,14 +63,14 @@ export interface AiProvider { */ export type RegistryStatus = 'up' | 'down' | 'skipped'; -export interface RegistryItem { +export type RegistryItem = { id: string; name: string; /** Base URL, no trailing slash (display only, no secrets). */ url: string; status: RegistryStatus; repositories?: string[]; -} +}; /** * npm surface (mirrors GET /api/v1/registry/npm/status + /health `npmRegistry` flag). @@ -79,7 +80,7 @@ export interface RegistryItem { */ export type NpmStatus = 'up' | 'down' | 'skipped'; -export interface NpmPackageItem { +export type NpmPackageItem = { id: string; name: string; /** Registry base URL (display only, no secrets). */ @@ -87,4 +88,4 @@ export interface NpmPackageItem { /** Observed scope, e.g. '@web2bizz' (carries no secrets). */ scope: string; status: NpmStatus; -} +}; diff --git a/contracts/openapi.yaml b/contracts/openapi.yaml index fd1d4d4..eeef69c 100644 --- a/contracts/openapi.yaml +++ b/contracts/openapi.yaml @@ -2450,6 +2450,7 @@ components: properties: status: type: string + enum: [ok] example: ok db: type: string @@ -2892,6 +2893,8 @@ components: type: string nullable: true description: "Machine reason when corrupted (missing-dir, no-git, rev-parse-failed, fsck-failed, timeout, storage-unconfigured, …). storage-unconfigured = REPOS_ROOT empty (required for project writes; fallback chain is readonly-registry only)" + scope: + $ref: '#/components/schemas/ProjectScope' CreateProject: type: object required: [name] From 514e10671fdd24283edc70a3d2f714a42517e3c9 Mon Sep 17 00:00:00 2001 From: alwoo Date: Tue, 20 Oct 2026 15:22:57 +0400 Subject: [PATCH 014/315] refactor(mobile): consume @devbox/contracts, split utils into modules Standalone npm wiring (file:../../packages/contracts, legacy-peer-deps, metro watchFolders, tsconfig paths) + backend-contracts shim. Flat shared/utils split into per-module dirs with colocated __tests__; hooks moved to shared/hooks. Root workspaces config + AGENTS.md docs. Guard warns (unvalidated-input) are pre-existing and non-blocking. --- .npmrc | 2 + .opencode | 2 +- AGENTS.md | 12 +- apps/mobile/.npmrc | 1 - apps/mobile/AGENTS.md | 2 +- apps/mobile/metro.config.js | 10 +- apps/mobile/package-lock.json | 266 +++++++++++++++++- apps/mobile/package.json | 2 + .../src/shared/api/backend-contracts.ts | 93 ++++++ .../use-ai-sheet/index.ts} | 0 .../use-keyboard-dock/index.ts} | 0 .../use-session-prompts/index.ts} | 2 +- .../use-session-screen/index.ts} | 28 +- .../use-session-send/index.ts} | 6 +- .../{ => __tests__}/lan-projects.test.ts | 10 +- .../{ => __tests__}/persisted-keys.test.ts | 2 +- .../__tests__}/active-tasks.test.ts | 2 +- .../index.ts} | 0 .../__tests__}/api-error.test.ts | 2 +- .../{api-error.ts => api-error/index.ts} | 0 .../__tests__}/app-version.test.ts | 6 +- .../{app-version.ts => app-version/index.ts} | 2 +- .../utils/{ => auth/__tests__}/auth.test.ts | 2 +- .../shared/utils/{auth.ts => auth/index.ts} | 0 .../__tests__}/catalog-parse.test.ts | 2 +- .../index.ts} | 2 +- .../utils/{composer.ts => composer/index.ts} | 0 .../__tests__}/demo-script.test.ts | 2 +- .../{demo-script.ts => demo-script/index.ts} | 2 +- .../__tests__}/diagnostics-classify.test.ts | 2 +- .../index.ts} | 0 .../{diagnostics.ts => diagnostics/index.ts} | 8 +- .../__tests__}/git-remotes.test.ts | 2 +- .../{git-remotes.ts => git-remotes/index.ts} | 0 .../__tests__}/github-mock.test.ts | 2 +- .../{github-mock.ts => github-mock/index.ts} | 0 .../{ => headers/__tests__}/headers.test.ts | 2 +- .../utils/{headers.ts => headers/index.ts} | 0 .../{ => __tests__}/catalog-parity.test.ts | 4 +- .../{ => __tests__}/locale-resolve.test.ts | 2 +- apps/mobile/src/shared/utils/i18n/index.ts | 2 + .../{lan-manual.ts => lan-manual/index.ts} | 0 .../shared/utils/{links.ts => links/index.ts} | 0 .../__tests__}/listed-session.test.ts | 4 +- .../index.ts} | 4 +- .../__tests__}/logbuffer.test.ts | 2 +- .../{logbuffer.ts => logbuffer/index.ts} | 0 .../__tests__}/message-merge.test.ts | 4 +- .../index.ts} | 2 +- .../__tests__}/message-queue.test.ts | 2 +- .../index.ts} | 0 .../__tests__}/model-selection.test.ts | 2 +- .../index.ts} | 0 .../index.ts} | 0 .../__tests__}/notify-format.test.ts | 2 +- .../index.ts} | 0 .../index.ts} | 0 .../__tests__}/part-merge.test.ts | 4 +- .../{part-merge.ts => part-merge/index.ts} | 2 +- .../__tests__}/prompt-from-parts.test.ts | 4 +- .../index.ts} | 2 +- .../index.ts} | 0 .../index.ts} | 4 +- .../__tests__}/query-keys.test.ts | 2 +- .../{query-keys.ts => query-keys/index.ts} | 0 .../index.ts} | 0 .../{revert-flow.ts => revert-flow/index.ts} | 0 .../__tests__}/revert-prune.test.ts | 4 +- .../index.ts} | 2 +- .../src/shared/utils/{sdk.ts => sdk/index.ts} | 26 +- .../index.ts} | 0 .../index.ts} | 0 .../index.ts} | 0 .../__tests__}/session-grouping.test.ts | 2 +- .../index.ts} | 0 .../session-list.integration.test.ts | 4 +- .../__tests__}/session-list.test.ts | 4 +- .../index.ts} | 2 +- .../__tests__}/session-load-reconcile.test.ts | 2 +- .../index.ts} | 0 .../session-status-reconcile.test.ts | 4 +- .../index.ts} | 2 +- apps/mobile/src/shared/utils/session/index.ts | 2 +- .../__tests__}/settings-merge.test.ts | 2 +- .../index.ts} | 0 .../{slash-state.ts => slash-state/index.ts} | 0 .../utils/{speech.ts => speech/index.ts} | 0 .../utils/{ => sse/__tests__}/sse.test.ts | 2 +- .../src/shared/utils/{sse.ts => sse/index.ts} | 0 .../__tests__}/status-labels.test.ts | 2 +- .../index.ts} | 2 +- .../__tests__}/store-review-policy.test.ts | 2 +- .../index.ts} | 0 .../index.ts} | 2 +- .../shared/utils/{types.ts => types/index.ts} | 2 +- .../__tests__}/update-check-policy.test.ts | 2 +- .../index.ts} | 0 .../index.ts} | 4 +- .../index.ts} | 2 +- .../__tests__}/waitlist-queue.test.ts | 2 +- .../{ => waitlist/__tests__}/waitlist.test.ts | 2 +- .../utils/{waitlist.ts => waitlist/index.ts} | 0 apps/mobile/src/types/expo-icons.d.ts | 4 +- .../mobile/src/types/react-native-marked.d.ts | 10 +- apps/mobile/tsconfig.json | 2 + bun.lock | 14 + package.json | 11 +- tsconfig.base.json | 4 +- 108 files changed, 525 insertions(+), 124 deletions(-) delete mode 100644 apps/mobile/.npmrc create mode 100644 apps/mobile/src/shared/api/backend-contracts.ts rename apps/mobile/src/shared/{utils/use-ai-sheet.ts => hooks/use-ai-sheet/index.ts} (100%) rename apps/mobile/src/shared/{utils/use-keyboard-dock.ts => hooks/use-keyboard-dock/index.ts} (100%) rename apps/mobile/src/shared/{utils/use-session-prompts.ts => hooks/use-session-prompts/index.ts} (98%) rename apps/mobile/src/shared/{utils/use-session-screen.ts => hooks/use-session-screen/index.ts} (96%) rename apps/mobile/src/shared/{utils/use-session-send.ts => hooks/use-session-send/index.ts} (96%) rename apps/mobile/src/shared/utils/{ => __tests__}/lan-projects.test.ts (92%) rename apps/mobile/src/shared/utils/{ => __tests__}/persisted-keys.test.ts (98%) rename apps/mobile/src/shared/utils/{ => active-tasks/__tests__}/active-tasks.test.ts (98%) rename apps/mobile/src/shared/utils/{active-tasks.ts => active-tasks/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => api-error/__tests__}/api-error.test.ts (98%) rename apps/mobile/src/shared/utils/{api-error.ts => api-error/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => app-version/__tests__}/app-version.test.ts (89%) rename apps/mobile/src/shared/utils/{app-version.ts => app-version/index.ts} (93%) rename apps/mobile/src/shared/utils/{ => auth/__tests__}/auth.test.ts (96%) rename apps/mobile/src/shared/utils/{auth.ts => auth/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => catalog-parse/__tests__}/catalog-parse.test.ts (96%) rename apps/mobile/src/shared/utils/{catalog-parse.ts => catalog-parse/index.ts} (98%) rename apps/mobile/src/shared/utils/{composer.ts => composer/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => demo-script/__tests__}/demo-script.test.ts (99%) rename apps/mobile/src/shared/utils/{demo-script.ts => demo-script/index.ts} (99%) rename apps/mobile/src/shared/utils/{ => diagnostics-classify/__tests__}/diagnostics-classify.test.ts (98%) rename apps/mobile/src/shared/utils/{diagnostics-classify.ts => diagnostics-classify/index.ts} (100%) rename apps/mobile/src/shared/utils/{diagnostics.ts => diagnostics/index.ts} (96%) rename apps/mobile/src/shared/utils/{ => git-remotes/__tests__}/git-remotes.test.ts (99%) rename apps/mobile/src/shared/utils/{git-remotes.ts => git-remotes/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => github-mock/__tests__}/github-mock.test.ts (89%) rename apps/mobile/src/shared/utils/{github-mock.ts => github-mock/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => headers/__tests__}/headers.test.ts (98%) rename apps/mobile/src/shared/utils/{headers.ts => headers/index.ts} (100%) rename apps/mobile/src/shared/utils/i18n/{ => __tests__}/catalog-parity.test.ts (95%) rename apps/mobile/src/shared/utils/i18n/{ => __tests__}/locale-resolve.test.ts (98%) create mode 100644 apps/mobile/src/shared/utils/i18n/index.ts rename apps/mobile/src/shared/utils/{lan-manual.ts => lan-manual/index.ts} (100%) rename apps/mobile/src/shared/utils/{links.ts => links/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => listed-session/__tests__}/listed-session.test.ts (89%) rename apps/mobile/src/shared/utils/{listed-session.ts => listed-session/index.ts} (93%) rename apps/mobile/src/shared/utils/{ => logbuffer/__tests__}/logbuffer.test.ts (99%) rename apps/mobile/src/shared/utils/{logbuffer.ts => logbuffer/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => message-merge/__tests__}/message-merge.test.ts (96%) rename apps/mobile/src/shared/utils/{message-merge.ts => message-merge/index.ts} (97%) rename apps/mobile/src/shared/utils/{ => message-queue/__tests__}/message-queue.test.ts (96%) rename apps/mobile/src/shared/utils/{message-queue.ts => message-queue/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => model-selection/__tests__}/model-selection.test.ts (96%) rename apps/mobile/src/shared/utils/{model-selection.ts => model-selection/index.ts} (100%) rename apps/mobile/src/shared/utils/{notifications.ts => notifications/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => notify-format/__tests__}/notify-format.test.ts (95%) rename apps/mobile/src/shared/utils/{notify-format.ts => notify-format/index.ts} (100%) rename apps/mobile/src/shared/utils/{outbox-flush.ts => outbox-flush/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => part-merge/__tests__}/part-merge.test.ts (95%) rename apps/mobile/src/shared/utils/{part-merge.ts => part-merge/index.ts} (96%) rename apps/mobile/src/shared/utils/{ => prompt-from-parts/__tests__}/prompt-from-parts.test.ts (92%) rename apps/mobile/src/shared/utils/{prompt-from-parts.ts => prompt-from-parts/index.ts} (94%) rename apps/mobile/src/shared/utils/{query-client.ts => query-client/index.ts} (100%) rename apps/mobile/src/shared/utils/{query-invalidate.ts => query-invalidate/index.ts} (86%) rename apps/mobile/src/shared/utils/{ => query-keys/__tests__}/query-keys.test.ts (95%) rename apps/mobile/src/shared/utils/{query-keys.ts => query-keys/index.ts} (100%) rename apps/mobile/src/shared/utils/{reconnect-flash.ts => reconnect-flash/index.ts} (100%) rename apps/mobile/src/shared/utils/{revert-flow.ts => revert-flow/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => revert-prune/__tests__}/revert-prune.test.ts (95%) rename apps/mobile/src/shared/utils/{revert-prune.ts => revert-prune/index.ts} (97%) rename apps/mobile/src/shared/utils/{sdk.ts => sdk/index.ts} (92%) rename apps/mobile/src/shared/utils/{server-config.ts => server-config/index.ts} (100%) rename apps/mobile/src/shared/utils/{session-alerts.ts => session-alerts/index.ts} (100%) rename apps/mobile/src/shared/utils/{session-binding.ts => session-binding/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => session-grouping/__tests__}/session-grouping.test.ts (96%) rename apps/mobile/src/shared/utils/{session-grouping.ts => session-grouping/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => session-list/__tests__}/session-list.integration.test.ts (97%) rename apps/mobile/src/shared/utils/{ => session-list/__tests__}/session-list.test.ts (97%) rename apps/mobile/src/shared/utils/{session-list.ts => session-list/index.ts} (98%) rename apps/mobile/src/shared/utils/{ => session-load-reconcile/__tests__}/session-load-reconcile.test.ts (93%) rename apps/mobile/src/shared/utils/{session-load-reconcile.ts => session-load-reconcile/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => session-status-reconcile/__tests__}/session-status-reconcile.test.ts (94%) rename apps/mobile/src/shared/utils/{session-status-reconcile.ts => session-status-reconcile/index.ts} (97%) rename apps/mobile/src/shared/utils/{ => settings-merge/__tests__}/settings-merge.test.ts (96%) rename apps/mobile/src/shared/utils/{settings-merge.ts => settings-merge/index.ts} (100%) rename apps/mobile/src/shared/utils/{slash-state.ts => slash-state/index.ts} (100%) rename apps/mobile/src/shared/utils/{speech.ts => speech/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => sse/__tests__}/sse.test.ts (98%) rename apps/mobile/src/shared/utils/{sse.ts => sse/index.ts} (100%) rename apps/mobile/src/shared/utils/{ => status-labels/__tests__}/status-labels.test.ts (96%) rename apps/mobile/src/shared/utils/{status-labels.ts => status-labels/index.ts} (96%) rename apps/mobile/src/shared/utils/{ => store-review-policy/__tests__}/store-review-policy.test.ts (96%) rename apps/mobile/src/shared/utils/{store-review-policy.ts => store-review-policy/index.ts} (100%) rename apps/mobile/src/shared/utils/{store-review.ts => store-review/index.ts} (99%) rename apps/mobile/src/shared/utils/{types.ts => types/index.ts} (98%) rename apps/mobile/src/shared/utils/{ => update-check-policy/__tests__}/update-check-policy.test.ts (99%) rename apps/mobile/src/shared/utils/{update-check-policy.ts => update-check-policy/index.ts} (100%) rename apps/mobile/src/shared/utils/{update-check.ts => update-check/index.ts} (97%) rename apps/mobile/src/shared/utils/{waitlist-queue-storage.ts => waitlist-queue-storage/index.ts} (99%) rename apps/mobile/src/shared/utils/{ => waitlist/__tests__}/waitlist-queue.test.ts (99%) rename apps/mobile/src/shared/utils/{ => waitlist/__tests__}/waitlist.test.ts (99%) rename apps/mobile/src/shared/utils/{waitlist.ts => waitlist/index.ts} (100%) diff --git a/.npmrc b/.npmrc index a3bf02d..81bf0f0 100644 --- a/.npmrc +++ b/.npmrc @@ -5,3 +5,5 @@ # Global auth in ~/.npmrc is left untouched — this file is project-level only. @web2bizz:registry=https://npm.registry.web2bizz.team/ //npm.registry.web2bizz.team/:_authToken=${NPM_TOKEN} +# legacy-peer-deps for npm/mobile standalone (bun ignores this flag); mobile inherits config up the tree. +legacy-peer-deps=true diff --git a/.opencode b/.opencode index 4cda1c9..cb08291 160000 --- a/.opencode +++ b/.opencode @@ -1 +1 @@ -Subproject commit 4cda1c9b3fa44142ba9049d5323127c51a2e15a5 +Subproject commit cb08291342fe9ab1a48c0d18e3ffd3cd3fe60253 diff --git a/AGENTS.md b/AGENTS.md index 280638a..cdefa9e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,14 @@ package.json, не Nx-проект, вне bun workspaces). `--legacy-peer-deps`), намеренно **вне bun workspaces**: ставится и запускается из своей директории, без `bun --filter`. +## Общий пакет контрактов + +- `@devbox/contracts` (`packages/contracts`, 0.1.0) — единый wire-контракт бэкенд↔фронт. 8 пар `entity.ts` + `entity.schema.ts` (health, session, repo-entry, api-error, auth, project, organization, opencode-key): типы + zod v4 boundary-схемы (Standard Schema, backend-verbatim ограничения), без рантайм-логики. +- `contracts/openapi.yaml` — источник правды wire-контракта: пакет зеркалит `components/schemas` поле-в-поле (Health.status enum `[ok]`, Project.scope optional и т.д.). Расхождение YAML ↔ пакет — баг пакета, не фича. +- backend/frontend — bun workspaces (`workspace:*`, уже в `workspaces` корня + `tsconfig.base.json` paths). mobile — standalone npm: `file:../../packages/contracts` + `npm install --legacy-peer-deps` (см. `apps/mobile/AGENTS.md`) + резолв `metro.config.js` watchFolders/extraNodeModules + `tsconfig.json` paths. +- `apps/backend/src/contracts.ts` и `apps/frontend/src/api/types.ts` — deprecated-реэкспорты (Forward-Only, на один релиз, новых экспортов не добавлять). `apps/frontend/src/lib/auth-schemas.ts` — такой же алиас; `apps/mobile/src/shared/api/backend-contracts.ts` — тонкий шим + `parseBackend*` fail-fast хелперы. +- Имя: `contracts` основное (контракт + валидация границы), `entities` — содержимое пар. `packages/shared` отклонён — слишком общее (сваливает контракты, утилиты и сторы в одну кучу). + ## Frontend — дизайн-система - Общие правила для всех UI-приложений — реферат @@ -47,8 +55,8 @@ package.json, не Nx-проект, вне bun workspaces). | Фичи | `src/features/<имя>/` | фича-модуль целиком: UI-секция + диалоги + локальный статус (`usage/`: `usage-section.tsx`, `api-key-dialog.tsx`, `usage-status.ts`, `__tests__/`) | `@/features/*` | `@/features/usage/usage-section` (из `app/(dashboard)/profile/page.tsx`) | | Компоненты | `src/components/` | общие презентационные компоненты (`states`, `layout/`, `profile/`, `projects/`, …) | `@/components/*` | `../../components/states` (из `src/features/usage/`) | | Хуки | `src/hooks/` | data-хуки (`useUsage`, `useProfile`, …) + `query-keys.ts` | `@/hooks/*` | `../../hooks/useUsage` (из `src/features/usage/`) | -| API | `src/api/` | HTTP-клиент, типы контрактов (`client.ts`, `types.ts`) | `@/api/*` | `../../api/types` (из `src/features/usage/`) | -| Lib | `src/lib/` | утилиты, схемы, сторы (`auth-store`, `format-error`) | `@/lib/*` | `../../lib/auth-store` (из `src/features/usage/`) | +| API | `src/api/` | HTTP-клиент (`client.ts`) + реэкспорт контрактов (`types.ts` — deprecated-реэкспорт `@devbox/contracts`, своих типов не заводить) | `@/api/*` | `../../api/types` (из `src/features/usage/`) | +| Lib | `src/lib/` | утилиты, сторы (`auth-store`, `format-error`) + алиасы схем (`auth-schemas` — реэкспорт пакета); `project/org-schemas` локально строже wire (UX trim/min/max/charset/i18n-коды, subset wire) с комментом-обоснованием | `@/lib/*` | `../../lib/auth-store` (из `src/features/usage/`) | | i18n | `src/i18n/` | словарь en/ru, провайдер | `@/i18n/*` | `../../i18n` (из `src/features/usage/`) | ## Фолбэки запрещены по умолчанию diff --git a/apps/mobile/.npmrc b/apps/mobile/.npmrc deleted file mode 100644 index 521a9f7..0000000 --- a/apps/mobile/.npmrc +++ /dev/null @@ -1 +0,0 @@ -legacy-peer-deps=true diff --git a/apps/mobile/AGENTS.md b/apps/mobile/AGENTS.md index 2729570..fd73361 100644 --- a/apps/mobile/AGENTS.md +++ b/apps/mobile/AGENTS.md @@ -7,7 +7,7 @@ Expo 57 + React Native 0.86.3 + React 19.2.3 + Expo Router. Single app, no monor ## Commands ```bash -npm install --legacy-peer-deps # required — .npmrc sets legacy-peer-deps=true, peer constraints need it +npm install --legacy-peer-deps # required — root .npmrc sets legacy-peer-deps=true (mobile inherits up the tree), peer constraints need it npm run typecheck # tsc --noEmit (strict, sole verification gate) npm test # node --test 'src/**/*.test.ts' 'scripts/*.test.mjs' — needs Node >= 23.6 for TS type-stripping node --test src/lib/auth.test.ts # single test file diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js index 0fc1e6d..6e0d3d3 100644 --- a/apps/mobile/metro.config.js +++ b/apps/mobile/metro.config.js @@ -11,7 +11,15 @@ const { getDefaultConfig } = require("expo/metro-config") /** @type {import('expo/metro-config').MetroConfig} */ const config = getDefaultConfig(__dirname) -config.watchFolders = [...(config.watchFolders ?? []), path.resolve(__dirname, "packages")] +config.watchFolders = [ + ...(config.watchFolders ?? []), + path.resolve(__dirname, "packages"), + // @devbox/contracts lives OUTSIDE the mobile root (../../packages/contracts, + // file: dep) — watch it so Metro picks up wire-contract changes without a + // cache clear. Installed via `npm install --legacy-peer-deps` from + // apps/mobile (standalone npm project, not a bun workspace). + path.resolve(__dirname, "../../packages/contracts"), +] config.resolver.extraNodeModules = { ...config.resolver.extraNodeModules, "@web2bizz/ui-native": path.resolve(__dirname, "packages/uikit"), diff --git a/apps/mobile/package-lock.json b/apps/mobile/package-lock.json index e9c4ee1..dc69e7d 100644 --- a/apps/mobile/package-lock.json +++ b/apps/mobile/package-lock.json @@ -1,20 +1,21 @@ { "name": "@opencode-ai/mobile", - "version": "0.5.6", + "version": "0.6.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@opencode-ai/mobile", - "version": "0.5.6", + "version": "0.6.2", "workspaces": [ "packages/*" ], "dependencies": { + "@devbox/contracts": "file:../../packages/contracts", "@expo/vector-icons": "^15.0.3", "@gorhom/bottom-sheet": "^5.2.14", "@react-native-async-storage/async-storage": "2.2.0", - "@react-native-masked-view/masked-view": "^0.3.2", + "@react-native-masked-view/masked-view": "~0.3.2", "@react-navigation/native": "^7.0.14", "@tanstack/react-query": "^5.62.0", "@web2bizz/ui-native": "file:packages/uikit", @@ -51,14 +52,30 @@ "react-native-screens": "~4.26.0", "react-native-svg": "15.15.4", "react-native-worklets": "0.10.1", + "zod": "4.6.5", "zustand": "^5.0.2" }, "devDependencies": { "@types/node": "^26.6.2", "@types/react": "~19.2.4", + "babel-plugin-module-resolver": "^5.0.2", "typescript": "~6.0.3" } }, + "../../packages/contracts": { + "name": "@devbox/contracts", + "version": "0.1.0", + "dependencies": { + "zod": "^4.6.5" + }, + "engines": { + "bun": ">=1.4.2", + "node": ">=22" + }, + "peerDependencies": { + "zod": "^4.6.5" + } + }, "node_modules/@babel/code-frame": { "version": "7.29.0", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", @@ -1132,6 +1149,10 @@ "node": ">=6.9.0" } }, + "node_modules/@devbox/contracts": { + "resolved": "../../packages/contracts", + "link": true + }, "node_modules/@egjs/hammerjs": { "version": "2.0.17", "resolved": "https://registry.npmjs.org/@egjs/hammerjs/-/hammerjs-2.0.17.tgz", @@ -1311,6 +1332,15 @@ } } }, + "node_modules/@expo/cli/node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/@expo/code-signing-certificates": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/@expo/code-signing-certificates/-/code-signing-certificates-0.0.6.tgz", @@ -3183,6 +3213,117 @@ "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", "license": "MIT" }, + "node_modules/babel-plugin-module-resolver": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/babel-plugin-module-resolver/-/babel-plugin-module-resolver-5.0.3.tgz", + "integrity": "sha512-h8h6H71ZvdLJZxZrYkaeR30BojTaV7O9GfqacY14SNj5CNB8ocL9tydNzTC0JrnNN7vY3eJhwCmkDj7tuEUaqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "find-babel-config": "^2.1.1", + "glob": "^9.3.3", + "pkg-up": "^3.1.0", + "reselect": "^4.1.7", + "resolve": "^1.22.8" + } + }, + "node_modules/babel-plugin-module-resolver/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/babel-plugin-module-resolver/node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/babel-plugin-module-resolver/node_modules/glob": { + "version": "9.3.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz", + "integrity": "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "minimatch": "^8.0.2", + "minipass": "^4.2.4", + "path-scurry": "^1.6.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/babel-plugin-module-resolver/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/babel-plugin-module-resolver/node_modules/minimatch": { + "version": "8.0.7", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-8.0.7.tgz", + "integrity": "sha512-V+1uQNdzybxa14e/p00HZnQNNcTjnRJjDxg2V8wtkjFctq4M7hXFws4oekyTP0Jebeq7QYtpFyOeBAjc88zvYg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/babel-plugin-module-resolver/node_modules/minipass": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.2.8.tgz", + "integrity": "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-module-resolver/node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/babel-plugin-module-resolver/node_modules/path-scurry/node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/babel-plugin-polyfill-corejs2": { "version": "0.4.17", "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.17.tgz", @@ -4959,6 +5100,29 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "license": "MIT" }, + "node_modules/find-babel-config": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/find-babel-config/-/find-babel-config-2.1.2.tgz", + "integrity": "sha512-ZfZp1rQyp4gyuxqt1ZqjFGVeVBvmpURMqdIWXbPRfB97Bf6BzdK/xSIbylEINzQ0kB5tlDQfn9HkNXXWsqTqLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "json5": "^2.2.3" + } + }, + "node_modules/find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/flow-enums-runtime": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/flow-enums-runtime/-/flow-enums-runtime-0.0.6.tgz", @@ -4980,6 +5144,13 @@ "node": ">= 0.6" } }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -5772,6 +5943,20 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", @@ -6665,6 +6850,45 @@ "node": ">=4" } }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/parse-png": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/parse-png/-/parse-png-2.1.0.tgz", @@ -6686,6 +6910,16 @@ "node": ">= 0.8" } }, + "node_modules/path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -6744,6 +6978,19 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkg-up": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-3.1.0.tgz", + "integrity": "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/plist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz", @@ -7378,6 +7625,13 @@ "node": ">=0.10.0" } }, + "node_modules/reselect": { + "version": "4.1.8", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-4.1.8.tgz", + "integrity": "sha512-ab9EmR80F/zQTMNeneUr4cv+jSwPJgIlvEmVwLerwrWVbpLlBuls9XHzIeTFy4cegU2NHBp3va0LKOzU5qFEYQ==", + "dev": true, + "license": "MIT" + }, "node_modules/resolve": { "version": "1.22.12", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", @@ -8613,9 +8867,9 @@ } }, "node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 2db95cb..03df274 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -20,6 +20,7 @@ "test": "node --test 'src/**/*.test.ts' 'packages/uikit/src/**/*.test.ts' 'scripts/*.test.mjs'" }, "dependencies": { + "@devbox/contracts": "file:../../packages/contracts", "@expo/vector-icons": "^15.0.3", "@gorhom/bottom-sheet": "^5.2.14", "@react-native-async-storage/async-storage": "2.2.0", @@ -60,6 +61,7 @@ "react-native-screens": "~4.26.0", "react-native-svg": "15.15.4", "react-native-worklets": "0.10.1", + "zod": "4.6.5", "zustand": "^5.0.2" }, "devDependencies": { diff --git a/apps/mobile/src/shared/api/backend-contracts.ts b/apps/mobile/src/shared/api/backend-contracts.ts new file mode 100644 index 0000000..ed27651 --- /dev/null +++ b/apps/mobile/src/shared/api/backend-contracts.ts @@ -0,0 +1,93 @@ +/** + * Backend wire contracts for mobile — thin Forward-Only re-export of + * `@devbox/contracts` (single source of truth, mirrors + * contracts/openapi.yaml field-for-field; zod v4 boundary schemas verbatim + * from the backend DTOs). + * + * Install: `npm install --legacy-peer-deps` from apps/mobile (standalone npm + * project, `--legacy-peer-deps` required — see apps/mobile/AGENTS.md). + * Resolve: `file:../../packages/contracts` in package.json (outside the + * mobile root) + `metro.config.js` watchFolders/extraNodeModules + + * `tsconfig.json` paths `@devbox/contracts` → package src. Primary runtime + * resolve is node_modules after install; the Metro/TS aliases keep the + * pre-install and bundler paths working. + * + * Why a shim (not a swap in sdk/index.ts): the opencode client in + * `src/shared/utils/sdk` talks to the UPSTREAM opencode server directly + * (`/global/health`, `/session`, `/project`, …) — its `Session` (slug / + * projectID / directory / time), `Project` (path: { cwd, root, absolute }) + * and `HealthResponse` ({ healthy, version } = openapi `OpencodeHealth`) are + * upstream shapes, NOT backend `/api/v1/*` wire. Swapping them for the + * backend `Session` ({ id, title, createdAt }) / `Project` (backend row + + * optional `scope`) / `HealthResponse` ({ status, db, opencode, … }) would + * silently break the wire. Those sdk types stay intentionally untouched; + * backend wire is imported FROM HERE when mobile starts speaking `/api/v1`. + * + * zod on the boundary (as backend): use the `*Schema.parse()` helpers below + * (fail-fast, same constraints/messages as the backend) at every backend + * response boundary — never trust-fetch without a schema. + */ +export type { + ApiError, + HealthResponse, + Session as BackendSession, + ChatMessage as BackendChatMessage, + MessagesResponse as BackendMessagesResponse, + Project as BackendProject, + ProjectScope, + Organization as BackendOrganization, + OrganizationMember as BackendOrganizationMember, + OrganizationInvite as BackendOrganizationInvite, + OrgRole, + OpencodeKeyStatus, + OpencodeKeyResult, + OpencodeKeyDeleteResult, + OpencodeUsage, + OpencodeLimitBucket, +} from "@devbox/contracts"; + +export { + apiErrorSchema, + healthResponseSchema, + sessionSchema, + messagesResponseSchema, + projectSchema, + projectScopeSchema, + createProjectSchema, + updateProjectSchema, + organizationSchema, + organizationMemberSchema, + organizationInviteSchema, + orgRoleSchema, + createOrganizationSchema, + updateOrganizationSchema, + opencodeKeyStatusSchema, + opencodeKeyResultSchema, + opencodeKeyDeleteResultSchema, + opencodeUsageSchema, + opencodeLimitBucketSchema, +} from "@devbox/contracts"; + +import { + apiErrorSchema, + healthResponseSchema, + opencodeUsageSchema, + type ApiError, + type HealthResponse, + type OpencodeUsage, +} from "@devbox/contracts"; + +/** Fail-fast backend `/health` boundary (throws on shape mismatch, as backend). */ +export function parseBackendHealth(payload: unknown): HealthResponse { + return healthResponseSchema.parse(payload); +} + +/** Fail-fast backend `GET /api/v1/usage` boundary (throws on shape mismatch). */ +export function parseBackendUsage(payload: unknown): OpencodeUsage { + return opencodeUsageSchema.parse(payload); +} + +/** Fail-fast backend `ApiError` envelope boundary (frozen shape, values only). */ +export function parseBackendApiError(payload: unknown): ApiError { + return apiErrorSchema.parse(payload); +} diff --git a/apps/mobile/src/shared/utils/use-ai-sheet.ts b/apps/mobile/src/shared/hooks/use-ai-sheet/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/use-ai-sheet.ts rename to apps/mobile/src/shared/hooks/use-ai-sheet/index.ts diff --git a/apps/mobile/src/shared/utils/use-keyboard-dock.ts b/apps/mobile/src/shared/hooks/use-keyboard-dock/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/use-keyboard-dock.ts rename to apps/mobile/src/shared/hooks/use-keyboard-dock/index.ts diff --git a/apps/mobile/src/shared/utils/use-session-prompts.ts b/apps/mobile/src/shared/hooks/use-session-prompts/index.ts similarity index 98% rename from apps/mobile/src/shared/utils/use-session-prompts.ts rename to apps/mobile/src/shared/hooks/use-session-prompts/index.ts index dc87e29..084584f 100644 --- a/apps/mobile/src/shared/utils/use-session-prompts.ts +++ b/apps/mobile/src/shared/hooks/use-session-prompts/index.ts @@ -1,6 +1,6 @@ import { Alert } from "react-native" import type { TFunction } from "i18next" -import type { Client } from "./sdk" +import type { Client } from "../../utils/sdk" export type SessionPromptDeps = { sessionClient: Client | null diff --git a/apps/mobile/src/shared/utils/use-session-screen.ts b/apps/mobile/src/shared/hooks/use-session-screen/index.ts similarity index 96% rename from apps/mobile/src/shared/utils/use-session-screen.ts rename to apps/mobile/src/shared/hooks/use-session-screen/index.ts index d6a951e..a5a1cf6 100644 --- a/apps/mobile/src/shared/utils/use-session-screen.ts +++ b/apps/mobile/src/shared/hooks/use-session-screen/index.ts @@ -9,17 +9,17 @@ import { useEvents, type PermissionRequest, type QuestionRequest } from "@/store import { useConnections } from "@/stores/connections" import { useCatalog } from "@/stores/catalog" import { useCatalogData } from "@/api/catalog" -import { useComposer } from "./composer" -import { useRevertFlow } from "./revert-flow" -import { useSessionAlerts } from "./session-alerts" -import { useReconnectFlash } from "./reconnect-flash" -import { useOutboxFlush } from "./outbox-flush" -import { useSlashState } from "./slash-state" -import { useSpeech } from "./speech" -import { useAiSheet } from "./use-ai-sheet" -import { useKeyboardDock } from "./use-keyboard-dock" -import { useSessionSend } from "./use-session-send" -import { useSessionPrompts } from "./use-session-prompts" +import { useComposer } from "../../utils/composer" +import { useRevertFlow } from "../../utils/revert-flow" +import { useSessionAlerts } from "../../utils/session-alerts" +import { useReconnectFlash } from "../../utils/reconnect-flash" +import { useOutboxFlush } from "../../utils/outbox-flush" +import { useSlashState } from "../../utils/slash-state" +import { useSpeech } from "../../utils/speech" +import { useAiSheet } from "../use-ai-sheet" +import { useKeyboardDock } from "../use-keyboard-dock" +import { useSessionSend } from "../use-session-send" +import { useSessionPrompts } from "../use-session-prompts" import { useAbortSession, useRevertSession, @@ -28,9 +28,9 @@ import { useQuestionReply, useQuestionReject, } from "@/api/session-ops" -import type { Agent, Client, Message, Part } from "./sdk" -import type { Provider } from "./catalog-parse" -import type { ListedSession } from "./listed-session" +import type { Agent, Client, Message, Part } from "../../utils/sdk" +import type { Provider } from "../../utils/catalog-parse" +import type { ListedSession } from "../../utils/listed-session" import type { StatusSnapshot } from "@web2bizz/ui-native" import type { SessionHeaderProps, diff --git a/apps/mobile/src/shared/utils/use-session-send.ts b/apps/mobile/src/shared/hooks/use-session-send/index.ts similarity index 96% rename from apps/mobile/src/shared/utils/use-session-send.ts rename to apps/mobile/src/shared/hooks/use-session-send/index.ts index 0a2a4bb..494ff03 100644 --- a/apps/mobile/src/shared/utils/use-session-send.ts +++ b/apps/mobile/src/shared/hooks/use-session-send/index.ts @@ -1,9 +1,9 @@ import { Alert } from "react-native" import type { TFunction } from "i18next" import type { Attachment } from "@web2bizz/ui-native" -import type { Client } from "./sdk" -import type { ListedSession } from "./listed-session" -import type { ServerCommand } from "./slash-state" +import type { Client } from "../../utils/sdk" +import type { ListedSession } from "../../utils/listed-session" +import type { ServerCommand } from "../../utils/slash-state" import type { QueuedDraft } from "@/stores/sessions" export type SessionSendParams = { diff --git a/apps/mobile/src/shared/utils/lan-projects.test.ts b/apps/mobile/src/shared/utils/__tests__/lan-projects.test.ts similarity index 92% rename from apps/mobile/src/shared/utils/lan-projects.test.ts rename to apps/mobile/src/shared/utils/__tests__/lan-projects.test.ts index 593e0f4..471570c 100644 --- a/apps/mobile/src/shared/utils/lan-projects.test.ts +++ b/apps/mobile/src/shared/utils/__tests__/lan-projects.test.ts @@ -1,10 +1,10 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { groupProjects } from "./session-grouping.ts" -import { lanConnectionIds, mergeSessionLists } from "./listed-session.ts" -import { buildManualLanUrl } from "./lan-manual.ts" -import { queryKeys } from "./query-keys.ts" -import type { Session } from "./sdk.ts" +import { groupProjects } from "../session-grouping/index.ts" +import { lanConnectionIds, mergeSessionLists } from "../listed-session/index.ts" +import { buildManualLanUrl } from "../lan-manual/index.ts" +import { queryKeys } from "../query-keys/index.ts" +import type { Session } from "../sdk/index.ts" const session = (id: string, updated: number, directory = "/proj"): Session => ({ id, diff --git a/apps/mobile/src/shared/utils/persisted-keys.test.ts b/apps/mobile/src/shared/utils/__tests__/persisted-keys.test.ts similarity index 98% rename from apps/mobile/src/shared/utils/persisted-keys.test.ts rename to apps/mobile/src/shared/utils/__tests__/persisted-keys.test.ts index a3ce5fa..13fe4e7 100644 --- a/apps/mobile/src/shared/utils/persisted-keys.test.ts +++ b/apps/mobile/src/shared/utils/__tests__/persisted-keys.test.ts @@ -34,7 +34,7 @@ const ALLOWED_PERSISTED_KEYS = new Map([ ["ASKED_KEY", "store-review: already-prompted flag"], ]) -const SRC = path.join(import.meta.dirname, "..") +const SRC = path.join(import.meta.dirname, "..", "..") function sourceFiles(dir: string): string[] { return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { diff --git a/apps/mobile/src/shared/utils/active-tasks.test.ts b/apps/mobile/src/shared/utils/active-tasks/__tests__/active-tasks.test.ts similarity index 98% rename from apps/mobile/src/shared/utils/active-tasks.test.ts rename to apps/mobile/src/shared/utils/active-tasks/__tests__/active-tasks.test.ts index 3288a42..a0cf2ba 100644 --- a/apps/mobile/src/shared/utils/active-tasks.test.ts +++ b/apps/mobile/src/shared/utils/active-tasks/__tests__/active-tasks.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { isTaskActive, selectActiveSessions, countActiveTasks } from "./active-tasks.ts" +import { isTaskActive, selectActiveSessions, countActiveTasks } from "../index.ts" const sessions = [{ id: "a" }, { id: "b" }, { id: "c" }] diff --git a/apps/mobile/src/shared/utils/active-tasks.ts b/apps/mobile/src/shared/utils/active-tasks/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/active-tasks.ts rename to apps/mobile/src/shared/utils/active-tasks/index.ts diff --git a/apps/mobile/src/shared/utils/api-error.test.ts b/apps/mobile/src/shared/utils/api-error/__tests__/api-error.test.ts similarity index 98% rename from apps/mobile/src/shared/utils/api-error.test.ts rename to apps/mobile/src/shared/utils/api-error/__tests__/api-error.test.ts index 3806564..5172e99 100644 --- a/apps/mobile/src/shared/utils/api-error.test.ts +++ b/apps/mobile/src/shared/utils/api-error/__tests__/api-error.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { ApiAuthError, apiErrorFor, isAuthError, isAuthStatus } from "./api-error.ts" +import { ApiAuthError, apiErrorFor, isAuthError, isAuthStatus } from "../index.ts" test("isAuthStatus: 401 and 403 are auth failures", () => { assert.equal(isAuthStatus(401), true) diff --git a/apps/mobile/src/shared/utils/api-error.ts b/apps/mobile/src/shared/utils/api-error/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/api-error.ts rename to apps/mobile/src/shared/utils/api-error/index.ts diff --git a/apps/mobile/src/shared/utils/app-version.test.ts b/apps/mobile/src/shared/utils/app-version/__tests__/app-version.test.ts similarity index 89% rename from apps/mobile/src/shared/utils/app-version.test.ts rename to apps/mobile/src/shared/utils/app-version/__tests__/app-version.test.ts index 763baaf..a4f662e 100644 --- a/apps/mobile/src/shared/utils/app-version.test.ts +++ b/apps/mobile/src/shared/utils/app-version/__tests__/app-version.test.ts @@ -12,9 +12,9 @@ import path from "node:path" // resolve, so this invariant is checked statically, same pattern as // persisted-keys.test.ts). A second direct `package.json` import in app/ // or src/ would silently fork the source of truth on the next bump. -const ROOT = path.join(import.meta.dirname, "..", "..", "..") +const ROOT = path.join(import.meta.dirname, "..", "..", "..", "..", "..") const APP_DIRS = [path.join(ROOT, "app"), path.join(ROOT, "src")] -const OWNER = path.join("src", "shared", "utils", "app-version.ts") +const OWNER = path.join("src", "shared", "utils", "app-version", "index.ts") function sourceFiles(dir: string): string[] { return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { @@ -33,7 +33,7 @@ test("package.json carries a dotted release version", () => { test("app-version.ts re-exports the package.json version", () => { const code = fs.readFileSync(path.join(ROOT, OWNER), "utf8") - assert.match(code, /from "\.\.\/\.\.\/\.\.\/package\.json"/, "must import the root package.json") + assert.match(code, /from "\.\.\/\.\.\/\.\.\/\.\.\/package\.json"/, "must import the root package.json") assert.match(code, /export const APP_VERSION/, "must export APP_VERSION") }) diff --git a/apps/mobile/src/shared/utils/app-version.ts b/apps/mobile/src/shared/utils/app-version/index.ts similarity index 93% rename from apps/mobile/src/shared/utils/app-version.ts rename to apps/mobile/src/shared/utils/app-version/index.ts index 8ece4e9..07de595 100644 --- a/apps/mobile/src/shared/utils/app-version.ts +++ b/apps/mobile/src/shared/utils/app-version/index.ts @@ -8,6 +8,6 @@ // // NOTE: intentionally relative — package.json lives at the mobile root, // outside the `@` (= src) and `@app` (= app) alias roots, so no alias covers it. -import pkg from "../../../package.json" +import pkg from "../../../../package.json" export const APP_VERSION: string = (pkg as { version?: string }).version ?? "unknown" diff --git a/apps/mobile/src/shared/utils/auth.test.ts b/apps/mobile/src/shared/utils/auth/__tests__/auth.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/auth.test.ts rename to apps/mobile/src/shared/utils/auth/__tests__/auth.test.ts index d8bdf96..eedf03a 100644 --- a/apps/mobile/src/shared/utils/auth.test.ts +++ b/apps/mobile/src/shared/utils/auth/__tests__/auth.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { buildAuth } from "./auth.ts" +import { buildAuth } from "../index.ts" test("no password -> no auth (open server)", () => { assert.equal(buildAuth("opencode", undefined), undefined) diff --git a/apps/mobile/src/shared/utils/auth.ts b/apps/mobile/src/shared/utils/auth/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/auth.ts rename to apps/mobile/src/shared/utils/auth/index.ts diff --git a/apps/mobile/src/shared/utils/catalog-parse.test.ts b/apps/mobile/src/shared/utils/catalog-parse/__tests__/catalog-parse.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/catalog-parse.test.ts rename to apps/mobile/src/shared/utils/catalog-parse/__tests__/catalog-parse.test.ts index ded96b2..f4edbbc 100644 --- a/apps/mobile/src/shared/utils/catalog-parse.test.ts +++ b/apps/mobile/src/shared/utils/catalog-parse/__tests__/catalog-parse.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { parseCatalogResponse } from "./catalog-parse.ts" +import { parseCatalogResponse } from "../index.ts" const agents = [ { name: "build", mode: "primary", hidden: false, options: {} }, diff --git a/apps/mobile/src/shared/utils/catalog-parse.ts b/apps/mobile/src/shared/utils/catalog-parse/index.ts similarity index 98% rename from apps/mobile/src/shared/utils/catalog-parse.ts rename to apps/mobile/src/shared/utils/catalog-parse/index.ts index 4bed798..4afe5eb 100644 --- a/apps/mobile/src/shared/utils/catalog-parse.ts +++ b/apps/mobile/src/shared/utils/catalog-parse/index.ts @@ -4,7 +4,7 @@ // Zustand selection store. Selection defaults (which agent/model is active) // stay in the store — they depend on the user's previous choice, not just the // server payload (see chooseModelSelection). -import type { Agent, Command } from "./sdk" +import type { Agent, Command } from "../sdk" export type ProviderModel = { id: string diff --git a/apps/mobile/src/shared/utils/composer.ts b/apps/mobile/src/shared/utils/composer/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/composer.ts rename to apps/mobile/src/shared/utils/composer/index.ts diff --git a/apps/mobile/src/shared/utils/demo-script.test.ts b/apps/mobile/src/shared/utils/demo-script/__tests__/demo-script.test.ts similarity index 99% rename from apps/mobile/src/shared/utils/demo-script.test.ts rename to apps/mobile/src/shared/utils/demo-script/__tests__/demo-script.test.ts index ea5aa1f..1a01735 100644 --- a/apps/mobile/src/shared/utils/demo-script.test.ts +++ b/apps/mobile/src/shared/utils/demo-script/__tests__/demo-script.test.ts @@ -5,7 +5,7 @@ import { buildDemoCompletionMessage, buildDemoDenialMessage, DEMO_SESSION_ID, -} from "./demo-script.ts" +} from "../index.ts" test("buildDemoScript: returns one user message followed by one assistant message", () => { const { messages } = buildDemoScript(1_000_000) diff --git a/apps/mobile/src/shared/utils/demo-script.ts b/apps/mobile/src/shared/utils/demo-script/index.ts similarity index 99% rename from apps/mobile/src/shared/utils/demo-script.ts rename to apps/mobile/src/shared/utils/demo-script/index.ts index cd45b70..8391c1d 100644 --- a/apps/mobile/src/shared/utils/demo-script.ts +++ b/apps/mobile/src/shared/utils/demo-script/index.ts @@ -5,7 +5,7 @@ // so the demo can render through the SAME presentational components // (MessageBubble, ToolCallCard, DiffView, PermissionPrompt) real sessions // use, instead of a parallel fake UI. -import type { Message, Part } from "./sdk" +import type { Message, Part } from "../sdk" export const DEMO_SESSION_ID = "demo-session" diff --git a/apps/mobile/src/shared/utils/diagnostics-classify.test.ts b/apps/mobile/src/shared/utils/diagnostics-classify/__tests__/diagnostics-classify.test.ts similarity index 98% rename from apps/mobile/src/shared/utils/diagnostics-classify.test.ts rename to apps/mobile/src/shared/utils/diagnostics-classify/__tests__/diagnostics-classify.test.ts index 16dee49..1f0e903 100644 --- a/apps/mobile/src/shared/utils/diagnostics-classify.test.ts +++ b/apps/mobile/src/shared/utils/diagnostics-classify/__tests__/diagnostics-classify.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { parseUrl, classify, type ProbeAttempt } from "./diagnostics-classify.ts" +import { parseUrl, classify, type ProbeAttempt } from "../index.ts" const probe = (over: Partial = {}): ProbeAttempt => ({ name: "p", diff --git a/apps/mobile/src/shared/utils/diagnostics-classify.ts b/apps/mobile/src/shared/utils/diagnostics-classify/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/diagnostics-classify.ts rename to apps/mobile/src/shared/utils/diagnostics-classify/index.ts diff --git a/apps/mobile/src/shared/utils/diagnostics.ts b/apps/mobile/src/shared/utils/diagnostics/index.ts similarity index 96% rename from apps/mobile/src/shared/utils/diagnostics.ts rename to apps/mobile/src/shared/utils/diagnostics/index.ts index 5bb5f30..dc597d6 100644 --- a/apps/mobile/src/shared/utils/diagnostics.ts +++ b/apps/mobile/src/shared/utils/diagnostics/index.ts @@ -4,11 +4,11 @@ import { Platform, Share } from "react-native" import * as Clipboard from "expo-clipboard" import * as Device from "expo-device" -import { APP_VERSION } from "./app-version" -import { log, formatLogLines } from "./logbuffer" -import { type Classification, type ProbeAttempt, type ParsedUrl, parseUrl, classify } from "./diagnostics-classify" +import { APP_VERSION } from "../app-version" +import { log, formatLogLines } from "../logbuffer" +import { type Classification, type ProbeAttempt, type ParsedUrl, parseUrl, classify } from "../diagnostics-classify" -export type { Classification, ProbeAttempt } from "./diagnostics-classify" +export type { Classification, ProbeAttempt } from "../diagnostics-classify" const PROBE_TIMEOUT_MS = 8_000 // Public 204 endpoints used purely as an "is the internet reachable at all" check. diff --git a/apps/mobile/src/shared/utils/git-remotes.test.ts b/apps/mobile/src/shared/utils/git-remotes/__tests__/git-remotes.test.ts similarity index 99% rename from apps/mobile/src/shared/utils/git-remotes.test.ts rename to apps/mobile/src/shared/utils/git-remotes/__tests__/git-remotes.test.ts index 337990e..197a89d 100644 --- a/apps/mobile/src/shared/utils/git-remotes.test.ts +++ b/apps/mobile/src/shared/utils/git-remotes/__tests__/git-remotes.test.ts @@ -6,7 +6,7 @@ import { gitProviderOfWebUrl, repoSlugOfWebUrl, toRepoLinks, -} from "./git-remotes.ts" +} from "../index.ts" // parseGitConfigRemotes ------------------------------------------------------- diff --git a/apps/mobile/src/shared/utils/git-remotes.ts b/apps/mobile/src/shared/utils/git-remotes/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/git-remotes.ts rename to apps/mobile/src/shared/utils/git-remotes/index.ts diff --git a/apps/mobile/src/shared/utils/github-mock.test.ts b/apps/mobile/src/shared/utils/github-mock/__tests__/github-mock.test.ts similarity index 89% rename from apps/mobile/src/shared/utils/github-mock.test.ts rename to apps/mobile/src/shared/utils/github-mock/__tests__/github-mock.test.ts index 09a4a4d..cd7c54b 100644 --- a/apps/mobile/src/shared/utils/github-mock.test.ts +++ b/apps/mobile/src/shared/utils/github-mock/__tests__/github-mock.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { filterMockRepos, MOCK_REPOS } from "./github-mock.ts" +import { filterMockRepos, MOCK_REPOS } from "../index.ts" test("filterMockRepos: empty query returns all", () => { assert.equal(filterMockRepos("").length, MOCK_REPOS.length) diff --git a/apps/mobile/src/shared/utils/github-mock.ts b/apps/mobile/src/shared/utils/github-mock/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/github-mock.ts rename to apps/mobile/src/shared/utils/github-mock/index.ts diff --git a/apps/mobile/src/shared/utils/headers.test.ts b/apps/mobile/src/shared/utils/headers/__tests__/headers.test.ts similarity index 98% rename from apps/mobile/src/shared/utils/headers.test.ts rename to apps/mobile/src/shared/utils/headers/__tests__/headers.test.ts index b1d9543..146c851 100644 --- a/apps/mobile/src/shared/utils/headers.test.ts +++ b/apps/mobile/src/shared/utils/headers/__tests__/headers.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { buildRequestHeaders } from "./headers.ts" +import { buildRequestHeaders } from "../index.ts" // These headers authenticate every request and tell the server which project // directory to operate in. A bug here breaks connections or silently targets the diff --git a/apps/mobile/src/shared/utils/headers.ts b/apps/mobile/src/shared/utils/headers/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/headers.ts rename to apps/mobile/src/shared/utils/headers/index.ts diff --git a/apps/mobile/src/shared/utils/i18n/catalog-parity.test.ts b/apps/mobile/src/shared/utils/i18n/__tests__/catalog-parity.test.ts similarity index 95% rename from apps/mobile/src/shared/utils/i18n/catalog-parity.test.ts rename to apps/mobile/src/shared/utils/i18n/__tests__/catalog-parity.test.ts index 43f1c26..567a7c6 100644 --- a/apps/mobile/src/shared/utils/i18n/catalog-parity.test.ts +++ b/apps/mobile/src/shared/utils/i18n/__tests__/catalog-parity.test.ts @@ -5,8 +5,8 @@ // as locale-resolve.test.ts. import { test } from "node:test" import assert from "node:assert/strict" -import en from "./en.json" with { type: "json" } -import ru from "./ru.json" with { type: "json" } +import en from "../en.json" with { type: "json" } +import ru from "../ru.json" with { type: "json" } // Flattens a nested translation object into dotted leaf-key paths, e.g. // { settings: { language: { label: "..." } } } -> ["settings.language.label"] diff --git a/apps/mobile/src/shared/utils/i18n/locale-resolve.test.ts b/apps/mobile/src/shared/utils/i18n/__tests__/locale-resolve.test.ts similarity index 98% rename from apps/mobile/src/shared/utils/i18n/locale-resolve.test.ts rename to apps/mobile/src/shared/utils/i18n/__tests__/locale-resolve.test.ts index 4a3be51..c007f32 100644 --- a/apps/mobile/src/shared/utils/i18n/locale-resolve.test.ts +++ b/apps/mobile/src/shared/utils/i18n/__tests__/locale-resolve.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { matchSupportedLocale, resolveLocale, FALLBACK_LOCALE } from "./locale-resolve.ts" +import { matchSupportedLocale, resolveLocale, FALLBACK_LOCALE } from "../locale-resolve.ts" test("matchSupportedLocale maps ru variants to ru", () => { assert.equal(matchSupportedLocale("ru"), "ru") diff --git a/apps/mobile/src/shared/utils/i18n/index.ts b/apps/mobile/src/shared/utils/i18n/index.ts new file mode 100644 index 0000000..b592485 --- /dev/null +++ b/apps/mobile/src/shared/utils/i18n/index.ts @@ -0,0 +1,2 @@ +export * from "./config" +export * from "./locale-resolve" diff --git a/apps/mobile/src/shared/utils/lan-manual.ts b/apps/mobile/src/shared/utils/lan-manual/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/lan-manual.ts rename to apps/mobile/src/shared/utils/lan-manual/index.ts diff --git a/apps/mobile/src/shared/utils/links.ts b/apps/mobile/src/shared/utils/links/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/links.ts rename to apps/mobile/src/shared/utils/links/index.ts diff --git a/apps/mobile/src/shared/utils/listed-session.test.ts b/apps/mobile/src/shared/utils/listed-session/__tests__/listed-session.test.ts similarity index 89% rename from apps/mobile/src/shared/utils/listed-session.test.ts rename to apps/mobile/src/shared/utils/listed-session/__tests__/listed-session.test.ts index 37c73ec..b6bb5f9 100644 --- a/apps/mobile/src/shared/utils/listed-session.test.ts +++ b/apps/mobile/src/shared/utils/listed-session/__tests__/listed-session.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { lanConnectionIds, mergeSessionLists } from "./listed-session.ts" -import type { Session } from "./sdk.ts" +import { lanConnectionIds, mergeSessionLists } from "../index.ts" +import type { Session } from "../../sdk/index.ts/index.ts" const session = (id: string, updated: number, directory = "/proj"): Session => ({ id, diff --git a/apps/mobile/src/shared/utils/listed-session.ts b/apps/mobile/src/shared/utils/listed-session/index.ts similarity index 93% rename from apps/mobile/src/shared/utils/listed-session.ts rename to apps/mobile/src/shared/utils/listed-session/index.ts index e483c61..39935e9 100644 --- a/apps/mobile/src/shared/utils/listed-session.ts +++ b/apps/mobile/src/shared/utils/listed-session/index.ts @@ -1,8 +1,8 @@ // Multi-server session listing: every session rendered in a list carries the // connection it came from, so actions (open/delete/rename) and badges can // route to / mark the right server. Pure — unit-testable under node --test. -import type { Session } from "./sdk" -import type { ServerConnection } from "./types" +import type { Session } from "../sdk" +import type { ServerConnection } from "../types" /** A session snapshot tagged with its origin connection. */ export type ListedSession = Session & { diff --git a/apps/mobile/src/shared/utils/logbuffer.test.ts b/apps/mobile/src/shared/utils/logbuffer/__tests__/logbuffer.test.ts similarity index 99% rename from apps/mobile/src/shared/utils/logbuffer.test.ts rename to apps/mobile/src/shared/utils/logbuffer/__tests__/logbuffer.test.ts index 8bb9794..273a94e 100644 --- a/apps/mobile/src/shared/utils/logbuffer.test.ts +++ b/apps/mobile/src/shared/utils/logbuffer/__tests__/logbuffer.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { log, getLogEntries, formatLogLines, clearLog, type LogEntry } from "./logbuffer.ts" +import { log, getLogEntries, formatLogLines, clearLog, type LogEntry } from "../index.ts" // The log buffer backs diagnostic reports. A regression in its ring-buffer cap, // message serialization, or formatting silently corrupts the attached logs, so diff --git a/apps/mobile/src/shared/utils/logbuffer.ts b/apps/mobile/src/shared/utils/logbuffer/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/logbuffer.ts rename to apps/mobile/src/shared/utils/logbuffer/index.ts diff --git a/apps/mobile/src/shared/utils/message-merge.test.ts b/apps/mobile/src/shared/utils/message-merge/__tests__/message-merge.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/message-merge.test.ts rename to apps/mobile/src/shared/utils/message-merge/__tests__/message-merge.test.ts index 31943d8..54ab84a 100644 --- a/apps/mobile/src/shared/utils/message-merge.test.ts +++ b/apps/mobile/src/shared/utils/message-merge/__tests__/message-merge.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { mergeIncomingMessage } from "./message-merge.ts" -import type { Message } from "./sdk.ts" +import { mergeIncomingMessage } from "../index.ts" +import type { Message } from "../../sdk/index.ts/index.ts" const msg = (id: string, role: "user" | "assistant" = "user"): Message => ({ id, diff --git a/apps/mobile/src/shared/utils/message-merge.ts b/apps/mobile/src/shared/utils/message-merge/index.ts similarity index 97% rename from apps/mobile/src/shared/utils/message-merge.ts rename to apps/mobile/src/shared/utils/message-merge/index.ts index 25bd7e6..30a2914 100644 --- a/apps/mobile/src/shared/utils/message-merge.ts +++ b/apps/mobile/src/shared/utils/message-merge/index.ts @@ -1,4 +1,4 @@ -import type { Message } from "./sdk" +import type { Message } from "../sdk" /** * Merge a server `message.updated` event into the current message list. diff --git a/apps/mobile/src/shared/utils/message-queue.test.ts b/apps/mobile/src/shared/utils/message-queue/__tests__/message-queue.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/message-queue.test.ts rename to apps/mobile/src/shared/utils/message-queue/__tests__/message-queue.test.ts index a58ca27..21f8714 100644 --- a/apps/mobile/src/shared/utils/message-queue.test.ts +++ b/apps/mobile/src/shared/utils/message-queue/__tests__/message-queue.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "node:test" import assert from "node:assert/strict" -import { createQueuedDraft, enqueueDraft, dequeueDraft, removeDraft, updateDraftText } from "./message-queue.ts" +import { createQueuedDraft, enqueueDraft, dequeueDraft, removeDraft, updateDraftText } from "../index.ts" describe("message-queue", () => { it("enqueues in FIFO order with unique ids", () => { diff --git a/apps/mobile/src/shared/utils/message-queue.ts b/apps/mobile/src/shared/utils/message-queue/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/message-queue.ts rename to apps/mobile/src/shared/utils/message-queue/index.ts diff --git a/apps/mobile/src/shared/utils/model-selection.test.ts b/apps/mobile/src/shared/utils/model-selection/__tests__/model-selection.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/model-selection.test.ts rename to apps/mobile/src/shared/utils/model-selection/__tests__/model-selection.test.ts index 4bc0746..51b0afa 100644 --- a/apps/mobile/src/shared/utils/model-selection.test.ts +++ b/apps/mobile/src/shared/utils/model-selection/__tests__/model-selection.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { chooseModelSelection } from "./model-selection.ts" +import { chooseModelSelection } from "../index.ts" const providers = [ { diff --git a/apps/mobile/src/shared/utils/model-selection.ts b/apps/mobile/src/shared/utils/model-selection/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/model-selection.ts rename to apps/mobile/src/shared/utils/model-selection/index.ts diff --git a/apps/mobile/src/shared/utils/notifications.ts b/apps/mobile/src/shared/utils/notifications/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/notifications.ts rename to apps/mobile/src/shared/utils/notifications/index.ts diff --git a/apps/mobile/src/shared/utils/notify-format.test.ts b/apps/mobile/src/shared/utils/notify-format/__tests__/notify-format.test.ts similarity index 95% rename from apps/mobile/src/shared/utils/notify-format.test.ts rename to apps/mobile/src/shared/utils/notify-format/__tests__/notify-format.test.ts index 65da5c2..5c6f62c 100644 --- a/apps/mobile/src/shared/utils/notify-format.test.ts +++ b/apps/mobile/src/shared/utils/notify-format/__tests__/notify-format.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { sanitizeBody, MAX_NOTIF_BODY } from "./notify-format.ts" +import { sanitizeBody, MAX_NOTIF_BODY } from "../index.ts" // Notification bodies come from the server (and ultimately the AI). They must be // neutralized before display: control chars stripped, whitespace trimmed, length capped. diff --git a/apps/mobile/src/shared/utils/notify-format.ts b/apps/mobile/src/shared/utils/notify-format/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/notify-format.ts rename to apps/mobile/src/shared/utils/notify-format/index.ts diff --git a/apps/mobile/src/shared/utils/outbox-flush.ts b/apps/mobile/src/shared/utils/outbox-flush/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/outbox-flush.ts rename to apps/mobile/src/shared/utils/outbox-flush/index.ts diff --git a/apps/mobile/src/shared/utils/part-merge.test.ts b/apps/mobile/src/shared/utils/part-merge/__tests__/part-merge.test.ts similarity index 95% rename from apps/mobile/src/shared/utils/part-merge.test.ts rename to apps/mobile/src/shared/utils/part-merge/__tests__/part-merge.test.ts index 3570ed4..533af68 100644 --- a/apps/mobile/src/shared/utils/part-merge.test.ts +++ b/apps/mobile/src/shared/utils/part-merge/__tests__/part-merge.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { applyIncomingParts } from "./part-merge.ts" -import type { Part } from "./sdk.ts" +import { applyIncomingParts } from "../index.ts" +import type { Part } from "../../sdk/index.ts/index.ts" const part = (id: string, messageID: string, text?: string): Part => ({ id, diff --git a/apps/mobile/src/shared/utils/part-merge.ts b/apps/mobile/src/shared/utils/part-merge/index.ts similarity index 96% rename from apps/mobile/src/shared/utils/part-merge.ts rename to apps/mobile/src/shared/utils/part-merge/index.ts index 6525d25..b2902c6 100644 --- a/apps/mobile/src/shared/utils/part-merge.ts +++ b/apps/mobile/src/shared/utils/part-merge/index.ts @@ -1,7 +1,7 @@ // Pure merge of incoming part snapshots into the per-message parts map. // Extracted from the sessions store's SSE handlers so the rules are // unit-testable under plain `node --test`. -import type { Part } from "./sdk" +import type { Part } from "../sdk" /** * Merge `incoming` parts into `current[messageID]`, matching by part id: diff --git a/apps/mobile/src/shared/utils/prompt-from-parts.test.ts b/apps/mobile/src/shared/utils/prompt-from-parts/__tests__/prompt-from-parts.test.ts similarity index 92% rename from apps/mobile/src/shared/utils/prompt-from-parts.test.ts rename to apps/mobile/src/shared/utils/prompt-from-parts/__tests__/prompt-from-parts.test.ts index de76647..4c1eaa2 100644 --- a/apps/mobile/src/shared/utils/prompt-from-parts.test.ts +++ b/apps/mobile/src/shared/utils/prompt-from-parts/__tests__/prompt-from-parts.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { extractPromptFromParts } from "./prompt-from-parts.ts" -import type { Part } from "./sdk.ts" +import { extractPromptFromParts } from "../index.ts" +import type { Part } from "../../sdk/index.ts/index.ts" test("extractPromptFromParts: joins multiple text parts with newlines", () => { const parts: Part[] = [ diff --git a/apps/mobile/src/shared/utils/prompt-from-parts.ts b/apps/mobile/src/shared/utils/prompt-from-parts/index.ts similarity index 94% rename from apps/mobile/src/shared/utils/prompt-from-parts.ts rename to apps/mobile/src/shared/utils/prompt-from-parts/index.ts index e4c3b96..90fae35 100644 --- a/apps/mobile/src/shared/utils/prompt-from-parts.ts +++ b/apps/mobile/src/shared/utils/prompt-from-parts/index.ts @@ -2,7 +2,7 @@ // state (text + file attachments), mirroring the TUI's revert-to-edit // reduce (packages/tui/src/routes/session/dialog-message.tsx). Kept // dependency-free so it's testable under plain `node --test`. -import type { Part } from "./sdk" +import type { Part } from "../sdk" export type PromptFromParts = { text: string diff --git a/apps/mobile/src/shared/utils/query-client.ts b/apps/mobile/src/shared/utils/query-client/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/query-client.ts rename to apps/mobile/src/shared/utils/query-client/index.ts diff --git a/apps/mobile/src/shared/utils/query-invalidate.ts b/apps/mobile/src/shared/utils/query-invalidate/index.ts similarity index 86% rename from apps/mobile/src/shared/utils/query-invalidate.ts rename to apps/mobile/src/shared/utils/query-invalidate/index.ts index 43e2a85..bcc9665 100644 --- a/apps/mobile/src/shared/utils/query-invalidate.ts +++ b/apps/mobile/src/shared/utils/query-invalidate/index.ts @@ -1,5 +1,5 @@ -import { queryClient } from "./query-client" -import { queryKeys, sessionsScopePrefix } from "./query-keys" +import { queryClient } from "../query-client" +import { queryKeys, sessionsScopePrefix } from "../query-keys" // Drop every snapshot scoped to the connection identity (sessions subtree, // catalog, project info, server projects). Call after any change that swaps diff --git a/apps/mobile/src/shared/utils/query-keys.test.ts b/apps/mobile/src/shared/utils/query-keys/__tests__/query-keys.test.ts similarity index 95% rename from apps/mobile/src/shared/utils/query-keys.test.ts rename to apps/mobile/src/shared/utils/query-keys/__tests__/query-keys.test.ts index 4df8329..63f2e85 100644 --- a/apps/mobile/src/shared/utils/query-keys.test.ts +++ b/apps/mobile/src/shared/utils/query-keys/__tests__/query-keys.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { queryKeys, sessionsScopePrefix } from "./query-keys.ts" +import { queryKeys, sessionsScopePrefix } from "../index.ts" test("list/catalog/project keys are stable literals", () => { assert.deepEqual([...queryKeys.sessionsList], ["sessions", "list"]) diff --git a/apps/mobile/src/shared/utils/query-keys.ts b/apps/mobile/src/shared/utils/query-keys/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/query-keys.ts rename to apps/mobile/src/shared/utils/query-keys/index.ts diff --git a/apps/mobile/src/shared/utils/reconnect-flash.ts b/apps/mobile/src/shared/utils/reconnect-flash/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/reconnect-flash.ts rename to apps/mobile/src/shared/utils/reconnect-flash/index.ts diff --git a/apps/mobile/src/shared/utils/revert-flow.ts b/apps/mobile/src/shared/utils/revert-flow/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/revert-flow.ts rename to apps/mobile/src/shared/utils/revert-flow/index.ts diff --git a/apps/mobile/src/shared/utils/revert-prune.test.ts b/apps/mobile/src/shared/utils/revert-prune/__tests__/revert-prune.test.ts similarity index 95% rename from apps/mobile/src/shared/utils/revert-prune.test.ts rename to apps/mobile/src/shared/utils/revert-prune/__tests__/revert-prune.test.ts index be0c0da..6f9ed32 100644 --- a/apps/mobile/src/shared/utils/revert-prune.test.ts +++ b/apps/mobile/src/shared/utils/revert-prune/__tests__/revert-prune.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { pruneRevertedTail } from "./revert-prune.ts" -import type { Message, Part } from "./sdk.ts" +import { pruneRevertedTail } from "../index.ts" +import type { Message, Part } from "../../sdk/index.ts/index.ts" const msg = (id: string, role: "user" | "assistant" = "user"): Message => ({ id, diff --git a/apps/mobile/src/shared/utils/revert-prune.ts b/apps/mobile/src/shared/utils/revert-prune/index.ts similarity index 97% rename from apps/mobile/src/shared/utils/revert-prune.ts rename to apps/mobile/src/shared/utils/revert-prune/index.ts index 7c09537..2664afd 100644 --- a/apps/mobile/src/shared/utils/revert-prune.ts +++ b/apps/mobile/src/shared/utils/revert-prune/index.ts @@ -1,4 +1,4 @@ -import type { Message, Part } from "./sdk" +import type { Message, Part } from "../sdk" /** * Optimistically drop the reverted tail from local chat state. diff --git a/apps/mobile/src/shared/utils/sdk.ts b/apps/mobile/src/shared/utils/sdk/index.ts similarity index 92% rename from apps/mobile/src/shared/utils/sdk.ts rename to apps/mobile/src/shared/utils/sdk/index.ts index 8d5e9b6..427e4d8 100644 --- a/apps/mobile/src/shared/utils/sdk.ts +++ b/apps/mobile/src/shared/utils/sdk/index.ts @@ -2,14 +2,25 @@ // We create our own lightweight client that mirrors the devbox SDK patterns // but works in React Native environment // expo/fetch provides WinterCG-compliant fetch with ReadableStream support for SSE +// +// NOTE (card 4/5, wire freeze): the types below are UPSTREAM opencode shapes +// (`/global/health`, `/session`, `/project`, … on the opencode server itself), +// NOT backend `/api/v1/*` wire from `@devbox/contracts`. In particular +// `HealthResponse` ({ healthy, version }) mirrors openapi `OpencodeHealth`, +// `Session`/`Project` mirror the upstream session/project objects, and the +// `ApiError` class below is a transport error (HTTP status + body) — not the +// backend `ApiError` envelope ({ code, message, correlationId }). Backend wire +// (Health/Session/MessagesResponse/Project/Organization/OpencodeKey*/Usage + +// zod v4 boundary schemas) lives in `@/api/backend-contracts` — import from +// there when speaking `/api/v1`, never swap these upstream types. import { fetch as expoFetch } from "expo/fetch" -import { buildRequestHeaders } from "./headers" -import { SSEParser } from "./sse" -import { apiErrorFor } from "./api-error" -import { loadSessionList } from "./session-list" +import { buildRequestHeaders } from "../headers" +import { SSEParser } from "../sse" +import { apiErrorFor } from "../api-error" +import { loadSessionList } from "../session-list" import type { FileRoot } from "@web2bizz/ui-native" -export { ApiAuthError, isAuthError } from "./api-error" +export { ApiAuthError, isAuthError } from "../api-error" export type ClientConfig = { baseUrl: string @@ -176,6 +187,8 @@ export type Event = { properties: Record } +// Upstream `GET /global/health` shape (= openapi `OpencodeHealth`), NOT the +// backend `GET /health` wire (`HealthResponse` in `@/api/backend-contracts`). export type HealthResponse = { healthy: boolean version: string @@ -186,6 +199,9 @@ const REQUEST_TIMEOUT_MS = 30_000 // Thrown by request() on a non-2xx response. Carries the HTTP status so // callers can distinguish e.g. 404 (older server, endpoint missing) from // other failures without parsing the message string. +// Transport error for upstream non-2xx (status + raw body). NOT the backend +// `ApiError` envelope ({ code, message, correlationId } in +// `@/api/backend-contracts`) — do not conflate; see the header note. export class ApiError extends Error { status: number constructor(status: number, body: string) { diff --git a/apps/mobile/src/shared/utils/server-config.ts b/apps/mobile/src/shared/utils/server-config/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/server-config.ts rename to apps/mobile/src/shared/utils/server-config/index.ts diff --git a/apps/mobile/src/shared/utils/session-alerts.ts b/apps/mobile/src/shared/utils/session-alerts/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/session-alerts.ts rename to apps/mobile/src/shared/utils/session-alerts/index.ts diff --git a/apps/mobile/src/shared/utils/session-binding.ts b/apps/mobile/src/shared/utils/session-binding/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/session-binding.ts rename to apps/mobile/src/shared/utils/session-binding/index.ts diff --git a/apps/mobile/src/shared/utils/session-grouping.test.ts b/apps/mobile/src/shared/utils/session-grouping/__tests__/session-grouping.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/session-grouping.test.ts rename to apps/mobile/src/shared/utils/session-grouping/__tests__/session-grouping.test.ts index 8a1d535..054d054 100644 --- a/apps/mobile/src/shared/utils/session-grouping.test.ts +++ b/apps/mobile/src/shared/utils/session-grouping/__tests__/session-grouping.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { groupByDirectory, groupProjects } from "./session-grouping.ts" +import { groupByDirectory, groupProjects } from "../index.ts" test("groupByDirectory: buckets items by directory, preserving item order within a bucket", () => { const items = [ diff --git a/apps/mobile/src/shared/utils/session-grouping.ts b/apps/mobile/src/shared/utils/session-grouping/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/session-grouping.ts rename to apps/mobile/src/shared/utils/session-grouping/index.ts diff --git a/apps/mobile/src/shared/utils/session-list.integration.test.ts b/apps/mobile/src/shared/utils/session-list/__tests__/session-list.integration.test.ts similarity index 97% rename from apps/mobile/src/shared/utils/session-list.integration.test.ts rename to apps/mobile/src/shared/utils/session-list/__tests__/session-list.integration.test.ts index 906f554..c5726c3 100644 --- a/apps/mobile/src/shared/utils/session-list.integration.test.ts +++ b/apps/mobile/src/shared/utils/session-list/__tests__/session-list.integration.test.ts @@ -11,8 +11,8 @@ import { test, before, after } from "node:test" import assert from "node:assert/strict" -import { createMockOpencodeServer } from "../../../tests/fixtures/mock-opencode-server.ts" -import { loadSessionList, legacySessionQuery, type SessionListTransport } from "./session-list.ts" +import { createMockOpencodeServer } from "../../../../../tests/fixtures/mock-opencode-server.ts" +import { loadSessionList, legacySessionQuery, type SessionListTransport } from "../index.ts" const PORT = 45071 let mock: ReturnType diff --git a/apps/mobile/src/shared/utils/session-list.test.ts b/apps/mobile/src/shared/utils/session-list/__tests__/session-list.test.ts similarity index 97% rename from apps/mobile/src/shared/utils/session-list.test.ts rename to apps/mobile/src/shared/utils/session-list/__tests__/session-list.test.ts index 4b3fbb4..d87a9d0 100644 --- a/apps/mobile/src/shared/utils/session-list.test.ts +++ b/apps/mobile/src/shared/utils/session-list/__tests__/session-list.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { loadSessionList, normalizeSessions, legacySessionQuery, type SessionListTransport } from "./session-list.ts" -import type { Session } from "./sdk.ts" +import { loadSessionList, normalizeSessions, legacySessionQuery, type SessionListTransport } from "../index.ts" +import type { Session } from "../../sdk/index.ts/index.ts" // Minimal Session factory — only the fields the list logic reads. function session(over: Partial & { id: string }): Session { diff --git a/apps/mobile/src/shared/utils/session-list.ts b/apps/mobile/src/shared/utils/session-list/index.ts similarity index 98% rename from apps/mobile/src/shared/utils/session-list.ts rename to apps/mobile/src/shared/utils/session-list/index.ts index a303068..4967071 100644 --- a/apps/mobile/src/shared/utils/session-list.ts +++ b/apps/mobile/src/shared/utils/session-list/index.ts @@ -8,7 +8,7 @@ // global `GET /experimental/session` returns EVERY session across ALL // directories. We prefer it, and fall back to the legacy directory path only on // 404 (older servers without the experimental route). -import type { Session } from "./sdk" +import type { Session } from "../sdk" export type SessionListParams = { roots?: boolean diff --git a/apps/mobile/src/shared/utils/session-load-reconcile.test.ts b/apps/mobile/src/shared/utils/session-load-reconcile/__tests__/session-load-reconcile.test.ts similarity index 93% rename from apps/mobile/src/shared/utils/session-load-reconcile.test.ts rename to apps/mobile/src/shared/utils/session-load-reconcile/__tests__/session-load-reconcile.test.ts index 578e08b..297e13f 100644 --- a/apps/mobile/src/shared/utils/session-load-reconcile.test.ts +++ b/apps/mobile/src/shared/utils/session-load-reconcile/__tests__/session-load-reconcile.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { isColdSessionLoad, isLiveEventForSession } from "./session-load-reconcile.ts" +import { isColdSessionLoad, isLiveEventForSession } from "../index.ts" test("isColdSessionLoad: no session shown yet -> cold (needs the spinner)", () => { assert.equal(isColdSessionLoad(undefined, "s1"), true) diff --git a/apps/mobile/src/shared/utils/session-load-reconcile.ts b/apps/mobile/src/shared/utils/session-load-reconcile/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/session-load-reconcile.ts rename to apps/mobile/src/shared/utils/session-load-reconcile/index.ts diff --git a/apps/mobile/src/shared/utils/session-status-reconcile.test.ts b/apps/mobile/src/shared/utils/session-status-reconcile/__tests__/session-status-reconcile.test.ts similarity index 94% rename from apps/mobile/src/shared/utils/session-status-reconcile.test.ts rename to apps/mobile/src/shared/utils/session-status-reconcile/__tests__/session-status-reconcile.test.ts index 6219cf4..e82e8a7 100644 --- a/apps/mobile/src/shared/utils/session-status-reconcile.test.ts +++ b/apps/mobile/src/shared/utils/session-status-reconcile/__tests__/session-status-reconcile.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { isSessionActuallyIdle } from "./session-status-reconcile.ts" -import type { Message } from "./sdk.ts" +import { isSessionActuallyIdle } from "../index.ts" +import type { Message } from "../../sdk/index.ts/index.ts" const userMsg = (id: string, overrides: Partial = {}): Message => ({ id, diff --git a/apps/mobile/src/shared/utils/session-status-reconcile.ts b/apps/mobile/src/shared/utils/session-status-reconcile/index.ts similarity index 97% rename from apps/mobile/src/shared/utils/session-status-reconcile.ts rename to apps/mobile/src/shared/utils/session-status-reconcile/index.ts index 84c6c74..f8c0959 100644 --- a/apps/mobile/src/shared/utils/session-status-reconcile.ts +++ b/apps/mobile/src/shared/utils/session-status-reconcile/index.ts @@ -1,4 +1,4 @@ -import type { Message } from "./sdk" +import type { Message } from "../sdk" /** * Decide whether a session the client believes is "busy" has actually diff --git a/apps/mobile/src/shared/utils/session/index.ts b/apps/mobile/src/shared/utils/session/index.ts index 7c3ac54..4ccc950 100644 --- a/apps/mobile/src/shared/utils/session/index.ts +++ b/apps/mobile/src/shared/utils/session/index.ts @@ -1,2 +1,2 @@ export * from "../session-binding" -export * from "../use-session-screen" +export * from "../../hooks/use-session-screen" diff --git a/apps/mobile/src/shared/utils/settings-merge.test.ts b/apps/mobile/src/shared/utils/settings-merge/__tests__/settings-merge.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/settings-merge.test.ts rename to apps/mobile/src/shared/utils/settings-merge/__tests__/settings-merge.test.ts index 20ea673..084d7b1 100644 --- a/apps/mobile/src/shared/utils/settings-merge.test.ts +++ b/apps/mobile/src/shared/utils/settings-merge/__tests__/settings-merge.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { clampPageSize, mergeStoredSettings } from "./settings-merge.ts" +import { clampPageSize, mergeStoredSettings } from "../index.ts" const DEFAULTS = { pageSize: 25, diff --git a/apps/mobile/src/shared/utils/settings-merge.ts b/apps/mobile/src/shared/utils/settings-merge/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/settings-merge.ts rename to apps/mobile/src/shared/utils/settings-merge/index.ts diff --git a/apps/mobile/src/shared/utils/slash-state.ts b/apps/mobile/src/shared/utils/slash-state/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/slash-state.ts rename to apps/mobile/src/shared/utils/slash-state/index.ts diff --git a/apps/mobile/src/shared/utils/speech.ts b/apps/mobile/src/shared/utils/speech/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/speech.ts rename to apps/mobile/src/shared/utils/speech/index.ts diff --git a/apps/mobile/src/shared/utils/sse.test.ts b/apps/mobile/src/shared/utils/sse/__tests__/sse.test.ts similarity index 98% rename from apps/mobile/src/shared/utils/sse.test.ts rename to apps/mobile/src/shared/utils/sse/__tests__/sse.test.ts index 396ab51..45c0544 100644 --- a/apps/mobile/src/shared/utils/sse.test.ts +++ b/apps/mobile/src/shared/utils/sse/__tests__/sse.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { SSEParser } from "./sse.ts" +import { SSEParser } from "../index.ts" // The opencode live chat is driven by this SSE stream. The hard cases are framing: // events that arrive split across network reads must not be dropped or corrupted. diff --git a/apps/mobile/src/shared/utils/sse.ts b/apps/mobile/src/shared/utils/sse/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/sse.ts rename to apps/mobile/src/shared/utils/sse/index.ts diff --git a/apps/mobile/src/shared/utils/status-labels.test.ts b/apps/mobile/src/shared/utils/status-labels/__tests__/status-labels.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/status-labels.test.ts rename to apps/mobile/src/shared/utils/status-labels/__tests__/status-labels.test.ts index e27b6f3..d90f1ce 100644 --- a/apps/mobile/src/shared/utils/status-labels.test.ts +++ b/apps/mobile/src/shared/utils/status-labels/__tests__/status-labels.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { statusFromPart, TOOL_STATUS } from "./status-labels.ts" +import { statusFromPart, TOOL_STATUS } from "../index.ts" // These labels are shown live while the agent works. A new tool type must degrade // to a sensible "Running ..." rather than a blank or wrong status. diff --git a/apps/mobile/src/shared/utils/status-labels.ts b/apps/mobile/src/shared/utils/status-labels/index.ts similarity index 96% rename from apps/mobile/src/shared/utils/status-labels.ts rename to apps/mobile/src/shared/utils/status-labels/index.ts index f17c2e4..65f1203 100644 --- a/apps/mobile/src/shared/utils/status-labels.ts +++ b/apps/mobile/src/shared/utils/status-labels/index.ts @@ -1,7 +1,7 @@ // Human-readable status labels shown while the agent works ("Searching codebase..."). // Extracted from stores/events.ts so the mapping is unit-testable in isolation. // `import type` is erased at runtime, so this module pulls in no RN/SDK code. -import type { Part } from "./sdk" +import type { Part } from "../sdk" // Tool status labels derived from part type. export const TOOL_STATUS: Record = { diff --git a/apps/mobile/src/shared/utils/store-review-policy.test.ts b/apps/mobile/src/shared/utils/store-review-policy/__tests__/store-review-policy.test.ts similarity index 96% rename from apps/mobile/src/shared/utils/store-review-policy.test.ts rename to apps/mobile/src/shared/utils/store-review-policy/__tests__/store-review-policy.test.ts index 4b4ae2a..c3599d1 100644 --- a/apps/mobile/src/shared/utils/store-review-policy.test.ts +++ b/apps/mobile/src/shared/utils/store-review-policy/__tests__/store-review-policy.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test" import assert from "node:assert/strict" -import { shouldRequestReview, DEFAULT_REVIEW_THRESHOLD } from "./store-review-policy.ts" +import { shouldRequestReview, DEFAULT_REVIEW_THRESHOLD } from "../index.ts" test("below the default threshold -> false", () => { assert.equal(shouldRequestReview(0), false) diff --git a/apps/mobile/src/shared/utils/store-review-policy.ts b/apps/mobile/src/shared/utils/store-review-policy/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/store-review-policy.ts rename to apps/mobile/src/shared/utils/store-review-policy/index.ts diff --git a/apps/mobile/src/shared/utils/store-review.ts b/apps/mobile/src/shared/utils/store-review/index.ts similarity index 99% rename from apps/mobile/src/shared/utils/store-review.ts rename to apps/mobile/src/shared/utils/store-review/index.ts index d5cbca8..228e7d6 100644 --- a/apps/mobile/src/shared/utils/store-review.ts +++ b/apps/mobile/src/shared/utils/store-review/index.ts @@ -20,7 +20,7 @@ import * as SecureStore from "expo-secure-store" import * as StoreReview from "expo-store-review" -import { shouldRequestReview, DEFAULT_REVIEW_THRESHOLD } from "./store-review-policy" +import { shouldRequestReview, DEFAULT_REVIEW_THRESHOLD } from "../store-review-policy" const COUNT_KEY = "opencode_review_success_count" const ASKED_KEY = "opencode_review_asked" diff --git a/apps/mobile/src/shared/utils/types.ts b/apps/mobile/src/shared/utils/types/index.ts similarity index 98% rename from apps/mobile/src/shared/utils/types.ts rename to apps/mobile/src/shared/utils/types/index.ts index f035652..3dd2454 100644 --- a/apps/mobile/src/shared/utils/types.ts +++ b/apps/mobile/src/shared/utils/types/index.ts @@ -34,4 +34,4 @@ export type AppSettings = { } // Re-export SDK types we'll use frequently -export type { Session, Message, Part, Project, Event, HealthResponse } from "./sdk" +export type { Session, Message, Part, Project, Event, HealthResponse } from "../sdk" diff --git a/apps/mobile/src/shared/utils/update-check-policy.test.ts b/apps/mobile/src/shared/utils/update-check-policy/__tests__/update-check-policy.test.ts similarity index 99% rename from apps/mobile/src/shared/utils/update-check-policy.test.ts rename to apps/mobile/src/shared/utils/update-check-policy/__tests__/update-check-policy.test.ts index 4b6e771..b1e34e4 100644 --- a/apps/mobile/src/shared/utils/update-check-policy.test.ts +++ b/apps/mobile/src/shared/utils/update-check-policy/__tests__/update-check-policy.test.ts @@ -11,7 +11,7 @@ import { LAST_CHECK_KEY, LATEST_KEY, DISMISSED_KEY, -} from "./update-check-policy.ts" +} from "../index.ts" test("parseVersion accepts the shapes our releases actually use", () => { assert.deepEqual(parseVersion("0.4.10"), [0, 4, 10]) diff --git a/apps/mobile/src/shared/utils/update-check-policy.ts b/apps/mobile/src/shared/utils/update-check-policy/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/update-check-policy.ts rename to apps/mobile/src/shared/utils/update-check-policy/index.ts diff --git a/apps/mobile/src/shared/utils/update-check.ts b/apps/mobile/src/shared/utils/update-check/index.ts similarity index 97% rename from apps/mobile/src/shared/utils/update-check.ts rename to apps/mobile/src/shared/utils/update-check/index.ts index 3e00ac0..5d54f3f 100644 --- a/apps/mobile/src/shared/utils/update-check.ts +++ b/apps/mobile/src/shared/utils/update-check/index.ts @@ -28,13 +28,13 @@ import { Platform } from "react-native" import AsyncStorage from "@react-native-async-storage/async-storage" -import { APP_VERSION } from "./app-version" +import { APP_VERSION } from "../app-version" import { DISMISSED_KEY, resolveUpdate, type AvailableUpdate, type UpdateStorage, -} from "./update-check-policy" +} from "../update-check-policy" export type { AvailableUpdate } diff --git a/apps/mobile/src/shared/utils/waitlist-queue-storage.ts b/apps/mobile/src/shared/utils/waitlist-queue-storage/index.ts similarity index 99% rename from apps/mobile/src/shared/utils/waitlist-queue-storage.ts rename to apps/mobile/src/shared/utils/waitlist-queue-storage/index.ts index d9e16be..26eeb8b 100644 --- a/apps/mobile/src/shared/utils/waitlist-queue-storage.ts +++ b/apps/mobile/src/shared/utils/waitlist-queue-storage/index.ts @@ -9,7 +9,7 @@ // the whole point is that the signup is never silently lost. import AsyncStorage from "@react-native-async-storage/async-storage" -import { flushQueue, loadQueue, enqueueSignup, removeFromQueue, type FlushOutcome, type QueuedSignup, type QueueStorage } from "./waitlist" +import { flushQueue, loadQueue, enqueueSignup, removeFromQueue, type FlushOutcome, type QueuedSignup, type QueueStorage } from "../waitlist" const storage: QueueStorage = { getItem: (key) => AsyncStorage.getItem(key), diff --git a/apps/mobile/src/shared/utils/waitlist-queue.test.ts b/apps/mobile/src/shared/utils/waitlist/__tests__/waitlist-queue.test.ts similarity index 99% rename from apps/mobile/src/shared/utils/waitlist-queue.test.ts rename to apps/mobile/src/shared/utils/waitlist/__tests__/waitlist-queue.test.ts index f1d5940..72523bf 100644 --- a/apps/mobile/src/shared/utils/waitlist-queue.test.ts +++ b/apps/mobile/src/shared/utils/waitlist/__tests__/waitlist-queue.test.ts @@ -13,7 +13,7 @@ import { type QueueStorage, type QueuedSignup, type WaitlistResult, -} from "./waitlist.ts" +} from "../index.ts" // In-memory stand-in for AsyncStorage. `fail` makes every write throw, which is // how a device with full/locked storage behaves. diff --git a/apps/mobile/src/shared/utils/waitlist.test.ts b/apps/mobile/src/shared/utils/waitlist/__tests__/waitlist.test.ts similarity index 99% rename from apps/mobile/src/shared/utils/waitlist.test.ts rename to apps/mobile/src/shared/utils/waitlist/__tests__/waitlist.test.ts index 3829fb5..ac7c6c4 100644 --- a/apps/mobile/src/shared/utils/waitlist.test.ts +++ b/apps/mobile/src/shared/utils/waitlist/__tests__/waitlist.test.ts @@ -8,7 +8,7 @@ import { buildWaitlistMailtoUrl, isRetryableFailure, submitWaitlistSignup, -} from "./waitlist.ts" +} from "../index.ts" // --- normalizeWaitlistEmail: mirror of the server's 400 rule --- diff --git a/apps/mobile/src/shared/utils/waitlist.ts b/apps/mobile/src/shared/utils/waitlist/index.ts similarity index 100% rename from apps/mobile/src/shared/utils/waitlist.ts rename to apps/mobile/src/shared/utils/waitlist/index.ts diff --git a/apps/mobile/src/types/expo-icons.d.ts b/apps/mobile/src/types/expo-icons.d.ts index 10379c0..66035af 100644 --- a/apps/mobile/src/types/expo-icons.d.ts +++ b/apps/mobile/src/types/expo-icons.d.ts @@ -4,14 +4,14 @@ declare module "@expo/vector-icons" { import type { TextProps } from "react-native" - interface IconProps extends TextProps { + type IconProps = TextProps & { name: string size?: number color?: string style?: any } - interface IconComponent extends React.FC { + type IconComponent = React.FC & { glyphMap: Record } diff --git a/apps/mobile/src/types/react-native-marked.d.ts b/apps/mobile/src/types/react-native-marked.d.ts index e9995f1..7855396 100644 --- a/apps/mobile/src/types/react-native-marked.d.ts +++ b/apps/mobile/src/types/react-native-marked.d.ts @@ -6,7 +6,7 @@ declare module "react-native-marked" { import type { FlatListProps, ImageStyle, TextStyle, ViewStyle } from "react-native" import type { Hooks, Tokenizer } from "marked" - export interface RendererInterface { + export type RendererInterface = { paragraph(children: ReactNode[], styles?: ViewStyle): ReactNode blockquote(children: ReactNode[], styles?: ViewStyle): ReactNode heading(text: string | ReactNode[], styles?: TextStyle, depth?: number): ReactNode @@ -75,16 +75,16 @@ declare module "react-native-marked" { getKey(): string } - export interface UserTheme { + export type UserTheme = { colors?: Record spacing?: Record } - export interface MarkedStyles { + export type MarkedStyles = { [key: string]: ViewStyle | TextStyle | ImageStyle | undefined } - export interface MarkdownProps { + export type MarkdownProps = { value: string flatListProps?: Omit, "data" | "renderItem" | "horizontal"> theme?: UserTheme @@ -97,7 +97,7 @@ declare module "react-native-marked" { // Used by packages/uikit/src/components/markdown/Markdown.tsx to render parsed blocks // directly (bypassing the FlatList-based default export) — see issue #104. - export interface useMarkdownHookOptions { + export type useMarkdownHookOptions = { colorScheme?: "light" | "dark" | null renderer?: RendererInterface theme?: UserTheme diff --git a/apps/mobile/tsconfig.json b/apps/mobile/tsconfig.json index 89c0882..4369b37 100644 --- a/apps/mobile/tsconfig.json +++ b/apps/mobile/tsconfig.json @@ -6,11 +6,13 @@ "paths": { "@/*": ["./src/*"], "@/utils/*": ["./src/shared/utils/*"], + "@/hooks/*": ["./src/shared/hooks/*"], "@/api/*": ["./src/shared/api/*"], "@/stores/*": ["./src/shared/stores/*"], "@/shared/*": ["./src/shared/*"], "@shared/*": ["./src/shared/*"], "@utils/*": ["./src/shared/utils/*"], + "@hooks/*": ["./src/shared/hooks/*"], "@api/*": ["./src/shared/api/*"], "@stores/*": ["./src/shared/stores/*"], "@app/*": ["./app/*"], diff --git a/bun.lock b/bun.lock index 58fb96d..c7c2f41 100644 --- a/bun.lock +++ b/bun.lock @@ -15,6 +15,7 @@ "name": "backend", "version": "0.1.0", "dependencies": { + "@devbox/contracts": "workspace:*", "@nestjs/common": "^12.1.0", "@nestjs/config": "^12.0.1", "@nestjs/core": "^12.1.0", @@ -46,6 +47,7 @@ "name": "frontend", "version": "0.1.0", "dependencies": { + "@devbox/contracts": "workspace:*", "@hookform/resolvers": "5.9.1", "@opencode-ai/sdk": "1.18.33", "@tanstack/react-query": "^5.104.1", @@ -71,6 +73,16 @@ "typescript": "^5.6.2", }, }, + "packages/contracts": { + "name": "@devbox/contracts", + "version": "0.1.0", + "dependencies": { + "zod": "^4.6.5", + }, + "peerDependencies": { + "zod": "^4.6.5", + }, + }, }, "packages": { "@angular-devkit/core": ["@angular-devkit/core@22.2.0", "", { "dependencies": { "ajv": "8.20.0", "ajv-formats": "3.0.1", "jsonc-parser": "3.3.1", "picomatch": "4.0.7", "rxjs": "7.8.2", "source-map": "0.8.0" }, "peerDependencies": { "chokidar": "^5.0.0" }, "optionalPeers": ["chokidar"] }, "sha512-dELBwXtJWUxFALdEVvdk8qK+XBa17EH5H9NZm+041/esjNi6SaZMusqBgr2PZKq7hD+O2jSCEHbey/hwkz2Awg=="], @@ -119,6 +131,8 @@ "@date-fns/tz": ["@date-fns/tz@1.5.0", "", {}, "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg=="], + "@devbox/contracts": ["@devbox/contracts@workspace:packages/contracts"], + "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="], "@emnapi/core": ["@emnapi/core@1.4.5", "", { "dependencies": { "@emnapi/wasi-threads": "1.0.4", "tslib": "^2.4.0" } }, "sha512-XsLw1dEOpkSX/WucdqUhPWP7hDxSvZiY+fsUC14h+FtQ2Ifni4znbBt8punRX+Uj2JG/uDb8nEHVKvrVlvdZ5Q=="], diff --git a/package.json b/package.json index 580f165..fa056da 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "packageManager": "bun@1.4.2", "workspaces": [ "apps/backend", - "apps/frontend" + "apps/frontend", + "packages/contracts" ], "scripts": { "dev": "pm2 start ecosystem.config.cjs --update-env || pm2 restart ecosystem.config.cjs --update-env", @@ -19,10 +20,10 @@ "dev:pm2:logs": "pm2 logs", "dev:pm2:stop": "pm2 delete ecosystem.config.cjs", "dev:pm2:restart": "pm2 restart ecosystem.config.cjs", - "build": "bun --filter backend build && bun --filter frontend build", - "build:backend": "bun --filter backend build", - "build:frontend": "bun --filter frontend build", - "lint": "bun --filter backend lint && bun --filter frontend lint", + "build": "bun --filter @devbox/contracts build && bun --filter backend build && bun --filter frontend build", + "build:backend": "bun --filter @devbox/contracts build && bun --filter backend build", + "build:frontend": "bun --filter @devbox/contracts build && bun --filter frontend build", + "lint": "bun --filter @devbox/contracts build && bun --filter backend lint && bun --filter frontend lint", "test": "bun --filter backend test && bun --filter frontend test" }, "engines": { diff --git a/tsconfig.base.json b/tsconfig.base.json index 81918d8..274df95 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -1,8 +1,8 @@ { "compilerOptions": { "target": "ES2022", - "module": "NodeNext", - "moduleResolution": "NodeNext", + "module": "ESNext", + "moduleResolution": "Bundler", "lib": ["ES2022"], "strict": true, "esModuleInterop": true, From 42c7fd656e114394c39b61e896b23379d5b790d6 Mon Sep 17 00:00:00 2001 From: alwoo Date: Tue, 20 Oct 2026 15:52:47 +0400 Subject: [PATCH 015/315] chore(nx): migrate build/lint/test to nx run-many with per-project targets Root scripts switch to nx run-many/affected (build/lint/test/graph); per-project project.json for backend/frontend/contracts with ^build deps; contracts dev watch via tsc --watch + contracts-watch PM2 app; dev chains prebuild contracts; docs updated. --- AGENTS.md | 9 +++++++-- README.md | 9 ++++++--- apps/backend/project.json | 31 +++++++++++++++++++++++++++++++ apps/frontend/project.json | 31 +++++++++++++++++++++++++++++++ docs/id-integration.md | 7 +++++-- ecosystem.config.cjs | 18 ++++++++++++++++++ nx.json | 28 +++++++++++++++++++++------- package.json | 20 ++++++++++++-------- packages/contracts/package.json | 1 + packages/contracts/project.json | 30 ++++++++++++++++++++++++++++++ 10 files changed, 162 insertions(+), 22 deletions(-) create mode 100644 apps/backend/project.json create mode 100644 apps/frontend/project.json create mode 100644 packages/contracts/project.json diff --git a/AGENTS.md b/AGENTS.md index cdefa9e..487bb9f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,8 +32,13 @@ package.json, не Nx-проект, вне bun workspaces). гейты mobile-приложения. - Порядок стилей: `@web2bizz/ui/styles.css` → `globals.css` (source order, не менять). Hex — только `:root` / `.dark`. -- Проверки после правок фронта: `bun --filter frontend lint` - (`tsc --noEmit`) + `bun --filter frontend build` (`next build --turbopack`). +- Проверки после правок фронта: `bun run lint` (`nx run-many -t lint`: + `tsc --noEmit` + `biome lint` per project) + `bun run build` + (`nx run-many -t build`, фронт → `next build --turbopack`). Точечно — + `bun run lint:affected` / `bun run build:affected` (`nx affected -t …`), + граф — `bun run graph`. Низкоуровнево — `bun --filter