diff --git a/README.md b/README.md index 37f7c876..e7610e81 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ > **Repository scope:** the lightweight Python meeting recorder remains in `beta-1/`. The experimental Rust broadcast engine moved to private CivicCast Lab. See `docs/RUST-SEPARATION.md`. Historical release evidence is unchanged. +## Station recorder candidate + +Windows 1.9.0.1 / Station 0.4.0 is in development and has not been published. It adds integrated recorder setup/recovery, camera and microphone selection with a test clip, eight-hour/64 GiB recording limits and streamed Records attachment, and renewable authorized operator sessions. Existing released MSI and historical acceptance remain unchanged. Candidate verification and limits: [recorder completion record](https://github.com/townlight/station/blob/main/beta-1/docs/RECORDER-COMPLETION.md). Tagging/publication require the project owner’s approval. + + ## Windows 1.8.2.1 maintenance release Windows 1.8.2.1 packages the staff authorization, explicit database configuration and component metadata corrections. Its exact signed installed checks cover setup, the 1.8.1.1 upgrade, saved staff records, procurement/Contracts handoffs, backup/restore and uninstall retention. Unchanged module and 31-source/34-format import evidence remains attributed to the earlier build that produced it; this is not a new exhaustive test of every module or live provider. diff --git a/USER-MANUAL.docx b/USER-MANUAL.docx index 3e9da8b3..1b30d336 100644 Binary files a/USER-MANUAL.docx and b/USER-MANUAL.docx differ diff --git a/USER-MANUAL.md b/USER-MANUAL.md index 1ff50d11..b0f39872 100644 --- a/USER-MANUAL.md +++ b/USER-MANUAL.md @@ -1,5 +1,35 @@ ## Windows 1.8.2.1 maintenance release +## Windows recorder update — 1.9.0.1 candidate (not published) + +This section describes the new candidate. The public 1.8.2.1 MSI does not acquire these capabilities until a new release is approved and published. Candidate verification and its limits are recorded in the [recorder completion record](https://github.com/townlight/station/blob/main/beta-1/docs/RECORDER-COMPLETION.md); this is separate from the published 1.8.2.1 evidence. + +### Clerk and operator + +1. Install Townlight and complete normal first-run setup with the full Windows profile or a custom selection that includes Meetings and Records (Station is bundled). Finishing setup provisions the bundled recorder, a private database and Windows sign-in task. No PostgreSQL, Python or media-runtime installation commands are needed. Existing installations use Settings → Modules → Townlight Station → **Set up meeting recording**. +2. Keep Windows signed in and the computer awake while recording. The recorder runs in that user's device-access session, independently of the Townlight window. It is not a multi-user server or a full PEG station. Closing the recorder tab does not stop a recording. +3. Sign in with an existing authorized staff account. From Meetings choose **Open / reconnect to meeting recorder**. Select a meeting and its agenda items. In input setup, find devices, choose one camera/capture device and one microphone, and save. Record a ten-second input test, then play it to check the picture and sound; the meter responds during playback. This test clip is temporary and is not a canonical meeting record. Windows camera/microphone privacy settings and exclusive device use still apply. Configured UDP MPEG-TS input remains supported. +4. Start the meeting recording. The default duration limit is eight hours, with a 64 GiB file limit and at least 1 GiB reserved disk space. Admission estimates the configured duration and bitrate. Free space is monitored while recording; low space or a limit requests a graceful stop and displays the reason. These are configured limits, not a claim that every eight-hour meeting has been tested. Plan space for the recording, its Records copy and backups. Sleep, sign-out, power failure and unavailable hardware can interrupt capture. +5. An open operator page renews its fifteen-minute session against the current Townlight staff authority. Sign-out, revoked permissions and the underlying staff-session expiry still take effect. Reopen from Townlight to reconnect to an existing recording; reconnect never starts a second recording. Select **Stop recording** to drain and finalize the file. +6. After completion, an authorized Records user selects a request and explicitly attaches the recording. Records streams a separate managed copy and verifies SHA-256, size and provenance; files up to 64 GiB are accepted subject to available space. Attachment is not public release. Review, redaction and publication remain separate Records decisions. + +### Administrator and recovery + +Station setup uses bundled native dependencies and its existing pinned CivicCast media implementation; it never starts or changes CivicCast or CivicCast Lab. The per-user logon task owns a separate PostgreSQL instance on loopback port 15435; Station's API listens only on 127.0.0.1:8756. Townlight's existing staff authority remains on its configured Suite origin. Protected settings and database credentials remain in the recorder data directory, under the selected city data location. Setup refuses unrelated nonempty storage or an unrelated task with the same name. Retry setup after correcting readiness errors; inspect the private background, PostgreSQL, API and worker logs when needed. + +Use **Check recorder readiness**, **Back up Station**, and **Restore Station backup** in Settings → Modules. Finish queued and active recordings before backup or restore. Backups contain a PostgreSQL dump, recording/ingest files, saved source choices and a SHA-256 member manifest; they omit credentials and native executables. Restore verifies the members, creates a pre-restore recovery copy, and restores into this installation's separately protected database. Recheck input selection afterward. A Suite backup includes a coherent Station backup when paired; it does not copy the running Station database or its secrets. Suite restore preserves that live private directory and applies the included Station backup separately. + +```mermaid +flowchart LR + Staff[Existing Townlight staff authority] --> Operator[Station operator] + Camera[Camera and microphone or UDP feed] --> Recorder[Per-user background recorder] + Operator --> Recorder + Recorder --> Private[Private Station database and recording] + Private -->|Explicit hash-verified attachment| Records[Records managed copy] + Records --> Review[Separate review and release decision] +``` + + Windows 1.8.2.1 packages the staff authorization, explicit database configuration and component metadata corrections. Its exact signed installed checks cover setup, the 1.8.1.1 upgrade, saved staff records, procurement/Contracts handoffs, backup/restore and uninstall retention. Unchanged module and 31-source/34-format import evidence remains attributed to the earlier build that produced it; this is not a new exhaustive test of every module or live provider. Windows 1.8.2.1 has signed installed acceptance for fresh setup and an in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city data and settings, close Townlight, run the signed MSI, and reopen it under the same Windows account with the existing `%LOCALAPPDATA%\CivicSuite` profile. Keep the prior installer and a restore path. Other upgrade paths are unverified. Station uses its separately configured service. The acceptance summary distinguishes new maintenance checks from reused workflow evidence. diff --git a/USER-MANUAL.pdf b/USER-MANUAL.pdf index 0e1997d8..89ecf590 100644 Binary files a/USER-MANUAL.pdf and b/USER-MANUAL.pdf differ diff --git a/USER-MANUAL.txt b/USER-MANUAL.txt index b019e96d..354ed073 100644 --- a/USER-MANUAL.txt +++ b/USER-MANUAL.txt @@ -1,14 +1,118 @@ Windows 1.8.2.1 maintenance release -Windows 1.8.2.1 packages the staff authorization, explicit database configuration and component metadata corrections. Its exact signed installed checks cover setup, the 1.8.1.1 upgrade, saved staff records, procurement/Contracts handoffs, backup/restore and uninstall retention. Unchanged module and 31-source/34-format import evidence remains attributed to the earlier build that produced it; this is not a new exhaustive test of every module or live provider. - -Windows 1.8.2.1 has signed installed acceptance for fresh setup and an in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city data and settings, close Townlight, run the signed MSI, and reopen it under the same Windows account with the existing %LOCALAPPDATA%\CivicSuite profile. Keep the prior installer and a restore path. Other upgrade paths are unverified. Station uses its separately configured service. The acceptance summary distinguishes new maintenance checks from reused workflow evidence. +Windows recorder update — 1.9.0.1 candidate (not published) + +This section describes the new candidate. The public 1.8.2.1 MSI does +not acquire these capabilities until a new release is approved and +published. Candidate verification and its limits are recorded in the +recorder completion record; this is separate from the published 1.8.2.1 +evidence. + +Clerk and operator + +1. Install Townlight and complete normal first-run setup with the full + Windows profile or a custom selection that includes Meetings and + Records (Station is bundled). Finishing setup provisions the bundled + recorder, a private database and Windows sign-in task. No + PostgreSQL, Python or media-runtime installation commands are + needed. Existing installations use Settings → Modules → Townlight + Station → Set up meeting recording. +2. Keep Windows signed in and the computer awake while recording. The + recorder runs in that user’s device-access session, independently of + the Townlight window. It is not a multi-user server or a full PEG + station. Closing the recorder tab does not stop a recording. +3. Sign in with an existing authorized staff account. From Meetings + choose Open / reconnect to meeting recorder. Select a meeting and + its agenda items. In input setup, find devices, choose one + camera/capture device and one microphone, and save. Record a + ten-second input test, then play it to check the picture and sound; + the meter responds during playback. This test clip is temporary and + is not a canonical meeting record. Windows camera/microphone privacy + settings and exclusive device use still apply. Configured UDP + MPEG-TS input remains supported. +4. Start the meeting recording. The default duration limit is eight + hours, with a 64 GiB file limit and at least 1 GiB reserved disk + space. Admission estimates the configured duration and bitrate. Free + space is monitored while recording; low space or a limit requests a + graceful stop and displays the reason. These are configured limits, + not a claim that every eight-hour meeting has been tested. Plan + space for the recording, its Records copy and backups. Sleep, + sign-out, power failure and unavailable hardware can interrupt + capture. +5. An open operator page renews its fifteen-minute session against the + current Townlight staff authority. Sign-out, revoked permissions and + the underlying staff-session expiry still take effect. Reopen from + Townlight to reconnect to an existing recording; reconnect never + starts a second recording. Select Stop recording to drain and + finalize the file. +6. After completion, an authorized Records user selects a request and + explicitly attaches the recording. Records streams a separate + managed copy and verifies SHA-256, size and provenance; files up to + 64 GiB are accepted subject to available space. Attachment is not + public release. Review, redaction and publication remain separate + Records decisions. + +Administrator and recovery + +Station setup uses bundled native dependencies and its existing pinned +CivicCast media implementation; it never starts or changes CivicCast or +CivicCast Lab. The per-user logon task owns a separate PostgreSQL +instance on loopback port 15435; Station’s API listens only on +127.0.0.1:8756. Townlight’s existing staff authority remains on its +configured Suite origin. Protected settings and database credentials +remain in the recorder data directory, under the selected city data +location. Setup refuses unrelated nonempty storage or an unrelated task +with the same name. Retry setup after correcting readiness errors; +inspect the private background, PostgreSQL, API and worker logs when +needed. + +Use Check recorder readiness, Back up Station, and Restore Station +backup in Settings → Modules. Finish queued and active recordings before +backup or restore. Backups contain a PostgreSQL dump, recording/ingest +files, saved source choices and a SHA-256 member manifest; they omit +credentials and native executables. Restore verifies the members, +creates a pre-restore recovery copy, and restores into this +installation’s separately protected database. Recheck input selection +afterward. A Suite backup includes a coherent Station backup when +paired; it does not copy the running Station database or its secrets. +Suite restore preserves that live private directory and applies the +included Station backup separately. + + flowchart LR + Staff[Existing Townlight staff authority] --> Operator[Station operator] + Camera[Camera and microphone or UDP feed] --> Recorder[Per-user background recorder] + Operator --> Recorder + Recorder --> Private[Private Station database and recording] + Private -->|Explicit hash-verified attachment| Records[Records managed copy] + Records --> Review[Separate review and release decision] + +Windows 1.8.2.1 packages the staff authorization, explicit database +configuration and component metadata corrections. Its exact signed +installed checks cover setup, the 1.8.1.1 upgrade, saved staff records, +procurement/Contracts handoffs, backup/restore and uninstall retention. +Unchanged module and 31-source/34-format import evidence remains +attributed to the earlier build that produced it; this is not a new +exhaustive test of every module or live provider. + +Windows 1.8.2.1 has signed installed acceptance for fresh setup and an +in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city +data and settings, close Townlight, run the signed MSI, and reopen it +under the same Windows account with the existing +%LOCALAPPDATA%\CivicSuite profile. Keep the prior installer and a +restore path. Other upgrade paths are unverified. Station uses its +separately configured service. The acceptance summary distinguishes new +maintenance checks from reused workflow evidence. Release and downloads · Acceptance and limits. Windows x64 Beta 1 · MSI 1.8.2.1 -Windows 1.8.1.1 adds shared meeting imports for 31 source families, with 34 supported source/format pairs. Installed Windows Sandbox checks exercised preview, save and durable readback using public captures and fixtures, plus the documented Townlight handoffs. These checks do not establish automatic discovery on every live portal or a complete retest of every module. +Windows 1.8.1.1 adds shared meeting imports for 31 source families, with +34 supported source/format pairs. Installed Windows Sandbox checks +exercised preview, save and durable readback using public captures and +fixtures, plus the documented Townlight handoffs. These checks do not +establish automatic discovery on every live portal or a complete retest +of every module. - Townlight Station Manual - Using this manual @@ -37,28 +141,60 @@ Townlight Station Manual Shared meeting imports · Windows 1.8.1.1 -Windows 1.8.1.1 adds shared meeting imports for 31 source families, with 34 supported source/format pairs. Installed Windows Sandbox checks exercised preview, save and durable readback using public captures and fixtures, plus the documented Townlight handoffs. These checks do not establish automatic discovery on every live portal or a complete retest of every module. +Windows 1.8.1.1 adds shared meeting imports for 31 source families, with +34 supported source/format pairs. Installed Windows Sandbox checks +exercised preview, save and durable readback using public captures and +fixtures, plus the documented Townlight handoffs. These checks do not +establish automatic discovery on every live portal or a complete retest +of every module. All 31 sources, formats and handoffs · Installed acceptance. -Windows 1.8.2.1 has signed installed acceptance for fresh setup and an in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city data and settings, close Townlight, run the signed MSI, and reopen it under the same Windows account with the existing %LOCALAPPDATA%\CivicSuite profile. Keep the prior installer and a restore path. Other upgrade paths are unverified. Station uses its separately configured service. The acceptance summary distinguishes new maintenance checks from reused workflow evidence. - -Windows 1.8.2.1 contains Townlight Runtime 0.3.2 and Meetings 1.0.6. Its current component sources and installed evidence are identified in the maintenance acceptance summary. - -Windows 1.8.1.1 adds shared meeting imports for 31 source families, with 34 supported source/format pairs. Installed Windows Sandbox checks exercised preview, save and durable readback using public captures and fixtures, plus the documented Townlight handoffs. These checks do not establish automatic discovery on every live portal or a complete retest of every module. +Windows 1.8.2.1 has signed installed acceptance for fresh setup and an +in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city +data and settings, close Townlight, run the signed MSI, and reopen it +under the same Windows account with the existing +%LOCALAPPDATA%\CivicSuite profile. Keep the prior installer and a +restore path. Other upgrade paths are unverified. Station uses its +separately configured service. The acceptance summary distinguishes new +maintenance checks from reused workflow evidence. + +Windows 1.8.2.1 contains Townlight Runtime 0.3.2 and Meetings 1.0.6. Its +current component sources and installed evidence are identified in the +maintenance acceptance summary. + +Windows 1.8.1.1 adds shared meeting imports for 31 source families, with +34 supported source/format pairs. Installed Windows Sandbox checks +exercised preview, save and durable readback using public captures and +fixtures, plus the documented Townlight handoffs. These checks do not +establish automatic discovery on every live portal or a complete retest +of every module. Using this manual -Townlight Station helps station operators, clerks, records staff and deployment administrators. Station adapts a pinned CivicCast media implementation into an independent Townlight boundary. It captures managed files or configured live UDP MPEG-TS, retains canonical meeting/agenda context, and hands verified recording evidence to Records. Scheduling, playout, approval and local playback have distinct controls. - -Staff should begin with First run and Daily workflow. Administrators should also read Architecture, Technical specifications, Configuration, Security and Recovery. Developers should use the exact API/data dictionary and examples. The table of contents and alphabetical subject index link to the relevant sections in the HTML edition; the PDF preserves headings and searchable text. An editable Word edition is included with the same documentation companion. +Townlight Station helps station operators, clerks, records staff and +deployment administrators. Station adapts a pinned CivicCast media +implementation into an independent Townlight boundary. It captures +managed files or configured live UDP MPEG-TS, retains canonical +meeting/agenda context, and hands verified recording evidence to +Records. Scheduling, playout, approval and local playback have distinct +controls. + +Staff should begin with First run and Daily workflow. Administrators +should also read Architecture, Technical specifications, Configuration, +Security and Recovery. Developers should use the exact API/data +dictionary and examples. The table of contents and alphabetical subject +index link to the relevant sections in the HTML edition; the PDF +preserves headings and searchable text. An editable Word edition is +included with the same documentation companion. Beta identity - ------------------------------------------------------------------------------------------------------------------------------------------------------------------ + ----------------------------------------------------------------------- Identity Value - ----------------------------------- ------------------------------------------------------------------------------------------------------------------------------ - Documentation Townlight naming, Access and Notice candidate + ----------------------------------- ----------------------------------- + Documentation Townlight naming, Access and Notice + candidate Intended installer 1.8.1.1 @@ -66,202 +202,473 @@ Beta identity Runtime distribution townlight-runtime 0.2.0 - Station distribution/import townlight-station 0.3.0 / townlight_station + Station distribution/import townlight-station 0.3.0 / + townlight_station - Acceptance composition Windows 1.8.2.1: fresh-install and 1.8.1.1 upgrade acceptance. Select the full profile. Station uses separate configuration. + Acceptance composition Windows 1.8.2.1: fresh-install and + 1.8.1.1 upgrade acceptance. Select + the full profile. Station uses + separate configuration. - Candidate hashes/signature SHA-256 checksums and Windows acceptance summary + Candidate hashes/signature SHA-256 checksums and Windows + acceptance summary Owned software license AGPL-3.0-only - ------------------------------------------------------------------------------------------------------------------------------------------------------------------ + ----------------------------------------------------------------------- -Station continues to use its separately configured service. The Windows MSI upgrade below applies to the desktop suite. +Station continues to use its separately configured service. The Windows +MSI upgrade below applies to the desktop suite. First run -Windows 1.8.2.1 has signed installed acceptance for fresh setup and an in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city data and settings, close Townlight, run the signed MSI, and reopen it under the same Windows account with the existing %LOCALAPPDATA%\CivicSuite profile. Keep the prior installer and a restore path. Other upgrade paths are unverified. Station uses its separately configured service. The acceptance summary distinguishes new maintenance checks from reused workflow evidence. +Windows 1.8.2.1 has signed installed acceptance for fresh setup and an +in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city +data and settings, close Townlight, run the signed MSI, and reopen it +under the same Windows account with the existing +%LOCALAPPDATA%\CivicSuite profile. Keep the prior installer and a +restore path. Other upgrade paths are unverified. Station uses its +separately configured service. The acceptance summary distinguishes new +maintenance checks from reused workflow evidence. Fresh installation -Run the signed Windows 1.8.2.1 MSI and use an empty database and a new Townlight profile for first run. - -1. Download the signed MSI, matching source companion and checksums from the public Windows release. -2. Verify the MSI hash and Authenticode publisher before installation. See the Windows acceptance summary for the tested setup. -3. Launch Townlight under the intended named Windows account. Choose the storage folders. Select Townlight Inspections candidate (inspections-preview) for the bounded desktop composition, including Access and Notice. A narrower default selection will not expose all workspaces. -4. Enter the city profile, time zone and contacts. Create the first named local administrator, sign in and choose protected backup storage. Continue without local AI is valid for the deterministic workflows. -5. Run Health Check and wait for readiness. Open Townlight. In System Health select Finish Records Migration to activate the canonical Python/PostgreSQL runtime. Do not fabricate migration receipts or seed accounts. -6. Create named staff through Settings. Import authorized sources using each product’s source library. All examples in this package are synthetic; they are not municipal authority. -7. Provision Station separately if it is part of the beta exercise. Selecting the desktop composition does not start or configure Station. Configure vision explicitly only if automatic photo drafting is selected. +Run the signed Windows 1.8.2.1 MSI and use an empty database and a new +Townlight profile for first run. + +1. Download the signed MSI, matching source companion and checksums + from the public Windows release. +2. Verify the MSI hash and Authenticode publisher before installation. + See the Windows acceptance summary for the tested setup. +3. Launch Townlight under the intended named Windows account. Choose + the storage folders. Select Townlight Inspections candidate + (inspections-preview) for the bounded desktop composition, including + Access and Notice. A narrower default selection will not expose all + workspaces. +4. Enter the city profile, time zone and contacts. Create the first + named local administrator, sign in and choose protected backup + storage. Continue without local AI is valid for the deterministic + workflows. +5. Run Health Check and wait for readiness. Open Townlight. In System + Health select Finish Records Migration to activate the canonical + Python/PostgreSQL runtime. Do not fabricate migration receipts or + seed accounts. +6. Create named staff through Settings. Import authorized sources using + each product’s source library. All examples in this package are + synthetic; they are not municipal authority. +7. Provision Station separately if it is part of the beta exercise. + Selecting the desktop composition does not start or configure + Station. Configure vision explicitly only if automatic photo + drafting is selected. Daily workflow 1. Prepare meeting context -Create and save the actual meeting and agenda in Meetings. Assign each selected agenda item to that meeting. A recording request cannot substitute an editable meeting label for the canonical records. +Create and save the actual meeting and agenda in Meetings. Assign each +selected agenda item to that meeting. A recording request cannot +substitute an editable meeting label for the canonical records. 2. Open the operator -Sign in as authorized staff. Use the configured local operator command with the explicit native profile root. It obtains a short-lived one-use browser ticket; the native proof is not placed in the URL. +Sign in as authorized staff. Use the configured local operator command +with the explicit native profile root. It obtains a short-lived one-use +browser ticket; the native proof is not placed in the URL. 3. Choose the input -Select the meeting, assigned agenda and administrator-configured live-source ID. For recorded-file work, place the source in the managed ingest directory and optionally supply an SRT sidecar. Callers cannot submit arbitrary pipelines or filesystem paths. +Select the meeting, assigned agenda and administrator-configured +live-source ID. For recorded-file work, place the source in the managed +ingest directory and optionally supply an SRT sidecar. Callers cannot +submit arbitrary pipelines or filesystem paths. 4. Capture and stop -Start capture and distinguish waiting for a signal from active recording. Stop requests pipeline drain. Wait for completed status and validated output; a partial, failed or interrupted attempt is not a completed recording. +Start capture and distinguish waiting for a signal from active +recording. Stop requests pipeline drain. Wait for completed status and +validated output; a partial, failed or interrupted attempt is not a +completed recording. 5. Review recording evidence -Inspect the media and retained context/hash. Retry is explicit for failed/interrupted recorded-file jobs. A lost live signal cannot be reconstructed: begin a new live recording and preserve the failed attempt. +Inspect the media and retained context/hash. Retry is explicit for +failed/interrupted recorded-file jobs. A lost live signal cannot be +reconstructed: begin a new live recording and preserve the failed +attempt. 6. Hand off to Records -Choose an existing Records request and attach the reviewed recording. The receiver checks bytes/hash and retains a locked private original. Repeating the same handoff retains one canonical document. +Choose an existing Records request and attach the reviewed recording. +The receiver checks bytes/hash and retains a locked private original. +Repeating the same handoff retains one canonical document. 7. Use playout deliberately -Scheduling, dry-run/commit playout, staff approval and local publication are distinct API operations. Public playback only serves the separately approved packaged output. Nothing in capture or Records handoff automatically publishes it. +Scheduling, dry-run/commit playout, staff approval and local publication +are distinct API operations. Public playback only serves the separately +approved packaged output. Nothing in capture or Records handoff +automatically publishes it. 8. Close and recover -Sign out of the operator. Back up Station’s database and media evidence together, separately from Core’s native profile backup. Restart interrupted work deliberately; do not automatically re-air a lost signal. +Sign out of the operator. Back up Station’s database and media evidence +together, separately from Core’s native profile backup. Restart +interrupted work deliberately; do not automatically re-air a lost +signal. Working safely -Use your own named account and save before leaving a screen. A saved draft is durable; unsaved form text may not be. If a write has an unknown result, reopen its record before repeating it. +Use your own named account and save before leaving a screen. A saved +draft is durable; unsaved form text may not be. If a write has an +unknown result, reopen its record before repeating it. -Read source jurisdiction, dates, citation, version and visibility. A copied source hash identifies exact bytes, not their legal applicability. If a source changes or permission is removed, resolve the source problem rather than substituting stale cached content. +Read source jurisdiction, dates, citation, version and visibility. A +copied source hash identifies exact bytes, not their legal +applicability. If a source changes or permission is removed, resolve the +source problem rather than substituting stale cached content. -Keep originals and derivatives separate. Review the intended audience before export. A public summary excludes private fields only through the applicable copy contract and your review. A renamed private packet is still private content. +Keep originals and derivatives separate. Review the intended audience +before export. A public summary excludes private fields only through the +applicable copy contract and your review. A renamed private packet is +still private content. -Drafting, review, approval, attachment, export, fulfillment and publication are separate operations. A Townlight workpaper does not itself adopt law, issue a permit, impose a fine or release a records response. The responsible staff member records the applicable decision. +Drafting, review, approval, attachment, export, fulfillment and +publication are separate operations. A Townlight workpaper does not +itself adopt law, issue a permit, impose a fine or release a records +response. The responsible staff member records the applicable decision. Connected workflows -Meetings → Station → Records is the accepted recording workflow. Townlight owns current session authority; Station owns its database, storage and media children. Standalone CivicCast remains separate, with no shared configuration, service, data directory or automatic updater fallback. +Meetings → Station → Records is the accepted recording workflow. +Townlight owns current session authority; Station owns its database, +storage and media children. Standalone CivicCast remains separate, with +no shared configuration, service, data directory or automatic updater +fallback. - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------------------------------------------- Direction Material - ----------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - Input A real Townlight staff session, saved Meetings records, a dedicated Station database/data root, a managed ingest filename or configured live-source ID, and optional supplied SRT captions for recorded-file input. - - Output Completed verified recording derivatives, retained original inputs/provenance, separately approved local playback packages and locked private Records evidence. - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------- ----------------------------------- + Input A real Townlight staff session, + saved Meetings records, a dedicated + Station database/data root, a + managed ingest filename or + configured live-source ID, and + optional supplied SRT captions for + recorded-file input. + + Output Completed verified recording + derivatives, retained original + inputs/provenance, separately + approved local playback packages + and locked private Records + evidence. + ----------------------------------------------------------------------- Product boundary -There is no Station first-run wizard or automatic activation by the desktop composition. The accepted normal-profile path uses an explicitly configured paired Townlight HTTP process. Physical encoder/network, remote identity, SCM commissioning, CDN delivery and long-duration field quality are not certified. Station does not perform automatic meeting speech recognition. +There is no Station first-run wizard or automatic activation by the +desktop composition. The accepted normal-profile path uses an explicitly +configured paired Townlight HTTP process. Physical encoder/network, +remote identity, SCM commissioning, CDN delivery and long-duration field +quality are not certified. Station does not perform automatic meeting +speech recognition. Architecture -The drawing shows the principal staff/evidence path. Native commands carry trusted identity to Python business services; PostgreSQL and retained original files hold durable state. A downstream copy does not silently transfer decision authority. Station has its own configured authority/media boundary, database and mutable files. The connected-workflow text supplies the drawing’s reading order and accessibility alternative. +The drawing shows the principal staff/evidence path. Native commands +carry trusted identity to Python business services; PostgreSQL and +retained original files hold durable state. A downstream copy does not +silently transfer decision authority. Station has its own configured +authority/media boundary, database and mutable files. The +connected-workflow text supplies the drawing’s reading order and +accessibility alternative. Scheduling playout and recovery Schedule a recording and interpret its state -Use Schedules after saving the actual meeting/agenda and placing a complete file in Station’s managed ingest directory. Choose the meeting, Start time, Source file in managed ingest, and optional SRT Caption sidecar, then select Schedule. The browser form schedules files. The service’s schedule API also supports a configured live-source ID; this is not a second input selector in that browser form. +Use Schedules after saving the actual meeting/agenda and placing a +complete file in Station’s managed ingest directory. Choose the meeting, +Start time, Source file in managed ingest, and optional SRT Caption +sidecar, then select Schedule. The browser form schedules files. The +service’s schedule API also supports a configured live-source ID; this +is not a second input selector in that browser form. -The browser’s datetime input is interpreted in the operator computer’s local timezone and converted to an ISO UTC instant. Verify that computer’s timezone before entering a city meeting time. A direct API client should send an explicit timezone offset or Z; a timezone-less API datetime is interpreted as UTC. A synthetic POST /v1/schedules body is: +The browser’s datetime input is interpreted in the operator computer’s +local timezone and converted to an ISO UTC instant. Verify that +computer’s timezone before entering a city meeting time. A direct API +client should send an explicit timezone offset or Z; a timezone-less API +datetime is interpreted as UTC. A synthetic POST /v1/schedules body is: {"meeting_id":"11111111-1111-4111-8111-111111111111","agenda_ids":[],"source_file":"synthetic-program.mp4","captions_file":"synthetic-captions.srt","start_at":"2026-11-05T18:00:00-07:00","idempotency_key":"synthetic-schedule-001"} -Use a real synthetic meeting ID and intended future exercise time, with files already in managed ingest. The body selects exactly one file or configured live source; a live source cannot use a sidecar. Reusing an idempotency key with changed input/context is a conflict. The initial response includes id, status: scheduled and start_at; it does not mean recording has finished. - -Refresh Schedules and inspect the returned identity/time. Cancel schedule is available while it remains scheduled; cancellation of an already dispatched or terminal entry is refused. The worker claims due work once and creates the linked recording. A start delayed by more than ten minutes is missed, not replayed late. A start within that grace can dispatch on the next worker pass. Inspect the linked recording for its own queued/running/completed or failed state. Do not assume scheduling also commits that recording to air. +Use a real synthetic meeting ID and intended future exercise time, with +files already in managed ingest. The body selects exactly one file or +configured live source; a live source cannot use a sidecar. Reusing an +idempotency key with changed input/context is a conflict. The initial +response includes id, status: scheduled and start_at; it does not mean +recording has finished. + +Refresh Schedules and inspect the returned identity/time. Cancel +schedule is available while it remains scheduled; cancellation of an +already dispatched or terminal entry is refused. The worker claims due +work once and creates the linked recording. A start delayed by more than +ten minutes is missed, not replayed late. A start within that grace can +dispatch on the next worker pass. Inspect the linked recording for its +own queued/running/completed or failed state. Do not assume scheduling +also commits that recording to air. Apply the caption profile -For a managed recorded file, an explicitly supplied SRT sidecar replaces embedded captions for this profile; otherwise embedded captions are retained where supported by the pinned media profile. Live capture preserves the embedded-caption path and does not accept an SRT sidecar. An absent caption stream is not automatic speech recognition. Check the actual captured/packaged captions for the selected synthetic input. +For a managed recorded file, an explicitly supplied SRT sidecar replaces +embedded captions for this profile; otherwise embedded captions are +retained where supported by the pinned media profile. Live capture +preserves the embedded-caption path and does not accept an SRT sidecar. +An absent caption stream is not automatic speech recognition. Check the +actual captured/packaged captions for the selected synthetic input. -Original files are limited to 2,147,483,647 bytes and sidecars to 5,000,000 bytes. After publication, browser playback uses the packaged MP4 and a separate WebVTT track when produced. Preserve original inputs and recorded caption provenance separately from those derivatives. +Original files are limited to 2,147,483,647 bytes and sidecars to +5,000,000 bytes. After publication, browser playback uses the packaged +MP4 and a separate WebVTT track when produced. Preserve original inputs +and recorded caption provenance separately from those derivatives. Check playout and commit deliberately -Open a completed recording. Select Check playout to queue mode: dry-run. Inspect its status and retained errors; a successful check does not change on-air state. To render and take that program to the scheduled on-air path, explicitly select Commit to air, which uses mode: commit. Wait for the playout to be complete; failed rendering is not a successful switch. +Open a completed recording. Select Check playout to queue mode: dry-run. +Inspect its status and retained errors; a successful check does not +change on-air state. To render and take that program to the scheduled +on-air path, explicitly select Commit to air, which uses mode: commit. +Wait for the playout to be complete; failed rendering is not a +successful switch. Equivalent POST /v1/playouts input is: {"recording_id":"22222222-2222-4222-8222-222222222222","mode":"dry-run","idempotency_key":"synthetic-playout-check-001"} -Replace the recording ID with completed synthetic evidence. A separate deliberate commit uses mode: commit and a new key; do not reuse the check’s key with a changed mode. Inspect the returned playout id and read /v1/playouts/{id} until terminal. The scheduled on-air program follows verified committed output, not every dry-run or every recording. Keep the worker and air roles distinct: one renders work, the other follows durable on-air state and emits the local program. +Replace the recording ID with completed synthetic evidence. A separate +deliberate commit uses mode: commit and a new key; do not reuse the +check’s key with a changed mode. Inspect the returned playout id and +read /v1/playouts/{id} until terminal. The scheduled on-air program +follows verified committed output, not every dry-run or every recording. +Keep the worker and air roles distinct: one renders work, the other +follows durable on-air state and emits the local program. Take a live override and return -In On air, choose an administrator-configured live input and enter a reason of at least three characters. Select Take live override and inspect the on-air mode/source. POST /v1/on-air/live uses live_source_id and reason; callers cannot supply an arbitrary network pipeline. +In On air, choose an administrator-configured live input and enter a +reason of at least three characters. Select Take live override and +inspect the on-air mode/source. POST /v1/on-air/live uses live_source_id +and reason; callers cannot supply an arbitrary network pipeline. -While live, select Return to schedule (POST /v1/on-air/return-to-schedule with no payload). Confirm the mode returns to scheduled program. The override supersedes the scheduled output; it does not delete its committed material. If no valid committed program is available, do not assume returning has produced a usable broadcast. Read actual output/state and any error. These are local synthetic on-air controls, not proof of a commissioned cable headend, physical receiver or public CDN. +While live, select Return to schedule +(POST /v1/on-air/return-to-schedule with no payload). Confirm the mode +returns to scheduled program. The override supersedes the scheduled +output; it does not delete its committed material. If no valid committed +program is available, do not assume returning has produced a usable +broadcast. Read actual output/state and any error. These are local +synthetic on-air controls, not proof of a commissioned cable headend, +physical receiver or public CDN. Approve and publish local playback -In Playout and playback, wait for a completed rendered playout. Review its actual media/context/captions, then enter the approval note and approve it. The API accepts a note of 3–500 characters at /v1/playouts/{id}/approve. Approval is retained with the authenticated staff actor; it does not itself publish. - -Select Publish locally only for that reviewed approved playout. /v1/playouts/{id}/publish packages local MP4/WebVTT playback. The response and subsequent playout view retain the publication details. Open the displayed local playback, verify it advances with the expected picture/sound, and inspect the caption track where supplied. Unpublished content is unavailable through the public playback route; guessing its ID does not authorize access. Repeating a completed publication returns the retained package rather than silently publishing changed media. - -The local playback route /v1/public/playback/{id} serves the packaged program; /captions serves its available WebVTT. This approval/publication is separate from Commit to air, capture, attachment to Records and a Records release. Internet commissioning remains outside this local procedure. +In Playout and playback, wait for a completed rendered playout. Review +its actual media/context/captions, then enter the approval note and +approve it. The API accepts a note of 3–500 characters at +/v1/playouts/{id}/approve. Approval is retained with the authenticated +staff actor; it does not itself publish. + +Select Publish locally only for that reviewed approved playout. +/v1/playouts/{id}/publish packages local MP4/WebVTT playback. The +response and subsequent playout view retain the publication details. +Open the displayed local playback, verify it advances with the expected +picture/sound, and inspect the caption track where supplied. Unpublished +content is unavailable through the public playback route; guessing its +ID does not authorize access. Repeating a completed publication returns +the retained package rather than silently publishing changed media. + +The local playback route /v1/public/playback/{id} serves the packaged +program; /captions serves its available WebVTT. This +approval/publication is separate from Commit to air, capture, attachment +to Records and a Records release. Internet commissioning remains outside +this local procedure. Recover without replaying unknown work -After a worker/API/air interruption, inspect durable schedules, recordings, attempts, playouts and on-air state before repeating any write. The worker marks interrupted in-flight work accordingly. Eligible failed/interrupted file recording retries are explicit; live loss requires a new live capture. Retain the prior attempt/logs and do not claim a missing live interval was reconstructed. - -Future scheduled intent survives restart. A claimed/dispatched schedule must not be duplicated; one beyond the ten-minute grace becomes missed. Read its linked recording and create new future intent only when deliberately required. On-air recovery preserves attribution and does not automatically resume a stale live override as if the source had remained valid. Check the actual on-air mode and available committed program after restart before choosing a new override. - -Visible failed/interrupted states and error text in the operator are the existing alert mechanism for this beta. Preserve the private process logs and attempt evidence. Reopen a normal operator ticket after API restart; do not replay an old ticket or bypass current staff authority. Restore Station’s database and its matching media as one recovery set, separately from Core’s native backup. Recheck original/output hashes and intended state after restoration. No automatic repair or database reset is implied by restart. - -Source contracts: townlight_station/operations.py, worker.py, airplay.py, operator.py, the pinned media profile and station/operator-ui/src/operator.tsx. Service request models are in the Station API companion. The three suite-side Station paths in its OpenAPI download are not the full separate /v1 service schema. +After a worker/API/air interruption, inspect durable schedules, +recordings, attempts, playouts and on-air state before repeating any +write. The worker marks interrupted in-flight work accordingly. Eligible +failed/interrupted file recording retries are explicit; live loss +requires a new live capture. Retain the prior attempt/logs and do not +claim a missing live interval was reconstructed. + +Future scheduled intent survives restart. A claimed/dispatched schedule +must not be duplicated; one beyond the ten-minute grace becomes missed. +Read its linked recording and create new future intent only when +deliberately required. On-air recovery preserves attribution and does +not automatically resume a stale live override as if the source had +remained valid. Check the actual on-air mode and available committed +program after restart before choosing a new override. + +Visible failed/interrupted states and error text in the operator are the +existing alert mechanism for this beta. Preserve the private process +logs and attempt evidence. Reopen a normal operator ticket after API +restart; do not replay an old ticket or bypass current staff authority. +Restore Station’s database and its matching media as one recovery set, +separately from Core’s native backup. Recheck original/output hashes and +intended state after restoration. No automatic repair or database reset +is implied by restart. + +Source contracts: townlight_station/operations.py, worker.py, +airplay.py, operator.py, the pinned media profile and +station/operator-ui/src/operator.tsx. Service request models are in the +Station API companion. The three suite-side Station paths in its OpenAPI +download are not the full separate /v1 service schema. Technical specifications Runtime and storage -The Windows 1.8.2.1 package has signed fresh-install and 1.8.1.1 upgrade acceptance. Its native shell uses Rust 2021, Tauri 2 and Microsoft WebView2; browser assets are JavaScript built with Vite 8.1.6. This describes the native desktop frontend; Station has a separate React operator, specified below or in its product manual. Canonical business workflows use bundled CPython 3.13.5, FastAPI, Pydantic, SQLAlchemy and Alembic, with PostgreSQL 17 / PostGIS and managed original files. Bundled dependency versions are recorded with the release evidence. Package minimum Python requirements can differ from the bundled executable; the metadata reference preserves both. No stack rewrite is implied by the beta label. - -The native transport is fixed to loopback 127.0.0.1:15480; PostgreSQL uses the configured local runtime port (default 15432). Optional local model service defaults to 127.0.0.1:15434. Those are deployment defaults, not internet endpoints. The runtime has health, module and readiness endpoints; readiness is stronger than process existence. The task queue is the existing local Core task infrastructure, not an assertion that a separate Redis service is required for this desktop composition. - -The default native profile is %LOCALAPPDATA%\CivicSuite; the historical directory name remains part of compatibility. Do not rename it to Townlight. A configured TOWNLIGHT_PROFILE_ROOT must be absolute. Local configuration and secrets live under that profile; protected managed files and database state must be backed up coherently. Source/runtime identity is distinct from a product’s display label. +The Windows 1.8.2.1 package has signed fresh-install and 1.8.1.1 upgrade +acceptance. Its native shell uses Rust 2021, Tauri 2 and Microsoft +WebView2; browser assets are JavaScript built with Vite 8.1.6. This +describes the native desktop frontend; Station has a separate React +operator, specified below or in its product manual. Canonical business +workflows use bundled CPython 3.13.5, FastAPI, Pydantic, SQLAlchemy and +Alembic, with PostgreSQL 17 / PostGIS and managed original files. +Bundled dependency versions are recorded with the release evidence. +Package minimum Python requirements can differ from the bundled +executable; the metadata reference preserves both. No stack rewrite is +implied by the beta label. + +The native transport is fixed to loopback 127.0.0.1:15480; PostgreSQL +uses the configured local runtime port (default 15432). Optional local +model service defaults to 127.0.0.1:15434. Those are deployment +defaults, not internet endpoints. The runtime has health, module and +readiness endpoints; readiness is stronger than process existence. The +task queue is the existing local Core task infrastructure, not an +assertion that a separate Redis service is required for this desktop +composition. + +The default native profile is %LOCALAPPDATA%\CivicSuite; the historical +directory name remains part of compatibility. Do not rename it to +Townlight. A configured TOWNLIGHT_PROFILE_ROOT must be absolute. Local +configuration and secrets live under that profile; protected managed +files and database state must be backed up coherently. Source/runtime +identity is distinct from a product’s display label. Data and consistency -Configured live-source IDs; canonical meeting/agenda snapshots; queued recordings and immutable attempts; input/output hashes; schedules; playout jobs and approvals; durable on-air state; publication packages; Records attachment provenance. +Configured live-source IDs; canonical meeting/agenda snapshots; queued +recordings and immutable attempts; input/output hashes; schedules; +playout jobs and approvals; durable on-air state; publication packages; +Records attachment provenance. -Versioned saves use expected prior revision identifiers where defined. Reopen and reconcile on conflict. Exact exports and handoffs use source IDs, current visibility, revision and SHA256. Review belongs to the saved revision and does not transfer silently to edited text. Database changes use the owning product’s migrations; a request or readiness check is not an authorization to mutate schema. +Versioned saves use expected prior revision identifiers where defined. +Reopen and reconcile on conflict. Exact exports and handoffs use source +IDs, current visibility, revision and SHA256. Review belongs to the +saved revision and does not transfer silently to edited text. Database +changes use the owning product’s migrations; a request or readiness +check is not an authorization to mutate schema. Capacity and platform statements -This beta has synthetic single-profile workflow evidence. It does not have a published benchmark for concurrent staff capacity, minimum RAM/CPU, large-source limits or a field SLA. Do not turn a developer machine’s specification into a supported minimum. Installer size is 2,092,122,112 bytes before installation; allow additional disk for extracted runtime, database, originals, exports, media and backups. Select equipment/storage after sizing those actual workloads. +This beta has synthetic single-profile workflow evidence. It does not +have a published benchmark for concurrent staff capacity, minimum +RAM/CPU, large-source limits or a field SLA. Do not turn a developer +machine’s specification into a supported minimum. Installer size is +2,092,122,112 bytes before installation; allow additional disk for +extracted runtime, database, originals, exports, media and backups. +Select equipment/storage after sizing those actual workloads. -The exact runtime payload lock records pinned files, sizes and hashes. The component metadata records shipped dependency declarations. These references are more precise than a manually copied dependency list. Third-party and historical license notices must accompany their matching payloads. +The exact runtime payload lock records pinned files, sizes and hashes. +The component metadata records shipped dependency declarations. These +references are more precise than a manually copied dependency list. +Third-party and historical license notices must accompany their matching +payloads. Station operator and media components -The native desktop frontend above is distinct from Station’s browser operator. The pinned operator package townlight-station-operator is version 0.1.0, using React/react-dom 19.1.1, TypeScript 5.9.2, Vite 7.3.7 and the React Vite plugin 5.0.2. Station serves its built assets through its own operator API. Its Python control/API package remains townlight-station 0.3.0, while its retained storage identity remains 0.1.0. These identities have different purposes and are not renumbered. - -The separate pinned CivicCast-derived media engine uses Python/native GStreamer processing and bounded media children. It is not the standalone CivicCast application. Station’s control database, data root, service/configuration and update identity remain independent. This describes the current mixed stack; no runtime rewrite or CivicCast migration is implied. +The native desktop frontend above is distinct from Station’s browser +operator. The pinned operator package townlight-station-operator is +version 0.1.0, using React/react-dom 19.1.1, TypeScript 5.9.2, Vite +7.3.7 and the React Vite plugin 5.0.2. Station serves its built assets +through its own operator API. Its Python control/API package remains +townlight-station 0.3.0, while its retained storage identity remains +0.1.0. These identities have different purposes and are not renumbered. + +The separate pinned CivicCast-derived media engine uses Python/native +GStreamer processing and bounded media children. It is not the +standalone CivicCast application. Station’s control database, data root, +service/configuration and update identity remain independent. This +describes the current mixed stack; no runtime rewrite or CivicCast +migration is implied. Station media and lifecycle contract -The package/API version is 0.3.0. Its retained storage identity has version 0.1.0; that is a separate storage marker and must not be rewritten to match the package. Product/app IDs are townlight-station and org.townlight.station; service identity is TownlightStation, virtual account NT SERVICE\TownlightStation, credential namespace townlight.station, database schema station, and update-channel identity townlight-station. An identity name or SCM entry point does not establish that a Windows service was registered. - -The control service is Python; its separate pinned CivicCast-derived engine uses native GStreamer media processing. There is no launch of the standalone CivicCast application. Default encoding is 1920×1080, 30 fps and 6000 kbps; explicit validated configuration may change it. The source lock is verified before use. Media children are isolated and bounded; unfinished attempts become interrupted on recovery. - -Recorded-file requests accept a managed ingest filename, optional SRT sidecar and idempotency key. Live requests accept a configured source ID, not a path. Select exactly one file or live source; live capture cannot also supply a sidecar. Inputs are bounded by the configured two-hour default timeout and a 2,147,483,647-byte file limit. Supplied SRT sidecars are bounded to 5,000,000 bytes. The queue admits at most 100 pending/running jobs; live admission is further serialized. A repeated idempotency key must identify the same source bytes, canonical meeting context and encoding profile. - -queued and running do not make content available as completed. Completion requires the worker’s clean media teardown and stream validation. Failed/interrupted file jobs may be explicitly retried; a live gap requires a new capture. Records receives verified bytes and canonical provenance as a locked private original. Local publication is an explicit later operation on separately approved playout; its MP4/WebVTT package is distinct from the retained recording and from a Records release. +The package/API version is 0.3.0. Its retained storage identity has +version 0.1.0; that is a separate storage marker and must not be +rewritten to match the package. Product/app IDs are townlight-station +and org.townlight.station; service identity is TownlightStation, virtual +account NT SERVICE\TownlightStation, credential namespace +townlight.station, database schema station, and update-channel identity +townlight-station. An identity name or SCM entry point does not +establish that a Windows service was registered. + +The control service is Python; its separate pinned CivicCast-derived +engine uses native GStreamer media processing. There is no launch of the +standalone CivicCast application. Default encoding is 1920×1080, 30 fps +and 6000 kbps; explicit validated configuration may change it. The +source lock is verified before use. Media children are isolated and +bounded; unfinished attempts become interrupted on recovery. + +Recorded-file requests accept a managed ingest filename, optional SRT +sidecar and idempotency key. Live requests accept a configured source +ID, not a path. Select exactly one file or live source; live capture +cannot also supply a sidecar. Inputs are bounded by the configured +two-hour default timeout and a 2,147,483,647-byte file limit. Supplied +SRT sidecars are bounded to 5,000,000 bytes. The queue admits at most +100 pending/running jobs; live admission is further serialized. A +repeated idempotency key must identify the same source bytes, canonical +meeting context and encoding profile. + +queued and running do not make content available as completed. +Completion requires the worker’s clean media teardown and stream +validation. Failed/interrupted file jobs may be explicitly retried; a +live gap requires a new capture. Records receives verified bytes and +canonical provenance as a locked private original. Local publication is +an explicit later operation on separately approved playout; its +MP4/WebVTT package is distinct from the retained recording and from a +Records release. Configuration and administration Prepare the normally activated synthetic profile -This procedure describes a future isolated beta installation. Documentation generation does not execute it. Complete normal Townlight Setup under the intended Windows account, select inspections-preview, sign in, and use Finish Records Migration. Keep the native database running and confirm the canonical runtime is ready. Use that account’s actual profile path; the default is %LOCALAPPDATA%\CivicSuite. Do not create session files, seed accounts or force domain_enabled=True. - -Station needs its own database and initially empty absolute data directory. It uses the same named Townlight staff authority through an additional configured loopback suite process. It does not launch or modify CivicCast. No SCM installation, registry edit or replacement of the desktop’s fixed-origin service is needed. - -The examples reserve suite port 15481, Station port 8756 and synthetic UDP input port 19000. Choose unused ports and change both configured origins together if needed. Never point these instructions at a city’s live profile or data. Use the actual installation directory if Townlight was installed elsewhere. +This procedure describes a future isolated beta installation. +Documentation generation does not execute it. Complete normal Townlight +Setup under the intended Windows account, select inspections-preview, +sign in, and use Finish Records Migration. Keep the native database +running and confirm the canonical runtime is ready. Use that account’s +actual profile path; the default is %LOCALAPPDATA%\CivicSuite. Do not +create session files, seed accounts or force domain_enabled=True. + +Station needs its own database and initially empty absolute data +directory. It uses the same named Townlight staff authority through an +additional configured loopback suite process. It does not launch or +modify CivicCast. No SCM installation, registry edit or replacement of +the desktop’s fixed-origin service is needed. + +The examples reserve suite port 15481, Station port 8756 and synthetic +UDP input port 19000. Choose unused ports and change both configured +origins together if needed. Never point these instructions at a city’s +live profile or data. Use the actual installation directory if Townlight +was installed elsewhere. Store the independent test configuration -Run the following in a deployment PowerShell session under the same Windows user. Keep this session for startup and shutdown. The dedicated parent holds configuration/logs; its data child is Station’s initially empty managed store. +Run the following in a deployment PowerShell session under the same +Windows user. Keep this session for startup and shutdown. The dedicated +parent holds configuration/logs; its data child is Station’s initially +empty managed store. $profilePath = Join-Path $env:LOCALAPPDATA 'CivicSuite' $control = Join-Path $profilePath 'runtime\python\python.exe' @@ -283,9 +690,16 @@ Run the following in a deployment PowerShell session under the same Windows user Set-Content -LiteralPath (Join-Path $stationRoot 'station-password.dpapi') Remove-Variable stationPassword,randomBytes -The password file uses the current Windows user’s DPAPI protection. It is not portable to a different user or machine without an explicit credential/recovery decision. Keep it out of source control, support bundles and public documentation. Reuse this protected configuration on restart rather than creating another database or password. +The password file uses the current Windows user’s DPAPI protection. It +is not portable to a different user or machine without an explicit +credential/recovery decision. Keep it out of source control, support +bundles and public documentation. Reuse this protected configuration on +restart rather than creating another database or password. -In the same session, establish the exact process environment. On a later restart, set $profilePath, $control, $payload and $stationRoot to these same existing locations, then repeat this environment/start section, not the first-time provisioning section. +In the same session, establish the exact process environment. On a later +restart, set $profilePath, $control, $payload and $stationRoot to these +same existing locations, then repeat this environment/start section, not +the first-time provisioning section. $secret = Get-Content -LiteralPath (Join-Path $stationRoot 'station-password.dpapi') -Raw | ConvertTo-SecureString @@ -313,11 +727,21 @@ In the same session, establish the exact process environment. On a later restart Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue Remove-Variable nativePassword,encodedNative,stationPassword,secret -Use the actual native PostgreSQL port/database/user if the deployment differs from the accepted defaults. Environment changes here apply to children of this shell, not the already running native supervisor. Keep secrets out of command arguments and output. The paired runtime deliberately uses normal verify_activation through its standard module entry point. +Use the actual native PostgreSQL port/database/user if the deployment +differs from the accepted defaults. Environment changes here apply to +children of this shell, not the already running native supervisor. Keep +secrets out of command arguments and output. The paired runtime +deliberately uses normal verify_activation through its standard module +entry point. Provision the Station database once -This first-time step creates only the dedicated synthetic role/database. Its role owns that database and its Station schema, with no superuser/global administration grant. It connects to the normally provisioned local database using the current profile’s protected credential. Existing role/database names cause a refusal before creation; do not drop or repurpose them automatically. +This first-time step creates only the dedicated synthetic role/database. +Its role owns that database and its Station schema, with no +superuser/global administration grant. It connects to the normally +provisioned local database using the current profile’s protected +credential. Existing role/database names cause a refusal before +creation; do not drop or repurpose them automatically. @' import os @@ -350,11 +774,20 @@ This first-time step creates only the dedicated synthetic role/database. Its rol & $control -B -m townlight_station.cli migrate if ($LASTEXITCODE -ne 0) { throw 'Station migration failed; retain logs and inspect the dedicated schema.' } -If database creation fails after the role was created, the operation is partially complete: inspect that exact owned role/database before resuming. Do not rerun against guessed names or remove unrelated objects. On normal restarts, the database already exists; skip creation and use the existing identity. migrate is explicit; API requests do not substitute for schema migration. +If database creation fails after the role was created, the operation is +partially complete: inspect that exact owned role/database before +resuming. Do not rerun against guessed names or remove unrelated +objects. On normal restarts, the database already exists; skip creation +and use the existing identity. migrate is explicit; API requests do not +substitute for schema migration. Start and check the paired processes -Use the same configured session. The standard suite entry point verifies the existing native activation. Check readiness of that exact paired origin, not only the desktop’s canonical port. Startup below creates hidden children with private log files and records their identities; it does not focus windows or install services. +Use the same configured session. The standard suite entry point verifies +the existing native activation. Check readiness of that exact paired +origin, not only the desktop’s canonical port. Startup below creates +hidden children with private log files and records their identities; it +does not focus windows or install services. $owned = @() function Start-StationRole([string]$name, [string[]]$arguments) { @@ -385,25 +818,59 @@ Use the same configured session. The standard suite entry point verifies the exi $air = Start-StationRole 'station-air' @('-B','-m','townlight_station.cli','air') $owned | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $stationRoot 'owned-processes.json') -Before launching, confirm ports 15481 and 8756 are unused. If readiness fails, inspect the relevant logs and retained profile/schema state; do not start another copy. A port that answers belongs to the intended process only when its ownership is established. A single worker owns a database. worker --once performs a bounded pass; it is not the normal continuous worker. The air role follows durable on-air state and emits the local program; it does not commission a physical transmitter or CDN. Its currently configured local output is under Station’s air directory. Back up the dedicated database and media together; Core’s native backup does not cover them. +Before launching, confirm ports 15481 and 8756 are unused. If readiness +fails, inspect the relevant logs and retained profile/schema state; do +not start another copy. A port that answers belongs to the intended +process only when its ownership is established. A single worker owns a +database. worker --once performs a bounded pass; it is not the normal +continuous worker. The air role follows durable on-air state and emits +the local program; it does not commission a physical transmitter or CDN. +Its currently configured local output is under Station’s air directory. +Back up the dedicated database and media together; Core’s native backup +does not cover them. Configure a live input and open the operator -Create live-sources.json under the Station data directory with the following fictional input. An actual sender must supply UDP MPEG-TS to that receiver; this configuration alone does not generate a signal. +Create live-sources.json under the Station data directory with the +following fictional input. An actual sender must supply UDP MPEG-TS to +that receiver; this configuration alone does not generate a signal. [{"id":"synthetic-chamber","label":"Synthetic chamber feed","kind":"udp-mpegts","address":"127.0.0.1","port":19000}] -At most 32 rows are accepted. IDs are unique 1–64 letters/digits/underscore/hyphen; labels have 1–100 characters; IPv4 and ports 1024–65535 are validated. Each row has exactly the five shown keys. Protect the source network; UDP is not authenticated. Then, under the same signed-in native account: +At most 32 rows are accepted. IDs are unique 1–64 +letters/digits/underscore/hyphen; labels have 1–100 characters; IPv4 and +ports 1024–65535 are validated. Each row has exactly the five shown +keys. Protect the source network; UDP is not authenticated. Then, under +the same signed-in native account: & $control -B -m townlight_station.cli operator --profile-root $profilePath --port 8756 -This normal operator command opens the operator for a future staff exercise. It reads the native session and exchanges a one-use launch ticket; it does not seed authority or put the native proof in a URL. Ticket expiry is 60 seconds, operator cookie lifetime 900 seconds, with at most 256 outstanding tickets/sessions each. Reopen normally after expiration, API restart or sign-out. Changing database/configuration identities does not repair a staff permission refusal. +This normal operator command opens the operator for a future staff +exercise. It reads the native session and exchanges a one-use launch +ticket; it does not seed authority or put the native proof in a URL. +Ticket expiry is 60 seconds, operator cookie lifetime 900 seconds, with +at most 256 outstanding tickets/sessions each. Reopen normally after +expiration, API restart or sign-out. Changing database/configuration +identities does not repair a staff permission refusal. Bounds and shutdown -Default encoding is 1920×1080, 30 fps, 6000 kbps. Optional Station variables permit MAX_SECONDS 10–86400 (default 7200), even WIDTH 320–3840 and HEIGHT 180–2160, FPS 1–60 and BITRATE_KBPS 128–50000; each is prefixed TOWNLIGHT_STATION_. The media source lock and exclusive data identity are verified before use. The dedicated database name must end in _station; unowned nonempty storage and escaping/reparse paths are refused. The existing SCM entry point is not a claim of installed service acceptance. - -To finish an exercise, stop live capture from the operator and wait for its completed or failed terminal state. Wait for any recording/playout work to finish, cancel unwanted future schedules, sign out and preserve the evidence/logs. The air role starts a separate media child; force-stopping only its parent does not run Python cleanup. Stop only the process trees you started, checking each root’s identity before using a saved PID: +Default encoding is 1920×1080, 30 fps, 6000 kbps. Optional Station +variables permit MAX_SECONDS 10–86400 (default 7200), even WIDTH +320–3840 and HEIGHT 180–2160, FPS 1–60 and BITRATE_KBPS 128–50000; each +is prefixed TOWNLIGHT_STATION_. The media source lock and exclusive data +identity are verified before use. The dedicated database name must end +in _station; unowned nonempty storage and escaping/reparse paths are +refused. The existing SCM entry point is not a claim of installed +service acceptance. + +To finish an exercise, stop live capture from the operator and wait for +its completed or failed terminal state. Wait for any recording/playout +work to finish, cancel unwanted future schedules, sign out and preserve +the evidence/logs. The air role starts a separate media child; +force-stopping only its parent does not run Python cleanup. Stop only +the process trees you started, checking each root’s identity before +using a saved PID: foreach ($entry in @($owned | Sort-Object StartTime -Descending)) { $process = Get-Process -Id $entry.Id -ErrorAction SilentlyContinue @@ -414,13 +881,23 @@ To finish an exercise, stop live capture from the operator and wait for its comp } } -Retain the ownership file if the shell must close; parse and verify its actual process paths/start times before acting. Do not terminate the native database/supervisor or CivicCast. Interrupting a worker during a job preserves an interrupted attempt, not completed media; recovery is described in the Station operating procedure. Clear secret-bearing environment values when closing the dedicated deployment shell. Do not delete the database/data root to “reset” an uncertain result. +Retain the ownership file if the shell must close; parse and verify its +actual process paths/start times before acting. Do not terminate the +native database/supervisor or CivicCast. Interrupting a worker during a +job preserves an interrupted attempt, not completed media; recovery is +described in the Station operating procedure. Clear secret-bearing +environment values when closing the dedicated deployment shell. Do not +delete the database/data root to “reset” an uncertain result. API and integration examples Native command example -The following JavaScript belongs in the existing trusted Townlight frontend/development environment with invoke imported from @tauri-apps/api/core. It is not a command for an arbitrary web page or an instruction for nontechnical staff. IDs must come from records created in an isolated synthetic exercise. +The following JavaScript belongs in the existing trusted Townlight +frontend/development environment with invoke imported from +@tauri-apps/api/core. It is not a command for an arbitrary web page or +an instruction for nontechnical staff. IDs must come from records +created in an isolated synthetic exercise. import { invoke } from '@tauri-apps/api/core'; const result = await invoke('meetings_domain_request', {request: {operation: 'get-meeting', id: meetingId}}); @@ -428,14 +905,23 @@ The following JavaScript belongs in the existing trusted Townlight frontend/deve Trusted local HTTP example -An administrator/developer can inspect an already-configured isolated runtime from a trusted local process. This PowerShell example reads the signed-in synthetic profile’s existing proof into memory; it does not create a user, seed a session, reveal the proof in output or bypass a permission check. Do not use real city data in development examples. A read response does not prove approval or publication. +An administrator/developer can inspect an already-configured isolated +runtime from a trusted local process. This PowerShell example reads the +signed-in synthetic profile’s existing proof into memory; it does not +create a user, seed a session, reveal the proof in output or bypass a +permission check. Do not use real city data in development examples. A +read response does not prove approval or publication. Invoke-RestMethod -Uri 'http://127.0.0.1:8756/health' # Authenticated recording operations additionally require current native proof. A synthetic write with subsequent readback -This example demonstrates the existing Meetings HTTP contract in an isolated exercise. It is intentionally fictional. It does not start a service. Its authentication setup is included so it can be run independently under the signed-in synthetic account. If a write times out, inspect current records before repeating it. +This example demonstrates the existing Meetings HTTP contract in an +isolated exercise. It is intentionally fictional. It does not start a +service. Its authentication setup is included so it can be run +independently under the signed-in synthetic account. If a write times +out, inspect current records before repeating it. $profilePath = Join-Path $env:LOCALAPPDATA 'CivicSuite' $sessionPath = Join-Path $profilePath 'config/local-session.json' @@ -455,11 +941,16 @@ This example demonstrates the existing Meetings HTTP contract in an isolated exe -Headers $headers Remove-Variable session, headers -This write requires Meetings to be enabled and the signed-in staff role to permit it. It is a cross-suite integration example; for this product’s request models, use the complete technical reference below. +This write requires Meetings to be enabled and the signed-in staff role +to permit it. It is a cross-suite integration example; for this +product’s request models, use the complete technical reference below. Recording and Records handoff example -An authenticated local client sends POST http://127.0.0.1:8756/v1/recordings with X-Townlight-Session and this JSON, replacing the synthetic UUIDs with saved synthetic meeting/agenda IDs. Configure synthetic-chamber first. +An authenticated local client sends +POST http://127.0.0.1:8756/v1/recordings with X-Townlight-Session and +this JSON, replacing the synthetic UUIDs with saved synthetic +meeting/agenda IDs. Configure synthetic-chamber first. { "meeting_id": "11111111-1111-4111-8111-111111111111", @@ -468,162 +959,357 @@ An authenticated local client sends POST http://127.0.0.1:8756/v1/recordings wit "idempotency_key": "synthetic-docs-capture-001" } -The initial response is 202 with a queued/running identity rather than completed media. Read /v1/recordings/{identity}, explicitly stop live capture through /v1/recordings/{identity}/stop, and wait for completed status before reading /content. Then the authorized Records client calls POST /desktop/v1/requests/{request_id}/station-recordings on the paired Suite runtime with: +The initial response is 202 with a queued/running identity rather than +completed media. Read /v1/recordings/{identity}, explicitly stop live +capture through /v1/recordings/{identity}/stop, and wait for completed +status before reading /content. Then the authorized Records client calls +POST /desktop/v1/requests/{request_id}/station-recordings on the paired +Suite runtime with: { "recording_id": "33333333-3333-4333-8333-333333333333", "expected_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } -The shown hash is deliberately a placeholder. Use the actual completed recording’s hash. A mismatched hash must fail. Repeating the identical completed handoff is idempotent; it does not create a release copy or fulfill a request. +The shown hash is deliberately a placeholder. Use the actual completed +recording’s hash. A mismatched hash must fail. Repeating the identical +completed handoff is idempotent; it does not create a release copy or +fulfill a request. Complete technical contract -Read the Station API reference for every documented operation, request field, constraint, response declaration and source supplement. Download the OpenAPI JSON for tools. For Station this is the suite-side schema only; its separate service contract is documented in the API supplement. The reference directory includes configuration/source inventories, dependency declarations, native command contracts, MCP signatures and candidate evidence. +Read the Station API reference for every documented operation, request +field, constraint, response declaration and source supplement. Download +the OpenAPI JSON for tools. For Station this is the suite-side schema +only; its separate service contract is documented in the API supplement. +The reference directory includes configuration/source inventories, +dependency declarations, native command contracts, MCP signatures and +candidate evidence. MCP and automation boundary -No direct product MCP server is exposed by the accepted Townlight desktop or Station boundary. Do not configure an invented townlight mcp command or assume an AI client has staff permissions. The integration surfaces for this beta are native IPC, the documented HTTP APIs, source bundle imports, exact exports and the existing Station CLI. +No direct product MCP server is exposed by the accepted Townlight +desktop or Station boundary. Do not configure an invented townlight mcp +command or assume an AI client has staff permissions. The integration +surfaces for this beta are native IPC, the documented HTTP APIs, source +bundle imports, exact exports and the existing Station CLI. -The bundled transcription code includes a TextFlowKit MCP adapter as a separate source capability. It offers job-based transcribe_media, get_transcript, list_jobs, get_job_status and export_transcript, and additional tools declared in that adapter. It uses stdio first and optional Streamable HTTP, with the MCP SDK as an optional extra. It is not automatically launched, authenticated as Townlight staff or accepted as a Townlight product MCP deployment. This documentation does not add such a service. +The bundled transcription code includes a TextFlowKit MCP adapter as a +separate source capability. It offers job-based transcribe_media, +get_transcript, list_jobs, get_job_status and export_transcript, and +additional tools declared in that adapter. It uses stdio first and +optional Streamable HTTP, with the MCP SDK as an optional extra. It is +not automatically launched, authenticated as Townlight staff or accepted +as a Townlight product MCP deployment. This documentation does not add +such a service. -For a transcription client already provisioned separately, an illustrative tool call is: +For a transcription client already provisioned separately, an +illustrative tool call is: {"name":"get_job_status","arguments":{"job_id":"synthetic-existing-job-id"}} -Use a job ID returned by that transcription service. This example does not create a Townlight record or bypass its review/Records handoff. The exact optional adapter tool signatures are supplied in the MCP source reference. Station meeting capture does not become live speech recognition because this optional donor adapter exists. +Use a job ID returned by that transcription service. This example does +not create a Townlight record or bypass its review/Records handoff. The +exact optional adapter tool signatures are supplied in the MCP source +reference. Station meeting capture does not become live speech +recognition because this optional donor adapter exists. Security and permissions -Use your own named account and save before leaving a screen. A saved draft is durable; unsaved form text may not be. If a write has an unknown result, reopen its record before repeating it. - -Read source jurisdiction, dates, citation, version and visibility. A copied source hash identifies exact bytes, not their legal applicability. If a source changes or permission is removed, resolve the source problem rather than substituting stale cached content. - -Keep originals and derivatives separate. Review the intended audience before export. A public summary excludes private fields only through the applicable copy contract and your review. A renamed private packet is still private content. - -Drafting, review, approval, attachment, export, fulfillment and publication are separate operations. A Townlight workpaper does not itself adopt law, issue a permit, impose a fine or release a records response. The responsible staff member records the applicable decision. - -The native session is validated and mapped to a persisted SQL identity. An editable actor/reviewer label is not authentication. Product/module permissions and source visibility apply at the server boundary. Revoked/unavailable authority fails closed for new Station operations; a previous permission result is not a perpetual authorization. - -Use protected local folders, account permissions and credential storage. Never include the native session file, database passwords, provider keys or unredacted support bundles in a public issue or generated public documentation. A local public view is not automatically a secured internet deployment. Keep network exposure and real equipment acceptance specific to the chosen beta site. +Use your own named account and save before leaving a screen. A saved +draft is durable; unsaved form text may not be. If a write has an +unknown result, reopen its record before repeating it. + +Read source jurisdiction, dates, citation, version and visibility. A +copied source hash identifies exact bytes, not their legal +applicability. If a source changes or permission is removed, resolve the +source problem rather than substituting stale cached content. + +Keep originals and derivatives separate. Review the intended audience +before export. A public summary excludes private fields only through the +applicable copy contract and your review. A renamed private packet is +still private content. + +Drafting, review, approval, attachment, export, fulfillment and +publication are separate operations. A Townlight workpaper does not +itself adopt law, issue a permit, impose a fine or release a records +response. The responsible staff member records the applicable decision. + +The native session is validated and mapped to a persisted SQL identity. +An editable actor/reviewer label is not authentication. Product/module +permissions and source visibility apply at the server boundary. +Revoked/unavailable authority fails closed for new Station operations; a +previous permission result is not a perpetual authorization. + +Use protected local folders, account permissions and credential storage. +Never include the native session file, database passwords, provider keys +or unredacted support bundles in a public issue or generated public +documentation. A local public view is not automatically a secured +internet deployment. Keep network exposure and real equipment acceptance +specific to the chosen beta site. Backup recovery and maintenance -Save work and use Core’s canonical Backup Now before maintenance. That operation stops writers. Preserve the coherent profile/database/document backup and its receipt, then use Start to resume. A source export is not a full backup. - -Use Restore Latest Backup through the supported controls. If the result says Restore needs service start, use Start, then Check, and reopen a known record. Do not repeat restore merely because services need to start. The prior accepted profile exercise verified request/marker recovery for its identified artifact. Repeat the required recovery proof for this changed signed candidate before calling it accepted. - -Keep Station’s dedicated database and media evidence together in its own backup. Core’s native-profile backup must not be assumed to include an external Station data directory. Stop writers during a coordinated backup. Preserve failed media attempts and logs. - -On failure, record the time, selected composition, component/installer versions and exact message. Check System Health for stopped, starting, ready or failed dependencies. Use the existing Retry control after readiness; do not create duplicate business records to refresh a stale view. Share only a redacted diagnostic bundle. Preserve secrets, original evidence, recovery material and unrelated installations. +Save work and use Core’s canonical Backup Now before maintenance. That +operation stops writers. Preserve the coherent profile/database/document +backup and its receipt, then use Start to resume. A source export is not +a full backup. + +Use Restore Latest Backup through the supported controls. If the result +says Restore needs service start, use Start, then Check, and reopen a +known record. Do not repeat restore merely because services need to +start. The prior accepted profile exercise verified request/marker +recovery for its identified artifact. Repeat the required recovery proof +for this changed signed candidate before calling it accepted. + +Keep Station’s dedicated database and media evidence together in its own +backup. Core’s native-profile backup must not be assumed to include an +external Station data directory. Stop writers during a coordinated +backup. Preserve failed media attempts and logs. + +On failure, record the time, selected composition, component/installer +versions and exact message. Check System Health for stopped, starting, +ready or failed dependencies. Use the existing Retry control after +readiness; do not create duplicate business records to refresh a stale +view. Share only a redacted diagnostic bundle. Preserve secrets, +original evidence, recovery material and unrelated installations. Troubleshooting - ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - Symptom Likely meaning Next action - ----------------------------- ------------------------------------------------------------------------ ---------------------------------------------------------------------------------------------------- - Workspace absent Wrong product composition or unavailable canonical runtime. Check selected composition; activate through Finish Records Migration; wait for readiness. - - Cannot sign in / 401 Missing or expired named account session. Sign in normally; reopen a Station launch ticket if applicable. - - Permission denied / 403 Account, module, source or browser-origin permission. Ask the authorized administrator to inspect the intended permission; do not invent role headers. - - Save conflict / 409 The saved revision, expected source hash or lifecycle changed. Keep edits, reopen current state and reconcile deliberately. - - Invalid input / 422 Required field, format, geometry, source envelope or state is invalid. Read the field detail and correct the input/source; preserve originals. - - Service unavailable / 503 Database, schema, connected source or configuration unavailable. Inspect System Health and the named dependency. Preserve work; retry only after readiness. - - Export refused Missing exact review, approval, audience or source authorization. Read the refusal and complete the owning product’s explicit decision. - - Restore needs service start The snapshot was restored but services have not resumed. Use Start, then Check and verify a saved record; do not blindly repeat restore. - - Ticket expired or used A launch is one-use and expires after 60 seconds. Reopen from the signed-in native session; do not replay the old URL. - - Recording interrupted Input/worker failed or a live signal was lost. Retain attempt/logs. Retry eligible file work explicitly; start a new live capture for a live gap. - - Recording not downloadable It is not complete or its retained bytes failed validation. Inspect state and evidence; do not serve a partial attempt as completed media. - ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------------------------------------------- + Symptom Likely meaning Next action + ----------------------- ----------------------- ----------------------- + Workspace absent Wrong product Check selected + composition or composition; activate + unavailable canonical through Finish Records + runtime. Migration; wait for + readiness. + + Cannot sign in / 401 Missing or expired Sign in normally; + named account session. reopen a Station launch + ticket if applicable. + + Permission denied / 403 Account, module, source Ask the authorized + or browser-origin administrator to + permission. inspect the intended + permission; do not + invent role headers. + + Save conflict / 409 The saved revision, Keep edits, reopen + expected source hash or current state and + lifecycle changed. reconcile deliberately. + + Invalid input / 422 Required field, format, Read the field detail + geometry, source and correct the + envelope or state is input/source; preserve + invalid. originals. + + Service unavailable / Database, schema, Inspect System Health + 503 connected source or and the named + configuration dependency. Preserve + unavailable. work; retry only after + readiness. + + Export refused Missing exact review, Read the refusal and + approval, audience or complete the owning + source authorization. product’s explicit + decision. + + Restore needs service The snapshot was Use Start, then Check + start restored but services and verify a saved + have not resumed. record; do not blindly + repeat restore. + + Ticket expired or used A launch is one-use and Reopen from the + expires after 60 signed-in native + seconds. session; do not replay + the old URL. + + Recording interrupted Input/worker failed or Retain attempt/logs. + a live signal was lost. Retry eligible file + work explicitly; start + a new live capture for + a live gap. + + Recording not It is not complete or Inspect state and + downloadable its retained bytes evidence; do not serve + failed validation. a partial attempt as + completed media. + ----------------------------------------------------------------------- Verified workflows and limits -The separately configured Station workflow was exercised on the original Windows 1.6.0.1 Beta 1. The follow-up Windows 1.6.0.1 Station delivery exercised encrypted live feed and recording delivery. The Windows 1.8.0.1 acceptance summary records the previous 1.8.0.1 MSI checks. Station capture and its Meetings-to-Records handoff were outside that run. Field equipment, city credentials, and live YouTube commissioning require separate local verification. +The separately configured Station workflow was exercised on the original +Windows 1.6.0.1 Beta 1. The follow-up Windows 1.6.0.1 Station delivery +exercised encrypted live feed and recording delivery. The Windows +1.8.0.1 acceptance summary records the previous 1.8.0.1 MSI checks. +Station capture and its Meetings-to-Records handoff were outside that +run. Field equipment, city credentials, and live YouTube commissioning +require separate local verification. -The separate provisioning/service boundary and existing external-service limits remain as described below. Staff remain responsible for official release and publication decisions. No additional provider or selected-model change is made. +The separate provisioning/service boundary and existing external-service +limits remain as described below. Staff remain responsible for official +release and publication decisions. No additional provider or +selected-model change is made. Terms of service and license Scope and status -These terms describe the Townlight Beta 1 software and this documentation package. This public Windows beta is for evaluation. No uptime commitment, support response time, indemnity, data-processing agreement or paid service is created by these documents. A separate signed agreement, if any, governs services it actually provides. +These terms describe the Townlight Beta 1 software and this +documentation package. This public Windows beta is for evaluation. No +uptime commitment, support response time, indemnity, data-processing +agreement or paid service is created by these documents. A separate +signed agreement, if any, governs services it actually provides. Software license and rights -Current Townlight-owned distributions identified in this candidate use AGPL-3.0-only. The full license is supplied with this documentation and with the source companion. The license governs rights to run, copy, modify and convey the covered software; these operational terms do not add restrictions to those rights. Historical grants and dependency licenses retain their own terms. CivicCast remains a separate product and is not relicensed by this documentation work. - -When conveying covered software, retain applicable notices and provide the corresponding source and installation/build information required by the license. For a modified version supporting remote network interaction, follow section 13’s source-offer requirement. The companion archive identifies the source for this candidate; a link to a different public branch is not a substitute for the matching source. Read the supplied license for the complete conditions. See the GNU license reference and GNU licensing FAQ. +Current Townlight-owned distributions identified in this candidate use +AGPL-3.0-only. The full license is supplied with this documentation and +with the source companion. The license governs rights to run, copy, +modify and convey the covered software; these operational terms do not +add restrictions to those rights. Historical grants and dependency +licenses retain their own terms. CivicCast remains a separate product +and is not relicensed by this documentation work. + +When conveying covered software, retain applicable notices and provide +the corresponding source and installation/build information required by +the license. For a modified version supporting remote network +interaction, follow section 13’s source-offer requirement. The companion +archive identifies the source for this candidate; a link to a different +public branch is not a substitute for the matching source. Read the +supplied license for the complete conditions. See the GNU license +reference and GNU licensing FAQ. Data ownership and access -Importing a document does not transfer its ownership or grant permission to publish it. The operating organization controls its accounts, access decisions, lawful source use, retention and review/release policy. Keep resident information, credentials, private notes and restricted evidence in their authorized locations. Documentation examples contain fictional data. No real city account, credential or record is required to exercise these examples in an isolated test environment. +Importing a document does not transfer its ownership or grant permission +to publish it. The operating organization controls its accounts, access +decisions, lawful source use, retention and review/release policy. Keep +resident information, credentials, private notes and restricted evidence +in their authorized locations. Documentation examples contain fictional +data. No real city account, credential or record is required to exercise +these examples in an isolated test environment. Local operation and external processors -The tested Windows beta workflow uses named staff accounts. Station has separate storage and credentials. Configure backup destinations and optional model/network providers deliberately. A configured external provider may receive submitted prompts, images or audio according to that configuration and provider’s terms; this documentation does not promise that every optional configuration is offline. An email outbox or local public view does not establish external delivery or an internet deployment. This static documentation site has no analytics, account collection or remote font dependency. +The tested Windows beta workflow uses named staff accounts. Station has +separate storage and credentials. Configure backup destinations and +optional model/network providers deliberately. A configured external +provider may receive submitted prompts, images or audio according to +that configuration and provider’s terms; this documentation does not +promise that every optional configuration is offline. An email outbox or +local public view does not establish external delivery or an internet +deployment. This static documentation site has no analytics, account +collection or remote font dependency. Staff decisions and source applicability -Staff verify the jurisdiction, source currency, permissions, citations and proposed audience. Model output and generated guidance require review. No draft is automatically an official legal interpretation, zoning determination, permit approval, fee assessment, enforcement notice or records-release decision. Official permit fee authority remains with the adopted source and responsible organization; imported amounts do not become a new authoritative calculation. +Staff verify the jurisdiction, source currency, permissions, citations +and proposed audience. Model output and generated guidance require +review. No draft is automatically an official legal interpretation, +zoning determination, permit approval, fee assessment, enforcement +notice or records-release decision. Official permit fee authority +remains with the adopted source and responsible organization; imported +amounts do not become a new authoritative calculation. Beta operation and recovery -Windows 1.8.0.1 was tested for fresh installation and in-place upgrade from 1.7.2.1. Upgrade paths from versions older than 1.7.2.1 are unverified. Station uses its separately configured service. Keep backups and original evidence. Test your physical equipment and network and service configuration before relying on them. See the acceptance summary for the tested paths. +Windows 1.8.0.1 was tested for fresh installation and in-place upgrade +from 1.7.2.1. Upgrade paths from versions older than 1.7.2.1 are +unverified. Station uses its separately configured service. Keep backups +and original evidence. Test your physical equipment and network and +service configuration before relying on them. See the acceptance summary +for the tested paths. Warranty and liability -The covered software’s warranty and liability conditions are those in sections 15–17 of the supplied AGPL and any applicable separate written undertaking. This documentation creates no additional warranty or limitation beyond those terms. Third-party software is subject to its retained license notices. Nothing here removes rights that applicable law makes nonwaivable. +The covered software’s warranty and liability conditions are those in +sections 15–17 of the supplied AGPL and any applicable separate written +undertaking. This documentation creates no additional warranty or +limitation beyond those terms. Third-party software is subject to its +retained license notices. Nothing here removes rights that applicable +law makes nonwaivable. Support and incident reporting -Use the project’s existing SUPPORT and SECURITY guidance for its matching repository. Report reproducible behavior with the version, operation and redacted logs. Do not put credentials, resident records or unredacted evidence in a public issue. Coordinate sensitive reports through the channel designated in SECURITY. No new support address or service commitment is invented here. +Use the project’s existing SUPPORT and SECURITY guidance for its +matching repository. Report reproducible behavior with the version, +operation and redacted logs. Do not put credentials, resident records or +unredacted evidence in a public issue. Coordinate sensitive reports +through the channel designated in SECURITY. No new support address or +service commitment is invented here. Ending a beta exercise and document changes -When an organization ends testing, it controls retention/export and removes access according to its policy. Uninstall may retain data; back up and inspect the selected removal options. Ending an exercise does not revoke rights already granted by AGPL. Later software/documentation versions must identify their changed candidate and scope; historical receipts retain their original identities. These terms do not claim that a city has accepted a contract merely by reading a manual. +When an organization ends testing, it controls retention/export and +removes access according to its policy. Uninstall may retain data; back +up and inspect the selected removal options. Ending an exercise does not +revoke rights already granted by AGPL. Later software/documentation +versions must identify their changed candidate and scope; historical +receipts retain their original identities. These terms do not claim that +a city has accepted a contract merely by reading a manual. Glossary - --------------------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------------------------------------------- Term Meaning - ----------------------------------- --------------------------------------------------------------------------------------------------------------------- - Approval An explicit authorized decision on the saved text/artifact. It is separate from saving or attachment. + ----------------------------------- ----------------------------------- + Approval An explicit authorized decision on + the saved text/artifact. It is + separate from saving or attachment. - Canonical record The owning product’s retained identity and saved version, rather than an editable copied label. + Canonical record The owning product’s retained + identity and saved version, rather + than an editable copied label. - Composition The selected set of desktop modules; inspections-preview exposes the eight staff products. + Composition The selected set of desktop + modules; inspections-preview + exposes the eight staff products. - Corresponding source The source/build material matching the delivered covered program, subject to its license. + Corresponding source The source/build material matching + the delivered covered program, + subject to its license. - Derivative / Records copy A separately prepared document with its own intended audience and hash. + Derivative / Records copy A separately prepared document with + its own intended audience and hash. - Hash / SHA256 A fingerprint of exact bytes. It detects change; it does not establish legal authority. + Hash / SHA256 A fingerprint of exact bytes. It + detects change; it does not + establish legal authority. - Idempotency Repeating the same identified request has the same intended effect; changing its payload can be refused. + Idempotency Repeating the same identified + request has the same intended + effect; changing its payload can be + refused. - IPC The native desktop command boundary between its browser interface and Rust host. + IPC The native desktop command boundary + between its browser interface and + Rust host. - MCP Model Context Protocol; no direct Townlight product server is enabled by this beta. + MCP Model Context Protocol; no direct + Townlight product server is enabled + by this beta. - Original Retained source bytes. A reviewed derivative does not replace them. + Original Retained source bytes. A reviewed + derivative does not replace them. - Provenance Source, version, date, actor and relationship information retained with evidence. + Provenance Source, version, date, actor and + relationship information retained + with evidence. - Revision An immutable saved version. Later edits do not inherit an earlier review automatically. + Revision An immutable saved version. Later + edits do not inherit an earlier + review automatically. - Snapshot A fixed audience-specific copy tied to a source/reviewed revision. + Snapshot A fixed audience-specific copy tied + to a source/reviewed revision. - Station Townlight’s separate media boundary using a pinned CivicCast-derived engine; standalone CivicCast remains separate. - --------------------------------------------------------------------------------------------------------------------------------------------------------- + Station Townlight’s separate media boundary + using a pinned CivicCast-derived + engine; standalone CivicCast + remains separate. + ----------------------------------------------------------------------- Alphabetical subject index @@ -649,22 +1335,33 @@ Alphabetical subject index Operating subject links - Apply the caption profile — Apply the caption profile. -- Approve and publish local playback — Approve and publish local playback. +- Approve and publish local playback — Approve and publish local + playback. - Bounds and shutdown — Bounds and shutdown. -- Check playout and commit deliberately — Check playout and commit deliberately. -- Configure a live input and open the operator — Configure a live input and open the operator. -- Prepare the normally activated synthetic profile — Prepare the normally activated synthetic profile. -- Provision the Station database once — Provision the Station database once. -- Recover without replaying unknown work — Recover without replaying unknown work. -- Schedule a recording and interpret its state — Schedule a recording and interpret its state. +- Check playout and commit deliberately — Check playout and commit + deliberately. +- Configure a live input and open the operator — Configure a live input + and open the operator. +- Prepare the normally activated synthetic profile — Prepare the + normally activated synthetic profile. +- Provision the Station database once — Provision the Station database + once. +- Recover without replaying unknown work — Recover without replaying + unknown work. +- Schedule a recording and interpret its state — Schedule a recording + and interpret its state. - Scheduling playout and recovery — Scheduling playout and recovery. -- Start and check the paired processes — Start and check the paired processes. -- Store the independent test configuration — Store the independent test configuration. +- Start and check the paired processes — Start and check the paired + processes. +- Store the independent test configuration — Store the independent test + configuration. - Take a live override and return — Take a live override and return. Source and document control -This manual covers the Station service paired with Windows MSI 1.8.1.1. The Windows acceptance summary records the tested Meetings, Station and Records handoff. +This manual covers the Station service paired with Windows MSI 1.8.1.1. +The Windows acceptance summary records the tested Meetings, Station and +Records handoff. Workflow subject index @@ -696,23 +1393,63 @@ Workflow subject index Completed recordings on YouTube and live CivicCast coverage -This source extension adds only completed-recording YouTube uploads and a live Station-to-CivicCast feed. It is not in the published Beta 1 installer. Existing component versions are retained. New Station code is AGPL-3.0-only. The pinned CivicCast source and third-party licenses remain unchanged. Standalone CivicCast is a separate product; no installer, account, database, service or default in it is changed by Station. +This source extension adds only completed-recording YouTube uploads and +a live Station-to-CivicCast feed. It is not in the published Beta 1 +installer. Existing component versions are retained. New Station code is +AGPL-3.0-only. The pinned CivicCast source and third-party licenses +remain unchanged. Standalone CivicCast is a separate product; no +installer, account, database, service or default in it is changed by +Station. Staff workflow -For live coverage, choose a meeting, its chamber input and the administrator’s CivicCast live feed option, then start recording. Choose Recording only to capture privately without a network feed. A disconnected receiver does not stop the recording. Station sends the live MPEG-TS bytes as the recording grows; it does not wait for the completed file. The feed is available only during that capture. The CivicCast/PEG operator selects that source and controls when it is broadcast on local cable. Station does not automatically put the PEG channel on air. sending means transport bytes were sent, not proof of cable carriage. - -After Station shows complete, use Upload completed recording to YouTube. Review the title, select private/unlisted/public visibility (default private), and enter the approval note. Click Upload to YouTube. This is an explicit external upload to the Station-configured OAuth account. No upload occurs just because recording stopped, a playout was committed or a Records attachment was made. Station does not create a YouTube livestream. - -The upload receipt shows queued/running/uploaded/failed/needs-reconciliation, the chosen visibility and returned video link. uploaded is the YouTube upload acknowledgement; YouTube may still be processing the video. The canonical recording remains private and byte-identical for the existing Records handoff. The YouTube visibility is separate from local playback/disclosure approval. +For live coverage, choose a meeting, its chamber input and the +administrator’s CivicCast live feed option, then start recording. Choose +Recording only to capture privately without a network feed. A +disconnected receiver does not stop the recording. Station sends the +live MPEG-TS bytes as the recording grows; it does not wait for the +completed file. The feed is available only during that capture. The +CivicCast/PEG operator selects that source and controls when it is +broadcast on local cable. Station does not automatically put the PEG +channel on air. sending means transport bytes were sent, not proof of +cable carriage. + +After Station shows complete, use Upload completed recording to YouTube. +Review the title, select private/unlisted/public visibility (default +private), and enter the approval note. Click Upload to YouTube. This is +an explicit external upload to the Station-configured OAuth account. No +upload occurs just because recording stopped, a playout was committed or +a Records attachment was made. Station does not create a YouTube +livestream. + +The upload receipt shows +queued/running/uploaded/failed/needs-reconciliation, the chosen +visibility and returned video link. uploaded is the YouTube upload +acknowledgement; YouTube may still be processing the video. The +canonical recording remains private and byte-identical for the existing +Records handoff. The YouTube visibility is separate from local +playback/disclosure approval. Architecture -The sender has bounded, leaky buffers and follows the live edge after congestion. Its network sink shares no pipeline with the recorder. A late join or connection loss can leave a live coverage gap, while the private recording continues. H.264/AAC and existing MPEG-TS captions are forwarded without another encode. The MP4 upload remux reuses vod_job.py; it does not generate transcripts or captions, and does not upload a separate caption track. Upload queue work runs in a separate process so a long upload never monopolizes the capture worker. +The sender has bounded, leaky buffers and follows the live edge after +congestion. Its network sink shares no pipeline with the recorder. A +late join or connection loss can leave a live coverage gap, while the +private recording continues. H.264/AAC and existing MPEG-TS captions are +forwarded without another encode. The MP4 upload remux reuses +vod_job.py; it does not generate transcripts or captions, and does not +upload a separate caption track. Upload queue work runs in a separate +process so a long upload never monopolizes the capture worker. Administrator setup -Use Station’s existing dedicated data root and PostgreSQL database. Stop Station writers for a coordinated backup, retain that backup, and run the explicit townlight-station migrate before starting this source version. Schema 4 adds station.youtube_uploads, keeping existing recording/schedule/playout evidence. The data identity marker and component versions are unchanged. Old services expect schema 3; use a matched source/runtime and preserve the backup for rollback. +Use Station’s existing dedicated data root and PostgreSQL database. Stop +Station writers for a coordinated backup, retain that backup, and run +the explicit townlight-station migrate before starting this source +version. Schema 4 adds station.youtube_uploads, keeping existing +recording/schedule/playout evidence. The data identity marker and +component versions are unchanged. Old services expect schema 3; use a +matched source/runtime and preserve the backup for rollback. Create civiccast-feeds.json in the private Station data directory: @@ -726,17 +1463,38 @@ Create civiccast-feeds.json in the private Station data directory: } ] -The address is a numeric IPv4 local interface bind address on Station, not the CivicCast computer. 192.0.2.10 is a documentation placeholder. Use the actual Station interface, an unused port (1024–65535), and appropriate network access between those two systems. Clients select an administrator-defined ID, never an arbitrary destination or media pipeline. Keep configuration files private. - -Set TOWNLIGHT_STATION_SRT_PEG in the capture worker’s process environment to a 10–79 character SRT passphrase. Configure a separate CivicCast SRT live source with the caller URI srt://:10080?mode=caller&latency=200 and the same passphrase through CivicCast’s existing credential control. Do not put the passphrase in the URI. Station’s listener uses 128-bit SRT encryption. Keep the two accounts and configuration stores separate; matching this specific transport credential is the deliberate pairing. Site-specific camera, headend and firewall commissioning remain deployment work. - -For completed uploads, configure these Station-only environment variables in the upload worker process. Obtain OAuth authorization for the intended Station YouTube channel/account through the existing deployment’s Google configuration; no OAuth onboarding framework is added here. Do not use CivicCast’s credentials implicitly or copy its profile. +The address is a numeric IPv4 local interface bind address on Station, +not the CivicCast computer. 192.0.2.10 is a documentation placeholder. +Use the actual Station interface, an unused port (1024–65535), and +appropriate network access between those two systems. Clients select an +administrator-defined ID, never an arbitrary destination or media +pipeline. Keep configuration files private. + +Set TOWNLIGHT_STATION_SRT_PEG in the capture worker’s process +environment to a 10–79 character SRT passphrase. Configure a separate +CivicCast SRT live source with the caller URI +srt://:10080?mode=caller&latency=200 and the same +passphrase through CivicCast’s existing credential control. Do not put +the passphrase in the URI. Station’s listener uses 128-bit SRT +encryption. Keep the two accounts and configuration stores separate; +matching this specific transport credential is the deliberate pairing. +Site-specific camera, headend and firewall commissioning remain +deployment work. + +For completed uploads, configure these Station-only environment +variables in the upload worker process. Obtain OAuth authorization for +the intended Station YouTube channel/account through the existing +deployment’s Google configuration; no OAuth onboarding framework is +added here. Do not use CivicCast’s credentials implicitly or copy its +profile. - TOWNLIGHT_STATION_YOUTUBE_CLIENT_ID - TOWNLIGHT_STATION_YOUTUBE_CLIENT_SECRET -- TOWNLIGHT_STATION_YOUTUBE_REFRESH_TOKEN (authorized for YouTube video uploads) +- TOWNLIGHT_STATION_YOUTUBE_REFRESH_TOKEN (authorized for YouTube video + uploads) -Run the existing serve and capture worker, plus the separate upload consumer with the same Station settings and dedicated database: +Run the existing serve and capture worker, plus the separate upload +consumer with the same Station settings and dedicated database: townlight-station migrate townlight-station serve @@ -744,27 +1502,48 @@ Run the existing serve and capture worker, plus the separate upload consumer wit townlight-station worker townlight-station uploads -These are deployment commands, not commands executed against installed apps by this development task. Run only one capture worker and one upload worker per database. Each holds a distinct advisory lock; media children require the existing Windows job containment. The recorder child gets no provider credentials; the SRT child receives only its explicit transport passphrase plus the existing runtime allowlist. The upload worker reads only the Station OAuth variables. OAuth/upload HTTP is restricted to Google HTTPS hosts; redirects are not followed. The pinned donor import is checked against Station’s declared media source. +These are deployment commands, not commands executed against installed +apps by this development task. Run only one capture worker and one +upload worker per database. Each holds a distinct advisory lock; media +children require the existing Windows job containment. The recorder +child gets no provider credentials; the SRT child receives only its +explicit transport passphrase plus the existing runtime allowlist. The +upload worker reads only the Station OAuth variables. OAuth/upload HTTP +is restricted to Google HTTPS hosts; redirects are not followed. The +pinned donor import is checked against Station’s declared media source. HTTP API and examples -All /v1 operations below require the existing current Townlight staff session header (X-Townlight-Session) or the existing same-origin operator session. Read roles can inspect receipts. Starting live feed/upload/retry requires the existing Station capture capability. No new login, role system or MCP server is added. +All /v1 operations below require the existing current Townlight staff +session header (X-Townlight-Session) or the existing same-origin +operator session. Read roles can inspect receipts. Starting live +feed/upload/retry requires the existing Station capture capability. No +new login, role system or MCP server is added. - ------------------------------------------------------------------------------------------------------------------------------------------ - Method and route Purpose - -------------------------------------------- --------------------------------------------------------------------------------------------- - GET /v1/civiccast-feeds Capture-authorized list of configured IDs and labels; no transport credentials + --------------------------------------------------------------------------- + Method and route Purpose + --------------------------------------- ----------------------------------- + GET /v1/civiccast-feeds Capture-authorized list of + configured IDs and labels; no + transport credentials - POST /v1/recordings Existing capture contract plus optional civiccast_feed_id, allowed only with live_source_id + POST /v1/recordings Existing capture contract plus + optional civiccast_feed_id, allowed + only with live_source_id - POST /v1/recordings/{recording_id}/youtube Queue one explicit completed-recording upload + POST Queue one explicit + /v1/recordings/{recording_id}/youtube completed-recording upload - GET /v1/youtube-uploads Read-authorized latest 100 durable upload receipts + GET /v1/youtube-uploads Read-authorized latest 100 durable + upload receipts - POST /v1/youtube-uploads/{upload_id}/retry Capture-authorized retry of a preparation failure only - ------------------------------------------------------------------------------------------------------------------------------------------ + POST Capture-authorized retry of a + /v1/youtube-uploads/{upload_id}/retry preparation failure only + --------------------------------------------------------------------------- -Station’s generated /openapi.json includes the new routes and request schemas. Example bodies (use real canonical IDs from the selected deployment): +Station’s generated /openapi.json includes the new routes and request +schemas. Example bodies (use real canonical IDs from the selected +deployment): { "meeting_id": "11111111-1111-4111-8111-111111111111", @@ -781,31 +1560,73 @@ Station’s generated /openapi.json includes the new routes and request schemas. "idempotency_key": "council-vod-2026-10-30" } -Upload titles are 1–100 characters; control characters and angle brackets are rejected. Visibility is private/unlisted/public; approval note 3–500 characters; key 1–100 characters. Repeating the same key returns the same intent, a changed request conflicts, and another key cannot duplicate an existing recording upload. A missing/uncompleted/tampered recording is rejected before upload admission; the worker independently verifies the recording hash before remuxing/sending. Retained receipts include approving actor, note/time, recording hash, MP4 path/ hash/size, chosen title/privacy and provider video ID/URL after acknowledgement. No OAuth token, passphrase or donor credential pointer is stored in receipts. +Upload titles are 1–100 characters; control characters and angle +brackets are rejected. Visibility is private/unlisted/public; approval +note 3–500 characters; key 1–100 characters. Repeating the same key +returns the same intent, a changed request conflicts, and another key +cannot duplicate an existing recording upload. A +missing/uncompleted/tampered recording is rejected before upload +admission; the worker independently verifies the recording hash before +remuxing/sending. Retained receipts include approving actor, note/time, +recording hash, MP4 path/ hash/size, chosen title/privacy and provider +video ID/URL after acknowledgement. No OAuth token, passphrase or donor +credential pointer is stored in receipts. Recovery and limits -A failed preparation (for example missing Station OAuth configuration or failed remux) is failed; correct the cause and explicitly call its retry route. The prior attempt files remain retained. Once any external request begins, an error is conservatively needs-reconciliation. A worker restart also moves interrupted running uploads to that state. There is no automatic retry that could create a duplicate YouTube video. Check YouTube Studio and the retained job before a human chooses another external action. This increment provides no automatic remote reconciliation/delete/reupload control. A valid uploaded link is retained even if the capture worker is restarted. The existing recording/Records path does not depend on the external upload succeeding. - -Live sender state is in the recording’s details.civiccast_delivery; its final byte count and per-attempt status/log files stay with the private recording. On capture-worker restart, an interrupted feed is marked interrupted rather than left appearing to send. Stop/reap is bounded even if the network child hangs. No feed is automatically re-aired after recovery. +A failed preparation (for example missing Station OAuth configuration or +failed remux) is failed; correct the cause and explicitly call its retry +route. The prior attempt files remain retained. Once any external +request begins, an error is conservatively needs-reconciliation. A +worker restart also moves interrupted running uploads to that state. +There is no automatic retry that could create a duplicate YouTube video. +Check YouTube Studio and the retained job before a human chooses another +external action. This increment provides no automatic remote +reconciliation/delete/reupload control. A valid uploaded link is +retained even if the capture worker is restarted. The existing +recording/Records path does not depend on the external upload +succeeding. + +Live sender state is in the recording’s details.civiccast_delivery; its +final byte count and per-attempt status/log files stay with the private +recording. On capture-worker restart, an interrupted feed is marked +interrupted rather than left appearing to send. Stop/reap is bounded +even if the network child hangs. No feed is automatically re-aired after +recovery. Verification and release status -tests/accept_deliveries.py exercises the real Station API/store/media/remux, CivicCast’s pinned SRT source adapter and real YouTube file-upload client using a disposable PostgreSQL cluster, generated audio/video, synthetic staff authority and httpx.MockTransport for Google. No city systems or external publication are involved. tests/accept_delivery_ui.cjs drives the actual compiled operator controls in headless Chromium with synthetic API responses. Existing boundary/ operations checks and TypeScript compilation also apply. +tests/accept_deliveries.py exercises the real Station +API/store/media/remux, CivicCast’s pinned SRT source adapter and real +YouTube file-upload client using a disposable PostgreSQL cluster, +generated audio/video, synthetic staff authority and httpx.MockTransport +for Google. No city systems or external publication are involved. +tests/accept_delivery_ui.cjs drives the actual compiled operator +controls in headless Chromium with synthetic API responses. Existing +boundary/ operations checks and TypeScript compilation also apply. -Example invocation from a development environment with existing dependencies: +Example invocation from a development environment with existing +dependencies: $env:PYTHONPATH = (Resolve-Path ./beta-1).Path $env:STATION_TEST_PG_BIN = 'C:/test-tools/postgres/bin' $env:STATION_TEST_MEDIA_RUNTIME = 'C:/test-tools/station-media-runtime' python -B ./beta-1/tests/accept_deliveries.py C:/test-output/station-deliveries-new -Use a new output directory; the script starts/stops only its owned disposable cluster and children. See the task’s retained acceptance receipts for actual results. This evidence establishes the new source wiring synthetically. It does not replace CivicCast’s already established real YouTube delivery evidence, nor claim a new real YouTube upload, physical cable broadcast, signed installer or Sandbox acceptance of this extension. Published Beta 1 artifacts stay unchanged. +Use a new output directory; the script starts/stops only its owned +disposable cluster and children. See the task’s retained acceptance +receipts for actual results. This evidence establishes the new source +wiring synthetically. It does not replace CivicCast’s already +established real YouTube delivery evidence, nor claim a new real YouTube +upload, physical cable broadcast, signed installer or Sandbox acceptance +of this extension. Published Beta 1 artifacts stay unchanged. Delivery subject index - CivicCast live feed -- YouTube: explicit completed recording upload; visibility; receipt and reconciliation. +- YouTube: explicit completed recording upload; visibility; receipt and + reconciliation. - Schema4: durable upload intent; existing evidence retained. -The resident portal is deployed separately. See the Townlight Portal Guide for its workflow and acceptance limits. +The resident portal is deployed separately. See the Townlight Portal +Guide for its workflow and acceptance limits. diff --git a/beta-1/README.md b/beta-1/README.md index d1e2076f..df3d915e 100644 --- a/beta-1/README.md +++ b/beta-1/README.md @@ -1,5 +1,10 @@ ## Windows 1.8.2.1 maintenance release +## Station recorder candidate + +Windows 1.9.0.1 / Station 0.4.0 is in development and has not been published. It adds integrated recorder setup/recovery, camera and microphone selection with a test clip, eight-hour/64 GiB recording limits and streamed Records attachment, and renewable authorized operator sessions. Existing released MSI and historical acceptance remain unchanged. Installed candidate acceptance and merge are pending; tagging/publication require Scott approval. + + Windows 1.8.2.1 packages the staff authorization, explicit database configuration and component metadata corrections. Its exact signed installed checks cover setup, the 1.8.1.1 upgrade, saved staff records, procurement/Contracts handoffs, backup/restore and uninstall retention. Unchanged module and 31-source/34-format import evidence remains attributed to the earlier build that produced it; this is not a new exhaustive test of every module or live provider. Windows 1.8.2.1 has signed installed acceptance for fresh setup and an in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city data and settings, close Townlight, run the signed MSI, and reopen it under the same Windows account with the existing `%LOCALAPPDATA%\CivicSuite` profile. Keep the prior installer and a restore path. Other upgrade paths are unverified. Station uses its separately configured service. The acceptance summary distinguishes new maintenance checks from reused workflow evidence. diff --git a/beta-1/USER-MANUAL.docx b/beta-1/USER-MANUAL.docx index 3e9da8b3..1b30d336 100644 Binary files a/beta-1/USER-MANUAL.docx and b/beta-1/USER-MANUAL.docx differ diff --git a/beta-1/USER-MANUAL.md b/beta-1/USER-MANUAL.md index 1ff50d11..b0f39872 100644 --- a/beta-1/USER-MANUAL.md +++ b/beta-1/USER-MANUAL.md @@ -1,5 +1,35 @@ ## Windows 1.8.2.1 maintenance release +## Windows recorder update — 1.9.0.1 candidate (not published) + +This section describes the new candidate. The public 1.8.2.1 MSI does not acquire these capabilities until a new release is approved and published. Candidate verification and its limits are recorded in the [recorder completion record](https://github.com/townlight/station/blob/main/beta-1/docs/RECORDER-COMPLETION.md); this is separate from the published 1.8.2.1 evidence. + +### Clerk and operator + +1. Install Townlight and complete normal first-run setup with the full Windows profile or a custom selection that includes Meetings and Records (Station is bundled). Finishing setup provisions the bundled recorder, a private database and Windows sign-in task. No PostgreSQL, Python or media-runtime installation commands are needed. Existing installations use Settings → Modules → Townlight Station → **Set up meeting recording**. +2. Keep Windows signed in and the computer awake while recording. The recorder runs in that user's device-access session, independently of the Townlight window. It is not a multi-user server or a full PEG station. Closing the recorder tab does not stop a recording. +3. Sign in with an existing authorized staff account. From Meetings choose **Open / reconnect to meeting recorder**. Select a meeting and its agenda items. In input setup, find devices, choose one camera/capture device and one microphone, and save. Record a ten-second input test, then play it to check the picture and sound; the meter responds during playback. This test clip is temporary and is not a canonical meeting record. Windows camera/microphone privacy settings and exclusive device use still apply. Configured UDP MPEG-TS input remains supported. +4. Start the meeting recording. The default duration limit is eight hours, with a 64 GiB file limit and at least 1 GiB reserved disk space. Admission estimates the configured duration and bitrate. Free space is monitored while recording; low space or a limit requests a graceful stop and displays the reason. These are configured limits, not a claim that every eight-hour meeting has been tested. Plan space for the recording, its Records copy and backups. Sleep, sign-out, power failure and unavailable hardware can interrupt capture. +5. An open operator page renews its fifteen-minute session against the current Townlight staff authority. Sign-out, revoked permissions and the underlying staff-session expiry still take effect. Reopen from Townlight to reconnect to an existing recording; reconnect never starts a second recording. Select **Stop recording** to drain and finalize the file. +6. After completion, an authorized Records user selects a request and explicitly attaches the recording. Records streams a separate managed copy and verifies SHA-256, size and provenance; files up to 64 GiB are accepted subject to available space. Attachment is not public release. Review, redaction and publication remain separate Records decisions. + +### Administrator and recovery + +Station setup uses bundled native dependencies and its existing pinned CivicCast media implementation; it never starts or changes CivicCast or CivicCast Lab. The per-user logon task owns a separate PostgreSQL instance on loopback port 15435; Station's API listens only on 127.0.0.1:8756. Townlight's existing staff authority remains on its configured Suite origin. Protected settings and database credentials remain in the recorder data directory, under the selected city data location. Setup refuses unrelated nonempty storage or an unrelated task with the same name. Retry setup after correcting readiness errors; inspect the private background, PostgreSQL, API and worker logs when needed. + +Use **Check recorder readiness**, **Back up Station**, and **Restore Station backup** in Settings → Modules. Finish queued and active recordings before backup or restore. Backups contain a PostgreSQL dump, recording/ingest files, saved source choices and a SHA-256 member manifest; they omit credentials and native executables. Restore verifies the members, creates a pre-restore recovery copy, and restores into this installation's separately protected database. Recheck input selection afterward. A Suite backup includes a coherent Station backup when paired; it does not copy the running Station database or its secrets. Suite restore preserves that live private directory and applies the included Station backup separately. + +```mermaid +flowchart LR + Staff[Existing Townlight staff authority] --> Operator[Station operator] + Camera[Camera and microphone or UDP feed] --> Recorder[Per-user background recorder] + Operator --> Recorder + Recorder --> Private[Private Station database and recording] + Private -->|Explicit hash-verified attachment| Records[Records managed copy] + Records --> Review[Separate review and release decision] +``` + + Windows 1.8.2.1 packages the staff authorization, explicit database configuration and component metadata corrections. Its exact signed installed checks cover setup, the 1.8.1.1 upgrade, saved staff records, procurement/Contracts handoffs, backup/restore and uninstall retention. Unchanged module and 31-source/34-format import evidence remains attributed to the earlier build that produced it; this is not a new exhaustive test of every module or live provider. Windows 1.8.2.1 has signed installed acceptance for fresh setup and an in-place upgrade from Windows 1.8.1.1. Before upgrading, back up city data and settings, close Townlight, run the signed MSI, and reopen it under the same Windows account with the existing `%LOCALAPPDATA%\CivicSuite` profile. Keep the prior installer and a restore path. Other upgrade paths are unverified. Station uses its separately configured service. The acceptance summary distinguishes new maintenance checks from reused workflow evidence. diff --git a/beta-1/USER-MANUAL.pdf b/beta-1/USER-MANUAL.pdf index 0e1997d8..89ecf590 100644 Binary files a/beta-1/USER-MANUAL.pdf and b/beta-1/USER-MANUAL.pdf differ diff --git a/beta-1/docs/RECORDER-COMPLETION.md b/beta-1/docs/RECORDER-COMPLETION.md new file mode 100644 index 00000000..1d11eb84 --- /dev/null +++ b/beta-1/docs/RECORDER-COMPLETION.md @@ -0,0 +1,32 @@ +# Windows recorder completion contract + +## Windows recorder update — 1.9.0.1 candidate (not published) + +The Townlight Station candidate verification record covers Windows 1.9.0.1 as an unpublished candidate, while 1.8.2.1 is the current public release. See the [Suite pull request checks](https://github.com/townlight/townlight/pull/330/checks) for installed acceptance results. + +### Clerk and operator + +1. Install Townlight and complete normal first-run setup with the full Windows profile or a custom selection that includes Meetings and Records (Station is bundled). Finishing setup provisions the bundled recorder, a private database and Windows sign-in task. No PostgreSQL, Python or media-runtime installation commands are needed. Existing installations use Settings → Modules → Townlight Station → **Set up meeting recording**. +2. Keep Windows signed in and the computer awake while recording. The recorder runs in that user's device-access session, independently of the Townlight window. It is not a multi-user server or a full PEG station. Closing the recorder tab does not stop a recording. +3. Sign in with an existing authorized staff account. From Meetings choose **Open / reconnect to meeting recorder**. Select a meeting and its agenda items. In input setup, find devices, choose one camera/capture device and one microphone, and save. Record a ten-second input test, then play it to check the picture and sound; the meter responds during playback. This test clip is temporary and is not a canonical meeting record. Windows camera/microphone privacy settings and exclusive device use still apply. Configured UDP MPEG-TS input remains supported. +4. Start the meeting recording. The default duration limit is eight hours, with a 64 GiB file limit and at least 1 GiB reserved disk space. Admission estimates the configured duration and bitrate. Free space is monitored while recording; low space or a limit requests a graceful stop and displays the reason. These are configured limits, not a claim that every eight-hour meeting has been tested. Plan space for the recording, its Records copy and backups. Sleep, sign-out, power failure and unavailable hardware can interrupt capture. +5. An open operator page renews its fifteen-minute session against the current Townlight staff authority. Sign-out, revoked permissions and the underlying staff-session expiry still take effect. Reopen from Townlight to reconnect to an existing recording; reconnect never starts a second recording. Select **Stop recording** to drain and finalize the file. +6. After completion, an authorized Records user selects a request and explicitly attaches the recording. Records streams a separate managed copy and verifies SHA-256, size and provenance; files up to 64 GiB are accepted subject to available space. Attachment is not public release. Review, redaction and publication remain separate Records decisions. + +### Administrator and recovery + +Station setup uses bundled native dependencies and its existing pinned CivicCast media implementation; it never starts or changes CivicCast or CivicCast Lab. The per-user logon task owns a separate PostgreSQL instance on loopback port 15435; Station's API listens only on 127.0.0.1:8756. Townlight's existing staff authority remains on its configured Suite origin. Protected settings and database credentials remain in the recorder data directory, under the selected city data location. Setup refuses unrelated nonempty storage or an unrelated task with the same name. Retry setup after correcting readiness errors; inspect the private background, PostgreSQL, API and worker logs when needed. + +Use **Check recorder readiness**, **Back up Station**, and **Restore Station backup** in Settings → Modules. Finish queued and active recordings before backup or restore. Backups contain a PostgreSQL dump, recording/ingest files, saved source choices and a SHA-256 member manifest; they omit credentials and native executables. Restore verifies the members, creates a pre-restore recovery copy, and restores into this installation's separately protected database. Recheck input selection afterward. A Suite backup includes a coherent Station backup when paired; it does not copy the running Station database or its secrets. Suite restore preserves that live private directory and applies the included Station backup separately. + +```mermaid +flowchart LR + Staff[Existing Townlight staff authority] --> Operator[Station operator] + Camera[Camera and microphone or UDP feed] --> Recorder[Per-user background recorder] + Operator --> Recorder + Recorder --> Private[Private Station database and recording] + Private -->|Explicit hash-verified attachment| Records[Records managed copy] + Records --> Review[Separate review and release decision] +``` + +Persistent recorder settings use current-user Windows DPAPI. The background task runs as that same account. PostgreSQL initialization receives its bootstrap credential through an account-private local memory pipe; no plaintext password file is created. Station backups exclude credentials. diff --git a/beta-1/operator-ui/src/operator.css b/beta-1/operator-ui/src/operator.css index 13ce6afe..551368f4 100644 --- a/beta-1/operator-ui/src/operator.css +++ b/beta-1/operator-ui/src/operator.css @@ -1,3 +1,4 @@ /* SPDX-License-Identifier: AGPL-3.0-only */ :root{color-scheme:light;font-family:system-ui,sans-serif;color:#17333b;background:#f2f5f3}*{box-sizing:border-box}body{margin:0}header,main,footer{max-width:1100px;margin:auto;padding:24px}header{display:flex;justify-content:space-between;align-items:center;border-bottom:2px solid #cbd9d3}h1{font-size:40px;margin:4px 0}h2{font-size:24px;margin-top:0}.eyebrow{font-size:12px;letter-spacing:3px;font-weight:700}section{background:white;border:1px solid #cbd9d3;border-radius:12px;padding:24px;margin:20px 0}p{line-height:1.5}label{display:grid;gap:7px;font-weight:600;flex:1}form,.section-heading{display:flex;gap:16px;align-items:end;margin:18px 0}input,select,button{font:inherit;border:1px solid #829b91;border-radius:6px;padding:11px;min-height:44px}input,select{width:100%;background:#fff}button{cursor:pointer;background:#155b4c;color:white;font-weight:600;white-space:nowrap}button:disabled{opacity:.55;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #d07b1a;outline-offset:3px}.section-heading{justify-content:space-between}article{border-top:1px solid #d9e3df;padding:20px 0;overflow-wrap:anywhere}article h3{margin:0 0 8px}.status{font-weight:700}.error{color:#962716}#message{border-left:4px solid #155b4c;padding:12px;background:#e3eee8}footer{color:#4b645b;font-size:14px}[hidden]{display:none!important}@media(max-width:650px){header,main,footer{padding:16px}section{padding:16px}form{flex-direction:column;align-items:stretch}h1{font-size:32px}header{align-items:start}header button{white-space:normal}} .agenda-choice{display:flex;align-items:center;gap:12px;margin:12px 0}.agenda-choice input{width:20px;min-height:20px}details{margin-top:18px;font-size:14px} +video{display:block;max-width:100%;width:640px;background:#152f3a;margin:16px 0}meter{width:100%;max-width:640px;height:24px} diff --git a/beta-1/operator-ui/src/operator.tsx b/beta-1/operator-ui/src/operator.tsx index 33864b2c..1bed9a2f 100644 --- a/beta-1/operator-ui/src/operator.tsx +++ b/beta-1/operator-ui/src/operator.tsx @@ -17,6 +17,9 @@ function App(){ const [imported,setImported]=useState<{index:number;direct:boolean}[]>([]),[importIndex,setImportIndex]=useState(''); const [onAirSource,setOnAirSource]=useState(''),[reason,setReason]=useState(''); const [feeds,setFeeds]=useState([]),[feed,setFeed]=useState(''),[uploads,setUploads]=useState([]); + const [devices,setDevices]=useState([]),[camera,setCamera]=useState(''),[microphone,setMicrophone]=useState(''); + const [preview,setPreview]=useState(''),[storage,setStorage]=useState(null),[level,setLevel]=useState(0); + const previewElement=useRef(null); const pending=useRef(null), refreshing=useRef(false); const tell=(text:string,bad=false)=>{setMessage(text);setError(bad);}; const fail=(e:any)=>{tell(e.message,true);if(e.status===401)setConnected(false);}; @@ -36,6 +39,7 @@ function App(){ replace('records',views[0],setRecords);replace('schedules',views[1],setSchedules); replace('playouts',views[2],setPlayouts);replace('air',views[3],setAir); const deliveries=await api('/v1/youtube-uploads');setUploads(deliveries); + setStorage(await api('/operator/storage')); }catch(e){fail(e);}finally{refreshing.current=false;} } useEffect(()=>{let alive=true;(async()=>{try{ @@ -46,6 +50,34 @@ function App(){ await refresh(); }catch(e){fail(e);}})();return()=>{alive=false;};},[]); useEffect(()=>{if(!connected)return;const timer=setInterval(refresh,2000);return()=>clearInterval(timer);},[connected]); + useEffect(()=>{if(!connected)return;const timer=setInterval(()=>{ + api('/operator/renew',{}).catch(fail); + },60000);return()=>clearInterval(timer);},[connected]); + useEffect(()=>{ + if(!preview||!previewElement.current)return; + const context=new AudioContext(),node=context.createMediaElementSource(previewElement.current); + const analyser=context.createAnalyser();node.connect(analyser);analyser.connect(context.destination); + const buffer=new Uint8Array(analyser.fftSize); + const timer=setInterval(()=>{analyser.getByteTimeDomainData(buffer); + setLevel(Math.sqrt(buffer.reduce((sum,v)=>sum+((v-128)/128)**2,0)/buffer.length));},100); + const resume=()=>{void context.resume();};previewElement.current.addEventListener('play',resume); + const video=previewElement.current; + return()=>{clearInterval(timer);video.removeEventListener('play',resume);void context.close();}; + },[preview]); + async function findDevices(){setBusy(true);try{ + const found=await api('/operator/devices');setDevices(found); + setCamera(found.find((d:any)=>d.kind==='video')?.id||''); + setMicrophone(found.find((d:any)=>d.kind==='audio')?.id||''); + tell(found.length?'Choose the chamber camera and microphone.':'No supported inputs found. Check Windows permissions and device connections.'); + }catch(e){fail(e);}finally{setBusy(false);}} + async function saveDevices(e:React.FormEvent){e.preventDefault();setBusy(true);try{ + const input=await api('/operator/devices',{video_id:camera,audio_id:microphone}); + setSources(await api('/v1/live-sources'));setSource(input.id); + tell('Chamber inputs saved. Run a test and check picture and sound.'); + }catch(e){fail(e);}finally{setBusy(false);}} + async function testDevices(){setBusy(true);setPreview('');try{ + const result=await api('/operator/input-test',{});setPreview(result.preview_url+'?v='+Date.now());tell(result.message); + }catch(e){fail(e);}finally{setBusy(false);}} async function queueCapture(values:object){ if(!pending.current||JSON.stringify(pending.current.values)!==JSON.stringify(values))pending.current={values,key:crypto.randomUUID()}; await api('/v1/recordings',{...values,idempotency_key:pending.current.key});pending.current=null;tell('Recording accepted. Watch its status below.');await refresh(); @@ -89,7 +121,18 @@ function App(){ } {!sources.length&&

No live input configured. Ask your Station administrator to configure the chamber feed.

}} + {connected&&catalog?.can_capture&&

Chamber camera and microphone

+

Use one local camera/capture input and microphone, or retain your configured network chamber feed. Input testing is unavailable during a meeting recording.

+ + {devices.length>0&&
+ + +
} + + {preview&&
} +
} {connected&&catalog?.can_capture&&

Record a meeting

Select the meeting and chamber feed. Recordings remain private for Records review.

+ {storage&&

Recording storage: {(storage.free_bytes/1024**3).toFixed(1)} GB free. Configured maximum: {Math.round(storage.max_seconds/3600)} hours. {!storage.ready?'Free more space before starting.':''} Records needs space for its separate verified copy.

}
{catalog.agenda.filter(a=>a.meeting_id===meeting).map(a=>)} @@ -139,6 +182,7 @@ function Recording({record:r,catalog,stop,attach,play,busy,uploads,upload}:{reco const [request,setRequest]=useState(''),[local,setLocal]=useState(false); const status=r.control.stop_requested_at&&['queued','running'].includes(r.status)?'Stopping — finishing and verifying media':r.status==='running'?(r.live_progress?.bytes_written>0?'Recording live feed':'Starting — waiting for live input'):r.status; return

{r.details.meeting.title}

{status}

+ {r.details.attempts?.at(-1)?.end_reason&&r.details.attempts.at(-1).end_reason!=='operator-stop'&&

Recording ended because of {r.details.attempts.at(-1).end_reason}. Check the end of the recording before using it as a complete meeting record.

} {r.status==='running'&&r.live_progress?.bytes_written>0&&

{(r.live_progress.bytes_written/1048576).toFixed(2)} MiB captured

} {catalog.can_capture&&r.details.live_source&&['queued','running'].includes(r.status)&&} {['failed','interrupted'].includes(r.status)&&

Recording did not complete. Partial evidence is retained. Start a new live recording; missing live time cannot be recovered.

} diff --git a/beta-1/pyproject.toml b/beta-1/pyproject.toml index ff7c3e26..d95adc3b 100644 --- a/beta-1/pyproject.toml +++ b/beta-1/pyproject.toml @@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta" [project] name = "townlight-station" -version = "0.3.1" +version = "0.4.0" description = "Independent Townlight Station service using the pinned CivicCast media implementation" requires-python = ">=3.12" license = "AGPL-3.0-only" license-files = ["LICENSE", "THIRD-PARTY-NOTICES.md", "UI-THIRD-PARTY-LICENSES.txt"] -dependencies = ["fastapi>=0.115,<1", "uvicorn>=0.30,<1", "httpx>=0.27,<1", "sqlalchemy>=2,<3", "psycopg2-binary>=2.9,<3", "pydantic>=2,<3", "pywin32>=311; sys_platform == 'win32'"] +dependencies = ["fastapi>=0.115,<1", "uvicorn>=0.30,<1", "httpx>=0.27,<1", "sqlalchemy>=2,<3", "psycopg2-binary>=2.9,<3", "pydantic>=2,<3", "pywin32==311; sys_platform == 'win32'"] [project.scripts] townlight-station = "townlight_station.cli:main" diff --git a/beta-1/tests/test_input_setup.py b/beta-1/tests/test_input_setup.py new file mode 100644 index 00000000..8c761bbf --- /dev/null +++ b/beta-1/tests/test_input_setup.py @@ -0,0 +1,108 @@ +import hashlib +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from townlight_station.device_probe import resolve_device +from townlight_station.devices import save_selection +from townlight_station.live import sources +from townlight_station.backup import verify_backup +from townlight_station.setup_windows import load_configuration + + +def test_saved_inputs_use_resolved_ids_and_retain_udp(tmp_path, monkeypatch): + camera, microphone = 'a'*64, 'b'*64 + found = [{'id': camera, 'label': 'Camera', 'kind': 'video'}, + {'id': microphone, 'label': 'Microphone', 'kind': 'audio'}] + monkeypatch.setattr('townlight_station.devices.discover', lambda _: found) + cfg = SimpleNamespace(data=tmp_path) + udp = {'id': 'chamber', 'label': 'Chamber feed', 'kind': 'udp-mpegts', 'address': '127.0.0.1', 'port': 12000} + (tmp_path/'live-sources.json').write_text(json.dumps([udp])) + save_selection(cfg, camera, microphone) + configured = sources(cfg) + assert configured['chamber'] == udp + assert configured['local-chamber']['video_id'] == camera + with pytest.raises(ValueError, match='missing'): + save_selection(cfg, 'c'*64, microphone) + assert sources(cfg)['local-chamber']['video_id'] == camera + + +def test_missing_or_ambiguous_device_never_falls_back(): + with pytest.raises(ValueError): + resolve_device([], 'a'*64, 'audio') + device = {'id':'a'*64, 'kind':'audio'} + with pytest.raises(ValueError): + resolve_device([device, device], 'a'*64, 'audio') + + +def test_config_rejects_unrelated_environment_and_wrong_storage(tmp_path): + path = tmp_path/'settings.json' + path.write_text(json.dumps({'DATA_ROOT': str(tmp_path), 'DATABASE_URL': 'test', 'CIVICCAST_DATABASE_URL': 'private'})) + with pytest.raises(ValueError, match='Invalid'): + load_configuration(path) + path.write_text(json.dumps({'DATA_ROOT': str(tmp_path/'other')})) + with pytest.raises(ValueError, match='protected data'): + load_configuration(path) + + +def test_windows_configuration_is_account_protected_and_legacy_plaintext_is_replaced(tmp_path): + import secrets + from townlight_station.setup_windows import save_configuration + path = tmp_path/'settings.json' + password = secrets.token_hex(32) + values = {'DATA_ROOT':str(tmp_path), 'DATABASE_ADMIN_PASSWORD':password} + save_configuration(path, values) + assert password.encode() not in path.read_bytes() + assert load_configuration(path) == values + # Earlier private candidate configurations are migrated on their next read. + path.write_text(json.dumps(values), encoding='utf-8') + assert load_configuration(path) == values + assert password.encode() not in path.read_bytes() + + +def test_backup_rejects_changed_unlisted_and_traversal_files(tmp_path): + dump = tmp_path/'station.dump' + dump.write_bytes(b'fixture-dump') + manifest = {'product':'townlight-station-backup', 'version':1, + 'files':{'station.dump':{'size_bytes':dump.stat().st_size, + 'sha256':hashlib.sha256(dump.read_bytes()).hexdigest()}}} + (tmp_path/'manifest.json').write_text(json.dumps(manifest)) + verify_backup(tmp_path) + dump.write_bytes(b'changed') + with pytest.raises(ValueError, match='changed'): + verify_backup(tmp_path) + manifest['files']['../outside'] = {'size_bytes':0, 'sha256':'0'*64} + # Restore original dump first so this check exercises traversal, not its digest. + dump.write_bytes(b'fixture-dump') + (tmp_path/'manifest.json').write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match='Unsafe'): + verify_backup(tmp_path) + + +def test_logon_task_accepts_windows_sid_serialization_and_rejects_other_executable(tmp_path, monkeypatch): + import subprocess + import win32api + import win32security + from xml.sax.saxutils import escape + from townlight_station.setup_windows import register_task + python = tmp_path/'pythonw.exe' + config = tmp_path/'settings.json' + username = win32api.GetUserNameEx(2) + sid = win32security.ConvertSidToStringSid(win32security.LookupAccountName(None, username)[0]) + args = subprocess.list2cmdline(['-B', '-m', 'townlight_station.cli', 'background', '--config', str(config)]) + calls = [] + executable = str(python) + def run(command, **kwargs): + calls.append(command) + xml = f'{sid}{escape(executable)}{escape(args)}' + return SimpleNamespace(returncode=0, stdout=xml) + monkeypatch.setattr('townlight_station.setup_windows.subprocess.run', run) + register_task(python, config) + assert len(calls) == 3 + calls.clear() + executable = str(tmp_path/'unrelated.exe') + with pytest.raises(ValueError, match='unrelated scheduled task'): + register_task(python, config) + assert len(calls) == 1 diff --git a/beta-1/tests/test_long_meeting.py b/beta-1/tests/test_long_meeting.py new file mode 100644 index 00000000..a54e20ee --- /dev/null +++ b/beta-1/tests/test_long_meeting.py @@ -0,0 +1,58 @@ +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient + +from townlight_station.boundary import Settings +from townlight_station.operator import install_operator + + +def test_default_policy_can_hold_eight_hours(): + fields = Settings.__dataclass_fields__ + assert fields['max_seconds'].default == 8 * 60 * 60 + assert fields['max_bytes'].default >= 32 * 1024**3 + + +def test_operator_renewal_checks_authority_and_extends_session(monkeypatch): + import townlight_station.operator as operator + clock = [0.0] + monkeypatch.setattr(operator.time, 'monotonic', lambda: clock[0]) + valid = [True] + + class Suite: + def get(self, path, proof): + if not valid[0] or proof != 'a' * 64: + raise HTTPException(401, 'Signed out') + return {'actor_id': 'clerk'} + + app = FastAPI() + install_operator(app, SimpleNamespace(), Suite()) + with TestClient(app) as client: + headers = {'Origin': 'http://testserver', 'X-Station-UI': '1'} + ticket = client.post('/v1/operator-ticket', headers={'X-Townlight-Session': 'a'*64}).json()['ticket'] + assert client.post('/operator/session', json={'ticket': ticket}, headers=headers).status_code == 200 + clock[0] = 800 + assert client.post('/operator/renew', json={}, headers=headers).status_code == 200 + clock[0] = 1000 + assert client.post('/operator/renew', json={}, headers=headers).status_code == 200 + valid[0] = False + assert client.post('/operator/renew', json={}, headers=headers).status_code == 401 + valid[0] = True + # Revoked browser authority cannot resurrect just because Suite is available. + assert client.post('/operator/renew', json={}, headers=headers).status_code == 401 + + +def test_recording_disk_budget_is_bounded_and_actionable(tmp_path, monkeypatch): + from townlight_station.storage_policy import require_capacity, storage_status + monkeypatch.setattr('townlight_station.storage_policy.shutil.disk_usage', + lambda _: SimpleNamespace(free=100 * 1024**3)) + settings = SimpleNamespace(data=tmp_path, bitrate_kbps=6000, max_seconds=28800, + max_bytes=64*1024**3, reserve_bytes=1024**3) + assert storage_status(settings)['estimated_recording_bytes'] > 20*1024**3 + require_capacity(settings) + monkeypatch.setattr('townlight_station.storage_policy.shutil.disk_usage', + lambda _: SimpleNamespace(free=1024**3)) + with pytest.raises(ValueError, match='space'): + require_capacity(settings) diff --git a/beta-1/townlight_station/__init__.py b/beta-1/townlight_station/__init__.py index 4e08e78d..7cf4d693 100644 --- a/beta-1/townlight_station/__init__.py +++ b/beta-1/townlight_station/__init__.py @@ -1,3 +1,3 @@ # SPDX-License-Identifier: AGPL-3.0-only """Townlight Station. Does not bootstrap a CivicCast installation.""" -VERSION = "0.3.0" +VERSION = "0.4.0" diff --git a/beta-1/townlight_station/api.py b/beta-1/townlight_station/api.py index bf45682a..695737ef 100644 --- a/beta-1/townlight_station/api.py +++ b/beta-1/townlight_station/api.py @@ -80,7 +80,16 @@ async def lifespan(app): @app.get('/health') def health(): store.ready() - return {'product': IDENTITY['product'], 'ready': True} + if (settings.data/'settings.json').exists(): + import time + try: + pulse = json.loads((settings.data/'background-health.json').read_text(encoding='utf-8')) + if not 0 <= time.time()-pulse['updated_at'] <= 10: + raise ValueError('stale') + except (OSError, ValueError, KeyError): + raise HTTPException(503, 'Recorder background supervisor is not ready') from None + from .setup_windows import task_name + return {'product': IDENTITY['product'], 'ready': True, 'instance': task_name(settings.data)} @app.get('/v1/identity') def identity(proof: str | None = Header(default=None, alias='X-Townlight-Session')): @@ -109,6 +118,11 @@ def capture(data: Capture, proof: str | None = Header(default=None, alias='X-Tow original = private_path(settings.data, 'ingest', data.source_file) if data.source_file else None if original and (not original.is_file() or original.stat().st_size > settings.max_bytes): raise HTTPException(422, 'Source file missing or exceeds configured limit') + from .storage_policy import require_capacity + try: + require_capacity(settings, source_bytes=original.stat().st_size if original else 0) + except ValueError as exc: + raise HTTPException(507, str(exc)) from None input_hash = sha256(original) if original else None imported_source = read_provenance(private_path(settings.data, 'ingest'), data.source_file, data.meeting_id, input_hash) captions = private_path(settings.data, 'ingest', data.captions_file) if data.captions_file else None @@ -121,6 +135,8 @@ def capture(data: Capture, proof: str | None = Header(default=None, alias='X-Tow with store.engine.begin() as conn: # Serialize idempotency checks including bytes and captured meeting version. conn.execute(sa.text('SELECT pg_advisory_xact_lock(1953721717)')) + if (settings.data/'background.stop').exists(): + raise HTTPException(503, 'Recorder is stopping; retry setup before starting another recording') prior = conn.execute(sa.select(recordings).where(recordings.c.creator == principal['actor_id'], recordings.c.idempotency_key == data.idempotency_key)).mappings().first() if prior: diff --git a/beta-1/townlight_station/backup.py b/beta-1/townlight_station/backup.py new file mode 100644 index 00000000..801e86aa --- /dev/null +++ b/beta-1/townlight_station/backup.py @@ -0,0 +1,132 @@ +# SPDX-License-Identifier: AGPL-3.0-only +"""Coherent recorder backup/restore, excluding credentials and native runtimes.""" +import json +from pathlib import Path +import shutil +import subprocess +import tempfile +from contextlib import contextmanager +from datetime import datetime, timezone + +import sqlalchemy as sa +from sqlalchemy.engine import make_url +from .boundary import private_path, sha256 +from .store import Store, recordings + + +def _tool(settings, name, args): + import os + db = make_url(settings.database_url) + env = dict(os.environ, PGPASSWORD=db.password) + root = Path(os.environ['TOWNLIGHT_STATION_POSTGRES_BIN']) + subprocess.run([str(root/(name+'.exe')), '-h', db.host, '-p', str(db.port), '-U', db.username, + '-d', db.database, *args], env=env, capture_output=True, check=True, + timeout=1800, creationflags=subprocess.CREATE_NO_WINDOW) + + +@contextmanager +def maintenance(store): + # A session lock spans external pg_dump/pg_restore without retaining table locks. + with store.engine.connect().execution_options(isolation_level='AUTOCOMMIT') as connection: + connection.execute(sa.text('SELECT pg_advisory_lock(1953721717)')) + try: + if connection.scalar(sa.select(sa.func.count()).select_from(recordings) + .where(recordings.c.status.in_(('queued', 'running')))): + raise ValueError('Finish active and queued recordings before backup or restore') + yield connection + finally: + connection.execute(sa.text('SELECT pg_advisory_unlock(1953721717)')) + + +def backup(settings, destination): + destination = Path(destination).absolute() + private_path(destination) + if destination.resolve().is_relative_to(settings.data.resolve()): + raise ValueError('Backup must be outside the recorder data directory') + destination.mkdir(parents=True, exist_ok=False) + store = Store(settings.database_url) + try: + with maintenance(store): + _tool(settings, 'pg_dump', ['--format=custom', '--schema=station', '-f', str(destination/'station.dump')]) + for folder in ('recordings', 'ingest'): + source = private_path(settings.data, folder) + for file in source.rglob('*'): + private_path(source, *file.relative_to(source).parts) + shutil.copytree(source, destination/folder) + for name in ('live-sources.json', 'local-input.json', 'civiccast-feeds.json'): + source = private_path(settings.data, name) + if source.is_file(): + shutil.copy2(source, destination/name) + files = {p.relative_to(destination).as_posix(): {'sha256': sha256(p), 'size_bytes': p.stat().st_size} + for p in destination.rglob('*') if p.is_file()} + manifest = {'product': 'townlight-station-backup', 'version': 1, + 'created_at': datetime.now(timezone.utc).isoformat(), 'files': files} + (destination/'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8') + return {'backup_directory': str(destination), 'files': len(files), + 'message': 'Station database and recording files backed up with SHA-256 manifest. Credentials stay with this installation.'} + finally: + store.engine.dispose() + + +def verify_backup(source): + source = Path(source).absolute() + private_path(source) + manifest = json.loads((source/'manifest.json').read_text(encoding='utf-8')) + if manifest.get('product') != 'townlight-station-backup' or manifest.get('version') != 1: + raise ValueError('Not a supported Station backup') + files = manifest.get('files') + if not isinstance(files, dict) or not 1 <= len(files) <= 100000 or 'station.dump' not in files: + raise ValueError('Invalid Station backup manifest') + allowed = {'station.dump', 'live-sources.json', 'local-input.json', 'civiccast-feeds.json'} + for name, expected in files.items(): + relative = Path(name) + if (not name or ':' in name or '\\' in name or relative.is_absolute() or '..' in relative.parts + or (name not in allowed and relative.parts[0] not in ('recordings', 'ingest'))): + raise ValueError('Unsafe backup member') + path = private_path(source, *relative.parts) + if not path.is_file() or path.stat().st_size != expected['size_bytes'] or sha256(path) != expected['sha256']: + raise ValueError('Station backup file is missing or changed: '+name) + actual = {p.relative_to(source).as_posix() for p in source.rglob('*') if p.is_file()} + if actual != set(files) | {'manifest.json'}: + raise ValueError('Station backup has unlisted files') + return manifest + + +def restore(settings, source): + source = Path(source).absolute() + manifest = verify_backup(source) + # Recovery copy is made before any replacement, without overwriting older evidence. + recovery = settings.data.parent/('station-pre-restore-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%f')) + backup(settings, recovery) + store = Store(settings.database_url) + try: + with maintenance(store): + required = sum(v['size_bytes'] for v in manifest['files'].values()) + if shutil.disk_usage(settings.data).free < required + settings.reserve_bytes: + raise ValueError('Insufficient restore staging space; existing records were not replaced') + with tempfile.TemporaryDirectory(prefix='restore-', dir=settings.data/'temp') as staging: + staging = Path(staging) + for name in manifest['files']: + if name == 'station.dump': + continue + dst = staging/name + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source/name, dst) + # Native tool applies the dump in one transaction; no credentials restored. + _tool(settings, 'pg_restore', ['--clean', '--if-exists', '--no-owner', '--no-privileges', + '--single-transaction', '--schema=station', str(source/'station.dump')]) + for name in ('recordings', 'ingest', 'live-sources.json', 'local-input.json', 'civiccast-feeds.json'): + target = private_path(settings.data, name) + incoming = staging/name + if target.is_dir(): + shutil.rmtree(target) + elif target.exists(): + target.unlink() + if incoming.exists(): + incoming.replace(target) + elif name in ('recordings', 'ingest'): + target.mkdir() + return {'restored': True, 'recovery_directory': str(recovery), + 'message': 'Station backup restored. Recheck chamber inputs before the next meeting.'} + finally: + store.engine.dispose() diff --git a/beta-1/townlight_station/boundary.py b/beta-1/townlight_station/boundary.py index 960c247c..c65b6683 100644 --- a/beta-1/townlight_station/boundary.py +++ b/beta-1/townlight_station/boundary.py @@ -50,12 +50,13 @@ class Settings: media_python: Path media_runtime: Path ffprobe: Path - max_seconds: int = 7200 - max_bytes: int = 2_147_483_647 + max_seconds: int = 28800 + max_bytes: int = 64 * 1024**3 width: int = 1920 height: int = 1080 fps: int = 30 bitrate_kbps: int = 6000 + reserve_bytes: int = 1024**3 @classmethod def from_env(cls): @@ -63,9 +64,11 @@ def from_env(cls): get = lambda name: os.environ[prefix + name] result = cls(Path(get('DATA_ROOT')), get('DATABASE_URL'), service_url(get('SUITE_URL')), Path(get('MEDIA_SOURCE')), Path(get('MEDIA_PYTHON')), Path(get('MEDIA_RUNTIME')), - Path(get('FFPROBE')), int(os.environ.get(prefix+'MAX_SECONDS', '7200')), + Path(get('FFPROBE')), int(os.environ.get(prefix+'MAX_SECONDS', '28800')), + max_bytes=int(os.environ.get(prefix+'MAX_BYTES', str(64 * 1024**3))), width=int(os.environ.get(prefix+'WIDTH', '1920')), height=int(os.environ.get(prefix+'HEIGHT', '1080')), - fps=int(os.environ.get(prefix+'FPS', '30')), bitrate_kbps=int(os.environ.get(prefix+'BITRATE_KBPS', '6000'))) + fps=int(os.environ.get(prefix+'FPS', '30')), bitrate_kbps=int(os.environ.get(prefix+'BITRATE_KBPS', '6000')), + reserve_bytes=int(os.environ.get(prefix+'RESERVE_BYTES', str(1024**3)))) result.validate() return result @@ -80,6 +83,8 @@ def validate(self): raise ValueError('Station requires its own PostgreSQL database ending in _station') if not 10 <= self.max_seconds <= 86400: raise ValueError('Invalid media timeout') + if not 1024**2 <= self.max_bytes <= 64 * 1024**3 or self.reserve_bytes < 256*1024**2: + raise ValueError('Invalid recording storage policy') if (not 320 <= self.width <= 3840 or not 180 <= self.height <= 2160 or self.width % 2 or self.height % 2 or not 1 <= self.fps <= 60 or not 128 <= self.bitrate_kbps <= 50000): raise ValueError('Invalid encoding profile') diff --git a/beta-1/townlight_station/cli.py b/beta-1/townlight_station/cli.py index ecf9cc85..8991c9a3 100644 --- a/beta-1/townlight_station/cli.py +++ b/beta-1/townlight_station/cli.py @@ -6,13 +6,60 @@ def main(): parser = argparse.ArgumentParser(prog='townlight-station') - parser.add_argument('command', choices=['migrate', 'serve', 'worker', 'air', 'operator', 'uploads']) + parser.add_argument('command', choices=['migrate', 'serve', 'worker', 'air', 'operator', 'uploads', 'setup', 'background', 'backup', 'restore', 'stop']) parser.add_argument('--port', type=int, default=8756) parser.add_argument('--once', action='store_true') parser.add_argument('--profile-root', type=str) + parser.add_argument('--config', type=str) + parser.add_argument('--payload-root', type=str) + parser.add_argument('--data-root', type=str) + parser.add_argument('--destination', type=str) + parser.add_argument('--suite-url', type=str, default='http://127.0.0.1:15480') args = parser.parse_args() + if args.command == 'setup': + import json + from .setup_windows import provision + if not args.payload_root or not args.data_root: + parser.error('setup requires explicit payload and data directories') + print(json.dumps(provision(args.payload_root, args.data_root, args.suite_url))) + return + if args.command == 'background': + from .setup_windows import background + if not args.config: + parser.error('background requires the protected configuration path') + # pythonw has no console: keep failures in the protected recorder directory. + from pathlib import Path + from contextlib import redirect_stdout, redirect_stderr + from .boundary import private_path + from .setup_windows import load_configuration + import traceback + load_configuration(args.config) + log_path = private_path(Path(args.config).parent, 'background.log') + with log_path.open('a', encoding='utf-8') as log, redirect_stdout(log), redirect_stderr(log): + try: + background(args.config) + except Exception: + traceback.print_exc(file=log) + raise + return + if args.config: + from .setup_windows import load_configuration + load_configuration(args.config) + if args.command == 'stop': + import json + from .setup_windows import stop_task + if not args.config: + parser.error('stop requires the recorder configuration') + print(json.dumps(stop_task(args.config))) + return cfg = Settings.from_env() if args.command != 'operator' else None - if args.command == 'migrate': + if args.command in ('backup', 'restore'): + import json + from .backup import backup, restore + if not args.destination: + parser.error('backup/restore requires the selected absolute directory') + print(json.dumps((backup if args.command == 'backup' else restore)(cfg, args.destination))) + elif args.command == 'migrate': cfg.initialize_storage() store = Store(cfg.database_url) try: @@ -45,7 +92,12 @@ def main(): with httpx.Client(trust_env=False, timeout=15) as client: result = client.post(origin+'/v1/operator-ticket', headers={'X-Townlight-Session': proof}) result.raise_for_status() - webbrowser.open(origin+'/#ticket='+result.json()['ticket']) + url = origin+'/#ticket='+result.json()['ticket'] + import os + if os.environ.get('TOWNLIGHT_SUPPRESS_OPEN_BROWSER') == '1': + print(json.dumps({'operator_url': url})) + else: + webbrowser.open(url) else: from .worker import run run(once=args.once) diff --git a/beta-1/townlight_station/device_probe.py b/beta-1/townlight_station/device_probe.py new file mode 100644 index 00000000..bc8f077f --- /dev/null +++ b/beta-1/townlight_station/device_probe.py @@ -0,0 +1,65 @@ +# SPDX-License-Identifier: AGPL-3.0-only +"""Native media-Python process only. Enumerate sources without opening capture.""" +import hashlib +import json +import sys + + +def enumerate_devices(): + from gi.repository import Gst + monitor = Gst.DeviceMonitor.new() + monitor.add_filter('Video/Source', None) + monitor.add_filter('Audio/Source', None) + if not monitor.start(): + raise RuntimeError('Windows capture discovery unavailable; check the installed media runtime') + result = [] + try: + for device in monitor.get_devices(): + element = device.create_element(None) + if element is None: + continue + factory = element.get_factory().get_name() + allowed = {'mfvideosrc', 'ksvideosrc', 'dshowvideosrc', 'wasapi2src', 'wasapisrc'} + if factory not in allowed: + continue + props = {} + for key in ('device-path', 'device', 'device-name', 'device-index'): + if element.find_property(key): + value = element.get_property(key) + if isinstance(value, (str, int)) and not isinstance(value, bool): + props[key] = value + if props.get('device-path'): + props.pop('device-index', None) # Keep the explicit endpoint, not a volatile index. + if factory in {'wasapi2src', 'wasapisrc'}: + endpoint = str(props.get('device', '')) + # WASAPI also advertises render/loopback and dynamic default endpoints. + # Only an explicit capture endpoint identifies the chosen microphone. + if not endpoint.startswith('{0.0.1.'): + continue + properties = device.get_properties() + identity = properties.to_string() if properties else device.get_display_name() + fingerprint = hashlib.sha256((factory+'\n'+identity).encode()).hexdigest() + result.append({'id': fingerprint, 'label': device.get_display_name(), + 'kind': 'video' if 'Video' in device.get_device_class() else 'audio', + 'factory': factory, 'properties': props}) + finally: + monitor.stop() + return result + + +def resolve_device(devices, identity, kind): + matches = [d for d in devices if d['id'] == identity and d['kind'] == kind] + if len(matches) != 1: + raise ValueError(f'Selected {kind} device is missing or ambiguous; reopen input setup') + return matches[0] + + +if __name__ == '__main__': + sys.path.insert(0, sys.argv[1]) + from civiccast.native.gstreamer_runtime import bootstrap_installed_gstreamer_runtime + bootstrap_installed_gstreamer_runtime() + import gi + gi.require_version('Gst', '1.0') + from gi.repository import Gst + Gst.init(None) + print(json.dumps(enumerate_devices()), flush=True) diff --git a/beta-1/townlight_station/devices.py b/beta-1/townlight_station/devices.py new file mode 100644 index 00000000..25ffd687 --- /dev/null +++ b/beta-1/townlight_station/devices.py @@ -0,0 +1,30 @@ +# SPDX-License-Identifier: AGPL-3.0-only +import json +from pathlib import Path +import subprocess +import uuid + +from .boundary import private_path + + +def discover(settings): + settings.verify_media() + result = subprocess.run([str(settings.media_python), '-B', + str(Path(__file__).with_name('device_probe.py')), str(settings.media_source)], + env=settings.worker_environment(), capture_output=True, text=True, + timeout=20, check=True, creationflags=subprocess.CREATE_NO_WINDOW) + return json.loads(result.stdout.strip().splitlines()[-1]) + + +def save_selection(settings, video_id, audio_id): + from .device_probe import resolve_device + devices = discover(settings) + video = resolve_device(devices, video_id, 'video') + audio = resolve_device(devices, audio_id, 'audio') + value = {'id': 'local-chamber', 'label': video['label']+' / '+audio['label'], + 'kind': 'windows-devices', 'video_id': video_id, 'audio_id': audio_id} + path = private_path(settings.data, 'local-input.json') + temporary = path.with_name(path.name+'.'+uuid.uuid4().hex+'.tmp') + temporary.write_text(json.dumps(value), encoding='utf-8') + temporary.replace(path) + return value diff --git a/beta-1/townlight_station/input_test.py b/beta-1/townlight_station/input_test.py new file mode 100644 index 00000000..2841066a --- /dev/null +++ b/beta-1/townlight_station/input_test.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: AGPL-3.0-only +"""Bounded input check in the capture account; never a canonical meeting record.""" +import json +from pathlib import Path +import subprocess +import time + +from .boundary import private_path +from .live import sources + + +def record_test(settings): + source = sources(settings).get('local-chamber') + if not source: + raise ValueError('Save a camera and microphone before testing') + folder = private_path(settings.data, 'temp', 'input-test') + folder.mkdir(parents=True, exist_ok=True) + output = folder / 'preview.ts' + marker = output.with_suffix('.stop') + marker.unlink(missing_ok=True) + preview = folder / 'preview.mp4' + preview.unlink(missing_ok=True) + with (folder / 'capture.log').open('w', encoding='utf-8') as log: + child = subprocess.Popen([str(settings.media_python), '-B', + str(Path(__file__).with_name('media_job.py')), str(settings.media_source), + str(folder), str(output), json.dumps(settings.encoding_profile()), json.dumps(source)], + env=settings.worker_environment(), stdout=log, stderr=subprocess.STDOUT, + creationflags=subprocess.CREATE_NO_WINDOW) + try: + time.sleep(10) + marker.write_text('input-test-stop', encoding='ascii') + if child.wait(timeout=20) != 0: + raise ValueError('Camera test failed; check Windows privacy permissions, device use and input selection') + finally: + if child.poll() is None: + child.kill() + child.wait(timeout=10) + subprocess.run([str(settings.ffprobe.with_name('ffmpeg.exe')), '-nostdin', '-y', + '-i', str(output), '-map', '0:v:0', '-map', '0:a:0', '-c', 'copy', '-movflags', '+faststart', str(preview)], + capture_output=True, timeout=30, check=True, creationflags=subprocess.CREATE_NO_WINDOW) + return {'ready': True, 'preview_url': '/operator/input-test/content', + 'message': 'Play the test clip and confirm picture and sound before recording the meeting.'} diff --git a/beta-1/townlight_station/live.py b/beta-1/townlight_station/live.py index c01dce6a..7b43ff0b 100644 --- a/beta-1/townlight_station/live.py +++ b/beta-1/townlight_station/live.py @@ -23,4 +23,13 @@ def sources(settings): if type(row['port']) is not int or not 1024 <= row['port'] <= 65535: raise ValueError('Invalid live receive port') result[row['id']] = row + local = private_path(settings.data, 'local-input.json') + if local.exists(): + row = json.loads(local.read_text(encoding='utf-8')) + if (set(row) != {'id', 'label', 'kind', 'video_id', 'audio_id'} + or row['id'] != 'local-chamber' or row['kind'] != 'windows-devices' + or any(not isinstance(row.get(k), str) or not re.fullmatch(r'[a-f0-9]{64}', row[k]) + for k in ('video_id', 'audio_id'))): + raise ValueError('Invalid saved camera/microphone selection; reopen input setup') + result[row['id']] = row return result diff --git a/beta-1/townlight_station/media_job.py b/beta-1/townlight_station/media_job.py index b8773567..6b1c8b97 100644 --- a/beta-1/townlight_station/media_job.py +++ b/beta-1/townlight_station/media_job.py @@ -21,13 +21,31 @@ # cccombiner passes through unchanged when it has no requested caption pad. caption_policy = (E('ccextractor', props={'remove-caption-meta': True}),) if has_sidecar else () program = g.PlaylistLeg(label='program', subchains=(( - *((E('udpsrc', props={'address': live['address'], 'port': live['port'], 'caps': 'video/mpegts,systemstream=true,packetsize=188', 'do-timestamp': True}), E('decodebin')) if live else + *((E('udpsrc', props={'address': live['address'], 'port': live['port'], 'caps': 'video/mpegts,systemstream=true,packetsize=188', 'do-timestamp': True}), E('decodebin')) if live and live.get('kind') != 'windows-devices' else (E('filesrc', props={'location': str(folder / 'source.media')}), E('decodebin'))), *caption_policy, E('videoconvert'), E('videoscale'), E('videorate'), E('capsfilter', props={'caps': f"video/x-raw,format=I420,width={profile['width']},height={profile['height']},framerate={profile['fps']}/1"}), ),), audio_tail=(E('audioconvert'), E('audioresample'), E('capsfilter', props={'caps': 'audio/x-raw,format=S16LE,rate=48000,channels=2,layout=interleaved'}))) +if live and live.get('kind') == 'windows-devices': + # Re-resolve saved IDs in the actual capture account. Never trust client factories/properties. + from civiccast.native.gstreamer_runtime import bootstrap_installed_gstreamer_runtime + bootstrap_installed_gstreamer_runtime() + import gi + gi.require_version('Gst', '1.0') + from gi.repository import Gst + Gst.init(None) + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from device_probe import enumerate_devices, resolve_device + devices = enumerate_devices() + camera = resolve_device(devices, live['video_id'], 'video') + microphone = resolve_device(devices, live['audio_id'], 'audio') + program = g.SourceLeg(label='program', elements=( + E(camera['factory'], props=camera['properties']), E('videoconvert'), E('videoscale'), E('videorate'), + E('capsfilter', props={'caps': f"video/x-raw,format=I420,width={profile['width']},height={profile['height']},framerate={profile['fps']}/1"})), + audio=(E(microphone['factory'], props=microphone['properties']), E('audioconvert'), E('audioresample'), + E('capsfilter', props={'caps': 'audio/x-raw,format=S16LE,rate=48000,channels=2,layout=interleaved'}))) encoder = g.encode_chain_specs(**profile, gop=profile['fps']) if not has_sidecar: # Preserve decoder caption metadata by serializing it into the new H.264 diff --git a/beta-1/townlight_station/operator.py b/beta-1/townlight_station/operator.py index 178104cc..2153ebcf 100644 --- a/beta-1/townlight_station/operator.py +++ b/beta-1/townlight_station/operator.py @@ -2,6 +2,7 @@ """Short-lived operator sessions launched explicitly by authenticated Townlight staff.""" from pathlib import Path import secrets +import subprocess import time from uuid import UUID import httpx @@ -29,7 +30,9 @@ class ImportedRecording(BaseModel): def install_operator(app, settings, suite): + import threading tickets, sessions = {}, {} + input_lock = threading.Lock() static = Path(__file__).with_name('ui') @app.middleware('http') @@ -84,6 +87,90 @@ def logout(request: Request): response.delete_cookie('station_operator', path='/') return response + @app.post('/operator/renew') + def renew(request: Request): + token = request.cookies.get('station_operator') + entry = sessions.get(token) + if not entry: + raise HTTPException(401, 'Reconnect through your signed-in Townlight session; recording continues') + try: + suite.get('/desktop/v1/station/context?capability=read', entry[0]) + except HTTPException as exc: + if exc.status_code in (401, 403): + sessions.pop(token, None) + raise + renewed = secrets.token_urlsafe(32) + sessions.pop(token, None) + sessions[renewed] = (entry[0], time.monotonic()+900) + response = JSONResponse({'connected': True, 'expires_in': 900}) + response.set_cookie('station_operator', renewed, httponly=True, + secure=request.url.scheme == 'https', samesite='strict', + max_age=900, path='/') + return response + + @app.get('/operator/devices') + def device_list(proof: str | None = Header(default=None, alias='X-Townlight-Session')): + suite.get('/desktop/v1/station/context?capability=capture', proof) + from .devices import discover + try: + return [{'id': d['id'], 'label': d['label'], 'kind': d['kind']} for d in discover(settings)] + except (OSError, ValueError, subprocess.SubprocessError): + raise HTTPException(503, 'Input discovery failed. Check the installed media runtime and Windows camera/microphone permissions.') from None + + class DeviceSelection(BaseModel): + model_config = ConfigDict(extra='forbid') + video_id: str = Field(pattern='^[a-f0-9]{64}$') + audio_id: str = Field(pattern='^[a-f0-9]{64}$') + + @app.post('/operator/devices') + def select_devices(data: DeviceSelection, proof: str | None = Header(default=None, alias='X-Townlight-Session')): + suite.get('/desktop/v1/station/context?capability=capture', proof) + from .devices import save_selection + try: + return save_selection(settings, data.video_id, data.audio_id) + except (OSError, ValueError, subprocess.SubprocessError): + raise HTTPException(422, 'Selected inputs are unavailable; refresh the device list and check Windows permissions.') from None + + @app.post('/operator/input-test') + def test_inputs(proof: str | None = Header(default=None, alias='X-Townlight-Session')): + suite.get('/desktop/v1/station/context?capability=capture', proof) + from .store import Store, recordings + import sqlalchemy as sa + from .input_test import record_test + store = Store(settings.database_url) + try: + with store.engine.begin() as conn: + # Same lock as capture admission: testing must not seize a meeting's device. + conn.execute(sa.text('SELECT pg_advisory_xact_lock(1953721717)')) + if conn.scalar(sa.select(sa.func.count()).select_from(recordings) + .where(recordings.c.status.in_(('queued', 'running')))): + raise HTTPException(409, 'Finish the active recording before testing inputs') + if not input_lock.acquire(blocking=False): + raise HTTPException(409, 'An input test is already running') + try: + return record_test(settings) + except (OSError, ValueError, subprocess.SubprocessError): + raise HTTPException(422, 'Input test failed. Check device access and the Station input-test log, then retry.') from None + finally: + input_lock.release() + finally: + store.engine.dispose() + + @app.get('/operator/input-test/content') + def input_preview(proof: str | None = Header(default=None, alias='X-Townlight-Session')): + suite.get('/desktop/v1/station/context?capability=capture', proof) + from .boundary import private_path + path = private_path(settings.data, 'temp', 'input-test', 'preview.mp4') + if not path.is_file(): + raise HTTPException(404, 'Run an input test first') + return FileResponse(path, media_type='video/mp4') + + @app.get('/operator/storage') + def capacity(proof: str | None = Header(default=None, alias='X-Townlight-Session')): + suite.get('/desktop/v1/station/context?capability=read', proof) + from .storage_policy import storage_status + return storage_status(settings) + @app.get('/operator/catalog') def catalog(proof: str | None = Header(default=None, alias='X-Townlight-Session')): suite.get('/desktop/v1/station/context?capability=read', proof) @@ -129,7 +216,9 @@ def stage_imported_recording( def handoff(data: Handoff, proof: str | None = Header(default=None, alias='X-Townlight-Session')): suite.get('/desktop/v1/station/context?capability=read', proof) try: - with httpx.Client(base_url=settings.suite_url, timeout=150, trust_env=False, follow_redirects=False) as client: + # Records streams and verifies a separate copy; a multi-hour meeting + # can legitimately take longer than the ordinary interactive timeout. + with httpx.Client(base_url=settings.suite_url, timeout=httpx.Timeout(30, read=1800), trust_env=False, follow_redirects=False) as client: result = client.post(f'/desktop/v1/requests/{data.request_id}/station-recordings', headers={'X-Townlight-Session': proof}, json={'recording_id': str(data.recording_id), 'expected_sha256': data.expected_sha256}) if result.status_code != 200: diff --git a/beta-1/townlight_station/setup_windows.py b/beta-1/townlight_station/setup_windows.py new file mode 100644 index 00000000..63df7df7 --- /dev/null +++ b/beta-1/townlight_station/setup_windows.py @@ -0,0 +1,427 @@ +# SPDX-License-Identifier: AGPL-3.0-only +"""Per-user Windows recorder provisioning and owned background process lifecycle. + +The logon task runs in the user's device-access session, outside the desktop's +job object. It owns a separate PostgreSQL cluster and never borrows CivicCast data. +""" +import json +import os +from pathlib import Path +import secrets +import subprocess +import sys +import time +import xml.etree.ElementTree as ET +import base64 + +from .boundary import Settings, private_path + +CONFIG_KEYS = {'DATA_ROOT', 'DATABASE_URL', 'SUITE_URL', 'MEDIA_SOURCE', 'MEDIA_PYTHON', + 'MEDIA_RUNTIME', 'FFPROBE', 'CONTROL_PYTHON', 'POSTGRES_BIN', + 'MAX_SECONDS', 'MAX_BYTES', 'RESERVE_BYTES', 'WIDTH', 'HEIGHT', 'FPS', 'BITRATE_KBPS', 'DATABASE_ADMIN_PASSWORD'} + + +def save_configuration(path, values): + import win32crypt + # DPAPI is bound to this Windows account, matching the InteractiveToken task. + protected = win32crypt.CryptProtectData(json.dumps(values).encode('utf-8'), + 'Townlight Station', None, None, None, 1) # CRYPTPROTECT_UI_FORBIDDEN + temporary = path.with_suffix('.tmp') + temporary.write_text(json.dumps({'windows_protected_configuration': base64.b64encode(protected).decode('ascii')}), encoding='utf-8') + temporary.replace(path) + + +def load_configuration(path): + path = Path(path) + if not path.is_absolute(): + raise ValueError('Station configuration path must be absolute') + private_path(path.parent, path.name) + values = json.loads(path.read_text(encoding='utf-8')) + legacy = isinstance(values, dict) and 'windows_protected_configuration' not in values + if isinstance(values, dict) and set(values) == {'windows_protected_configuration'}: + import win32crypt + values = json.loads(win32crypt.CryptUnprotectData(base64.b64decode(values['windows_protected_configuration'], validate=True), None, None, None, 1)[1].decode('utf-8')) + if not isinstance(values, dict) or set(values) - CONFIG_KEYS or any(not isinstance(v, str) for v in values.values()): + raise ValueError('Invalid Station configuration') + if Path(values.get('DATA_ROOT', '')).resolve() != path.parent.resolve(): + raise ValueError('Station configuration must belong to its protected data directory') + if legacy: + save_configuration(path, values) + for key, value in values.items(): + os.environ['TOWNLIGHT_STATION_'+key] = value + return values + + +def task_name(data): + import hashlib + return 'Townlight Station '+hashlib.sha256(str(data.resolve()).casefold().encode()).hexdigest()[:16] + + +def verify_task_owner(xml, python, args, username): + import win32security + tree = ET.fromstring(xml) + ns = {'t': 'http://schemas.microsoft.com/windows/2004/02/mit/task'} + existing = tree.findtext('.//t:Exec/t:Arguments', namespaces=ns) + command = tree.findtext('.//t:Exec/t:Command', namespaces=ns) + owner = tree.findtext('.//t:Principal/t:UserId', namespaces=ns) + try: + existing_sid = win32security.ConvertStringSidToSid(owner) if owner and owner.startswith('S-1-') else win32security.LookupAccountName(None, owner)[0] + same_owner = existing_sid == win32security.LookupAccountName(None, username)[0] + except Exception: + same_owner = False + if existing != args or not command or Path(command).resolve() != Path(python).resolve() or not same_owner: + raise ValueError('An unrelated scheduled task owns this name; no task was replaced') + + +def register_task(python, config): + import win32api + from xml.sax.saxutils import escape + name = task_name(config.parent) + username = win32api.GetUserNameEx(2) # NameSamCompatible; no password storage. + args = subprocess.list2cmdline(['-B', '-m', 'townlight_station.cli', 'background', '--config', str(config)]) + # Check ownership before updating a task with this deterministic name. + scheduler = str(Path(os.environ['SYSTEMROOT'])/'System32/schtasks.exe') + query = subprocess.run([scheduler, '/Query', '/TN', name, '/XML'], + capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW) + if query.returncode == 0: + verify_task_owner(query.stdout, python, args, username) + xml = f''' + +Townlight owned meeting recorder: {escape(str(config))} +true{escape(username)} +{escape(username)}InteractiveTokenLeastPrivilege +trueIgnoreNewfalsefalsePT0StruePT1M3 +{escape(str(python))}{escape(args)}{escape(str(python.parent))}''' + task_file = config.parent/'logon-task.xml' + task_file.write_text(xml, encoding='utf-16') + subprocess.run([scheduler, '/Create', '/TN', name, '/XML', str(task_file), '/F'], + capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW) + subprocess.run([scheduler, '/Run', '/TN', name], capture_output=True, + check=True, creationflags=subprocess.CREATE_NO_WINDOW) + + +def stop_task(config): + import win32api + values = load_configuration(config) + config = Path(config) + scheduler = str(Path(os.environ['SYSTEMROOT'])/'System32/schtasks.exe') + name = task_name(config.parent) + query = subprocess.run([scheduler, '/Query', '/TN', name, '/XML'], capture_output=True, + text=True, timeout=10, creationflags=subprocess.CREATE_NO_WINDOW) + if query.returncode != 0: + status = subprocess.run([str(Path(values['POSTGRES_BIN'])/'pg_ctl.exe'), '-D', str(config.parent/'postgres'), 'status'], capture_output=True, timeout=10, creationflags=subprocess.CREATE_NO_WINDOW) + if status.returncode == 3 and not (config.parent/'background-health.json').exists(): + return {'stopped': True, 'message': 'Recorder is already stopped; data is preserved.'} + raise ValueError('Recorder task is unavailable; no unrelated process was stopped') + python = Path(values['CONTROL_PYTHON']).with_name('pythonw.exe') + args = subprocess.list2cmdline(['-B', '-m', 'townlight_station.cli', 'background', '--config', str(config)]) + verify_task_owner(query.stdout, python, args, win32api.GetUserNameEx(2)) + from .store import Store + from .backup import maintenance + store = Store(values['DATABASE_URL']) + try: + with maintenance(store): + (config.parent/'background.stop').write_text('stop', encoding='ascii') + finally: + store.engine.dispose() + # Graceful process termination closes API/workers and cleanly stops PostgreSQL. + deadline = time.monotonic()+180 + while time.monotonic() < deadline: + health = config.parent/'background-health.json' + if not health.exists(): + break + time.sleep(.5) + else: + raise RuntimeError('Recorder did not stop cleanly; task and data were preserved for recovery') + subprocess.run([scheduler, '/Delete', '/TN', name, '/F'], capture_output=True, + check=True, timeout=10, creationflags=subprocess.CREATE_NO_WINDOW) + return {'stopped': True, 'message': 'Recorder stopped and its owned logon task removed. Data and backups are preserved.'} + + +def provision(payload, data, suite_url): + payload, data = Path(payload).resolve(), Path(data).absolute() + private_path(data) + config = data/'settings.json' + if config.exists(): + values = load_configuration(config) + if values['SUITE_URL'] != suite_url: + raise ValueError('Existing Station is paired with another Suite origin') + else: + password = secrets.token_hex(32) + values = dict(DATA_ROOT=str(data), + DATABASE_URL=f'postgresql+psycopg2://station_app:{password}@127.0.0.1:15435/townlight_station', + DATABASE_ADMIN_PASSWORD=secrets.token_hex(32), + SUITE_URL=suite_url, MEDIA_SOURCE=str(payload/'station/media-source'), + MEDIA_PYTHON=str(payload/'station/media-runtime/python.exe'), + MEDIA_RUNTIME=str(payload/'station/media-runtime'), + FFPROBE=str(payload/'station/bin/ffprobe.exe'), + CONTROL_PYTHON=str(payload/'python/python.exe'), POSTGRES_BIN=str(payload/'postgres/bin')) + for k, v in values.items(): + os.environ['TOWNLIGHT_STATION_'+k] = v + cfg = Settings.from_env() + cfg.initialize_storage() # Refuses unowned nonempty data and applies private ACLs. + cfg.verify_media() + save_configuration(config, values) + paths = dict(MEDIA_SOURCE=str(payload/'station/media-source'), + MEDIA_PYTHON=str(payload/'station/media-runtime/python.exe'), + MEDIA_RUNTIME=str(payload/'station/media-runtime'), FFPROBE=str(payload/'station/bin/ffprobe.exe'), + CONTROL_PYTHON=str(payload/'python/python.exe'), POSTGRES_BIN=str(payload/'postgres/bin')) + values.update(paths) + for k, v in values.items(): + os.environ['TOWNLIGHT_STATION_'+k] = v + cfg = Settings.from_env() + cfg.verify_media() + # Validate media environment and plugins in the actual native runtime. + from .devices import discover + discover(cfg) # Empty devices is permitted; a saved network source may be used. + save_configuration(config, values) + pythonw = Path(values['CONTROL_PYTHON']).with_name('pythonw.exe') + if not pythonw.is_file(): + raise ValueError('Installed background Python is missing; repair the Townlight installation') + (data/'background.stop').unlink(missing_ok=True) + register_task(pythonw, config) + import httpx + deadline = time.monotonic()+240 + while True: + try: + with httpx.Client(trust_env=False, timeout=2) as client: + response = client.get('http://127.0.0.1:8756/health') + if response.status_code == 200 and response.json().get('product') == 'townlight-station' and response.json().get('instance') == task_name(data): + break + except httpx.HTTPError: + pass + if time.monotonic() >= deadline: + raise RuntimeError('Recorder is configured but not ready. Review its private PostgreSQL, serve and worker logs, then retry setup.') + time.sleep(1) + return {'configured': True, 'task': task_name(data), 'data_directory': str(data), + 'message': 'Recorder starts at Windows sign-in. Keep Windows signed in during recording.'} + + +def background(config): + import psycopg2 + import win32api + import win32con + import win32event + from sqlalchemy.engine import make_url + from .store import Store + values = load_configuration(config) + cfg = Settings.from_env() + cfg.initialize_storage() + cfg.verify_media() + sys.path.insert(0, str(cfg.media_source)) + from civiccast.platform.child_containment import contain_own_descendants + containment = contain_own_descendants() + if not containment.active: + raise RuntimeError('Recorder cannot contain its own children') + db = make_url(cfg.database_url) + pg = Path(values['POSTGRES_BIN']) + pg_ctl = pg / 'pg_ctl.exe' + cluster = private_path(cfg.data, 'postgres') + cluster.mkdir(exist_ok=True) + if not (cluster / 'PG_VERSION').exists(): + from .windows_cluster import initialize_cluster + initialize_cluster(pg, cluster, values['DATABASE_ADMIN_PASSWORD']) + pid_path = cluster / 'postmaster.pid' + pg_log = private_path(cfg.data, 'postgres.log') + handles, children = [], [] + owned = False + postmaster_pid = None + postmaster_handle = None + + def start(name, argv): + log = (cfg.data / (name + '.log')).open('a', encoding='utf-8') + handles.append(log) + child = subprocess.Popen(argv, stdout=log, stderr=subprocess.STDOUT, + creationflags=subprocess.CREATE_NO_WINDOW) + children.append(child) + return child + + def read_pid(): + try: + return int(pid_path.read_text(encoding='utf-8').splitlines()[0].strip()) + except (OSError, ValueError, IndexError): + return None + + def alive(handle): + return (handle is not None and + win32event.WaitForSingleObject(handle, 0) == win32event.WAIT_TIMEOUT) + + try: + # A running cluster is foreign to this startup attempt. Never touch it. + status = subprocess.run([str(pg_ctl), 'status', '-D', str(cluster)], + capture_output=True, timeout=30, + creationflags=subprocess.CREATE_NO_WINDOW) + if status.returncode == 0: + raise RuntimeError('Recorder cluster is already running; refusing to touch it') + if status.returncode != 3: + raise RuntimeError('Recorder cluster status is indeterminate; refusing to start') + + # pg_ctl starts postgres.exe with a restricted token and inherits the + # already-active Station Job Object, so crash containment still applies. + with private_path(cfg.data, 'postgres-start.log').open('a', encoding='utf-8') as startup_log: + startup = subprocess.run( + [str(pg_ctl), 'start', '-w', '-t', '160', '-D', str(cluster), + '-l', str(pg_log), '-o', f'-h 127.0.0.1 -p {db.port}'], + stdin=subprocess.DEVNULL, stdout=startup_log, stderr=subprocess.STDOUT, + timeout=200, + creationflags=subprocess.CREATE_NO_WINDOW) + if startup.returncode != 0: + raise RuntimeError('Recorder database did not start; inspect its private PostgreSQL log') + + postmaster_pid = read_pid() + if not postmaster_pid: + raise RuntimeError('Recorder database started without a readable postmaster PID file') + try: + postmaster_handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, postmaster_pid) + except Exception: + raise RuntimeError('Recorder database postmaster is not running after start') from None + if not alive(postmaster_handle): + raise RuntimeError('Recorder database postmaster is not running after start') + + # pg_ctl -w -t 160 already blocked until the postmaster accepts + # connections; the SQL retry below is only a short post-condition so + # the whole function stays inside the caller's 240s budget. + deadline = time.monotonic() + 15 + connection = None + while connection is None: + try: + connection = psycopg2.connect( + host=db.host, port=db.port, user='station_owner', + password=values['DATABASE_ADMIN_PASSWORD'], dbname='postgres', + connect_timeout=2) + except psycopg2.OperationalError: + if not alive(postmaster_handle) or time.monotonic() >= deadline: + raise RuntimeError('Recorder database did not start; inspect its private PostgreSQL log') from None + time.sleep(0.5) + + # One authenticated session serves both the identity check and the + # bootstrap SQL, so there is no window for a foreign cluster to swap + # in between SHOW data_directory and CREATE ROLE / CREATE DATABASE. + try: + connection.autocommit = True + with connection.cursor() as cursor: + cursor.execute('SHOW data_directory') + actual = Path(cursor.fetchone()[0]) + if actual.resolve() != cluster.resolve(): + raise RuntimeError('Recorder database identity does not match the configured data directory') + + # Ownership is claimed only when: our pg_ctl start succeeded, the + # PID file still names the postmaster we started, the handle we + # hold is still live, and SQL confirmed our data directory. The + # liveness/PID recheck happens right before we claim ownership and + # before any CREATE statements run. + if not alive(postmaster_handle): + raise RuntimeError('Recorder database postmaster exited') + if read_pid() != postmaster_pid: + raise RuntimeError('Recorder database postmaster PID file changed; refusing to continue') + owned = True + + with connection.cursor() as cursor: + from psycopg2 import sql + cursor.execute('SELECT 1 FROM pg_roles WHERE rolname=%s', (db.username,)) + if not cursor.fetchone(): + cursor.execute(sql.SQL('CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD %s') + .format(sql.Identifier(db.username)), (db.password,)) + cursor.execute('SELECT 1 FROM pg_database WHERE datname=%s', (db.database,)) + if not cursor.fetchone(): + cursor.execute(sql.SQL('CREATE DATABASE {} OWNER {}') + .format(sql.Identifier(db.database), sql.Identifier(db.username))) + finally: + connection.close() + + store = Store(cfg.database_url) + try: + store.migrate() + finally: + store.engine.dispose() + + for role in ('serve', 'worker', 'uploads'): + # The API and workers receive only the application login, not the cluster owner secret. + saved_admin = os.environ.pop('TOWNLIGHT_STATION_DATABASE_ADMIN_PASSWORD', None) + try: + start(role, [values['CONTROL_PYTHON'], '-B', '-m', 'townlight_station.cli', role]) + finally: + if saved_admin is not None: + os.environ['TOWNLIGHT_STATION_DATABASE_ADMIN_PASSWORD'] = saved_admin + + while not (cfg.data / 'background.stop').exists(): + for child in children: + if child.poll() is not None: + raise RuntimeError('Recorder child exited; logon task will perform bounded restart') + if not alive(postmaster_handle): + raise RuntimeError('Recorder database postmaster exited; logon task will perform bounded restart') + if read_pid() != postmaster_pid: + raise RuntimeError('Recorder database postmaster PID file changed; refusing to continue') + health = cfg.data / 'background-health.json' + temporary = health.with_suffix('.tmp') + temporary.write_text(json.dumps({'updated_at': time.time(), 'pid': os.getpid()}), encoding='utf-8') + temporary.replace(health) + time.sleep(1) + finally: + # Each cleanup step is isolated so that a failure in one (child kill, + # DB stop) never prevents the remaining handles/handlers from being + # released, and so that the primary error is never silently masked. + primary_error = sys.exc_info()[1] + cleanup_error = None + + try: + for child in reversed(children): + if child.poll() is None: + child.terminate() + try: + child.wait(timeout=20) + except subprocess.TimeoutExpired: + child.kill() + child.wait(timeout=10) + except BaseException as exc: + if cleanup_error is None: + cleanup_error = exc + + try: + # Fast stop only our exact original postmaster, still live, with + # the same PID file. A non-zero exit must be reported rather than + # silently discarded. + if (owned and postmaster_handle is not None and alive(postmaster_handle) and + read_pid() == postmaster_pid): + stop = subprocess.run( + [str(pg_ctl), '-D', str(cluster), '-m', 'fast', '-w', '-t', '180', 'stop'], + capture_output=True, timeout=200, + creationflags=subprocess.CREATE_NO_WINDOW) + win32event.WaitForSingleObject(postmaster_handle, 30000) + if stop.returncode != 0 and cleanup_error is None: + cleanup_error = RuntimeError( + 'Recorder database fast stop failed; inspect its private PostgreSQL log') + except BaseException as exc: + if cleanup_error is None: + cleanup_error = exc + + try: + if postmaster_handle is not None: + win32api.CloseHandle(postmaster_handle) + except BaseException as exc: + if cleanup_error is None: + cleanup_error = exc + + try: + for log in handles: + log.close() + except BaseException as exc: + if cleanup_error is None: + cleanup_error = exc + + try: + (cfg.data / 'background-health.json').unlink(missing_ok=True) + except BaseException as exc: + if cleanup_error is None: + cleanup_error = exc + + if cleanup_error is not None: + if isinstance(primary_error, (KeyboardInterrupt, SystemExit)): + # Don't replace operator-initiated interrupts/exits. + pass + elif primary_error is not None: + # Chaining keeps the original launch/child/postmaster error + # visible in the traceback alongside the stop failure. + raise cleanup_error from primary_error + else: + raise cleanup_error diff --git a/beta-1/townlight_station/storage_policy.py b/beta-1/townlight_station/storage_policy.py new file mode 100644 index 00000000..5fa6c18e --- /dev/null +++ b/beta-1/townlight_station/storage_policy.py @@ -0,0 +1,25 @@ +# SPDX-License-Identifier: AGPL-3.0-only +"""Bounded large-meeting storage; no file is read into memory for budgeting.""" +import shutil + + +def storage_status(settings): + # Include AAC audio and TS overhead above configured video bitrate. + estimated = int((settings.bitrate_kbps + 256) * 1000 / 8 * settings.max_seconds * 1.12) + reserve = settings.reserve_bytes + free = shutil.disk_usage(settings.data).free + return {'free_bytes': free, 'reserve_bytes': reserve, + 'estimated_recording_bytes': estimated, + 'max_bytes': settings.max_bytes, 'max_seconds': settings.max_seconds, + 'ready': estimated <= settings.max_bytes and free >= estimated + reserve, + 'low_space': free < reserve + 256*1024**2} + + +def require_capacity(settings, *, source_bytes=0): + status = storage_status(settings) + needed = status['estimated_recording_bytes'] + source_bytes + status['reserve_bytes'] + if status['estimated_recording_bytes'] > settings.max_bytes: + raise ValueError('Recording size policy cannot hold the configured meeting duration') + if status['free_bytes'] < needed: + raise ValueError('Insufficient recording space; free space or choose another recording drive in setup') + return status diff --git a/beta-1/townlight_station/ui/operator.css b/beta-1/townlight_station/ui/operator.css index 574cde53..d8cb00d5 100644 --- a/beta-1/townlight_station/ui/operator.css +++ b/beta-1/townlight_station/ui/operator.css @@ -1 +1 @@ -:root{color-scheme:light;font-family:system-ui,sans-serif;color:#17333b;background:#f2f5f3}*{box-sizing:border-box}body{margin:0}header,main,footer{max-width:1100px;margin:auto;padding:24px}header{display:flex;justify-content:space-between;align-items:center;border-bottom:2px solid #cbd9d3}h1{font-size:40px;margin:4px 0}h2{font-size:24px;margin-top:0}.eyebrow{font-size:12px;letter-spacing:3px;font-weight:700}section{background:#fff;border:1px solid #cbd9d3;border-radius:12px;padding:24px;margin:20px 0}p{line-height:1.5}label{display:grid;gap:7px;font-weight:600;flex:1}form,.section-heading{display:flex;gap:16px;align-items:end;margin:18px 0}input,select,button{font:inherit;border:1px solid #829b91;border-radius:6px;padding:11px;min-height:44px}input,select{width:100%;background:#fff}button{cursor:pointer;background:#155b4c;color:#fff;font-weight:600;white-space:nowrap}button:disabled{opacity:.55;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #d07b1a;outline-offset:3px}.section-heading{justify-content:space-between}article{border-top:1px solid #d9e3df;padding:20px 0;overflow-wrap:anywhere}article h3{margin:0 0 8px}.status{font-weight:700}.error{color:#962716}#message{border-left:4px solid #155b4c;padding:12px;background:#e3eee8}footer{color:#4b645b;font-size:14px}[hidden]{display:none!important}@media(max-width:650px){header,main,footer{padding:16px}section{padding:16px}form{flex-direction:column;align-items:stretch}h1{font-size:32px}header{align-items:start}header button{white-space:normal}}.agenda-choice{display:flex;align-items:center;gap:12px;margin:12px 0}.agenda-choice input{width:20px;min-height:20px}details{margin-top:18px;font-size:14px} +:root{color-scheme:light;font-family:system-ui,sans-serif;color:#17333b;background:#f2f5f3}*{box-sizing:border-box}body{margin:0}header,main,footer{max-width:1100px;margin:auto;padding:24px}header{display:flex;justify-content:space-between;align-items:center;border-bottom:2px solid #cbd9d3}h1{font-size:40px;margin:4px 0}h2{font-size:24px;margin-top:0}.eyebrow{font-size:12px;letter-spacing:3px;font-weight:700}section{background:#fff;border:1px solid #cbd9d3;border-radius:12px;padding:24px;margin:20px 0}p{line-height:1.5}label{display:grid;gap:7px;font-weight:600;flex:1}form,.section-heading{display:flex;gap:16px;align-items:end;margin:18px 0}input,select,button{font:inherit;border:1px solid #829b91;border-radius:6px;padding:11px;min-height:44px}input,select{width:100%;background:#fff}button{cursor:pointer;background:#155b4c;color:#fff;font-weight:600;white-space:nowrap}button:disabled{opacity:.55;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #d07b1a;outline-offset:3px}.section-heading{justify-content:space-between}article{border-top:1px solid #d9e3df;padding:20px 0;overflow-wrap:anywhere}article h3{margin:0 0 8px}.status{font-weight:700}.error{color:#962716}#message{border-left:4px solid #155b4c;padding:12px;background:#e3eee8}footer{color:#4b645b;font-size:14px}[hidden]{display:none!important}@media(max-width:650px){header,main,footer{padding:16px}section{padding:16px}form{flex-direction:column;align-items:stretch}h1{font-size:32px}header{align-items:start}header button{white-space:normal}}.agenda-choice{display:flex;align-items:center;gap:12px;margin:12px 0}.agenda-choice input{width:20px;min-height:20px}details{margin-top:18px;font-size:14px}video{display:block;max-width:100%;width:640px;background:#152f3a;margin:16px 0}meter{width:100%;max-width:640px;height:24px} diff --git a/beta-1/townlight_station/ui/operator.js b/beta-1/townlight_station/ui/operator.js index bef385b7..69a04f7b 100644 --- a/beta-1/townlight_station/ui/operator.js +++ b/beta-1/townlight_station/ui/operator.js @@ -1,9 +1,9 @@ -(function(){const $=document.createElement("link").relList;if($&&$.supports&&$.supports("modulepreload"))return;for(const ll of document.querySelectorAll('link[rel="modulepreload"]'))S(ll);new MutationObserver(ll=>{for(const I of ll)if(I.type==="childList")for(const cl of I.addedNodes)cl.tagName==="LINK"&&cl.rel==="modulepreload"&&S(cl)}).observe(document,{childList:!0,subtree:!0});function F(ll){const I={};return ll.integrity&&(I.integrity=ll.integrity),ll.referrerPolicy&&(I.referrerPolicy=ll.referrerPolicy),ll.crossOrigin==="use-credentials"?I.credentials="include":ll.crossOrigin==="anonymous"?I.credentials="omit":I.credentials="same-origin",I}function S(ll){if(ll.ep)return;ll.ep=!0;const I=F(ll);fetch(ll.href,I)}})();function z0(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}var ff={exports:{}},Z={};var ur;function O0(){if(ur)return Z;ur=1;var _=Symbol.for("react.transitional.element"),$=Symbol.for("react.portal"),F=Symbol.for("react.fragment"),S=Symbol.for("react.strict_mode"),ll=Symbol.for("react.profiler"),I=Symbol.for("react.consumer"),cl=Symbol.for("react.context"),kl=Symbol.for("react.forward_ref"),R=Symbol.for("react.suspense"),A=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),el=Symbol.iterator;function w(s){return s===null||typeof s!="object"?null:(s=el&&s[el]||s["@@iterator"],typeof s=="function"?s:null)}var zl={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,Gl={};function Tl(s,z,D){this.props=s,this.context=z,this.refs=Gl,this.updater=D||zl}Tl.prototype.isReactComponent={},Tl.prototype.setState=function(s,z){if(typeof s!="object"&&typeof s!="function"&&s!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,s,z,"setState")},Tl.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function Gt(){}Gt.prototype=Tl.prototype;function bl(s,z,D){this.props=s,this.context=z,this.refs=Gl,this.updater=D||zl}var Rl=bl.prototype=new Gt;Rl.constructor=bl,j(Rl,Tl.prototype),Rl.isPureReactComponent=!0;var Nl=Array.isArray,J={H:null,A:null,T:null,S:null,V:null},Xl=Object.prototype.hasOwnProperty;function Vl(s,z,D,M,B,k){return D=k.ref,{$$typeof:_,type:s,key:z,ref:D!==void 0?D:null,props:k}}function nl(s,z){return Vl(s.type,z,void 0,void 0,void 0,s.props)}function Ol(s){return typeof s=="object"&&s!==null&&s.$$typeof===_}function Dt(s){var z={"=":"=0",":":"=2"};return"$"+s.replace(/[=:]/g,function(D){return z[D]})}var At=/\/+/g;function Ml(s,z){return typeof s=="object"&&s!==null&&s.key!=null?Dt(""+s.key):z.toString(36)}function Xt(){}function _t(s){switch(s.status){case"fulfilled":return s.value;case"rejected":throw s.reason;default:switch(typeof s.status=="string"?s.then(Xt,Xt):(s.status="pending",s.then(function(z){s.status==="pending"&&(s.status="fulfilled",s.value=z)},function(z){s.status==="pending"&&(s.status="rejected",s.reason=z)})),s.status){case"fulfilled":return s.value;case"rejected":throw s.reason}}throw s}function ql(s,z,D,M,B){var k=typeof s;(k==="undefined"||k==="boolean")&&(s=null);var Q=!1;if(s===null)Q=!0;else switch(k){case"bigint":case"string":case"number":Q=!0;break;case"object":switch(s.$$typeof){case _:case $:Q=!0;break;case N:return Q=s._init,ql(Q(s._payload),z,D,M,B)}}if(Q)return B=B(s),Q=M===""?"."+Ml(s,0):M,Nl(B)?(D="",Q!=null&&(D=Q.replace(At,"$&/")+"/"),ql(B,z,D,"",function(Ut){return Ut})):B!=null&&(Ol(B)&&(B=nl(B,D+(B.key==null||s&&s.key===B.key?"":(""+B.key).replace(At,"$&/")+"/")+Q)),z.push(B)),1;Q=0;var Wl=M===""?".":M+":";if(Nl(s))for(var vl=0;vl>>1,s=b[al];if(0>>1;alll(M,H))Bll(k,M)?(b[al]=k,b[B]=H,al=B):(b[al]=M,b[D]=H,al=D);else if(Bll(k,H))b[al]=k,b[B]=H,al=B;else break l}}return O}function ll(b,O){var H=b.sortIndex-O.sortIndex;return H!==0?H:b.id-O.id}if(_.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var I=performance;_.unstable_now=function(){return I.now()}}else{var cl=Date,kl=cl.now();_.unstable_now=function(){return cl.now()-kl}}var R=[],A=[],N=1,el=null,w=3,zl=!1,j=!1,Gl=!1,Tl=!1,Gt=typeof setTimeout=="function"?setTimeout:null,bl=typeof clearTimeout=="function"?clearTimeout:null,Rl=typeof setImmediate<"u"?setImmediate:null;function Nl(b){for(var O=F(A);O!==null;){if(O.callback===null)S(A);else if(O.startTime<=b)S(A),O.sortIndex=O.expirationTime,$(R,O);else break;O=F(A)}}function J(b){if(Gl=!1,Nl(b),!j)if(F(R)!==null)j=!0,Xl||(Xl=!0,Ml());else{var O=F(A);O!==null&&ql(J,O.startTime-b)}}var Xl=!1,Vl=-1,nl=5,Ol=-1;function Dt(){return Tl?!0:!(_.unstable_now()-Olb&&Dt());){var al=el.callback;if(typeof al=="function"){el.callback=null,w=el.priorityLevel;var s=al(el.expirationTime<=b);if(b=_.unstable_now(),typeof s=="function"){el.callback=s,Nl(b),O=!0;break t}el===F(R)&&S(R),Nl(b)}else S(R);el=F(R)}if(el!==null)O=!0;else{var z=F(A);z!==null&&ql(J,z.startTime-b),O=!1}}break l}finally{el=null,w=H,zl=!1}O=void 0}}finally{O?Ml():Xl=!1}}}var Ml;if(typeof Rl=="function")Ml=function(){Rl(At)};else if(typeof MessageChannel<"u"){var Xt=new MessageChannel,_t=Xt.port2;Xt.port1.onmessage=At,Ml=function(){_t.postMessage(null)}}else Ml=function(){Gt(At,0)};function ql(b,O){Vl=Gt(function(){b(_.unstable_now())},O)}_.unstable_IdlePriority=5,_.unstable_ImmediatePriority=1,_.unstable_LowPriority=4,_.unstable_NormalPriority=3,_.unstable_Profiling=null,_.unstable_UserBlockingPriority=2,_.unstable_cancelCallback=function(b){b.callback=null},_.unstable_forceFrameRate=function(b){0>b||125al?(b.sortIndex=H,$(A,b),F(R)===null&&b===F(A)&&(Gl?(bl(Vl),Vl=-1):Gl=!0,ql(J,H-al))):(b.sortIndex=s,$(R,b),j||zl||(j=!0,Xl||(Xl=!0,Ml()))),b},_.unstable_shouldYield=Dt,_.unstable_wrapCallback=function(b){var O=w;return function(){var H=w;w=O;try{return b.apply(this,arguments)}finally{w=H}}}})(of)),of}var ir;function D0(){return ir||(ir=1,df.exports=M0()),df.exports}var rf={exports:{}},wl={};var fr;function U0(){if(fr)return wl;fr=1;var _=vf();function $(R){var A="https://react.dev/errors/"+R;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(_)}catch($){console.error($)}}return _(),rf.exports=U0(),rf.exports}var dr;function N0(){if(dr)return Uu;dr=1;var _=D0(),$=vf(),F=R0();function S(l){var t="https://react.dev/errors/"+l;if(1s||(l.current=al[s],al[s]=null,s--)}function M(l,t){s++,al[s]=l.current,l.current=t}var B=z(null),k=z(null),Q=z(null),Wl=z(null);function vl(l,t){switch(M(Q,t),M(k,l),M(B,null),t.nodeType){case 9:case 11:l=(l=t.documentElement)&&(l=l.namespaceURI)?qo(l):0;break;default:if(l=t.tagName,t=t.namespaceURI)t=qo(t),l=Ho(t,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}D(B),M(B,l)}function Ut(){D(B),D(k),D(Q)}function Qt(l){l.memoizedState!==null&&M(Wl,l);var t=B.current,e=Ho(t,l.type);t!==e&&(M(k,l),M(B,e))}function te(l){k.current===l&&(D(B),D(k)),Wl.current===l&&(D(Wl),_u._currentValue=H)}var vt=Object.prototype.hasOwnProperty,ut=_.unstable_scheduleCallback,Le=_.unstable_cancelCallback,Ke=_.unstable_shouldYield,Rt=_.unstable_requestPaint,nt=_.unstable_now,Jn=_.unstable_getCurrentPriorityLevel,qa=_.unstable_ImmediatePriority,Ru=_.unstable_UserBlockingPriority,Je=_.unstable_NormalPriority,wn=_.unstable_LowPriority,Nu=_.unstable_IdlePriority,Nt=_.log,kn=_.unstable_setDisableYieldValue,ee=null,$l=null;function y(l){if(typeof Nt=="function"&&kn(l),$l&&typeof $l.setStrictMode=="function")try{$l.setStrictMode(ee,l)}catch{}}var Y=Math.clz32?Math.clz32:Wn,Ll=Math.log,Fl=Math.LN2;function Wn(l){return l>>>=0,l===0?32:31-(Ll(l)/Fl|0)|0}var qu=256,Hu=4194304;function Oe(l){var t=l&42;if(t!==0)return t;switch(l&-l){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function Yu(l,t,e){var a=l.pendingLanes;if(a===0)return 0;var u=0,n=l.suspendedLanes,c=l.pingedLanes;l=l.warmLanes;var i=a&134217727;return i!==0?(a=i&~n,a!==0?u=Oe(a):(c&=i,c!==0?u=Oe(c):e||(e=i&~l,e!==0&&(u=Oe(e))))):(i=a&~n,i!==0?u=Oe(i):c!==0?u=Oe(c):e||(e=a&~l,e!==0&&(u=Oe(e)))),u===0?0:t!==0&&t!==u&&(t&n)===0&&(n=u&-u,e=t&-t,n>=e||n===32&&(e&4194048)!==0)?t:u}function Ha(l,t){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&t)===0}function rr(l,t){switch(l){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function yf(){var l=qu;return qu<<=1,(qu&4194048)===0&&(qu=256),l}function mf(){var l=Hu;return Hu<<=1,(Hu&62914560)===0&&(Hu=4194304),l}function $n(l){for(var t=[],e=0;31>e;e++)t.push(l);return t}function Ya(l,t){l.pendingLanes|=t,t!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function vr(l,t,e,a,u,n){var c=l.pendingLanes;l.pendingLanes=e,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=e,l.entangledLanes&=e,l.errorRecoveryDisabledLanes&=e,l.shellSuspendCounter=0;var i=l.entanglements,f=l.expirationTimes,v=l.hiddenUpdates;for(e=c&~e;0{for(const P of tl)if(P.type==="childList")for(const cl of P.addedNodes)cl.tagName==="LINK"&&cl.rel==="modulepreload"&&S(cl)}).observe(document,{childList:!0,subtree:!0});function I(tl){const P={};return tl.integrity&&(P.integrity=tl.integrity),tl.referrerPolicy&&(P.referrerPolicy=tl.referrerPolicy),tl.crossOrigin==="use-credentials"?P.credentials="include":tl.crossOrigin==="anonymous"?P.credentials="omit":P.credentials="same-origin",P}function S(tl){if(tl.ep)return;tl.ep=!0;const P=I(tl);fetch(tl.href,P)}})();function zm(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var hf={exports:{}},Z={};var id;function Om(){if(id)return Z;id=1;var A=Symbol.for("react.transitional.element"),F=Symbol.for("react.portal"),I=Symbol.for("react.fragment"),S=Symbol.for("react.strict_mode"),tl=Symbol.for("react.profiler"),P=Symbol.for("react.consumer"),cl=Symbol.for("react.context"),Pl=Symbol.for("react.forward_ref"),R=Symbol.for("react.suspense"),_=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),al=Symbol.iterator;function k(s){return s===null||typeof s!="object"?null:(s=al&&s[al]||s["@@iterator"],typeof s=="function"?s:null)}var Rl={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},V=Object.assign,Vl={};function Ml(s,z,D){this.props=s,this.context=z,this.refs=Vl,this.updater=D||Rl}Ml.prototype.isReactComponent={},Ml.prototype.setState=function(s,z){if(typeof s!="object"&&typeof s!="function"&&s!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,s,z,"setState")},Ml.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function xt(){}xt.prototype=Ml.prototype;function Al(s,z,D){this.props=s,this.context=z,this.refs=Vl,this.updater=D||Rl}var Bl=Al.prototype=new xt;Bl.constructor=Al,V(Bl,Ml.prototype),Bl.isPureReactComponent=!0;var Cl=Array.isArray,w={H:null,A:null,T:null,S:null,V:null},Ll=Object.prototype.hasOwnProperty;function Kl(s,z,D,M,Y,W){return D=W.ref,{$$typeof:A,type:s,key:z,ref:D!==void 0?D:null,props:W}}function ll(s,z){return Kl(s.type,z,void 0,void 0,void 0,s.props)}function yl(s){return typeof s=="object"&&s!==null&&s.$$typeof===A}function Nt(s){var z={"=":"=0",":":"=2"};return"$"+s.replace(/[=:]/g,function(D){return z[D]})}var zt=/\/+/g;function Nl(s,z){return typeof s=="object"&&s!==null&&s.key!=null?Nt(""+s.key):z.toString(36)}function Zt(){}function Ot(s){switch(s.status){case"fulfilled":return s.value;case"rejected":throw s.reason;default:switch(typeof s.status=="string"?s.then(Zt,Zt):(s.status="pending",s.then(function(z){s.status==="pending"&&(s.status="fulfilled",s.value=z)},function(z){s.status==="pending"&&(s.status="rejected",s.reason=z)})),s.status){case"fulfilled":return s.value;case"rejected":throw s.reason}}throw s}function Gl(s,z,D,M,Y){var W=typeof s;(W==="undefined"||W==="boolean")&&(s=null);var Q=!1;if(s===null)Q=!0;else switch(W){case"bigint":case"string":case"number":Q=!0;break;case"object":switch(s.$$typeof){case A:case F:Q=!0;break;case N:return Q=s._init,Gl(Q(s._payload),z,D,M,Y)}}if(Q)return Y=Y(s),Q=M===""?"."+Nl(s,0):M,Cl(Y)?(D="",Q!=null&&(D=Q.replace(zt,"$&/")+"/"),Gl(Y,z,D,"",function(qt){return qt})):Y!=null&&(yl(Y)&&(Y=ll(Y,D+(Y.key==null||s&&s.key===Y.key?"":(""+Y.key).replace(zt,"$&/")+"/")+Q)),z.push(Y)),1;Q=0;var lt=M===""?".":M+":";if(Cl(s))for(var vl=0;vl>>1,s=b[ul];if(0>>1;ultl(M,H))Ytl(W,M)?(b[ul]=W,b[Y]=H,ul=Y):(b[ul]=M,b[D]=H,ul=D);else if(Ytl(W,H))b[ul]=W,b[Y]=H,ul=Y;else break l}}return O}function tl(b,O){var H=b.sortIndex-O.sortIndex;return H!==0?H:b.id-O.id}if(A.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var P=performance;A.unstable_now=function(){return P.now()}}else{var cl=Date,Pl=cl.now();A.unstable_now=function(){return cl.now()-Pl}}var R=[],_=[],N=1,al=null,k=3,Rl=!1,V=!1,Vl=!1,Ml=!1,xt=typeof setTimeout=="function"?setTimeout:null,Al=typeof clearTimeout=="function"?clearTimeout:null,Bl=typeof setImmediate<"u"?setImmediate:null;function Cl(b){for(var O=I(_);O!==null;){if(O.callback===null)S(_);else if(O.startTime<=b)S(_),O.sortIndex=O.expirationTime,F(R,O);else break;O=I(_)}}function w(b){if(Vl=!1,Cl(b),!V)if(I(R)!==null)V=!0,Ll||(Ll=!0,Nl());else{var O=I(_);O!==null&&Gl(w,O.startTime-b)}}var Ll=!1,Kl=-1,ll=5,yl=-1;function Nt(){return Ml?!0:!(A.unstable_now()-ylb&&Nt());){var ul=al.callback;if(typeof ul=="function"){al.callback=null,k=al.priorityLevel;var s=ul(al.expirationTime<=b);if(b=A.unstable_now(),typeof s=="function"){al.callback=s,Cl(b),O=!0;break t}al===I(R)&&S(R),Cl(b)}else S(R);al=I(R)}if(al!==null)O=!0;else{var z=I(_);z!==null&&Gl(w,z.startTime-b),O=!1}}break l}finally{al=null,k=H,Rl=!1}O=void 0}}finally{O?Nl():Ll=!1}}}var Nl;if(typeof Bl=="function")Nl=function(){Bl(zt)};else if(typeof MessageChannel<"u"){var Zt=new MessageChannel,Ot=Zt.port2;Zt.port1.onmessage=zt,Nl=function(){Ot.postMessage(null)}}else Nl=function(){xt(zt,0)};function Gl(b,O){Kl=xt(function(){b(A.unstable_now())},O)}A.unstable_IdlePriority=5,A.unstable_ImmediatePriority=1,A.unstable_LowPriority=4,A.unstable_NormalPriority=3,A.unstable_Profiling=null,A.unstable_UserBlockingPriority=2,A.unstable_cancelCallback=function(b){b.callback=null},A.unstable_forceFrameRate=function(b){0>b||125ul?(b.sortIndex=H,F(_,b),I(R)===null&&b===I(_)&&(Vl?(Al(Kl),Kl=-1):Vl=!0,Gl(w,H-ul))):(b.sortIndex=s,F(R,b),V||Rl||(V=!0,Ll||(Ll=!0,Nl()))),b},A.unstable_shouldYield=Nt,A.unstable_wrapCallback=function(b){var O=k;return function(){var H=k;k=O;try{return b.apply(this,arguments)}finally{k=H}}}})(bf)),bf}var rd;function Dm(){return rd||(rd=1,Sf.exports=Mm()),Sf.exports}var Ef={exports:{}},Il={};var od;function Um(){if(od)return Il;od=1;var A=pf();function F(R){var _="https://react.dev/errors/"+R;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(A)}catch(F){console.error(F)}}return A(),Ef.exports=Um(),Ef.exports}var vd;function Nm(){if(vd)return Qu;vd=1;var A=Dm(),F=pf(),I=Rm();function S(l){var t="https://react.dev/errors/"+l;if(1s||(l.current=ul[s],ul[s]=null,s--)}function M(l,t){s++,ul[s]=l.current,l.current=t}var Y=z(null),W=z(null),Q=z(null),lt=z(null);function vl(l,t){switch(M(Q,t),M(W,l),M(Y,null),t.nodeType){case 9:case 11:l=(l=t.documentElement)&&(l=l.namespaceURI)?Bo(l):0;break;default:if(l=t.tagName,t=t.namespaceURI)t=Bo(t),l=Co(t,l);else switch(l){case"svg":l=1;break;case"math":l=2;break;default:l=0}}D(Y),M(Y,l)}function qt(){D(Y),D(W),D(Q)}function De(l){l.memoizedState!==null&&M(lt,l);var t=Y.current,e=Co(t,l.type);t!==e&&(M(W,l),M(Y,e))}function Fe(l){W.current===l&&(D(Y),D(W)),lt.current===l&&(D(lt),Yu._currentValue=H)}var Ue=Object.prototype.hasOwnProperty,Ie=A.unstable_scheduleCallback,Re=A.unstable_cancelCallback,xu=A.unstable_shouldYield,Pe=A.unstable_requestPaint,ct=A.unstable_now,la=A.unstable_getCurrentPriorityLevel,Zu=A.unstable_ImmediatePriority,ju=A.unstable_UserBlockingPriority,ta=A.unstable_NormalPriority,Ne=A.unstable_LowPriority,ae=A.unstable_IdlePriority,La=A.log,it=A.unstable_setDisableYieldValue,ql=null,Wl=null;function ft(l){if(typeof La=="function"&&it(l),Wl&&typeof Wl.setStrictMode=="function")try{Wl.setStrictMode(ql,l)}catch{}}var El=Math.clz32?Math.clz32:uc,ec=Math.log,ac=Math.LN2;function uc(l){return l>>>=0,l===0?32:31-(ec(l)/ac|0)|0}var qe=256,ea=4194304;function Ht(l){var t=l&42;if(t!==0)return t;switch(l&-l){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function aa(l,t,e){var a=l.pendingLanes;if(a===0)return 0;var u=0,n=l.suspendedLanes,c=l.pingedLanes;l=l.warmLanes;var i=a&134217727;return i!==0?(a=i&~n,a!==0?u=Ht(a):(c&=i,c!==0?u=Ht(c):e||(e=i&~l,e!==0&&(u=Ht(e))))):(i=a&~n,i!==0?u=Ht(i):c!==0?u=Ht(c):e||(e=a&~l,e!==0&&(u=Ht(e)))),u===0?0:t!==0&&t!==u&&(t&n)===0&&(n=u&-u,e=t&-t,n>=e||n===32&&(e&4194048)!==0)?t:u}function He(l,t){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&t)===0}function nc(l,t){switch(l){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vu(){var l=qe;return qe<<=1,(qe&4194048)===0&&(qe=256),l}function Mt(){var l=ea;return ea<<=1,(ea&62914560)===0&&(ea=4194304),l}function ue(l){for(var t=[],e=0;31>e;e++)t.push(l);return t}function ne(l,t){l.pendingLanes|=t,t!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function cc(l,t,e,a,u,n){var c=l.pendingLanes;l.pendingLanes=e,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=e,l.entangledLanes&=e,l.errorRecoveryDisabledLanes&=e,l.shellSuspendCounter=0;var i=l.entanglements,f=l.expirationTimes,y=l.hiddenUpdates;for(e=c&~e;0)":-1u||f[a]!==v[u]){var E=` -`+f[a].replace(" at new "," at ");return l.displayName&&E.includes("")&&(E=E.replace("",l.displayName)),E}while(1<=a&&0<=u);break}}}finally{ec=!1,Error.prepareStackTrace=e}return(e=l?l.displayName||l.name:"")?Ie(e):""}function br(l){switch(l.tag){case 26:case 27:case 5:return Ie(l.type);case 16:return Ie("Lazy");case 13:return Ie("Suspense");case 19:return Ie("SuspenseList");case 0:case 15:return ac(l.type,!1);case 11:return ac(l.type.render,!1);case 1:return ac(l.type,!0);case 31:return Ie("Activity");default:return""}}function zf(l){try{var t="";do t+=br(l),l=l.return;while(l);return t}catch(e){return` +`+sc+l+Mf}var rc=!1;function oc(l,t){if(!l||rc)return"";rc=!0;var e=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(t){var T=function(){throw Error()};if(Object.defineProperty(T.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(T,[])}catch(g){var h=g}Reflect.construct(l,[],T)}else{try{T.call()}catch(g){h=g}l.call(T.prototype)}}else{try{throw Error()}catch(g){h=g}(T=l())&&typeof T.catch=="function"&&T.catch(function(){})}}catch(g){if(g&&h&&typeof g.stack=="string")return[g.stack,h.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var u=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");u&&u.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var n=a.DetermineComponentFrameRoot(),c=n[0],i=n[1];if(c&&i){var f=c.split(` +`),y=i.split(` +`);for(u=a=0;au||f[a]!==y[u]){var E=` +`+f[a].replace(" at new "," at ");return l.displayName&&E.includes("")&&(E=E.replace("",l.displayName)),E}while(1<=a&&0<=u);break}}}finally{rc=!1,Error.prepareStackTrace=e}return(e=l?l.displayName||l.name:"")?ra(e):""}function bd(l){switch(l.tag){case 26:case 27:case 5:return ra(l.type);case 16:return ra("Lazy");case 13:return ra("Suspense");case 19:return ra("SuspenseList");case 0:case 15:return oc(l.type,!1);case 11:return oc(l.type.render,!1);case 1:return oc(l.type,!0);case 31:return ra("Activity");default:return""}}function Df(l){try{var t="";do t+=bd(l),l=l.return;while(l);return t}catch(e){return` Error generating stack: `+e.message+` -`+e.stack}}function yt(l){switch(typeof l){case"bigint":case"boolean":case"number":case"string":case"undefined":return l;case"object":return l;default:return""}}function Of(l){var t=l.type;return(l=l.nodeName)&&l.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Er(l){var t=Of(l)?"checked":"value",e=Object.getOwnPropertyDescriptor(l.constructor.prototype,t),a=""+l[t];if(!l.hasOwnProperty(t)&&typeof e<"u"&&typeof e.get=="function"&&typeof e.set=="function"){var u=e.get,n=e.set;return Object.defineProperty(l,t,{configurable:!0,get:function(){return u.call(this)},set:function(c){a=""+c,n.call(this,c)}}),Object.defineProperty(l,t,{enumerable:e.enumerable}),{getValue:function(){return a},setValue:function(c){a=""+c},stopTracking:function(){l._valueTracker=null,delete l[t]}}}}function Gu(l){l._valueTracker||(l._valueTracker=Er(l))}function Mf(l){if(!l)return!1;var t=l._valueTracker;if(!t)return!0;var e=t.getValue(),a="";return l&&(a=Of(l)?l.checked?"true":"false":l.value),l=a,l!==e?(t.setValue(l),!0):!1}function Xu(l){if(l=l||(typeof document<"u"?document:void 0),typeof l>"u")return null;try{return l.activeElement||l.body}catch{return l.body}}var pr=/[\n"\\]/g;function mt(l){return l.replace(pr,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function uc(l,t,e,a,u,n,c,i){l.name="",c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"?l.type=c:l.removeAttribute("type"),t!=null?c==="number"?(t===0&&l.value===""||l.value!=t)&&(l.value=""+yt(t)):l.value!==""+yt(t)&&(l.value=""+yt(t)):c!=="submit"&&c!=="reset"||l.removeAttribute("value"),t!=null?nc(l,c,yt(t)):e!=null?nc(l,c,yt(e)):a!=null&&l.removeAttribute("value"),u==null&&n!=null&&(l.defaultChecked=!!n),u!=null&&(l.checked=u&&typeof u!="function"&&typeof u!="symbol"),i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"?l.name=""+yt(i):l.removeAttribute("name")}function Df(l,t,e,a,u,n,c,i){if(n!=null&&typeof n!="function"&&typeof n!="symbol"&&typeof n!="boolean"&&(l.type=n),t!=null||e!=null){if(!(n!=="submit"&&n!=="reset"||t!=null))return;e=e!=null?""+yt(e):"",t=t!=null?""+yt(t):e,i||t===l.value||(l.value=t),l.defaultValue=t}a=a??u,a=typeof a!="function"&&typeof a!="symbol"&&!!a,l.checked=i?l.checked:!!a,l.defaultChecked=!!a,c!=null&&typeof c!="function"&&typeof c!="symbol"&&typeof c!="boolean"&&(l.name=c)}function nc(l,t,e){t==="number"&&Xu(l.ownerDocument)===l||l.defaultValue===""+e||(l.defaultValue=""+e)}function Pe(l,t,e,a){if(l=l.options,t){t={};for(var u=0;u"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),dc=!1;if(xt)try{var Xa={};Object.defineProperty(Xa,"passive",{get:function(){dc=!0}}),window.addEventListener("test",Xa,Xa),window.removeEventListener("test",Xa,Xa)}catch{dc=!1}var ue=null,oc=null,Zu=null;function Bf(){if(Zu)return Zu;var l,t=oc,e=t.length,a,u="value"in ue?ue.value:ue.textContent,n=u.length;for(l=0;l=xa),xf=" ",jf=!1;function Vf(l,t){switch(l){case"keyup":return Wr.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lf(l){return l=l.detail,typeof l=="object"&&"data"in l?l.data:null}var aa=!1;function Fr(l,t){switch(l){case"compositionend":return Lf(t);case"keypress":return t.which!==32?null:(jf=!0,xf);case"textInput":return l=t.data,l===xf&&jf?null:l;default:return null}}function Ir(l,t){if(aa)return l==="compositionend"||!hc&&Vf(l,t)?(l=Bf(),Zu=oc=ue=null,aa=!1,l):null;switch(l){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:e,offset:t-l};l=a}l:{for(;e;){if(e.nextSibling){e=e.nextSibling;break l}e=e.parentNode}e=void 0}e=If(e)}}function ls(l,t){return l&&t?l===t?!0:l&&l.nodeType===3?!1:t&&t.nodeType===3?ls(l,t.parentNode):"contains"in l?l.contains(t):l.compareDocumentPosition?!!(l.compareDocumentPosition(t)&16):!1:!1}function ts(l){l=l!=null&&l.ownerDocument!=null&&l.ownerDocument.defaultView!=null?l.ownerDocument.defaultView:window;for(var t=Xu(l.document);t instanceof l.HTMLIFrameElement;){try{var e=typeof t.contentWindow.location.href=="string"}catch{e=!1}if(e)l=t.contentWindow;else break;t=Xu(l.document)}return t}function bc(l){var t=l&&l.nodeName&&l.nodeName.toLowerCase();return t&&(t==="input"&&(l.type==="text"||l.type==="search"||l.type==="tel"||l.type==="url"||l.type==="password")||t==="textarea"||l.contentEditable==="true")}var cv=xt&&"documentMode"in document&&11>=document.documentMode,ua=null,Ec=null,Ka=null,pc=!1;function es(l,t,e){var a=e.window===e?e.document:e.nodeType===9?e:e.ownerDocument;pc||ua==null||ua!==Xu(a)||(a=ua,"selectionStart"in a&&bc(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),Ka&&La(Ka,a)||(Ka=a,a=Nn(Ec,"onSelect"),0>=c,u-=c,Vt=1<<32-Y(t)+u|e<n?n:8;var c=b.T,i={};b.T=i,ci(l,!1,t,e);try{var f=u(),v=b.S;if(v!==null&&v(i,f),f!==null&&typeof f=="object"&&typeof f.then=="function"){var E=mv(f,a);cu(l,t,E,ot(l))}else cu(l,t,a,ot(l))}catch(T){cu(l,t,{then:function(){},status:"rejected",reason:T},ot())}finally{O.p=n,b.T=c}}function Ev(){}function ui(l,t,e,a){if(l.tag!==5)throw Error(S(476));var u=ad(l).queue;ed(l,u,t,H,e===null?Ev:function(){return ud(l),e(a)})}function ad(l){var t=l.memoizedState;if(t!==null)return t;t={memoizedState:H,baseState:H,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wt,lastRenderedState:H},next:null};var e={};return t.next={memoizedState:e,baseState:e,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wt,lastRenderedState:e},next:null},l.memoizedState=t,l=l.alternate,l!==null&&(l.memoizedState=t),t}function ud(l){var t=ad(l).next.queue;cu(l,t,{},ot())}function ni(){return Jl(_u)}function nd(){return _l().memoizedState}function cd(){return _l().memoizedState}function pv(l){for(var t=l.return;t!==null;){switch(t.tag){case 24:case 3:var e=ot();l=ie(e);var a=fe(t,l,e);a!==null&&(rt(a,t,e),lu(a,t,e)),t={cache:Bc()},l.payload=t;return}t=t.return}}function Tv(l,t,e){var a=ot();e={lane:a,revertLane:0,action:e,hasEagerState:!1,eagerState:null,next:null},on(l)?fd(t,e):(e=zc(l,t,e,a),e!==null&&(rt(e,l,a),sd(e,t,a)))}function id(l,t,e){var a=ot();cu(l,t,e,a)}function cu(l,t,e,a){var u={lane:a,revertLane:0,action:e,hasEagerState:!1,eagerState:null,next:null};if(on(l))fd(t,u);else{var n=l.alternate;if(l.lanes===0&&(n===null||n.lanes===0)&&(n=t.lastRenderedReducer,n!==null))try{var c=t.lastRenderedState,i=n(c,e);if(u.hasEagerState=!0,u.eagerState=i,ct(i,c))return wu(l,t,u,0),yl===null&&Ju(),!1}catch{}if(e=zc(l,t,u,a),e!==null)return rt(e,l,a),sd(e,t,a),!0}return!1}function ci(l,t,e,a){if(a={lane:2,revertLane:Xi(),action:a,hasEagerState:!1,eagerState:null,next:null},on(l)){if(t)throw Error(S(479))}else t=zc(l,e,a,2),t!==null&&rt(t,l,2)}function on(l){var t=l.alternate;return l===x||t!==null&&t===x}function fd(l,t){ya=un=!0;var e=l.pending;e===null?t.next=t:(t.next=e.next,e.next=t),l.pending=t}function sd(l,t,e){if((e&4194048)!==0){var a=t.lanes;a&=l.pendingLanes,e|=a,t.lanes=e,gf(l,e)}}var rn={readContext:Jl,use:cn,useCallback:El,useContext:El,useEffect:El,useImperativeHandle:El,useLayoutEffect:El,useInsertionEffect:El,useMemo:El,useReducer:El,useRef:El,useState:El,useDebugValue:El,useDeferredValue:El,useTransition:El,useSyncExternalStore:El,useId:El,useHostTransitionStatus:El,useFormState:El,useActionState:El,useOptimistic:El,useMemoCache:El,useCacheRefresh:El},dd={readContext:Jl,use:cn,useCallback:function(l,t){return tt().memoizedState=[l,t===void 0?null:t],l},useContext:Jl,useEffect:ws,useImperativeHandle:function(l,t,e){e=e!=null?e.concat([l]):null,dn(4194308,4,Fs.bind(null,t,l),e)},useLayoutEffect:function(l,t){return dn(4194308,4,l,t)},useInsertionEffect:function(l,t){dn(4,2,l,t)},useMemo:function(l,t){var e=tt();t=t===void 0?null:t;var a=l();if(Qe){y(!0);try{l()}finally{y(!1)}}return e.memoizedState=[a,t],a},useReducer:function(l,t,e){var a=tt();if(e!==void 0){var u=e(t);if(Qe){y(!0);try{e(t)}finally{y(!1)}}}else u=t;return a.memoizedState=a.baseState=u,l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:l,lastRenderedState:u},a.queue=l,l=l.dispatch=Tv.bind(null,x,l),[a.memoizedState,l]},useRef:function(l){var t=tt();return l={current:l},t.memoizedState=l},useState:function(l){l=li(l);var t=l.queue,e=id.bind(null,x,t);return t.dispatch=e,[l.memoizedState,e]},useDebugValue:ei,useDeferredValue:function(l,t){var e=tt();return ai(e,l,t)},useTransition:function(){var l=li(!1);return l=ed.bind(null,x,l.queue,!0,!1),tt().memoizedState=l,[!1,l]},useSyncExternalStore:function(l,t,e){var a=x,u=tt();if(ul){if(e===void 0)throw Error(S(407));e=e()}else{if(e=t(),yl===null)throw Error(S(349));(W&124)!==0||Ns(a,t,e)}u.memoizedState=e;var n={value:e,getSnapshot:t};return u.queue=n,ws(Hs.bind(null,a,n,l),[l]),a.flags|=2048,ha(9,sn(),qs.bind(null,a,n,e,t),null),e},useId:function(){var l=tt(),t=yl.identifierPrefix;if(ul){var e=Lt,a=Vt;e=(a&~(1<<32-Y(a)-1)).toString(32)+e,t="«"+t+"R"+e,e=nn++,0G?(Cl=q,q=null):Cl=q.sibling;var tl=h(o,q,r[G],p);if(tl===null){q===null&&(q=Cl);break}l&&q&&tl.alternate===null&&t(o,q),d=n(tl,d,G),V===null?U=tl:V.sibling=tl,V=tl,q=Cl}if(G===r.length)return e(o,q),ul&&He(o,G),U;if(q===null){for(;GG?(Cl=q,q=null):Cl=q.sibling;var ze=h(o,q,tl.value,p);if(ze===null){q===null&&(q=Cl);break}l&&q&&ze.alternate===null&&t(o,q),d=n(ze,d,G),V===null?U=ze:V.sibling=ze,V=ze,q=Cl}if(tl.done)return e(o,q),ul&&He(o,G),U;if(q===null){for(;!tl.done;G++,tl=r.next())tl=T(o,tl.value,p),tl!==null&&(d=n(tl,d,G),V===null?U=tl:V.sibling=tl,V=tl);return ul&&He(o,G),U}for(q=a(q);!tl.done;G++,tl=r.next())tl=g(q,o,G,tl.value,p),tl!==null&&(l&&tl.alternate!==null&&q.delete(tl.key===null?G:tl.key),d=n(tl,d,G),V===null?U=tl:V.sibling=tl,V=tl);return l&&q.forEach(function(_0){return t(o,_0)}),ul&&He(o,G),U}function ol(o,d,r,p){if(typeof r=="object"&&r!==null&&r.type===j&&r.key===null&&(r=r.props.children),typeof r=="object"&&r!==null){switch(r.$$typeof){case w:l:{for(var U=r.key;d!==null;){if(d.key===U){if(U=r.type,U===j){if(d.tag===7){e(o,d.sibling),p=u(d,r.props.children),p.return=o,o=p;break l}}else if(d.elementType===U||typeof U=="object"&&U!==null&&U.$$typeof===nl&&rd(U)===d.type){e(o,d.sibling),p=u(d,r.props),fu(p,r),p.return=o,o=p;break l}e(o,d);break}else t(o,d);d=d.sibling}r.type===j?(p=Ne(r.props.children,o.mode,p,r.key),p.return=o,o=p):(p=Wu(r.type,r.key,r.props,null,o.mode,p),fu(p,r),p.return=o,o=p)}return c(o);case zl:l:{for(U=r.key;d!==null;){if(d.key===U)if(d.tag===4&&d.stateNode.containerInfo===r.containerInfo&&d.stateNode.implementation===r.implementation){e(o,d.sibling),p=u(d,r.children||[]),p.return=o,o=p;break l}else{e(o,d);break}else t(o,d);d=d.sibling}p=Dc(r,o.mode,p),p.return=o,o=p}return c(o);case nl:return U=r._init,r=U(r._payload),ol(o,d,r,p)}if(ql(r))return X(o,d,r,p);if(Ml(r)){if(U=Ml(r),typeof U!="function")throw Error(S(150));return r=U.call(r),C(o,d,r,p)}if(typeof r.then=="function")return ol(o,d,vn(r),p);if(r.$$typeof===Rl)return ol(o,d,Pu(o,r),p);yn(o,r)}return typeof r=="string"&&r!==""||typeof r=="number"||typeof r=="bigint"?(r=""+r,d!==null&&d.tag===6?(e(o,d.sibling),p=u(d,r),p.return=o,o=p):(e(o,d),p=Mc(r,o.mode,p),p.return=o,o=p),c(o)):e(o,d)}return function(o,d,r,p){try{iu=0;var U=ol(o,d,r,p);return ga=null,U}catch(q){if(q===Ia||q===tn)throw q;var V=it(29,q,null,o.mode);return V.lanes=p,V.return=o,V}}}var Sa=vd(!0),yd=vd(!1),Et=z(null),Ht=null;function de(l){var t=l.alternate;M(Ul,Ul.current&1),M(Et,l),Ht===null&&(t===null||va.current!==null||t.memoizedState!==null)&&(Ht=l)}function md(l){if(l.tag===22){if(M(Ul,Ul.current),M(Et,l),Ht===null){var t=l.alternate;t!==null&&t.memoizedState!==null&&(Ht=l)}}else oe()}function oe(){M(Ul,Ul.current),M(Et,Et.current)}function kt(l){D(Et),Ht===l&&(Ht=null),D(Ul)}var Ul=z(0);function mn(l){for(var t=l;t!==null;){if(t.tag===13){var e=t.memoizedState;if(e!==null&&(e=e.dehydrated,e===null||e.data==="$?"||$i(e)))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if((t.flags&128)!==0)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===l)break;for(;t.sibling===null;){if(t.return===null||t.return===l)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}function ii(l,t,e,a){t=l.memoizedState,e=e(a,t),e=e==null?t:N({},t,e),l.memoizedState=e,l.lanes===0&&(l.updateQueue.baseState=e)}var fi={enqueueSetState:function(l,t,e){l=l._reactInternals;var a=ot(),u=ie(a);u.payload=t,e!=null&&(u.callback=e),t=fe(l,u,a),t!==null&&(rt(t,l,a),lu(t,l,a))},enqueueReplaceState:function(l,t,e){l=l._reactInternals;var a=ot(),u=ie(a);u.tag=1,u.payload=t,e!=null&&(u.callback=e),t=fe(l,u,a),t!==null&&(rt(t,l,a),lu(t,l,a))},enqueueForceUpdate:function(l,t){l=l._reactInternals;var e=ot(),a=ie(e);a.tag=2,t!=null&&(a.callback=t),t=fe(l,a,e),t!==null&&(rt(t,l,e),lu(t,l,e))}};function hd(l,t,e,a,u,n,c){return l=l.stateNode,typeof l.shouldComponentUpdate=="function"?l.shouldComponentUpdate(a,n,c):t.prototype&&t.prototype.isPureReactComponent?!La(e,a)||!La(u,n):!0}function gd(l,t,e,a){l=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(e,a),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(e,a),t.state!==l&&fi.enqueueReplaceState(t,t.state,null)}function Ze(l,t){var e=t;if("ref"in t){e={};for(var a in t)a!=="ref"&&(e[a]=t[a])}if(l=l.defaultProps){e===t&&(e=N({},e));for(var u in l)e[u]===void 0&&(e[u]=l[u])}return e}var hn=typeof reportError=="function"?reportError:function(l){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof l=="object"&&l!==null&&typeof l.message=="string"?String(l.message):String(l),error:l});if(!window.dispatchEvent(t))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",l);return}console.error(l)};function Sd(l){hn(l)}function bd(l){console.error(l)}function Ed(l){hn(l)}function gn(l,t){try{var e=l.onUncaughtError;e(t.value,{componentStack:t.stack})}catch(a){setTimeout(function(){throw a})}}function pd(l,t,e){try{var a=l.onCaughtError;a(e.value,{componentStack:e.stack,errorBoundary:t.tag===1?t.stateNode:null})}catch(u){setTimeout(function(){throw u})}}function si(l,t,e){return e=ie(e),e.tag=3,e.payload={element:null},e.callback=function(){gn(l,t)},e}function Td(l){return l=ie(l),l.tag=3,l}function Ad(l,t,e,a){var u=e.type.getDerivedStateFromError;if(typeof u=="function"){var n=a.value;l.payload=function(){return u(n)},l.callback=function(){pd(t,e,a)}}var c=e.stateNode;c!==null&&typeof c.componentDidCatch=="function"&&(l.callback=function(){pd(t,e,a),typeof u!="function"&&(ge===null?ge=new Set([this]):ge.add(this));var i=a.stack;this.componentDidCatch(a.value,{componentStack:i!==null?i:""})})}function _v(l,t,e,a,u){if(e.flags|=32768,a!==null&&typeof a=="object"&&typeof a.then=="function"){if(t=e.alternate,t!==null&&Wa(t,e,u,!0),e=Et.current,e!==null){switch(e.tag){case 13:return Ht===null?Hi():e.alternate===null&&Sl===0&&(Sl=3),e.flags&=-257,e.flags|=65536,e.lanes=u,a===Xc?e.flags|=16384:(t=e.updateQueue,t===null?e.updateQueue=new Set([a]):t.add(a),Bi(l,a,u)),!1;case 22:return e.flags|=65536,a===Xc?e.flags|=16384:(t=e.updateQueue,t===null?(t={transitions:null,markerInstances:null,retryQueue:new Set([a])},e.updateQueue=t):(e=t.retryQueue,e===null?t.retryQueue=new Set([a]):e.add(a)),Bi(l,a,u)),!1}throw Error(S(435,e.tag))}return Bi(l,a,u),Hi(),!1}if(ul)return t=Et.current,t!==null?((t.flags&65536)===0&&(t.flags|=256),t.flags|=65536,t.lanes=u,a!==Nc&&(l=Error(S(422),{cause:a}),ka(ht(l,e)))):(a!==Nc&&(t=Error(S(423),{cause:a}),ka(ht(t,e))),l=l.current.alternate,l.flags|=65536,u&=-u,l.lanes|=u,a=ht(a,e),u=si(l.stateNode,a,u),xc(l,u),Sl!==4&&(Sl=2)),!1;var n=Error(S(520),{cause:a});if(n=ht(n,e),mu===null?mu=[n]:mu.push(n),Sl!==4&&(Sl=2),t===null)return!0;a=ht(a,e),e=t;do{switch(e.tag){case 3:return e.flags|=65536,l=u&-u,e.lanes|=l,l=si(e.stateNode,a,l),xc(e,l),!1;case 1:if(t=e.type,n=e.stateNode,(e.flags&128)===0&&(typeof t.getDerivedStateFromError=="function"||n!==null&&typeof n.componentDidCatch=="function"&&(ge===null||!ge.has(n))))return e.flags|=65536,u&=-u,e.lanes|=u,u=Td(u),Ad(u,l,e,a),xc(e,u),!1}e=e.return}while(e!==null);return!1}var _d=Error(S(461)),Yl=!1;function Ql(l,t,e,a){t.child=l===null?yd(t,null,e,a):Sa(t,l.child,e,a)}function zd(l,t,e,a,u){e=e.render;var n=t.ref;if("ref"in a){var c={};for(var i in a)i!=="ref"&&(c[i]=a[i])}else c=a;return Ge(t),a=Jc(l,t,e,c,n,u),i=wc(),l!==null&&!Yl?(kc(l,t,u),Wt(l,t,u)):(ul&&i&&Uc(t),t.flags|=1,Ql(l,t,a,u),t.child)}function Od(l,t,e,a,u){if(l===null){var n=e.type;return typeof n=="function"&&!Oc(n)&&n.defaultProps===void 0&&e.compare===null?(t.tag=15,t.type=n,Md(l,t,n,a,u)):(l=Wu(e.type,null,a,t,t.mode,u),l.ref=t.ref,l.return=t,t.child=l)}if(n=l.child,!gi(l,u)){var c=n.memoizedProps;if(e=e.compare,e=e!==null?e:La,e(c,a)&&l.ref===t.ref)return Wt(l,t,u)}return t.flags|=1,l=jt(n,a),l.ref=t.ref,l.return=t,t.child=l}function Md(l,t,e,a,u){if(l!==null){var n=l.memoizedProps;if(La(n,a)&&l.ref===t.ref)if(Yl=!1,t.pendingProps=a=n,gi(l,u))(l.flags&131072)!==0&&(Yl=!0);else return t.lanes=l.lanes,Wt(l,t,u)}return di(l,t,e,a,u)}function Dd(l,t,e){var a=t.pendingProps,u=a.children,n=l!==null?l.memoizedState:null;if(a.mode==="hidden"){if((t.flags&128)!==0){if(a=n!==null?n.baseLanes|e:e,l!==null){for(u=t.child=l.child,n=0;u!==null;)n=n|u.lanes|u.childLanes,u=u.sibling;t.childLanes=n&~a}else t.childLanes=0,t.child=null;return Ud(l,t,a,e)}if((e&536870912)!==0)t.memoizedState={baseLanes:0,cachePool:null},l!==null&&ln(t,n!==null?n.cachePool:null),n!==null?Ms(t,n):Vc(),md(t);else return t.lanes=t.childLanes=536870912,Ud(l,t,n!==null?n.baseLanes|e:e,e)}else n!==null?(ln(t,n.cachePool),Ms(t,n),oe(),t.memoizedState=null):(l!==null&&ln(t,null),Vc(),oe());return Ql(l,t,u,e),t.child}function Ud(l,t,e,a){var u=Gc();return u=u===null?null:{parent:Dl._currentValue,pool:u},t.memoizedState={baseLanes:e,cachePool:u},l!==null&&ln(t,null),Vc(),md(t),l!==null&&Wa(l,t,a,!0),null}function Sn(l,t){var e=t.ref;if(e===null)l!==null&&l.ref!==null&&(t.flags|=4194816);else{if(typeof e!="function"&&typeof e!="object")throw Error(S(284));(l===null||l.ref!==e)&&(t.flags|=4194816)}}function di(l,t,e,a,u){return Ge(t),e=Jc(l,t,e,a,void 0,u),a=wc(),l!==null&&!Yl?(kc(l,t,u),Wt(l,t,u)):(ul&&a&&Uc(t),t.flags|=1,Ql(l,t,e,u),t.child)}function Rd(l,t,e,a,u,n){return Ge(t),t.updateQueue=null,e=Us(t,a,e,u),Ds(l),a=wc(),l!==null&&!Yl?(kc(l,t,n),Wt(l,t,n)):(ul&&a&&Uc(t),t.flags|=1,Ql(l,t,e,n),t.child)}function Nd(l,t,e,a,u){if(Ge(t),t.stateNode===null){var n=fa,c=e.contextType;typeof c=="object"&&c!==null&&(n=Jl(c)),n=new e(a,n),t.memoizedState=n.state!==null&&n.state!==void 0?n.state:null,n.updater=fi,t.stateNode=n,n._reactInternals=t,n=t.stateNode,n.props=a,n.state=t.memoizedState,n.refs={},Qc(t),c=e.contextType,n.context=typeof c=="object"&&c!==null?Jl(c):fa,n.state=t.memoizedState,c=e.getDerivedStateFromProps,typeof c=="function"&&(ii(t,e,c,a),n.state=t.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof n.getSnapshotBeforeUpdate=="function"||typeof n.UNSAFE_componentWillMount!="function"&&typeof n.componentWillMount!="function"||(c=n.state,typeof n.componentWillMount=="function"&&n.componentWillMount(),typeof n.UNSAFE_componentWillMount=="function"&&n.UNSAFE_componentWillMount(),c!==n.state&&fi.enqueueReplaceState(n,n.state,null),eu(t,a,n,u),tu(),n.state=t.memoizedState),typeof n.componentDidMount=="function"&&(t.flags|=4194308),a=!0}else if(l===null){n=t.stateNode;var i=t.memoizedProps,f=Ze(e,i);n.props=f;var v=n.context,E=e.contextType;c=fa,typeof E=="object"&&E!==null&&(c=Jl(E));var T=e.getDerivedStateFromProps;E=typeof T=="function"||typeof n.getSnapshotBeforeUpdate=="function",i=t.pendingProps!==i,E||typeof n.UNSAFE_componentWillReceiveProps!="function"&&typeof n.componentWillReceiveProps!="function"||(i||v!==c)&&gd(t,n,a,c),ce=!1;var h=t.memoizedState;n.state=h,eu(t,a,n,u),tu(),v=t.memoizedState,i||h!==v||ce?(typeof T=="function"&&(ii(t,e,T,a),v=t.memoizedState),(f=ce||hd(t,e,f,a,h,v,c))?(E||typeof n.UNSAFE_componentWillMount!="function"&&typeof n.componentWillMount!="function"||(typeof n.componentWillMount=="function"&&n.componentWillMount(),typeof n.UNSAFE_componentWillMount=="function"&&n.UNSAFE_componentWillMount()),typeof n.componentDidMount=="function"&&(t.flags|=4194308)):(typeof n.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=a,t.memoizedState=v),n.props=a,n.state=v,n.context=c,a=f):(typeof n.componentDidMount=="function"&&(t.flags|=4194308),a=!1)}else{n=t.stateNode,Zc(l,t),c=t.memoizedProps,E=Ze(e,c),n.props=E,T=t.pendingProps,h=n.context,v=e.contextType,f=fa,typeof v=="object"&&v!==null&&(f=Jl(v)),i=e.getDerivedStateFromProps,(v=typeof i=="function"||typeof n.getSnapshotBeforeUpdate=="function")||typeof n.UNSAFE_componentWillReceiveProps!="function"&&typeof n.componentWillReceiveProps!="function"||(c!==T||h!==f)&&gd(t,n,a,f),ce=!1,h=t.memoizedState,n.state=h,eu(t,a,n,u),tu();var g=t.memoizedState;c!==T||h!==g||ce||l!==null&&l.dependencies!==null&&Iu(l.dependencies)?(typeof i=="function"&&(ii(t,e,i,a),g=t.memoizedState),(E=ce||hd(t,e,E,a,h,g,f)||l!==null&&l.dependencies!==null&&Iu(l.dependencies))?(v||typeof n.UNSAFE_componentWillUpdate!="function"&&typeof n.componentWillUpdate!="function"||(typeof n.componentWillUpdate=="function"&&n.componentWillUpdate(a,g,f),typeof n.UNSAFE_componentWillUpdate=="function"&&n.UNSAFE_componentWillUpdate(a,g,f)),typeof n.componentDidUpdate=="function"&&(t.flags|=4),typeof n.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof n.componentDidUpdate!="function"||c===l.memoizedProps&&h===l.memoizedState||(t.flags|=4),typeof n.getSnapshotBeforeUpdate!="function"||c===l.memoizedProps&&h===l.memoizedState||(t.flags|=1024),t.memoizedProps=a,t.memoizedState=g),n.props=a,n.state=g,n.context=f,a=E):(typeof n.componentDidUpdate!="function"||c===l.memoizedProps&&h===l.memoizedState||(t.flags|=4),typeof n.getSnapshotBeforeUpdate!="function"||c===l.memoizedProps&&h===l.memoizedState||(t.flags|=1024),a=!1)}return n=a,Sn(l,t),a=(t.flags&128)!==0,n||a?(n=t.stateNode,e=a&&typeof e.getDerivedStateFromError!="function"?null:n.render(),t.flags|=1,l!==null&&a?(t.child=Sa(t,l.child,null,u),t.child=Sa(t,null,e,u)):Ql(l,t,e,u),t.memoizedState=n.state,l=t.child):l=Wt(l,t,u),l}function qd(l,t,e,a){return wa(),t.flags|=256,Ql(l,t,e,a),t.child}var oi={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function ri(l){return{baseLanes:l,cachePool:bs()}}function vi(l,t,e){return l=l!==null?l.childLanes&~e:0,t&&(l|=pt),l}function Hd(l,t,e){var a=t.pendingProps,u=!1,n=(t.flags&128)!==0,c;if((c=n)||(c=l!==null&&l.memoizedState===null?!1:(Ul.current&2)!==0),c&&(u=!0,t.flags&=-129),c=(t.flags&32)!==0,t.flags&=-33,l===null){if(ul){if(u?de(t):oe(),ul){var i=gl,f;if(f=i){l:{for(f=i,i=qt;f.nodeType!==8;){if(!i){i=null;break l}if(f=Mt(f.nextSibling),f===null){i=null;break l}}i=f}i!==null?(t.memoizedState={dehydrated:i,treeContext:qe!==null?{id:Vt,overflow:Lt}:null,retryLane:536870912,hydrationErrors:null},f=it(18,null,null,0),f.stateNode=i,f.return=t,t.child=f,Il=t,gl=null,f=!0):f=!1}f||Be(t)}if(i=t.memoizedState,i!==null&&(i=i.dehydrated,i!==null))return $i(i)?t.lanes=32:t.lanes=536870912,null;kt(t)}return i=a.children,a=a.fallback,u?(oe(),u=t.mode,i=bn({mode:"hidden",children:i},u),a=Ne(a,u,e,null),i.return=t,a.return=t,i.sibling=a,t.child=i,u=t.child,u.memoizedState=ri(e),u.childLanes=vi(l,c,e),t.memoizedState=oi,a):(de(t),yi(t,i))}if(f=l.memoizedState,f!==null&&(i=f.dehydrated,i!==null)){if(n)t.flags&256?(de(t),t.flags&=-257,t=mi(l,t,e)):t.memoizedState!==null?(oe(),t.child=l.child,t.flags|=128,t=null):(oe(),u=a.fallback,i=t.mode,a=bn({mode:"visible",children:a.children},i),u=Ne(u,i,e,null),u.flags|=2,a.return=t,u.return=t,a.sibling=u,t.child=a,Sa(t,l.child,null,e),a=t.child,a.memoizedState=ri(e),a.childLanes=vi(l,c,e),t.memoizedState=oi,t=u);else if(de(t),$i(i)){if(c=i.nextSibling&&i.nextSibling.dataset,c)var v=c.dgst;c=v,a=Error(S(419)),a.stack="",a.digest=c,ka({value:a,source:null,stack:null}),t=mi(l,t,e)}else if(Yl||Wa(l,t,e,!1),c=(e&l.childLanes)!==0,Yl||c){if(c=yl,c!==null&&(a=e&-e,a=(a&42)!==0?1:Fn(a),a=(a&(c.suspendedLanes|e))!==0?0:a,a!==0&&a!==f.retryLane))throw f.retryLane=a,ia(l,a),rt(c,l,a),_d;i.data==="$?"||Hi(),t=mi(l,t,e)}else i.data==="$?"?(t.flags|=192,t.child=l.child,t=null):(l=f.treeContext,gl=Mt(i.nextSibling),Il=t,ul=!0,Ye=null,qt=!1,l!==null&&(St[bt++]=Vt,St[bt++]=Lt,St[bt++]=qe,Vt=l.id,Lt=l.overflow,qe=t),t=yi(t,a.children),t.flags|=4096);return t}return u?(oe(),u=a.fallback,i=t.mode,f=l.child,v=f.sibling,a=jt(f,{mode:"hidden",children:a.children}),a.subtreeFlags=f.subtreeFlags&65011712,v!==null?u=jt(v,u):(u=Ne(u,i,e,null),u.flags|=2),u.return=t,a.return=t,a.sibling=u,t.child=a,a=u,u=t.child,i=l.child.memoizedState,i===null?i=ri(e):(f=i.cachePool,f!==null?(v=Dl._currentValue,f=f.parent!==v?{parent:v,pool:v}:f):f=bs(),i={baseLanes:i.baseLanes|e,cachePool:f}),u.memoizedState=i,u.childLanes=vi(l,c,e),t.memoizedState=oi,a):(de(t),e=l.child,l=e.sibling,e=jt(e,{mode:"visible",children:a.children}),e.return=t,e.sibling=null,l!==null&&(c=t.deletions,c===null?(t.deletions=[l],t.flags|=16):c.push(l)),t.child=e,t.memoizedState=null,e)}function yi(l,t){return t=bn({mode:"visible",children:t},l.mode),t.return=l,l.child=t}function bn(l,t){return l=it(22,l,null,t),l.lanes=0,l.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null},l}function mi(l,t,e){return Sa(t,l.child,null,e),l=yi(t,t.pendingProps.children),l.flags|=2,t.memoizedState=null,l}function Yd(l,t,e){l.lanes|=t;var a=l.alternate;a!==null&&(a.lanes|=t),Hc(l.return,t,e)}function hi(l,t,e,a,u){var n=l.memoizedState;n===null?l.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:a,tail:e,tailMode:u}:(n.isBackwards=t,n.rendering=null,n.renderingStartTime=0,n.last=a,n.tail=e,n.tailMode=u)}function Bd(l,t,e){var a=t.pendingProps,u=a.revealOrder,n=a.tail;if(Ql(l,t,a.children,e),a=Ul.current,(a&2)!==0)a=a&1|2,t.flags|=128;else{if(l!==null&&(l.flags&128)!==0)l:for(l=t.child;l!==null;){if(l.tag===13)l.memoizedState!==null&&Yd(l,e,t);else if(l.tag===19)Yd(l,e,t);else if(l.child!==null){l.child.return=l,l=l.child;continue}if(l===t)break l;for(;l.sibling===null;){if(l.return===null||l.return===t)break l;l=l.return}l.sibling.return=l.return,l=l.sibling}a&=1}switch(M(Ul,a),u){case"forwards":for(e=t.child,u=null;e!==null;)l=e.alternate,l!==null&&mn(l)===null&&(u=e),e=e.sibling;e=u,e===null?(u=t.child,t.child=null):(u=e.sibling,e.sibling=null),hi(t,!1,u,e,n);break;case"backwards":for(e=null,u=t.child,t.child=null;u!==null;){if(l=u.alternate,l!==null&&mn(l)===null){t.child=u;break}l=u.sibling,u.sibling=e,e=u,u=l}hi(t,!0,e,null,n);break;case"together":hi(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function Wt(l,t,e){if(l!==null&&(t.dependencies=l.dependencies),he|=t.lanes,(e&t.childLanes)===0)if(l!==null){if(Wa(l,t,e,!1),(e&t.childLanes)===0)return null}else return null;if(l!==null&&t.child!==l.child)throw Error(S(153));if(t.child!==null){for(l=t.child,e=jt(l,l.pendingProps),t.child=e,e.return=t;l.sibling!==null;)l=l.sibling,e=e.sibling=jt(l,l.pendingProps),e.return=t;e.sibling=null}return t.child}function gi(l,t){return(l.lanes&t)!==0?!0:(l=l.dependencies,!!(l!==null&&Iu(l)))}function zv(l,t,e){switch(t.tag){case 3:vl(t,t.stateNode.containerInfo),ne(t,Dl,l.memoizedState.cache),wa();break;case 27:case 5:Qt(t);break;case 4:vl(t,t.stateNode.containerInfo);break;case 10:ne(t,t.type,t.memoizedProps.value);break;case 13:var a=t.memoizedState;if(a!==null)return a.dehydrated!==null?(de(t),t.flags|=128,null):(e&t.child.childLanes)!==0?Hd(l,t,e):(de(t),l=Wt(l,t,e),l!==null?l.sibling:null);de(t);break;case 19:var u=(l.flags&128)!==0;if(a=(e&t.childLanes)!==0,a||(Wa(l,t,e,!1),a=(e&t.childLanes)!==0),u){if(a)return Bd(l,t,e);t.flags|=128}if(u=t.memoizedState,u!==null&&(u.rendering=null,u.tail=null,u.lastEffect=null),M(Ul,Ul.current),a)break;return null;case 22:case 23:return t.lanes=0,Dd(l,t,e);case 24:ne(t,Dl,l.memoizedState.cache)}return Wt(l,t,e)}function Cd(l,t,e){if(l!==null)if(l.memoizedProps!==t.pendingProps)Yl=!0;else{if(!gi(l,e)&&(t.flags&128)===0)return Yl=!1,zv(l,t,e);Yl=(l.flags&131072)!==0}else Yl=!1,ul&&(t.flags&1048576)!==0&&rs(t,Fu,t.index);switch(t.lanes=0,t.tag){case 16:l:{l=t.pendingProps;var a=t.elementType,u=a._init;if(a=u(a._payload),t.type=a,typeof a=="function")Oc(a)?(l=Ze(a,l),t.tag=1,t=Nd(null,t,a,l,e)):(t.tag=0,t=di(null,t,a,l,e));else{if(a!=null){if(u=a.$$typeof,u===Nl){t.tag=11,t=zd(null,t,a,l,e);break l}else if(u===Vl){t.tag=14,t=Od(null,t,a,l,e);break l}}throw t=_t(a)||a,Error(S(306,t,""))}}return t;case 0:return di(l,t,t.type,t.pendingProps,e);case 1:return a=t.type,u=Ze(a,t.pendingProps),Nd(l,t,a,u,e);case 3:l:{if(vl(t,t.stateNode.containerInfo),l===null)throw Error(S(387));a=t.pendingProps;var n=t.memoizedState;u=n.element,Zc(l,t),eu(t,a,null,e);var c=t.memoizedState;if(a=c.cache,ne(t,Dl,a),a!==n.cache&&Yc(t,[Dl],e,!0),tu(),a=c.element,n.isDehydrated)if(n={element:a,isDehydrated:!1,cache:c.cache},t.updateQueue.baseState=n,t.memoizedState=n,t.flags&256){t=qd(l,t,a,e);break l}else if(a!==u){u=ht(Error(S(424)),t),ka(u),t=qd(l,t,a,e);break l}else for(l=t.stateNode.containerInfo,l.nodeType===9?l=l.body:l=l.nodeName==="HTML"?l.ownerDocument.body:l,gl=Mt(l.firstChild),Il=t,ul=!0,Ye=null,qt=!0,e=yd(t,null,a,e),t.child=e;e;)e.flags=e.flags&-3|4096,e=e.sibling;else{if(wa(),a===u){t=Wt(l,t,e);break l}Ql(l,t,a,e)}t=t.child}return t;case 26:return Sn(l,t),l===null?(e=xo(t.type,null,t.pendingProps,null))?t.memoizedState=e:ul||(e=t.type,l=t.pendingProps,a=Hn(Q.current).createElement(e),a[Kl]=t,a[Pl]=l,xl(a,e,l),Hl(a),t.stateNode=a):t.memoizedState=xo(t.type,l.memoizedProps,t.pendingProps,l.memoizedState),null;case 27:return Qt(t),l===null&&ul&&(a=t.stateNode=Xo(t.type,t.pendingProps,Q.current),Il=t,qt=!0,u=gl,Ee(t.type)?(Fi=u,gl=Mt(a.firstChild)):gl=u),Ql(l,t,t.pendingProps.children,e),Sn(l,t),l===null&&(t.flags|=4194304),t.child;case 5:return l===null&&ul&&((u=a=gl)&&(a=Pv(a,t.type,t.pendingProps,qt),a!==null?(t.stateNode=a,Il=t,gl=Mt(a.firstChild),qt=!1,u=!0):u=!1),u||Be(t)),Qt(t),u=t.type,n=t.pendingProps,c=l!==null?l.memoizedProps:null,a=n.children,wi(u,n)?a=null:c!==null&&wi(u,c)&&(t.flags|=32),t.memoizedState!==null&&(u=Jc(l,t,gv,null,null,e),_u._currentValue=u),Sn(l,t),Ql(l,t,a,e),t.child;case 6:return l===null&&ul&&((l=e=gl)&&(e=l0(e,t.pendingProps,qt),e!==null?(t.stateNode=e,Il=t,gl=null,l=!0):l=!1),l||Be(t)),null;case 13:return Hd(l,t,e);case 4:return vl(t,t.stateNode.containerInfo),a=t.pendingProps,l===null?t.child=Sa(t,null,a,e):Ql(l,t,a,e),t.child;case 11:return zd(l,t,t.type,t.pendingProps,e);case 7:return Ql(l,t,t.pendingProps,e),t.child;case 8:return Ql(l,t,t.pendingProps.children,e),t.child;case 12:return Ql(l,t,t.pendingProps.children,e),t.child;case 10:return a=t.pendingProps,ne(t,t.type,a.value),Ql(l,t,a.children,e),t.child;case 9:return u=t.type._context,a=t.pendingProps.children,Ge(t),u=Jl(u),a=a(u),t.flags|=1,Ql(l,t,a,e),t.child;case 14:return Od(l,t,t.type,t.pendingProps,e);case 15:return Md(l,t,t.type,t.pendingProps,e);case 19:return Bd(l,t,e);case 31:return a=t.pendingProps,e=t.mode,a={mode:a.mode,children:a.children},l===null?(e=bn(a,e),e.ref=t.ref,t.child=e,e.return=t,t=e):(e=jt(l.child,a),e.ref=t.ref,t.child=e,e.return=t,t=e),t;case 22:return Dd(l,t,e);case 24:return Ge(t),a=Jl(Dl),l===null?(u=Gc(),u===null&&(u=yl,n=Bc(),u.pooledCache=n,n.refCount++,n!==null&&(u.pooledCacheLanes|=e),u=n),t.memoizedState={parent:a,cache:u},Qc(t),ne(t,Dl,u)):((l.lanes&e)!==0&&(Zc(l,t),eu(t,null,null,e),tu()),u=l.memoizedState,n=t.memoizedState,u.parent!==a?(u={parent:a,cache:a},t.memoizedState=u,t.lanes===0&&(t.memoizedState=t.updateQueue.baseState=u),ne(t,Dl,a)):(a=n.cache,ne(t,Dl,a),a!==u.cache&&Yc(t,[Dl],e,!0))),Ql(l,t,t.pendingProps.children,e),t.child;case 29:throw t.pendingProps}throw Error(S(156,t.tag))}function $t(l){l.flags|=4}function Gd(l,t){if(t.type!=="stylesheet"||(t.state.loading&4)!==0)l.flags&=-16777217;else if(l.flags|=16777216,!Jo(t)){if(t=Et.current,t!==null&&((W&4194048)===W?Ht!==null:(W&62914560)!==W&&(W&536870912)===0||t!==Ht))throw Pa=Xc,Es;l.flags|=8192}}function En(l,t){t!==null&&(l.flags|=4),l.flags&16384&&(t=l.tag!==22?mf():536870912,l.lanes|=t,Ta|=t)}function su(l,t){if(!ul)switch(l.tailMode){case"hidden":t=l.tail;for(var e=null;t!==null;)t.alternate!==null&&(e=t),t=t.sibling;e===null?l.tail=null:e.sibling=null;break;case"collapsed":e=l.tail;for(var a=null;e!==null;)e.alternate!==null&&(a=e),e=e.sibling;a===null?t||l.tail===null?l.tail=null:l.tail.sibling=null:a.sibling=null}}function hl(l){var t=l.alternate!==null&&l.alternate.child===l.child,e=0,a=0;if(t)for(var u=l.child;u!==null;)e|=u.lanes|u.childLanes,a|=u.subtreeFlags&65011712,a|=u.flags&65011712,u.return=l,u=u.sibling;else for(u=l.child;u!==null;)e|=u.lanes|u.childLanes,a|=u.subtreeFlags,a|=u.flags,u.return=l,u=u.sibling;return l.subtreeFlags|=a,l.childLanes=e,t}function Ov(l,t,e){var a=t.pendingProps;switch(Rc(t),t.tag){case 31:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return hl(t),null;case 1:return hl(t),null;case 3:return e=t.stateNode,a=null,l!==null&&(a=l.memoizedState.cache),t.memoizedState.cache!==a&&(t.flags|=2048),Jt(Dl),Ut(),e.pendingContext&&(e.context=e.pendingContext,e.pendingContext=null),(l===null||l.child===null)&&(Ja(t)?$t(t):l===null||l.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,ms())),hl(t),null;case 26:return e=t.memoizedState,l===null?($t(t),e!==null?(hl(t),Gd(t,e)):(hl(t),t.flags&=-16777217)):e?e!==l.memoizedState?($t(t),hl(t),Gd(t,e)):(hl(t),t.flags&=-16777217):(l.memoizedProps!==a&&$t(t),hl(t),t.flags&=-16777217),null;case 27:te(t),e=Q.current;var u=t.type;if(l!==null&&t.stateNode!=null)l.memoizedProps!==a&&$t(t);else{if(!a){if(t.stateNode===null)throw Error(S(166));return hl(t),null}l=B.current,Ja(t)?vs(t):(l=Xo(u,a,e),t.stateNode=l,$t(t))}return hl(t),null;case 5:if(te(t),e=t.type,l!==null&&t.stateNode!=null)l.memoizedProps!==a&&$t(t);else{if(!a){if(t.stateNode===null)throw Error(S(166));return hl(t),null}if(l=B.current,Ja(t))vs(t);else{switch(u=Hn(Q.current),l){case 1:l=u.createElementNS("http://www.w3.org/2000/svg",e);break;case 2:l=u.createElementNS("http://www.w3.org/1998/Math/MathML",e);break;default:switch(e){case"svg":l=u.createElementNS("http://www.w3.org/2000/svg",e);break;case"math":l=u.createElementNS("http://www.w3.org/1998/Math/MathML",e);break;case"script":l=u.createElement("div"),l.innerHTML="