mirror of
https://github.com/THU-MAIC/OpenMAIC.git
synced 2026-10-17 05:29:46 +08:00
@openmaic/generation@0.0.1
144
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
2b3f2eaa37 |
feat(asr): add local FunASR provider (#1044)
Signed-off-by: LauraGPT <199134975+LauraGPT@users.noreply.github.com> Co-authored-by: LauraGPT <199134975+LauraGPT@users.noreply.github.com> |
||
|
|
378579e9df |
fix(slide-renderer): keep arrowheads visible when toggling thumbnails… (#1045)
* fix(slide-renderer): keep arrowheads visible when toggling thumbnails or fullscreen * fix(renderer): bump version to 0.0.5 --------- Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn> |
||
|
|
4f20c5151a |
fix(i18n): translate ASR provider names in the generation toolbar (#1028)
The provider dropdown in the media popover rendered `p.name` straight from
`ASR_PROVIDERS`. That field is a registry label, not a UI string, and
several entries are written in Chinese:
browser-native → 浏览器原生 ASR (Web Speech API)
qwen-asr → Qwen ASR (阿里云百炼)
So a user on any non-Chinese locale saw Chinese in the toolbar, while the
settings dialog showed the same providers correctly — it resolves the name
through `t('settings.providerBrowserNative')` and friends.
The id→i18n-key tables move to `lib/audio/provider-display.ts` and both
surfaces use them, so they cannot drift apart again. The settings dialog
keeps its own handling of custom providers, which carry a user-supplied
name rather than an i18n key.
TTS is included in the shared module for symmetry (`doubao-tts` and
`qwen-tts` have the same problem), though the popover's TTS tab is
currently a toggle with no provider list.
Image and video groups in the same popover also render `p.name`, but those
registry labels are already English, so no user-visible string changes;
left alone to keep this focused.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
||
|
|
6f6b6eca07 |
fix(editor): localize Pro mode right rail labels (#1023)
* fix(editor): localize pro mode right rail labels * fix(i18n): translate AI editor title * fix(i18n): localize Korean roster classmate label |
||
|
|
f378c25a53 |
feat(storage): route settings/user-profile persist through KVStore (no legacy migration) (#1001)
* feat(storage): route zustand persist through KVStore The settings and user-profile stores persisted through zustand's default `localStorage` storage, while the rest of the app's small keyed values had already moved to `@openmaic/storage`'s `KVStore` — two unrelated mechanisms over the same browser API, which is the split-brain the storage RFC set out to remove. `kvPersistStorage` shipped with the package but had no importer. Add `lib/store/kv-persist.ts`, the app seam that adapts a `KVStore` into a zustand `PersistStorage`, and wire both stores to it under an explicit `account` scope. Store logic is unchanged: `version` / `migrate` / `merge` still belong to the stores, only the bytes' destination moves. Existing installs are adopted rather than orphaned. On first read the seam moves the raw `localStorage` entry into the KV scope — write first, then drop the raw key, so an interrupted migration leaves the value readable from one side or the other but never from neither. Once KV holds the entry it is authoritative, so a stale raw entry reappearing cannot roll back newer state, and re-running can neither duplicate nor resurrect anything. An entry that is not a readable persist envelope is left exactly where it is. Hydration is now asynchronous, because a `KVStore` may be remote. The browser backend resolves within a few microtasks of the store module being evaluated, so nothing user-visible changes, but tests that assert on persisted state now await `persist.rehydrate()` instead of relying on a synchronous read. The four pre-persist keys (`llmModel` / `providersConfig` / `ttsModel` / `selectedAgentIds`) are deliberately untouched: they are read-only inputs to a migration that never owned them, and `providersConfig` is still read independently by `lib/ai/providers.ts`. Part of #857. * fix(storage): close the async-storage failure modes in the KV persist seam Cross-review found that routing `persist` through an asynchronous store opens failure modes a synchronous `localStorage` never had. Each one below is now covered by a test that fails without its fix. Data loss on a failed or empty hydration. A KV read that threw was indistinguishable from an empty scope, so the store stayed on defaults while an always-on initializer's `set()` persisted those defaults; the next load then read them as a completed migration and deleted the raw original, leaving nothing. Reads now separate "nothing there" from "the backend could not answer": a failed read serves the raw entry read-only, adopts nothing and deletes nothing, and leaves the key unwritable for the session so no un-hydrated state can be persisted over an original. Raw entries are additionally only dropped against a recorded completion marker, so a KV entry of unknown provenance can never authorize deleting the only copy of the user's data. Lost adoption across tabs. A reader whose KV read answered before another tab's adoption write, and whose localStorage read landed after that tab's delete, saw nothing in either place and hydrated defaults. Against a remote backend that interleaving is ordinary rather than rare, so an apparent "nothing anywhere" is now re-checked before it is believed. Out-of-order writes. Two rapid `setItem`s could complete in either order and let the older value win. Reads and writes are serialized per key. Pre-persist migration resurrecting on every load. `migrateFromOldStorage` was guarded by the existence of the raw `settings-storage` key — the very key the migration removes — so once the blob moved into the KVStore it ran on every load and republished whatever the pre-persist keys still held, including API keys the user had since deleted, into first-frame state. It is now the persist layer's last-resort source instead of a synchronous read in the store initializer: its result is adopted like any other migration, so the adopted entry is the marker that stops it. Initial state is plain defaults, and nothing stored reaches observable state before the storage layer has vouched for it. The source keys are still only read, never deleted, since `lib/ai/providers.ts` remains a reader. Also: KV reads and writes are guarded so a corrupt entry surfaces instead of throwing through zustand's silent catch; clearing the cache now clears the migrated stores through their own storage, which a server-backed scope would need and a blanket `localStorage.clear()` would only appear to do; `removeItem` drops the KV copy before the raw one; and the e2e suite gains post-migration steady-state coverage, which every existing spec missed by seeding the pre-cutover key. Part of #857. * fix(storage): scope migration bookkeeping to the device, gate writes on call Second review round. The findings shared one root cause: two of the three sentinels recorded a fact about *this machine's* files but were stored beside the data, in the store's own scope. Under a syncing `account` backend that is a category error with teeth — one device's history would travel to another and authorize deleting files it says nothing about. Sentinels are now always `device`-scoped and carry a reserved `__` prefix, whatever scope the store uses. The worst combination this closes: device A migrates, its marker syncs, device B — which has never run this build — loads and deletes the raw entry that is still the only copy of its own settings. A test drives exactly that sequence against two devices sharing one account scope and nothing else. The pre-persist fallback gains a device sentinel of its own. Its source keys are device-local and deliberately left in place, so "KV and raw are both empty" was not a safe trigger: clearing the account entry, from the cache button or a server-side wipe, let any device re-read those keys and republish credentials the user had rotated. It is now consulted at most once per device, and `removeItem` deliberately does not clear that sentinel — clearing the entry is precisely the case it exists for. The fallback also no longer writes the adoption marker: that marker is a licence to delete a raw persist entry, and the fallback has adopted no such thing. Were it written, a raw entry later restored by an older bundle would be deleted unread. The write gate is now read when `setItem` is called rather than when its queued turn arrives. Evaluated inside the queue, a write issued during hydration waited behind `getItem`, found the gate opened by the very read it raced, and persisted its pre-hydration snapshot on top of the stored value. Refused writes are no longer a dead end: the first one asks the store to rehydrate, since the backend may have recovered, and if that does not work the user is told through a durable notice rather than losing every change on reload. Each refusal is logged, not just the first — a once-per-session warning hides how long a session has been silently unsaved. `removeItem` now propagates backend failures, so clearing the cache cannot report success for a clear that did not happen, and that flow reloads immediately instead of leaving a window in which a background `set()` re-persists the credentials just deleted. Also: the recovery hook is bound after each store is constructed, because naming the store inside its own definition made its type circular and silently widened every selector to `any`; the `serial` comment no longer claims an unreachable rejection handler; and the pre-persist version stamp documents that it skips `migrate`'s unversioned normalization too, which `merge` redoes anyway. Part of #857. * refactor(storage): make the KV persist seam a per-key state machine Three review rounds kept turning up the same defect class in new places: a backend failure read as "there is nothing there", and the result of an operation that nobody looked at. Patching instances of it was not working, because both are possible whenever a call site is free to decide for itself what a failed operation meant. This makes that decision unavailable to call sites. Every backend call now returns an `Outcome` whose payload is a private field and whose only reader demands a `KeyState`. Feeding the machine is not a convention to remember; it is the only way to get the value out. What comes back is the value or `UNAVAILABLE` — deliberately not `null`, so "the backend could not answer" is not spellable as "nothing is there". The machine then decides, in one place, what failure means: any read failure is unavailability, any write failure closes the key, and either raises the health signal and asks for recovery. The scattered closure flags (a settled set, a warned set, a recovery latch) become one explicit phase per key — unhydrated, settled, unavailable, clearing — with the transition table written out in the docstring and a test per row. What that consumes: - A write failing after the key settled used to be ignored; its outcome now closes the key, signals, and the value is remembered for replay. - `removeItem` enters `clearing` synchronously at call time, so a `set()` racing a clear cannot be admitted, queue behind the delete, and write the just-deleted value back. Nothing is replayed across a clear. - The pre-persist sentinel is recorded by *every* settling path, not only the one that consults the old keys. A device that had only ever loaded an already-populated account entry recorded nothing, and so stayed eligible to republish its own stale credentials the moment that entry was cleared — which the docstring already claimed it would not. - Two places treated a failed read as an answer: the sentinel read that decides whether the fallback runs, and the confirming re-read before adopting. Both now stop. - An adoption whose marker did not land no longer settles, and never deletes the raw entry: no proof, no licence. - Refused and failed writes are remembered and replayed once storage recovers, but only when the store was holding real data at the time — replaying a snapshot taken over defaults would overwrite the stored value, which is the failure this seam exists to prevent. When a snapshot cannot be replayed the user is told, because rehydration is about to discard those edits. - Health notices publish on a later task, so a recovery that lands moments later cancels a warning nobody should have seen, and a subscriber mounting after the failure is caught up once its toast host exists. `StorageHealthNotice` now sits after the `Toaster` for the same reason. Also: adoption re-reads before committing so a concurrent write is not rolled back; a shadowed raw entry is only deleted if it parses, matching the promise never to delete bytes we could not read; the unavailable copy points at the control that resolves it rather than suggesting a reload that cannot; and the version pin, the pre-persist retention rationale, and the cache-clear comment say what is actually true. Part of #857. * fix(storage): separate the contexts settle() was conflating Convergence round on the state machine. The findings share a root: settle() treated every read that concluded as licence to open the key, without asking what else was true at the time. - A read finishing while a clear is outstanding no longer settles. Under a remote backend a recovery rehydrate in flight during a clear is ordinary, and opening the gate there admits a write that queues behind the pending delete and restores the credentials just removed. Only finishClear opens a cleared key. - The raw entry served read-only after a failed read no longer counts as the authoritative value. A shadowed raw entry is by construction the older copy — long-term coexistence with a newer KV value is a designed state — so an edit taken against it must never be replayed, or one transient read failure on one device rolls the whole account back. - A write that lands supersedes an earlier failed one. Both were admitted before the key closed, so the queue ordered them; replaying the older snapshot on recovery would undo the newer value. - Unreachable browser storage is a failure, not an empty store. Privacy modes make localStorage throw; treating that as "nothing stored" hydrated defaults, refused every write and said nothing until the user reloaded and found the work gone. SSR stays a silent no-op. - The recovery latch re-arms when storage answers, so the three recovery transitions are not empty promises from the second failure onward. - A refusal carries the phase it happened in. Cold-start timing — an always-on initializer writing before the first read resolves, on a backend that never failed — is a log line, not a sticky red toast; only a refusal under `unavailable` reports lost changes. The health channel stops delivering stale catch-ups: its timers are cancellable and re-read the current state when they fire, so a recovery cannot be overtaken by a warning with nothing left to dismiss it. And `changes-lost` is now a fait accompli rather than a condition — a later recovery has nothing to retract and leaves it standing. Also: a throwing `localStorage` is unavailability rather than absence wherever the raw entry is read; clearing records the pre-persist sentinel like every other settling path, making that docstring true; the raw entry is dropped before the marker so a failed marker clear leaves something inert; and the pre-persist fallback and its four source reads can no longer throw into zustand's silent catch. Part of #857. * fix(storage): hold a replay until it lands, and prove a raw copy before deleting it Three failure-path corners. A replay was retired the moment its write was attempted. Readable but not writable is a real state — a quota-exhausted backend answers reads perfectly — so a recovering read could succeed, the replay write fail, and the snapshot be gone with nothing owed: the next rehydrate served the older stored value over the user's edit and said nothing. The snapshot is now held until the write is durable; a failed replay goes back to being a refused write, so the next recovery tries again and a permanent failure is eventually reported. The adoption marker was treated as proof that a raw entry is the migration's leftover. It proves only that a migration happened on this device once. A rolled-back deployment, or a tab still running the old bundle, writes the raw key again with settings the migration never saw, and the next load on the new bundle deleted them unread. A raw entry is now dropped only when its content equals the value shadowing it — anything else is data, and keeping a copy beats deleting an original here as everywhere else in this file. `changes-lost` was being cancelled by a later recovery. The two statuses answer different questions: "storage is down" describes the world now and stops being true when storage works, while "your edits were lost" describes something that already happened and no amount of recovery undoes. They are now tracked on independent lines per key and rendered as two toasts with distinct ids, so retracting the fault cannot take the acknowledgement with it; the loss notice goes away only when the user closes it. Part of #857. * fix(storage): bound recovery, keep a live store from walking backwards Three interactions the state machine did not have an answer for. Recovery had no budget. A backend that reads but cannot write — a quota-exhausted one does exactly that — turned it into a treadmill: the recovering read succeeds, the key settles, the replay write fails, and that failure asks for recovery again, forever. Attempts now follow a backoff schedule whose length is the cap, and the budget is re-armed only on real progress: a settle that left nothing owed. A settle reached *by* a recovery with a replay still queued is not progress, and counting it as such is precisely what made every lap look like a fresh start. When the budget runs out the key is left read-only and the loss is reported, rather than retrying where nobody can see it failing. A failed read could walk a live store backwards. Once a session has loaded the authoritative value, a transient read failure was still falling back to the shadowed raw copy — which is legitimately older, and legitimately long-lived now that a differing raw entry is kept rather than deleted — and handing it to zustand overwrote a live store with stale data. Worse, the store had already latched "holding real data", so edits made on top of that stale value counted as replayable. A failed read after an authoritative one now returns nothing, which is exactly "keep what you have", and the raw fallback stays where it belongs: the case where nothing authoritative has been seen at all. Dismissing a lost-changes toast only closed the UI. The key stayed in the lost set, so the same store losing changes a second time was swallowed as a duplicate and any later subscriber resurrected a notice the user had already dealt with. The close button now clears the latch, so a second loss is reported and an acknowledged one stays gone. Part of #857. * fix(storage): close the last two provisional and clear-ordering gaps An abandoned migration was handing back an authoritative value. When the confirming re-read fails, or the adoption write does, `adopt` returns the raw envelope unadopted — the same footing as the raw copy served after any other failed read — but it was returned bare, so the store latched "holding real data" and an edit taken on top of it counted as replayable. Another device publishing to the account scope in that window would have been rolled back. `adopt` now reports provisionality like every other read path, and the shape is a named `LoadedValue` so the next path cannot forget. Clearing swallowed a failed raw-entry deletion. The account entry was already gone by then and the marker was cleared afterwards, so the operation reported success while leaving an empty scope beside a live raw entry — precisely the shape the next hydration re-adopts, handing back the settings the user had just deleted. The raw entry now goes first and its failure propagates, which also fixes the ordering: failing before anything is removed leaves the KV value authoritative and the clear simply unperformed, which the caller can retry. Adoption keeps the tolerant variant, where a leftover raw entry is a duplicate rather than a loss. Part of #857. * fix(storage): make the shadowed-raw delete atomic against a concurrent tab cosarah reproduced a data loss: both raw-entry deletes verified the value, then awaited (reading or writing the adoption marker), then removed the key by name. A tab running an old bundle — which takes no Web Lock, so a lock could not have helped — overwrites the raw key with newer settings during that await, and the unconditional `removeItem` then deletes the newer value. The raw side is synchronous `localStorage`, so the fix needs no lock. Both deletes now finish every await first, then run a single synchronous compare-and-delete: re-read the raw bytes, and remove only if they still equal the exact string that was verified. A competing tab is a separate context whose writes surface here only at event-loop boundaries, so its write lands wholly before the re-read (seen — bytes differ — kept) or after the remove, never in between. A changed value is newer data, not a migration leftover, and is kept. Both sites cosarah named are covered: the shadowed-cleanup path (`dropShadowedLegacy`) and the adoption cleanup in `adopt`. `readLegacyEntry` now carries the exact bytes alongside the parse so the re-check is byte-exact rather than comparing a re-serialized value. The clear path's delete is unchanged: it is a deliberate full delete, not a conditional leftover cleanup. Part of #857. * fix(storage): stop deleting the raw entry — adopt by copy (Plan B) Maintainer decision after cross-vendor + red-team review: `localStorage` has no cross-process atomic compare-and-delete (the storage mutex was dropped from the spec), so a tab on an old bundle can insert a write between our re-read and our removeItem in a genuinely parallel process. The synchronous compare-and-delete narrowed that window but could not close it — as its own comment admitted. Since the raw-cleanup cannot be done safely on localStorage while an old bundle may be live, this stops doing it. Adoption is now a copy: the value is written to KV and the raw entry is left in place. The delete race is therefore impossible — there is no delete. KV stays authoritative (once it holds the value, reads take the KV path and never consume the raw one), so the shadow duplicate is inert, left for a wholesale raw-cleanup at migration exit. Removed with the two deletes: - `dropShadowedLegacy` (its only job was the gated delete) and its three call sites. - `deleteLegacyIfUnchanged` and the `{raw,value}` shape of the legacy read (`readLegacyEntry` → back to `readLegacy` returning the value). - The adoption marker (`__persist-adopted:`), whose only reader was that delete gate. It did not prevent re-adoption — the presence of the KV value does — so removing it breaks no invariant. `dropRaw` / `expectedRaw` on `adopt` and the marker-clear step in the clear path go with it. The clear path (user deletes all data) still deletes the raw entry strictly — that is a deliberate full delete, not a migration cleanup. Tests: the delete/marker cases become "the raw shadow always survives, KV is authoritative"; a two-device and an old-bundle-concurrent-write case guard it, and re-adding a delete on either adoption path turns them red. Part of #857. * fix(storage): add a monotonic migrated marker to stop shadow resurrection Cross-vendor + red-team review independently caught a P1 the previous "adopt-as-copy" revision introduced. Because the raw entry is now kept and writes only ever reach KV, the raw copy becomes a frozen pre-cutover value. If the account KV is later emptied by something other than a local clear — a server-side wipe, an account switch, KV eviction — the next load saw `stored === null` beside a live raw entry and re-adopted that stale copy, refilling the wiped account with ancient settings/credentials and syncing them to every device. Deterministic, not a race; it would fire once a server-backed account backend exists. Root cause: "keep the raw entry" inherently requires a record that it has already been migrated, so an empty-KV load can tell "first migration" from "external wipe". Removing the old delete-authorization marker in the copy revision dropped that record — Plan B was only half done. Adds a monotonic, device-scoped `__migrated:<name>` marker: - Read on every load. `stored === null` + raw present + marker set ⇒ respect the wipe, do not adopt (fall through to the confirm re-read, so a concurrent repopulation is still served). Only a genuine first migration (no marker, raw present) adopts. - Written best-effort after a successful KV write. A failed write degrades to the KV value's own presence check, so resurrection needs both a failed marker write and a later external wipe. - Read failure fails closed (do not adopt), never "assume not migrated". - Monotonic: only ever set true, cleared only by a deliberate full clear — no compare-and-delete race, which is why it is safe where deleting the raw entry was not. Live state with a real reader, not the delete-authorization marker removed earlier. The clear path clears the marker too (back to a genuine first-load state); best-effort, since with the raw entry already gone a leftover marker is inert. Tests: resurrection guard (external wipe does not re-adopt; concurrent post-wipe write is served; first migration records the marker; marker read fails closed) + the clear-path marker clearing. Mutation-checked: removing the gate resurrects the shadow, dropping the record leaves it unguarded. P3: the inert `__persist-adopted:` test rot is retargeted to the real `__migrated:` path. Part of #857. * refactor(storage): remove automatic legacy migration — pure KV wiring Maintainer decision (terminal): after repeated review rounds kept finding new P1s in the legacy-adoption path — its state space is too large to keep correct — the PR is narrowed from "migrate + wire" to "wire only". Settings and user-profile persist through the KVStore; pre-cutover data is not migrated; an upgrading user reconfigures once (the data is reconstructable and the cost is one-time). Removed the entire legacy-adoption subsystem from the adapter: - `adopt()`, `readLegacy()`, the `legacyStorage` dep, and the raw-fallback read on a failed KV read. - The `__migrated:` marker and its resurrection guard, the confirm-re-read, and the `provisional`/`LoadedValue` machinery. - The `prePersistFallback` dep, `recordPrePersistHandled`, the `__pre-persist-consulted:` sentinel, and `readSentinel`/`writeSentinel`. - In settings.ts, `readPrePersistSettings` (the llmModel/providersConfig reader wired as that fallback) — reading legacy keys is migration, which this PR no longer does. `lib/ai/providers.ts` still reads `providersConfig` independently, so those source keys are left in place. The adapter now reads and writes the KV scope and touches no legacy key: an empty scope hydrates the store to defaults (ordinary zustand). `load()` is a single KV read; a failed read stays unsettled so defaults are never persisted over an unread value; the clear path removes only the KV entry. Kept, because they are async-storage *steady state* a remote KV backend needs, not migration scaffolding: the KeyState machine (hydration gate, write gate, recovery, replay), the Outcome discipline, per-key serialization, and the persist-health channel. Added `purgeLegacyPersistKey`: a best-effort, fire-and-forget removal of the old raw persist blob, called once by each store. Never read, so a leftover is pure garbage — and the old settings blob held plaintext provider API keys, so clearing it is a small security win. Net: the adapter drops ~460 lines. Tests are rewritten to steady-state KV coverage plus an explicit "old raw key is ignored, not migrated" proof at the store level; the e2e seed fixtures move from the raw key to the KV scope key. Part of #857. * docs(storage): align README and comments with the no-migration behavior Follow-up requested on the approved PR: the migration/adoption logic was removed, but a few comments and one README roadmap line still referred to those deleted concepts. Documentation only — no behaviour change. - README roadmap: the settings/user-profile line said "adopting their pre-cutover raw keys"; it now states there is no automatic migration (legacy keys ignored and best-effort purged, users reconfigure once). - kv-persist.ts: the per-key serial chain comment no longer claims to keep "adoption" from interleaving; it serializes a key's read/write/clear. - settings.ts: `SETTINGS_PERSIST_VERSION` no longer documents a "pre-persist fallback" that no longer exists. - Test/fixture headers that described seeding "the pre-cutover raw key" for "one-time adoption" now describe seeding the KV `account` scope, with no legacy-key migration. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(storage): bump version to 0.1.1 for README doc alignment The README is a publishable input, and the no-migration doc alignment changed it, so the package version must increase. Patch bump: documentation only, no code or API change. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com> Co-authored-by: wyuc <zdq1204@gmail.com> |
||
|
|
23a9e757d5 |
refactor(choreography): drive overlays from descriptors (#947)
* feat(choreography): add Motion descriptor adapter * fix(choreography): harden descriptor lookups * fix(choreography): preserve descriptor special keys * refactor(choreography): drive overlays from descriptors * fix(choreography): preserve spotlight fade easing * fix(choreography): align descriptor consumers * docs(choreography): clarify spotlight easing |
||
|
|
61a7154f07 |
feat(pi): add evidence-aware Director context runtime (#971)
* feat(pi): add evidence-aware Director context runtime * fix(web-search): require completed native search * fix(orchestration): preserve whiteboard across agent handoffs * fix(pi): remove wrap-up turn bypass |
||
|
|
ff95e6683d |
feat(renderer): add optional playback canvas (#958)
* feat(renderer): add optional playback canvas * style(renderer): format playback tests * fix(renderer): center text by default * fix(renderer): address playback review feedback * docs(renderer): align playback canvas API docs --------- Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn> |
||
|
|
6d29241bb0 |
feat(video-export): fidelity polish — spotlight geometry, video clips, formulas, subtitles (#952)
* fix(video-export): bridge play_video element id → media ref Generated-media records are keyed by the element's media ref (gen_vid_…), but a play_video action targets the slide element by its .id. The app-side compiler deps looked media/durations up by the raw element id, so every generated video missed → present:false → no <video> emitted, no bytes collected → the clip vanished from the export (only its static first frame, baked into the base PNG, remained). Build an elementId → mediaRef bridge across all slide scenes in createVideoTimelineDeps (mirroring the live engine's resolveMediaPlaceholderId) and resolve both media() and videoDurationMs() through it. Refs #867. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): re-measure KaTeX fit-scale after fonts settle KaTeX sizes large delimiters (\left\{, \begin{cases}) from its KaTeX_Size faces, which load asynchronously. KatexContent measured its shrink-to-fit scale once on mount, against the fallback font, and never recomputed — so a cold slide snapshot baked a stale scale and the big brace desynced from the piecewise body ("大括号后面的分段函数与大括号错位"). - Re-run the fit-scale measurement on document.fonts.ready and on each `loadingdone`, keeping the shrink-only (cap-at-1) behavior. - slideToPng waits two extra frames before capture so the font-triggered React re-measure commits into the DOM html2canvas reads. Refs #867. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): place spotlight/laser/video on the rendered content box The pure geometry helper resolves an element's authored outer box against a fixed 1000×562.5 base, but the live overlays — and the exported frame PNG — measure the element's `.element-content` box, which for horizontal text is auto-height plus 10px content padding. So a spotlight/laser sat offset from where the text actually renders ("spotlight 与对应元素的位置有偏差", #867 item 5). Add an optional GeometryProbe to the compiler's DI boundary: when supplied, the geometry pass prefers each element's measured content-box geometry (video keeps its rotation from the authored element), degrading to the pure authored-box calc on a miss so the compiler stays deterministic in unit contexts. App side: measureSlideElementGeometry (new, in @openmaic/renderer/snapshot) mounts the slide off-screen and reads the same `.element-content`-against- container box the live SpotlightOverlay uses; createVideoTimelineDeps pre-measures every spotlight/laser/play_video target per scene and serves the probe as a synchronous table lookup. Tests: geometry.test.ts quantifies the outer-box vs content-box delta and proves probe-wins / fallback / rotation-preservation; timeline-deps.test.ts covers the pre-measure wiring. Refs #867. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): decode a first-frame poster for posterless videos A play_video clip only shows during its play window; the rest of the time the static base-frame PNG backs that spot. But html2canvas can't draw a <video>, so the snapshot swaps it for its poster <img> — and generated videos usually carry no poster, leaving the video area blank whenever the clip isn't playing. When a video record has no stored poster bytes, decode the video blob's first frame (seek slightly off 0, draw to a canvas) and set element.poster before the base snapshot, so that spot shows the first frame — the "paused on frame one" look — instead of blank. Falls back to no poster on decode failure / timeout / CORS taint, never failing the export. Refs #867. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(video-export): split subtitles, make burn-in optional, centered modal Burned-in captions used one cue per whole narration paragraph, so a long cue became a 4–6 line block covering the lower half of the slide, and there was no way to turn it off. - Split cues (pure, compiler layer): lib/video-export/split-cue.ts splits each cue on sentence → clause → hard-wrap to ≤~40 CJK-equiv units, distributing the parent window by character weight (last piece pinned to the parent end, sub-1.2s slivers merged). Wired into the timeline pass, so the burned-in overlay and the SRT/VTT sidecar share one split track and can't drift. - Burn-in optional (default off, #867 item 2): emitHyperframes gains burnInSubtitles; off → clean video + sidecar SRT/VTT only. Caption layout hard- clamped to 2 lines so an outlier can't grow tall again. - Download subtitles without rendering: compileSubtitles() runs only the compiler (no assets/zip/service); new useDownloadSubtitles saves an .srt. - Centered modal: video-export-dialog.tsx replaces the cramped dropdown section, grouping Output / Subtitles / Actions / Progress with a stable lifecycle for multi-minute renders. header-controls opens it from an "Export Video" entry; old video-export-menu.tsx removed. i18n keys added across all 8 locales. Refs #867. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * style: prettier format video-export fidelity changes Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test: drop unused playVideo helper in timeline-deps test The media-bridge tests assert via deps.assets.media(...) directly, so the playVideo helper (and its PlayVideoAction import) were dead. Flagged by the code-quality bot on #952. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): resolve cross-review findings + lower subtitle band - emit-hyperframes: drop duplicate `display:-webkit-box` on subtitle cues so they start truly `display:none` (a second declaration overrode the `none`, showing every cue stacked at t=0 when burn-in was enabled). - geometry: don't feed the measured content-box AABB to a rotated video clip — it already encloses the rotation, so re-applying `rotate` doubled it. Rotated elements fall back to the authored box (one, un-doubled source of truth). - build-export-zip: extract shared `compileStageIr` so buildExportZip and compileSubtitles can't drift on the timing/assets/geometry wiring. - split-cue: join merged CJK cue pieces without a spurious ASCII space. - subtitles: lower the caption band (bottomRatio 0.055 → 0.01) and hoist the band's magic numbers into a named SUBTITLE constants block. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): stop the snapshot onclone override from reshaping KaTeX The export snapshot injects a neutral-kerning / geometricPrecision style over `.slide-renderer-prose *` to keep CJK prose+table glyphs from mis-advancing under html2canvas-pro. KaTeX formulas (output:'html') also live inside `.slide-renderer-prose`, so the override was reshaping their math glyph advances — a burned-in formula rendered subtly differently from the live canvas, which applies no such override. Empirical check (Playwright + system Chrome, cases+fraction formula, native paint vs html2canvas): the override raised the formula's mean per-pixel delta vs the live paint from 120.1 to 139.2 (~16%) and moved ~75% of inked pixels. Restoring native font-kerning/text-rendering for `.katex` subtrees brings the formula's delta back to 120.1 (bit-identical to the no-override capture) while prose and table text keep the override. The residual 120.1 is the deeper html2canvas rasterization gap (vlist/frac-line/delimiter), a separate track. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): render slides via native paint, bundle KaTeX font embed Root-fix the exported-vs-live formula distortion (and the filter/mask/video gaps) by rasterizing slides with native Chrome paint instead of html2canvas's reimplementation. - slideToPng now captures via html-to-image (foreignObject → the same Chrome engine that paints the live classroom rasterizes the same DOM). KaTeX formulas, CSS filter, soft-edge masks, and mixed CJK/Latin text come out as the classroom shows them. html2canvas-pro stays as a fallback (with the filter/mask bakes + KaTeX text-rendering reset) for when native paint can't run — e.g. a cross-origin image taints the canvas. - A foreignObject SVG can't reach the document font registry, so fonts must be inlined. KaTeX math faces are prepended from the bundled woff2 (KATEX_FONT_EMBED_CSS, generated by scripts/generate-katex-fonts.mjs), NOT left to runtime getFontEmbedCSS — which reads cssRules and silently drops a cross-origin KaTeX stylesheet, collapsing a large brace to a fallback glyph (the observed "formula render failure" on e.g. a \begin{cases} with \text{}). A per-face guard verifies every KaTeX face the formula references is embedded, falling back to html2canvas otherwise. Verified in a Playwright spike (native vs html2canvas vs html-to-image): formula inked-delta 143→53; filter/mask/video match native; and with getFontEmbedCSS forced empty, the bundled embed alone still renders the failing formula correctly. Renderer package tests: 226 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): prettier-format the generated KaTeX font-embed module The generator emitted an unformatted TS file (double quotes, long unwrapped CSS literal) that failed CI `prettier --check`. Run the generated output through the repo's Prettier config before writing, so every rebuild produces CI-clean, stable output. Regenerated the committed file to match. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(lint): rename reserved `module` var in katex-fonts generator; ignore .scratch - generate-katex-fonts.mjs assigned to a variable named `module`, tripping @next/next/no-assign-module-variable (the one hard eslint error). Renamed to `fileContents`; generated output is byte-identical (deterministic). - Add `.scratch/**` to the eslint globalIgnores (alongside .claude/.worktrees) so local throwaway verification scaffolding doesn't pollute `pnpm lint`. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): address PR #952 review — scene-scoped media bridge, safer cue splitting Resolves the two blocking correctness issues and three follow-ups from the cross-review on #952. - Scope the elementId→mediaRef bridge by scene (was deck-wide/last-writer-wins): slide-local ids like `video_001` now resolve within their own scene. `assets.media` uses its scene arg; `timing.videoDurationMs` resolves via action object identity. Adds a cross-scene collision test. - Stop treating every ASCII period as a sentence boundary: a lone `.` splits only when not between word chars (3.14, v1.2) and not an abbreviation dot (e.g.), collapsing repeated-punctuation runs. Adds decimal/version/abbrev/ellipsis tests. - Share the module-level in-flight guard across ZIP export and subtitle download (extracted to export-in-flight.ts); dialog `busy` folds in `downloading`. - Skip the off-screen geometry render for the subtitles-only path (skipGeometry); duration probes are kept so sidecar cue timing stays in sync with the video. - Align measure.ts font settling with slideToPng: force-load each used face before fonts.ready so measured content-boxes don't bake fallback advance widths. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * style(video-export): prettier-format split-cue test Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * perf(video-export): enable beginFrame capture via PRODUCER_BROWSER_GPU_MODE=hardware The producer defaults to `software` GPU mode, which silently force-enables the CPU-bound `Page.captureScreenshot` fallback: SwiftShader pins every core on rasterization and caps frame capture at ~10 fps. Selecting `hardware` keeps Chromium's `HeadlessExperimental.beginFrame` capture active instead. Measured on a 900-frame (30s) clip, no real GPU on the host: - capture ~10 -> ~19 fps, total 100s -> 62s (~38% faster) - CPU peak ~810% -> ~98%; peak mem 2.2 GiB -> 0.9 GiB - static frames pixel-identical; animation frames differ only in sub-pixel edge antialiasing (same-path re-render is deterministic/inf PSNR) No real GPU is required — the win is the faster capture API, not hardware rasterization; beginFrame falls back gracefully if the host lacks a GPU. Also eases the RENDER_JOB_DEADLINE_MS timeout risk on long videos. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(video-export): sentence splitting via Intl.Segmenter + abbreviation merge Addresses the PR #952 follow-up: separate sentence-boundary detection from cue shaping and stop growing a custom punctuation heuristic. - splitSentences now delegates boundary detection to Intl.Segmenter (locale- agnostic ICU), the multilingual/CJK baseline. It already preserves 3.14, v1.2, e.g., U.S., ellipses, and CJK 。!?… without any hand-rolled period scan. - ICU still ends a sentence after a titlecase abbreviation before a capitalized word (Dr. Smith, Fig. 3) — the edge case the reviewer flagged. A small abbreviation-aware post-merge re-joins those, driven by an ABBREVIATIONS set. - Semicolons are no longer sentence ends (they join clauses); moved ;; into the clause-level SECONDARY splitter so over-budget sentences still break there. - Cue shaping (budget / clause / hard-wrap / weighted timing) is unchanged, so detection and shaping are now distinct stages. Not using `sbd` as suggested: lib/video-export/*.ts sits behind the machine- enforced eslint purity boundary (imports limited to @openmaic/dsl, zod, ../choreography, siblings), so a new npm dep is rejected. Intl.Segmenter is a pure Node >=20.9 builtin, matching the reviewer's "small abbreviation-aware post-merge layer" alternative. Tests: add Dr. Smith / Fig. 3 / U.S. coverage; the rhetorical ellipsis now stays one under-budget cue (was split); add a semicolon over-budget case. 22/22 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * style(video-export): prettier-format split-cue sentence refactor Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * i18n(es-MX): add 7 subtitle/video export keys to align with en-US main added the Spanish (Mexico) locale (#942) after this branch's subtitle keys landed, so es-MX was the only locale missing export.subtitles* and export.videoBurnSubtitles* — which failed the i18n key-alignment CI check. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): restrict title post-merge so it never deletes real boundaries Addresses the blocking re-review on the Intl.Segmenter change: the abbreviation post-merge unconditionally rejoined the next ICU segment whenever the previous one ended in a listed abbreviation, which erased genuine sentence boundaries — `It was made by Acme Inc. Next point.` collapsed into one cue, and even an explicit newline (`Acme Inc.\nNext topic`) was rejoined. The merge now fires only for the case ICU actually mis-splits — a title (Mr/Mrs/Ms/Dr/Prof/Sr/Jr) before a capitalized proper noun — and only when: - the previous segment does not end at a newline (hard boundary), and - the next segment starts with a capital letter. Sentence-trailing abbreviations (Inc./Ltd./etc./vs./No.) are dropped from the set entirely: they legitimately end sentences, and ICU already keeps a title before a number (No. 5, Fig. 3) or a lowercase continuation (etc. and…) whole without any merge, so nothing there needs rejoining. Regression tests: Inc./etc. boundary preserved, newline-after-title preserved, lowercase continuation kept whole, plus the retained Dr. Smith / Fig. 3 / U.S. cases. 26 split-cue tests pass; full video-export suite 123 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
b4e3145c90 |
feat(roster): single-source the generated agent roster on the stage document (#994)
* feat(roster): single-source the generated agent roster on the stage document The generated agent roster used to live in two places at once: the stage document carried generatedAgentConfigs, while a per-stage IndexedDB mirror (db.generatedAgents) was the actual read authority — and the only home of each agent's voice binding. The split caused real losses: voices vanished on device switches, exports, and shares (the mirror never travels), the load path trusted a device-local table over the portable document, and roster edits persisted through a bespoke debounce with no beforeunload flush. Make the stage document the single source of truth: - Contract: add optional voiceConfig/voiceDesign to GeneratedAgentConfig in @openmaic/dsl (VoiceDesign moves into the contract; the app re-exports it). Additive optional fields — not a breaking serialized-shape change, so DSL_VERSION stays put per the version policy. - Writes: remove every mirror writer (registry saveGeneratedAgents, the stage store's debouncedSaveAgents bypass, classroom-load hydration, import direct writes). setStageAgents now only marks the stage dirty for the shared persistence scheduler plus synchronous in-memory registry/selection mirrors; generation and import embed the roster on the stage. - Reads: classroom load hydrates the registry from the loaded stage's generatedAgentConfigs; export reads the stage roster directly. - Lazy migration: the mirror is retained read-only. On load, a roster (or voice fields) missing from the document is backfilled from the mirror, committed onto the in-memory stage, and persisted by the next flush — idempotent, and gated on the current stage id after every await so a classroom switch cannot leak a stale roster into the registry. - Deletion: deleteStageData discards the deleted stage's pending persistence work so a queued flush cannot resurrect the document. - Round trip: classroom ZIP manifests now carry the voice fields, so export/import preserves agent voices. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(roster): harden deletion, migration, selection, and ingress paths Review hardening on top of the roster single-source change: - Deletion vs in-flight persistence: deleting a stage now registers a session-scoped tombstone (lib/utils/deleted-stages.ts) before the cascade starts. Every persistence landing point checks it — the scheduled flush and the departing-stage retry drop their snapshots, and the aggregate/incremental saves re-check under the document lock, including the incremental path's full-save fallback that would otherwise rebuild a deleted document from the in-memory snapshot. A deletion that fails before the document is removed lifts the tombstone so the still-existing stage keeps persisting. - Lazy migration termination: a fruitless legacy-mirror probe (nothing to merge — e.g. server-generated rosters, which are voiceless by design) is remembered per stage for the session instead of re-querying the mirror on every load forever. Successful merges are not memoized so a failed flush is retried on the next load. Docstrings now state the real lifecycle. - Selection provenance: setStageAgents no longer overwrites a user-set agent selection with the full roster. Stage-derived selections still track the roster; a user-set auto selection is only narrowed to surviving agents (newcomers are not auto-selected, the user-set flag is untouched), and a user-set preset selection is left alone — matching restoreAgentSelection. - Mirror hygiene: deleteStageData clears the deleted stage's rows from the legacy roster mirror (best-effort), and the mirror table's docs now describe its actual access pattern (migration reads + deletion hygiene). - Registry persistence: the agent registry's persist snapshot partializes generated agents out of localStorage, making the stage document the roster's only durable home; the rehydration merge filter remains as defense in depth. - Ingress validation: imported manifest voice fields are structurally validated (malformed bindings dropped per field, the agent survives), and applyGeneratedAgentsToRegistry validates providerId against the known TTS provider registry instead of casting, treating unknown providers as "no bound voice". - Contract: drop the speculative AgentVoiceConfig.modelId — an audit of every roster producer, current and historical, found none that ever emitted it. Contract fields are added once a producer exists, not before. New tests cover the deletion tombstone at both the store and storage layers (including the missing-destination full-save pin and the lock-race re-check), the fruitless-probe memo, the selection-provenance matrix, persistence exclusion of generated agents, and voice-field sanitization on import. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(roster): close tombstone lifecycle, probe-memo, and selection-intent gaps Second hardening pass over the deletion/migration/selection fixes: - Tombstone lifecycle: a deleted classroom id can legitimately come back (deletion is client-side only). Explicit (re)creation points now lift the tombstone — server-copy restore in applyClassroomStageAndScenes and backup restore in importDatabase — so edits after a same-session restore persist again, while in-flight flushes stay fenced. - Failed deletion now restores the dirt it discarded: deleteStageData snapshots the pending map plus the in-flight round before tombstoning, and re-marks it when the delete fails with the document still present. - Legacy-mirror probe memo now distinguishes a FAILED read (null, retried on the next load) from a confirmed-empty mirror (memoized), so a transient IndexedDB error cannot suppress migration for the whole session. - Incremental save tail (currentScene KV row + chat sessions) is tombstone- fenced like the aggregate path, and both paths re-check the tombstone immediately before every write, with comments scoped honestly for the lock-free (no Web Locks) best-effort LWW fallback. - Roster-edit selection mirror: an empty intersection now falls back to the full roster and clears the user-set flag (matching restoreAgentSelection's length > 0 gate), and a user-set selection that equals the pre-edit full roster keeps tracking the roster wholesale so newcomers are not excluded forever by the AgentBar auto-toggle snapshot. - TTS/ASR provider lookups use Object.hasOwn instead of `in`/bare indexing, so prototype-chain keys ('toString', 'constructor', ...) no longer pass the provider whitelist or resolve to Object.prototype members. - Documented the per-tab limit of the tombstone set. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(roster): replace the boolean deletion tombstone with a deletion-generation model A boolean tombstone cannot express the deletion lifecycle once a deleted id legitimately comes back (server-copy restore on revisit, backup import): after the restore lifts the flag, a pre-delete flush still in flight is indistinguishable from a post-restore edit and can overwrite the restored document with pre-delete content. Two rounds of point fixes kept leaking variants of this race, so this restructures the fence instead. deleted-stages.ts now keeps a per-stage monotonic deletion epoch plus a deleted flag. markStageDeleted bumps the epoch; unmarkStageDeleted clears only the flag and never rewinds the epoch. Every persistence path captures the epoch at the moment it captures the data it will write (flush-round snapshot, departing-stage snapshot, aggregate save entry) and re-checks "captured epoch is current AND not deleted" immediately before each individual write. Invariants: - A write captured before a deletion can never land after it, even when a same-id restore has lifted the deleted flag (the captured epoch is permanently stale). - A write capturing data after a restore observes the current epoch and persists normally. - A failed deletion lifts only the flag; the restored pending changes are re-queued as descriptors, so their flush re-captures current store state under the current epoch and is neither dropped nor a stale replay. Also fixed in the same restructuring: - Incremental tail writes (currentScene, chats) each re-check independently; a delete landing while the first tail write is awaiting now fences the chat write instead of riding the earlier check. - Deleting a classroom evicts it from the warm in-memory store, and loadFromStorage treats a warm-but-deleted stage as not loaded (discarding the ghost), so navigating Back to a deleted classroom reaches the server-restore path instead of rendering an editable ghost whose every edit is silently dropped. - importDatabase records each document's pre-import deletion state and reinstates it when a failed import rolls the document back, so an outstanding flush cannot recreate the rolled-back document. - Docstrings on the failed-deletion restore path now state that only dirt captured before the deletion is restored; edits refused during the deletion window are not part of the snapshot. New tests cover the epoch invariants at the storage layer (pre-delete rounds dropped across restores on the incremental, aggregate, and tail paths; post-restore captures landing; strictly increasing epochs), the scheduler layer (departing-retry delete+restore straddle; restored dirt flushing under the current epoch), the warm-ghost restore driven through the real loadFromStorage, and the import lift/rollback pair. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(deletion): report fenced drops, gate ghost eviction on cascade settlement Edge hardening around the deletion-epoch fence; the epoch model itself is unchanged. - An epoch-stale drop is now reported, not disguised: saveStageData / saveStageDataIncremental return a distinct 'stale-dropped' status (entry check, every in-mutation re-check, and both tail-write re-checks) instead of a shape identical to success. saveToStorage reacts by skipping all success bookkeeping - no chatSnapshot rebind to a snapshot that never landed, no pending-dirt clearing - and returns false, keeping its "true means verified write" contract honest. persistDirtySnapshot keeps its existing (correct) semantics explicitly: a drop has nothing to retry. - Warm-ghost eviction is settlement-gated: the deletion cascade records an in-flight bit (begun by deleteStageData, settled in its finally), and the deleted-warm branch of loadFromStorage keeps the warm state while the cascade is unsettled - a delete can still fail before removing the document, in which case the warm state plus the restored pending dirt is the only copy of the pre-delete edits. Once settled, the ghost discard and server-restore path behave as before. - Read-side landing re-check: loadFromStorage re-checks isStageDeleted after hydration, immediately before set(), mirroring the write-side "re-check immediately before landing" discipline - a lock-free mid-cascade read can no longer re-materialize a ghost classroom. - clearStoreForDeletedStage re-checks isStageDeleted at eviction time, so a same-id restore completing inside the cascade-tail window is never wiped. - capturedEpoch is now a required parameter on both storage entry points: the default (call-time capture) silently reopened the capture-point/ validation-point split for future callers; the type system now enforces the pairing. All production callers already passed it explicitly. New tests cover the dropped-status contract, the cascade in-flight lifecycle (including both failure shapes), keep-warm during an unsettled delete with end-to-end pending restore after a failed delete, settlement- then-eviction on success, the eviction guard against a tail-window restore, and the read-side hydration re-check. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(deletion): settle the deleted-warm load by awaiting the cascade outcome Hardening around the deletion settlement gate introduced previously; the epoch model is unchanged. - The deleted-warm branch of loadFromStorage no longer completes the load while the deletion cascade is undecided (which exposed a classroom whose edits were refused without being restorable, and left a successful deletion's eviction with no follow-up reload). It now parks on a per-stage settlement promise (stageDeletionSettled) and branches on the outcome: a failed delete keeps the warm, restored classroom; a successful delete falls through to a full cold load so the server-restore path recovers the route; a navigation that moved on during the park is stopped by the load token guard. The eviction (clearStoreForDeletedStage) deliberately stops claiming a new load token so the parked load stays current - ghost re-materialization is fenced by the read-side deleted re-checks instead. No deadlock: a parked load holds no document lock, and the cascade never waits on a load. - 'stale-dropped' now propagates through the debounced flush path: persistDirtySnapshot returns the sentinel instead of an empty failure set, and startFlushRound skips the chatSnapshot rebind on it (mirroring saveToStorage) - a falsely rebound baseline would let later chat saves no-op-skip chats that never landed and corrupt cross-tab conflict detection. Pending-map clearing keeps its empty-failure semantics (restored descriptors mint fresh revisions). - The cascade in-flight state is a counter (begin++/settle--) instead of a boolean, and deleteStageData is single-flight per stage (a concurrent second call joins the first cascade), so overlapping deletions can never expose an undecided cascade as settled. - The StaleDroppedSave docstring no longer overpromises: a tail saveCurrentScene can land after the cascade's clearCurrentScene; the orphaned cursor row is ignored by the load path rather than removed by the cascade. Net +8 tests: overlapping-cascade counting, settlement-promise resolution (success and failure), concurrent double-delete single-flight join, the parked mid-cascade Back in both outcomes plus the navigation-away guard, and the fenced flush round keeping an honest chat baseline end-to-end. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(deletion): re-verify store identity on keep-warm resume, re-run joined deletes after a mid-cascade restore Three hardening refinements on the deletion/persistence fencing: - loadFromStorage's parked keep-warm branch now mirrors the success path's store-identity guard: if a tokenless writer (e.g. a database import) replaced the stage during the park, a failed deletion falls through to the cold load instead of reporting another classroom as the kept warm state. The ghost-discard block is correspondingly gated on the deleted flag so the fall-through does not mislabel a surviving document as a ghost. - deleteStageData: a joined call carries its own deletion intent. When the first cascade fulfills but a same-id restore lifted the deleted flag in the meantime, the joined caller now runs one fresh cascade against the restored document instead of reporting the pre-restore outcome. Exactly one re-check per call (no recursion); a rejected first cascade still propagates unchanged to every joined caller. - Narrowed the failed-delete restore-ownership comments: the restore covers only the pending map plus an in-flight flush round's dirt; a departing-stage snapshot is outside that capture and is fenced and dropped by design. Comment-only, no behavior change. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(roster): gate deleted-warm handling on stage identity, keep an explicit empty roster authoritative Final-audit fixes, three items: - loadFromStorage keyed its deleted-warm settlement handling (park / keep-warm / ghost discard) behind the scenes.length > 0 shortcut, so a zero-scene warm ghost of a deleted classroom skipped it entirely: the cold load found no document, the ghost stayed in the store, and the classroom loader's server-fallback gate (!getCurrentStage()) never ran — the silently-uneditable trap this branch exists to close, in its scene-less form. Deletion handling now keys on stage identity alone, before any scene-count shortcut; the non-deleted warm skip still requires scenes. - rosterNeedsLegacyFallback collapsed "roster field absent" (document predates roster persistence) with "explicitly persisted empty roster". A future writer persisting [] on a device whose read-only mirror still held stale rows would have its emptied roster resurrected on every load. The full-lift branch now triggers only when the field is absent (undefined); an explicit [] is authoritative and never probes the mirror. No current writer produces [], but the read side no longer depends on that invariant. - The GeneratedAgentConfig docstring claimed the voice fields are not a breaking change; that only holds for this codebase's tolerant structural validators. The generated stage.schema.json sets additionalProperties: false, so consumers pinning an older published schema artifact reject documents carrying the new fields. The docstring now states both sides honestly. Tests: a zero-scene deleted warm ghost is restored through the real loadFromStorage (fails pre-fix), an explicit empty roster does not resurrect stale mirror rows (fails pre-fix), and the rosterNeedsLegacyFallback unit matrix covers undefined vs []. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(deletion): re-queue aggregate persistence when a failed deletion is recovered Direct aggregate saves (saveToStorage: generation completion, server-restore hydration) run outside the pending map and the flush round, so the deletion path's pre-delete dirt snapshot cannot describe them. When a deletion bumped the epoch while such a save was in flight, the save was correctly fenced ('stale-dropped') — but if the deletion then failed before removing the document, the recovery only re-queued the snapshotted scheduler descriptors. The fenced aggregate-only content stayed memory-only with no retry anywhere, and a later reload lost it. The failed-deletion restore now merges a full re-mark of the aggregate (structure / stage / outline / currentScene / chats plus a descriptor for every current scene) into the recovery set, still guarded on the store holding the stage. Because the flush recaptures the CURRENT store state under the CURRENT epoch, this necessarily carries whatever the fenced aggregate save held — and, for the same reason, edits refused by the scheduler during the deletion window, which previously stayed memory-only as well; the scope docstrings now say so instead of declaring them excluded. New integration coverage drives the real store scheduler and the real storage layer end to end: a genuinely fenced in-flight saveToStorage (generation completion) plus a pre-removal deletion failure ends with the completion flag durable on the next flush; a deletion-window scene edit survives the same way; and a successful deletion re-marks nothing (control). Both recovery tests fail against the previous restore logic. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com> |
||
|
|
3eea9dc542 |
feat(runtime): complete the #869 learner-data cutover — quiz + playback onto RuntimeStore (#955)
* feat(runtime): persist quiz attempts in RuntimeStore * fix(runtime): coalesce quiz draft snapshots * fix(runtime): recover concurrent quiz attempts * fix(runtime): handle quiz completion races * fix(runtime): commit quiz review atomically * fix(runtime): dedupe concurrent quiz writes * fix(runtime): drop stale quiz drafts * fix: harden quiz runtime review recovery * fix: serialize quiz attempt identity * feat: read quiz state from runtime store * fix: persist quiz retries before resetting * fix: preserve authoritative quiz outcomes * fix: preserve legacy quiz retries during cutover * fix: reconcile legacy quiz snapshots safely * fix: drain rollover quiz write queues * fix: drain completed quiz retry queues * fix: reuse concurrent quiz retries * fix(quiz): preserve drafts across abrupt reloads * fix(quiz): recover empty retry sessions * fix(chat): abort stalled runtime state reads * fix(quiz): expose queued phases to readers * fix(quiz): retain concurrent writer tails * fix(quiz): canonicalize retry branches * fix(quiz): keep retry rollovers monotonic * fix(quiz): validate skipped retry siblings * fix(quiz): close read cutover races * test(classroom): cover legacy quiz summaries * fix(quiz): reset async consumers on scene changes * fix(quiz): close scene transition windows * test(pbl): cover launch freshness guards * fix(quiz): close cutover concurrency gaps * fix(quiz): harden retry and context freshness * fix(quiz): reject malformed legacy answers * fix(quiz): validate legacy answer values * test(quiz): cover legacy multi-answer migration * fix(merge): retire dead ChatRequestTemplate.storeState after quiz read cutover Main's three call sites built static storeState blocks that runAgentLoopFn never consumed (it always rebuilds fresh state via getStoreState); the quiz read cutover replaced that callback with the async two-phase RuntimeStore read, leaving the template field with zero consumers. Drop it. * feat(storage): conform HTTP/PG backends and reference server to RuntimeAppendOptions The quiz write path's expectedLastSeq / sessionTransition / RuntimeAppendConflictError semantics existed only in the browser backend; server-backed deployments would silently accept conflicting appends and leave completed sessions active. Forward the options over the wire, detect conflicts atomically under the PG transaction, map them to HTTP 409 RUNTIME_APPEND_CONFLICT, and rematerialize the typed error client-side so quiz retry logic works across every backend. Co-authored-by: Codex <codex@openai.com> * fix(chat): Pi single requests build storeState via the async runtime quiz read Pi bypasses runAgentLoop's per-iteration getStoreState and serializes the request template straight to /api/chat/pi, which rejects bodies without storeState. Extract the fresh-snapshot builder (async RuntimeStore quiz read with the scene-transition guard) and call it on the Pi path too. * ci: whitelist the runtime-data-cutover integration trunk for PR checks * feat(runtime): playback cutover — cursor in KV, discussion facts in RuntimeStore (#956) * feat(runtime): cut playback over to the runtime layer — cursor in KV, facts in RuntimeStore (#869) The fourth and last runtime family. Consumed-discussion facts become append-only 'playback' records folded into a set at read (at-least-once appends, no conflict machinery); the resume cursor is device-scoped last-write-wins KV per the amended #779/#869 split. sessionStorage keeps same-tab priority; KV takes over on fresh tabs/reloads. The dead Dexie playbackState machinery is retired, with a one-time lazy migration of any legacy row (cursor half + facts half) before deletion, and stage deletion now clears both the KV cursor and any unmigrated legacy row. Co-authored-by: Codex <codex@openai.com> * test(runtime): include playbackState in the stage-delete db mock --------- Co-authored-by: Codex <codex@openai.com> * fix(playback): persist discussion facts on every consumption path (#957) * fix(playback): persist discussion facts on every consumption path (final-review P0+P1s) - The engine now publishes a progress snapshot the moment a discussion is consumed (join / skip / unselected-agent auto-skip). onProgress otherwise fires before the discussion action executes and a discussion is the scene's last action, so the fact never reached persistence. - Reads fold records across ALL playback sessions in the learner partition (mergeLearner deliberately preserves same-kind sessions from both keys). - Legacy migration appends only not-yet-durable facts, so an interrupted migration resumes instead of dropping the tail. - recordConsumedDiscussion reports durability; the component drops failed ids from its observed set so a later progress tick retries (at-least-once). * test(e2e): live verification of the playback persistence chain Seeds a deterministic stage straight into the Dexie DB, starts the lecture via the canvas overlay, and asserts the full chain: discussion auto-skip appends a discussionConsumed record to maic-runtime, the device cursor lands in KV, and both survive a fresh browsing context (empty sessionStorage). * refactor(playback): consumed-discussion state is volatile by decision — cursor-only persistence (#959) Product ruling on #869's fourth family: playback learner state is front-end ephemeral UX, not learner data. A re-shown proactive card auto-skips, joined discussions' content already lives in chat runtime records, and no replay export / analytics consumer exists — so durable facts bought nothing over in-memory + same-tab sessionStorage. Drop lib/playback/runtime.ts and the RuntimeStore facts wiring; keep the device-scoped KV resume cursor (the half with real UX value), the engine's consumption-time progress snapshot (cursor freshness), and the legacy Dexie retirement (cursor half migrates, row deletes, consumed ids are dropped). * fix(review): P3 pair from cross-review — scene-id boundary + sessionTransition 400 (#966) * fix(review): scene-id boundary for quiz context + 4xx for malformed sessionTransition (P3 pair) Review findings on #955: didActiveSceneRemainUnchanged compared the active scene by object identity, so a store update reallocating the scene during the async quiz read dropped the learner's graded answers from that turn's request — the scene id is the real boundary. The records route now classifies a malformed sessionTransition as a validation failure instead of letting the store's throw surface as a 500. * fix(playback): superseded-engine cursor guard + migration write-window recheck Second-vendor review of the #959 shrink (requested after the cross-review noted it had single-vendor coverage) found: an engine orphaned by a scene switch during async lecture resume could pass the idle-only recheck, be resurrected, and publish its old scene's progress over the new scene's debounced cursor — the resume continuation now requires identity with the installed engine, and onProgress drops snapshots from superseded engines. The legacy cursor migration also rechecks KV immediately before its write so a concurrent tab's newer cursor cannot be overwritten and orphaned by the legacy-row delete. Co-authored-by: Codex <codex@openai.com> --------- Co-authored-by: Codex <codex@openai.com> * fix(review): approval follow-up P3 nits (#967) * release: v0.3.1 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): approval P3 nits — ISO gate on sessionTransition, dead mocks, corrupt-timestamp guard - The records route's sessionTransition guard now requires an ISO updatedAt (isIsoTimestamp), matching the sibling PATCH /status route - Dead vi.mock factories for the deleted playback-storage module dropped - A corrupt legacy playback timestamp falls back to 'now' instead of wedging migration into a permanent re-throw that disabled resume --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Codex <codex@openai.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
84b1907255 |
feat(video-export): service-backed MP4 render + in-app one-click export (#866) (#937)
* feat(video-export): service-backed MP4 render + in-app one-click export (#866)
Adds the last mile of classroom video export: turning the self-contained
Hyperframes project ZIP (#865) into an MP4 via an isolated render service,
one-click in-app.
- render-service/: standalone Node 22 + Chromium + FFmpeg container wrapping
@hyperframes/producer's library API. Async job model (POST /render -> 202
jobId, GET poll, GET download, DELETE cancel). Swappable JobStore /
ArtifactStore seams (in-memory + local-disk now; Redis/S3 + presigned-302
download later) so it scales horizontally without changing the HTTP contract.
Concurrency + per-user guards are config knobs.
- App integration: thin Next proxy routes under app/api/export-video/* (forward
only, no rendering) + capability probe. use-render-video.ts uploads the ZIP,
polls via runPolledTask, downloads the MP4; shared buildExportZip prefix with
the existing ZIP path. Export menu gains resolution/fps/quality selectors and
a progress bar; degrades to ZIP download when RENDER_SERVICE_URL is unset.
- docker-compose: render-service under an opt-in "video-export" profile.
- Entry is main.ts (not server.ts): the producer auto-starts its own server on
:9847 when the process entry path ends with /src/server.ts.
Verified end-to-end in the container: rendered a real 640s (10.7 min) classroom
ZIP to a valid H.264 720p + AAC MP4 (duration matches source) in ~9.6 min
(~0.9x realtime, 4-worker frame capture). Degrade path, queued-cancel + cleanup,
and per-user 429 guard all exercised. pnpm check / lint / tsc / i18n pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(video-export): global render progress store, percent+ETA UI, ring on export button (#866)
Addresses two UX issues found while driving the in-app MP4 export:
1. Progress display was raw and unfriendly (showed producer's English stage
strings like "Capturing frame 5130/19220") and had no time estimate. Now the
menu shows only "<percent>% · about <remaining> left". ETA is computed from a
recent-speed estimate (percent-per-ms over the last sample), EMA-smoothed —
which tracks the render's non-uniform pace (prep -> frame capture with a
4->1 worker drop -> encode) far better than a whole-run average, and never
shows a stale/rising ETA.
2. Switching scenes mid-render unmounted the export menu and lost the progress
(and reset the local "already rendering" ref, allowing a duplicate submit).
The whole render lifecycle now lives in a global store
(lib/store/video-render.ts), so progress survives menu close / scene switch
and duplicate submits are guarded by status. A persistent CircularProgress
ring on the export button shows live progress whether or not the menu is open.
Also fixes the progress scale: the producer reports progress as 0..100, but our
HTTP contract (and success path) is 0..1 — the service now normalizes it, so the
client no longer showed "2000%".
- lib/store/video-render.ts: new global store owning submit->poll->download,
recent-speed ETA, duplicate-submit guard.
- lib/video-export-app/use-render-video.ts: thin facade over the store.
- components/ui/circular-progress.tsx: lightweight SVG progress ring.
- components/stage/{header-controls,video-export-menu}.tsx: ring on the export
button; menu shows percent + ETA, subscribes to the store.
- render-service/src/render-manager.ts: normalize producer progress 0..100 -> 0..1.
- i18n: percent/ETA strings across all 8 locales (drops the stage-based string).
- render-service/package-lock.json: complete integrity hashes (reproducible npm ci).
Verified: ETA logic checked against the real segmented render curve (worker drop
raises ETA, encode speedup drives it to ~0); progress scale fix confirmed live
against the container (0.2 -> 20%). tsc / lint / prettier / i18n pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(video-export): persist render options in the store, not the menu component
Selecting 720p/24fps/draft, switching scenes, and reopening the export menu
showed the defaults again (1080p/30/standard). The selections lived in the
VideoExportMenu component's local state, which reset when the menu unmounted on
a scene switch — the running render still used the chosen options, but the UI
misrepresented them.
Move resolution/fps/quality into the global video-render store (with a
setOptions action). The menu now reads/writes the store, so selections survive
menu close / scene switch, and while a render runs the selectors reflect the
options that render is actually using. startRender() reads options from the
store instead of taking them as an argument.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(video-export): deployment correctness + resource/isolation controls (PR #937 review)
Addresses the blocking findings from wyuc's review. Output fidelity was fine;
these harden deployment and production resource/isolation boundaries.
#1 Compose advertised MP4 but couldn't render in prod:
- Capability now probes the service's /health (checkRenderServiceHealth), so a
configured-but-absent service reports disabled and the UI degrades to ZIP
instead of 502-ing.
- RENDER_SERVICE_URL is operator-supplied trusted config, so the proxy no longer
runs it through the SSRF guard — the one-command `docker compose --profile
video-export up` now works without globally weakening SSRF via
ALLOW_LOCAL_NETWORKS. resolveRenderServiceUrl() is now synchronous.
- Client degrades to ZIP on any failed submit (not only 501).
#2 Unbounded upload/queue (ZIP-bomb / DoS):
- unzip.ts bounds the archive via fflate's filter BEFORE decompression: entry
count, per-entry and total expanded size, and compression ratio.
- Proxy rejects oversized uploads (413) by Content-Length before forwarding.
- RenderManager enforces a global queue-depth cap (RENDER_MAX_QUEUE).
- All limits are env-tunable knobs in config.ts.
#3 Per-user guard was ineffective + admission ran after extraction:
- Identity is derived server-side (client IP) and forwarded as x-openmaic-client;
the service ignores any client-supplied userId, and the proxy strips it.
- Admission is split into reserve()/submit()/release(): the slot is reserved
BEFORE extraction, so a rejected caller never triggers a decompression.
Additional risks:
- Per-job wall-clock watchdog (RENDER_JOB_DEADLINE_MS) aborts + fails a hung
render so it can't hold a slot/scratch forever.
- Download proxy bounds only the time-to-headers, not the body stream, so large
MP4s over slow links no longer truncate.
- Client cancels the server job (DELETE) when a started render fails/times out.
- Compose puts render-service on an internal:true network (no host/internet
route), sandboxing the Chromium that runs the uploaded HTML; the export ZIP is
self-contained so no outbound is needed. README documents the standalone caveat.
Not closing #866: the smoke/golden-render CI acceptance criterion remains a
follow-up (see PR description).
Verified in-container: legal render 202; ZIP-bomb (entry-count + compression-
ratio) rejected 400 before any decompression; per-identity guard 429 with a
spoofed multipart userId ignored; reserve-before-extract leaves no scratch dir
on rejection; watchdog aborts an overrunning job and frees the slot. tsc / lint /
prettier / i18n pass; render-service tsc passes.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(video-export): real audio durations + burned-in subtitles (PR #937 review)
Two export-fidelity issues found in wyuc's deeper E2E:
A. Narration was scheduled from estimated durations, cutting audio off mid-
sentence and advancing the timeline early. The scheduler trusted
AudioFileRecord.duration (recorded only since #861), so the many existing
classrooms without it fell back to text-length estimates — measured 4.35s
average / 10.23s max underestimate across 47 clips. timeline-deps now probes
the real duration from each narration blob via an off-document <audio>
(symmetric to the existing video probe), preferring it over the stored
duration, then the estimate only when no audio asset exists. Everything
downstream (narration starts, scene/total duration, subtitle cues) re-derives
from the corrected value in the pure compiler — no compiler change needed.
B. The final MP4 had no subtitles (only H.264+AAC), and the ZIP's SRT/VTT used
the same estimated boundaries. The emitter now renders a burned-in subtitle
overlay: one caption box + a hidden div per cue, revealed/hidden by the paused
GSAP timeline at each cue's start/end (corrected timings from A), so Chromium's
frame capture bakes them in. The producer has no subtitle track of its own, so
burn-in is the v1 approach.
Verified: emitter unit tests + snapshot updated (subtitle overlay + toggle
statements, escaped text, hidden-by-default); 82 video-export tests pass incl.
the determinism red-line proxy. Rendered a synthetic subtitle project through the
container and confirmed by pixel analysis that captions appear only within their
cue window (2429 near-white px in the caption band at t=1.5s vs 0 at t=0.05s).
tsc / lint / prettier / i18n pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(video-export): subtitle layout + upload/admission hardening (PR #937 review)
Address the three P1 blockers plus actionable P2s from the
|
||
|
|
bb8d4f30e7 |
feat(chat): add experimental Pi classroom runtime behind a flag (#914)
* feat(chat): add experimental Pi classroom runtime * fix(chat): harden Pi whiteboard action sequencing * style(chat): format session retirement flow * style(playback): format async scene transition * fix(chat): retire actions on session errors * fix(chat): close Pi runtime lifecycle gaps * fix(chat): avoid replaying historical whiteboard actions * fix(chat): prevent Pi structured-output residue from leaking and inflating turns Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(chat): expose whiteboard element/line ids and bound code-line context Surface each element's id (and code line ids) in the Pi whiteboard context so later child agents can target wb_delete / wb_edit_code, and cap the rendered code lines with a shared character budget so a code-heavy board cannot grow the prompt without bound. Return only the current turn's whiteboard ledger from the Pi director loop instead of carrying history forward across requests. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(chat): bound Pi whiteboard code context Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(chat): prioritize newer persisted whiteboard code in budget Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(chat): enforce whiteboard boundaries across Pi sessions * feat(chat): refine soft-closing discussion controls * fix(chat): make whiteboard clearing model-directed --------- Co-authored-by: apple <apple@GigideMacBook-Air.local> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: LING-6150 <duan.lin@northeastern.edu> |
||
|
|
65bf20a84b |
feat(runtime): cut chat sessions over to RuntimeStore (#926)
* feat(runtime): persist chat sessions in RuntimeStore * fix(runtime): harden chat persistence ordering * fix(runtime): protect cross-tab chat snapshots * fix(runtime): compare structured chat values safely * fix(runtime): preserve chat backup and reset semantics * fix(runtime): restore imported chat snapshots * fix(runtime): isolate chat load failures * fix(runtime): make cache clearing lossless * fix(runtime): normalize empty chat saves * fix(runtime): serialize legacy chat migration * fix(chat): serialize backup restoration * test(chat): cover multi-stage restore locking * fix(chat): coordinate fallback migrations across tabs * fix(chat): harden cross-tab migration locking * fix(database): retire abandoned chat lease schema * fix(chat): preserve monotonic local edits * fix(chat): protect unseen runtime sessions * fix(chat): order lifecycle transitions monotonically * fix(chat): serialize runtime maintenance * fix(chat): order queued writes before maintenance * fix(chat): preserve cross-version lock compatibility * fix(chat): preserve streamed and backup data * fix(chat): isolate empty no-lock saves * fix(chat): isolate partial runtime snapshots * fix(runtime): close cross-store cutover races * fix(runtime): close remaining cutover races * fix(chat): retain caller-visible conflict baseline * fix(chat): preserve read-only legacy autosaves * fix(chat): avoid restore lock inversion * fix(runtime): enroll writes before maintenance * fix(runtime): retain maintenance ordering * fix(runtime): close restore and deletion races * fix(chat): order partition queues within lock epochs * fix(chat): preserve recovery and deletion intent * fix(runtime): recover interrupted chat restores * fix(backup): scope chat deduplication by stage * fix(backup): stage chats by runtime partition * fix(backup): clear staged chats with stages |
||
|
|
d8a0081c7d |
feat(video-export): L1 Hyperframes emitter + browser collection + export ZIP (#865) (#931)
* feat(video-export): L1 Hyperframes emitter + browser collection + export ZIP (#865) Consume the VideoTimeline IR (#864/#913) and produce a self-contained Hyperframes composition project that `npx hyperframes render` turns into an MP4 (render execution itself is #866). - lib/video-export/emit-hyperframes: pure IR → Hyperframes project emitter (one flat composition, one paused GSAP timeline on window.__timelines, spotlight/laser overlays from lib/choreography descriptors). Stays under the purity boundary; emits HTML/JS strings only. - lib/video-export/subtitles: SRT/VTT serialization of the IR subtitle track. - lib/video-export-app: impure app glue (DI adapters over Dexie, slide-snapshot collection lifted from #849, streaming ZIP packaging, useExportVideo hook). - Vendor GSAP locally (public/vendor/gsap.min.js) — determinism red-line. - Export menu entry with resolution select + i18n across all 8 locales. Verified end-to-end against the real hyperframes CLI: lint passes 0 errors on a real classroom export, and a rendered slice produces a valid H.264+AAC MP4. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(video-export): gate Export Video menu behind NEXT_PUBLIC_ENABLE_VIDEO_EXPORT flag The video export UI is experimental until the render pipeline (#866) lands, so hide the "Export Video" affordance behind an off-by-default feature flag. - Add isVideoExportEnabled() to lib/config/feature-flags (NEXT_PUBLIC_, so it inlines at build time for the client-side export menu). - Gate the Export Video block in header-controls on the flag. - Cover the new flag in tests/config/feature-flags.test.ts. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): ossKey fallback for evicted blobs + emitter dedup Address code-review findings on #931. - collect: resolveBytes() prefers the local Dexie blob and falls back to the record's CDN ossKey (audio) / ossKey+posterOssKey (media/poster) so a live-mode classroom whose local blobs were LRU-evicted still exports a self-contained ZIP. timeline-deps presence checks widened to `blob.size > 0 || !!ossKey` so the compiler keeps these entries instead of marking them absent; video-duration probe stays local-only. - emit-hyperframes: extract one shared escapeHtml + sec into format.ts, dropping the two divergent escapers (attr vs escapeHtml) and the two sec() definitions with different rounding, plus the middle-man escapeAttr. Output is byte-identical (snapshot unchanged). - Add tests/video-export/collect.test.ts (ossKey fallback, local-first, fetch 404/throw, video+poster). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(video-export): restore evicted generated media into base-frame snapshots Address review blocker (P1) on #931: the ossKey fallback covered standalone audio/video/image/poster asset entries but not the slide base-frame path. resolveGeneratedMedia only accepted a non-empty local blob, so a live-mode record with an evicted blob + valid ossKey had its image src cleared (and video/poster not restored) before slideToPng snapshotted the slide — the frame PNG lost the generated media even though the standalone asset was fetched. - resolveGeneratedMedia now resolves bytes via resolveBytes (local blob first, then ossKey / posterOssKey) before creating the snapshot object URLs. - Add frame-collection tests: evicted image restored via ossKey, evicted video+poster restored, and image with no ossKey still cleared. The renderer snapshot is mocked so the frame path runs in plain Node. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn> |
||
|
|
e601eaa3d5 |
feat(pbl): cut learner state over to RuntimeStore (#922)
Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com> |
||
|
|
cc5a6ab152 |
feat(agent): edit_elements — NL → EditIntent vertical (#895) (#896)
* feat(agent): add edit_elements NL → EditIntent vertical (#895) Give the editing surface its first real consumer: natural-language per-element style/geometry edits flow through the same EditIntent vocabulary as pointer gestures, with an all-or-nothing validation gate and one undo entry per instruction. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(agent): harden edit_elements against CR findings (#895) Re-validate intents at apply time (atomic refuse on missing/locked ids), type-check prop values, require an open edit session for undo, clamp line stroke width correctly, enforce group cohesion, nest shape text chrome, and surface refuseReason on the tool card. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(agent): close remaining edit_elements CR residuals (#895) Feed apply outcomes into next-turn history and post-run chat corrections, phrase tool success as proposed-not-applied, and tighten gradient/filters/ enums/per-type value validation plus label-less shape text refusal. Co-authored-by: Cursor <cursoragent@cursor.com> * refactor(agent): derive edit_elements prop validation from the DSL schema (#895) Three review rounds each found a hand-written validator disagreeing with the DSL contract (a gradient pos range pinned at [0,1] against the percent contract, a textType enum matching the DSL in neither direction, per-type ownership gaps like vertical-on-shape and color-on-everything). Replace the class instead of the instances: - The gate now loads the dsl-generated JSON schema (@openmaic/dsl/schema/scene.schema.json) and validates every proposed prop value against the target element type's subschema via a compact schema-subset checker — per-type ownership, enums, and structured shapes (outline/shadow/gradient/filters) come from the single source of truth and stay correct as the DSL evolves. - Explicit policy layers stay on top: the content/identity blocklist (schema would allow what policy forbids), geometry clamps (coords, min sizes, line stroke width), and a numeric-range overlay for what plain number types cannot express — gradient stop pos is a percent in [0,100] (the previous [0,1] check refused canonical gradients and the unit test pinned the wrong contract), fontSize/lineHeight/radius bounds, filter value length, stop-count cap. - Consequences: color is refused on types that do not render it, with prompt guidance steering text color to defaultColor and shape body to fill; fill on charts is now allowed (the schema has it; the inventory already advertised it); textType accepts the full DSL enum. - Apply-time revalidation also refuses element-type drift via a gate-time targetElementTypes map carried in the tool details. - Refusal reasons render as visible card text, not only a hover title. - Test pins added for all of the above plus selection scoping, coord bounds, non-finite rotate, and empty batch/props. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(agent): harden the schema-derived gate — fail closed, assert schema source, unify numeric clamping (#895) - A schema construct the subset checker cannot judge (unresolved $ref, malformed anyOf, unsupported keywords) now refuses instead of accepting — the gate fails closed on the unknown. - A module-load assertion verifies the loaded dsl schema carries every definition the gate maps and a sane TextType enum, so a stale or missing build artifact fails loudly with a rebuild hint instead of validating an outdated contract silently. - Numeric-overshoot convention unified and documented: structural, enum, or ownership mismatches refuse (teaching the model the contract); numeric overshoot on a valid prop clamps (matching gesture behavior) — opacity now clamps like geometry. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(agent): localize edit element refusals (#895) * fix(agent): preserve partial element edit semantics (#895) * fix(agent): prevent stale element edit application (#895) * fix(agent): preserve live canvas edit invariants (#895) * fix(agent): close element style contract gaps (#895) * fix(agent): reject non-persistent element styles (#895) * fix(agent): preserve rigid group geometry (#895) * fix(agent): tolerate decimal group translations (#895) * fix(agent): constrain line height edits (#895) * fix(agent): reject stale or shadowed element edits (#895) * fix(agent): close renderer contract gaps (#895) --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com> |
||
|
|
9670100363 |
feat(extraction): media (audio/video) extraction + AliDocMind provider (#887)
* feat(extraction): add AliDocMind provider + media extraction abstraction Adds AliDocMind (Aliyun Document Mind LLM version) as a new vendor alongside unpdf/MinerU, and introduces the media (audio/video) extraction layer that mirrors the document extraction one. Document side (file: pdf/docx/pptx/xlsx/images): - PDF_PROVIDERS gains an `alidocmind` entry; parseWithAliDocMind() maps layouts[] -> ParsedPdfContent. Flows through the existing document extractor registry, so AliDocMind is selectable anywhere MinerU is. - PDFParserConfig / DocumentExtractorConfig gain accessKeyId/accessKeySecret (AliDocMind uses AK/SK, not a single apiKey); env fallback via ALIDOCMIND_ACCESS_KEY_ID / ALIDOCMIND_ACCESS_KEY_SECRET. Media side (mp4/mp3/wav/... -> MediaArtifact): - New lib/media-parse/ domain mirroring lib/pdf/ (types/constants/providers). parseMedia() maps AliDocMind segments[]/audio_frames/video_frames -> MediaArtifact (transcript + keyframes). - MediaExtractorProvider interface + media registry + extractMedia() entry, symmetric to DocumentExtractorProvider / extractDocument(). - MediaArtifact and the ExtractionResult/Artifact/Error/Job envelope live in lib/document/types.ts (re-exported from @/lib/document). Shared AliDocMind SDK wrapper (lib/pdf/alidocmind-client.ts) handles the submit -> poll -> get flow for both sides via @alicloud/docmind-api20220711. Tests: env-gated smoke test (tests/document/alidocmind.smoke.test.ts) drives a real PDF and a real video through AliDocMind; media-artifact type test; extractor-registry test updated for the new provider. Part of #621 (MAIC ETL). Media extraction is the sibling to the document extraction landed in #741. * feat(extraction): wire AliDocMind AK/SK through settings UI + routes Surfaces AliDocMind in the (post-#837) Document Parsing settings panel as a peer of unpdf/MinerU — one panel, one credential entry, more supported formats. Threads Aliyun AccessKey ID/Secret from the store through the extraction routes. - Store: pdfProvidersConfig + setPDFProviderConfig gain accessKeyId/accessKeySecret; default alidocmind entry added. - pdf-settings.tsx: AliDocMind branch renders AccessKey ID + Secret inputs (secret masked with show/hide) and a Test Connection button; request-URL preview shows the DocMind endpoint. Provider auto-appears in the panel via PDF_PROVIDERS; supported-format badges come from #837's registry (ALIDOCMIND_MIMES added to lib/document/mime.ts). - verify-pdf-provider route: alidocmind branch verifies AK/SK via a lightweight authenticated probe (verifyAliDocMindCredentials) — auth-level errors fail, anything else passes. - extract-document route + generation flow (app/page.tsx, generation-preview): accessKeyId/accessKeySecret carried through session → FormData → config. - i18n: alidocmindAccessKeyId / alidocmindAccessKeySecret in 8 locales. - Icon: reuse /logos/bailian.svg (Aliyun family) instead of a missing asset. Verified end-to-end against the running app: AliDocMind panel renders, Test Connection returns "连接成功" through the real Aliyun API. Part of #886. * feat(extraction): route audio/video uploads through extractMedia() (reuse document path) Media uploads now flow through the same upload picker, /api/extract-document route, and generation pipeline as documents — no separate upload area. Only the extraction differs: media mimes dispatch to extractMedia() -> MediaArtifact, which is flattened to the text shape the generation pipeline already consumes. - mime.ts: register audio/video formats in DOCUMENT_FORMATS (accept string, extension map, badges resolve for them); add MEDIA_PROVIDER_SUPPORTED_MIME_TYPES + SUPPORTED_MEDIA_MIME_TYPES, kept separate from PROVIDER_SUPPORTED_MIME_TYPES so the document drift-guard stays document-only. mimesForProviders() folds in a provider's media mimes, so the existing upload helpers (getAcceptStringForProviders / isMimeSupportedByProviders / format badges) cover media automatically when the provider supports it. - extract-document route: media mimes dispatch to extractMedia(); MediaArtifact flattened to timestamped text (synopsis + transcript + keyframes). - Tests: 6 media cases in mime.test.ts (accept/validation/badges/normalization). Verified: uploading a real video through the route returns synopsis + timestamped transcript/keyframes as text (curl, real AliDocMind key). Part of #886. * feat(extraction): use Alibaba Cloud icon for AliDocMind provider Replace the placeholder bailian.svg with a dedicated Alibaba Cloud icon mark (the square symbol from the official wordmark, text removed) so the provider reads as Aliyun rather than Bailian. Square aspect matches the other provider icons. Source: Alibaba Cloud / Alibaba Group brand assets. * style: prettier format AliDocMind + media extraction files * fix(extraction): harden AliDocMind — SSRF guard, cred verify, env gate, table text Addresses review findings on the AliDocMind provider: - SSRF (high): the media branch of /api/extract-document now runs the same validateUrlForSSRF check on a client-supplied baseUrl as the document branch, so an audio/video upload can't point the server's Aliyun SDK at an internal host. - Credential verify (high): verifyAliDocMindCredentials now whitelists success signals instead of blacklisting auth errors. Probed against the real API: valid creds + bogus job returns a no-throw "BizIdNotExistOrResultExpired" body; invalid creds throw InvalidAccessKeyId.NotFound. Only a no-throw response or a "biz-not-found" business error counts as valid — an unreachable endpoint, a localized error, or throttling now correctly reports failure instead of a false "connection successful". - Env-fallback gate (med): resolveCredentials no longer reads ALIDOCMIND_ACCESS_KEY_ID/SECRET unconditionally. Env fallback is opt-in via allowEnvFallback, which the route sets only for a server-managed provider, so an unauthenticated client request can't silently run on the server account. - getDocParserResult error body (med): fetchResult throws on a non-200 result envelope instead of returning {} (empty text presented as success). - Media pagination (med): stop after the first page when segments[] are present — layoutNum/layoutStepSize address layout blocks, not media segments, so re-requesting would loop over the same segments to the safety cap. - Table content (med): tables/charts carry content in llmResult, not markdownContent; the layouts→text mapping now prefers llmResult for those types so table content isn't dropped (tables: true was advertised). - Dead code: remove getCurrentMediaParseConfig (referenced non-existent store fields; the single-panel UI reuses pdfProvidersConfig). - Dedup: media MIME list lives only in lib/document/mime.ts (ALIDOCMIND_MEDIA_MIMES); the media registry imports it. - Tests: smoke test asserts durationMs is in ms (>1000 for a ~52s clip) to guard a ms/s unit mismatch; uses allowEnvFallback for the env-cred path. Verified with the real key: PDF + video smoke tests pass; verify classifies valid vs invalid creds correctly. Part of #886. * feat(extraction): extract AliDocMind images to base64 (parity with unpdf/MinerU) AliDocMind embeds figure/picture image URLs inside each layout's markdownContent (markdown ``), not a dedicated field, and the URLs are short-lived OSS signed links. Previously we emitted `images: []` and left the expiring URLs inside the extracted text. Now, for figure/picture layouts we: - parse the OSS image URL out of markdownContent, - fetch it at extraction time (before the signature expires) and re-encode to PNG base64 via sharp — the same base64 `images[]` contract unpdf/MinerU produce, so downstream storeImages → IndexedDB → slide works unchanged, - populate metadata.pdfImages + imageMapping (the generation flow prefers pdfImages), - strip the remote-URL markdown from the emitted text so expiring links don't leak into the prompt. Downloads run concurrently; a failed/`sharp` image is dropped, never failing the whole parse. Also fixes the prior over-broad table handling: only `table` blocks read llmResult; `figure` is treated as an image (chart-figure llmResult still kept in text). Verified with the real key: a sample PDF yields 24 base64 images in both images[] and metadata.pdfImages, and no oss-cn-hangzhou URLs remain in text. Part of #886. * docs(test): note AliDocMind video smoke test is non-deterministic server-side * fix(extraction): correct AliDocMind pageCount (pageNum is 0-based) Verified against a real response: AliDocMind reports pageNum 0..13 and pageCountEstimate 13 for a 14-page document — both are 0-based. The metadata pageCount previously used pageCountEstimate directly, undercounting by one. Use the already-1-based maxPage, falling back to pageCountEstimate+1 only when no blocks were seen. Document the 0-based convention at the normalization site. * fix(extraction): address AliDocMind review — verify/SSRF/config/media (P1+P2) Resolves all P1/P2 findings from the cross-review on #887. P1 (blocking): 1. verifyAliDocMindCredentials now inspects the no-throw response body.code. An OSS-only key returns NoPermission without throwing; previously that was green-lit as "connection successful" then failed at extraction. Only a success/200 or the job-not-found probe code is accepted. Deterministic mocked test added (tests/document/alidocmind-verify.test.ts). 2. verify route trust boundary: managed → server-owned AK/SK + default endpoint only (ignore client values); unmanaged → client creds only, never env fallback, and the client endpoint is SSRF-validated before signing. 3. image fetch hardened: restricted to Aliyun OSS hosts, redirects disallowed, per-image byte cap, image-count cap, bounded concurrency (was unbounded Promise.all over provider-returned URLs). 4. AliDocMind is now selectable in the generation toolbar — availability recognizes the AK/SK pair, not just apiKey. P2 (correctness): 5. Explicit server-config for the AK/SK pair (applyAliDocMindFallback + resolveManagedAliDocMindCredentials); verify and extract now resolve managed/env identically instead of verify-uses-env / extract-rejects. 6. Poll loop checks body.code before status, so a body-level error (e.g. NoPermission) fails fast instead of retrying for the full 15 min. 7. Image page numbers preserved through fetch/filter — no longer hard-coded to page 1, so multi-page image→page association is correct. 8. Empty media extraction (no synopsis/transcript/keyframes) returns 422 PARSE_FAILED instead of HTTP 200 with empty text. 9. Format matrix trimmed to the official contract: images JPG/JPEG/PNG/BMP/GIF (dropped WebP/JP2), media MP4/MKV/AVI/MOV/WMV/MP3/WAV/AAC (dropped M4A). 10. A document-only provider (unpdf/mineru) uploaded with a media file now returns a clear 4xx instead of an opaque 500. P3: credential-verify failures return INVALID_CREDENTIALS 4xx (not INTERNAL_ERROR 500); formatTimestamp emits HH:MM:SS past one hour. Verified with the real key: verify classifies valid→ok and invalid→fail; PDF (24 images, correct page numbers) and MP4 extraction pass end-to-end. * fix(extraction): make AliDocMind selectable + correct analysis label for media Two UI/UX fixes found while manually testing the AliDocMind flow end-to-end: - Persisted-state backfill: add ensureBuiltInPDFProviders so a PDF/document provider added after a user's settings were persisted (AliDocMind) is backfilled into pdfProvidersConfig on rehydrate. Without it the provider never appeared in the store, so it couldn't be selected and never picked up its server-configured flag. Wired into both persist migrate() and merge(), mirroring the existing image/video/web-search backfills. - Analysis step label: getGenerationStepText showed "解析 document 文件" for audio/video (the type map fell through to the literal "document"). Documents keep their precise token (PDF/DOCX/PPTX/XLSX/images); audio/video now use a dedicated, locale-correct string (generation.analyzingMediaMaterial, added to all 8 locales) instead of forcing a format token into the "{{type}} 文件" template. Manually verified end-to-end (real key): PDF, MP4, and MP3 (audio extracted from the sample video) each extract and drive full course generation; a DocMind-restricted AK/SK (OSS-only) now correctly fails verification with NoPermission (400) instead of a false "connection successful". * fix(extraction): address 2nd-round AliDocMind review (managed creds, stream cap, empty verify) Resolves the three follow-up findings on #887: 1. [P1] YAML-managed AliDocMind creds now reach extraction. Both extract paths (document + media) previously cleared the managed AK/SK and relied on an env-only fallback, so a YAML-only deployment verified but failed to extract. They now resolve server-owned creds via the shared resolveManagedAliDocMindCredentials() (env OR YAML), matching the verifier. Regression test added for YAML-only creds with no ALIDOCMIND_* env. 2. [P1] Image download is now size-capped while streaming. Instead of buffering the whole response and checking length afterward, the body is read chunk by chunk with a cumulative byte count that aborts the moment it exceeds the cap — a missing/false Content-Length can no longer exhaust memory. Host allowlist tightened to oss-*.aliyuncs.com. Tests: non-OSS host refusal, no-Content-Length overflow abort, declared-oversize rejection. 3. [P2] Empty verification body no longer counts as success. Removed the codeStr === '' branch from the positive-signal whitelist (a working key always returns the job-not-found business code for the bogus probe id). Regression test added for empty and absent bodies. Rebased onto main (package.json: kept @openmaic/storage + AliCloud deps). Verified with the real key: PDF + MP4 extraction still pass end-to-end. * fix(extraction): merge AliDocMind AK/SK into a baseUrl-configured YAML entry Follow-up to the YAML-managed credential fix. When a YAML `pdf.alidocmind` entry also specifies `baseUrl`, the generic loadEnvSection() (pdf requires a baseUrl) creates the pdf.alidocmind entry copying only apiKey/baseUrl/models/ proxy — never AK/SK. applyAliDocMindFallback() then returned early because the entry already existed, so the provider was "managed" but had no usable credentials, and resolveManagedAliDocMindCredentials() returned undefined (verify + extract both silently lost the creds). Merge the AK/SK into the existing entry instead of returning early. Added a regression test with baseUrl + accessKeyId + accessKeySecret together (the previous test omitted baseUrl, so the generic loader skipped the entry and the bug was masked). * fix(extraction): don't mark AliDocMind managed without AK/SK; align poll code check Two edge cases from a follow-up adversarial pass: - [MED] A YAML `pdf.alidocmind` entry with `baseUrl` but no AK/SK (and no env AK/SK) made the generic loader create the entry → isServerConfigured=true (managed) → but resolveManagedAliDocMindCredentials() returned undefined, so the provider was locked out AND client-entered AK/SK were silently dropped. applyAliDocMindFallback now deletes a credential-less entry so the provider stays UNMANAGED (clients supply their own creds). Regression test added. - [LOW] verify accepted a `code: "success"` body but the extraction poll loop threw on any non-"200" code — a success-shaped status would pass verification then fail extraction. The poll loop now treats "200"/"success" as benign, matching verifyAliDocMindCredentials. --------- Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn> |
||
|
|
6f7ffa8302 |
chore: tighten GitHub issue intake (#921)
* chore: tighten issue intake * fix: address issue intake review feedback * test: preserve scene selectors in pro mode --------- Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com> |
||
|
|
40ff80ab63 |
feat(editor): add draggable insert toolbar (#912)
* feat(editor): add draggable insert toolbar * fix(editor): improve toolbar accessibility * fix(quiz): update empty-state guidance * fix(settings): sanitize retired toolbar state * fix(editor): keep hints from blocking controls * fix(editor): refine toolbar and hint interactions * fix(editor): preserve toolbar position across scenes --------- Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com> |
||
|
|
c56929510c |
feat(web-search): add SearXNG provider support (#842)
* feat(web-search): add SearXNG provider support Enable self-hosted SearXNG via SEARXNG_BASE_URL, with server-side provider fallback, settings sync, and tests. Co-authored-by: Cursor <cursoragent@cursor.com> * style: fix Prettier formatting in web-search files Restore pnpm check by applying Prettier to imports, headers, and test assertions. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web-search): keep SearXNG base URLs server-managed only Close the SSRF primitive by ignoring client-supplied SearXNG URLs at the route boundary and rejecting them in resolveSafeClientWebSearchBaseUrl. Add negative route/config tests and an opt-in live smoke test for the JSON API. Co-authored-by: Cursor <cursoragent@cursor.com> * style: fix Prettier formatting for SearXNG web-search changes Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: 徐松 <song.xu@aieshanghai.com> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
3b63710376 |
feat(ai): add Azure OpenAI provider (#916)
* feat(ai): add Azure OpenAI provider Add deployment-based Azure OpenAI configuration for both client and server-managed setups, normalize Azure portal endpoints, and expose the provider in settings. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b0d3a94f-089a-470e-9987-608f1506ca6f * style: format Azure provider type Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b0d3a94f-089a-470e-9987-608f1506ca6f --------- Co-authored-by: MarshellOnMoon <121332425+MarshellOnMoon@users.noreply.github.com> |
||
|
|
6e9dcf45b6 | fix(roundtable): cap non-presentation input height (#917) | ||
|
|
baff0998bb |
Feat/document bundles milestone 3 (#844)
* feat(document): support document bundles * fix(document): avoid server extractor imports in client bundle * fix(pdf): default mineru backend to pipeline * fix(document): address bundle review findings * fix(document): harden extraction limits and storage errors * fix(document): make analysis step format agnostic --------- Co-authored-by: Rowan_lxb <Lxb_savior@163.com> |
||
|
|
c8a638a101 |
feat: support GPT-5.6 model family (#907)
* feat: support GPT-5.6 model family * test: cover GPT-5.6 SDK validation * fix: canonicalize GPT-5.6 Sol alias * fix: complete GPT-5.6 alias lookups --------- Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com> |
||
|
|
50d3abc32e | fix(chat): preserve message line breaks (#908) | ||
|
|
e136c81c03 |
chore(generation): remove dead legacy pipeline chain (#904) (#905)
Remove the generation-pipeline leftovers orphaned since the old
/api/generate route was deleted in
|
||
|
|
ce89b4c314 |
fix(home): clarify Interactive Mode selected state (#901)
* fix(home): clarify interactive mode selected state * fix(home): soften light interactive mode state * fix(home): honor reduced motion in dark mode * test(home): assert current interactive mode styles --------- Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com> |
||
|
|
7fffec78f6 |
feat(choreography): shared orchestration spec in lib/choreography (#863) (#890)
* feat(choreography): shared orchestration spec in lib/choreography (#863) Introduce lib/choreography/ as the single source of truth for the orchestration semantics a faithful classroom-video exporter needs from playback, so the app runtime and the exporter interpret one spec instead of each re-implementing (and silently drifting from) the other. Kept in lib/ rather than a package: these semantics co-evolve with the playback engine, and the exporter will also live in the app, so both consumers share them via ordinary imports. Purity is machine-enforced by an eslint boundary on lib/choreography/** (blocks @/ host-app paths + react/react-dom/gsap/framer-motion/motion), so the exporter can interpret the spec in a pure Node environment. - timing.ts — timing constants + the deterministic no-audio speech estimate, moved verbatim from the engines. - cursor.ts — resolvePlaybackCursor + EMPTY_SCENE_DWELL, moved from lib/playback/engine-cursor.ts (typed on dsl SceneCore). - timeline.ts — new pure resolveActionTimeline: index-domain -> time-domain expansion (blocking cursor-advance vs fire-and-forget visual duration), keyed off the DSL fire-and-forget partition. - descriptors/— versioned, zod-schema-validated animation descriptors spotlight.v1 + laser.v1 (declarative: property/from/to/ duration/easing; no implementation), pinned to the current overlay components. Behavior-neutral engine refactor: lib/action/engine.ts and lib/playback/engine.ts import from lib/choreography and the local literals are deleted, so the timing dimension now has exactly one copy. The spotlight/laser overlay components still hardcode their animation values (they do not yet READ the descriptors) — tracked in #889. Closes #863 * fix(choreography): address cross-review findings on resolveActionTimeline + descriptors - P1: model implicit whiteboard auto-open — a wb_* mutation on a closed board now prepends a synthetic IMPLICIT_WB_OPEN (WB_OPEN_MS) beat, mirroring the engine's ensureWhiteboardOpen; open state carries across scenes and toggles on wb_open/wb_close (new `whiteboardOpen` option to seed it). - P2: scale real speech audio duration by playbackSpeed too (live path sets AudioPlayer.setPlaybackRate), keeping it in lockstep with the estimate path. - P2: express the spotlight mask relationship in the descriptor model — LayerSchema gains `role` ('content'|'mask') + `maskedBy` (subtract|intersect); spotlight.v1's cutout is now a mask layer the dim layer subtracts, so a non-React consumer reconstructs the cutout instead of a black rect. - P3: wb_clear on an empty board is 0ms (engine early-returns), not wbClearMs(0). Tests: tests/lib/choreography 45 pass (+6); engine regression 28 pass; tsc + lint clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(choreography): address final-audit findings on effect lifetime + spotlight descriptor Second cross-review round (fresh-session codex final audit) surfaced three deeper mismatches with live playback: - P1: fire-and-forget effect lifetime is not a flat EFFECT_AUTO_CLEAR_MS. The engine's processNext clears effects at every scene boundary and on completion, and scheduleEffectClear uses one shared timer each new effect resets. Added clampFireAndForgetLifetimes: an effect's visual durationMs is now min(next scene boundary / completion, shared-timer deadline chained through later effects in the same scene). advancesCursorMs (0) is untouched. - P2: spotlight dimness default is 0.5 (executeSpotlight: dimOpacity ?? 0.5; DSL documents 0.5), not the component's unreachable ?? 0.7 fallback. Fixed the descriptor param + test. - P2: model the spotlight wrapper's enter/exit opacity fade (motion.div, no explicit duration → engine default). TrackSchema.durationMs is now optional to express "use the consumer's engine default"; dim layer carries the fade tracks. Tests: tests/lib/choreography 50 pass (+5, incl. boundary-cut / completion-cut / full-lifetime / shared-timer-extension / wrapper-fade); engine regression 28 pass; tsc + lint clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(choreography): pin spotlight fade duration + laser dot geometry in descriptors Third cross-review round (codex) flagged two descriptor-completeness gaps that would make a non-Motion consumer (the exporter) diverge from the app: - Spotlight wrapper fade: the enter/exit opacity tracks left durationMs implicit (Motion default). A literal consumer treats a missing duration as instant, so the spotlight would pop on/off. Pinned to Motion's default 300ms tween. - Laser dot geometry: the descriptor captured only tracks, not the dot group's center anchor (translate -50%,-50%) or the rounded-full ring/core. A literal renderer would draw an offset 10px square. Added the static geometry (anchor, borderRadius 9999, ring inset/position) so the shape/position match the app. Also refined the effect-lifetime docstring to cite the app's per-scene engine teardown/completion (the actual clearEffects path) rather than an intra-engine boundary gate that is dead in the single-scene-per-engine configuration. The empty-scene "speech dwell → blank chat bubble" observation is pre-existing behavior: EMPTY_SCENE_DWELL is a verbatim move from lib/playback/engine-cursor.ts (unchanged from origin/main), out of scope for this move-only PR; tracked separately. Tests: tests/lib/choreography 54 pass; engine regression 28 pass; tsc + lint clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(choreography): zero-duration for engine-skipped/no-op actions in timeline Fourth cross-review round (codex) flagged two remaining timeline divergences: - Skipped discussions: the engine skips a discussion outright (no timer) when it's already consumed or its agent isn't selected, but the timeline always charged DISCUSSION_TRIGGER_DELAY_MS. Added `isDiscussionSkipped` resolver (runtime-state-dependent, like getVideoDurationMs) → 0ms when skipped. - No-op whiteboard draws: executeWbDrawText (empty content) and executeWbDrawTable (no rows/cols) return before any delay. The timeline now charges 0ms for these determinable-from-the-action no-ops instead of WB_DRAW_MS. (KaTeX-failure / missing-edit-target no-ops depend on runtime state and remain out of scope, consistent with the resolver pattern.) Tests: tests/lib/choreography 56 pass; engine regression 28 pass; tsc + lint clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(choreography): exact-5s effect chain break + spotlight dim full-screen geometry Fifth cross-review round (codex), both P2: - Effect chain break at an EXACT 5s boundary: the earlier effect's clear timer is queued before the reading timer that triggers the later effect (same 5000ms delay), so it fires first — the predecessor is cleared at exactly deadlineMs, not extended. Changed the chain guard from `> deadlineMs` to `>= deadlineMs`. - Spotlight dim layer full-screen geometry: the descriptor recorded only fill + mask relation, leaving a literal consumer no way to know the dim rect spans the 0..100 viewport. Added explicit x/y/width/height (100×100 at origin) so the descriptor is self-contained. Tests: tests/lib/choreography 57 pass; tsc + lint clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(choreography): no-op wb_edit_code resolver in timeline Sixth cross-review round (codex), one P2: executeWbEditCode returns before its delay when the edit can't apply (missing/non-code target, stale line refs). The timeline always charged WB_EDIT_MS. Added `isEditCodeNoop` resolver (runtime- state-dependent, same pattern as getClearElementCount / isDiscussionSkipped) → 0ms when the caller flags a no-op. Tests: tests/lib/choreography 58 pass; tsc + lint clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(choreography): descriptor layer inheritance for nested effect layers Seventh cross-review round (codex), two P2 with one root cause: the flat layers[] model couldn't express a child layer riding a parent's animation (the source nests some layers inside an animated wrapper). Added an `inheritsFrom: {parentId, props}` relation to LayerSchema: - Laser ring + core inheritsFrom the animated `dot` (left/top/opacity), so a literal consumer flies them in/out with the dot instead of leaving them at a static origin while only the dot moves. - Spotlight border inheritsFrom `dim` (opacity), so the outline fades out with the wrapper instead of lingering after the dimming layer disappears. Tests: tests/lib/choreography 60 pass; tsc + lint clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(choreography): address review — discussion auto-skip, explicit video policy, import allowlist Human review (wyuc) raised two blocking timing issues + one non-blocking guard: - Discussion dwell (blocking): a non-skipped discussion in unattended playback/export blocks for the trigger delay AND the ProactiveCard's own auto-skip countdown, not just DISCUSSION_TRIGGER_DELAY_MS. Added DISCUSSION_AUTO_SKIP_MS (5000) to the timing spec and charge DISCUSSION_TRIGGER_DELAY_MS + DISCUSSION_AUTO_SKIP_MS. ProactiveCard now reads the same constant (was a hardcoded 5000), so card countdown and timeline can't drift. A `spotlight -> discussion -> speech` timeline now extends the spotlight across the full discussion interval. - play_video (blocking): an unresolved duration no longer silently becomes a 0ms segment (which shifted every later action early). New `onUnresolvedVideoDuration` policy defaults to 'throw' (fail loudly); 'cap' assumes MAX_VIDEO_WAIT_MS, 'zero' opts back into no-dwell explicitly. - Purity guard (non-blocking): turned the lib/choreography boundary into a true import allowlist. Beyond the existing @/… + render-package blocks, it now rejects parent-escape (../…) imports/re-exports, any bare package other than @openmaic/dsl / zod, and dynamic import()/require(). Negative-tested: ../store, a stray bare package, export * from ../playback, and import('react') all fail. Tests: tests/lib/choreography 60 pass; engine regression 28 pass; tsc + lint clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn> |
||
|
|
5627b99156 |
feat(pbl): runtime-event outbox + dual-write into the RuntimeStore (#869 Part C, step 2) (#893)
* feat(pbl): emit typed runtime events from every learner-state mutation (#869) The outbox half of the runtime split: pure operations append typed PBLRuntimeEvents to project.runtimeEvents (ring-capped at 500, dedup by id) for every learner-state mutation — messages, submissions, evaluations, status changes across project/milestone/microtask/uiPhase, handover and task-completion gates, and proficiency updates. Emission stays inside the pure mutators (no I/O), so events cross the stateless server boundary inside the project; a client-side drainer (next commit) copies them into the RuntimeStore. Zero read-side changes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(pbl): drain the runtime-event outbox into the RuntimeStore (#869) Client-only drainer: after each persisted project change, copy new runtimeEvents into the learner's active 'pbl' RuntimeSession (created lazily), watermarked per stage through the device-scoped KV. Mid-drain failures persist the last-success watermark and retry next tick; a watermark evicted from the ring-capped ledger redrains visible events (documented at-least-once — downstream folds dedup by event id). The whole drain is bounded and never throws into the save path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(pbl): dual-write engagement events; end-to-end outbox coverage (#869) The drainer now copies both in-project ledgers — runtimeEvents and engagementEvents — into the learner's pbl RuntimeSession, with independent watermarks that advance separately (a failure in one ledger never loses the other's progress). End-to-end test drives real operations through the reducers and drains into a real BrowserRuntimeStore over fake-indexeddb, asserting the full ordered event trail with correct anchors. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pbl): harden the outbox drain per cross-review (#869) - Watermarks scope to (stageId, sceneId, learnerKey): multi-scene stages and multi-learner devices no longer cross-contaminate or redrain. - First-session creation is race-free: deterministic session id (pbl-<stageId>-<learnerKey>) with already-exists fallback plus an in-flight memo, so concurrent drains cannot split one history. - A corrupt watermark value degrades to a fresh redrain and is repaired on the next persist, instead of permanently blocking the drain. - Stage deletion clears its drain watermarks alongside the runtime rows. - resetProjectProgress emits a project_reset epoch marker so folds never resurrect pre-reset submissions/evaluations from the preserved ledger. - Normalization repairs use deterministic event ids, collapsing echoes from cloned-copy re-normalization under id-dedup. - Docs: ring-overflow latent-loss window (dual-write accepts it; the read-flip backfills from a projectV2 snapshot) and the fold-baseline contract (status 'active' / uiPhase 'hero' from design-time defaults). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pbl): carry server-minted events across the advance patch (#869) Two holes on the server-patch path: applyAdvanceProjectPatch computed status-change 'from' values after Object.assign had already replaced the milestone snapshot (suppressing every real Instructor-advance event as from===to), and events minted server-side during advanceMicrotask (e.g. handover_staged) lived only on the transient server copy — the advance patch carried no runtimeEvents, so the client ledger never drained them. Patches now carry the operation's event delta; the client appends them first, and both sides mint deterministic patch:* ids for the same transition so echoes collapse under id-dedup. Server-side facts are authoritative; client emissions remain as a compatibility fallback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pbl): scope deterministic event ids to the reset epoch (#869) Deterministic norm:/patch: status-event ids now lead with the count of project_reset events visible in the ledger, so a learner repeating the same transition after a reset is recorded instead of deduped against the pre-reset event. The epoch is derived from the same visible window the id-dedup scans, so ring-buffer eviction can never desynchronize the two. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(store): drain debounced saves before teardown (#869) setStageAgents schedules debouncedSave + debouncedSaveAgents; tests that finished without flushing left timers firing after environment teardown, lazily importing the settings/providers chain into a torn-down runtime (deterministic on CI once this branch grew the stage-storage import graph). Store tests now run fake timers and assert zero pending timers at teardown; the same latent race in the insert-scene-after and generation-complete suites is fixed in the same style. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pbl): address review — durable epoch, id-set deltas, ordered drain, post-save signal (#869) - runtimeResetEpoch is a monotonic project field incremented on reset, never derived from the ring buffer, so evicting an old reset marker can no longer collapse post-reset transitions into pre-reset ids. - Advance patches capture their event delta by id-set difference, not array index, so cap eviction mid-operation cannot drop server events. - The drainer merges both ledgers into one timestamp-ordered stream (stable within each ledger) before appending, so RuntimeStore seq preserves global chronology instead of ledger-grouped order. - Draining now subscribes to a post-save signal emitted after saveToStorage commits, instead of firing on the in-memory update — the dual-write can no longer outrun the source-of-truth persistence. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(pbl): drain the persisted snapshot, decoupled from scene mounting (#869) The post-save signal now carries the PBL scenes exactly as persisted; a module-level singleton subscription drains them, replacing the component-ref hook. Navigating away before the debounced save fires no longer strands the saved scene's outbox, and an in-flight save can no longer drain a newer unsaved snapshot. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
a2886af92a |
Added ComfyUi to has Image Provider (#850)
* feat: integrate comfyui workflows into image provider selection * style: format code with prettier * fix: align i18n keys for russian locale * feat: implement requested changes and format code * feat: implement requested changes including renaming default workflow --------- Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn> |
||
|
|
b5e1963e48 |
feat(document): rename to Document Parsing, show supported formats, extend MinerU support
Squashed from PR #837 after review approval and green CI. |
||
|
|
d00795094c |
feat(playback): add action-level navigation (#843)
Squashed from #843. Adds Notes click-to-jump action navigation and action-level playback resume/restore, with visible toolbar sentence controls removed after review. |
||
|
|
ee626121cd | fix(slide): tolerate malformed generated slide data | ||
|
|
6b93980f82 |
feat(editor): redesign the narration timeline (action picker + inline insert) and enable it for interactive/PBL scenes (#834)
* feat(editor): enable narration timeline for interactive/pbl scenes * docs(editor): fix stale timeline-gating comment in EditChromeRoot * i18n(editor): add action-picker + addAction strings * feat(editor): pure pickerOptions filter for the action picker * feat(editor): ActionPicker popover (shared by header pill + inline +) * feat(editor): header add-action pill opens ActionPicker; drop drag-chips * feat(editor): inline + insert between cells opens ActionPicker * style(editor): reskin SpeechClip + TTS footer to Pro Mode v2 * style(editor): align discussion dash tint to neutral primary token Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * style(editor): reskin CueMarker (bound label) + DiscussionClip + NodeDot * fix(editor): complete picker i18n locales, label inline insert button, use primary token - Add edit.timeline.addAction and edit.picker.{title,speechDesc,spotlightDesc,laserDesc,discussionDesc} to zh-TW, ja-JP, ko-KR, ru-RU, pt-BR, ar-SA locale files, mirroring the existing en-US/zh-CN structure. - Give the inline "+" insert button in ActionsBar's DropZone an accessible name (aria-label + title) by threading an insertLabel prop from the root component, which already has the translator. - Replace the raw bg-violet-500 active-divider glow in DropZone with the bg-primary token. * chore(editor): drop dead drag-to-add path and orphaned i18n keys, explain disabled discussion option * style: format picker-options with prettier --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
0b1304fe0c |
fix(editor): show per-line loading while the batch "regenerate all TTS" runs (#830)
Clicking the batch "regenerate all TTS" control (the timeline's "voice all" button) only set a global in-flight flag and spun the button; each speech line's status row (preview / regenerate) kept showing its old status, so the batch gave no per-line feedback — even though the single-line regenerate path shows a "generating" state. Track the ids being regenerated in ActionsBar and pass a `regenerating` flag down to each SpeechTtsBar; while set, the line shows the generating state (spinner + disabled buttons) and the single-line regenerate is disabled (no concurrent double-regen). To avoid a ~1-frame flash back to the "not voiced" status at batch end (the parent flag clears before the async audioExists re-check resolves), each line latches a `batchPending` flag on the rising edge of `regenerating` (adjusted during render, not in an effect) and clears it inside its own audio re-check effect. The clear is guarded by `!regenerating` (and `regenerating` is an effect dep, so a stale pre-batch check is cancelled at batch start), so only the batch-end re-check clears the latch. The re-check is wrapped so an IndexedDB rejection still clears the latch (the row can never wedge in the generating state), and ttsRefresh is always bumped in the finally so every line re-checks at batch end, including the all-fail case. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
d54e62f5c4 |
feat(token-plan): one-click token-plan setup + deployment usage dashboard (#784)
* feat(usage): add usage normalization, pricing, model-fetch, balance, storage Foundational layer for token-plan usage tracking (cc-switch-modeled): - lib/usage/normalize.ts: AI SDK v6 usage → four-class token shape - lib/usage/pricing.ts + defaults: per-class USD pricing table - lib/server/model-fetch.ts: /models candidate-URL multi-fallback (ported) - lib/usage/balance-providers.ts: built-in balance queries + detection - lib/server/usage-storage.ts: fire-and-forget jsonl logging to data/usage All pure/storage logic covered by vitest (32 tests). * feat(usage): capture token usage at the callLLM/streamLLM chokepoint - callLLM records result.usage before returning - streamLLM wraps onFinish to record totalUsage on stream completion, preserving any caller-supplied onFinish - provider/model derived from the model instance (no route changes) - fs-backed storage imported dynamically; fire-and-forget, never throws - include_usage is already sent by @ai-sdk/openai, so streaming is covered * feat(usage): add probe-models, balance, and usage API routes - POST /api/provider/probe-models: discover chat models via /models with candidate fallback; SSRF-guarded; filters non-chat ids; 401/404 typed - POST /api/provider/balance: built-in balance detection + billing fallback - GET /api/usage: aggregate jsonl by model/day/source with costIncomplete flag Verified e2e against the live MAIC gateway: 16 chat models (6 filtered), balance detected, and a real callLLM writes a costed usage row. * feat(settings): add token-plan preset picker to provider dialog - lib/config/token-plan-presets.ts: data-driven vendor presets (Huawei/MiniMax/ Xiaomi token plans, OpenRouter/SiliconFlow gateways, DeepSeek/GLM/Qwen/Hunyuan/ Doubao direct) with baseURL, protocol, optional modelsUrl, category - add-provider-dialog: '选择厂商/自定义' tabs; picking a preset auto-fills baseURL+protocol+modelsUrl, custom tab unchanged - ProviderSettings.modelsUrl carries the optional /models override - i18n keys added across all 8 locales Verified in-browser: preset picker renders grouped by category. * feat(settings): add Fetch Models button and balance bar to provider panel - 拉取模型: probes /models, merges discovered ids into the model list (dedupe, keeps manual additions), with success/no-endpoint/auth messages - 查询余额: queries /api/provider/balance, renders a balance bar or a 'check console' hint when unsupported - index.tsx: handleModelsFetched merges probe results into provider config - i18n keys across all 8 locales; removed a now-unused eslint-disable Verified in-browser against MAIC gateway: 16 models fetched, balance shown. * feat(settings): add usage dashboard to System Settings - usage-dashboard.tsx: echarts dual-axis daily trend (tokens + cost), totals cards, by-model table, refresh; reads GET /api/usage - mounted at the top of GeneralSettings (系统设置) - honest disclaimer + costIncomplete marker when a model lacks pricing - i18n keys across all 8 locales Verified in-browser: shows 1 request / 31 tokens / $0.0003 from a prior call. * feat(token-plan): multi-modal one-click setup in System Settings - token-plan-presets.ts: presets now declare per-modality targets (llm/image/video/tts/webSearch); MiniMax is the full-set template, others LLM-only — extend by adding entries (at-our-best adaptation) - apply-token-plan.ts: fills one key into every declared modality via injected store setters, isolating per-modality failures (TDD, 4 tests) - token-plan-settings.tsx: new sidebar page — pick plan, enter key, one-click apply lights up adapted modalities (+LLM model probe), shows 'not adapted yet' for the rest, balance bar reused - reverted add-provider dialog to plain custom form (preset picker moved here) - i18n across all 8 locales Verified in-browser: Token Plan page renders, MiniMax shows all 5 modalities, apply/balance UI wired. 859 tests pass, build clean. * feat(token-plan): add custom token plan entry to Token Plan page - Custom card at the bottom of the provider list: pick it to manually enter name + protocol + baseURL (LLM-only), then key + one-click apply via the same applyTokenPlan flow (mirrors cc-switch's custom provider) - effectivePreset unifies preset vs custom for apply/balance/probe - i18n keys (customGroup/customName/customHint) across all 8 locales Verified in-browser: custom card expands the manual form; preset flow intact. * feat(token-plan): reflect persisted config on the Token Plan page Other settings panels read the store directly, so they survive section switches; the Token Plan page only wrote the store, so it looked blank on return. Now it also reads providersConfig: - selecting a preset prefills its saved API key - configured presets show a '已配置/Configured' badge State persistence was never broken (apply writes zustand→localStorage); this fixes the missing read-back so the page reflects it. * fix(settings): isLLMProviderConfigured crashed on providers without models Root cause of 'token plan config disappears': applyTokenPlan writes a new LLM provider with no models yet (probe fills them later). isLLMProviderConfigured did config.models.length unguarded → threw inside setProviderConfig's resolver → the whole set() aborted → key/baseUrl/type never persisted. - guard models in isLLMProviderConfigured (shared validator; affects any provider written without a models array) - seed models:[] in applyTokenPlan's LLM write for a valid initial shape - regression tests: validator no longer throws; apply+probe write keeps apiKey Verified in-browser: DeepSeek persists key and shows 已配置 after section switch. * feat(token-plan): add remove/teardown for a configured token plan Apply had no inverse. Add removeTokenPlan: clears the API key and disables (enabled:false) every modality the plan declared; a custom LLM provider is deleted entirely (removeProvider), built-ins keep the cleared shape. - removeTokenPlan in apply-token-plan.ts (mirrors applyTokenPlan, isolated per-modality, injected setters; 3 tests) - trash button on configured preset cards in the Token Plan page; resets page state if the removed plan was selected - i18n 'remove' across all 8 locales Verified in-browser: removing DeepSeek empties its key and drops the 已配置 badge. * feat(usage): track multimodal usage, drop cost/pricing Reframe usage stats as pure usage (no cost), per user decision: - usage-storage: drop all cost fields; add kind (llm/image/video/tts/asr) + quantity + unit; LLM keeps token counts, others store quantity - delete lib/usage/pricing.ts + pricing-defaults.json + its test - instrument image/video/tts at the server-only API routes (not in the provider dispatch — those files are in the client graph and importing fs-backed usage-storage broke the client bundle) - /api/usage: aggregate by model/day/modality, no cost - dashboard: per-modality usage (tokens/images/seconds/chars), token-only daily trend, no '$'; i18n cost keys replaced with modality/unit keys - backward compatible: legacy rows (no kind, stray cost fields) read as llm 912 tests pass, build clean. * feat(usage): per-modality dashboard layout + softer dark-mode chart - group usage into per-modality sections (LLM/image/video/tts/asr), each table's usage column uses one consistent unit (token/image/sec/char) — no more mixed units in a single column - summary chips per modality with their own unit - trend chart now plots daily REQUESTS (unit-agnostic, works for any modality) instead of LLM-only tokens - theme-aware chart: faint thin line + soft gradient area, muted axis/grid colors via useTheme — fixes the harsh solid stroke in dark mode Verified in-browser (dark): TTS shows '字符', LLM shows 'Token', separate sections; chart no longer has a hard line. * refactor(usage): dedupe model/fetch/usage helpers, parallel balance probe Review cleanups on the token-plan/usage branch: - extract modelInfoFromId() (shared vision heuristic + ModelInfo shape) - extract fetchWithTimeout() shared by model-fetch and balance-providers - extract recordGenerationUsage() to dedupe the image/tts/video routes - queryBalance: fetch billing subscription + usage in parallel - parseOneApiBilling: report quota without remaining when usage endpoint is unavailable, instead of implying zero spend (full balance) - split the two jammed imports in settings/index.tsx * feat(token-plan): drop custom token-plan support Custom token plans (manual baseURL/protocol entry) added complexity for little gain — a one-off provider is better configured directly on the Providers page. Token Plan is now preset-only: - remove custom mode, manual fields, and the custom card from the UI - collapse effectivePreset back to the selected preset - drop the now-dead removeProvider action + custom-id branch in removeTokenPlan - remove orphaned customGroup/customName/customHint i18n keys (8 locales) * feat(token-plan): add Volcengine/Tencent/Bailian plans, drop balance feature Add three vendor token-plan presets (all map to existing built-in LLM providers, so it's data-only — no new adapters): - 火山方舟 Volcengine Ark → doubao, OpenAI /api/v3 - 腾讯 TokenHub Token Plan → tencent-hunyuan, OpenAI /plan/v3 (the plan-specific base; /v1 is the pay-as-you-go gateway) - 阿里百炼 Token Plan → qwen, cross-model plan (Qwen + DeepSeek/Kimi/ GLM/MiniMax) on one key; model list is probed/entered Remove the balance/quota feature entirely — we now track usage, not cost, and every vendor's balance query needs its own cloud AK/SK + signature (Volcengine SigV4 / Tencent TC3 / Aliyun BSS), which the Bearer-key billing-endpoint probe never supported anyway: - delete lib/usage/balance-providers.ts, /api/provider/balance, its test - strip the Check Balance button + balance bar from the token-plan page and the provider config panel - remove the 4 balance i18n keys across all 8 locales - restore an eslint-disable the branch had dropped in provider-config-panel * feat(token-plan): use cloud-brand logos for vendor token plans The three vendor plans are cloud offerings, not single-model products, so icon them with the cloud brand rather than a model logo: - 火山方舟 → volcengine.svg (was doubao.svg) - 腾讯 TokenHub → tencentcloud.svg (was hunyuan.svg) - 阿里百炼 → alibabacloud.svg (was bailian.svg) Logos are the colored brand variants from lobehub/lobe-icons, matching the existing colored-logo style (plain <img>, no dark:invert needed). * feat(token-plan): keep only MiniMax and Volcengine presets Trim the token-plan list to the two we want to ship: MiniMax (full-set template) and 火山方舟 Volcengine Ark. Drop the Tencent/Bailian plans and the OpenRouter/SiliconFlow/DeepSeek/GLM/Qwen entries. - remove the now-unused tencentcloud.svg / alibabacloud.svg logos (volcengine.svg stays; the other logos are still used by the provider registry) - retarget the LLM-only apply test from the deleted deepseek preset to volcengine-ark * feat(token-plan): restore aggregator/third-party presets Previous commit over-trimmed: the intent was to drop only the Tencent and Bailian token plans, not the OpenRouter/SiliconFlow/DeepSeek/GLM/Qwen entries. Bring those back; keep only Tencent/Bailian removed. - token_plan: MiniMax, 火山方舟 Volcengine Ark - aggregator: OpenRouter, SiliconFlow - third_party: DeepSeek, GLM, Qwen Revert the apply test back to the deepseek fixture (restored). tencentcloud.svg / alibabacloud.svg stay deleted (their plans are gone). * fix(token-plan): point Volcengine plan at the Coding Plan endpoint The plan's ark--prefixed API keys authenticate only against /api/coding/v3, not the general /api/v3 endpoint — the latter rejects them with "The API key format is incorrect", so model probing returned nothing. Switch the base URL to https://ark.cn-beijing.volces.com/api/coding/v3. * fix(token-plan): Volcengine is an Agent Plan (Anthropic /api/plan) Per the Ark Agent Plan docs, the ark--prefixed keys authenticate ONLY against the dedicated Anthropic-compatible base https://ark.cn-beijing. volces.com/api/plan ("其他 Base URL 无法在 Agent Plan 中使用"). The general /api/v3 and the Coding Plan /api/coding endpoints both reject the key as "API key format is incorrect", which is why model probing kept returning 0. - baseUrl → https://ark.cn-beijing.volces.com/api/plan/v1 (the /v1 lets the Anthropic SDK land on /api/plan/v1/messages) - apiFormat → anthropic - rename to 火山方舟 Agent Plan Probe still targets /api/plan/v1/models (the path exists); if the Anthropic gateway doesn't return an OpenAI-shaped list, users fall back to typing a model id like ark-code-latest. * fix(token-plan): Volcengine Agent Plan = OpenAI /api/plan/v3 + ark-code-latest Settled after probing the real key and reading cc-switch's approach: - The ark- plan key works on the OpenAI-compatible /api/plan/v3 endpoint (chat/completions returns 200); switch apiFormat back to openai. - The plan exposes NO /models list (every /api/plan/*/models is 404), which is why probing kept returning 0. cc-switch handles this by hardcoding a single ark-code-latest (an auto-routing alias valid on any tier) and does NOT use AK/SK for model listing — so we do the same. - Seed defaultModels: ['ark-code-latest'] only; users add specific ids by hand. Supporting machinery (kept, general-purpose): - applyTokenPlan seeds models from defaultModels instead of wiping to [] - handleApply uses defaultModels and skips the doomed probe when present - drop stray .playwright-mcp/ debug artifacts and gitignore them * style: fix prettier formatting in usage files CI runs prettier on the whole repo (prettier . --check); these four files predate this branch's formatting pass and tripped the check. * feat(token-plan): verify Volcengine Agent Plan's published model set The Agent Plan publishes a fixed model set but exposes no /models endpoint, so carry the documented models as CANDIDATES and verify each on apply: - add verifyModels flag to TokenPlanModalityTarget - new /api/provider/probe-chat-models route: sends a minimal chat request per candidate (OpenAI /chat/completions or Anthropic /messages) in parallel, returns the subset that succeeds; SSRF-guarded, auth-failure short-circuits - handleApply gains a verify branch (before the fixed-defaultModels fast path), falling back to the seeded list if verification fails - Volcengine preset now carries the 12 published Agent Plan text models (doubao-seed-2.0-*/deepseek-v4-*/minimax-m*/glm-5.2/kimi-k2.*) as candidates This auto-prunes retired (docs flag deepseek-v3.2/glm-5.1 as 即将下线) and tier-gated models without code changes. Verified all 12 resolve against a real plan key. * feat(token-plan): wire Volcengine Agent Plan image + video modalities Make the Ark seedream/seedance adapters path-configurable and light up the image/video modalities on the Volcengine plan: - seedream/seedance adapters: resolveArkRoot() uses baseUrl verbatim when it already carries an /api/... path (token plan's /api/plan/v3), else appends the standard /api/v3 — no regression for the pay-as-you-go default host. - applyTokenPlan: image/video branches inject a modality's defaultModels as customModels and set them as the active provider+model, so generation works out of the box. New optional setImageProvider/ModelId + setVideoProvider/ ModelId actions (UI passes the store setters; tests omit them). - Volcengine preset declares image (doubao-seedream-5.0-lite, verified 200 on /api/plan/v3/images/generations) and video (doubao-seedance-2.0/1.5-pro — Medium+ tiers only; lower tiers reject at call time, no code change needed to upgrade). Applying the plan overwrites the shared seedream/seedance slot with the plan config (same overwrite model as LLM); switching back to pay-as-you-go is a manual edit or plan removal. Verified image end-to-end with a real plan key. * feat(token-plan): verify image/video models on apply, disable unsupported tiers The Volcengine plan lit up video optimistically, but lower tiers (Small) don't include video — so using it 404'd with UnsupportedModel. Probe media models on apply and only keep what the tier actually supports: - generalize /api/provider/probe-chat-models with a `kind` (chat|image|video): image hits /images/generations, video hits /contents/generations/tasks with empty content. The model-support check (404 UnsupportedModel) runs before any billable work, so probing never starts a real image/video job; for media, "supported" = any non-404 response. - handleApply: after lighting up image/video, probe each verifyModels modality; prune to the verified model set + re-select a working model, or disable the modality entirely if none pass (no false "available"). - Volcengine preset: image/video targets gain verifyModels: true. - add settings.tokenPlan.tierUnsupported across 8 locales. Verified with a real Small-tier key: image (seedream-5.0-lite) passes and is kept; video (seedance-2.0/1.5-pro) 404s and is disabled. * feat(web-search): add Doubao (豆包搜索) provider Doubao Search (Custom 版) over its REST endpoint POST open.feedcoopapi.com/search_api/web_search with Bearer auth — the same endpoint the askecho-search-infinity MCP server wraps, so the Volcengine Agent Plan key authenticates directly. Mirrors the MiniMax adapter: maps Result.WebResults to WebSearchSource (prefers Summary, the query-relevant excerpt, over Snippet for LLM use) and surfaces errors from ResponseMetadata.Error. - register 'doubao' in WebSearchProviderId + WEB_SEARCH_PROVIDERS - searchWithDoubao adapter, searchWeb dispatch, store default config - SSRF allowlist entry for the search host * feat(audio): support Agent Plan single-key auth for Doubao TTS generateDoubaoTTS now picks auth + endpoint from the key shape, since Volcengine exposes Seed-TTS as two products with separate credentials (verified: a plan key 401s on the normal endpoint, and the plan endpoint rejects appId-style auth): - single key (no colon) -> X-Api-Key, for the Agent Plan /plan endpoint - appId:accessKey -> X-Api-App-Id + X-Api-Access-Key (unchanged) A malformed pair (empty half) fails clearly instead of sending an empty header. Reuses the existing NDJSON/base64-mp3 parsing and voice list. * fix(media): map MiniMax video 720p to its real 768P tier normalizeVideoOptions defaults minimax-video to '720p' (the first supported resolution), but Hailuo 2.3 only accepts 768P/1080P and rejects 720P with '2013 ... does not support resolution 720P'. MiniMax's mid tier is 768P, not 720P (the adapter already falls back to 768P, as does the connectivity test), so map the shared enum's '720p' to 768P. Regression tests lock the mapping. * feat(token-plan): add web search + TTS to Volcengine Agent Plan, widen image tiers Extend the volcengine-ark preset now that the adapters exist: - webSearch -> doubao (own host open.feedcoopapi.com, not the ark endpoint) - tts -> doubao-tts on the /api/plan/tts endpoint (single-key auth) - image defaultModels widened to a best-first Seedream 5.0/4.5/4.0 list so a higher tier keeps the strongest model while verifyModels prunes the rest; video keeps the 2.0 + 1.5-pro candidates Comments record the verified host/auth quirks of each modality. * feat(token-plan): show result panel only after probing, with two clear states Addresses review feedback that a green check implied generation works when it only meant 'configured'. The panel now renders after probing finishes (gated on results && !applying) so it reflects the final set, and uses two states: green when the modality is configured/usable, muted when a live probe proved it unavailable (e.g. video on a tier without it). * feat(token-plan): scope presets to true multi-modal token plans Drop the single-modality LLM presets (OpenRouter, SiliconFlow, DeepSeek, GLM, Qwen) from Token Plan. A token plan's defining trait is one key spanning many modalities; those entries are ordinary LLM API providers already covered by the add-provider flow, and listing them here muddied the 'one key, every modality' promise. Only MiniMax and the Volcengine Ark Agent Plan remain. The UI already hides categories with no entries. apply-token-plan's LLM-only test now uses a local fixture instead of the removed deepseek preset. * feat(token-plan): progressive reveal of probe results on apply The result panel previously rendered all at once after probing finished, reading as dead air during the model probe. Now rows appear immediately on Apply: modalities with a live probe in flight show a spinner ('pending') and resolve to lit/failed independently as each probe returns, while non-probe modalities show lit right away. Probes run in parallel (Promise.all) instead of sequentially. A row only turns green once its own probe confirms, so this reveals structure + live progress without a premature green — complementing the earlier 'render only after probing' intent rather than reverting it. Per review feedback from @wyuc on #784. * fix(token-plan): enrich seeded models with built-in thinking capability Token Plan built ModelInfo objects from probed ids via modelInfoFromId(), filling only streaming/tools/vision — so a model that supports configurable thinking lost capabilities.thinking and InlineThinkingControl was hidden. modelInfoFromId now takes an optional providerId and overlays the catalog thinking capability for that (provider, model) pair; applyTokenPlan does the same for its synchronously-seeded list. Added the Ark Agent Plan's dotted aliases to the metadata table: - native Doubao Seed 2.0 family (doubao-seed-2.0-pro/code/lite/mini) - cross-vendor models the plan serves through its OpenAI-compatible endpoint (deepseek-v4-pro/flash, glm-5.2, kimi-k2.7-code/k2.6, minimax-m3/m2.7, ark-code-latest) All verified against a live plan key: each accepts the gateway's unified reasoning_effort field (low/medium/high) and actually reasons. They share the doubao effort adapter, which disables via 'minimal' (not 'none') — matching what the plan endpoint accepts (it rejects reasoning_effort:'none'). Addresses review point #1 from @wyuc on #784. * Improve token plan capability setup UI * fix token plan setup flow * chore: prettier format tts-providers.ts |
||
|
|
3b7a0ca0c0 |
feat(document): add multi-format course material upload (#741)
* feat(document): add multi-format course material upload * fix(document): support office uploads with mineru cloud * fix(document): handle mineru cloud office edge cases * fix(document): align mineru cloud artifact metadata --------- Co-authored-by: Yanpeng Wang <yanpg.wang@gmail.com> |
||
|
|
9ffdd72f77 |
fix(quiz): render formulas in quiz text (#833)
* fix(quiz): render formulas in quiz text * fix(quiz): tighten formula rendering heuristics |
||
|
|
b6fe2814d2 |
fix(quiz): stop leaking questions on entry and pass results to chat agent (#823)
* fix(quiz): stop leaking questions on entry and pass results to chat agent Fixes #822. Two related defects on quiz scenes: 1. The `quiz-actions` opening monologue could enumerate question stems, compare options, and trigger a `discussion` action that walked agents through the quiz BEFORE the learner had answered anything. 2. After the learner submitted, the chat/discussion agent never saw their answers, correctness, the canonical `analysis`, or the `aiComment` from `/api/quiz-grade` — so post-quiz feedback was generic and often re-explained the whole quiz from scratch. Changes: - `lib/prompts/templates/quiz-actions/{system,user}.md`: collapse the generator down to a brief 1-2 segment opening, forbid `discussion` actions in scene.actions, and add explicit "no preview, no answer, no detailed concept re-teach" safety rules. - `lib/types/chat.ts` + `lib/chat/agent-loop.ts`: add optional `quizResults` to `StatelessChatRequest.storeState` / `AgentLoopStoreState` (sceneId + answers + per-question status/earned/aiComment). - `components/chat/use-chat-sessions.ts`: hydrate `quizResults` from `readSubmittedState(sceneId)` once per agent-loop iteration (and on initial dispatch) so retries are picked up. - `lib/orchestration/summarizers/state-context.ts`: when results are present, surface per-question student answer / correct answer / verdict / analysis / aiComment with a "address THIS student's mistakes" instruction; when unsubmitted, keep question visibility for clarifying questions but pin strict no-leak rules so a learner saying "I'm done" cannot bait the agent into reciting the quiz. Discussion / multi-agent round-robin and the canonical session flow are untouched. * style: apply prettier formatting to state-context --------- Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn> |
||
|
|
6538e718ff |
feat(editor): in-editor authoring of classroom agents (Stage-level roster) (#816)
* feat(editor): agent roster edit operations Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(editor): dedupe agent.delete lookup + cover history cap/color/teacherCount Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(editor): materialize agent roster from presets Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(editor): cycle prepended-teacher index + document branch-1 as-is Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(editor): stage store viewMode + agent roster persistence Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(editor): useAgentRoster controller hook Implements the AgentRosterController hook that bridges the store, history stack, and agent-ops layer for the agents authoring view. - Materializes roster from stage on mount via materializeRoster + resolvePreset - Holds AgentRosterHistory in React state; exposes add/update/remove/reorder - Guards LAST_TEACHER errors (caught, no-op) in update + remove - Exposes SurfaceHistory-shaped history object for undo/redo wiring - Syncs history.present to setStageAgents via useEffect on every change Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(editor): Agents view UI components Adds AgentsView, AgentRosterGrid, AgentCard, AgentInspector, AvatarPicker. Layout: full-height panel with a scrollable grid of agent cards on the left and a fixed inspector panel on the right (opens when a card is selected). - AgentCard: avatar + name + role badge + persona excerpt; ◀/▶ reorder buttons; delete button disabled + titled when canRemove=false (last teacher) - AgentRosterGrid: responsive grid with trailing [+ 添加角色] add tile - AgentInspector: name input, role select (teacher/assistant/student), AvatarPicker over AGENT_DEFAULT_AVATARS, persona textarea capped 2000 chars - AvatarPicker: grid of AGENT_DEFAULT_AVATARS with violet selection ring - AgentsView: composes the hook + grid + inspector; renders its own CommandBar (title="Agents", history=hook.history) with leading/trailing slots Styling follows quiz surface conventions (rounded-2xl cards, zinc palette, violet accent on selection, same FOCUS ring treatment for inputs). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(editor): [Slides]/[Agents] view toggle wired into Pro-mode chrome - CommandBar: add optional `leading?: ReactNode` center slot for the toggle - EditShell/Frame: thread new `commandLeading` prop down to CommandBar - EditChromeRoot: read viewMode/setViewMode from useStageStore; build a ViewModeToggle ([幻灯片] / [角色] segmented control) passed as commandLeading to both EditShell (slides mode) and AgentsView (agents mode) - When viewMode==='agents', render AgentsView instead of EditShell; leftRail and bottomRail are naturally absent since AgentsView owns its own layout - When viewMode==='slides', existing EditShell path is unchanged - CommandBar history in agents mode binds to useAgentRoster().history; title = "Agents" Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(editor): functional state updates in useAgentRoster + last-teacher role feedback Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(editor): break infinite render loop in Agents view persistence effect Remove `stage` from the useEffect dep array in useAgentRoster — setStageAgents mutates stage (new object ref), which was triggering re-render → effect → loop (React error #185). setStageAgents already no-ops when stage is null (lib/store/stage.ts:287), so the `if (stage)` guard is also removed. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(editor): persist agent roster edits to registry + stage snapshot - Add generatedAgentConfigs to StageRecord (database.ts) so Dexie can round-trip it through db.stages. - Include generatedAgentConfigs in saveStageData whitelist (stage-storage.ts) so editor reloads restore the user's roster edits. - In saveToStorage (stage.ts), call saveGeneratedAgents(stageId, configs) after the stage snapshot write; this is already debounced (500 ms) via debouncedSave, so db.generatedAgents + the in-memory registry are synced without writing on every keystroke. saveGeneratedAgents clears-then- bulk-inserts, so deleted agents are fully removed from the registry. - Add 3 timer-driven tests that verify saveStageData carries generatedAgentConfigs and saveGeneratedAgents is called with the correct payload after the debounce fires. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(editor): scope agent-registry sync to real roster edits (cross-review) - FIX A (P1): remove saveGeneratedAgents from shared saveToStorage; add dedicated debouncedSaveAgents called only from setStageAgents — scene advances (setCurrentSceneId etc.) no longer churn db.generatedAgents - FIX B (P2.1): add isDirtyRef guard in useAgentRoster so opening the Agents tab without editing does not persist/rewrite the roster; ref is set in applyOp, add, undo, redo before any setHistState mutation - FIX C (P2.2): coalesce consecutive agent.update ops on the same agent+fields into one history entry so undo steps over a whole edit rather than each keystroke - Tests: add regression guards asserting saveGeneratedAgents is NOT called on setCurrentSceneId or plain saveToStorage, IS called after setStageAgents (new dedicated debounce path) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(editor): clone preset agents to fresh ids on materialization (cross-review P1) * refactor(editor): move agent roster into right-rail tab beside Edit with AI The [幻灯片][角色] top toggle + full-canvas AgentsView swap is replaced by a tabbed right rail (RightRailTabs) with "Edit with AI" and "角色" tabs. The slide canvas stays visible in all modes; agents are edited in the 角色 tab of the right rail. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(editor): restyle agent panel to Design B accordion (课堂阵容) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(editor): cross-review — persona draft sync, scoped preset re-id, AI-tab gating, dead-code cleanup Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(editor): avatar click expands card, editable-name affordance, add-button copy * fix(editor): cross-review — drop blur-level undo coalescing, sync playback selection to edited roster Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * style(editor): prettier format agent panel files (CI fix) --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> |
||
|
|
5daf3e5a6e |
fix(editor): keep emptied/zero-action scenes playable, bind outline by stable id, surface incomplete content (#814)
Editor empty-state robustness: dwell on zero-action scenes (engine + PlaybackChromeRoot) so emptied/blank slides stay playable; bind a scene's outline by stable outlineId (reorder/insert/duplicate-safe, allOutlines in scene order); clear the cue preview on glyph unmount; surface incomplete content calmly (amber dashed frame on clips, amber dot on blank outline titles + rail, neutral N/M-ready generate gate). Cross-reviewed (Codex + Claude), 5 rounds to a clean pass. |
||
|
|
0bcab10b83 |
fix(lecture-notes): render interactive-webpage widget actions in notes area (#810)
Interactive-webpage scenes (SceneType 'interactive') emit four widget_* action types — widget_highlight, widget_setState, widget_annotation, widget_reveal — each typically followed by a speech action. These execute correctly on stage during playback but were dropped from the Lecture Notes timeline due to two compounding gaps: 1. chat-area.tsx built lectureNotes with an allowlist that only admitted speech/spotlight/laser/play_video/discussion, filtering out all widget_* types so they never entered the notes data. 2. lecture-notes-view.tsx ACTION_ICON_ONLY had no entries for widget_*, and unknown types render as null, so even with data they would be invisible. Add the four widget_* types to the allowlist and extend ACTION_ICON_ONLY with icon/style entries (Highlighter/SlidersHorizontal/StickyNote/Eye), reusing the existing inline icon-only badge pattern already used by spotlight/laser. |
||
|
|
b93434ae2c |
feat(agent-edit): multi-session conversation history for the AI editor (#801)
* feat(agent-edit): multi-session conversation history for the AI editor The "Edit with AI" panel kept only one thread per stage in localStorage, and "New conversation" deleted it, so previous conversations were unrecoverable. Add a per-stage session list backed by IndexedDB (Dexie v12 `agentEditSessions`): - "New conversation" now archives the current session and starts a fresh one instead of deleting it; a history popover in the panel header lists past sessions (auto-titled from the first user message) to switch back to or delete. - One-time migration of the existing single-thread localStorage entry. - The active session id is remembered per stage so a refresh restores it, including a just-cleared empty session (clean slate survives reload). - saveSession preserves the original createdAt and tombstones deleted ids so an in-flight save can't resurrect a deleted session; switching stages drops the previous thread synchronously so it can't leak into the new stage. - Sessions are pruned to a soft cap per stage and removed when a course is deleted. - i18n for all 8 locales; unit tests for title derivation and the store. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(types): drop redundant Window.SpeechRecognition augmentation conflicting with @assistant-ui/core @assistant-ui/core's speech adapter declares Window.SpeechRecognition and webkitSpeechRecognition globally as SpeechRecognitionConstructor. Three files (prompt-input, use-audio-recorder, use-browser-asr) re-declared them as `any`, which conflicts (TS2717) once that adapter's types are pulled into the program, and the constructed instance then lacks the event handlers the code sets (TS2339/2551). Rely on the global declaration and cast the instance to the local rich shape. Takes `tsc --noEmit` back to zero. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
a93f875044 | fix(agent): keep edit runtime alive across read-only scenes | ||
|
|
a88ee3d119 |
feat(editor): add discussion authoring to the script timeline (#798)
Add an append-only 'Add discussion' control + inline editor (topic/prompt/initiating agent) to the script timeline, respecting the action-parser invariant that a discussion is the scene's last action and at most one per scene. Yellow terminal-anchor styling; agent picker (with avatars) sourced from the selected agents the playback engine gates on. Runtime unchanged. |
||
|
|
0f44e9a46f |
Add PBL v2 runtime APIs and classroom UI (#799)
* feat: add PBL v2 runtime UI * fix: ship PBL v2 instructor avatar * fix: ship PBL v2 workspace logo * fix: prevent scenario PBL legacy fallback * chore: restore package lint comments * test: cover ordinary PBL legacy fallback * fix: front-load PBL single-call validation * fix: preserve PBL v2 content when assembling scenes --------- Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn> |
||
|
|
09863af421 |
Add PBL v2 core schema and generation path (#795)
* feat: add PBL v2 core planner * chore: restore unrelated lint comments * fix: document PBL v2 scenario outline flags * fix: expose PBL scenario subtype in outlines * chore: clear PBL v2 completion stats lint warning * chore: address PBL instructor code quality comments * fix: address PBL v2 review findings * chore: restore unrelated lint comments |
||
|
|
8d74639c19 |
fix(generation): show full key-point text in outline editor (#782)
Key-point chips in the pre-generation outline editor used a single-line `truncate`, so longer points were cut off with an ellipsis and users could not read the full text while reviewing the outline. Let the text wrap within the chip's max width and add a native title tooltip as a fallback. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
81dae36280 |
fix(editor): stop dumping raw tool-failure blob in AI edit tool cards (#785)
A failed tool card rendered the tool result's full text inline. For framework schema-validation failures that text is a large blob — the validation message plus the entire received-arguments JSON, including the full interactive-page HTML — which floods the Edit-with-AI panel. Remove the inline failure body. The card is non-expandable by design (a single status row), so failure surfaces through the amber ✗ status mark and its hover tooltip; the model also restates the actionable reason in its own reply. Drops the now-unused `failText` prop from ToolCard and its wiring at the three call sites, and refreshes the stale "surfaced inline" doc comments. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |