Compare commits
29 Commits
d00561f75d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dad3b7d36c | ||
|
|
66237bd217 | ||
|
|
bdc65529bd | ||
|
|
6d78476b2b | ||
|
|
a3be635648 | ||
|
|
eb194df8e0 | ||
|
|
46730279cb | ||
|
|
8a282b6d0d | ||
|
|
822c5fcac9 | ||
|
|
93c665fdbf | ||
|
|
7ce5a0fa12 | ||
|
|
012159aae2 | ||
|
|
e1c88b291c | ||
|
|
833eb00919 | ||
|
|
677937eb98 | ||
|
|
7a7f67d3e2 | ||
|
|
74d7e01e4f | ||
|
|
7a51f35ec4 | ||
|
|
4e1bee4503 | ||
|
|
977a8fafc4 | ||
|
|
138be5ac96 | ||
|
|
dfb3275afe | ||
|
|
a47fe0f845 | ||
|
|
ebfd3802c6 | ||
|
|
6ac8692d0d | ||
|
|
3478d28bb2 | ||
|
|
4658d66503 | ||
|
|
c72807dc26 | ||
|
|
5bc0915edf |
145
docs/engine-api.md
Normal file
145
docs/engine-api.md
Normal file
@@ -0,0 +1,145 @@
|
||||
# Alur API Express → Engine learning-lab
|
||||
|
||||
Express tidak punya backend sendiri. Semua logika AI (perencanaan, pembuatan materi, video, riset) ada di engine **learning-lab** (FastAPI, `/api/v1`). Express hanya membuat *agent* (jadwal) beserta konfigurasinya, lalu membaca dan meninjau hasilnya.
|
||||
|
||||
## Jalur request
|
||||
|
||||
| Lingkungan | Jalur |
|
||||
|---|---|
|
||||
| Production | `express.bawana.com/api/*` → redirect Netlify ([netlify.toml](../netlify.toml)) → `https://learningstudio.bawana.com/api/*` |
|
||||
| Dev | Proxy Vite `/api` → `ENGINE_URL` (default `http://localhost:8000`, [vite.config.ts](../vite.config.ts)) |
|
||||
|
||||
- Prefix `/api/v1` ditambahkan di [src/api/client.ts](../src/api/client.ts). Setiap request membawa `Authorization: Bearer <Clerk session token>`.
|
||||
- Request baca dan aksi diatur lajunya oleh `pace` di `client.ts`, supaya tidak terkena rate limit proxy (503/429).
|
||||
- Endpoint agent ada di `learning-lab/backend/app/api/v1/endpoints/agents.py` (semua di bawah `/organizations/current/agents`). Endpoint produksi konten ada di `agent_content.py` (`/organizations/current/agents/{id}/content`).
|
||||
|
||||
Di bawah ini, `AGENTS` = `/organizations/current/agents`.
|
||||
|
||||
## Jadwal = agent
|
||||
|
||||
Setiap jadwal Express adalah satu agent engine. Namanya diawali prefix Express, lalu dibaca lewat `expressAgents()` di [schedules.ts](../src/express/schedules.ts).
|
||||
|
||||
### Membuat jadwal (`createSchedule`)
|
||||
|
||||
| Langkah | Endpoint |
|
||||
|---|---|
|
||||
| (khusus video) Ambil harga satu video sebagai budget run | `GET AGENTS/video-quote?scenes=…&duration_seconds=…` |
|
||||
| Buat agent dengan konfigurasi dari `configFor()` | `POST AGENTS` |
|
||||
| Pasang dokumen Brain (semua dokumen yang siap, atau hanya yang dipilih) | `PUT AGENTS/{id}/knowledge-sources` |
|
||||
| Aktifkan (menyetujui aturan produksi; sebelum aktif tidak ada yang berjalan) | `POST AGENTS/{id}/activate` |
|
||||
|
||||
### Mengelola jadwal
|
||||
|
||||
| Aksi | Endpoint |
|
||||
|---|---|
|
||||
| Ubah brief (engine mengembalikan agent ke draft, jadi langsung diaktifkan ulang atau dipause) | `PATCH AGENTS/{id}`, lalu `POST AGENTS/{id}/activate` atau `/pause` |
|
||||
| Pause / resume | `POST AGENTS/{id}/pause`, `POST AGENTS/{id}/activate` |
|
||||
| Arsipkan | `POST AGENTS/{id}/archive` |
|
||||
| Riwayat run | `GET AGENTS/{id}/runs` |
|
||||
| Kesiapan knowledge | `GET AGENTS/{id}/knowledge-readiness` |
|
||||
|
||||
## 1. Konten materi (summary, quiz, flashcard, slide, audio, SCORM, …)
|
||||
|
||||
**Konfigurasi agent** (`configFor`):
|
||||
|
||||
```ts
|
||||
enabled_tools: ['knowledge.retrieve', 'compose.graph.retrieve', 'compose.create_material']
|
||||
material_outputs: outputsFor(kind)
|
||||
content_goal: { enabled: true, weekly_target, execution_mode: 'automatic' }
|
||||
```
|
||||
|
||||
Audio dan SCORM adalah jenis buatan Express sendiri, disusun dari output Compose. Audio adalah summary narasi; SCORM adalah pasangan summary dan quiz dari satu item rencana.
|
||||
|
||||
**Produksi** (`AGENTS/{id}/content`):
|
||||
|
||||
| Langkah | Endpoint |
|
||||
|---|---|
|
||||
| "Produce now", atau tick otomatis jam 09:00 WIB | `POST …/content/planning-quotes` `{ target }` |
|
||||
| Konfirmasi rencana | `POST …/content/plans/{plan}/confirm-planning` `{ revision }` |
|
||||
| Approve dan start | Dijalankan otomatis oleh tick engine (mode `automatic`) |
|
||||
| Retry satu item (maksimal 3 percobaan) | `POST …/plans/{plan}/items/{item}/retry-quote`, lalu `POST …/plans/{plan}/start` |
|
||||
| Status rencana dan periode minggu ini | `GET …/content` (di-cache 30 detik oleh `productionStatus`) |
|
||||
|
||||
**Di sisi engine** (`backend/app/services/`):
|
||||
|
||||
- `agent_content_planning.py`: model mengusulkan topik beserta bukti dari isi Brain.
|
||||
- `agent_content_execution.py`: membuat quote dan memesan kredit untuk setiap item.
|
||||
- `agent_materials.py`: menjalankan Compose (`compose_creation`) untuk membuat materinya.
|
||||
|
||||
**Hasil**: `material-drafts`.
|
||||
|
||||
## 2. Video
|
||||
|
||||
**Konfigurasi agent**:
|
||||
|
||||
```ts
|
||||
enabled_tools: ['knowledge.retrieve', 'compose.graph.retrieve', 'studio.create_video']
|
||||
video_options: { max_scenes, max_duration_seconds, art_style: 'realistic', language }
|
||||
run_schedule: { cadence: 'weekly' | 'daily', hour: 9, minute: 0, weekday: 0 }
|
||||
```
|
||||
|
||||
**Memicu run**: tick jadwal di engine, atau `runNow`, yaitu `POST AGENTS/{id}/runs` dengan header `Idempotency-Key`.
|
||||
|
||||
**Di sisi engine**, `agent_worker.py` menjalankan:
|
||||
|
||||
`agent_video_drafts.py` (membuat project Video Studio dan memesan kredit) → `agent_video_script.py` → `agent_video_storyboard.py` → `agent_video_clips.py` → `agent_video_render.py`
|
||||
|
||||
**Hasil**: `video-drafts`. Satu draft tidak bisa di-retry sendiri; yang dilakukan adalah run baru dari jadwalnya, dan tombol retry hanya muncul di draft terbaru.
|
||||
|
||||
## 3. Riset sumber web
|
||||
|
||||
**Konfigurasi agent**:
|
||||
|
||||
```ts
|
||||
enabled_tools: ['knowledge.retrieve', 'compose.graph.retrieve', 'browse.search', 'library.add_url']
|
||||
research_options: { max_results: 5 }
|
||||
auto_approve_sources
|
||||
```
|
||||
|
||||
**Memicu run**: jam 07:00 WIB, atau `POST AGENTS/{id}/runs`.
|
||||
|
||||
**Hasil**: `source-drafts`.
|
||||
|
||||
## Membaca dan meninjau hasil ([results.ts](../src/express/results.ts))
|
||||
|
||||
| Jenis | Daftar | Detail | Aksi |
|
||||
|---|---|---|---|
|
||||
| Materi | `GET AGENTS/{id}/material-drafts` | `GET AGENTS/{id}/material-drafts/{draft}` | `POST …/material-drafts/{draft}/decision` `{ expected_revision, decision }` |
|
||||
| Video | `GET AGENTS/{id}/video-drafts` | (judul diambil dari daftar) | `POST …/video-drafts/{draft}/review` `{ decision }`, `POST …/video-drafts/{draft}/cancel` |
|
||||
| Sumber | `GET AGENTS/{id}/source-drafts` | — | `POST …/source-drafts/{draft}/review` `{ expected_revision, decision }` |
|
||||
|
||||
Ekspor slide deck ke PPTX memakai `POST /slide-deck/{deckId}/export`.
|
||||
|
||||
### Pola polling
|
||||
|
||||
`listResults()` dipakai oleh halaman Results dan Production (query key `['results']`, `RESULTS_POLL` = setiap 30 detik):
|
||||
|
||||
- Setiap poll membaca `GET AGENTS/status?archived=true` satu kali, dengan `If-None-Match` (opsi `revalidate` di `client.ts`). Kalau tidak ada perubahan, engine menjawab 304.
|
||||
- Dari respons itu dibuat tanda per agent. Endpoint per jadwal (`material-drafts`, `video-drafts`, `source-drafts`) hanya dibaca ulang untuk agent yang tandanya berubah.
|
||||
- Pembacaan ulang tetap dipaksa untuk jadwal konten dengan plan aktif (topik plan belum punya draft), setelah 30 menit (URL video bertanda tangan berlaku 1 jam), dan setelah setiap mutation (`forgetReads`, [main.tsx](../src/main.tsx)).
|
||||
- Kalau `/status` sibuk, tanda terakhir dipakai. Kalau endpoint tidak tersedia, semua jadwal dibaca seperti dulu; jadwal arsip tetap cukup dibaca sekali.
|
||||
- Paling banyak 4 request per jadwal berjalan bersamaan (`PER_SCHEDULE_LIMIT`). Konten dibaca dulu, baru riset.
|
||||
- Kalau engine membalas 503/429, request dicoba sekali lagi setelah 3 detik. Kalau tetap gagal, hasil poll sebelumnya yang dipakai.
|
||||
- Di engine, `_video_draft_out` menjalankan sekitar 5 query untuk setiap draft (project, run step, dokumen, scene, kredit), dengan batas 100 draft per agent.
|
||||
|
||||
## Brain dan kredit ([src/api/engine.ts](../src/api/engine.ts))
|
||||
|
||||
| Aksi | Endpoint |
|
||||
|---|---|
|
||||
| Daftar / status / hapus / unduh dokumen | `GET /upload/list`, `GET /upload/{id}`, `DELETE /upload/{id}`, `GET /upload/{id}/file` |
|
||||
| Upload | `POST /upload/` |
|
||||
| Format yang didukung | `GET /upload/supported-formats` |
|
||||
| Knowledge graph dokumen | `GET /upload/{id}/knowledge`, `POST /upload/{id}/knowledge/build` |
|
||||
| Proses ulang | `POST /upload/{id}/reprocess` |
|
||||
| Versi baru atau bukan | `POST /upload/{id}/versions/link` atau `/decline` |
|
||||
| Saldo kredit | `GET /organizations/me` |
|
||||
| Pemilik jadwal | `GET /auth/me`, `GET /organizations/current/dashboard/members` |
|
||||
|
||||
## Kode lama yang tidak dipakai
|
||||
|
||||
Fungsi berikut di `src/api/engine.ts` tidak dipanggil di mana pun di `src/`. Ini sisa alur versi awal, yang memakai satu agent tunggal bernama `Learning Lab Express` dan memanggil Compose langsung:
|
||||
|
||||
- `generateText`, `generateQuiz`: `POST /compose/sets`, `/generate/summary`, `/generate/quiz`
|
||||
- `ensureAgent`, `attachSources`, `setSchedule`, `research`
|
||||
|
||||
`resetAgentCache` masih dipakai oleh `AuthGate.tsx`.
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<meta name="description" content="Learning Lab Express by Bawana: Express Mode for learning-lab." />
|
||||
<meta name="description" content="Learning Lab Express by BAWANA: Express Mode for learning-lab." />
|
||||
<title>Learning Lab Express</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
|
||||
18
src/App.tsx
18
src/App.tsx
@@ -1,12 +1,21 @@
|
||||
import { useAuth } from '@clerk/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Navigate, Route, Routes } from 'react-router-dom'
|
||||
import { AuthGate } from './auth/AuthGate'
|
||||
import { AppLayout } from './components/AppLayout'
|
||||
import { AppLayout, ORG_ADMIN } from './components/AppLayout'
|
||||
import { BillingPage } from './pages/Billing'
|
||||
import { BrainPage } from './pages/Brain'
|
||||
import { ProductionPage } from './pages/Production'
|
||||
import { InstructionPage } from './pages/Instruction'
|
||||
import { SchedulePage } from './pages/Schedule'
|
||||
import { ResultsPage } from './pages/Results'
|
||||
|
||||
// For a member who opens the link directly; the engine refuses them the data either way.
|
||||
function AdminOnly({ children }: { children: ReactNode }) {
|
||||
const { orgRole } = useAuth()
|
||||
return orgRole === ORG_ADMIN ? children : <Navigate replace to="/production" />
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<AuthGate>
|
||||
@@ -14,14 +23,15 @@ export default function App() {
|
||||
<Route element={<AppLayout />}>
|
||||
<Route path="/production" element={<ProductionPage />} />
|
||||
<Route path="/upload" element={<BrainPage />} />
|
||||
<Route path="/brain" element={<InstructionPage />} />
|
||||
<Route path="/instruction" element={<InstructionPage />} />
|
||||
<Route path="/schedule" element={<SchedulePage />} />
|
||||
<Route path="/results" element={<ResultsPage />} />
|
||||
<Route path="/admin/billing" element={<AdminOnly><BillingPage /></AdminOnly>} />
|
||||
</Route>
|
||||
{/* Paths from before the routes were renamed, so old links keep working. */}
|
||||
<Route path="/instruction" element={<Navigate replace to="/brain" />} />
|
||||
<Route path="/brain" element={<Navigate replace to="/instruction" />} />
|
||||
<Route path="/otak" element={<Navigate replace to="/upload" />} />
|
||||
<Route path="/perintah" element={<Navigate replace to="/brain" />} />
|
||||
<Route path="/perintah" element={<Navigate replace to="/instruction" />} />
|
||||
<Route path="/jadwal" element={<Navigate replace to="/schedule" />} />
|
||||
<Route path="/hasil" element={<Navigate replace to="/results" />} />
|
||||
<Route path="*" element={<Navigate replace to="/production" />} />
|
||||
|
||||
57
src/api/client.test.ts
Normal file
57
src/api/client.test.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { limiter, pacer, request } from './client'
|
||||
|
||||
describe('limiter', () => {
|
||||
it('runs at most n calls at once, all of them, failures included', async () => {
|
||||
const limit = limiter(2)
|
||||
let running = 0, peak = 0
|
||||
const call = (n: number) => limit(async () => {
|
||||
peak = Math.max(peak, ++running)
|
||||
await new Promise(r => setTimeout(r, 5))
|
||||
running--
|
||||
if (n === 2) throw new Error('503')
|
||||
return n
|
||||
})
|
||||
const out = await Promise.allSettled([1, 2, 3, 4, 5].map(call))
|
||||
expect(peak).toBe(2)
|
||||
expect(out.map(r => (r.status === 'fulfilled' ? r.value : 'x'))).toEqual([1, 'x', 3, 4, 5])
|
||||
})
|
||||
})
|
||||
|
||||
describe('pacer', () => {
|
||||
it('lets a burst through, then spaces the rest out in order', async () => {
|
||||
const pace = pacer(100, 2)
|
||||
const t0 = Date.now()
|
||||
const order: number[] = []
|
||||
await Promise.all([1, 2, 3, 4, 5, 6].map(n => pace.wait().then(() => order.push(n))))
|
||||
// Two at once, then four more at 10 ms each.
|
||||
expect(Date.now() - t0).toBeGreaterThanOrEqual(35)
|
||||
expect(order).toEqual([1, 2, 3, 4, 5, 6])
|
||||
})
|
||||
|
||||
it('pauses everything after the proxy turns one away', async () => {
|
||||
const pace = pacer(100, 5)
|
||||
pace.pause(50)
|
||||
const t0 = Date.now()
|
||||
await pace.wait()
|
||||
expect(Date.now() - t0).toBeGreaterThanOrEqual(45)
|
||||
})
|
||||
})
|
||||
|
||||
describe('request with revalidate', () => {
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('sends the last ETag back and answers a 304 with the last body', async () => {
|
||||
const sent: (string | null)[] = []
|
||||
vi.stubGlobal('fetch', vi.fn(async (_url: string, init: RequestInit) => {
|
||||
const tag = new Headers(init.headers).get('If-None-Match')
|
||||
sent.push(tag)
|
||||
return tag
|
||||
? new Response(null, { status: 304, headers: { ETag: 'W/"1"' } })
|
||||
: new Response(JSON.stringify({ agents: [1] }), { status: 200, headers: { ETag: 'W/"1"' } })
|
||||
}))
|
||||
expect(await request('/etag-test', { revalidate: true })).toEqual({ agents: [1] })
|
||||
expect(await request('/etag-test', { revalidate: true })).toEqual({ agents: [1] })
|
||||
expect(sent).toEqual([null, 'W/"1"'])
|
||||
})
|
||||
})
|
||||
@@ -42,18 +42,30 @@ export interface RequestOptions extends Omit<RequestInit, 'body'> {
|
||||
body?: BodyInit
|
||||
/** 'blob' for file downloads; errors still come back as JSON. */
|
||||
as?: 'json' | 'blob'
|
||||
/** Waits its turn like a read: for actions sent many at a time, which would otherwise outrun the rate limit. */
|
||||
paced?: boolean
|
||||
/** For a read the engine answers with an ETag: asks again with If-None-Match, and a 304 returns the last answer. */
|
||||
revalidate?: boolean
|
||||
}
|
||||
|
||||
export async function request<T>(path: string, { json, headers, as = 'json', ...opts }: RequestOptions = {}): Promise<T> {
|
||||
// The last answer to each `revalidate` read, by path, with the ETag that identifies it.
|
||||
const validated = new Map<string, { etag: string; data: unknown }>()
|
||||
|
||||
export async function request<T>(path: string, { json, headers, as = 'json', paced, revalidate, ...opts }: RequestOptions = {}): Promise<T> {
|
||||
const h = new Headers(headers)
|
||||
const token = await getToken()
|
||||
if (token) h.set('Authorization', `Bearer ${token}`)
|
||||
const kept = revalidate ? validated.get(path) : undefined
|
||||
if (kept) h.set('If-None-Match', kept.etag)
|
||||
let body = opts.body
|
||||
if (json !== undefined) {
|
||||
h.set('Content-Type', 'application/json')
|
||||
body = JSON.stringify(json)
|
||||
}
|
||||
|
||||
if (paced || !opts.method || opts.method === 'GET') await pace.wait()
|
||||
else pace.take()
|
||||
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(BASE + path, { ...opts, headers: h, body })
|
||||
@@ -61,14 +73,22 @@ export async function request<T>(path: string, { json, headers, as = 'json', ...
|
||||
throw new EngineError(t('err.unreachable'), 0)
|
||||
}
|
||||
if (res.status === 204) return null as T
|
||||
if (res.status === 304 && kept) return kept.data as T
|
||||
if (as === 'blob' && res.ok) return (await res.blob()) as T
|
||||
const data = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
if (res.status === 502 || res.status === 504) throw new EngineError(t('err.unreachable'), res.status)
|
||||
// The proxy's rate limit answers 503 (or 429) with an HTML page, not the engine's JSON.
|
||||
if ((res.status === 503 || res.status === 429) && !data) {
|
||||
pace.pause(BUSY_PAUSE)
|
||||
throw new EngineError(t('err.busy'), res.status)
|
||||
}
|
||||
const err = new EngineError(detail(data?.detail), res.status, data && typeof data === 'object' ? data : null)
|
||||
if (res.status === 402) err.message = creditMessage(err)
|
||||
throw err
|
||||
}
|
||||
const etag = revalidate ? res.headers.get('ETag') : null
|
||||
if (etag) validated.set(path, { etag, data })
|
||||
return data as T
|
||||
}
|
||||
|
||||
@@ -76,3 +96,62 @@ export async function request<T>(path: string, { json, headers, as = 'json', ...
|
||||
export const opKey = (prefix: string) => `lle-${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
|
||||
|
||||
export const sleep = (ms: number) => new Promise(r => setTimeout(r, ms))
|
||||
|
||||
/** Spaces requests out to at most `perSecond` after a first `burst`. A limit on how many run at once
|
||||
* does not do this: the engine answers in about 100 ms, so four at a time is still 40 a second. */
|
||||
export function pacer(perSecond: number, burst: number) {
|
||||
let tokens = burst
|
||||
let last = Date.now()
|
||||
let queue = Promise.resolve()
|
||||
const refill = () => {
|
||||
const now = Date.now()
|
||||
tokens = Math.min(burst, tokens + ((now - last) * perSecond) / 1000)
|
||||
last = now
|
||||
}
|
||||
return {
|
||||
/** Waits for a turn; callers are served in the order they asked. */
|
||||
wait(): Promise<void> {
|
||||
const turn = queue.then(async () => {
|
||||
for (refill(); tokens < 1; refill()) await sleep(((1 - tokens) * 1000) / perSecond)
|
||||
tokens -= 1
|
||||
})
|
||||
queue = turn
|
||||
return turn
|
||||
},
|
||||
/** Takes a turn at once, ahead of the waiting ones, and the queue pays it back. */
|
||||
take() {
|
||||
refill()
|
||||
tokens -= 1
|
||||
},
|
||||
/** Sends nothing more for `ms`. */
|
||||
pause(ms: number) {
|
||||
refill()
|
||||
tokens = Math.min(tokens, (-ms * perSecond) / 1000)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// The engine's proxy allows 10 requests a second per address after a burst of 20, and answers the
|
||||
// rest 503. Everything the app reads shares one pace below that; an action the user takes (any
|
||||
// non-GET) is sent at once rather than queued behind a page's polling. When the proxy turns one away
|
||||
// anyway (e.g. another tab sharing the address), every request waits for it to recover.
|
||||
const pace = pacer(8, 10)
|
||||
const BUSY_PAUSE = 2000
|
||||
|
||||
/** Runs the calls it is given at most `n` at a time, for requests a page makes one per row. */
|
||||
export function limiter(n: number) {
|
||||
let running = 0
|
||||
const waiting: (() => void)[] = []
|
||||
return async <T,>(fn: () => Promise<T>): Promise<T> => {
|
||||
// A finished call hands its slot straight to the next waiting one, so none can slip in between.
|
||||
if (running >= n) await new Promise<void>(r => waiting.push(r))
|
||||
else running++
|
||||
try {
|
||||
return await fn()
|
||||
} finally {
|
||||
const next = waiting.shift()
|
||||
if (next) next()
|
||||
else running--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Typed engine calls used by Express Mode. Ported from prototype/engine.js.
|
||||
import { EngineError, opKey, request, sleep } from './client'
|
||||
import { EngineError, limiter, opKey, request, sleep } from './client'
|
||||
import { t } from '../i18n'
|
||||
|
||||
// ── Documents (Brain) ──
|
||||
@@ -76,7 +76,10 @@ export interface KnowledgeDetail {
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export const knowledgeDetail = (id: number) => request<KnowledgeDetail>(`/upload/${id}/knowledge`)
|
||||
// The Upload page asks once per document waiting on an answer; two at a time keeps a long list
|
||||
// from tripping the proxy's rate limit.
|
||||
const twoAtATime = limiter(2)
|
||||
export const knowledgeDetail = (id: number) => twoAtATime(() => request<KnowledgeDetail>(`/upload/${id}/knowledge`))
|
||||
|
||||
// Agree to the quoted price, build after a top-up, or retry a failed build. Spends workspace credits (402 when short).
|
||||
// Reads a failed document's stored file again, for free. A knowledge base it already has is kept.
|
||||
|
||||
@@ -1,28 +1,33 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useClerk, useOrganization, useOrganizationList, useUser } from '@clerk/react'
|
||||
import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react'
|
||||
import { useAuth, useClerk, useOrganization, useOrganizationList, useUser } from '@clerk/react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { NavLink, Outlet, useLocation } from 'react-router-dom'
|
||||
import { LANGS, locale, setLang, t, useLang, type Key } from '../i18n'
|
||||
import { workspaceCredits } from '../api/engine'
|
||||
import { Brand, Icon, type IconName } from './Icon'
|
||||
import { Toaster } from './Toast'
|
||||
import { ErrorBoundary } from './ErrorBoundary'
|
||||
|
||||
// Learning Studio (learning-lab/frontend); both apps share one Clerk instance, so the user stays signed in.
|
||||
const STUDIO_URL: string = import.meta.env.VITE_STUDIO_URL
|
||||
|
||||
/** The Clerk role the engine treats as the organization's owner (`require_org_owner`). */
|
||||
export const ORG_ADMIN = 'org:admin'
|
||||
|
||||
// The Production dashboard shows what Express is making; the four settings doors run it:
|
||||
// feed the Brain, give an instruction, watch the schedule, collect results.
|
||||
export const NAV_GROUPS: { label: Key; items: { to: string; label: Key; icon: IconName }[] }[] = [
|
||||
export const NAV_GROUPS: { label: Key; adminOnly?: boolean; items: { to: string; label: Key; icon: IconName }[] }[] = [
|
||||
{ label: 'nav.dashboard', items: [{ to: '/production', label: 'nav.production', icon: 'chart' }] },
|
||||
{
|
||||
label: 'nav.settings',
|
||||
items: [
|
||||
{ to: '/upload', label: 'nav.brain', icon: 'brain' },
|
||||
{ to: '/brain', label: 'nav.instruction', icon: 'spark' },
|
||||
{ to: '/instruction', label: 'nav.instruction', icon: 'spark' },
|
||||
{ to: '/schedule', label: 'nav.schedule', icon: 'calendar' },
|
||||
{ to: '/results', label: 'nav.results', icon: 'layers' },
|
||||
],
|
||||
},
|
||||
{ label: 'nav.admin', adminOnly: true, items: [{ to: '/admin/billing', label: 'nav.billing', icon: 'coin' }] },
|
||||
]
|
||||
export const NAV = NAV_GROUPS.flatMap(g => g.items)
|
||||
|
||||
@@ -129,6 +134,16 @@ function OrgSwitcher() {
|
||||
}
|
||||
|
||||
// Remembered per browser; storage can throw in private windows, so it falls back to expanded.
|
||||
// Between the phone layout and a full desktop, the sidebar would leave too little room for the
|
||||
// page and the topbar, so it starts as the icon rail there; the toggle still opens it for this visit.
|
||||
const NARROW = '(min-width: 701px) and (max-width: 1024px)'
|
||||
function useNarrow() {
|
||||
return useSyncExternalStore(
|
||||
notify => { const m = matchMedia(NARROW); m.addEventListener('change', notify); return () => m.removeEventListener('change', notify) },
|
||||
() => matchMedia(NARROW).matches,
|
||||
)
|
||||
}
|
||||
|
||||
const COLLAPSED_KEY = 'sidebar-collapsed'
|
||||
function readCollapsed() {
|
||||
try { return localStorage.getItem(COLLAPSED_KEY) === '1' } catch { return false }
|
||||
@@ -139,16 +154,27 @@ export function AppLayout() {
|
||||
const [help, setHelp] = useState(false)
|
||||
const { user } = useUser()
|
||||
const { signOut } = useClerk()
|
||||
const { orgRole } = useAuth()
|
||||
const { pathname } = useLocation()
|
||||
const current = NAV.find(n => pathname.startsWith(n.to))
|
||||
// Nav groups stay closed unless they hold the current page; a click on the label overrides that until the next route.
|
||||
const [toggled, setToggled] = useState<Partial<Record<Key, boolean>>>({})
|
||||
useEffect(() => setToggled({}), [pathname])
|
||||
const [collapsed, setCollapsed] = useState(readCollapsed)
|
||||
const toggleCollapsed = () => setCollapsed(c => {
|
||||
try { localStorage.setItem(COLLAPSED_KEY, c ? '0' : '1') } catch { /* keep it for this visit only */ }
|
||||
return !c
|
||||
})
|
||||
useEffect(() => { setToggled({}) }, [pathname])
|
||||
// The window scrolls, not <main>, so a new page would open at the last page's scroll position.
|
||||
// In braces: Chrome's scrollTo now returns a Promise, which React would keep as the effect's
|
||||
// cleanup and call on the next route change ("is not a function"), unmounting the whole app.
|
||||
useLayoutEffect(() => { window.scrollTo(0, 0) }, [pathname])
|
||||
const [saved, setSaved] = useState(readCollapsed)
|
||||
const narrow = useNarrow()
|
||||
const [openNarrow, setOpenNarrow] = useState(false)
|
||||
const collapsed = narrow ? !openNarrow : saved
|
||||
const toggleCollapsed = () => {
|
||||
if (narrow) return setOpenNarrow(o => !o)
|
||||
setSaved(c => {
|
||||
try { localStorage.setItem(COLLAPSED_KEY, c ? '0' : '1') } catch { /* keep it for this visit only */ }
|
||||
return !c
|
||||
})
|
||||
}
|
||||
const name = user?.fullName || user?.primaryEmailAddress?.emailAddress || '-'
|
||||
|
||||
return (
|
||||
@@ -157,7 +183,7 @@ export function AppLayout() {
|
||||
<NavLink to="/production"><Brand /></NavLink>
|
||||
<OrgSwitcher />
|
||||
<nav aria-label={t('layout.mainNav')}>
|
||||
{NAV_GROUPS.map(g => {
|
||||
{NAV_GROUPS.filter(g => !g.adminOnly || orgRole === ORG_ADMIN).map(g => {
|
||||
// The icon rail has no group labels, so every item shows.
|
||||
const open = collapsed || (toggled[g.label] ?? g.items.some(n => pathname.startsWith(n.to)))
|
||||
return [
|
||||
@@ -206,8 +232,8 @@ export function AppLayout() {
|
||||
</div>
|
||||
</header>
|
||||
{/* Keyed by route so each page plays the fade-in from theme.css. */}
|
||||
<main tabIndex={-1} key={pathname}><Outlet /></main>
|
||||
<footer className="app-footer">Learning Lab Express <span>by Bawana</span><span>{t('layout.footer')}</span></footer>
|
||||
<main tabIndex={-1} key={pathname}><ErrorBoundary><Outlet /></ErrorBoundary></main>
|
||||
<footer className="app-footer">Learning Lab Express <span>by BAWANA</span><span>{t('layout.footer')}</span></footer>
|
||||
</div>
|
||||
{help && <HelpDialog onClose={() => setHelp(false)} />}
|
||||
<Toaster />
|
||||
|
||||
40
src/components/ErrorBoundary.tsx
Normal file
40
src/components/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Component, type ReactNode } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { Empty } from './Page'
|
||||
|
||||
// Without this, one component throwing while rendering unmounts the whole app and leaves a white
|
||||
// page. The layout keys it by route, so moving to another page clears the error; main.tsx also puts
|
||||
// one around the whole app (the layout included), cleared by a change of `resetKey`.
|
||||
export class ErrorBoundary extends Component<{ children: ReactNode; resetKey?: string; className?: string }, { error: Error | null }> {
|
||||
state = { error: null as Error | null }
|
||||
|
||||
componentDidUpdate(prev: { resetKey?: string }) {
|
||||
if (this.state.error && prev.resetKey !== this.props.resetKey) this.setState({ error: null })
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error) {
|
||||
return { error }
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error) {
|
||||
console.error('Page crashed', error)
|
||||
}
|
||||
|
||||
render() {
|
||||
const { error } = this.state
|
||||
if (!error) return this.props.children
|
||||
return (
|
||||
<div className={this.props.className ?? 'card'}>
|
||||
<Empty icon="info" title={t('err.crashTitle')}>
|
||||
{t('err.crashCopy')}
|
||||
<br />
|
||||
<small>{error.name}: {error.message}</small>
|
||||
</Empty>
|
||||
<div style={{ display: 'flex', justifyContent: 'center', gap: 8, paddingBottom: 24 }}>
|
||||
<button className="btn small" onClick={() => this.setState({ error: null })}>{t('common.retry')}</button>
|
||||
<button className="btn small primary" onClick={() => window.location.reload()}>{t('err.reload')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ export function Brand() {
|
||||
return (
|
||||
<span className="brand">
|
||||
<span className="brand-mark"><Icon name="book" /></span>
|
||||
<span>Learning Lab <b>Express</b><small>by Bawana</small></span>
|
||||
<span>Learning Lab <b>Express</b><small>by BAWANA</small></span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
93
src/express/billing.test.ts
Normal file
93
src/express/billing.test.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { dayKey, entryTime, lastDays, ledgerSince, moduleOf, usageCsv, usageInPeriod, type LedgerEntry } from './billing'
|
||||
import { request } from '../api/client'
|
||||
|
||||
vi.mock('../api/client', () => ({ request: vi.fn() }))
|
||||
|
||||
const at = (y: number, m: number, d: number, h = 12) => new Date(y, m - 1, d, h).toISOString()
|
||||
const entry = (id: number, kind: string, amount: number, created_at: string): LedgerEntry =>
|
||||
({ id, kind, amount, activity: 'agent.browse.search', actor_name: 'Ana', created_at })
|
||||
|
||||
afterEach(() => vi.mocked(request).mockReset())
|
||||
|
||||
describe('entryTime', () => {
|
||||
it('reads a time without an offset as UTC', () => {
|
||||
expect(entryTime('2026-11-04T01:00:00').toISOString()).toBe('2026-11-04T01:00:00.000Z')
|
||||
expect(entryTime('2026-11-04T01:00:00.250').toISOString()).toBe('2026-11-04T01:00:00.250Z')
|
||||
})
|
||||
|
||||
it('keeps an offset that is there', () => {
|
||||
expect(entryTime('2026-11-04T08:00:00+07:00').toISOString()).toBe('2026-11-04T01:00:00.000Z')
|
||||
expect(entryTime('2026-11-04T01:00:00Z').toISOString()).toBe('2026-11-04T01:00:00.000Z')
|
||||
})
|
||||
})
|
||||
|
||||
describe('usageInPeriod', () => {
|
||||
it('includes both whole end days and nothing outside them', () => {
|
||||
const { rows } = usageInPeriod([
|
||||
entry(1, 'charge', -1, new Date(2026, 10, 1, 0, 0).toISOString()),
|
||||
entry(2, 'charge', -2, new Date(2026, 10, 3, 23, 59).toISOString()),
|
||||
entry(3, 'charge', -4, new Date(2026, 10, 4, 0, 0).toISOString()),
|
||||
entry(4, 'charge', -8, new Date(2026, 9, 31, 23, 59).toISOString()),
|
||||
], '2026-11-01', '2026-11-03')
|
||||
expect(rows.map(r => r.id)).toEqual([1, 2])
|
||||
})
|
||||
|
||||
it('subtracts refunds and ignores grants and adjustments', () => {
|
||||
const { rows, total } = usageInPeriod([
|
||||
entry(1, 'charge', -10, at(2026, 11, 2)),
|
||||
entry(2, 'refund', 3, at(2026, 11, 2)),
|
||||
entry(3, 'grant', 500, at(2026, 11, 2)),
|
||||
entry(4, 'adjustment', -20, at(2026, 11, 2)),
|
||||
], '2026-11-01', '2026-11-03')
|
||||
expect(total).toBe(7)
|
||||
expect(rows.map(r => r.id)).toEqual([1, 2])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ledgerSince', () => {
|
||||
it('follows pages until the ledger ends', async () => {
|
||||
vi.mocked(request)
|
||||
.mockResolvedValueOnce({ entries: [entry(3, 'charge', -1, at(2026, 11, 3))], next_before_id: 3 })
|
||||
.mockResolvedValueOnce({ entries: [entry(2, 'charge', -1, at(2026, 11, 2))], next_before_id: null })
|
||||
expect((await ledgerSince('2026-11-01')).map(e => e.id)).toEqual([3, 2])
|
||||
expect(vi.mocked(request).mock.calls[1][0]).toContain('before_id=3')
|
||||
})
|
||||
|
||||
it('stops once a page reaches past the start of the period', async () => {
|
||||
vi.mocked(request).mockResolvedValueOnce({ entries: [entry(9, 'charge', -1, at(2026, 10, 1))], next_before_id: 9 })
|
||||
await ledgerSince('2026-11-01')
|
||||
expect(request).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('usageCsv', () => {
|
||||
const when = new Date(2026, 10, 3, 9, 5).toISOString()
|
||||
|
||||
it('writes a header and one row per entry, with refunds negative', () => {
|
||||
const lines = usageCsv([entry(1, 'charge', -5, when), entry(2, 'refund', 3, when)]).split('\r\n')
|
||||
expect(lines[0]).toBe('Date,User,Module,Activity,Type,Credits')
|
||||
expect(lines[1]).toBe('2026-11-03 09:05,Ana,Agent,browse search,Charge,5')
|
||||
expect(lines[2]).toBe('2026-11-03 09:05,Ana,Agent,browse search,Refund,-3')
|
||||
})
|
||||
|
||||
it('quotes what would break a column and defuses formulas', () => {
|
||||
const row = (actor_name: string | null) => usageCsv([{ ...entry(1, 'charge', -5, when), actor_name }]).split('\r\n')[1].split(',Agent')[0]
|
||||
expect(row('Doe, "Ana"')).toBe('2026-11-03 09:05,"Doe, ""Ana"""')
|
||||
expect(row('=HYPERLINK("x")')).toBe(`2026-11-03 09:05,"'=HYPERLINK(""x"")"`)
|
||||
expect(row(null)).toBe('2026-11-03 09:05,-')
|
||||
})
|
||||
})
|
||||
|
||||
describe('helpers', () => {
|
||||
it('names the module and detail of an activity', () => {
|
||||
expect(moduleOf('agent.browse.search')).toEqual({ module: 'Agent', detail: 'browse search' })
|
||||
expect(moduleOf('slide_deck.generate')).toEqual({ module: 'Slide deck', detail: 'generate' })
|
||||
expect(moduleOf(null)).toEqual({ module: '-', detail: '' })
|
||||
})
|
||||
|
||||
it('counts the last days including today, in local dates', () => {
|
||||
expect(dayKey(new Date(2026, 0, 5))).toBe('2026-01-05')
|
||||
expect(lastDays(30, new Date(2026, 10, 4))).toEqual({ from: '2026-10-06', to: '2026-11-04' })
|
||||
})
|
||||
})
|
||||
93
src/express/billing.ts
Normal file
93
src/express/billing.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
// Billing reads the organization's credit ledger. The engine records credits, not LLM tokens, and its
|
||||
// ledger has no date filter, so a period is loaded page by page and cut to size here.
|
||||
import { request } from '../api/client'
|
||||
import { t } from '../i18n'
|
||||
|
||||
export interface LedgerEntry {
|
||||
id: number
|
||||
kind: string
|
||||
/** Signed: negative for a charge, positive for a refund or grant. */
|
||||
amount: number
|
||||
activity: string | null
|
||||
actor_name: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
interface LedgerPage { entries: LedgerEntry[]; next_before_id: number | null }
|
||||
|
||||
const LEDGER = '/organizations/current/dashboard/ledger'
|
||||
|
||||
// The ledger's times are UTC without saying so; new Date() alone would read them as local time.
|
||||
export const entryTime = (iso: string) => new Date(/(Z|[+-]\d\d:?\d\d)$/.test(iso) ? iso : `${iso}Z`)
|
||||
|
||||
const startOf = (day: string) => new Date(`${day}T00:00:00`)
|
||||
const endOf = (day: string) => {
|
||||
const end = startOf(day)
|
||||
end.setDate(end.getDate() + 1)
|
||||
return end
|
||||
}
|
||||
|
||||
/** A local date as the yyyy-mm-dd a date input uses. */
|
||||
export function dayKey(date: Date) {
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
|
||||
}
|
||||
|
||||
export function lastDays(days: number, today = new Date()) {
|
||||
const from = new Date(today)
|
||||
from.setDate(from.getDate() - (days - 1))
|
||||
return { from: dayKey(from), to: dayKey(today) }
|
||||
}
|
||||
|
||||
/** Every ledger entry back to the start of a day. Pages come newest first, so older pages can stop early. */
|
||||
export async function ledgerSince(from: string): Promise<LedgerEntry[]> {
|
||||
const start = startOf(from)
|
||||
const entries: LedgerEntry[] = []
|
||||
let before: number | null = null
|
||||
do {
|
||||
const query: string = before === null ? '' : `&before_id=${before}`
|
||||
const page: LedgerPage = await request<LedgerPage>(`${LEDGER}?limit=200${query}`)
|
||||
entries.push(...page.entries)
|
||||
const oldest = page.entries.at(-1)
|
||||
before = oldest && entryTime(oldest.created_at) >= start ? page.next_before_id : null
|
||||
} while (before !== null)
|
||||
return entries
|
||||
}
|
||||
|
||||
/** What a period consumed: charges, less what was refunded. Top-ups and adjustments are not consumption. */
|
||||
export function usageInPeriod(entries: LedgerEntry[], from: string, to: string) {
|
||||
const start = startOf(from)
|
||||
const end = endOf(to)
|
||||
const rows = entries.filter(e => {
|
||||
if (e.kind !== 'charge' && e.kind !== 'refund') return false
|
||||
const at = entryTime(e.created_at)
|
||||
return at >= start && at < end
|
||||
})
|
||||
return { rows, total: rows.reduce((sum, e) => sum - e.amount, 0) }
|
||||
}
|
||||
|
||||
/** "agent.browse.search" → Agent, browse search. */
|
||||
export function moduleOf(activity: string | null) {
|
||||
if (!activity) return { module: '-', detail: '' }
|
||||
const [first, ...rest] = activity.split('.').map(part => part.replace(/_/g, ' '))
|
||||
return { module: first.charAt(0).toUpperCase() + first.slice(1), detail: rest.join(' ') }
|
||||
}
|
||||
|
||||
// A name is free text: quoted when it needs it, and kept from running as a formula when opened in Excel.
|
||||
function cell(value: string | number) {
|
||||
if (typeof value === 'number') return String(value)
|
||||
const safe = /^([=+@\t\r]|-.)/.test(value) ? `'${value}` : value
|
||||
return /[",\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe
|
||||
}
|
||||
|
||||
/** The rows as CSV, in local time and plain numbers. The BOM makes Excel read names as UTF-8. */
|
||||
export function usageCsv(rows: LedgerEntry[]) {
|
||||
const header = [t('billing.colDate'), t('billing.colUser'), t('billing.colModule'), t('billing.colActivity'), t('billing.colType'), t('billing.colCredits')]
|
||||
const lines = rows.map(e => {
|
||||
const at = entryTime(e.created_at)
|
||||
const time = `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`
|
||||
const { module, detail } = moduleOf(e.activity)
|
||||
return [`${dayKey(at)} ${time}`, e.actor_name || '-', module, detail, t(e.kind === 'refund' ? 'billing.refund' : 'billing.charge'), -e.amount]
|
||||
})
|
||||
return `${[header, ...lines].map(line => line.map(cell).join(',')).join('\r\n')}\r\n`
|
||||
}
|
||||
@@ -47,6 +47,23 @@ describe('parseInstruction', () => {
|
||||
expect(content('1 modul scorm dengan kuis per minggu')[0].kind).toBe('scorm')
|
||||
})
|
||||
|
||||
it('reads INTERACTIVE, the name the interface shows, as SCORM', () => {
|
||||
const rules = content('1 video per week, 2 podcasts per week and 1 INTERACTIVE module per week about onboarding')
|
||||
expect(rules.map(r => [r.kind, r.count, r.per, r.topic])).toEqual([
|
||||
['video', 1, 'week', 'onboarding'],
|
||||
['audio', 2, 'week', 'onboarding'],
|
||||
['scorm', 1, 'week', 'onboarding'],
|
||||
])
|
||||
expect(content('2 interactive per week')[0]).toMatchObject({ kind: 'scorm', count: 2 })
|
||||
expect(content('1 modul interaktif dengan kuis per minggu')[0].kind).toBe('scorm')
|
||||
})
|
||||
|
||||
it('keeps the named kind when interactive only describes it', () => {
|
||||
expect(content('2 kuis interaktif per minggu')[0].kind).toBe('quiz')
|
||||
expect(content('1 interactive video per week')[0].kind).toBe('video')
|
||||
expect(content('2 summaries per week about interactive learning')[0].kind).toBe('summary')
|
||||
})
|
||||
|
||||
it('reports clauses it did not understand', () => {
|
||||
const { rules, unknown } = parseInstruction('2 summaries per day. hello there')
|
||||
expect(rules).toHaveLength(1)
|
||||
|
||||
@@ -19,7 +19,7 @@ export const kindLabel = (kind: ContentKind) => t(`kind.${kind}` as Key)
|
||||
// Checked in order; the first match wins, so multi-word phrases come before their parts.
|
||||
const KIND_WORDS: [ContentKind, RegExp][] = [
|
||||
// SCORM first: a SCORM module includes a quiz, so "SCORM module with a quiz" is still SCORM.
|
||||
['scorm', /\b(scorm|skorm|skong|e-?learning)\b/],
|
||||
['scorm', /\b(scorm|skorm|skong|e-?learning|interactive modules?|modul(e|es)? interaktif)\b/],
|
||||
['flashcards', /\b(flash ?cards?|kartu (belajar|hafalan))\b/],
|
||||
['quiz', /\b(kuis|quiz|quizzes|soal latihan|tes|tests?|ujian|exams?)\b/],
|
||||
['roleplay', /\b(role ?-?plays?|bermain peran)\b/],
|
||||
@@ -30,13 +30,18 @@ const KIND_WORDS: [ContentKind, RegExp][] = [
|
||||
['summary', /\b(summary|summaries|ringkasan|rangkuman|artikel|articles?|teks|texts?)\b/],
|
||||
]
|
||||
|
||||
// The interface calls SCORM "INTERACTIVE", so the bare word means it too, but only when nothing else
|
||||
// is named: "kuis interaktif" stays a quiz, and "summaries about interactive learning" stay summaries.
|
||||
const INTERACTIVE = /\b(interactive|interaktif)\b/
|
||||
|
||||
/** Every content kind a text names, in the order it names them: "ringkasan dan kuis" → summary, quiz. */
|
||||
export function kindsIn(text: string): ContentKind[] {
|
||||
return KIND_WORDS
|
||||
const kinds = KIND_WORDS
|
||||
.map(([kind, re]) => [kind, text.search(re)] as const)
|
||||
.filter(([, at]) => at >= 0)
|
||||
.sort((a, b) => a[1] - b[1])
|
||||
.map(([kind]) => kind)
|
||||
return kinds.length || !INTERACTIVE.test(text) ? kinds : ['scorm']
|
||||
}
|
||||
|
||||
// "10 konten", "5 materi pembelajaran", "10 pdf": content of no particular kind, so the agent asks which.
|
||||
@@ -208,6 +213,8 @@ function parseClause(clause: string): Rule | null {
|
||||
const m = re.exec(clause)
|
||||
if (m) return contentRule(clause, kind, countOf(clause, m.index))
|
||||
}
|
||||
const interactive = INTERACTIVE.exec(clause)
|
||||
if (interactive) return contentRule(clause, 'scorm', countOf(clause, interactive.index))
|
||||
const g = GENERIC.exec(clause)
|
||||
if (g) {
|
||||
const count = countBefore(clause, g.index)
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { correctIndex, keepSettled, questionsOf, toMarkdown, withPlanItem, type Material } from './results'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { EngineError } from '../api/client'
|
||||
import {
|
||||
correctIndex, decideMaterial, forgetReads, isStuckVideo, keepSettled, questionsOf, remembering, settleLimited, toMarkdown, videoStatus, withDecisions, withPlanItem, type Material,
|
||||
} from './results'
|
||||
import { sentencesOf, scriptLang } from '../components/AudioPlayer'
|
||||
import type { Schedule } from './schedules'
|
||||
|
||||
describe('correctIndex', () => {
|
||||
const options = ['Listen first', 'Interrupt', 'Leave']
|
||||
@@ -66,6 +70,51 @@ describe('withPlanItem', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('settleLimited', () => {
|
||||
it('runs at most the limit at once and keeps order and failures', async () => {
|
||||
let running = 0, peak = 0
|
||||
const out = await settleLimited([1, 2, 3, 4, 5, 6], 2, async n => {
|
||||
peak = Math.max(peak, ++running)
|
||||
await new Promise(r => setTimeout(r, 5))
|
||||
running--
|
||||
if (n === 3) throw new Error('503')
|
||||
return n * 10
|
||||
})
|
||||
expect(peak).toBe(2)
|
||||
expect(out.map(r => (r.status === 'fulfilled' ? r.value : 'x'))).toEqual([10, 20, 'x', 40, 50, 60])
|
||||
})
|
||||
})
|
||||
|
||||
describe('remembering', () => {
|
||||
const schedule = (id: number) => ({ agent: { id } }) as Schedule
|
||||
const answers = (...seq: (number[] | number)[]) => vi.fn(async () => {
|
||||
const next = seq.shift()!
|
||||
if (typeof next === 'number') throw new EngineError('err', next)
|
||||
return next
|
||||
})
|
||||
|
||||
it('asks a busy engine once more', async () => {
|
||||
const fn = answers(503, [1])
|
||||
expect(await remembering(fn, 0)(schedule(1))).toEqual([1])
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps the last results while the engine stays busy', async () => {
|
||||
const read = remembering(answers([1, 2], 503, 503, 502), 0)
|
||||
const s = schedule(1)
|
||||
expect(await read(s)).toEqual([1, 2])
|
||||
expect(await read(s)).toEqual([1, 2])
|
||||
expect(await read(s)).toEqual([1, 2])
|
||||
})
|
||||
|
||||
it('drops a schedule the engine refuses, and one never read', async () => {
|
||||
const read = remembering(answers([1], 404), 0)
|
||||
await read(schedule(1))
|
||||
await expect(read(schedule(1))).rejects.toThrow()
|
||||
await expect(remembering(answers(503, 503), 0)(schedule(2))).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('keepSettled', () => {
|
||||
const ok = (v: number[]): PromiseSettledResult<number[]> => ({ status: 'fulfilled', value: v })
|
||||
const bad = (message: string): PromiseSettledResult<number[]> => ({ status: 'rejected', reason: new Error(message) })
|
||||
@@ -82,3 +131,82 @@ describe('keepSettled', () => {
|
||||
expect(keepSettled([])).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('remembering an archived schedule', () => {
|
||||
const archived = { agent: { id: 7, status: 'archived' } } as Schedule
|
||||
|
||||
it('reads it once until an action', async () => {
|
||||
const fn = vi.fn(async () => [1])
|
||||
const read = remembering(fn, 0)
|
||||
await read(archived)
|
||||
expect(await read(archived)).toEqual([1])
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
forgetReads()
|
||||
await read(archived)
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('remembering with status marks', () => {
|
||||
const active = { agent: { id: 9, status: 'active' } } as Schedule
|
||||
|
||||
it('reads a schedule again only when its mark changes', async () => {
|
||||
const fn = vi.fn(async () => [1])
|
||||
const read = remembering(fn, 0)
|
||||
await read(active, 'a')
|
||||
await read(active, 'a')
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
await read(active, 'b')
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('reads every time without a mark, or while the last read was not quiet', async () => {
|
||||
const fn = vi.fn(async () => [1])
|
||||
await remembering(fn, 0)(active)
|
||||
await remembering(fn, 0)(active)
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
let quiet = false
|
||||
const read = remembering(fn, 0, () => quiet)
|
||||
await read(active, 'a')
|
||||
await read(active, 'a')
|
||||
expect(fn).toHaveBeenCalledTimes(4)
|
||||
quiet = true
|
||||
await read(active, 'a')
|
||||
await read(active, 'a')
|
||||
expect(fn).toHaveBeenCalledTimes(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('videoStatus', () => {
|
||||
it('fails a video the engine stopped without a confirmed result', () => {
|
||||
expect(videoStatus({ status: 'clips', latest_error: 'clip_outcome_unknown' })).toBe('failed')
|
||||
expect(isStuckVideo({ status: 'clips', latest_error: 'clip_outcome_unknown' })).toBe(true)
|
||||
})
|
||||
it('keeps a video at work while its stages run', () => {
|
||||
expect(videoStatus({ status: 'clips', latest_error: null })).toBe('generating')
|
||||
})
|
||||
it('does not call a cancelled video stuck', () => {
|
||||
expect(isStuckVideo({ status: 'cancelled', latest_error: 'user_cancelled' })).toBe(false)
|
||||
expect(videoStatus({ status: 'cancelled', latest_error: 'clip_outcome_unknown' })).toBe('failed')
|
||||
})
|
||||
})
|
||||
|
||||
describe('withDecisions', () => {
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
const scorm = (status: Material['status']) => ({
|
||||
id: 7, agentId: 3, kind: 'scorm', status, revision: 1, createdAt: '2026-10-29T00:00:00Z', sources: [],
|
||||
parts: [{ id: 7, revision: 1, kind: 'summary', status }, { id: 8, revision: 1, kind: 'quiz', status }],
|
||||
}) as unknown as Material
|
||||
|
||||
it('shows a decision before any read says so, and drops it once one does', async () => {
|
||||
vi.stubGlobal('fetch', async () => new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
await decideMaterial(scorm('ready'), 'accept')
|
||||
// A remembered read from before the decision still says ready.
|
||||
const shown = withDecisions(scorm('ready'))
|
||||
expect(shown.status).toBe('accepted')
|
||||
expect(shown.parts.map(p => p.status)).toEqual(['accepted', 'accepted'])
|
||||
// The engine's own answer wins from then on, even if the material is later edited back to ready.
|
||||
expect(withDecisions(scorm('accepted')).status).toBe('accepted')
|
||||
expect(withDecisions(scorm('ready')).status).toBe('ready')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
// content plan item that ordered them), rendered videos (video-drafts) and web sources found by
|
||||
// research (source-drafts). Audio and SCORM are Express kinds built from Compose outputs: an audio
|
||||
// lesson is a narration summary, a SCORM module is the summary + quiz pair one plan item produced.
|
||||
import { request } from '../api/client'
|
||||
import { EngineError, request, sleep } from '../api/client'
|
||||
import { t } from '../i18n'
|
||||
import { kindLabel, type ContentKind, type Rule } from './parse'
|
||||
import { expressAgents, MAX_ATTEMPTS, PLAN_ACTIVE, productionStatus, retryItem, runNow, type PlanItem, type Schedule } from './schedules'
|
||||
import { expressAgents, forgetProductionReads, MAX_ATTEMPTS, PLAN_ACTIVE, productionStatus, retryItem, runNow, type PlanItem, type Schedule } from './schedules'
|
||||
|
||||
const AGENTS = '/organizations/current/agents'
|
||||
|
||||
@@ -41,7 +41,8 @@ export interface Material {
|
||||
rule: Rule
|
||||
/** How to produce it again, when the engine allows another attempt: the plan item, or (video) a new run. */
|
||||
retry?: { planId: number; itemId: number } | { run: true }
|
||||
video?: { url: string | null; progress: number; credits: number | null }
|
||||
/** stuck: the engine stopped it without knowing whether a paid step finished; only cancelling settles it. */
|
||||
video?: { url: string | null; progress: number; credits: number | null; stuck: boolean }
|
||||
}
|
||||
|
||||
// Labels are resolved at render time so they follow the UI language.
|
||||
@@ -87,14 +88,22 @@ const STOPPED = new Set<PlanItem['status']>(['failed', 'blocked', 'cancelled', '
|
||||
export const withPlanItem = (status: MaterialStatus, item: PlanItem['status'] | undefined): MaterialStatus =>
|
||||
item && STOPPED.has(item) && (status === 'preparing' || status === 'generating') ? 'failed' : status
|
||||
|
||||
// Schedules whose last read had a production plan at work. A plan's topics show before they have
|
||||
// drafts, and the status read only sees drafts, so these are read on every poll.
|
||||
const planning = new Set<number>()
|
||||
|
||||
async function materialsOf(schedule: Schedule): Promise<Material[]> {
|
||||
if (schedule.rule.type === 'content' && schedule.rule.kind === 'video') return videosOf(schedule)
|
||||
const { agent, rule } = schedule
|
||||
const kind = rule.type === 'content' ? rule.kind : 'summary'
|
||||
const [drafts, status] = await Promise.all([
|
||||
request<RawMaterial[]>(`${AGENTS}/${agent.id}/material-drafts`),
|
||||
productionStatus(agent.id).catch(() => null),
|
||||
// Without its plan a schedule still has drafts; a busy engine fails the whole read instead, so
|
||||
// the last complete one is shown rather than drafts missing their titles and planned pieces.
|
||||
productionStatus(agent.id).catch(e => { if (passing(e)) throw e; return null }),
|
||||
])
|
||||
if (status?.plans.some(p => PLAN_ACTIVE.has(p.status))) planning.add(agent.id)
|
||||
else planning.delete(agent.id)
|
||||
const items = new Map<number, PlanItem & { planId: number }>()
|
||||
for (const plan of status?.plans ?? []) {
|
||||
for (const item of plan.items ?? []) if (item.run_id) items.set(item.run_id, { ...item, planId: plan.id })
|
||||
@@ -134,6 +143,7 @@ interface RawVideo {
|
||||
status: string
|
||||
title: string | null
|
||||
progress_percentage: number
|
||||
latest_error: string | null
|
||||
video_url: string | null
|
||||
sources: { document_id: number; title: string }[]
|
||||
actual_credits: number | null
|
||||
@@ -141,9 +151,15 @@ interface RawVideo {
|
||||
}
|
||||
|
||||
// Video drafts move through script, storyboard, clips and render before they are ready to review.
|
||||
function videoStatus(s: string): MaterialStatus {
|
||||
// A stage whose outcome the engine could not confirm (e.g. clip_outcome_unknown) stops the run for
|
||||
// good, though the draft still says it is at work: that is a failure until it is cancelled.
|
||||
export const isStuckVideo = (d: Pick<RawVideo, 'status' | 'latest_error'>) =>
|
||||
!['ready', 'accepted', 'rejected', 'failed', 'cancelled'].includes(d.status) && !!d.latest_error?.endsWith('_outcome_unknown')
|
||||
|
||||
export function videoStatus(d: Pick<RawVideo, 'status' | 'latest_error'>): MaterialStatus {
|
||||
const s = d.status
|
||||
if (s === 'ready' || s === 'accepted' || s === 'rejected') return s
|
||||
if (s === 'failed' || s === 'cancelled') return 'failed'
|
||||
if (s === 'failed' || s === 'cancelled' || isStuckVideo(d)) return 'failed'
|
||||
return 'generating'
|
||||
}
|
||||
|
||||
@@ -153,13 +169,15 @@ async function videosOf({ agent, rule, active }: Schedule): Promise<Material[]>
|
||||
// newest draft only, so older failures don't each start another (paid) run.
|
||||
const newest = Math.max(...drafts.map(d => d.id))
|
||||
return drafts.map(d => {
|
||||
const status = videoStatus(d.status)
|
||||
const status = videoStatus(d)
|
||||
const stuck = isStuckVideo(d)
|
||||
return {
|
||||
retry: status === 'failed' && active && d.id === newest ? { run: true } as const : undefined,
|
||||
// A stuck video is cancelled first; a new run beside it would leave it unsettled.
|
||||
retry: status === 'failed' && !stuck && active && d.id === newest ? { run: true } as const : undefined,
|
||||
id: d.id, agentId: agent.id, kind: 'video', status, revision: 0,
|
||||
parts: [{ id: d.id, revision: 0, kind: 'video', status }],
|
||||
planTitle: d.title, composeSetId: null, sources: d.sources.map(s => s.title), createdAt: d.created_at, rule,
|
||||
video: { url: d.video_url, progress: d.progress_percentage, credits: d.actual_credits },
|
||||
video: { url: d.video_url, progress: d.progress_percentage, credits: d.actual_credits, stuck },
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -182,14 +200,112 @@ export function keepSettled<T>(results: PromiseSettledResult<T[]>[]): T[] {
|
||||
return kept
|
||||
}
|
||||
|
||||
// Promise.allSettled over a function, running at most `limit` at a time. Results are loaded one
|
||||
// request per schedule and polled; firing them all at once floods the engine, which then answers
|
||||
// some with 503 and drops those schedules' results until the next poll.
|
||||
export async function settleLimited<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<PromiseSettledResult<R>[]> {
|
||||
const out: PromiseSettledResult<R>[] = new Array(items.length)
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
while (next < items.length) {
|
||||
const i = next++
|
||||
try { out[i] = { status: 'fulfilled', value: await fn(items[i]) } }
|
||||
catch (reason) { out[i] = { status: 'rejected', reason } }
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
|
||||
return out
|
||||
}
|
||||
|
||||
const PER_SCHEDULE_LIMIT = 4
|
||||
|
||||
// The proxy's rate limit (503/429), a 5xx or no answer at all passes; a 4xx (e.g. a deleted agent) does not.
|
||||
const passing = (e: unknown) => e instanceof EngineError && (e.status === 0 || e.status === 429 || e.status >= 500)
|
||||
|
||||
const settledReads: Map<number, unknown>[] = []
|
||||
|
||||
/** After any action: a schedule's results (a decision on one) and production plans (a started or
|
||||
* retried piece) may have changed, so the next poll reads them again. */
|
||||
export function forgetReads() {
|
||||
for (const s of settledReads) s.clear()
|
||||
forgetProductionReads()
|
||||
}
|
||||
|
||||
// A settled read is still read again after this long: a ready video's signed URL lasts an hour.
|
||||
const SETTLED_FOR = 30 * 60_000
|
||||
|
||||
/** Wraps a per-schedule read so a passing failure does not change what the page shows: a busy
|
||||
* engine is asked once more after a pause, and if it still fails, the schedule's results from the
|
||||
* last poll that read them are used. Dropping them instead made every count on the page dip for
|
||||
* one poll and come back on the next.
|
||||
*
|
||||
* `mark` is what the engine's status read says about the schedule now; while it is the same as at
|
||||
* the last read, nothing the read shows has changed and that read is used again. A schedule whose
|
||||
* last read was not `quiet` (e.g. a plan whose topics have no drafts yet) is read every time. */
|
||||
export function remembering<T>(fn: (s: Schedule) => Promise<T[]>, pause = 3000, quiet: (s: Schedule) => boolean = () => true) {
|
||||
const last = new Map<number, T[]>()
|
||||
const settled = new Map<number, { mark: string; at: number }>()
|
||||
settledReads.push(settled)
|
||||
return async (s: Schedule, mark?: string): Promise<T[]> => {
|
||||
const id = s.agent.id
|
||||
// Without a status read, an archived schedule is the one known to make nothing new.
|
||||
const key = mark ?? (s.agent.status === 'archived' ? 'archived' : undefined)
|
||||
const kept = settled.get(id)
|
||||
if (key && kept?.mark === key && Date.now() - kept.at < SETTLED_FOR) return last.get(id)!
|
||||
try {
|
||||
const read = await fn(s).catch(async e => {
|
||||
if (!(e instanceof EngineError && (e.status === 503 || e.status === 429))) throw e
|
||||
await sleep(pause)
|
||||
return fn(s)
|
||||
})
|
||||
last.set(id, read)
|
||||
if (key && quiet(s)) settled.set(id, { mark: key, at: Date.now() })
|
||||
else settled.delete(id)
|
||||
return read
|
||||
} catch (e) {
|
||||
const kept = last.get(id)
|
||||
if (kept && passing(e)) return kept
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const readMaterials = remembering(materialsOf, undefined, s => !planning.has(s.agent.id))
|
||||
const readSources = remembering(sourcesOf)
|
||||
|
||||
interface AgentStatus { id: number }
|
||||
|
||||
/** One read of every schedule's runs and drafts, as a mark per schedule that changes whenever
|
||||
* anything in its results does (a draft's status or progress, a new run). The engine answers an
|
||||
* unchanged one with 304. A busy engine keeps the last marks, rather than being sent a read of
|
||||
* every schedule; without any (an engine that has no such read), every schedule is read. */
|
||||
let lastMarks: Map<number, string> | null = null
|
||||
async function changeMarks(): Promise<Map<number, string> | null> {
|
||||
try {
|
||||
const { agents } = await request<{ agents: AgentStatus[] }>(`${AGENTS}/status?archived=true`, { revalidate: true })
|
||||
lastMarks = new Map(agents.map(a => [a.id, JSON.stringify(a)]))
|
||||
} catch (e) {
|
||||
if (!passing(e)) lastMarks = null
|
||||
console.warn('Agent status could not be read', e)
|
||||
}
|
||||
return lastMarks
|
||||
}
|
||||
|
||||
// One status read per poll, plus a read of each schedule whose results changed since the last one.
|
||||
// A page opened or refocused within the interval reuses what was read; an action on a result or
|
||||
// schedule still refreshes them at once.
|
||||
export const RESULTS_POLL = { refetchInterval: 30_000, staleTime: 30_000 }
|
||||
|
||||
export async function listResults(): Promise<{ materials: Material[]; sources: FoundSource[] }> {
|
||||
const schedules = await expressAgents({ archived: true })
|
||||
const [materials, sources] = await Promise.all([
|
||||
Promise.allSettled(schedules.filter(s => s.rule.type === 'content').map(materialsOf)),
|
||||
Promise.allSettled(schedules.filter(s => s.rule.type === 'research').map(sourcesOf)),
|
||||
])
|
||||
const [schedules, marks] = await Promise.all([expressAgents({ archived: true }), changeMarks()])
|
||||
const content = schedules.filter(s => s.rule.type === 'content')
|
||||
const research = schedules.filter(s => s.rule.type === 'research')
|
||||
const marked = <T,>(read: (s: Schedule, mark?: string) => Promise<T[]>) => (s: Schedule) => read(s, marks?.get(s.agent.id))
|
||||
// One shared budget: research runs after content rather than alongside it.
|
||||
const materials = await settleLimited(content, PER_SCHEDULE_LIMIT, marked(readMaterials))
|
||||
const sources = await settleLimited(research, PER_SCHEDULE_LIMIT, marked(readSources))
|
||||
const newest = <T extends { createdAt: string }>(a: T, b: T) => b.createdAt.localeCompare(a.createdAt)
|
||||
return { materials: keepSettled(materials).sort(newest), sources: keepSettled(sources).sort(newest) }
|
||||
return { materials: keepSettled(materials).map(withDecisions).sort(newest), sources: keepSettled(sources).sort(newest) }
|
||||
}
|
||||
|
||||
const draftContent = (m: Material, id: number) =>
|
||||
@@ -209,14 +325,36 @@ export async function materialContent(m: Material): Promise<{ content: MaterialC
|
||||
// The engine renders slide decks to PPTX itself; other kinds have no file export there.
|
||||
export const exportPptx = (deckId: number) => request<Blob>(`/slide-deck/${deckId}/export`, { method: 'POST', as: 'blob' })
|
||||
|
||||
/** Stops a video still being made, or settles a stuck one; the engine keeps every charge it knows of. */
|
||||
export const canCancelVideo = (m: Material) => m.kind === 'video' && (isWorking(m) || !!m.video?.stuck)
|
||||
export const cancelVideo = (m: Material) => request(`${AGENTS}/${m.agentId}/video-drafts/${m.id}/cancel`, { method: 'POST' })
|
||||
|
||||
export const retryMaterial = ({ agentId, retry }: Material) =>
|
||||
retry && 'run' in retry ? runNow(agentId) : retryItem(agentId, retry!.planId, retry!.itemId)
|
||||
|
||||
// A decision the engine took, kept until a read of its part says so too: the read right after it
|
||||
// may be the last poll's (a busy engine) and still say ready, which left Approve looking undone.
|
||||
const decided = new Map<string, MaterialStatus>()
|
||||
const partKey = (m: Material, p: Part) => `${materialKey(m)}-${p.id}`
|
||||
|
||||
export function withDecisions(m: Material): Material {
|
||||
let changed = false
|
||||
const parts = m.parts.map(p => {
|
||||
const status = decided.get(partKey(m, p))
|
||||
if (!status) return p
|
||||
if (p.status !== 'ready') { decided.delete(partKey(m, p)); return p }
|
||||
changed = true
|
||||
return { ...p, status }
|
||||
})
|
||||
return changed ? { ...m, parts, status: combined(parts) } : m
|
||||
}
|
||||
|
||||
// Every part waiting for review gets the same decision, so a SCORM module is approved as one.
|
||||
export async function decideMaterial(m: Material, decision: 'accept' | 'reject') {
|
||||
for (const p of m.parts.filter(p => p.status === 'ready')) {
|
||||
if (m.kind === 'video') await request(`${AGENTS}/${m.agentId}/video-drafts/${p.id}/review`, { method: 'POST', json: { decision } })
|
||||
else await request(`${AGENTS}/${m.agentId}/material-drafts/${p.id}/decision`, { method: 'POST', json: { expected_revision: p.revision, decision } })
|
||||
decided.set(partKey(m, p), decision === 'accept' ? 'accepted' : 'rejected')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ContentRule, ResearchRule } from './parse'
|
||||
import { budgetFor, canSchedule, configFor, isMine, needsTwoSources, productionError, ruleOf, VIDEO, type ExpressAgent } from './schedules'
|
||||
import {
|
||||
budgetFor, canSchedule, configFor, createSchedule, isMine, missingDocuments, needsTwoSources, productionError, resumeSchedule, ruleOf, updateTopic, VIDEO,
|
||||
type ExpressAgent, type Schedule,
|
||||
} from './schedules'
|
||||
|
||||
const rule = (kind: ContentRule['kind'], count = 2, per: ContentRule['per'] = 'week', topic = 'onboarding', language: ContentRule['language'] = 'English'): ContentRule =>
|
||||
({ type: 'content', kind, count, per, topic, language })
|
||||
@@ -139,3 +142,77 @@ describe('isMine', () => {
|
||||
expect(isMine(schedule(null), owners)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('missingDocuments', () => {
|
||||
it('leaves out the documents a schedule already has', () => {
|
||||
expect(missingDocuments([1, 2, 3], [{ kind: 'document', id: 2 }, { kind: 'compose_set', id: 3 }])).toEqual([1, 3])
|
||||
})
|
||||
})
|
||||
|
||||
// Answers the engine's calls by method and path, and records them in order.
|
||||
function fakeEngine(answer: (method: string, path: string) => { status?: number; body?: unknown }) {
|
||||
const calls: string[] = []
|
||||
vi.stubGlobal('fetch', async (url: string, init: RequestInit = {}) => {
|
||||
const method = init.method ?? 'GET'
|
||||
const path = url.replace('/api/v1', '')
|
||||
calls.push(`${method} ${path}${init.body ? ` ${init.body}` : ''}`)
|
||||
const { status = 200, body = {} } = answer(method, path)
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
|
||||
})
|
||||
return calls
|
||||
}
|
||||
|
||||
const doc = (id: number) => ({ id, filename: `d${id}.pdf`, status: 'completed', knowledge_status: 'ready', created_at: '2026-10-01T00:00:00Z' })
|
||||
const put = (id: number) => `PUT /organizations/current/agents/1/knowledge-sources {"kind":"document","source_id":${id}}`
|
||||
|
||||
describe('updateTopic and resumeSchedule', () => {
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
const schedule = (active: boolean): Schedule => {
|
||||
const agent = { ...agentFrom(configFor(rule('summary'))), status: active ? 'active' : 'paused' }
|
||||
return { agent, rule: ruleOf(agent), active }
|
||||
}
|
||||
const engine = () => fakeEngine((method, path) => {
|
||||
if (path === '/upload/list') return { body: [doc(1), doc(2), doc(3)] }
|
||||
if (path.endsWith('/knowledge-sources') && method === 'GET') return { body: [{ kind: 'document', id: 1 }, { kind: 'document', id: 2 }] }
|
||||
return { body: { id: 1, status: 'active' } }
|
||||
})
|
||||
|
||||
it('re-activates right after the topic changes, then attaches only new material', async () => {
|
||||
const calls = engine()
|
||||
await updateTopic(schedule(true), 'leadership')
|
||||
expect(calls[0]).toMatch(/^PATCH \/organizations\/current\/agents\/1 /)
|
||||
expect(calls[1]).toBe('POST /organizations/current/agents/1/activate')
|
||||
expect(calls.filter(c => c.startsWith('PUT'))).toEqual([put(3)])
|
||||
})
|
||||
|
||||
it('keeps a paused schedule paused', async () => {
|
||||
const calls = engine()
|
||||
await updateTopic(schedule(false), 'leadership')
|
||||
expect(calls[1]).toBe('POST /organizations/current/agents/1/pause')
|
||||
})
|
||||
|
||||
it('resumes with one activate and attaches only new material', async () => {
|
||||
const calls = engine()
|
||||
await resumeSchedule(schedule(false))
|
||||
expect(calls[0]).toBe('POST /organizations/current/agents/1/activate')
|
||||
expect(calls.filter(c => c.includes('/activate'))).toHaveLength(1)
|
||||
expect(calls.filter(c => c.startsWith('PUT'))).toEqual([put(3)])
|
||||
})
|
||||
})
|
||||
|
||||
describe('createSchedule', () => {
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('attaches every ready document, skips one it cannot share, reports progress, then activates', async () => {
|
||||
const calls = fakeEngine((method, path) => {
|
||||
if (path === '/upload/list') return { body: [doc(1), doc(2), doc(3)] }
|
||||
if (method === 'PUT') return calls.at(-1)!.includes('"source_id":2') ? { status: 404, body: { detail: 'Ready workspace source not found' } } : { body: {} }
|
||||
return { body: { ...agentFrom(configFor(rule('summary'))), status: 'active' } }
|
||||
})
|
||||
const progress: string[] = []
|
||||
await createSchedule(rule('summary'), undefined, (done, total) => progress.push(`${done}/${total}`))
|
||||
expect(calls.filter(c => c.startsWith('PUT')).sort()).toEqual([put(1), put(2), put(3)])
|
||||
expect(calls.at(-1)).toBe('POST /organizations/current/agents/1/activate')
|
||||
expect(progress).toEqual(['0/3', '1/3', '2/3', '3/3'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Each Express schedule is one engine agent. Content rules use the engine's recurring production
|
||||
// (content_goal: weekly plans with novelty checks, started automatically); research and video rules
|
||||
// use run_schedule (one run per day or week; a video run renders one video).
|
||||
import { opKey, request } from '../api/client'
|
||||
import { EngineError, limiter, opKey, request } from '../api/client'
|
||||
import { listDocuments, type Agent, type RunSchedule } from '../api/engine'
|
||||
import { getLang, t } from '../i18n'
|
||||
import {
|
||||
@@ -265,41 +265,84 @@ export function canSchedule(rule: Rule): rule is ResearchRule | ContentRule {
|
||||
}
|
||||
|
||||
// The production corpus is the agent's own sources: the chosen documents, or every ready Brain document.
|
||||
async function attachBrain(agentId: number, chosen?: number[]) {
|
||||
const ids = chosen ?? (await listDocuments()).filter(d => d.knowledge === 'ready').map(d => d.docId)
|
||||
for (const id of ids) {
|
||||
await request(`${AGENTS}/${agentId}/knowledge-sources`, { method: 'PUT', json: { kind: 'document', source_id: id } })
|
||||
.catch(() => undefined) // a document someone else cannot share is skipped, not fatal
|
||||
// The engine adds them one request at a time and checks the whole workspace on each, so a Brain of
|
||||
// 150 documents is 150 slow requests: they go a few at a time, paced under the proxy's rate limit.
|
||||
const ATTACH_AT_ONCE = 3
|
||||
const ATTACH_TRIES = 3
|
||||
|
||||
export type AttachProgress = (done: number, total: number) => void
|
||||
|
||||
async function attachOne(agentId: number, id: number, tries = ATTACH_TRIES): Promise<void> {
|
||||
try {
|
||||
await request(`${AGENTS}/${agentId}/knowledge-sources`, { method: 'PUT', paced: true, json: { kind: 'document', source_id: id } })
|
||||
} catch (e) {
|
||||
// A busy proxy is asked again once the pace has waited for it; a document someone else cannot
|
||||
// share (404) is skipped, not fatal.
|
||||
const busy = e instanceof EngineError && (e.status === 503 || e.status === 429)
|
||||
if (busy && tries > 1) return attachOne(agentId, id, tries - 1)
|
||||
}
|
||||
}
|
||||
|
||||
async function attachDocuments(agentId: number, ids: number[], onProgress?: AttachProgress) {
|
||||
const one = limiter(ATTACH_AT_ONCE)
|
||||
let done = 0
|
||||
onProgress?.(0, ids.length)
|
||||
await Promise.all(ids.map(id => one(async () => {
|
||||
await attachOne(agentId, id)
|
||||
onProgress?.(++done, ids.length)
|
||||
})))
|
||||
}
|
||||
|
||||
/** The ready documents a whole-Brain schedule does not have yet. */
|
||||
export const missingDocuments = (ready: number[], attached: { kind: string; id: number }[]) => {
|
||||
const have = new Set(attached.filter(s => s.kind === 'document').map(s => s.id))
|
||||
return ready.filter(id => !have.has(id))
|
||||
}
|
||||
|
||||
const readyDocuments = async () => (await listDocuments()).filter(d => d.knowledge === 'ready').map(d => d.docId)
|
||||
|
||||
// A whole-Brain schedule picks up material added since it was made; a schedule of chosen material keeps to it.
|
||||
// The schedule's own change has gone through by then, so a failure here does not fail it: the next
|
||||
// edit or resume attaches what is still missing.
|
||||
async function attachNewMaterial(schedule: Schedule) {
|
||||
if (usesChosen(schedule.agent)) return
|
||||
const id = schedule.agent.id
|
||||
try {
|
||||
const [ready, attached] = await Promise.all([readyDocuments(), request<{ kind: string; id: number }[]>(`${AGENTS}/${id}/knowledge-sources`)])
|
||||
await attachDocuments(id, missingDocuments(ready, attached))
|
||||
} catch (e) {
|
||||
console.warn(`New Brain material was not attached to schedule ${id}`, e)
|
||||
}
|
||||
return ids.length
|
||||
}
|
||||
|
||||
/** With `chosen` document ids the schedule uses only those; without, the whole Brain. */
|
||||
export async function createSchedule(rule: Rule, chosen?: number[]): Promise<ExpressAgent> {
|
||||
export async function createSchedule(rule: Rule, chosen?: number[], onProgress?: AttachProgress): Promise<ExpressAgent> {
|
||||
const only = chosen?.length ? chosen : undefined
|
||||
// A video schedule's run budget is today's price of one video, so it is fetched first.
|
||||
const credits = rule.type === 'content' && rule.kind === 'video' ? (await videoQuote()).max_credits : 0
|
||||
const agent = await request<ExpressAgent>(AGENTS, { method: 'POST', json: configFor(rule, credits, !!only) })
|
||||
await attachBrain(agent.id, only)
|
||||
await attachDocuments(agent.id, only ?? (await readyDocuments()), onProgress)
|
||||
// Activating approves the production rules as they stand; until then nothing runs.
|
||||
return request<ExpressAgent>(`${AGENTS}/${agent.id}/activate`, { method: 'POST' })
|
||||
}
|
||||
|
||||
/** Changing a rule changes what was approved, so the agent is re-activated right after. */
|
||||
/** Changing the brief changes what was approved, so the engine sets the agent back to draft; it is
|
||||
* re-activated (or kept paused) at once. Sources are not part of the approval, so new material
|
||||
* is attached after that, without leaving the schedule paused meanwhile. */
|
||||
export async function updateTopic(schedule: Schedule, topic: string): Promise<ExpressAgent> {
|
||||
const rule = { ...schedule.rule, topic: topic.trim() }
|
||||
const chosen = usesChosen(schedule.agent)
|
||||
const { name, goal, instructions } = configFor(rule, 0, chosen)
|
||||
const { name, goal, instructions } = configFor(rule, 0, usesChosen(schedule.agent))
|
||||
await request(`${AGENTS}/${schedule.agent.id}`, { method: 'PATCH', json: { name, goal, instructions } })
|
||||
if (!chosen) await attachBrain(schedule.agent.id)
|
||||
return request<ExpressAgent>(`${AGENTS}/${schedule.agent.id}/${schedule.active ? 'activate' : 'pause'}`, { method: 'POST' })
|
||||
const agent = await request<ExpressAgent>(`${AGENTS}/${schedule.agent.id}/${schedule.active ? 'activate' : 'pause'}`, { method: 'POST' })
|
||||
await attachNewMaterial(schedule)
|
||||
return agent
|
||||
}
|
||||
|
||||
export const pauseSchedule = (id: number) => request<ExpressAgent>(`${AGENTS}/${id}/pause`, { method: 'POST' })
|
||||
export async function resumeSchedule(schedule: Schedule) {
|
||||
const id = schedule.agent.id
|
||||
if (!usesChosen(schedule.agent)) await attachBrain(id)
|
||||
return request<ExpressAgent>(`${AGENTS}/${id}/activate`, { method: 'POST' })
|
||||
const agent = await request<ExpressAgent>(`${AGENTS}/${schedule.agent.id}/activate`, { method: 'POST' })
|
||||
await attachNewMaterial(schedule)
|
||||
return agent
|
||||
}
|
||||
export const archiveSchedule = (id: number) => request<ExpressAgent>(`${AGENTS}/${id}/archive`, { method: 'POST' })
|
||||
|
||||
@@ -350,7 +393,19 @@ export function planProgress(plan: ContentPlan) {
|
||||
}
|
||||
}
|
||||
|
||||
export const productionStatus = (id: number) => request<ProductionStatus>(`${AGENTS}/${id}/content`)
|
||||
// The Schedule page (one query per row) and Results (one read per schedule) both poll this; a read
|
||||
// from the last half minute, or one still on its way, answers both. forgetReads drops them after an action.
|
||||
const PRODUCTION_FRESH = 30_000
|
||||
const productionReads = new Map<number, { at: number; read: Promise<ProductionStatus> }>()
|
||||
export function productionStatus(id: number, maxAge = PRODUCTION_FRESH): Promise<ProductionStatus> {
|
||||
const kept = productionReads.get(id)
|
||||
if (kept && Date.now() - kept.at < maxAge) return kept.read
|
||||
const read = request<ProductionStatus>(`${AGENTS}/${id}/content`)
|
||||
productionReads.set(id, { at: Date.now(), read })
|
||||
read.catch(() => { if (productionReads.get(id)?.read === read) productionReads.delete(id) })
|
||||
return read
|
||||
}
|
||||
export const forgetProductionReads = () => productionReads.clear()
|
||||
|
||||
// Produce now = the same plan the 09:00 tick would create, just earlier. The engine's tick then
|
||||
// approves and starts it within a minute because Express schedules run in automatic mode.
|
||||
|
||||
266
src/i18n.ts
266
src/i18n.ts
@@ -8,12 +8,40 @@ export const LANGS: { code: Lang; label: string }[] = [{ code: 'en', label: 'EN'
|
||||
const en = {
|
||||
// Layout
|
||||
'nav.brain': 'Upload material',
|
||||
'nav.instruction': 'Brain and AI',
|
||||
'nav.instruction': 'Instruction',
|
||||
'nav.schedule': 'Schedule',
|
||||
'nav.results': 'Results',
|
||||
'nav.dashboard': 'Dashboard',
|
||||
'nav.settings': 'Settings',
|
||||
'nav.production': 'Production',
|
||||
'nav.admin': 'Admin',
|
||||
'nav.billing': 'Billing',
|
||||
'billing.title': 'Billing',
|
||||
'billing.description': 'The credits your organization used, by date, person and module. Only organization admins can see this page.',
|
||||
'billing.total': 'Total used',
|
||||
'billing.period': '{from} to {to}',
|
||||
'billing.balance': 'Current balance',
|
||||
'billing.balanceSub': 'Organization credits',
|
||||
'billing.usage': 'Credit usage',
|
||||
'billing.from': 'Start date',
|
||||
'billing.to': 'End date',
|
||||
'billing.colDate': 'Date',
|
||||
'billing.colUser': 'User',
|
||||
'billing.colModule': 'Module',
|
||||
'billing.colCredits': 'Credits',
|
||||
'billing.refund': 'Refund',
|
||||
'billing.loading': 'Loading credit usage',
|
||||
'billing.loadFailed': 'Credit usage could not be loaded',
|
||||
'billing.empty': 'No credits used in this period',
|
||||
'billing.emptyCopy': 'Try a wider date range.',
|
||||
'billing.more': 'Show more',
|
||||
'billing.count': '{n} transactions',
|
||||
'billing.countOne': '{n} transaction',
|
||||
'billing.export': 'Export CSV',
|
||||
'billing.colActivity': 'Activity',
|
||||
'billing.colType': 'Type',
|
||||
'billing.charge': 'Charge',
|
||||
'billing.note': 'Usage is counted in credits, the unit your organization is charged in. Refunds are taken off the total.',
|
||||
'layout.learningSpace': 'Learning space',
|
||||
'layout.switchOrg': 'Switch organization',
|
||||
'layout.breadcrumb': 'Workspace',
|
||||
@@ -33,7 +61,7 @@ const en = {
|
||||
'auth.headline1': 'Team knowledge.',
|
||||
'auth.headline2': 'New ideas.',
|
||||
'auth.headline3': 'Learning that never stops.',
|
||||
'auth.copy': 'Upload material to the Brain, give one instruction, and AI keeps creating new learning content on schedule.',
|
||||
'auth.copy': 'Upload material to the Brain, give one instruction, and the Agent keeps creating new learning content on schedule.',
|
||||
'auth.benefitUpload': 'Upload material to the Brain',
|
||||
'auth.benefitSchedule': 'Schedule research and content',
|
||||
'auth.benefitDownload': 'Open and download the results',
|
||||
@@ -92,7 +120,7 @@ const en = {
|
||||
|
||||
// Brain
|
||||
'brain.title': 'Upload material',
|
||||
'brain.description': 'Upload your team’s training material here. Every file is processed into the Brain the AI creates content from.',
|
||||
'brain.description': 'Upload your team’s training material here. Every file is processed into the Brain the Agent creates content from.',
|
||||
'brain.metricMaterial': 'Material',
|
||||
'brain.metricMaterialSub': 'documents in the workspace',
|
||||
'brain.metricReady': 'In the Brain',
|
||||
@@ -100,6 +128,10 @@ const en = {
|
||||
'brain.metricAction': 'Needs action',
|
||||
'brain.metricActionSub': 'waiting for your approval',
|
||||
'brain.listTitle': 'Material',
|
||||
'brain.allStatuses': 'All statuses',
|
||||
'brain.duplicateConfirm': 'Already in the Brain: {names}. Upload another copy anyway? Cancel skips these files.',
|
||||
'brain.duplicateSkipped': 'Skipped: already in the Brain',
|
||||
'brain.downloaded': '{name} is downloading: this format opens in its own app.',
|
||||
'brain.loading': 'Loading material…',
|
||||
'brain.engineDown': 'Cannot reach the engine',
|
||||
'brain.empty': 'No material yet',
|
||||
@@ -140,14 +172,14 @@ const en = {
|
||||
'brain.deleteConfirm': 'Delete “{name}” from the Brain?',
|
||||
|
||||
// Instruction
|
||||
'ins.title': 'Brain and AI',
|
||||
'ins.description': 'Tell the AI what to make from the Brain. It turns your instruction into research and content schedules that keep running until you stop them.',
|
||||
'ins.title': 'Instruction',
|
||||
'ins.description': 'Tell the Agent what to make from the Brain. It turns your instruction into research and content schedules that keep running until you stop them.',
|
||||
'ins.label': 'Instruction',
|
||||
'ins.ex1': 'Make 2 summaries per day and 1 quiz per week about leadership',
|
||||
'ins.ex2': 'Research the internet every day about leadership',
|
||||
'ins.ex3': '3 roleplays per week about negotiating with customers',
|
||||
'ins.ex4': 'Research every Monday about sales trends, then make 5 flashcards per week',
|
||||
'ins.ex5': '1 video per week, 2 podcasts per week and 1 SCORM module per week about onboarding',
|
||||
'ins.ex5': '1 video per week, 2 podcasts per week and 1 INTERACTIVE module per week about onboarding',
|
||||
'ins.previewTitle': 'Schedules to create',
|
||||
'ins.readyCount': '{n} ready',
|
||||
'ins.approveNote': 'Once approved, schedules start right away. Content is created from the Brain without repeating existing content, using workspace credits within the limits above.',
|
||||
@@ -195,7 +227,7 @@ const en = {
|
||||
'kind.slide_deck': 'Slides',
|
||||
'kind.video': 'Video',
|
||||
'kind.audio': 'Audio',
|
||||
'kind.scorm': 'SCORM',
|
||||
'kind.scorm': 'INTERACTIVE',
|
||||
'day.0': 'Monday', 'day.1': 'Tuesday', 'day.2': 'Wednesday', 'day.3': 'Thursday', 'day.4': 'Friday', 'day.5': 'Saturday', 'day.6': 'Sunday',
|
||||
|
||||
// Schedule
|
||||
@@ -232,7 +264,7 @@ const en = {
|
||||
'prod.runningTitle': 'Producing {n} new pieces',
|
||||
'prod.lastTitle': 'Last production',
|
||||
'prod.count': '{ready} of {total} ready',
|
||||
'prod.stepTopics': 'AI chooses new topics',
|
||||
'prod.stepTopics': 'Agent chooses new topics',
|
||||
'prod.stepStart': 'Starting',
|
||||
'prod.stepCreate': 'Creating content ({ready}/{total})',
|
||||
'prod.stepDone': 'Done',
|
||||
@@ -270,6 +302,11 @@ const en = {
|
||||
'runErr.agent_not_active': 'The schedule is paused or deleted.',
|
||||
'runErr.run_access_revoked': 'You no longer have permission to run this schedule.',
|
||||
'runErr.required_tool_unavailable': 'A tool this schedule needs is turned off.',
|
||||
'runErr.user_cancelled': 'Cancelled.',
|
||||
'runErr.video_script_outcome_unknown': 'The video stopped without a confirmed result. Cancel it on Results to make it again.',
|
||||
'runErr.video_storyboard_outcome_unknown': 'The video stopped without a confirmed result. Cancel it on Results to make it again.',
|
||||
'runErr.video_style_outcome_unknown': 'The video stopped without a confirmed result. Cancel it on Results to make it again.',
|
||||
'runErr.video_clip_outcome_unknown': 'The video stopped without a confirmed result. Cancel it on Results to make it again.',
|
||||
'sch.noNewSources': 'No new sources found. A more specific topic may help.',
|
||||
'sch.blockedBy': 'Blocking material:',
|
||||
'sch.blockedNone': 'All material is ready now. Try again.',
|
||||
@@ -287,7 +324,7 @@ const en = {
|
||||
|
||||
// Results
|
||||
'res.title': 'Results',
|
||||
'res.description': 'Everything Express creates: text, quizzes, roleplays, video, audio, and SCORM.',
|
||||
'res.description': 'Everything Express creates: text, quizzes, roleplays, video, audio, and interactive.',
|
||||
'res.empty': 'No results yet',
|
||||
'res.emptyCopy': 'Content and sources from your schedules appear here. Give an instruction to start a schedule.',
|
||||
'res.tabContent': 'Content',
|
||||
@@ -300,6 +337,7 @@ const en = {
|
||||
'res.filterStatus': 'Filter by status',
|
||||
'res.allKinds': 'All types',
|
||||
'res.status.all': 'All statuses',
|
||||
'res.status.done': 'Finished',
|
||||
'res.status.review': 'Needs review',
|
||||
'res.status.approved': 'Approved',
|
||||
'res.status.working': 'In progress',
|
||||
@@ -316,13 +354,13 @@ const en = {
|
||||
'res.loadFailed': 'Results could not be loaded',
|
||||
'res.noMatch': 'Nothing matches',
|
||||
'res.noMatchCopy': 'Try another keyword, type, or status.',
|
||||
'res.noteContent': 'Download as PDF, Markdown or SCORM; slide decks also as PowerPoint, videos as MP4, audio scripts as text. Roleplay and simulation run interactively in Learning Studio.',
|
||||
'res.noteContent': 'Download as PDF, Markdown or INTERACTIVE; slide decks also as PowerPoint, videos as MP4, audio scripts as text. Roleplay and simulation run interactively in Learning Studio.',
|
||||
'res.noteResearch': 'Research finds web sources. Add the useful ones to the Library, then build their knowledge on the Brain page.',
|
||||
'res.sourceCount': '{n} sources',
|
||||
'res.sourceOne': '1 source',
|
||||
'res.working': 'Being created…',
|
||||
'res.close': 'Close',
|
||||
'res.reviewNotice': 'AI-generated draft. Check it, then approve it or reject it.',
|
||||
'res.reviewNotice': 'Agent-generated draft. Check it, then approve it or reject it.',
|
||||
'res.noContent': 'No content to show',
|
||||
'res.noContentCopy': 'This item has not finished or its output is no longer available.',
|
||||
'res.info': 'Content details',
|
||||
@@ -348,14 +386,14 @@ const en = {
|
||||
'res.field.objective': 'Objective',
|
||||
'res.field.learning_objectives': 'Learning objectives',
|
||||
'res.field.user_role': 'Learner role',
|
||||
'res.field.ai_character': 'AI character',
|
||||
'res.field.ai_character': 'Agent character',
|
||||
'res.field.difficulty': 'Difficulty',
|
||||
'res.field.context': 'Context',
|
||||
|
||||
// Media and SCORM (Phases 4, 5, 7)
|
||||
'ins.noteVideo': 'One video per run, about {seconds} seconds in {scenes} scenes, made by Video Studio. Each video waits for your review in Results.',
|
||||
'ins.noteAudio': 'Written as a narration script. Results plays it with the device voice and downloads it as text (no MP3 yet: the engine has no audio service for agents).',
|
||||
'ins.noteScorm': 'Each module is a lesson with a 10-question quiz, downloaded from Results as a SCORM 1.2 package for your LMS.',
|
||||
'ins.noteScorm': 'Each module is a lesson with a 10-question quiz, downloaded from Results as an INTERACTIVE package for your LMS.',
|
||||
'ins.videoCadence': 'A video schedule makes one video per run: choose 1 per day or 1 per week.',
|
||||
'ins.videoQuoteFailed': 'The video price could not be checked: {message}',
|
||||
'ins.budgetVideo': '{n} per video',
|
||||
@@ -369,7 +407,7 @@ const en = {
|
||||
'agent.greeting': 'Hi! Tell me what to create from the Brain and how often, or what to research on the internet. If anything is unclear, I will ask you here.',
|
||||
'agent.understood': 'Got it. Here is the plan so far:\n{list}',
|
||||
'agent.added': 'Added to the plan:\n{list}',
|
||||
'agent.notUnderstood': 'I could not find a content type or research request in that. I can make summaries, quizzes, flashcards, roleplays, simulations, slides, videos, audio and SCORM modules from the Brain, or research the internet. Try something like “2 summaries per day about leadership”.',
|
||||
'agent.notUnderstood': 'I could not find a content type or research request in that. I can make summaries, quizzes, flashcards, roleplays, simulations, slides, videos, audio and INTERACTIVE modules from the Brain, or research the internet. Try something like “2 summaries per day about leadership”.',
|
||||
'agent.askKind': '{count} pieces of content{about}: which kind? Pick one, or name several (for example “summaries and quizzes”) to split them.',
|
||||
'agent.askPer': 'How often should this be made? You did not say, and I would rather not guess.\n{list}',
|
||||
'agent.optMix': 'Mix (summaries, quizzes, flashcards)',
|
||||
@@ -395,6 +433,9 @@ const en = {
|
||||
'agent.languageSet': 'Content will be written in {language}.',
|
||||
'ins.language': 'Content language',
|
||||
'ins.languagePending': 'Not chosen yet',
|
||||
'ins.kindPending': 'Choose a kind',
|
||||
'ins.perPending': 'Choose how often',
|
||||
'ins.incomplete': 'Choose the kind, the frequency and the content language first.',
|
||||
'agent.skipped': 'OK, I skipped “{part}”.',
|
||||
'agent.removed': 'Removed {rule}.',
|
||||
'agent.updated': 'Updated: {rule}.',
|
||||
@@ -402,6 +443,7 @@ const en = {
|
||||
'agent.wholeBrain': 'OK, the whole Brain it is.',
|
||||
'agent.reset': 'Starting over. What should I create?',
|
||||
'agent.approving': 'Creating the schedules…',
|
||||
'agent.attaching': 'Connecting the Brain to schedule {n} of {count}: {done} of {total} documents',
|
||||
'agent.done': 'Done: {n} schedules are active and start right away.',
|
||||
'agent.partial': '{ok} of {n} schedules were created. The ones that failed are still in the plan: fix them, then approve again.',
|
||||
'agent.optSkip': 'Skip',
|
||||
@@ -425,6 +467,13 @@ const en = {
|
||||
'res.videoNotReady': 'The video is not ready yet',
|
||||
'res.videoFailed': 'The video could not be made',
|
||||
'res.videoFailedCopy': 'Rendering stopped before the video was finished.',
|
||||
'res.videoStuck': 'The video stopped',
|
||||
'res.videoStuckCopy': 'The engine could not confirm whether a step finished, so it will not continue. Cancel it to settle its credits; the schedule can then make it again.',
|
||||
'res.videoStuckShort': 'Stopped: cancel to retry',
|
||||
'res.cancelVideo': 'Cancel video',
|
||||
'res.cancellingVideo': 'Cancelling…',
|
||||
'res.cancelVideoConfirm': 'Cancel this video? Credits already spent are not refunded.',
|
||||
'res.videoCancelled': 'Video cancelled',
|
||||
'res.downloadVideo': 'Download video (MP4)',
|
||||
'res.creditsUsed': 'Credits used',
|
||||
'res.accepted': 'Approved.',
|
||||
@@ -438,11 +487,11 @@ const en = {
|
||||
'res.scriptHint': 'Narration text, for recording or a TTS tool',
|
||||
'res.quiz': 'Quiz',
|
||||
'res.quizPending': 'The quiz is not ready yet.',
|
||||
'res.scormModule': 'SCORM 1.2 module',
|
||||
'res.scormModule': 'INTERACTIVE module',
|
||||
'res.scormMeta': 'Lesson + {n} questions · pass mark {mastery}%',
|
||||
'res.scormHint': 'For an LMS: the lesson, marked complete when finished',
|
||||
'res.scormQuizHint': 'For an LMS: lesson and quiz, reports score and pass/fail',
|
||||
'res.scormReady': 'SCORM package downloaded. Upload the .zip to your LMS.',
|
||||
'res.scormReady': 'INTERACTIVE package downloaded. Upload the .zip to your LMS.',
|
||||
'scorm.submit': 'Check answers',
|
||||
'scorm.retry': 'Try again',
|
||||
'scorm.complete': 'Mark as complete',
|
||||
@@ -468,7 +517,7 @@ const en = {
|
||||
'brainPanel.search': 'Search material…',
|
||||
'brainPanel.noMatch': 'No material matches',
|
||||
'brainPanel.noMatchCopy': 'Try another keyword or upload more material.',
|
||||
'brainPanel.note': 'Chosen material is what the AI uses. Leave everything unticked to use the whole Brain.',
|
||||
'brainPanel.note': 'Chosen material is what the Agent uses. Leave everything unticked to use the whole Brain.',
|
||||
'brainPanel.selectAll': 'Select all',
|
||||
'brainPanel.nChosen': '{n} chosen materials',
|
||||
'ins.topicPlaceholderChosen': 'Topic (empty = all chosen material)',
|
||||
@@ -488,21 +537,25 @@ const en = {
|
||||
'help.boxBody': 'Four steps from your material to finished content.',
|
||||
'help.open': 'View the guide',
|
||||
'help.title': 'How Learning Lab Express works',
|
||||
'help.subtitle': 'Upload material → Brain and AI → Schedule → Results',
|
||||
'help.subtitle': 'Upload material → Instruction → Schedule → Results',
|
||||
'help.brainTitle': 'Upload material',
|
||||
'help.brainBody': 'Upload your training material. Once its knowledge is built, the AI creates everything from it.',
|
||||
'help.instructionTitle': 'Brain and AI',
|
||||
'help.brainBody': 'Upload your training material. Once its knowledge is built, the Agent creates everything from it.',
|
||||
'help.instructionTitle': 'Instruction',
|
||||
'help.instructionBody': 'Say what you need in one sentence, e.g. “3 quizzes per week and 1 video per week about leadership”. Check the schedules, then approve them.',
|
||||
'help.scheduleTitle': 'Schedule',
|
||||
'help.scheduleBody': 'Schedules run on their own. Pause them, change the topic, or produce now; each stays within its credit limit.',
|
||||
'help.resultsTitle': 'Results',
|
||||
'help.resultsBody': 'Review what was made, approve or reject it, and download it: PDF, Markdown, PowerPoint, MP4, audio script, or SCORM for your LMS.',
|
||||
'help.note': 'Content is AI-generated: always review it before using it. Credits come from your organization’s workspace.',
|
||||
'help.resultsBody': 'Review what was made, approve or reject it, and download it: PDF, Markdown, PowerPoint, MP4, audio script, or INTERACTIVE for your LMS.',
|
||||
'help.note': 'Content is Agent-generated: always review it before using it. Credits come from your organization’s workspace.',
|
||||
'help.done': 'Got it',
|
||||
|
||||
// Errors from the engine client
|
||||
'err.unreachable': 'Cannot reach the learning-lab engine.',
|
||||
'err.generic': 'The request to the engine failed.',
|
||||
'err.busy': 'The engine is busy right now. Try again in a moment.',
|
||||
'err.crashTitle': 'This page could not be shown',
|
||||
'err.crashCopy': 'Something went wrong while showing this page. Try again, or reload.',
|
||||
'err.reload': 'Reload',
|
||||
'err.credits': 'Not enough credits: needs {required}, balance {balance}.',
|
||||
'err.creditsShort': 'Not enough credits.',
|
||||
'err.docFailed': 'The document could not be processed.',
|
||||
@@ -518,35 +571,35 @@ const id: Record<Key, string> = {
|
||||
'prod.unitMaterial': 'materi',
|
||||
'prod.unitMaterialOne': 'materi',
|
||||
'prod.unitContent': 'konten',
|
||||
'prod.metricMaterial': 'Total materi di Brain',
|
||||
'prod.metricMaterial': 'Total materi di Otak',
|
||||
'prod.metricMaterialSub': 'Sumber pengetahuan tim Anda',
|
||||
'prod.metricMade': 'Semua konten dibuat',
|
||||
'prod.metricMadeSub': 'Seluruh hasil pembuatan konten',
|
||||
'prod.metricLms': 'Sudah diupload ke LMS',
|
||||
'prod.metricLmsSub': 'Status upload pada demo ini',
|
||||
'prod.metricLms': 'Sudah diunggah ke LMS',
|
||||
'prod.metricLmsSub': 'Status unggahan pada demo ini',
|
||||
'prod.activityTitle': 'Aktivitas konten',
|
||||
'prod.activityDescription': 'Dari pengetahuan di Brain menjadi pembelajaran baru.',
|
||||
'prod.activityDescription': 'Dari pengetahuan di Otak menjadi pembelajaran baru.',
|
||||
'prod.activityAll': 'Lihat semua hasil konten',
|
||||
'prod.activityLatest': 'Konten terbaru',
|
||||
'prod.activityWorking': 'Konten in progress',
|
||||
'prod.activityWorking': 'Konten sedang dibuat',
|
||||
'prod.activityNoneLatest': 'Belum ada konten yang dibuat.',
|
||||
'prod.activityNoneWorking': 'Tidak ada konten yang sedang dibuat.',
|
||||
'prod.eyebrow': 'Workspace overview',
|
||||
'prod.eyebrow': 'Ringkasan ruang kerja',
|
||||
'prod.welcome': 'Selamat datang',
|
||||
'prod.welcomeName': 'Selamat datang, {name}',
|
||||
'prod.newContent': 'Buat konten baru',
|
||||
'prod.graphTitle': 'Knowledge graph',
|
||||
'prod.clickNode': 'Klik sebuah node',
|
||||
'prod.graphTitle': 'Peta pengetahuan',
|
||||
'prod.clickNode': 'Klik titik untuk melihat detailnya',
|
||||
'prod.fullscreen': 'Layar penuh',
|
||||
'prod.exitFullscreen': 'Keluar layar penuh',
|
||||
'prod.loadingGraph': 'Menggambar knowledge graph…',
|
||||
'prod.graphLabel': 'Knowledge graph berisi {nodes} node',
|
||||
'prod.loadingGraph': 'Menggambar peta pengetahuan…',
|
||||
'prod.graphLabel': 'Peta pengetahuan berisi {nodes} titik',
|
||||
'prod.hub.sources': 'Basis pengetahuan',
|
||||
'prod.hub.made': 'Konten',
|
||||
'prod.nodes': 'Node',
|
||||
'prod.nodes': 'Titik',
|
||||
'prod.nodesSub': 'di Otak ini',
|
||||
'prod.links': 'Tautan',
|
||||
'prod.linksSub': 'koneksi antar node',
|
||||
'prod.linksSub': 'koneksi antartitik',
|
||||
'prod.scheduleTitle': 'Jadwal',
|
||||
'prod.noSchedules': 'Belum ada jadwal.',
|
||||
'prod.giveInstruction': 'Beri perintah',
|
||||
@@ -554,18 +607,46 @@ const id: Record<Key, string> = {
|
||||
'prod.nothingNow': 'Tidak ada yang sedang dibuat.',
|
||||
'prod.more': '+{n} lagi di Hasil',
|
||||
'nav.brain': 'Upload materi',
|
||||
'nav.instruction': 'Brain and AI',
|
||||
'nav.instruction': 'Instruksi',
|
||||
'nav.schedule': 'Jadwal',
|
||||
'nav.results': 'Hasil',
|
||||
'nav.dashboard': 'Dasbor',
|
||||
'nav.settings': 'Pengaturan',
|
||||
'nav.production': 'Produksi',
|
||||
'nav.admin': 'Admin',
|
||||
'nav.billing': 'Billing',
|
||||
'billing.title': 'Billing',
|
||||
'billing.description': 'Kredit yang dipakai organisasi Anda, per tanggal, pengguna, dan modul. Halaman ini hanya bisa dilihat admin organisasi.',
|
||||
'billing.total': 'Total terpakai',
|
||||
'billing.period': '{from} sampai {to}',
|
||||
'billing.balance': 'Saldo saat ini',
|
||||
'billing.balanceSub': 'Kredit organisasi',
|
||||
'billing.usage': 'Konsumsi kredit',
|
||||
'billing.from': 'Tanggal mulai',
|
||||
'billing.to': 'Tanggal akhir',
|
||||
'billing.colDate': 'Tanggal',
|
||||
'billing.colUser': 'Pengguna',
|
||||
'billing.colModule': 'Modul',
|
||||
'billing.colCredits': 'Kredit',
|
||||
'billing.refund': 'Dikembalikan',
|
||||
'billing.loading': 'Memuat konsumsi kredit',
|
||||
'billing.loadFailed': 'Konsumsi kredit tidak bisa dimuat',
|
||||
'billing.empty': 'Tidak ada kredit terpakai di periode ini',
|
||||
'billing.emptyCopy': 'Coba rentang tanggal yang lebih lebar.',
|
||||
'billing.more': 'Tampilkan lagi',
|
||||
'billing.count': '{n} transaksi',
|
||||
'billing.countOne': '{n} transaksi',
|
||||
'billing.export': 'Ekspor CSV',
|
||||
'billing.colActivity': 'Aktivitas',
|
||||
'billing.colType': 'Jenis',
|
||||
'billing.charge': 'Terpakai',
|
||||
'billing.note': 'Pemakaian dihitung dalam kredit, satuan yang ditagihkan ke organisasi Anda. Kredit yang dikembalikan mengurangi total.',
|
||||
'layout.learningSpace': 'Ruang belajar',
|
||||
'layout.switchOrg': 'Ganti organisasi',
|
||||
'layout.breadcrumb': 'Ruang kerja',
|
||||
'layout.signOut': 'Keluar',
|
||||
'layout.engine': 'Engine learning-lab',
|
||||
'layout.creditsTitle': 'Saldo kredit workspace',
|
||||
'layout.creditsTitle': 'Saldo kredit ruang kerja',
|
||||
'layout.toStudio': 'Beralih ke Learning Lab',
|
||||
'layout.footer': 'Ruang kerja untuk pengetahuan yang terus berkembang.',
|
||||
'layout.mainNav': 'Navigasi utama',
|
||||
@@ -578,7 +659,7 @@ const id: Record<Key, string> = {
|
||||
'auth.headline1': 'Pengetahuan tim.',
|
||||
'auth.headline2': 'Ide baru.',
|
||||
'auth.headline3': 'Pembelajaran tanpa henti.',
|
||||
'auth.copy': 'Unggah materi ke Otak, beri satu perintah, dan AI terus membuat konten pembelajaran baru sesuai jadwal.',
|
||||
'auth.copy': 'Unggah materi ke Otak, beri satu perintah, dan Agent terus membuat konten pembelajaran baru sesuai jadwal.',
|
||||
'auth.benefitUpload': 'Unggah materi ke Otak',
|
||||
'auth.benefitSchedule': 'Jadwalkan riset dan konten',
|
||||
'auth.benefitDownload': 'Buka dan unduh hasilnya',
|
||||
@@ -593,14 +674,18 @@ const id: Record<Key, string> = {
|
||||
'common.credits': '{n} kredit',
|
||||
|
||||
'brain.title': 'Upload materi',
|
||||
'brain.description': 'Unggah materi pelatihan tim di sini. Setiap file diproses ke dalam Otak yang menjadi sumber AI membuat konten.',
|
||||
'brain.description': 'Unggah materi pelatihan tim di sini. Setiap file diproses ke dalam Otak yang menjadi sumber Agent membuat konten.',
|
||||
'brain.metricMaterial': 'Materi',
|
||||
'brain.metricMaterialSub': 'dokumen di ruang kerja',
|
||||
'brain.metricReady': 'Masuk Otak',
|
||||
'brain.metricReadySub': 'knowledge base siap',
|
||||
'brain.metricReadySub': 'basis pengetahuan siap',
|
||||
'brain.metricAction': 'Perlu tindakan',
|
||||
'brain.metricActionSub': 'menunggu persetujuan Anda',
|
||||
'brain.listTitle': 'Materi',
|
||||
'brain.allStatuses': 'Semua status',
|
||||
'brain.duplicateConfirm': 'Sudah ada di Otak: {names}. Tetap unggah salinan lain? Batal akan melewati file ini.',
|
||||
'brain.duplicateSkipped': 'Dilewati: sudah ada di Otak',
|
||||
'brain.downloaded': '{name} sedang diunduh: format ini dibuka di aplikasinya sendiri.',
|
||||
'brain.loading': 'Memuat materi…',
|
||||
'brain.engineDown': 'Engine tidak dapat dihubungi',
|
||||
'brain.empty': 'Belum ada materi',
|
||||
@@ -640,14 +725,14 @@ const id: Record<Key, string> = {
|
||||
'brain.open': 'Buka {name}',
|
||||
'brain.deleteConfirm': 'Hapus “{name}” dari Otak?',
|
||||
|
||||
'ins.title': 'Brain and AI',
|
||||
'ins.description': 'Beri tahu AI apa yang perlu dibuat dari Otak. AI menyusun instruksi Anda menjadi jadwal riset dan pembuatan konten yang terus berjalan sampai Anda menghentikannya.',
|
||||
'ins.title': 'Instruksi',
|
||||
'ins.description': 'Beri tahu Agent apa yang perlu dibuat dari Otak. Agent menyusun instruksi Anda menjadi jadwal riset dan pembuatan konten yang terus berjalan sampai Anda menghentikannya.',
|
||||
'ins.label': 'Instruksi',
|
||||
'ins.ex1': 'Bikin 2 ringkasan per hari dan 1 kuis per minggu soal leadership',
|
||||
'ins.ex2': 'Riset internet tiap hari soal leadership',
|
||||
'ins.ex3': '3 roleplay per minggu tentang negosiasi dengan pelanggan',
|
||||
'ins.ex4': 'Riset tiap Senin soal tren sales, lalu buat 5 flashcard per minggu',
|
||||
'ins.ex5': '1 video per minggu, 2 podcast per minggu dan 1 modul SCORM per minggu soal onboarding',
|
||||
'ins.ex5': '1 video per minggu, 2 podcast per minggu dan 1 modul INTERACTIVE per minggu soal onboarding',
|
||||
'ins.previewTitle': 'Jadwal yang akan dibuat',
|
||||
'ins.readyCount': '{n} siap',
|
||||
'ins.approveNote': 'Setelah disetujui, jadwal langsung aktif. Konten dibuat dari materi di Otak tanpa mengulang yang sudah ada, dan memakai kredit ruang kerja sesuai batas di atas.',
|
||||
@@ -694,7 +779,7 @@ const id: Record<Key, string> = {
|
||||
'kind.slide_deck': 'Slide',
|
||||
'kind.video': 'Video',
|
||||
'kind.audio': 'Audio',
|
||||
'kind.scorm': 'SCORM',
|
||||
'kind.scorm': 'INTERACTIVE',
|
||||
'day.0': 'Senin', 'day.1': 'Selasa', 'day.2': 'Rabu', 'day.3': 'Kamis', 'day.4': 'Jumat', 'day.5': 'Sabtu', 'day.6': 'Minggu',
|
||||
|
||||
'sch.title': 'Jadwal',
|
||||
@@ -730,14 +815,14 @@ const id: Record<Key, string> = {
|
||||
'prod.runningTitle': 'Memproduksi {n} konten baru',
|
||||
'prod.lastTitle': 'Produksi terakhir',
|
||||
'prod.count': '{ready} dari {total} siap',
|
||||
'prod.stepTopics': 'AI memilih topik baru',
|
||||
'prod.stepTopics': 'Agent memilih topik baru',
|
||||
'prod.stepStart': 'Memulai',
|
||||
'prod.stepCreate': 'Membuat konten ({ready}/{total})',
|
||||
'prod.stepDone': 'Selesai',
|
||||
'prod.failed': 'Produksi gagal ({code}).',
|
||||
'prod.someFailed': '{n} gagal.',
|
||||
'prod.shortfall': 'Brain hanya punya materi baru untuk lebih sedikit konten dari yang diminta (kurang {n}); tambah dokumen untuk topik lain.',
|
||||
'prod.viewResults': 'Lihat di Results',
|
||||
'prod.shortfall': 'Otak hanya punya materi baru untuk lebih sedikit konten dari yang diminta (kurang {n}); tambah dokumen untuk topik lain.',
|
||||
'prod.viewResults': 'Lihat di Hasil',
|
||||
'sch.produceHowMany': 'Berapa konten sekarang? (sisa {max} untuk minggu ini)',
|
||||
'sch.checkPrice': 'Cek harga',
|
||||
'sch.checkingPrice': 'Mengecek…',
|
||||
@@ -760,31 +845,36 @@ const id: Record<Key, string> = {
|
||||
'runErr.material_sources_unavailable': 'Tidak ada materi siap yang cocok dengan jadwal ini.',
|
||||
'runErr.knowledge_search_failed': 'Pencarian materi gagal. Coba lagi.',
|
||||
'runErr.organization_wallet': 'Kredit organisasi tidak cukup.',
|
||||
'runErr.run_cap': 'Run ini melebihi batas kredit per run.',
|
||||
'runErr.run_cap': 'Proses ini melebihi batas kredit per proses.',
|
||||
'runErr.monthly_cap': 'Batas kredit bulanan jadwal ini sudah tercapai.',
|
||||
'runErr.reservation_cap': 'Terlalu banyak kredit sudah dipesan oleh run lain.',
|
||||
'runErr.reservation_cap': 'Terlalu banyak kredit sudah dipesan oleh proses lain.',
|
||||
'runErr.price_changed': 'Harga berubah. Coba lagi.',
|
||||
'runErr.video_price_changed': 'Harga video berubah. Coba lagi.',
|
||||
'runErr.agent_not_active': 'Jadwal sedang dijeda atau sudah dihapus.',
|
||||
'runErr.run_access_revoked': 'Kamu tidak lagi punya izin menjalankan jadwal ini.',
|
||||
'runErr.required_tool_unavailable': 'Alat yang dibutuhkan jadwal ini sedang nonaktif.',
|
||||
'sch.noNewSources': 'Tidak ada source baru yang ditemukan. Topik yang lebih spesifik bisa membantu.',
|
||||
'runErr.user_cancelled': 'Dibatalkan.',
|
||||
'runErr.video_script_outcome_unknown': 'Video berhenti tanpa hasil yang pasti. Batalkan di Hasil agar bisa dibuat ulang.',
|
||||
'runErr.video_storyboard_outcome_unknown': 'Video berhenti tanpa hasil yang pasti. Batalkan di Hasil agar bisa dibuat ulang.',
|
||||
'runErr.video_style_outcome_unknown': 'Video berhenti tanpa hasil yang pasti. Batalkan di Hasil agar bisa dibuat ulang.',
|
||||
'runErr.video_clip_outcome_unknown': 'Video berhenti tanpa hasil yang pasti. Batalkan di Hasil agar bisa dibuat ulang.',
|
||||
'sch.noNewSources': 'Tidak ada sumber baru yang ditemukan. Topik yang lebih spesifik bisa membantu.',
|
||||
'sch.blockedBy': 'Materi yang menahan:',
|
||||
'sch.blockedNone': 'Semua materi sudah siap. Coba lagi.',
|
||||
'sch.fixInStudio': 'Buka di Learning Studio',
|
||||
'issue.document_processing': 'masih diproses',
|
||||
'issue.document_failed': 'gagal diproses; proses ulang atau hapus',
|
||||
'issue.graph_building': 'knowledge graph masih dibangun',
|
||||
'issue.graph_not_ready': 'knowledge graph belum disiapkan',
|
||||
'issue.graph_building': 'peta pengetahuan masih dibangun',
|
||||
'issue.graph_not_ready': 'peta pengetahuan belum disiapkan',
|
||||
'issue.legacy_set_needs_conversion': 'set Compose lama; perlu dikonversi',
|
||||
'issue.no_knowledge_sources': 'set Compose tidak punya sumber',
|
||||
'issue.source_not_accessible': 'set Compose memakai dokumen yang tidak bisa kamu akses',
|
||||
'issue.source_graph_not_ready': 'salah satu dokumen sumber belum siap',
|
||||
'issue.source_version_changed': 'dokumen sumber berubah; perbarui set-nya',
|
||||
'issue.snapshot_not_ready': 'graph Compose belum disiapkan',
|
||||
'issue.snapshot_not_ready': 'peta pengetahuan Compose belum disiapkan',
|
||||
|
||||
'res.title': 'Hasil',
|
||||
'res.description': 'Semua konten yang dihasilkan Express: teks, kuis, roleplay, video, audio, dan SCORM.',
|
||||
'res.description': 'Semua konten yang dihasilkan Express: teks, kuis, roleplay, video, audio, dan INTERACTIVE.',
|
||||
'res.empty': 'Belum ada hasil',
|
||||
'res.emptyCopy': 'Konten dan sumber dari jadwal Anda tampil di sini. Beri perintah untuk memulai jadwal.',
|
||||
'res.tabContent': 'Konten',
|
||||
@@ -797,6 +887,7 @@ const id: Record<Key, string> = {
|
||||
'res.filterStatus': 'Filter status',
|
||||
'res.allKinds': 'Semua jenis',
|
||||
'res.status.all': 'Semua status',
|
||||
'res.status.done': 'Selesai dibuat',
|
||||
'res.status.review': 'Perlu ditinjau',
|
||||
'res.status.approved': 'Disetujui',
|
||||
'res.status.working': 'Sedang dibuat',
|
||||
@@ -808,18 +899,18 @@ const id: Record<Key, string> = {
|
||||
'res.state.failed': 'Gagal',
|
||||
'res.state.rejected': 'Ditolak',
|
||||
'res.source.pending': 'Perlu ditinjau',
|
||||
'res.source.accepted': 'Masuk Library',
|
||||
'res.source.accepted': 'Masuk Pustaka',
|
||||
'res.source.rejected': 'Ditolak',
|
||||
'res.loadFailed': 'Hasil tidak dapat dimuat',
|
||||
'res.noMatch': 'Tidak ada yang cocok',
|
||||
'res.noMatchCopy': 'Coba kata kunci, jenis, atau status lain.',
|
||||
'res.noteContent': 'Unduh sebagai PDF, Markdown, atau SCORM; slide deck juga sebagai PowerPoint, video sebagai MP4, naskah audio sebagai teks. Roleplay dan simulasi dijalankan secara interaktif di Learning Studio.',
|
||||
'res.noteResearch': 'Riset menemukan sumber dari web. Masukkan yang berguna ke Library, lalu bangun pengetahuannya di halaman Brain.',
|
||||
'res.noteContent': 'Unduh sebagai PDF, Markdown, atau INTERACTIVE; slide deck juga sebagai PowerPoint, video sebagai MP4, naskah audio sebagai teks. Roleplay dan simulasi dijalankan secara interaktif di Learning Studio.',
|
||||
'res.noteResearch': 'Riset menemukan sumber dari web. Masukkan yang berguna ke Pustaka, lalu bangun pengetahuannya di halaman Upload materi.',
|
||||
'res.sourceCount': '{n} sumber',
|
||||
'res.sourceOne': '1 sumber',
|
||||
'res.working': 'Sedang dibuat…',
|
||||
'res.close': 'Tutup',
|
||||
'res.reviewNotice': 'Draft buatan AI. Periksa dulu, lalu setujui atau tolak.',
|
||||
'res.reviewNotice': 'Draf buatan Agent. Periksa dulu, lalu setujui atau tolak.',
|
||||
'res.noContent': 'Tidak ada konten untuk ditampilkan',
|
||||
'res.noContentCopy': 'Item ini belum selesai atau hasilnya sudah tidak tersedia.',
|
||||
'res.info': 'Informasi konten',
|
||||
@@ -827,17 +918,17 @@ const id: Record<Key, string> = {
|
||||
'res.schedule': 'Jadwal',
|
||||
'res.created': 'Dibuat',
|
||||
'res.sources': 'Sumber',
|
||||
'res.footNote': 'Dibuat oleh Express dari Brain Anda.',
|
||||
'res.footNote': 'Dibuat oleh Express dari Otak Anda.',
|
||||
'res.openStudio': 'Buka di Learning Studio',
|
||||
'res.download': 'Unduh',
|
||||
'res.preparingFile': 'Menyiapkan file…',
|
||||
'res.pdfHint': 'Membuka dialog cetak: pilih “Save as PDF” / “Simpan sebagai PDF”',
|
||||
'res.pdfHint': 'Membuka dialog cetak: pilih “Simpan sebagai PDF”',
|
||||
'res.pptxHint': 'Slide dari Learning Studio',
|
||||
'res.mdHint': 'Teks dengan judul, untuk disunting',
|
||||
'res.accept': 'Setujui',
|
||||
'res.reject': 'Tolak',
|
||||
'res.addToBrain': 'Masukkan ke Library',
|
||||
'res.inBrain': 'lihat Brain',
|
||||
'res.addToBrain': 'Masukkan ke Pustaka',
|
||||
'res.inBrain': 'lihat di Otak',
|
||||
'res.answer': 'Jawaban',
|
||||
'res.slide': 'Slide {n}',
|
||||
'res.field.description': 'Deskripsi',
|
||||
@@ -845,14 +936,14 @@ const id: Record<Key, string> = {
|
||||
'res.field.objective': 'Tujuan',
|
||||
'res.field.learning_objectives': 'Tujuan pembelajaran',
|
||||
'res.field.user_role': 'Peran peserta',
|
||||
'res.field.ai_character': 'Karakter AI',
|
||||
'res.field.ai_character': 'Karakter Agent',
|
||||
'res.field.difficulty': 'Tingkat kesulitan',
|
||||
'res.field.context': 'Konteks',
|
||||
|
||||
// Media dan SCORM (Fase 4, 5, 7)
|
||||
'ins.noteVideo': 'Satu video per proses, sekitar {seconds} detik dalam {scenes} adegan, dibuat oleh Video Studio. Setiap video menunggu tinjauan Anda di Hasil.',
|
||||
'ins.noteAudio': 'Dibuat sebagai naskah narasi. Hasil memutarnya dengan suara perangkat dan mengunduhnya sebagai teks (belum MP3: engine belum punya layanan audio untuk agen).',
|
||||
'ins.noteScorm': 'Setiap modul berisi materi dan kuis 10 soal, diunduh dari Hasil sebagai paket SCORM 1.2 untuk LMS Anda.',
|
||||
'ins.noteScorm': 'Setiap modul berisi materi dan kuis 10 soal, diunduh dari Hasil sebagai paket INTERACTIVE untuk LMS Anda.',
|
||||
'ins.videoCadence': 'Jadwal video membuat satu video per proses: pilih 1 per hari atau 1 per minggu.',
|
||||
'ins.videoQuoteFailed': 'Harga video tidak bisa dicek: {message}',
|
||||
'ins.budgetVideo': '{n} per video',
|
||||
@@ -866,7 +957,7 @@ const id: Record<Key, string> = {
|
||||
'agent.greeting': 'Halo! Ceritakan konten apa yang perlu dibuat dari Otak dan seberapa sering, atau apa yang perlu diriset di internet. Kalau ada yang belum jelas, saya tanyakan di sini.',
|
||||
'agent.understood': 'Siap. Ini rencananya sejauh ini:\n{list}',
|
||||
'agent.added': 'Ditambahkan ke rencana:\n{list}',
|
||||
'agent.notUnderstood': 'Saya belum menemukan jenis konten atau permintaan riset di situ. Saya bisa membuat ringkasan, kuis, flashcard, roleplay, simulasi, slide, video, audio, dan modul SCORM dari Otak, atau riset internet. Coba misalnya “2 ringkasan per hari soal leadership”.',
|
||||
'agent.notUnderstood': 'Saya belum menemukan jenis konten atau permintaan riset di situ. Saya bisa membuat ringkasan, kuis, flashcard, roleplay, simulasi, slide, video, audio, dan modul INTERACTIVE dari Otak, atau riset internet. Coba misalnya “2 ringkasan per hari soal leadership”.',
|
||||
'agent.askKind': '{count} konten{about}: jenisnya apa? Pilih satu, atau sebut beberapa (misalnya “ringkasan dan kuis”) untuk membaginya.',
|
||||
'agent.askPer': 'Seberapa sering ini dibuat? Anda belum menyebutkannya, dan saya tidak mau menebak.\n{list}',
|
||||
'agent.optMix': 'Campuran (ringkasan, kuis, flashcard)',
|
||||
@@ -892,6 +983,9 @@ const id: Record<Key, string> = {
|
||||
'agent.languageSet': 'Konten akan ditulis dalam {language}.',
|
||||
'ins.language': 'Bahasa konten',
|
||||
'ins.languagePending': 'Belum dipilih',
|
||||
'ins.kindPending': 'Pilih jenis',
|
||||
'ins.perPending': 'Pilih frekuensi',
|
||||
'ins.incomplete': 'Pilih jenis, frekuensi, dan bahasa konten dulu.',
|
||||
'agent.skipped': 'Oke, “{part}” saya lewati.',
|
||||
'agent.removed': '{rule} dihapus.',
|
||||
'agent.updated': 'Diperbarui: {rule}.',
|
||||
@@ -899,6 +993,7 @@ const id: Record<Key, string> = {
|
||||
'agent.wholeBrain': 'Oke, pakai seluruh Otak.',
|
||||
'agent.reset': 'Mulai dari awal. Apa yang perlu dibuat?',
|
||||
'agent.approving': 'Membuat jadwal…',
|
||||
'agent.attaching': 'Menghubungkan Otak ke jadwal {n} dari {count}: {done} dari {total} dokumen',
|
||||
'agent.done': 'Selesai: {n} jadwal aktif dan langsung berjalan.',
|
||||
'agent.partial': '{ok} dari {n} jadwal berhasil dibuat. Yang gagal masih ada di rencana: perbaiki, lalu setujui lagi.',
|
||||
'agent.optSkip': 'Lewati',
|
||||
@@ -922,6 +1017,13 @@ const id: Record<Key, string> = {
|
||||
'res.videoNotReady': 'Video belum siap',
|
||||
'res.videoFailed': 'Video gagal dibuat',
|
||||
'res.videoFailedCopy': 'Proses render berhenti sebelum video selesai.',
|
||||
'res.videoStuck': 'Video berhenti',
|
||||
'res.videoStuckCopy': 'Engine tidak bisa memastikan apakah satu tahap selesai, jadi proses tidak dilanjutkan. Batalkan video ini untuk menyelesaikan kreditnya; setelah itu jadwal bisa membuatnya lagi.',
|
||||
'res.videoStuckShort': 'Berhenti: batalkan untuk coba lagi',
|
||||
'res.cancelVideo': 'Batalkan video',
|
||||
'res.cancellingVideo': 'Membatalkan…',
|
||||
'res.cancelVideoConfirm': 'Batalkan video ini? Kredit yang sudah terpakai tidak dikembalikan.',
|
||||
'res.videoCancelled': 'Video dibatalkan',
|
||||
'res.downloadVideo': 'Unduh video (MP4)',
|
||||
'res.creditsUsed': 'Kredit terpakai',
|
||||
'res.accepted': 'Disetujui.',
|
||||
@@ -935,11 +1037,11 @@ const id: Record<Key, string> = {
|
||||
'res.scriptHint': 'Teks narasi, untuk direkam atau alat TTS',
|
||||
'res.quiz': 'Kuis',
|
||||
'res.quizPending': 'Kuisnya belum siap.',
|
||||
'res.scormModule': 'Modul SCORM 1.2',
|
||||
'res.scormModule': 'Modul INTERACTIVE',
|
||||
'res.scormMeta': 'Materi + {n} soal · nilai lulus {mastery}%',
|
||||
'res.scormHint': 'Untuk LMS: materi, ditandai selesai setelah dibaca',
|
||||
'res.scormQuizHint': 'Untuk LMS: materi dan kuis, melaporkan nilai dan lulus/tidak',
|
||||
'res.scormReady': 'Paket SCORM terunduh. Unggah file .zip ke LMS Anda.',
|
||||
'res.scormReady': 'Paket INTERACTIVE terunduh. Unggah file .zip ke LMS Anda.',
|
||||
'scorm.submit': 'Periksa jawaban',
|
||||
'scorm.retry': 'Coba lagi',
|
||||
'scorm.complete': 'Tandai selesai',
|
||||
@@ -959,46 +1061,50 @@ const id: Record<Key, string> = {
|
||||
'audio.ready': '{n} kalimat · tekan Dengarkan untuk mulai',
|
||||
'audio.sentence': 'Kalimat {n} dari {total}',
|
||||
'brain.deleted': '“{name}” dihapus.',
|
||||
'brainPanel.title': 'Brain',
|
||||
'brainPanel.title': 'Otak',
|
||||
'brainPanel.count': '{n} materi',
|
||||
'brainPanel.copy': 'Knowledge base tim Anda.',
|
||||
'brainPanel.copy': 'Basis pengetahuan tim Anda.',
|
||||
'brainPanel.search': 'Cari materi…',
|
||||
'brainPanel.noMatch': 'Belum ada materi yang cocok',
|
||||
'brainPanel.noMatchCopy': 'Coba kata kunci lain atau upload materi baru.',
|
||||
'brainPanel.note': 'Materi yang dipilih menjadi acuan AI. Kosongkan pilihan untuk memakai seluruh Brain.',
|
||||
'brainPanel.note': 'Materi yang dipilih menjadi acuan Agent. Kosongkan pilihan untuk memakai seluruh Otak.',
|
||||
'brainPanel.selectAll': 'Pilih semua',
|
||||
'brainPanel.nChosen': '{n} materi pilihan',
|
||||
'ins.topicPlaceholderChosen': 'Topik (kosong = semua materi pilihan)',
|
||||
'brainPanel.selected': '{n} dipilih',
|
||||
'brainPanel.wholeBrain': 'Seluruh Brain digunakan',
|
||||
'brainPanel.wholeBrain': 'Seluruh Otak digunakan',
|
||||
'brainPanel.select': 'Pilih {name}',
|
||||
'brainPanel.notReady': 'Bisa dipilih setelah masuk Brain',
|
||||
'brainPanel.notReady': 'Bisa dipilih setelah masuk Otak',
|
||||
'ins.sourcesChosen': 'Sumber: {n} materi dipilih',
|
||||
'ins.sourcesAll': 'Sumber: seluruh Brain',
|
||||
'ins.tooFewChosen': ' Jadwal konten (ringkasan, kuis, dan sejenisnya) butuh minimal {n} materi. Pilih satu lagi di panel Brain.',
|
||||
'ins.tooFewInBrain': ' Jadwal konten (ringkasan, kuis, dan sejenisnya) butuh minimal {n} materi siap di Brain. Unggah satu lagi dulu.',
|
||||
'ins.sourcesAll': 'Sumber: seluruh Otak',
|
||||
'ins.tooFewChosen': ' Jadwal konten (ringkasan, kuis, dan sejenisnya) butuh minimal {n} materi. Pilih satu lagi di panel Otak.',
|
||||
'ins.tooFewInBrain': ' Jadwal konten (ringkasan, kuis, dan sejenisnya) butuh minimal {n} materi siap di Otak. Unggah satu lagi dulu.',
|
||||
'sch.tooFewSources': 'Jadwal ini punya kurang dari {n} materi siap, padahal konten direncanakan dari pasangan materi. Hapus lalu buat ulang dengan {n} materi atau lebih.',
|
||||
'brainPanel.upload': 'Upload materi',
|
||||
'brainPanel.upload': 'Unggah materi',
|
||||
|
||||
// Panduan
|
||||
'help.boxTitle': 'Cara kerja Express',
|
||||
'help.boxBody': 'Empat langkah dari materi sampai konten jadi.',
|
||||
'help.open': 'Lihat panduan',
|
||||
'help.title': 'Cara kerja Learning Lab Express',
|
||||
'help.subtitle': 'Upload materi → Brain and AI → Jadwal → Hasil',
|
||||
'help.subtitle': 'Upload materi → Instruksi → Jadwal → Hasil',
|
||||
'help.brainTitle': 'Upload materi',
|
||||
'help.brainBody': 'Unggah materi pelatihan. Setelah pengetahuannya dibangun, AI membuat semua konten dari situ.',
|
||||
'help.instructionTitle': 'Brain and AI',
|
||||
'help.brainBody': 'Unggah materi pelatihan. Setelah pengetahuannya dibangun, Agent membuat semua konten dari situ.',
|
||||
'help.instructionTitle': 'Instruksi',
|
||||
'help.instructionBody': 'Tulis kebutuhan Anda dalam satu kalimat, misalnya “3 kuis per minggu dan 1 video per minggu soal leadership”. Periksa jadwalnya, lalu setujui.',
|
||||
'help.scheduleTitle': 'Jadwal',
|
||||
'help.scheduleBody': 'Jadwal berjalan sendiri. Jeda, ganti topik, atau produksi sekarang; masing-masing tetap dalam batas kreditnya.',
|
||||
'help.resultsTitle': 'Hasil',
|
||||
'help.resultsBody': 'Tinjau hasilnya, setujui atau tolak, lalu unduh: PDF, Markdown, PowerPoint, MP4, naskah audio, atau SCORM untuk LMS.',
|
||||
'help.note': 'Konten dibuat AI: selalu tinjau sebelum dipakai. Kredit diambil dari ruang kerja organisasi Anda.',
|
||||
'help.resultsBody': 'Tinjau hasilnya, setujui atau tolak, lalu unduh: PDF, Markdown, PowerPoint, MP4, naskah audio, atau INTERACTIVE untuk LMS.',
|
||||
'help.note': 'Konten dibuat Agent: selalu tinjau sebelum dipakai. Kredit diambil dari ruang kerja organisasi Anda.',
|
||||
'help.done': 'Mengerti',
|
||||
|
||||
'err.unreachable': 'Engine learning-lab tidak dapat dihubungi.',
|
||||
'err.generic': 'Permintaan ke engine gagal.',
|
||||
'err.busy': 'Engine sedang sibuk. Coba lagi sebentar lagi.',
|
||||
'err.crashTitle': 'Halaman ini tidak dapat ditampilkan',
|
||||
'err.crashCopy': 'Terjadi kesalahan saat menampilkan halaman ini. Coba lagi, atau muat ulang.',
|
||||
'err.reload': 'Muat ulang',
|
||||
'err.credits': 'Kredit tidak cukup: butuh {required}, saldo {balance}.',
|
||||
'err.creditsShort': 'Kredit tidak cukup.',
|
||||
'err.docFailed': 'Dokumen gagal diproses.',
|
||||
|
||||
28
src/main.tsx
28
src/main.tsx
@@ -3,9 +3,11 @@ import { createRoot } from 'react-dom/client'
|
||||
import { ClerkProvider } from '@clerk/react'
|
||||
import { enUS, idID } from '@clerk/localizations'
|
||||
import { MutationCache, QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { BrowserRouter, useLocation } from 'react-router-dom'
|
||||
import { EngineError } from './api/client'
|
||||
import App from './App'
|
||||
import { ErrorBoundary } from './components/ErrorBoundary'
|
||||
import { forgetReads } from './express/results'
|
||||
import { useLang } from './i18n'
|
||||
import './styles/mockup.css'
|
||||
import './styles/app.css'
|
||||
@@ -17,11 +19,20 @@ if (!clerkPubKey) {
|
||||
}
|
||||
|
||||
const queryClient: QueryClient = new QueryClient({
|
||||
// Any action may have spent workspace credits, so the topbar balance is read again after each one.
|
||||
mutationCache: new MutationCache({ onSettled: () => queryClient.invalidateQueries({ queryKey: ['credits'] }) }),
|
||||
mutationCache: new MutationCache({
|
||||
// Runs before the action's own onSuccess, whose invalidations must not get a remembered read.
|
||||
onSuccess: forgetReads,
|
||||
// Any action may have spent workspace credits, so the topbar balance is read again after each one.
|
||||
onSettled: () => queryClient.invalidateQueries({ queryKey: ['credits'] }),
|
||||
}),
|
||||
defaultOptions: {
|
||||
// Retrying a 4xx (auth, credits, validation) only repeats the same answer.
|
||||
queries: { retry: (n, e) => n < 2 && !(e instanceof EngineError && e.status >= 400 && e.status < 500) },
|
||||
queries: {
|
||||
retry: (n, e) => n < 2 && !(e instanceof EngineError && e.status >= 400 && e.status < 500 && e.status !== 429),
|
||||
// A busy engine (rate limited) is asked again only after it has had time to recover; an
|
||||
// immediate retry from every query at once is what keeps it over the limit.
|
||||
retryDelay: (n, e) => (e instanceof EngineError && (e.status === 503 || e.status === 429) ? 5000 : 1000) * 2 ** n,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -30,6 +41,13 @@ const clerkAppearance = {
|
||||
variables: { colorPrimary: '#1570ef', colorText: '#101828', fontFamily: "'Plus Jakarta Sans', system-ui, sans-serif", borderRadius: '12px' },
|
||||
}
|
||||
|
||||
// A crash outside a page (the layout, the sign-in gate) would otherwise unmount everything and leave
|
||||
// a white page until a reload; moving to another page tries again.
|
||||
function AppBoundary() {
|
||||
const { pathname } = useLocation()
|
||||
return <ErrorBoundary resetKey={pathname} className="card app-crash"><App /></ErrorBoundary>
|
||||
}
|
||||
|
||||
// Clerk's own sign-in and organization screens follow the app language.
|
||||
function Root() {
|
||||
const lang = useLang()
|
||||
@@ -37,7 +55,7 @@ function Root() {
|
||||
<ClerkProvider publishableKey={clerkPubKey} afterSignOutUrl="/" localization={lang === 'id' ? idID : enUS} appearance={clerkAppearance}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
<AppBoundary />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</ClerkProvider>
|
||||
|
||||
100
src/pages/Billing.tsx
Normal file
100
src/pages/Billing.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { locale, t, useLang } from '../i18n'
|
||||
import { workspaceCredits } from '../api/engine'
|
||||
import { entryTime, lastDays, ledgerSince, moduleOf, usageCsv, usageInPeriod } from '../express/billing'
|
||||
import { download } from '../express/results'
|
||||
import { Icon } from '../components/Icon'
|
||||
import { Empty, PageHead, Skeleton, SkeletonRows } from '../components/Page'
|
||||
|
||||
const PAGE = 100
|
||||
|
||||
// The engine limits the ledger to organization admins, whatever this page shows.
|
||||
export function BillingPage() {
|
||||
useLang()
|
||||
const [{ from, to }, setPeriod] = useState(() => lastDays(30))
|
||||
const [shown, setShown] = useState(PAGE)
|
||||
// A date input can be cleared, and a start after the end would be an empty period: keep the pair valid.
|
||||
const pick = (from: string, to: string) => { setPeriod({ from, to }); setShown(PAGE) }
|
||||
|
||||
const ledger = useQuery({ queryKey: ['billing', from], queryFn: () => ledgerSince(from) })
|
||||
const balance = useQuery({ queryKey: ['credits'], queryFn: workspaceCredits })
|
||||
const usage = ledger.data && usageInPeriod(ledger.data, from, to)
|
||||
|
||||
const number = (n: number) => n.toLocaleString(locale())
|
||||
const date = (iso: string) => new Intl.DateTimeFormat(locale(), { dateStyle: 'medium', timeStyle: 'short' }).format(entryTime(iso))
|
||||
const day = (key: string) => new Intl.DateTimeFormat(locale(), { dateStyle: 'medium' }).format(new Date(`${key}T00:00:00`))
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHead title={t('billing.title')} description={t('billing.description')} />
|
||||
<div className="metrics">
|
||||
<div className="metric">
|
||||
<span>{t('billing.total')}</span>
|
||||
<strong>{usage ? number(usage.total) : <Skeleton w={90} h={34} />}</strong>
|
||||
<small>{t('billing.period', { from: day(from), to: day(to) })}</small>
|
||||
</div>
|
||||
<div className="metric">
|
||||
<span>{t('billing.balance')}</span>
|
||||
<strong>{balance.data != null ? number(balance.data) : <Skeleton w={90} h={34} />}</strong>
|
||||
<small>{t('billing.balanceSub')}</small>
|
||||
</div>
|
||||
</div>
|
||||
<section className="card">
|
||||
<div className="toolbar billing-toolbar">
|
||||
<h3>{t('billing.usage')} {usage && <span className="badge neutral">{t(usage.rows.length === 1 ? 'billing.countOne' : 'billing.count', { n: number(usage.rows.length) })}</span>}</h3>
|
||||
<div className="toolbar-controls billing-controls">
|
||||
<label className="billing-date">{t('billing.from')}
|
||||
<input type="date" value={from} max={to} onChange={e => e.target.value && pick(e.target.value, e.target.value > to ? e.target.value : to)} />
|
||||
</label>
|
||||
<label className="billing-date">{t('billing.to')}
|
||||
<input type="date" value={to} min={from} onChange={e => e.target.value && pick(e.target.value < from ? e.target.value : from, e.target.value)} />
|
||||
</label>
|
||||
<button className="btn" disabled={!usage?.rows.length}
|
||||
onClick={() => usage && download(`credit-usage-${from}-to-${to}.csv`, new Blob([usageCsv(usage.rows)], { type: 'text/csv;charset=utf-8' }))}>
|
||||
<Icon name="download" />{t('billing.export')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{ledger.isPending && <SkeletonRows label={t('billing.loading')} />}
|
||||
{ledger.isError && <Empty icon="info" title={t('billing.loadFailed')}>{ledger.error.message}</Empty>}
|
||||
{usage && usage.rows.length === 0 && <Empty icon="coin" title={t('billing.empty')}>{t('billing.emptyCopy')}</Empty>}
|
||||
{usage && usage.rows.length > 0 && (
|
||||
<div className="billing-scroll">
|
||||
<table className="billing-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{t('billing.colDate')}</th>
|
||||
<th scope="col">{t('billing.colUser')}</th>
|
||||
<th scope="col">{t('billing.colModule')}</th>
|
||||
<th scope="col" className="num">{t('billing.colCredits')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{usage.rows.slice(0, shown).map(e => {
|
||||
const { module, detail } = moduleOf(e.activity)
|
||||
return (
|
||||
<tr key={e.id}>
|
||||
<td>{date(e.created_at)}</td>
|
||||
<td>{e.actor_name || '-'}</td>
|
||||
<td><b>{module}</b>{detail && <small>{detail}</small>}</td>
|
||||
<td className="num">
|
||||
{number(-e.amount)}
|
||||
{e.kind === 'refund' && <small>{t('billing.refund')}</small>}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{usage && usage.rows.length > shown && (
|
||||
<div className="billing-more"><button className="btn" onClick={() => setShown(s => s + PAGE)}>{t('billing.more')}</button></div>
|
||||
)}
|
||||
<div className="spacer" />
|
||||
<div className="inline-note"><Icon name="info" />{t('billing.note')}</div>
|
||||
</section>
|
||||
</>
|
||||
)
|
||||
}
|
||||
9
src/pages/Brain.test.ts
Normal file
9
src/pages/Brain.test.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { duplicateNames } from './Brain'
|
||||
|
||||
describe('duplicateNames', () => {
|
||||
it('finds files already in the Brain, ignoring case, and repeats within one pick', () => {
|
||||
const dupes = duplicateNames(['Katalog.pdf', 'new.docx', 'new.docx', 'other.pdf'], ['katalog.PDF'])
|
||||
expect([...dupes]).toEqual(['Katalog.pdf', 'new.docx'])
|
||||
})
|
||||
})
|
||||
@@ -28,22 +28,52 @@ const extOf = (name: string) => '.' + (name.split('.').pop() ?? '').toLowerCase(
|
||||
export const useDocuments = () => useQuery({
|
||||
queryKey: ['documents'],
|
||||
queryFn: listDocuments,
|
||||
refetchInterval: q => (q.state.data?.some(d => phaseOf(d) === 'working') ? 3000 : 20_000),
|
||||
refetchInterval: q => (q.state.data?.some(d => phaseOf(d) === 'working') ? 5000 : 20_000),
|
||||
})
|
||||
|
||||
const PHASES: Phase[] = ['ready', 'working', 'answer', 'failed']
|
||||
|
||||
/** Files whose name is already in the Brain (or twice in the same pick), compared without case. */
|
||||
export function duplicateNames(names: string[], existing: string[]): Set<string> {
|
||||
const seen = new Set(existing.map(n => n.toLowerCase()))
|
||||
const dupes = new Set<string>()
|
||||
for (const name of names) {
|
||||
if (seen.has(name.toLowerCase())) dupes.add(name)
|
||||
seen.add(name.toLowerCase())
|
||||
}
|
||||
return dupes
|
||||
}
|
||||
|
||||
export function BrainPage() {
|
||||
const docs = useDocuments()
|
||||
const [query, setQuery] = useState('')
|
||||
const [phase, setPhase] = useState<Phase | 'all'>('all')
|
||||
const needle = query.trim().toLowerCase()
|
||||
const shown = docs.data?.filter(d => (phase === 'all' || phaseOf(d) === phase)
|
||||
&& (!needle || `${d.title} ${d.originalName}`.toLowerCase().includes(needle)))
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHead title={t('brain.title')} description={t('brain.description')} />
|
||||
<UploadBox />
|
||||
<div className="card">
|
||||
<div className="card-head"><h3>{t('brain.listTitle')}</h3><Icon name="brain" /></div>
|
||||
<div className="toolbar">
|
||||
<h3>{t('brain.listTitle')} {docs.data && <span className="badge neutral">{shown?.length}</span>}</h3>
|
||||
<div className="toolbar-controls">
|
||||
<div className="search"><Icon name="search" />
|
||||
<input type="search" aria-label={t('brainPanel.search')} placeholder={t('brainPanel.search')} value={query} onChange={e => setQuery(e.target.value)} />
|
||||
</div>
|
||||
<select aria-label={t('res.filterStatus')} value={phase} onChange={e => setPhase(e.target.value as Phase | 'all')}>
|
||||
<option value="all">{t('brain.allStatuses')} ({docs.data?.length ?? 0})</option>
|
||||
{PHASES.map(p => <option key={p} value={p}>{statusName(p)} ({docs.data?.filter(d => phaseOf(d) === p).length ?? 0})</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{docs.isPending && <SkeletonRows label={t('brain.loading')} />}
|
||||
{docs.isError && <Empty icon="info" title={t('brain.engineDown')}>{docs.error.message}</Empty>}
|
||||
{docs.data?.length === 0 && <Empty icon="upload" title={t('brain.empty')}>{t('brain.emptyCopy')}</Empty>}
|
||||
{!!docs.data?.length && <div className="result-list">{docs.data.map(d => <DocumentRow key={d.docId} doc={d} />)}</div>}
|
||||
{!!docs.data?.length && shown?.length === 0 && <Empty icon="search" title={t('res.noMatch')}>{t('res.noMatchCopy')}</Empty>}
|
||||
{!!shown?.length && <div className="result-list">{shown.map(d => <DocumentRow key={d.docId} doc={d} />)}</div>}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
@@ -137,9 +167,15 @@ function UploadBox() {
|
||||
async function upload(files: File[]) {
|
||||
if (!files.length) return
|
||||
const allowed = exts.data
|
||||
// The same file uploaded again is a second copy in the Brain; it is asked about, not assumed.
|
||||
const existing = queryClient.getQueryData<Source[]>(['documents'])?.map(d => d.originalName) ?? []
|
||||
const dupes = duplicateNames(files.map(f => f.name), existing)
|
||||
const skipDupes = dupes.size > 0 && !confirm(t('brain.duplicateConfirm', { names: [...dupes].join(', ') }))
|
||||
const batch: UploadItem[] = files.map(f => (allowed && !allowed.has(extOf(f.name))
|
||||
? { id: nextUploadId++, name: f.name, state: 'error', message: t('brain.unsupported') }
|
||||
: { id: nextUploadId++, name: f.name, state: 'uploading' }))
|
||||
: skipDupes && dupes.has(f.name)
|
||||
? { id: nextUploadId++, name: f.name, state: 'error', message: t('brain.duplicateSkipped') }
|
||||
: { id: nextUploadId++, name: f.name, state: 'uploading' }))
|
||||
// Appended, so files dropped while an earlier batch is still uploading keep their own rows.
|
||||
setItems(prev => [...prev.filter(it => it.state === 'uploading'), ...batch])
|
||||
// One at a time: each upload enqueues a processing job, and the list refreshes after each.
|
||||
@@ -248,8 +284,11 @@ function OpenButton({ doc }: { doc: Source }) {
|
||||
try {
|
||||
const url = URL.createObjectURL(await documentFile(doc.docId))
|
||||
if (tab) tab.location.href = url
|
||||
// Not viewable, or the tab was blocked: save it instead of doing nothing.
|
||||
else Object.assign(document.createElement('a'), { href: url, download: doc.originalName }).click()
|
||||
// Not viewable, or the tab was blocked: save it instead of doing nothing, and say so.
|
||||
else {
|
||||
Object.assign(document.createElement('a'), { href: url, download: doc.originalName }).click()
|
||||
toast(t('brain.downloaded', { name: doc.originalName }))
|
||||
}
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000)
|
||||
} catch (e) {
|
||||
tab?.close()
|
||||
@@ -265,6 +304,10 @@ function OpenButton({ doc }: { doc: Source }) {
|
||||
)
|
||||
}
|
||||
|
||||
const statusName = (phase: Phase) => ({
|
||||
ready: t('brain.statusReady'), working: t('brain.statusProcessing'), answer: t('brain.statusAnswer'), failed: t('brain.statusFailed'),
|
||||
}[phase])
|
||||
|
||||
function statusLabel(doc: Source, phase: Phase) {
|
||||
return {
|
||||
ready: t('brain.statusReady'),
|
||||
@@ -296,7 +339,8 @@ function Progress({ doc }: { doc: Source }) {
|
||||
// Each stop the engine can make before building, with the one answer it needs.
|
||||
function KnowledgeAction({ doc }: { doc: Source }) {
|
||||
const queryClient = useQueryClient()
|
||||
const detail = useQuery({ queryKey: ['knowledge', doc.docId, doc.knowledge], queryFn: () => knowledgeDetail(doc.docId) })
|
||||
// Keyed by the knowledge status, so it is read again when that changes and reused otherwise.
|
||||
const detail = useQuery({ queryKey: ['knowledge', doc.docId, doc.knowledge], queryFn: () => knowledgeDetail(doc.docId), staleTime: 5 * 60_000 })
|
||||
const refresh = () => queryClient.invalidateQueries({ queryKey: ['documents'] })
|
||||
const build = useMutation({ mutationFn: () => buildKnowledge(doc.docId), onSuccess: refresh })
|
||||
const version = useMutation({ mutationFn: (link: boolean) => answerVersion(doc.docId, link), onSuccess: refresh })
|
||||
|
||||
@@ -36,6 +36,8 @@ export function InstructionPage() {
|
||||
const [agent, setAgent] = useState<AgentState>(EMPTY)
|
||||
const [messages, setMessages] = useState<Message[]>([])
|
||||
const [saving, setSaving] = useState(false)
|
||||
// While schedules are created: which one, and how many Brain documents it has been given so far.
|
||||
const [progress, setProgress] = useState<{ n: number; count: number; done: number; total: number } | null>(null)
|
||||
const docs = useDocuments()
|
||||
const [phase, setPhase] = useState<Phase>('idle')
|
||||
// The live question whose typing has finished, so its reply options can show.
|
||||
@@ -53,6 +55,8 @@ export function InstructionPage() {
|
||||
// The whole Brain is attached, so every ready document counts.
|
||||
const tooFewSources = choosable(docs.data).length < MIN_PRODUCTION_SOURCES && ready.some(i => needsTwoSources(i.rule))
|
||||
const hasContent = agent.items.some(i => i.rule.type === 'content')
|
||||
// A kind or frequency the agent only guessed, or no content language yet: the plan is not finished.
|
||||
const incomplete = ready.some(i => i.rule.type === 'content' && (i.rule.kindGuessed || i.rule.perGuessed)) || (hasContent && !agent.language)
|
||||
// The agent's current turn: its question, or what it is waiting for. It stays live, so an edit in the plan updates it.
|
||||
const live = inLang(lang, () => saving
|
||||
? { text: t('agent.approving'), options: [] as string[] }
|
||||
@@ -101,16 +105,18 @@ export function InstructionPage() {
|
||||
|
||||
async function approve(state = agent, replyLang = lang) {
|
||||
const items = state.items.filter(i => canSchedule(i.rule))
|
||||
if (!items.length || tooFewSources) return
|
||||
const unfinished = items.some(i => i.rule.type === 'content' && (i.rule.kindGuessed || i.rule.perGuessed))
|
||||
if (!items.length || tooFewSources || unfinished) return
|
||||
setSaving(true)
|
||||
const done: Outcome[] = []
|
||||
const created = new Set<number>()
|
||||
// Approving from the plan before the agent asked about the language uses the conversation's language.
|
||||
const language: OutputLanguage = state.language ?? (replyLang === 'id' ? 'Bahasa Indonesia' : 'English')
|
||||
// One at a time so a failure (e.g. not an organization owner) is reported per schedule.
|
||||
for (const { id, rule } of items) {
|
||||
for (const [i, { id, rule }] of items.entries()) {
|
||||
try {
|
||||
await createSchedule(rule.type === 'content' ? { ...rule, language } : rule)
|
||||
await createSchedule(rule.type === 'content' ? { ...rule, language } : rule, undefined,
|
||||
(d, total) => setProgress({ n: i + 1, count: items.length, done: d, total }))
|
||||
done.push({ rule, ok: true })
|
||||
created.add(id)
|
||||
} catch (e) {
|
||||
@@ -118,6 +124,7 @@ export function InstructionPage() {
|
||||
}
|
||||
}
|
||||
setSaving(false)
|
||||
setProgress(null)
|
||||
// A new schedule may start producing right away; the dashboard shows it under content in progress.
|
||||
await Promise.all([queryClient.invalidateQueries({ queryKey: ['schedules'] }), queryClient.invalidateQueries({ queryKey: ['results'] })])
|
||||
const ok = done.filter(o => o.ok).length
|
||||
@@ -148,6 +155,7 @@ export function InstructionPage() {
|
||||
{phase === 'pausing' && <Typing />}
|
||||
{idle && live.text && (
|
||||
<Bubble key={live.text} message={{ role: 'agent', text: live.text, typed: true }} lang={lang} busy={saving}
|
||||
note={saving && progress?.total ? inLang(lang, () => t('agent.attaching', progress)) : undefined}
|
||||
onTyped={() => setTypedLive(live.text)} onType={scroll} />
|
||||
)}
|
||||
</div>
|
||||
@@ -193,8 +201,9 @@ export function InstructionPage() {
|
||||
<b className="rule-sources"><Icon name="brain" />{t('ins.sourcesAll')}</b>
|
||||
{t('ins.approveNote')}
|
||||
{tooFewSources && <span className="error">{t('ins.tooFewInBrain', { n: MIN_PRODUCTION_SOURCES })}</span>}
|
||||
{incomplete && <span className="error">{t('ins.incomplete')}</span>}
|
||||
</small>
|
||||
<button className="btn primary" disabled={saving || !idle || tooFewSources} onClick={() => approve()}>
|
||||
<button className="btn primary" disabled={saving || !idle || tooFewSources || incomplete} onClick={() => approve()}>
|
||||
<Icon name="check" />{saving ? t('ins.approving') : t('ins.approve', { n: ready.length })}
|
||||
</button>
|
||||
</div>
|
||||
@@ -221,8 +230,8 @@ function useTyped(text: string, enabled: boolean, onDone?: () => void, onType?:
|
||||
return text.slice(0, shown)
|
||||
}
|
||||
|
||||
function Bubble({ message, lang, busy, onTyped, onType }: {
|
||||
message: Message; lang: Lang; busy?: boolean; onTyped?: () => void; onType?: () => void
|
||||
function Bubble({ message, lang, busy, note, onTyped, onType }: {
|
||||
message: Message; lang: Lang; busy?: boolean; note?: string; onTyped?: () => void; onType?: () => void
|
||||
}) {
|
||||
const text = useTyped(message.text, !!message.typed, onTyped, onType)
|
||||
const typing = text.length < message.text.length
|
||||
@@ -232,6 +241,7 @@ function Bubble({ message, lang, busy, onTyped, onType }: {
|
||||
<div className="ai-bubble">
|
||||
{message.thought && <small className="ai-thought">{inLang(lang, () => t('agent.thought', { s: message.thought! }))}</small>}
|
||||
<p className={typing ? 'typing' : undefined}>{text}</p>
|
||||
{note && <small className="ai-thought" role="status">{note}</small>}
|
||||
{message.outcomes && !typing && (
|
||||
<ul className="rule-outcomes appear">
|
||||
{message.outcomes.map((o, i) => (
|
||||
@@ -295,12 +305,15 @@ function RuleCard({ rule, from, onChange, onRemove }: {
|
||||
<div className="rule-fields">
|
||||
{rule.type === 'content' ? (
|
||||
<>
|
||||
<select aria-label={t('ins.kind')} value={rule.kind} onChange={e => onChange({ kind: e.target.value as ContentKind })}>
|
||||
{/* A guessed kind or frequency shows as not chosen, as the rule's title says. */}
|
||||
<select aria-label={t('ins.kind')} value={rule.kindGuessed ? '' : rule.kind} onChange={e => onChange({ kind: e.target.value as ContentKind })}>
|
||||
{rule.kindGuessed && <option value="" disabled>{t('ins.kindPending')}</option>}
|
||||
{KINDS.map(k => <option key={k} value={k}>{kindLabel(k)}</option>)}
|
||||
</select>
|
||||
<input aria-label={t('ins.count')} type="number" min={1} max={50} value={rule.count}
|
||||
onChange={e => onChange({ count: Math.max(1, Number(e.target.value) || 1) })} />
|
||||
<select aria-label={t('ins.frequency')} value={rule.per} onChange={e => onChange({ per: e.target.value as ContentRule['per'] })}>
|
||||
<select aria-label={t('ins.frequency')} value={rule.perGuessed ? '' : rule.per} onChange={e => onChange({ per: e.target.value as ContentRule['per'] })}>
|
||||
{rule.perGuessed && <option value="" disabled>{t('ins.perPending')}</option>}
|
||||
<option value="day">{t('ins.perDay')}</option>
|
||||
<option value="week">{t('ins.perWeek')}</option>
|
||||
</select>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Icon } from '../components/Icon'
|
||||
import { PageHead, Skeleton, SkeletonCards } from '../components/Page'
|
||||
import { buildGraph, CLUSTERS, type Cluster, type Graph, type GraphNode } from '../express/graph'
|
||||
import { describeRule } from '../express/parse'
|
||||
import { isWorking, listResults, materialKey, titleOf, type Material } from '../express/results'
|
||||
import { isWorking, listResults, materialKey, RESULTS_POLL, titleOf, type Material } from '../express/results'
|
||||
import { listSchedules } from '../express/schedules'
|
||||
import { locale, t, type Key } from '../i18n'
|
||||
import { ContentCard, Preview } from './Results'
|
||||
@@ -54,8 +54,7 @@ export function ProductionPage() {
|
||||
const results = useQuery({
|
||||
queryKey: ['results'],
|
||||
queryFn: listResults,
|
||||
// Polled more often than on Results so a run that just started shows up under content in progress.
|
||||
refetchInterval: q => (q.state.data?.materials.some(isWorking) ? 10_000 : 20_000),
|
||||
...RESULTS_POLL,
|
||||
})
|
||||
const schedules = useQuery({ queryKey: ['schedules'], queryFn: listSchedules, refetchInterval: 30_000 })
|
||||
|
||||
@@ -81,7 +80,7 @@ export function ProductionPage() {
|
||||
title={<>{name ? t('prod.welcomeName', { name }) : t('prod.welcome')} <span className="welcome-spark">✦</span></>}
|
||||
actions={<>
|
||||
<Link className="btn" to="/upload"><Icon name="upload" />{t('nav.brain')}</Link>
|
||||
<Link className="btn primary" to="/brain"><Icon name="spark" />{t('prod.newContent')}</Link>
|
||||
<Link className="btn primary" to="/instruction"><Icon name="spark" />{t('prod.newContent')}</Link>
|
||||
</>} />
|
||||
<section ref={fullscreen.ref} className={`graph-stage${fullscreen.full ? ' full' : ''}${fullscreen.pinned ? ' pinned' : ''}`} aria-label={t('prod.graphTitle')}>
|
||||
<button type="button" className="graph-fullscreen" onClick={fullscreen.toggle} aria-pressed={fullscreen.full}
|
||||
@@ -99,7 +98,7 @@ export function ProductionPage() {
|
||||
<div><small>{t('prod.links')}</small>{graph ? <b>{graph.links.filter(l => !l.hub).length}</b> : <b>-</b>}<span>{t('prod.linksSub')}</span></div>
|
||||
</div>
|
||||
<h3>{t('prod.scheduleTitle')}</h3>
|
||||
{schedules.data?.length === 0 && <p className="graph-empty">{t('prod.noSchedules')} <Link to="/brain">{t('prod.giveInstruction')}</Link></p>}
|
||||
{schedules.data?.length === 0 && <p className="graph-empty">{t('prod.noSchedules')} <Link to="/instruction">{t('prod.giveInstruction')}</Link></p>}
|
||||
<ul className="graph-list">
|
||||
{schedules.data?.slice(0, 4).map(s => (
|
||||
<li key={s.agent.id}>
|
||||
@@ -126,7 +125,8 @@ export function ProductionPage() {
|
||||
|
||||
<div className="metrics prod-metrics">
|
||||
<div className="metric"><span>{t('prod.metricMaterial')}</span>{num(docs.data?.length ?? 0, !!docs.data, docs.data?.length === 1 ? 'prod.unitMaterialOne' : 'prod.unitMaterial')}<small>{t('prod.metricMaterialSub')}</small></div>
|
||||
<div className="metric"><span>{t('prod.metricMade')}</span>{num(materials.filter(m => m.status !== 'failed').length, !!results.data, 'prod.unitContent')}<small>{t('prod.metricMadeSub')}</small></div>
|
||||
{/* Counted as Results counts "Done" (?status=done), so the two pages show the same number. */}
|
||||
<div className="metric"><span>{t('prod.metricMade')}</span>{num(made.length, !!results.data, 'prod.unitContent')}<small>{t('prod.metricMadeSub')}</small></div>
|
||||
<div className="metric"><span>{t('prod.metricLms')}</span>{num(lms.length, !!results.data, 'prod.unitContent')}<small>{t('prod.metricLmsSub')}</small></div>
|
||||
</div>
|
||||
|
||||
@@ -149,7 +149,7 @@ function ContentActivity({ made, working, loading }: { made: Material[]; working
|
||||
<section className="prod-activity">
|
||||
<div className="section-heading">
|
||||
<div><h3>{t('prod.activityTitle')}</h3><p>{t('prod.activityDescription')}</p></div>
|
||||
<Link className="text-btn" to="/results">{t('prod.activityAll')}<Icon name="arrow-right" /></Link>
|
||||
<Link className="text-btn" to={`/results?status=${tab === 'latest' ? 'done' : 'working'}`}>{t('prod.activityAll')}<Icon name="arrow-right" /></Link>
|
||||
</div>
|
||||
<div className="result-tabs" role="tablist">
|
||||
<button role="tab" aria-selected={tab === 'latest'} className={tab === 'latest' ? 'active' : undefined} onClick={() => setTab('latest')}>
|
||||
@@ -176,6 +176,7 @@ function ContentActivity({ made, working, loading }: { made: Material[]; working
|
||||
// frame, so hovering or selecting (React state) never fights the animation.
|
||||
const DRIFT = 5
|
||||
const MAX_PARTICLES = 80
|
||||
const NAMED_NEIGHBOURS = 12
|
||||
const ease = (x: number) => 1 - Math.pow(1 - Math.min(1, Math.max(0, x)), 3)
|
||||
|
||||
function curve(ax: number, ay: number, bx: number, by: number, bend: number) {
|
||||
@@ -259,6 +260,9 @@ function KnowledgeGraph({ graph }: { graph: Graph }) {
|
||||
}
|
||||
return set
|
||||
}, [focus, graph])
|
||||
// Linked nodes are named only when there are few: a hub links to every document or result, and
|
||||
// naming them all at once piles hundreds of labels on top of each other.
|
||||
const nameNear = !!neighbours && !graph.nodes[index.get(focus!)!]?.hub && neighbours.size <= NAMED_NEIGHBOURS + 1
|
||||
const lit = (p: { a: number; b: number }) => neighbours?.has(graph.nodes[p.a].id) && neighbours.has(graph.nodes[p.b].id)
|
||||
|
||||
return (
|
||||
@@ -298,7 +302,7 @@ function KnowledgeGraph({ graph }: { graph: Graph }) {
|
||||
const r = n.hub ? 9 : 3.2 + Math.min(3, (degree.get(n.id) ?? 0) * 0.7)
|
||||
return (
|
||||
<g key={n.id} ref={el => { nodeEls.current[i] = el }}
|
||||
className={`graph-node c-${n.cluster}${n.hub ? ' hub' : ''}${neighbours && !neighbours.has(n.id) ? ' dim' : ''}${hover === n.id ? ' hover' : ''}${selected?.id === n.id ? ' sel' : ''}`}
|
||||
className={`graph-node c-${n.cluster}${n.hub ? ' hub' : ''}${neighbours && !neighbours.has(n.id) ? ' dim' : ''}${nameNear && n.id !== focus && neighbours?.has(n.id) ? ' near' : ''}${hover === n.id ? ' hover' : ''}${selected?.id === n.id ? ' sel' : ''}`}
|
||||
onMouseEnter={() => setHover(n.id)} onMouseLeave={() => setHover(null)}
|
||||
onClick={e => { e.stopPropagation(); setSelected(n) }}>
|
||||
<circle className="hit" r={r + 8} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Link, useSearchParams } from 'react-router-dom'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { AudioPlayer } from '../components/AudioPlayer'
|
||||
import { Icon, KIND_ICON, type IconName } from '../components/Icon'
|
||||
@@ -8,7 +8,7 @@ import { Empty, PageHead, SkeletonCards, SkeletonLines, SkeletonRows } from '../
|
||||
import { toast } from '../components/Toast'
|
||||
import { describeRule, kindLabel, type ContentKind } from '../express/parse'
|
||||
import {
|
||||
decideMaterial, download, exportPptx, fileName, isWorking, printPdf, listOf, listResults, materialContent, materialKey, questionsOf, retryMaterial, reviewSource, slidesOf, textOf,
|
||||
canCancelVideo, cancelVideo, decideMaterial, download, exportPptx, fileName, isWorking, printPdf, listOf, listResults, materialContent, RESULTS_POLL, materialKey, questionsOf, retryMaterial, reviewSource, slidesOf, textOf, withDecisions,
|
||||
titleOf, toMarkdown, type FoundSource, type Material, type MaterialContent, type MaterialStatus,
|
||||
} from '../express/results'
|
||||
import { MASTERY, scormPackage } from '../express/scorm'
|
||||
@@ -19,10 +19,15 @@ const STUDIO_URL: string = import.meta.env.VITE_STUDIO_URL
|
||||
// Setup fields of roleplay and simulator content, in display order.
|
||||
const FIELDS = ['description', 'topic', 'objective', 'learning_objectives', 'user_role', 'ai_character', 'difficulty', 'context'] as const
|
||||
|
||||
type StatusFilter = 'all' | 'review' | 'approved' | 'working' | 'failed'
|
||||
const STATUS_GROUP: Record<MaterialStatus, StatusFilter> = {
|
||||
// 'done' is everything no longer being made except failures, as the Production page counts it; the
|
||||
// Production page links here with ?status=done or ?status=working.
|
||||
const STATUS_FILTERS = ['all', 'done', 'review', 'approved', 'working', 'failed'] as const
|
||||
type StatusFilter = typeof STATUS_FILTERS[number]
|
||||
const STATUS_GROUP: Record<MaterialStatus, Exclude<StatusFilter, 'all' | 'done'>> = {
|
||||
preparing: 'working', generating: 'working', ready: 'review', accepted: 'approved', failed: 'failed', rejected: 'failed',
|
||||
}
|
||||
const matchesStatus = (m: Material, status: StatusFilter) =>
|
||||
status === 'all' || (status === 'done' ? !isWorking(m) && m.status !== 'failed' : STATUS_GROUP[m.status] === status)
|
||||
|
||||
const fmt = (iso: string) => new Intl.DateTimeFormat(locale(), { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(iso))
|
||||
|
||||
@@ -30,20 +35,23 @@ export function ResultsPage() {
|
||||
const results = useQuery({
|
||||
queryKey: ['results'],
|
||||
queryFn: listResults,
|
||||
refetchInterval: q => (q.state.data?.materials.some(isWorking) ? 10_000 : 60_000),
|
||||
...RESULTS_POLL,
|
||||
})
|
||||
const [tab, setTab] = useState<'content' | 'research'>('content')
|
||||
const [query, setQuery] = useState('')
|
||||
const [kind, setKind] = useState<ContentKind | 'all'>('all')
|
||||
const [status, setStatus] = useState<StatusFilter>('all')
|
||||
const [params] = useSearchParams()
|
||||
const [status, setStatus] = useState<StatusFilter>(() => STATUS_FILTERS.find(s => s === params.get('status')) ?? 'all')
|
||||
const [openId, setOpenId] = useState<string | null>(null)
|
||||
|
||||
const materials = results.data?.materials ?? []
|
||||
const sources = results.data?.sources ?? []
|
||||
const kinds = useMemo(() => [...new Set(materials.map(m => m.kind))], [materials])
|
||||
const needle = query.trim().toLowerCase()
|
||||
const shownMaterials = materials.filter(m => (kind === 'all' || m.kind === kind) && (status === 'all' || STATUS_GROUP[m.status] === status)
|
||||
&& (!needle || titleOf(m).toLowerCase().includes(needle)))
|
||||
const searched = materials.filter(m => (kind === 'all' || m.kind === kind) && (!needle || titleOf(m).toLowerCase().includes(needle)))
|
||||
const shownMaterials = searched.filter(m => matchesStatus(m, status))
|
||||
// Each status says how many it holds, so the tab's total and the dashboard's counts add up here.
|
||||
const statusCount = (s: StatusFilter) => searched.filter(m => matchesStatus(m, s)).length
|
||||
const shownSources = sources.filter(s => !needle || s.title.toLowerCase().includes(needle) || s.url?.toLowerCase().includes(needle))
|
||||
const open = materials.find(m => materialKey(m) === openId) ?? null
|
||||
const pending = sources.filter(s => s.status === 'pending').length
|
||||
@@ -73,7 +81,7 @@ export function ResultsPage() {
|
||||
{kinds.map(k => <option key={k} value={k}>{kindLabel(k)}</option>)}
|
||||
</select>
|
||||
<select aria-label={t('res.filterStatus')} value={status} onChange={e => setStatus(e.target.value as StatusFilter)}>
|
||||
{(['all', 'review', 'approved', 'working', 'failed'] as const).map(s => <option key={s} value={s}>{t(`res.status.${s}` as Key)}</option>)}
|
||||
{STATUS_FILTERS.map(s => <option key={s} value={s}>{t(`res.status.${s}` as Key)} ({statusCount(s)})</option>)}
|
||||
</select>
|
||||
</>
|
||||
)}
|
||||
@@ -105,7 +113,7 @@ function NoResults({ filtered, icon }: { filtered: boolean; icon: IconName }) {
|
||||
<span className="empty-icon"><Icon name={icon} /></span>
|
||||
<h3>{t('res.empty')}</h3>
|
||||
<p>{t('res.emptyCopy')}</p>
|
||||
<Link className="btn light" to="/brain"><Icon name="plus" />{t('sch.newInstruction')}</Link>
|
||||
<Link className="btn light" to="/instruction"><Icon name="plus" />{t('sch.newInstruction')}</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -126,12 +134,14 @@ export function ContentCard({ material: m, onOpen }: { material: Material; onOpe
|
||||
</div>
|
||||
<div className="content-card-body">
|
||||
<div className="content-card-top"><span className="type-badge"><Icon name={KIND_ICON[m.kind]} />{kindLabel(m.kind)}</span><StatusBadge status={m.status} /></div>
|
||||
<button className="content-title" disabled={working} onClick={onOpen}>{titleOf(m)}</button>
|
||||
{/* A video opens while it is made too: its progress and Cancel are there. */}
|
||||
<button className="content-title" disabled={working && !m.video} onClick={onOpen}>{titleOf(m)}</button>
|
||||
<p>{t(m.sources.length === 1 ? 'res.sourceOne' : 'res.sourceCount', { n: m.sources.length })} · {fmt(m.createdAt)}</p>
|
||||
<div className="content-card-foot">
|
||||
<span title={describeRule(m.rule)}>{describeRule(m.rule)}</span>
|
||||
{working
|
||||
? <span>{m.video ? t('res.videoProgress', { n: m.video.progress }) : t('res.working')}</span>
|
||||
: m.video?.stuck ? <span className="error">{t('res.videoStuckShort')}</span>
|
||||
: m.retry && <div className="content-card-actions"><RetryButton material={m} className="text-btn" /></div>}
|
||||
</div>
|
||||
</div>
|
||||
@@ -139,6 +149,24 @@ export function ContentCard({ material: m, onOpen }: { material: Material; onOpe
|
||||
)
|
||||
}
|
||||
|
||||
function CancelButton({ material: m, className }: { material: Material; className: string }) {
|
||||
const queryClient = useQueryClient()
|
||||
const cancel = useMutation({
|
||||
mutationFn: () => cancelVideo(m),
|
||||
onSuccess: () => {
|
||||
toast(t('res.videoCancelled'))
|
||||
queryClient.invalidateQueries({ queryKey: ['results'] })
|
||||
},
|
||||
onError: e => toast(e.message, { error: true }),
|
||||
})
|
||||
return (
|
||||
<button className={className} disabled={cancel.isPending}
|
||||
onClick={() => confirm(t('res.cancelVideoConfirm')) && cancel.mutate()}>
|
||||
{cancel.isPending ? t('res.cancellingVideo') : t('res.cancelVideo')}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// A failed plan item is produced again with a fresh quote; the result then shows as preparing.
|
||||
function RetryButton({ material: m, className }: { material: Material; className: string }) {
|
||||
const queryClient = useQueryClient()
|
||||
@@ -166,6 +194,9 @@ export function Preview({ material: m, onClose }: { material: Material; onClose:
|
||||
mutationFn: (decision: 'accept' | 'reject') => decideMaterial(m, decision),
|
||||
onSuccess: (_, decision) => {
|
||||
toast(t(decision === 'accept' ? 'res.accepted' : 'res.rejected'))
|
||||
// Shown at once; reading every schedule again takes a while, longer on a busy engine.
|
||||
queryClient.setQueryData<Awaited<ReturnType<typeof listResults>>>(['results'], old =>
|
||||
old && { ...old, materials: old.materials.map(withDecisions) })
|
||||
queryClient.invalidateQueries({ queryKey: ['results'] })
|
||||
},
|
||||
})
|
||||
@@ -208,6 +239,7 @@ export function Preview({ material: m, onClose }: { material: Material; onClose:
|
||||
<div className="modal-foot">
|
||||
{decide.error ? <small className="error">{decide.error.message}</small> : <small>{t('res.footNote')}</small>}
|
||||
{m.composeSetId && <a className="btn" href={`${STUDIO_URL}/compose/${m.composeSetId}`} target="_blank" rel="noreferrer">{t('res.openStudio')}</a>}
|
||||
{canCancelVideo(m) && <CancelButton material={m} className="btn danger" />}
|
||||
{m.retry && <RetryButton material={m} className="btn primary" />}
|
||||
{content.data?.content && <DownloadMenu material={m} content={content.data.content} outputId={content.data.outputId} />}
|
||||
{m.status === 'ready' && (
|
||||
@@ -263,7 +295,7 @@ function DownloadMenu({ material: m, content, outputId }: { material: Material;
|
||||
|
||||
const scormItem = (
|
||||
<button role="menuitem" onClick={() => { close(); scorm(m, content) }}>
|
||||
<b>SCORM 1.2 (.zip)</b><small>{t(m.kind === 'scorm' || m.kind === 'quiz' ? 'res.scormQuizHint' : 'res.scormHint')}</small>
|
||||
<b>INTERACTIVE (.zip)</b><small>{t(m.kind === 'scorm' || m.kind === 'quiz' ? 'res.scormQuizHint' : 'res.scormHint')}</small>
|
||||
</button>
|
||||
)
|
||||
|
||||
@@ -343,6 +375,7 @@ function Body({ material: m, content }: { material: Material; content: MaterialC
|
||||
const title = textOf(content.title) || titleOf(m)
|
||||
if (m.kind === 'video') {
|
||||
if (m.video?.url) return <article className="prose"><h1>{title}</h1><video className="source-player" controls preload="metadata" src={m.video.url} /></article>
|
||||
if (m.video?.stuck) return <Empty icon="video" title={t('res.videoStuck')}>{t('res.videoStuckCopy')}</Empty>
|
||||
if (m.status === 'failed') return <Empty icon="video" title={t('res.videoFailed')}>{t('res.videoFailedCopy')}</Empty>
|
||||
return <Empty icon="video" title={t('res.videoNotReady')}>{t('res.videoProgress', { n: m.video?.progress ?? 0 })}</Empty>
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import { toast } from '../components/Toast'
|
||||
import { describeRule } from '../express/parse'
|
||||
import { locale, t, type Key } from '../i18n'
|
||||
import {
|
||||
archiveSchedule, confirmProduction, isMine, isRunSchedule, knowledgeReadiness, listRuns, listSchedules, scheduleOwners, pauseSchedule, PLAN_ACTIVE, productionStatus, quoteProduction, resumeSchedule,
|
||||
planProgress, productionError, runNow as startRun, updateTopic, type ContentPlan, type Owners, type RunSummary, type Schedule,
|
||||
archiveSchedule, confirmProduction, forgetProductionReads, isMine, isRunSchedule, knowledgeReadiness, listRuns, listSchedules, scheduleOwners, pauseSchedule, PLAN_ACTIVE, productionStatus, quoteProduction, resumeSchedule,
|
||||
planProgress, productionError, runNow as startRun, updateTopic, type ContentPlan, type Owners, type ProductionStatus, type RunSummary, type Schedule,
|
||||
} from '../express/schedules'
|
||||
|
||||
const STUDIO_URL: string = import.meta.env.VITE_STUDIO_URL
|
||||
@@ -22,7 +22,8 @@ const runStatus = (s: string) => (RUN_STATUSES.has(s) ? t(`run.${s}` as Key) : s
|
||||
const RUN_ERRORS = new Set([
|
||||
'knowledge_not_ready', 'video_sources_unavailable', 'material_sources_unavailable', 'knowledge_search_failed',
|
||||
'organization_wallet', 'run_cap', 'monthly_cap', 'reservation_cap', 'price_changed', 'video_price_changed',
|
||||
'agent_not_active', 'run_access_revoked', 'required_tool_unavailable',
|
||||
'agent_not_active', 'run_access_revoked', 'required_tool_unavailable', 'user_cancelled',
|
||||
'video_script_outcome_unknown', 'video_storyboard_outcome_unknown', 'video_style_outcome_unknown', 'video_clip_outcome_unknown',
|
||||
])
|
||||
const ISSUE_REASONS = new Set([
|
||||
'document_processing', 'document_failed', 'graph_building', 'graph_not_ready', 'legacy_set_needs_conversion',
|
||||
@@ -58,7 +59,7 @@ export function SchedulePage() {
|
||||
return (
|
||||
<>
|
||||
<PageHead title={t('sch.title')} description={t('sch.description')}
|
||||
actions={<Link className="btn primary" to="/brain"><Icon name="plus" />{t('sch.newInstruction')}</Link>} />
|
||||
actions={<Link className="btn primary" to="/instruction"><Icon name="plus" />{t('sch.newInstruction')}</Link>} />
|
||||
{mixed && (
|
||||
<div className="result-tabs" role="tablist">
|
||||
<button role="tab" aria-selected={scope === 'mine'} className={scope === 'mine' ? 'active' : undefined} onClick={() => choose('mine')}>
|
||||
@@ -151,12 +152,21 @@ function ScheduleRow({ schedule, owners }: { schedule: Schedule; owners?: Owners
|
||||
)
|
||||
}
|
||||
|
||||
// Content schedules report this week's progress from the engine's production period.
|
||||
const useProduction = (agentId: number) => useQuery({
|
||||
queryKey: ['production', agentId],
|
||||
queryFn: () => productionStatus(agentId),
|
||||
refetchInterval: q => (q.state.data?.plans.some(p => PLAN_ACTIVE.has(p.status)) ? 5000 : 60_000),
|
||||
})
|
||||
// Content schedules report this week's progress from the engine's production period. Each row
|
||||
// asks for its own, so it is read once a minute; while its latest production is under way it is
|
||||
// read every few seconds, so each step shows as it happens. Starting a production refreshes it at once.
|
||||
const LIVE_POLL = 5000
|
||||
const isLive = (s: ProductionStatus | undefined) => !!s?.plans[0] && PLAN_ACTIVE.has(s.plans[0].status)
|
||||
function useProduction(agentId: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const key = ['production', agentId]
|
||||
return useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () => productionStatus(agentId, isLive(queryClient.getQueryData<ProductionStatus>(key)) ? LIVE_POLL : undefined),
|
||||
refetchInterval: q => (isLive(q.state.data) ? LIVE_POLL : 60_000),
|
||||
staleTime: q => (isLive(q.state.data) ? LIVE_POLL : 60_000),
|
||||
})
|
||||
}
|
||||
|
||||
function ProductionLine({ agentId, active }: { agentId: number; active: boolean }) {
|
||||
const status = useProduction(agentId)
|
||||
@@ -216,6 +226,8 @@ function ProducePanel({ schedule: { agent, rule }, onClose }: { schedule: Schedu
|
||||
const start = useMutation({
|
||||
mutationFn: (plan: ContentPlan) => confirmProduction(agent.id, plan),
|
||||
onSuccess: () => {
|
||||
// The read kept from before the start still shows no production; it must not answer the refresh.
|
||||
forgetProductionReads()
|
||||
queryClient.invalidateQueries({ queryKey: ['production', agent.id] })
|
||||
queryClient.invalidateQueries({ queryKey: ['results'] })
|
||||
onClose()
|
||||
@@ -253,7 +265,7 @@ function RunHistory({ agentId }: { agentId: number }) {
|
||||
const runs = useQuery({
|
||||
queryKey: ['runs', agentId],
|
||||
queryFn: () => listRuns(agentId),
|
||||
refetchInterval: q => (q.state.data?.some(r => ['queued', 'planning', 'running'].includes(r.status)) ? 3000 : false),
|
||||
refetchInterval: q => (q.state.data?.some(r => ['queued', 'planning', 'running'].includes(r.status)) ? 5000 : false),
|
||||
})
|
||||
if (runs.isPending) return <div className="run-history"><SkeletonLines count={3} label={t('sch.loadingHistory')} /></div>
|
||||
if (runs.isError) return <div className="run-history"><span className="error">{runs.error.message}</span></div>
|
||||
|
||||
@@ -209,3 +209,20 @@ textarea{resize:vertical;line-height:1.6}
|
||||
.compact-source-row>input:disabled{opacity:.4;cursor:not-allowed}
|
||||
.compact-brain .brain-selection label{font-size:13px}
|
||||
.compact-brain .brain-selection{font-size:12px}
|
||||
.app-crash{max-width:560px;margin:12vh auto;padding-top:8px}
|
||||
|
||||
/* Billing: the credit ledger as a table, which scrolls by itself on a phone. */
|
||||
/* One row wherever it fits: without the shared toolbar's 520px cap, it only wraps when the room runs out. */
|
||||
.billing-toolbar{flex-wrap:wrap}
|
||||
.toolbar .billing-controls{width:auto;max-width:none;margin-left:auto;flex-wrap:wrap;justify-content:flex-end;align-items:center}
|
||||
.billing-date{display:flex;align-items:center;gap:8px;margin:0;white-space:nowrap}
|
||||
.billing-date input:not([type=checkbox]):not([type=radio]):not([type=file]){width:auto;height:40px;min-height:40px;padding-block:0}
|
||||
.billing-controls .btn{height:40px;min-height:40px;margin:0}
|
||||
.billing-scroll{overflow-x:auto}
|
||||
.billing-table{width:100%;min-width:560px;border-collapse:collapse;font-size:13.5px}
|
||||
.billing-table th{text-align:left;font-size:12px;font-weight:650;color:var(--muted);padding:10px 12px;border-bottom:1px solid var(--line)}
|
||||
.billing-table td{padding:12px;border-bottom:1px solid var(--line);vertical-align:top}
|
||||
.billing-table tbody tr:last-child td{border-bottom:0}
|
||||
.billing-table small{display:block;color:var(--muted);font-size:12px;margin-top:2px}
|
||||
.billing-table .num{text-align:right;font-variant-numeric:tabular-nums}
|
||||
.billing-more{display:flex;justify-content:center;padding-top:14px}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -344,6 +344,8 @@ dialog::backdrop{background:rgba(16,24,40,.45);backdrop-filter:blur(4px)}
|
||||
.graph-node text{fill:#fff;font-size:13px;font-weight:700;letter-spacing:.01em;text-anchor:middle;paint-order:stroke;stroke:#08142a;stroke-width:4px;stroke-linejoin:round;pointer-events:none}
|
||||
.graph-node:not(.hub) text{font-size:11.5px;font-weight:600;opacity:0;transform:translateY(4px);transition:opacity .2s,transform .2s}
|
||||
.graph-node:not(.hub):is(.hover,.sel) text{opacity:1;transform:none}
|
||||
/* What the focused node is linked to is named too, a little quieter than the node itself. */
|
||||
.graph-node.near:not(.hub) text{opacity:.85;transform:none;font-size:10.5px;font-weight:500}
|
||||
.c-sources{--c:var(--g-sources)}.c-made{--c:var(--g-made)}
|
||||
|
||||
.graph-note{position:absolute;top:16px;left:16px;z-index:2;display:flex;align-items:center;gap:8px;max-width:min(460px,calc(100% - 340px));
|
||||
@@ -410,7 +412,9 @@ dialog::backdrop{background:rgba(16,24,40,.45);backdrop-filter:blur(4px)}
|
||||
.topbar{justify-content:flex-start}.topbar-right{margin-left:auto}
|
||||
.sidebar-help-icon{align-self:center;margin:auto 0 12px}
|
||||
@media(min-width:701px){
|
||||
.sidebar-collapsed .sidebar{width:76px;padding-left:12px;padding-right:12px}
|
||||
/* The rail lets the space menu spill past its edge, so the glow is clipped to the rail itself */
|
||||
.sidebar-collapsed .sidebar{width:76px;padding-left:12px;padding-right:12px;overflow:visible}
|
||||
.sidebar-collapsed .sidebar::before{clip-path:inset(140px 164px 0 120px)}
|
||||
.sidebar-collapsed .workspace-main{margin-left:76px;width:calc(100% - 76px)}
|
||||
.sidebar-collapsed .sidebar>a>.brand{margin:0 0 24px;justify-content:center}
|
||||
.sidebar-collapsed .sidebar .brand>span:last-child,
|
||||
@@ -426,3 +430,13 @@ dialog::backdrop{background:rgba(16,24,40,.45);backdrop-filter:blur(4px)}
|
||||
}
|
||||
@media(max-width:700px){.sidebar-toggle,.sidebar-help-icon{display:none}}
|
||||
@media(prefers-reduced-motion:reduce){.sidebar,.workspace-main{transition:none}}
|
||||
|
||||
/* Tablet widths: the topbar wraps instead of pushing its pills past the edge, and the page head's
|
||||
buttons go under the title when they no longer fit beside it */
|
||||
@media(min-width:701px) and (max-width:1100px){
|
||||
.topbar{height:auto;min-height:64px;padding-top:10px;padding-bottom:10px;flex-wrap:wrap;row-gap:8px}
|
||||
.topbar-right{flex-wrap:wrap;justify-content:flex-end;gap:8px 10px}
|
||||
.demo-indicator{display:none}
|
||||
.page-head{flex-wrap:wrap}
|
||||
.page-head .head-actions{flex-wrap:wrap}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user