Author SHA1 Message Date
omar 296b65f96a fix(native): apply icon view mode to sidebar activities
- Size connection and bookmark glyphs from the saved mode without changing row order or ownership.
- Cover expanded and collapsed layouts, window clamping and reopen in the four Windows locale/theme combinations.
2026-11-28 17:14:19 +03:00
omar 5055f0f174 fix(native): report observed Windows window state
- Project native maximized and fullscreen state to the owning Slint attachment.
- Verify real owned-window transitions, replacement isolation and disposal.
2026-11-28 17:02:56 +03:00
omar 6b10e0b174 fix(native): keep complex Mermaid diagrams manual
- Apply the existing complexity cutoff before automatic rendering; keep one Load or Retry control per diagram.
- Fit rendered graphs to their row and verify the preference, restart, and worker cancellation on Windows.
2026-11-28 16:47:36 +03:00
omar 2f24754d8b test(native): verify inline image auto-download preference
- Count authorized server-image requests and check painted PNG pixels across manual load, auto-load, and reopen.
- Keep ordinary web images and unsupported storage out of the fixture transport.
2026-11-28 16:44:20 +03:00
omar ba589e3a15 test(native): verify rich composer input and refusal
- Drive mounted Slint text input through preedit, commit, formatting, undo and a disconnected-core send refusal.
- Record preference coverage and the limits of the broader editor contract.
2026-11-28 16:29:49 +03:00
omar 07ba63560b fix(native): keep the dynamic chat toolbar with a draft
- Use the full draft for Dynamic visibility and preserve composer focus on toolbar pointer actions.
- Verify all three rendered modes, draft and selection retention, reopen behavior, and narrow chat regressions.
2026-11-28 16:29:05 +03:00
omar d436d87f71 fix(native): preserve chat selection across style changes
- Keep composer text and selection intact through native edit notifications and settings navigation.
- Keep timeline selection independent of detailed-only headers; verify the compact and detailed layouts and preference persistence in Slint.
2026-11-28 16:15:21 +03:00
omar a900128545 fix(native): keep shortcut completion under the recorder lock
- Serialize preview, completion and cancellation against the current recorder target.
- Verify real Windows release and restoration through Slint finish, cancel and focus loss.
2026-11-28 16:07:46 +03:00
omar 059b0c906d fix(native): show binding-specific global registration results
- Show the acknowledged backend and refusal on the owning binding row.
- Ignore older bind and rebound receipts after reconfiguration; verify a real Windows conflict and recovery without key input.
2026-11-28 15:46:09 +03:00
omar bd7b3643c2 test(native): verify Windows exact shortcut combinations
- Verify both checkbox states survive restart and agree with local matching.
- Probe actual Windows registration ownership and cleanup without sending key input.
2026-11-28 15:43:56 +03:00
omar 0eda270473 fix(native): resolve theme variants before saving selections
- Keep the current choice and appearance when selecting an unreadable variant or when the preference write fails.
- Verify rendered stock modes and local theme refresh and reopens on Windows.
2026-11-28 15:37:07 +03:00
omar b3a4ac854f fix(native): retain all shortcut conflict warnings
- Leave a missing whisper target unselected instead of showing an unrelated list.
- Verify the real editor save across restart and confirm Windows only attempts eligible bindings.
2026-11-28 15:35:10 +03:00
omar 7db69358fd feat(native): show acknowledged shortcut registration status
- Name the active shortcut profile independently of the profile being inspected.
- Refresh Slint registration counts from the current backend receipt and verify acceptance, refusal, and release on Windows.
2026-11-28 15:25:49 +03:00
omar 3e750fe0b4 docs(native): map the local contacts and public badge contract
- Reuse the integrated Windows receipts for local contact editing, roster presence, UID highlighting, and cached badge artwork.
2026-11-28 15:17:55 +03:00
omar 96b6f2aaef feat(native): show public badges in the participant tree
- Retry missing artwork when Show User Badges is re-enabled without discarding successful loads or bypassing network cooldowns.
- Record eight passing focused Windows tests and link the native setPrefs verification.
2026-11-28 15:15:21 +03:00
omar 22a4f3701e test: verify atomic native preference writes
- Require a visible error and retained selection after a failed Slint Display Size save.
- Cover mixed rejected patches and the typed recording destination boundary without opening a picker or secret store.
2026-11-28 15:00:46 +03:00
omar 1883ab95d5 Render public badge showcases in participant details
Resolve announced UUIDs against the public catalog and pass bounded, resource-free raster artwork to Slint.
Verify accessible metadata, painted artwork and unavailable states using a disposable catalog and cache.
2026-11-28 14:34:25 +03:00
omar 001ad6c3d0 test: verify native tab events across reconnect
- Extend the existing loopback Slint text smoke to cover detach, reconnect, and one delivery per conversation.
- Verify injected stale text is rejected separately from live server delivery.
2026-11-28 14:32:19 +03:00
omar 1fe5baba05 test: verify scoped native tab requests
- Run the existing two-tab Client Info smoke against the disposable loopback fixture.
- Verify unknown commands and malformed arguments over real stdio and record typed profile and stale-response evidence.
2026-11-28 14:19:14 +03:00
omar 4ae84566e2 Record isolated Linux Secret Service preflight
Record the verified private D-Bus setup and the missing GNOME Keyring provider without changing credential behavior.
2026-11-28 14:15:00 +03:00
omar 0ee62be668 feat: show scoped bookmark password status in Slint
- Display metadata-only status per password purpose and identify the bookmark/address in explicit password dialogs.
- Check Windows DPAPI save, clear, reveal, and stale-target rejection through the normal Slint workflow.
2026-11-28 14:11:26 +03:00
omar 6e5b7c9bde Cover bookmark credential backend refusals
Verify a simulated unavailable backend preserves saved bindings and migration markers, and distinguish actual unreadable DPAPI data from metadata availability.
2026-11-28 14:08:11 +03:00
omar b8b13bbd75 test: verify protected bookmark reconnect on beta14
- Exercise DPAPI-backed server and channel passwords from the normal Slint bookmark UI.
- Run isolated password controls, cancellation and stale lookup rejection against the disposable beta14 fixture.
2026-11-28 14:02:25 +03:00
omar fb5ce198f0 Merge commit '02f4001820' into work/integration-verified 2026-11-28 10:28:04 +03:00
omar 02f4001820 fix: validate and verify native bookmark schema fields
- Validate bookmark editor text before submission and reject noncanonical legacy password encodings.
- Verify disposable Windows saves, stale targets, actual DPAPI and loopback startup behavior.
2026-11-28 10:27:19 +03:00
omar c040d1a87a Integrate verified native identity request guards
Apply only f9cdcdd453 onto 87cfa59252 and record the focused integrated identity smoke.
2026-11-28 10:07:02 +03:00
omar 87cfa59252 test: verify live beta14 channel banner fetch
Reject zero channel IDs at the fetch_banner command boundary. Verify exact classic download bytes and rendered Slint row pixels, permission refusal, missing-file fallback and stale-reference rejection on disposable loopback beta14.
2026-11-28 10:04:25 +03:00
omar b370474999 Integrate verified desktop channel banner rendering
Integrate only 302ba80958 onto c4fe77d128, retaining adjacent tree, host editor, and capture behavior.
Record the seven focused Windows checks and the fixture-fed raster evidence in the integration handoff.
2026-11-28 09:50:35 +03:00
omar c4fe77d128 docs: record integrated host button checks 2026-11-28 09:39:11 +03:00
omar e94e6c770f Merge commit '8a5afa2814' into work/integration-verified
# Conflicts:
#	native/src/smoke/tabs.rs
2026-11-28 09:36:41 +03:00
omar 8a5afa2814 test: cover server host button edits on beta14
Verify length rejection, cancellation, independent and combined field saves, and exact restoration with a second guest on a private fixture.
2026-11-28 09:34:50 +03:00
omar 6bb621f895 docs: record integrated country flag verification 2026-11-28 09:27:07 +03:00
omar 43fab1649a Merge commit '09768a2113' into work/integration-verified 2026-11-28 09:24:08 +03:00
omar 4a64f41858 docs: record integrated host banner verification 2026-11-28 09:22:53 +03:00
omar 09768a2113 feat: render bundled country flags in the desktop tree
- Use pinned MIT flag-icons 7.3.2 assets without an emoji or unknown-code placeholder.
- Verify raster output, preference persistence and save refusal across the Windows appearance matrix.
2026-11-28 09:21:07 +03:00
omar 655e820756 Merge commit 'a31367cc51' into work/integration-verified
# Conflicts:
#	native/src/smoke/tabs.rs
2026-11-28 09:16:54 +03:00
omar 5384139230 Record stream setup integration verification 2026-11-28 09:13:34 +03:00
omar a31367cc51 test: cover server host banner edits on beta14
Verify input bounds, cancel, independent and combined changes, and exact restoration through the Slint editor and a second guest. Record fixture-only URL values and the focused live receipt.
2026-11-28 09:12:00 +03:00
omar eb27e9c896 Merge commit '41d0a387e1493dedaaa1f5ed55d32ef2bab8c374' into work/integration-verified 2026-11-28 09:10:38 +03:00
omar 41d0a387e1 Reject mismatched submissions without closing capture prompts
Validate the target and operation before removing a live capture prompt.
Verify the prompt survives both mismatches using the runtime command queue and decouple the disposable profile from Cargo output.
2026-11-28 09:07:29 +03:00
omar f145593741 Revoke cancelled capture selections in Slint
Bind chooser and preview prompts to the selected flow; ignore retired submissions and clear cancelled selections.
Exercise visible Slint controls in two isolated sessions with a catalog-only adapter and no media acquisition.
2026-11-28 09:03:19 +03:00
omar 4bfdc5cf44 docs: record integrated channel background verification 2026-11-28 08:42:37 +03:00
omar 9ba82dd229 Merge commit '5b55d159f7' into work/integration-verified 2026-11-28 08:40:18 +03:00
omar 5b55d159f7 Honor the channel background preference in the desktop tree
Gate the default fills without changing the stock gradients or row outlines.
Verify rendered pixels, independent rows, profile reopening, and rejected preference writes.
2026-11-28 08:38:15 +03:00
omar 0e7d1c8184 docs: map native channel CRUD verification
- Record prior live UI evidence and the exact integrated beta14 reconnect receipt.
- Separate delayed successful completion after reconnect from network acknowledgement timing and offline refusals.
2026-11-28 08:33:45 +03:00
omar 802bd30273 Merge commit 'ec580edc90' into work/integration-verified 2026-11-28 08:29:21 +03:00
omar ec580edc90 test: isolate acknowledged channel edits across live reconnect
Hold only successful Channel Edit completion delivery in the Windows test harness. Verify the first edit and replacement independently on disposable beta14, then assert old delivery leaves the busy replacement presentation unchanged.
Share the private fixture runner across the channel edit and bandwidth smokes, and record the live receipt.
2026-11-28 08:27:03 +03:00
omar 1d9f7d24db docs: record integrated ignored-user UI verification
- Move the rendered ignore evidence to docs/evidence.
- Record the reviewed cutoff and exact integration test result in the handoff.
2026-11-28 08:16:34 +03:00
omar 946fc93734 Merge commit 'a8157ab58d' into work/integration-verified 2026-11-28 08:14:29 +03:00
omar a8157ab58d test(chat): cover rendered ignore controls after restart 2026-11-28 08:13:10 +03:00
omar 89a9be03e8 test: reconcile restart-only language integration
- Import the locale used by the stream capture identity regressions locally.
- Exercise recent server events in both startup languages without expecting a saved language to retranslate the running app.
2026-11-28 08:06:51 +03:00
omar f9ae872168 Merge commit '8fb4356c91' into work/integration-verified 2026-11-28 08:02:09 +03:00
omar 8fb4356c91 Defer language changes until restart and preserve the saved choice
Save first, show the native restart confirmation only on success, and dispatch the existing relaunch route only on confirmation.
Keep the startup catalog active until the next launch and verify cancel, policy-denied confirmation, failed save, and separate-process restore.
2026-11-28 08:00:29 +03:00
omar 7765227d14 Merge commit '9c242d790f' into work/integration-verified 2026-11-28 08:00:25 +03:00
omar e95778946f test: recover server host message regression
- Restore the existing HostMessage fixture scenario and pre-integration evidence without changing capacity or quota coverage.
- Leave the private fixture and its configuration outside the commit.
2026-11-28 07:56:22 +03:00
omar 9c242d790f test: cover server transfer bandwidth edits on beta14
Verify isolated download and upload changes, paired edits, and exact restoration through Slint and a separate guest. Check in the loopback fixture runner and snapshot receipt.
2026-11-28 07:55:34 +03:00
omar ba1c1c5f53 Apply language changes without a restart prompt
Keep the controlled selector and the live catalog tied to the persisted preference.
Exercise rendered language choices, a fresh process, and refused writes in an isolated desktop profile.
2026-11-28 07:48:56 +03:00
omar ce440ae0da docs: record verified desktop integration handoff 2026-11-28 07:45:29 +03:00
omar 16ac392ab2 Merge commit '43d13d0436' into work/integration-verified 2026-11-28 07:43:31 +03:00
omar e8d8f7ca10 Merge commit '6ab51d5fb' into work/integration-verified 2026-11-28 07:43:31 +03:00
omar 272c5810bb Merge commit 'c7ccea544c' into work/integration-verified 2026-11-28 07:43:31 +03:00
omar 6d428354cb Merge commit 'b1b3496a38' into work/integration-verified 2026-11-28 07:43:31 +03:00
omar 7c798210c8 Merge commit '92aef5d4' into work/integration-verified 2026-11-28 07:43:25 +03:00
omar 43d13d0436 Apply Display Size to the collapsed desktop sidebar
Keep persisted collapse state independent of the selected scale.
Verify real Slint selection, footer geometry, atomic write refusal and two runtime restarts in all four stock locale/theme combinations.
2026-11-28 07:41:29 +03:00
omar b1b3496a38 test: cover server transfer quota edits on beta14
Seed finite download and upload baselines on the disposable fixture, then verify Slint validation, cancellation, save and exact restoration from two guest sessions.
2026-11-28 07:39:51 +03:00
omar 92aef5d4e3 test(core): verify transfer quota wire precision 2026-11-28 07:33:36 +03:00
omar c7ccea544c test(chat): retain ignored message regressions 2026-11-28 07:30:49 +03:00
omar 978cb3283c test: cover server capacity edits on beta14
Exercise both capacity inputs through the Slint editor and independently read cancellation, save and restoration from a second guest.
2026-11-28 07:29:32 +03:00
omar ed7dfa5a5c test(chat): cover ignored users across restart 2026-11-28 07:27:00 +03:00
omar 6ab51d5fb0 Keep cancelled stream setup in its publisher slot
Prevent a replacement from inheriting the cancelled publication’s late stream ID.
Cover the cancellation and unregister ordering in the offline native publisher tests.
2026-11-28 07:26:25 +03:00
omar 6ca233c6db Match Display Size preview marks to TeamSpeak 6 geometry
Use the 6.0.0.5232 nested preview scale to derive marker size, spacing, and bar dimensions.
Keep the existing preference callback and selection state unchanged.
2026-11-28 07:25:33 +03:00
omar 261f84af1b test(core): verify server capacity property wire output 2026-11-28 07:21:02 +03:00
omar caf29f4c5e Allow editing server properties without rename permission 2026-11-28 07:06:46 +03:00
omar fb779cf5ee Refresh the server name used by the next edit confirmation 2026-11-28 06:57:51 +03:00
omar b0e6062697 Verify default channel selection by fresh guest arrival 2026-11-28 06:51:23 +03:00
omar 6738124c77 Verify channel encryption setting roundtrip on beta14 2026-11-28 06:46:42 +03:00
omar 6f9a330cbc Verify channel banner URL and mode changes on beta14 2026-11-28 06:41:37 +03:00
omar d99a72244b Verify explicit channel codec latency factor readback on beta14 2026-11-28 06:36:12 +03:00
omar b0fc91f652 Exercise channel moderation threshold through the native editor 2026-11-28 06:29:18 +03:00
omar e696e7cc2d Verify permanent and semi-permanent channel types on beta14 2026-11-28 06:24:34 +03:00
omar 95e028d250 Verify temporary channel expiry after editing the delete delay 2026-11-28 06:19:56 +03:00
omar a8b63590ee Verify channel create and edit refusals belong to the original guest 2026-11-28 06:12:22 +03:00
omar 8e11486a07 Distinguish group creation scopes and verify channel group lifecycle 2026-11-28 06:06:23 +03:00
omar 2b16a6c9fa Confirm group deletion once and verify server group lifecycle 2026-11-28 05:55:05 +03:00
omar 6368b84915 Resolve omitted group types from the matching session roster 2026-11-28 05:40:32 +03:00
omar 62ab1896e5 Surface partial permission catalog refusals without dropping groups 2026-11-28 05:35:48 +03:00
omar c4b40fb3fe Verify channel family capacity edits against beta14 readback 2026-11-28 05:30:14 +03:00
omar cb8c81cbe4 Verify channel predecessor changes on two beta14 rosters 2026-11-28 05:25:55 +03:00
omar 86d3b17234 Verify occupied channel moves and report missing permission IDs 2026-11-28 05:22:15 +03:00
omar 4b968914ad Verify occupied channel deletion and reject replies for retired sessions 2026-11-28 05:10:49 +03:00
omar 32b761795b Honor blank bookmark names and verify channel capacity modes 2026-11-28 04:57:53 +03:00
omar 883a926e43 Verify saved voice routes with PCM on private beta14 2026-11-28 04:52:05 +03:00
omar f43400825d Verify saved voice device choices survive failed edits and restarts 2026-11-28 04:46:08 +03:00
omar 97e08a9244 Restore saved voice device selections before first use 2026-11-28 04:41:51 +03:00
omar 4777f73cf9 Restore saved voice volume before first playback 2026-11-28 04:32:07 +03:00
omar 580cf600d0 Verify connection retry after a refused password 2026-11-28 04:24:44 +03:00
omar 2e5f62807d Verify microphone toolbar mute and unmute across two voice clients 2026-11-28 04:16:30 +03:00
omar 49207846eb Validate microphone ownership before publishing unmute 2026-11-28 04:10:00 +03:00
omar 06702a0a62 Verify transmit gating through native audio settings 2026-11-28 04:00:29 +03:00
omar ef383bab30 Reject explicit null options in the transmit DSP command 2026-11-28 03:55:26 +03:00
omar c3b1082282 Verify live voice gating across a mid-burst detector change 2026-11-28 03:52:57 +03:00
omar 79eacbec6a Verify playback DSP command arguments and output boundaries 2026-11-28 03:48:22 +03:00
omar da827f1f93 Verify live playback AGC changes at the synthetic output 2026-11-28 03:46:13 +03:00
omar fa38d4c3d6 Apply saved playback AGC before joining a server 2026-11-28 03:39:14 +03:00
omar e954707948 Fix temporary password management and verify guest-owned rules 2026-11-28 03:31:39 +03:00
omar 87ab44808f Add server-bound confirmation for clearing the ban list 2026-11-28 03:22:21 +03:00
omar 49536d35c1 Verify timed ban creation through the native panel 2026-11-28 03:16:58 +03:00
omar 5a4d2edf97 Confirm removal of a single ban only once 2026-11-28 03:12:47 +03:00
omar d56b097984 Show ban expiry and scope ban list replies to the viewed server 2026-11-28 03:02:42 +03:00
omar 21752a8852 Retain selected chat attachments for confirmed overwrite 2026-11-28 02:49:02 +03:00
omar 33a8f266ab Verify transfer bandwidth restoration after refused starts and resumes 2026-11-28 02:22:51 +03:00
omar 8c1ae8477a Verify channel password rotation and explicit removal on beta14 2026-11-28 02:18:05 +03:00
omar 67e592c3cc Exclude password values and key pairs from admin property readback 2026-11-28 02:10:27 +03:00
omar 866d37b57b Verify channel pronunciation survives creation and editing 2026-11-28 02:07:20 +03:00
omar 04734b17be Verify Opus channel creation and codec changes on beta14 2026-11-28 02:03:00 +03:00
omar f7dc6cb5b4 Verify finite channel and family limits at creation 2026-11-28 01:56:34 +03:00
omar e8f18d5543 Verify unlimited channel capacity modes after reopening the editor 2026-11-28 01:52:59 +03:00
omar 4a0f6d87f2 Verify finite channel capacity edits on beta14 2026-11-28 01:48:22 +03:00
omar 34e07df0da Verify protected channel creation through the native form 2026-11-28 01:43:53 +03:00
omar 7ee33dc33e Verify authorized channel description at creation on beta14 2026-11-28 01:39:33 +03:00
omar 815c7c446f Clear download progress when a release is withdrawn 2026-11-28 01:35:22 +03:00
omar dd433fac97 Verify explicit update download rejects incomplete packages 2026-11-28 01:32:45 +03:00
omar fa0546e215 Clear last-check time when switching update channels 2026-11-28 01:28:48 +03:00
omar 20e99f000c Scope shortcut conflicts to their profile and label unnamed bookmark folders 2026-11-28 01:22:29 +03:00
omar d2617e44ba Support nickname and UID searches in the native client database 2026-11-28 01:14:44 +03:00
omar 17089bca60 Verify authorized database listing and nickname search on beta14 2026-11-28 01:01:20 +03:00
omar bf6adcd301 Verify voice toolbar controls target the input owner on beta14 2026-11-28 00:54:44 +03:00
omar f453f48fc7 Keep the transmitting tab active when another tab deafens 2026-11-28 00:46:11 +03:00
omar 6dfaf45628 Read audio state without interrupting the active capture route 2026-11-28 00:39:42 +03:00
omar a47bebf922 Verify fresh voice playback after releasing the native UI attachment 2026-11-28 00:33:43 +03:00
omar 00643532a3 Require explicit unmute before admitting voice to playback 2026-11-28 00:22:32 +03:00
omar a1bf10f801 Record native capture ingress and peer verification 2026-11-28 00:11:15 +03:00
omar aab5a34b7c Verify capture release across a 600 ms consumer stall 2026-11-28 00:07:14 +03:00
omar 4aaab8f649 Document beta14 refusal to provision legacy codec channels 2026-11-28 00:02:22 +03:00
omar 0f5551ab86 Preserve authorized input when switching between PTT and continuous speech 2026-11-27 23:59:23 +03:00
omar 9cbf0bd02d Recover PTT key recording errors in Audio settings and verify remapping 2026-11-27 23:55:09 +03:00
omar ef5c9a89e5 Preserve voice routing across overlapping talk and mute holds 2026-11-27 23:47:29 +03:00
omar 59d5a92583 Resume an authorized PTT input on repeated holds and verify release timing 2026-11-27 23:40:58 +03:00
omar 639b8b7094 Preserve the capture permit during push-to-talk release delay 2026-11-27 23:30:56 +03:00
omar 0e6b285a9e Verify saved whisper receive policy against key-driven beta14 traffic 2026-11-27 23:25:41 +03:00
omar d8e40b497c Bind whisper capture permits atomically and honor the owning shortcut release 2026-11-27 23:15:13 +03:00
omar bbd2c350fc Verify nonmembers do not receive current-channel group whispers 2026-11-27 22:49:21 +03:00
omar ea957ec030 Verify live server and channel group whisper delivery 2026-11-27 22:43:45 +03:00
omar 748e760caa Clear stale whisper recipients when changing group catalogs 2026-11-27 22:31:39 +03:00
omar bf8f819a9d Reject zero-valued whisper group targets before routing 2026-11-27 22:19:39 +03:00
omar d77d0c3e7f Revalidate whisper recipients before sending the end marker 2026-11-27 22:14:39 +03:00
omar 8be4404f54 Record beta14 transport verification for whisper admission 2026-11-27 22:10:34 +03:00
omar 82a72e2fb6 Update whisper receipts only for admitted voice packets 2026-11-27 22:05:57 +03:00
omar 6d5e01693e Update dialog toggles immediately and verify authorized server log reads 2026-11-27 22:01:45 +03:00
omar 0e7d0b9bf4 Reject non-object requests and arguments before stdio dispatch 2026-11-27 21:43:48 +03:00
omar 0d7edae8cf Keep subscription refusals on the original server tab 2026-11-27 21:40:18 +03:00
omar 49cfd53f97 Validate channel subscription arguments and verify two-tab scope 2026-11-27 21:32:50 +03:00
omar 1d5e4ba860 Report duplicate shortcut IDs skipped during profile import 2026-11-27 21:21:12 +03:00
omar e15858b79d Invalidate pending channel reads when the channel is deleted 2026-11-27 21:17:42 +03:00
omar c8cbf4613d Verify channel directory mutations and cancellation on classic beta14 2026-11-27 21:09:52 +03:00
omar d72c273acd Verify shared upload bandwidth and live slot reduction against classic beta14 2026-11-27 21:03:58 +03:00
omar f76a7fb237 Preserve both permission group catalogs across scoped refreshes 2026-11-27 20:50:09 +03:00
omar aff60b9ff3 Load server logs with validated session-bound query options 2026-11-27 20:36:39 +03:00
omar 8e9f28c856 Bind server information replies to the viewed session 2026-11-27 20:09:35 +03:00
omar 5e73b78b55 Validate protected participant move passwords in the editor 2026-11-27 19:55:46 +03:00
omar cebac974d9 Accept move replies after the participant roster updates 2026-11-27 19:49:04 +03:00
omar 534f9b56d1 Bind participant move confirmation to the original destination 2026-11-27 19:43:47 +03:00
omar baea1f7142 Prefill group rename and submit only changed names 2026-11-27 19:23:19 +03:00
omar d687e35096 Discard superseded client database searches and pages 2026-11-27 19:16:26 +03:00
omar 6f1ffc34c1 Verify server database query bounds and guest refusal 2026-11-27 19:11:28 +03:00
omar c3f3c43224 Validate administrative client search text by Unicode scalar count 2026-11-27 19:03:24 +03:00
omar 8072e6f1d1 Count Unicode characters consistently in group names 2026-11-27 18:58:37 +03:00
omar d1b611a911 Enforce safe integer bounds on administrative writes and targets 2026-11-27 18:53:43 +03:00
omar 1213468924 Check channel codec quality across create and edit forms 2026-11-27 18:45:05 +03:00
omar bff5c3377d Verify channel renames against the original server channel ID 2026-11-27 18:40:16 +03:00
omar 90bcf5d929 Support session-bound multi-file selection for channel uploads 2026-11-27 18:31:41 +03:00
omar a0c33187bf Verify remembered and one-off download destinations across tabs 2026-11-27 18:21:36 +03:00
omar 49c747e3f5 Avoid sorting active transfers to check queue capacity 2026-11-27 18:14:15 +03:00
omar 5f71304898 Verify download slot reduction across live server tabs 2026-11-27 18:12:44 +03:00
omar 37552c282b Verify the download ceiling across two connected server tabs 2026-11-27 18:08:21 +03:00
omar b41b2d75f8 Preserve the selected filename when renaming channel files 2026-11-27 17:59:28 +03:00
omar e1a07a2e2f Keep capture closed when microphone handoff fails 2026-11-27 17:46:37 +03:00
omar a6684d352a Remember acknowledged server logins despite playback errors 2026-11-27 17:29:06 +03:00
omar 3396dcbd90 Restore the saved address in the initial server tab 2026-11-27 17:21:03 +03:00
omar b684eca1d8 Verify Matrix room links preserve the active server draft 2026-11-27 17:12:07 +03:00
omar be3654f149 Exercise account-free settings and offline chat boundaries 2026-11-27 17:08:28 +03:00
omar a8fc57c2e1 Report unsupported incoming whisper shortcuts when loading profiles 2026-11-27 17:02:57 +03:00
omar 149bad248e Address whisper replies to the exact sending connection 2026-11-27 16:37:23 +03:00
omar 9c0ddd48ca Record successful desktop parity publication 2026-11-27 16:33:38 +03:00
omar 20240c1027 Bind received whispers and replies to the original sender identity 2026-11-27 16:33:15 +03:00
omar d1450439d5 Render channel commander status and confirm self-only changes 2026-11-27 16:21:26 +03:00
omar d9570f3cc8 Apply participant volume while dragging and persist gain by UID on release 2026-11-27 16:01:48 +03:00
omar b266f4f1b7 Resolve participant permissions for each opened context menu 2026-11-27 15:44:57 +03:00
omar 62bb67b5a3 Validate Poke drafts and keep them editable until acknowledgement 2026-11-27 15:22:07 +03:00
omar 256e10a9c1 Show scoped participant connection statistics with localized units 2026-11-27 15:03:53 +03:00
omar 89a2b21746 Keep participant details bound to the selected session and UID 2026-11-27 14:45:58 +03:00
omar 0b4a707637 Separate direct talk power moderation from pending queue grants 2026-11-27 14:31:09 +03:00
omar c80219b1a3 Validate optional status messages and verify talk requests on beta14 2026-11-27 14:17:45 +03:00
omar 380e9d4b63 Verify tab disconnect leaves the other guest and microphone owner intact 2026-11-27 14:11:50 +03:00
omar 389e26dc89 Validate manager requests before revoking the current capture route 2026-11-27 14:04:46 +03:00
omar f41e064ea6 Validate connection text and identity arguments before dispatch 2026-11-27 13:56:43 +03:00
omar c12cf2123f Report the acknowledged subset of a partial snapshot import 2026-11-27 13:52:10 +03:00
omar 6bf4de71c6 Bind snapshot preview actions to the selected import token 2026-11-27 13:43:59 +03:00
omar 75514f1a84 Show the published filename for a partial snapshot export 2026-11-27 13:33:39 +03:00
omar 5f3cf5f797 Stop cancelled snapshot jobs before their first server query 2026-11-27 13:30:02 +03:00
omar 179683867c Scope snapshot progress to its running job and count planned operations 2026-11-27 13:26:14 +03:00
omar e47a81d82c Reject oversized snapshot selections before reading regular files 2026-11-27 13:08:21 +03:00
omar 160ba55c92 Verify a channels-only snapshot through Windows Save and Open dialogs 2026-11-27 13:05:19 +03:00
omar c912eb3a9c Validate exported channel topology and revoke cancelled import previews 2026-11-27 12:52:48 +03:00
omar 89cf17066f Reject mismatched channel properties during snapshot export 2026-11-27 12:46:27 +03:00
omar 4fee4c0ce6 Keep channel details bound to the current selection and session 2026-11-27 12:43:01 +03:00
omar 061bb2d33c Verify contact highlighting against the saved UID after restart 2026-11-27 12:31:01 +03:00
omar 96d9c45203 Scope contact ignore actions to the current local address book 2026-11-27 12:20:25 +03:00
omar 2e45637f1d Display and copy only the explicit desktop download location 2026-11-27 12:12:44 +03:00
omar b7635deb8b Honor channel permission hints for file moves and directory downloads 2026-11-27 12:06:03 +03:00
omar de99c5fdea Bound chat image decoding and verify channel image presentation 2026-11-27 12:01:05 +03:00
omar b4e084dd25 Validate transfer control IDs and verify paused downloads on beta14 2026-11-27 11:49:19 +03:00
omar c6cb35366e Record atomic download failure checks on Windows 2026-11-27 11:42:42 +03:00
omar 67b2fc60b2 Verify transfer progress and history isolation across reconnects 2026-11-27 11:41:19 +03:00
omar a3ee6cc0c0 Validate channel file IDs and exercise downloads from the Slint browser 2026-11-27 11:34:26 +03:00
omar 8d4daf4ef8 Release unused directory leases when file tokens are discarded 2026-11-27 11:27:22 +03:00
omar e25263e807 Verify persisted directional limits in Windows transfer settings 2026-11-27 11:24:39 +03:00
omar ba6cae3948 Verify that one-off download destinations expire on reconnect 2026-11-27 11:20:25 +03:00
omar e7951f1bc6 Verify the restored Windows download location with a real transfer 2026-11-27 11:13:45 +03:00
omar 6712e6dab6 Verify recording destination through the Windows folder picker 2026-11-27 10:51:54 +03:00
omar 9a518bda66 Bind recording controls and status updates to the selected take 2026-11-27 10:37:07 +03:00
omar 59166106f2 Bind broadcast controls to their source and wait for setup acknowledgement 2026-11-27 10:19:41 +03:00
omar dc3e596625 Scope stream ICE candidates to the negotiated transport 2026-11-27 10:09:11 +03:00
omar 1fe05c06fe Verify selected Slint stream joins with decoded audio and video 2026-11-27 09:54:33 +03:00
omar b685597092 Discover channel streams when opening the Streams stage 2026-11-27 09:45:45 +03:00
omar 59a2878447 Keep stream leave and delayed UI cleanup bound to the original viewer 2026-11-27 09:27:50 +03:00
omar 8630542261 Keep stream moderation actions bound to the named viewer 2026-11-27 09:16:33 +03:00
omar 039af3f3b7 Bind the broadcast Stop action to its registered publisher 2026-11-27 09:05:09 +03:00
omar 8004c01526 Verify stream admission decisions isolate concurrent beta14 viewers 2026-11-27 08:56:44 +03:00
omar f7601e7a4f Verify approved beta14 viewer receives decoded native video 2026-11-27 08:49:01 +03:00
omar 402d8ff675 Verify stream admission refusal on two beta14 clients 2026-11-27 08:41:41 +03:00
omar 1e2856e261 Edit confirmed settings from an active broadcast tile 2026-11-27 08:39:14 +03:00
omar f563d2ba9a Expose stream metadata changes only after server acknowledgement 2026-11-27 08:29:31 +03:00
omar e52db5b112 Send the beta14 publisher stop reason and verify stream discovery 2026-11-27 08:19:09 +03:00
omar c27a425680 Verify decoded audio tone alongside moving WebRTC video 2026-11-27 08:05:19 +03:00
omar f0ed160cd0 Verify a decoded colour transition in native WebRTC loopback 2026-11-27 08:00:29 +03:00
omar 6053e8b315 Route server stop events to the registered publication 2026-11-27 07:55:34 +03:00
omar 5933297cae Bind stream admission decisions to the selected viewer UID 2026-11-27 07:49:26 +03:00
omar 5e646fc527 Bind manual stream viewer removal to the selected UID 2026-11-27 07:46:07 +03:00
omar aa88f78c44 Recheck viewer identity before queued stream evictions 2026-11-27 07:43:14 +03:00
omar 85e559dad5 Apply publisher-scoped stream stops to current viewers immediately 2026-11-27 07:38:47 +03:00
omar 6fea1a8d31 Reject malformed stream viewer recipient IDs 2026-11-27 07:35:49 +03:00
omar 54179705e2 Surface viewer ICE send failures after the answer 2026-11-27 07:32:44 +03:00
omar dfb60d7b7c Validate outgoing stream signal envelopes and join notes before dispatch 2026-11-27 07:29:20 +03:00
omar 335466b4a1 Refresh displayed chat and event clocks when time format changes 2026-11-27 07:25:27 +03:00
omar 6ac09676b0 Verify server chat permission refusals preserve the draft 2026-11-27 07:18:36 +03:00
omar 4244adfed6 Verify live private and channel text delivery through Slint 2026-11-27 07:14:45 +03:00
omar 390261e166 Show rejected channel passwords and verify protected joins on beta14 2026-11-27 07:12:53 +03:00
omar 2af19bcfcf Validate join targets and bind subscription menus to current channel state 2026-11-27 07:03:56 +03:00
omar 0ef6447971 Apply chat display and ignore preferences consistently 2026-11-27 06:54:43 +03:00
omar c0835c613c Verify native PTT persistence and connected whisper settings 2026-11-27 06:48:03 +03:00
omar 20e6008fd4 Verify held whisper reconnect and persisted bookmark folder moves 2026-11-27 06:39:05 +03:00
omar 8a98e3dcc6 Require a visible matching UID for individual whisper recipients 2026-11-27 06:33:00 +03:00
omar 90c28eedbb Require one distinct usable privilege key in creation replies 2026-11-27 06:28:57 +03:00
omar 533b2b2d81 Verify participant information from Slint across reconnect 2026-11-27 06:10:30 +03:00
omar 509bbb872d Verify client identity before returning client information 2026-11-27 06:05:11 +03:00
omar c84910524f Add read-only beta14 database identity comparison 2026-11-27 05:54:48 +03:00
omar 60d1953ff6 Match database ID replies to the requested client UID 2026-11-27 05:49:24 +03:00
omar 25575d1111 Identify newly created groups by type and pre-request IDs 2026-11-27 05:46:16 +03:00
omar d84153004d Filter channel file listings locally in the native browser 2026-11-27 05:40:18 +03:00
omar 643d0e45e6 Keep permission context when searching or paging the client database 2026-11-27 05:33:25 +03:00
omar 3a8e15e4c5 Keep scoped administration list rows bound to their explicit target 2026-11-27 05:28:17 +03:00
omar d5ba657f6e Keep nickname editor open until the server accepts the change 2026-11-27 05:26:13 +03:00
omar e9f375c4f7 Persist channel member disclosure per server address 2026-11-27 05:16:04 +03:00
omar f804bef346 Verify participant ordering independently of desktop tree density 2026-11-27 05:09:31 +03:00
omar 3db0766339 Apply the saved tree style to native desktop participant rows 2026-11-27 05:05:11 +03:00
omar faf9f957e7 Report the selected taskbar hide mode and clarify lock mute behavior 2026-11-27 04:59:20 +03:00
omar 2c8a47d51f Verify recording mode survives restarts and cancelled setup 2026-11-27 04:52:23 +03:00
omar 2e3b2719e7 Name native recording takes automatically and verify Windows export 2026-11-27 04:48:48 +03:00
omar 7729f263c0 Persist stream volume when the user commits a change 2026-11-27 04:40:02 +03:00
omar d59bebd7eb Align native stream volume controls with the viewer gain range 2026-11-27 04:36:05 +03:00
omar d5b9541d1d Reject server-routed streams before starting a P2P viewer 2026-11-27 04:31:27 +03:00
omar 8a8f52d7f1 Invalidate stale channel descriptions and verify live edit readback 2026-11-27 04:26:06 +03:00
omar 89a930d2f5 Show recovery guidance for unavailable saved audio devices 2026-11-27 04:12:34 +03:00
omar 0354a6fb8b Recognize copied IPv6 file links in native chat 2026-11-27 04:08:57 +03:00
omar 010e6b45fd Honor server defaults when creating a channel from the native form 2026-11-27 04:06:04 +03:00
omar a25bd6b19d Record beta14 channel creation acknowledgement and edit readback 2026-11-27 03:55:29 +03:00
omar e6a8d2f7bc Require an unambiguous channel ID before post-create actions 2026-11-27 03:52:05 +03:00
omar 95ebf37f0b Reject stale predecessors when creating or editing channels 2026-11-27 03:48:48 +03:00
omar b3f73c389d Scope channel creation order to the selected parent 2026-11-27 03:46:24 +03:00
omar 3c828e35f3 Report unchanged channel moves without a server write 2026-11-27 03:40:40 +03:00
omar 8930007945 Recheck channel move topology before dispatch 2026-11-27 03:34:52 +03:00
omar 9b19e96271 Populate channel move destinations and scope predecessors to their parent 2026-11-27 03:30:49 +03:00
omar cc3cb2702c Add a focused channel order readback check for private beta14 fixtures 2026-11-27 03:18:43 +03:00
omar be1d308f9e Use current channel topology for admin property readback 2026-11-27 03:14:38 +03:00
omar 981c486b0c Show the joined channel codec when legacy voice is unavailable 2026-11-27 03:08:06 +03:00
omar 827f2c3053 Revoke each affected audio capture worker once 2026-11-27 02:58:59 +03:00
omar ced85a30cc Keep direct-mode capture valid when reapplying set_transmit 2026-11-27 02:53:19 +03:00
omar 2a0a95f668 Record TS6 transmission mode comparison and PCM gate results 2026-11-27 02:51:03 +03:00
omar 0e6bfb77bc Preserve PTT delay presets and cancel pending releases on rebind 2026-11-27 02:49:44 +03:00
omar f1e7d8d5c4 Verify talk request draft validation and stale session refusal 2026-11-27 02:40:12 +03:00
omar afac6cffee Reject stale native grants after a talk request is withdrawn 2026-11-27 02:29:08 +03:00
omar 20a36d0dcf Allow talk requests without text and verify moderation on beta14 2026-11-27 02:22:45 +03:00
omar 2780adc2ce Keep delivering away status when an earlier tab reconnects 2026-11-27 02:08:24 +03:00
omar 3daa2fd990 Apply the confirmed away message to each captured server session 2026-11-27 02:03:09 +03:00
omar 220119e64f Show recent talk requests first without changing grant-next priority 2026-11-27 01:50:22 +03:00
omar 4dd514ea05 Reset speaker gain without unmuting on Alt-click 2026-11-27 01:45:10 +03:00
omar 764e3dc060 Use the TeamSpeak gain taper in the peer volume dialog 2026-11-27 01:38:54 +03:00
omar 49b9ce5dcd Restore valid speaker gains when one saved UID is unreadable 2026-11-27 01:31:29 +03:00
omar abdcbf1135 Keep active microphone capture when returning to its server tab 2026-11-27 01:28:23 +03:00
omar 373bd3d314 Use complete server announcements for file backend selection 2026-11-27 01:25:36 +03:00
omar a215cebfee Verify desktop log directory access and isolated refusal 2026-11-27 01:22:23 +03:00
omar ab3508c9cb Open installed theme folders from desktop Appearance 2026-11-27 01:19:23 +03:00
omar 4fb47fbde1 Expose independent advanced controls for six TeamSpeak notification cues 2026-11-27 01:14:15 +03:00
omar bab7c93d00 Preserve channel movement across roster visibility changes 2026-11-27 01:06:04 +03:00
omar 2b176ccdff Show inherited bookmarks under the current default identity 2026-11-27 01:01:47 +03:00
omar 582fe2d6c2 Record live TS6 beta14 identity security challenge verification 2026-11-27 00:56:39 +03:00
omar 4ca8678e6b Offer scoped identity security review after a connection refusal 2026-11-27 00:50:52 +03:00
omar b5302b813a Honor first-run theme when resuming an empty native profile 2026-11-27 00:39:50 +03:00
omar 6f8e4bd3df Verify nondefault identity selection and bookmarks after UI reattachment 2026-11-27 00:33:44 +03:00
omar 9496f99fd4 Verify stale cancellation cannot stop a new identity search 2026-11-27 00:29:53 +03:00
omar fe9fe247c4 Record Windows cancellation checks for identity export 2026-11-27 00:24:20 +03:00
omar d57e90e67c Count only new identities against the vault limit and report import results 2026-11-27 00:22:18 +03:00
omar 530d15aef7 Publish desktop identity backups without truncating the previous file 2026-11-27 00:15:22 +03:00
omar 351366fb3d Forget the selected identity after confirmed deletion 2026-11-26 23:59:21 +03:00
omar 8312cb029a Verify offline profile changes across tabs, UI attachments and restart 2026-11-26 23:55:07 +03:00
omar 5162a890c4 Keep unavailable tabs recoverable and reject stale selections locally 2026-11-26 23:50:23 +03:00
omar f3f0950313 Revoke captured voice on confirmed own-channel moves 2026-11-26 23:41:59 +03:00
omar 5b27eb6d49 Verify contact sort order after two native restarts 2026-11-26 23:37:30 +03:00
omar d55f71577c Preserve contact grouping when offline contacts are hidden 2026-11-26 23:34:05 +03:00
omar 53daeca615 Keep unread messages visible on collapsed contact groups 2026-11-26 23:31:36 +03:00
omar 57cf5ba51b Count private unread for contacts across server tabs 2026-11-26 23:29:11 +03:00
omar 9d8a8ea2ae Persist independent online and offline contact group expansion 2026-11-26 23:23:32 +03:00
omar b6db8a2b29 Persist desktop bookmark disclosure across restarts 2026-11-26 23:19:11 +03:00
omar 5b508e70e6 Restore desktop pane widths and clamp ultrawide drags 2026-11-26 23:13:42 +03:00
omar 73c73d5cbc Match TS6 variant ordering in the native theme picker 2026-11-26 23:07:14 +03:00
omar 923dced8b0 Cover encoder refusal and receive silence for all legacy codecs 2026-11-26 23:04:49 +03:00
omar 2b2160869e Record Windows theme ZIP import and rejection evidence 2026-11-26 23:01:28 +03:00
omar 8cf21cf4de Group installed theme variants and verify live previews 2026-11-26 22:53:44 +03:00
omar da12f9ae86 Confirm declared theme links and label documentation correctly 2026-11-26 22:44:55 +03:00
omar f6bc5f8922 Warn about locally flagged domains in settings links 2026-11-26 22:39:38 +03:00
omar bef919fa16 Show the local phishing list status in trusted sites 2026-11-26 22:35:53 +03:00
omar 00ee68c348 Report missing theme selection and verify stock fallback across restart 2026-11-26 22:30:34 +03:00
omar 206a5a61ed Document TS6 settings exclusions against the installed Windows reference 2026-11-26 22:16:40 +03:00
omar fa46fb1ade Record Windows desktop startup and sidebar acceptance 2026-11-26 22:10:05 +03:00
omar 76795c6ac9 Connect startup bookmarks in sidebar display order 2026-11-26 22:00:12 +03:00
omar 20fcc27182 Verify configured upload rate at the receiving TCP socket 2026-11-26 21:54:15 +03:00
omar a6e3c6b1d6 Keep dismissed password prompts closed across repeated snapshots 2026-11-26 21:50:18 +03:00
omar 5b40669953 Explain advertised Matrix rooms in standard server chat 2026-11-26 21:35:48 +03:00
omar 4d578bc028 Display live recording waveforms and bind finalization to its take 2026-11-26 21:29:11 +03:00
omar 82b7f000bd Match recording waveform peaks to silence written on overflow 2026-11-26 21:20:13 +03:00
omar 20e3ec5592 Verify Windows recording export against finalized WAV and manifest 2026-11-26 21:13:54 +03:00
omar 1f008bcb27 Confirm recording overwrites before publishing any tracks 2026-11-26 21:02:10 +03:00
omar f0827a221c Show recording finalization until the writer completes 2026-11-26 20:50:06 +03:00
omar b93a87ba93 Retain the recording directory grant until its writer finishes 2026-11-26 20:44:52 +03:00
omar d738f2feca Document live recording timeline and PCM byte accounting 2026-11-26 20:35:36 +03:00
omar e45f80e363 Refuse export of recordings that failed to finalize 2026-11-26 20:31:29 +03:00
omar 84b6692230 Verify scoped private history writes from received chat events 2026-11-26 20:23:12 +03:00
omar 5d3eb925fe Keep the active conversation when closing a background private chat 2026-11-26 20:18:33 +03:00
omar 6ce8153371 Verify scoped history pagination through the native chat controls 2026-11-26 20:08:48 +03:00
omar 2c52126955 Avoid duplicating live chat records already loaded from disk 2026-11-26 20:02:05 +03:00
omar 08647b6830 Check the captured channel in the core before sending chat 2026-11-26 19:54:47 +03:00
omar 2ba2e8dda4 Isolate chat drafts and pending sends by connection tab 2026-11-26 19:47:45 +03:00
omar 06ee7e1fb0 Keep settings checkboxes bound to acknowledged values 2026-11-26 19:38:11 +03:00
omar dff1fb2d7b Cancel held PTT without a release delay when switching shortcut profiles 2026-11-26 19:33:31 +03:00
omar 476319613a Restore the active shortcut editor after deleting a profile 2026-11-26 19:27:41 +03:00
omar fe3f8b1b62 Keep settings choices bound to acknowledged values 2026-11-26 19:21:53 +03:00
omar 09b55b8040 Confirm tab core restart in the native shell 2026-11-26 18:55:35 +03:00
omar 230023a13b Publish failed core restarts before acknowledging the request 2026-11-26 18:50:55 +03:00
omar d2c1f2294b Verify microphone handoff and stale events after connection slot reuse 2026-11-26 18:47:36 +03:00
omar 72233d108b Retire media only when the connection manager accepts close or restart
- Fence playback and queued session work by the retired session key without revoking another tab’s capture.
- Preserve held transmission when the final tab cannot close; cover the eight-tab limit in Slint.
2026-11-26 18:42:54 +03:00
omar 3ce99945b8 Record beta14 refusal of legacy channel codec fixtures 2026-11-26 18:27:10 +03:00
omar 034f7c0198 Expose whisper store warnings and keep settings actions clickable 2026-11-26 18:25:30 +03:00
omar d314dbc312 Verify restored Slint document focus using keyboard activation 2026-11-26 18:21:12 +03:00
omar 00f585c3b9 Preserve whisper shortcuts when confirmed list deletion fails 2026-11-26 18:20:57 +03:00
omar a153511710 Apply saved whisper policy before a native session connects
- Serialize preference changes with preflight acknowledgement, without holding the policy lock through the network handshake.
2026-11-26 18:08:07 +03:00
omar 3b5c49e329 Drop buffered and stale whisper audio at policy boundaries 2026-11-26 18:05:21 +03:00
omar b19b432281 Ignore global key releases for locally held shortcuts 2026-11-26 17:37:42 +03:00
omar 58547c8221 Exercise channel administration through the real Rust CLI
- Validate temporary channel creation, sparse edits, stale requests and limit readback on an isolated TeamSpeak beta14.
- Report omitted inheritance flags and permission refusals separately from confirmed server writes.
2026-11-26 17:34:40 +03:00
omar 845244ec2c Keep administrative drafts until the server acknowledges the edit
- Retain submitted values on validation and server errors, and ignore completions targeting a replaced dialog or session.
- Cover both editors using Slint callbacks and an isolated runtime.
2026-11-26 17:29:47 +03:00
omar de84b526d4 Populate channel and server editors from their live targets
- Preserve untouched values and never prefill passwords. Expose the server storage quota and SFU endpoint and restrict banner options to channel edits.
- Require an acknowledged child channel id for post-create icon changes. Seven targeted Windows regression tests passed.
2026-11-26 17:15:14 +03:00
omar c3baa1952c Float the desktop composer over the full chat viewport
- Reserve trailing scroll space as the desktop editor grows and keep compact layout unchanged.
- Measured channel timeline and composer rectangles match across EN/RU and dark/light at 1280x800.
2026-11-26 17:04:45 +03:00
omar c2d62e0fdc Measure the visible chat viewport on both clients
- Preserve unmasked whole-frame and raw geometry metrics; compare the visible log against each side’s measured composer position.
- Cover offset, size mismatch and missing geometry in three tests.
2026-11-26 17:00:50 +03:00
omar 57807c184e Integrate and verify the native Windows desktop client
- Update pinned Rust, Slint, DSP and WebRTC dependencies, preserving the local vendor patches and source receipts.
- Fix desktop audio scheduling and disconnect handling; include isolated duplex, identity, bookmark and notification checks.
- Record measured differences from TeamSpeak 6.0.0.5232; full visual and server-feature parity remain open.
2026-11-26 16:59:05 +03:00
986 changed files with 118807 additions and 49469 deletions

No files matched your search

+384
View File
@@ -2,6 +2,390 @@
## Unreleased
- Edit Server stays accessible when the user may change specific properties but not the server name. The server still authorizes each save.
- After renaming a server, Server Info shows the acknowledged name and the next Edit Server dialog uses it for confirmation.
- The Permission Groups panel and creation dialogs distinguish New Server Group from New Channel Group in English and Russian.
- Permission Groups asks for the group name once before deleting. Rename no longer depends on nonexistent per-kind rename permission flags; the server checks the target group's modify power.
- Refreshing Permission Groups accepts beta14 list rows without a type when the current roster confirms the group ID, name and kind. Template and query groups remain hidden.
- Permission Groups now shows the server's catalog error alongside group rows already available from the roster.
- When a TeamSpeak permission refusal includes a missing permission ID, the native client displays that ID with the server error.
- Clearing a bookmark name in the desktop editor now uses its server address as the display name, matching the bookmark store.
- The first microphone or playback request now uses the device selected in the saved profile, even before Audio settings are opened. Restoring the selection does not start either device.
- The saved voice output level is applied before the first connection. Adjusting voice volume no longer reconfigures the microphone or reopens audio devices.
- Unmuting from the voice toolbar or a shortcut now checks the imported microphone mapping before telling the server that the microphone is unmuted. A refused shortcut leaves the other tabs muted too.
- The core rejects explicit null detector, sensitivity, and level values in set_transmit instead of silently treating them as omitted.
- New server connections apply the selected output profile's per-speaker automatic gain control before receiving voice. Audio settings changes also reach ready cores that have not joined a server yet.
- Temporary password management now reads beta14 password rows, shows their issuer and expiry, and offers the server default or a current channel when creating a rule.
- The Banned Users panel can now clear all bans after typed confirmation for the viewed server. Closing the dialog without confirming leaves the rules unchanged.
- Removing one ban now requires a single confirmation for the selected rule.
- The ban list shows the reason, issuer and expiry of each rule. Invalid expiry data is shown as unknown, not permanent. Late replies cannot populate a closed panel or a different server's list.
- A chat attachment that collides with an existing server file can now be replaced from Transfers after confirmation. The retry uses the bytes originally selected, even if the local file has since changed.
- The core omits channel and server password values and the server key pair from cached admin properties, while preserving password flags.
- A release check now clears the old download progress when the offered package changes or disappears.
- Switching update channels clears the previous channel's last-check time until the new channel is checked.
- Shortcut conflicts now appear only in the profile that owns the conflicting chord. The bookmark Move dialog now labels unnamed folders in both destination and ordering choices.
- Search the server client database by nickname or UID. Enter submits the query; typing still filters the file browser immediately.
- Deafening a second server tab or restoring its sound no longer interrupts microphone capture on the transmitting tab.
- Reading mute state with an empty set_audio request no longer interrupts voice capture. Partial updates preserve the omitted flag and reject explicit null values.
- Playback no longer treats a missing or malformed output mute flag as permission to play voice. The initial roster must also identify the local client.
- Turning off push-to-talk after releasing the key resumes the previously authorized microphone on the same connection. Turning push-to-talk back on stops continuous speech until the next hold.
- Audio settings now show the PTT key being recorded, a Cancel action, and an inline error if the chord is invalid or cannot be saved. The previous binding remains usable after cancellation.
- Holding Push to Mute while speaking with Push to Talk no longer reconfigures capture on key-down. Releasing mute resumes the voice route only when transmission is still requested.
- Pressing push-to-talk again after its release delay expires resumes the previously active, authorized microphone on the same connection. A focus or input route change clears that remembered state.
- Releasing the on-screen push-to-talk button keeps capture active while another PTT key is held or the configured release delay is running. Repeated releases no longer extend the delay.
- Local whisper shortcuts bind the acknowledged whisper route together with its capture permit. When a second shortcut replaces the first, releasing the first no longer silences the second.
- Switching a whisper list to a different server or channel group catalog clears the old group and resets its delivery scope. A picker opened for the previous group type cannot select a recipient in the new catalog.
- Server and channel group whispers reject zero IDs even when padded with zeroes. Positive decimal IDs with leading zeroes remain valid.
- Ending a whisper rechecks its recipients against the current roster, so a departed client's reused numeric ID does not receive the end marker.
- Rejected voice packets no longer create a whisper history event or interrupt an active whisper. Only packets admitted by the jitter buffer update the receiver's whisper state.
- Dialog checkboxes now show their edited state immediately. A second click before submission toggles the current value rather than repeating the previous edit.
- The diagnostic stdio bridge requires JSON objects for requests and their arguments. Positional arrays and explicit null arguments no longer dispatch commands; omitting arguments for a no-argument command still works.
- A delayed channel subscription refusal is no longer displayed on a different server tab or after reconnection.
- The stdio channel subscription commands now reject positional arrays. They require named fields, including an explicit boolean for subscribe or unsubscribe.
- Imported shortcut files now report skipped duplicate profile and binding IDs. The first entry is retained, including when a duplicate uses different UUID letter case.
- A pending channel information or description request now rejects a reply if the requested channel was deleted, even if a new channel has since used its numeric ID.
- Permission Groups shows only regular groups. Refreshing one group list preserves the other list and the creation actions. A late request to open the panel no longer replaces the current tab or reopens a closed panel.
- Server Log now waits for Load and accepts the requested line count, start position, order and instance flag. A refusal leaves the request editable; switching server tabs invalidates the old request.
- Server Info discards late replies from a closed panel or a previous connection. Empty, ambiguous and mismatched server-property replies no longer open an editor.
- The Move to Own Channel form checks the password's 1024-byte UTF-8 limit before submission and preserves leading and trailing spaces.
- A confirmed participant move no longer reports a changed target just because the roster already shows the participant in the destination channel. Replies from a replaced session are still rejected.
- Move to Own Channel is offered only for participants in another channel. Its confirmation stays bound to the original participant and destination, asks for a password only for a protected channel, and keeps server refusals visible.
- Group Rename opens with the selected group's current name. Blank and unchanged names close the editor without submitting; changed names are trimmed before submission.
- A late client database search or page response no longer replaces newer results or reopens a closed panel. Results and errors are bound to the original server and tab.
- Client database search accepts patterns up to 255 Unicode characters. Administrative client UID fields use the 128-character limit, independently of UTF-8 byte length.
- Server and channel group names use the same 128-character Unicode limit in the editor and core. Multibyte names no longer fail early because of their UTF-8 byte length.
- Administrative commands reject IDs, log offsets and editable numeric properties above the reference interface's safe-integer limit before connecting. Server quota, bandwidth and default-group fields enforce the same limit in the native editor.
- Desktop users can select multiple files in the channel upload dialog. Selections above 100 files are rejected as a batch; cancelling or reconnecting does not queue files in another session.
- The channel file Rename form opens with the current filename. Confirming the same name leaves the file unchanged without sending a rename command.
- Switching the microphone to another server tab no longer marks audio devices active before they start. If setup fails, neither tab retains a usable capture permit. Muted sessions no longer report an expected absence of a capture permit as a changed target.
- A successful server login remembers the address even if the selected playback device is unavailable. The playback error is still reported.
- The first empty server tab restores the last saved address in its Connect form after restart. Additional empty tabs do not inherit that address.
- Shortcut profile diagnostics now distinguish unsupported Block Incoming Whispers bindings from other invalid entries. Other valid bindings remain usable.
- Whisper history and notifications use the sender captured at receipt. A guest who later receives the same client number cannot inherit the original guest's reply action.
- Reply Whisper addresses only the connection that sent the whisper, even when a second client is connected with the same UID. Saved whisper lists keep their existing multi-client behavior.
- Channel commanders have a separate indicator in the detailed tree. The compact tree uses the saved commander lamp setting. Only the user's own row offers a commander change, and its confirmation reflects the current server flag.
- Participant volume changes while dragging the fader; releasing it saves the gain by UID. Mute stays local to the connection. Reset removes the saved modifier and unmutes the participant.
- The participant menu reads the selected client's capabilities on opening. Late replies cannot change a closed or reopened menu, and unavailable server actions stay disabled.
- Poke accepts up to 1024 UTF-8 bytes locally. A server refusal keeps the message editable; submitting a draft after the recipient leaves cannot send it to a replacement participant.
- Participant Connection Info shows localized timing, packet loss and traffic metrics without rounding 64-bit counters. Old statistics cannot populate a replacement tab or participant.
- Participant Info retains previously returned fields when a later update omits them. Superseded replies and errors cannot populate the next tab or a new participant reusing the same client number.
- The participant menu offers Grant or Revoke according to the current talker flag. Manual grants no longer require a pending request. Queue grants still require the selected request in the moderator's current channel.
- Reject explicitly null away and talk-request messages. Omitting a message remains valid.
- Invalid connection requests no longer revoke the current microphone route or trigger a default identity lookup. The manager forwards validated commands to the embedded core without parsing them again.
- Validate connect and disconnect string lengths and selected identity IDs before dispatch. The JSON bridge rejects explicitly null fields instead of treating them as omitted.
- Partial snapshot imports now list acknowledged changes alongside failures. Property and permission rows identify the object and field without displaying its value. Reusing an existing icon does not count as an upload.
- Snapshot Apply and Cancel now refer to the exact previewed file, even when the next file has a catalog with the same ID.
- A saved partial snapshot now shows its filename alongside the warning and issue details.
- Cancelling a snapshot immediately after starting it now prevents the initial server query. A cancellation received during that query stops subsequent work.
- Snapshot progress and cancellation controls are tied to the job, session and window that opened the panel. Completed and planned counts now use the same units, including permission reads.
- Reject oversized regular snapshot files using their checked descriptor size before reading the payload. Unknown-size streams remain bounded during reading.
- Dismissing an idle snapshot import now revokes its token, so a late confirmation cannot apply a file that was cancelled.
- Snapshot export rejects incomplete channel trees and ambiguous sibling order before writing the snapshot.
- Snapshot export no longer attaches an unrelated channel's properties to a saved channel. Missing or ambiguous properties are reported as a partial export.
- Channel Info ignores superseded successes and errors after navigation or reconnect. It rejects an empty, ambiguous or mismatched reply instead of showing the wrong channel.
- Contacts offers Ignore or Unignore according to the selected UID's current state. A queued action from a deleted contact can no longer change the ignore list.
- Desktop transfer settings display and copy the explicitly selected default download folder. Using the system Downloads folder does not turn it into a saved preference.
- The channel file browser disables Move when the channel denies rename. Download Folder requires both browsing and downloading permission.
- Check the dimensions of inline channel images before allocating decoded pixels.
- Reject zero transfer IDs for pause, resume and cancel before dispatch.
- Reject channel IDs above the protocol's safe-integer limit in file operations before sending a request.
- Releasing a file chooser token no longer keeps an unused directory grant alive solely to suggest its path in a later dialog. An active download still retains its own grant until it finishes.
- Opening the recording panel reads the recorder status. Pause, Resume, Stop and Reveal stay bound to the selected take so delayed controls cannot affect the next recording in the same tab.
- A stale Preview, Start or Stop command no longer acts on a replacement source in the same tab. A broadcast is shown as live only after both the setup acknowledgement and the server-assigned stream ID arrive.
- Reject zero client IDs for targeted stream commands. After WebRTC renegotiation, match ICE candidates to the addressed media transport and attach receiver sinks only after the answer commits.
- Opening Streams now queries other participants in the connected client's current channel. A background refresh cannot cancel a pending request for a selected participant.
- Leaving a stream closes the selected viewer immediately. A repeated stop waits for the pending leave instead of sending another request, and delayed cleanup does not close a replacement viewer of the same stream.
- Broadcast admission and removal buttons name their viewer. Actions stay bound to the same viewer when the list order changes.
- Stop on an active broadcast tile now targets the registered stream and its publisher. Closing the capture no longer looks up a replacement publisher to stop after the wait.
- Active publications now have an Edit broadcast action for the title, video bitrate, viewer limit and admission policy. It edits the registered stream without selecting or restarting the capture source.
- A running publisher reports changed stream settings only after the server acknowledges the update. Tighter admission rules apply immediately; looser rules wait for acknowledgement. A late reply cannot replace the state of a disconnected publication.
- Stopping a publication sends the close reason required by TS6 beta14. Stream discovery now distinguishes a server refusal for the requested participant from a successful lookup with no streams.
- A server stop naming only the local publisher now releases its registered capture. Queued stream notifications stay with the publication that received them and cannot stop its replacement.
- Approving or denying a stream viewer request now checks the UID selected in the menu. An obsolete request cannot admit or block a different viewer who was assigned the same client number.
- Removing or blocking a viewer from a stream menu now uses the UID captured when the action was selected. A replacement viewer can keep watching if the server reuses that number.
- Automatic stream viewer removal rechecks the viewer's UID before sending. A replacement client does not inherit a queued eviction when publication privacy changes.
- When the server stops a stream by publisher ID alone, current viewers of that publisher close immediately. The stop does not replay against a newly opened viewer.
- The stream viewer ignores a join reply or signaling event with a malformed recipient ID instead of treating it as unaddressed. Omitted IDs and empty wire flags remain supported.
- A viewer now reports a rejected outgoing ICE candidate after sending its answer, closes that peer, and leaves the stream once. Previously the send failure was lost.
- The core rejects malformed outgoing stream negotiation messages before transmission. Stream join notes now enforce the original 200-unit single-line limit.
- Switching between 12- and 24-hour time now updates loaded chat messages immediately. Recent server events use localized day periods without changing their recorded timestamps.
- A rejected channel password now opens an empty retry field with a localized error. Cancelling the password prompt leaves the user in the original channel.
- The channel menu offers Subscribe or Unsubscribe according to the current snapshot. A command from a dismissed or replaced menu cannot act on a newly selected channel.
- Joining channel zero now returns a local validation error through both the embedded and diagnostic APIs.
- Show Moderation Events now hides and restores channel events already in the chat view, including events received while hidden. Ordinary chat history is unchanged.
- Incoming chat with no explicit sender UID now uses the matching roster entry for the ignore list, just as it does for authorship. Reusing a client number does not transfer another user's ignore status.
- Private whispers no longer target a participant by client number alone when their UID is unavailable. Whispering to an explicitly selected channel still works.
- Creating a privilege key no longer reports success with an empty or ambiguous key. A repeated notification for the same key is accepted.
- Client information requests recheck the participant's UID when the server acknowledges the request. A stale client number cannot return another participant's details.
- Client database ID lookup now checks the returned UID and rejects conflicting IDs instead of passing unrelated notification rows to callers.
- Group creation no longer returns an existing group or a same-name group of another type as the newly created group. Follow-up permissions require one matching new ID.
- Searching a channel directory filters the loaded file names locally. Refreshing the same folder keeps the filter; opening another folder clears it.
- Searching or paging the client database now refreshes permission hints just like opening the first page, without losing the query or page offset.
- Filter scoped administration lists row by row so a change of group or channel within a notification cannot mix permissions from different targets.
- The connected nickname editor starts with the current name and stays open on server refusal. It uses the core's nickname validation and closes after an acknowledged change.
- Channel disclosure now remembers hidden participants per server address after restart. Collapsing a channel leaves its subchannels visible.
- The Compact tree style now reduces participant row and icon sizes without shrinking channels. The selected style takes effect immediately and survives restart.
- Desktop settings now report taskbar hiding as enabled for On Minimize, On Close and Both. The microphone lock description no longer promises automatic unmuting.
- Starting a local recording no longer asks for a free-form name that the core would reject. The native client uses the local start timestamp for the take folder, or the core's UTC name when the local offset is unavailable.
- Releasing the stream volume slider or confirming its form saves the level for the next viewer. Dragging previews the selected stream without writing preferences for each movement.
- Stream volume controls now use the playback engine's 0–100% range. Clicking the middle of the slider sets the selected viewer to half gain.
- Streams announced in server-routed mode show the SFU limitation instead of offering P2P playback. Direct streams from the same publisher remain watchable.
- A server notification that a channel description changed now invalidates its cached text and any pending description read for that channel. A newly reported empty description remains distinct from an unknown one.
- Audio and notification device pickers identify unavailable saved devices after enumeration. The saved route remains selected, and its name returns when the device becomes available again.
- Chat recognizes copied server-file links with bracketed IPv6 addresses, including links inside BBCode.
- The native Create Channel dialog no longer sends untouched optional overrides that can make ordinary guest creation fail. Codec and voice encryption offer Server default; explicit choices still go to the server.
- Channel creation returns an ID only for a matching notification from the same client under the requested parent. An accepted creation without a unique ID asks the caller to reload the tree before applying further changes.
- When creating a channel, changing its parent clears the previous insertion point. The picker lists only children of the new parent; leaving the position unset lets the server choose it.
Creating or editing now also checks the selected predecessor at submission and refuses the change if it moved to another parent or disappeared.
- Moving a channel to its current parent and explicit position returns an unchanged result without sending a server command.
- Move Channel opens at the channel's current position. Selecting a new parent offers First and that parent's children; the moving channel and its descendants are excluded from the destinations.
The core also checks the destination against the current tree when the move is submitted, so a predecessor that has since moved or disappeared cannot silently redirect the operation.
- Channel information and lists now show the current parent and preceding sibling after a neighboring channel moves.
- The server view now names the legacy Speex or CELT codec of the joined channel when voice is unavailable. Browsing another channel does not change the warning. The native transmission gate requires a known Opus codec.
- Reapplying direct voice transmission no longer ends an active burst or invalidates captured frames. Switching between direct transmission and voice activation still invalidates the old capture epoch.
- Push-to-talk release delay can now be set from Audio settings. Off preserves the last duration and cancels a running delay. Changing shortcut profiles also cancels a pending release from the previous profile.
- A talk request can now be submitted without a message. Pokes still require text.
Once a withdrawal is visible to the moderator, the old Grant action no longer gives that client talk power.
- The Away with Message shortcut prompts once for all connected sessions. If a tab reconnects before confirmation, its replacement stays untouched and the other original sessions still receive the message. Cancel leaves all statuses unchanged; the per-server menu still targets one session.
- The moderation queue shows the newest talk requests first. Grant Next still selects the oldest waiting peer in the current channel and skips withdrawn requests.
- Alt-clicking the speaker gain slider resets only the gain to 0 dB. The Reset button also clears local mute. Both changes take effect on confirmation.
- The peer volume dialog now has a tapered slider from -200 to +10 dB in 0.5 dB increments. Reset restores 0 dB and clears local mute in the draft; Cancel leaves the original settings untouched.
- An unreadable speaker UID in saved local volume preferences no longer prevents valid speaker gains from being restored. Loading reports the invalid entry and leaves the original file untouched.
- Returning to the server tab that already owns the live microphone no longer interrupts capture when automatic microphone switching is enabled.
- File transfers now recognize HTTPFT and S3 anywhere in the server's capability announcement. A new connection without an announcement no longer displays the previous server's features.
- Desktop Appearance can open the folder of an individual installed theme. The existing Open Extension Directory button still opens the parent folder.
- Advanced notification settings now have separate controls and Listen actions for moderator moves into and out of your channel, a kick into your channel, assignment and removal of a server group, and permission errors. Existing advanced choices still apply until a variant is edited.
- Clients crossing channel subscription boundaries are reported as moving when the server supplies the movement reason or both channels. Subscribing to a roster no longer announces those clients as connecting. Batched roster entries preserve the previous channel for subsequent moves.
- Identity Details lists bookmarks in folder order. Bookmarks with no assigned identity follow the current default without rewriting the bookmark.
- When a connection is refused because its identity security level is too low, the server tab offers to review that identity at the requested level. Opening the review does not start a search or reconnect.
- First-run setup now keeps the selected theme when resuming an initialized profile without an identity. A failed theme save can be retried before any identity is created.
- Identity import now reports how many distinct identities were added or already present. Reimporting a known key no longer fails when all 256 slots are occupied.
- Desktop identity export now saves `.ini` backups atomically. A write failure leaves the previous backup intact.
- Removing the selected identity clears its saved selection. Details and subsequent edits stay with the surviving identity.
- A tab with a failed core remains selectable for recovery. Selecting a stale tab after restart no longer exits the application or disrupts the other tabs.
- On a confirmed move to another channel, the core revokes already captured audio before publishing the new channel snapshot. Other users' moves do not interrupt capture.
- Hiding offline contacts also hides the grouping switch without resetting its saved value.
- Collapsed contact groups show the total unread private messages for their hidden contacts.
- Contacts now count unread private messages across all server tabs, including conversations that have no open chat tab.
- Online and offline contact groups can be expanded independently and remember their state across restarts.
- The desktop bookmark section can be collapsed from its header and remembers that choice across restarts.
- Desktop sidebar and server pane widths now survive restart, including sizes saved by earlier native builds. Dragging on an ultrawide display cannot exceed the supported 1600 px server pane width.
- Variants in a theme package are sorted by name in the picker, matching the TS6 desktop order.
- The theme picker groups installed variants by package and shows shared package links once.
- The theme picker shows only declared package links, labels documentation separately from email, and confirms each destination before opening it.
- External links from Settings now show the local malicious-domain warning before opening. Malformed DNS names are rejected before classification.
- Trusted sites now shows whether the phishing list is up to date, using a previous copy, or unavailable.
- Reloading themes now names a missing selected variant when restoring the stock theme.
- A failed recording finalization now leaves the incomplete WAV in staging. The recording panel reports the writer error and does not offer to export it.
- Stopping a recording no longer releases its directory grant while the writer is still finalizing WAV files. A late completion from an older take does not release the new take's grant.
- The recording panel shows “Finalizing recording” after Stop. A late status reply cannot restore Pause or Stop while the WAV writer finishes.
- Recording export asks about all existing destination files before replacing any of them. Cancelling an overwrite prompt leaves the existing files unchanged and retains the recording in staging.
- Recording waveforms now show silence for blocks lost to a full writer queue, matching the saved WAV.
- The recording panel now shows a live waveform for each track. Late replies cannot reopen a dismissed panel, and an older take's completion cannot authorize the current export.
- Server chat now identifies advertised Matrix rooms as unsupported without disabling ordinary text chat or asking for an account.
- Cancelling a password prompt no longer lets an older application snapshot reopen it.
- Startup connections follow the order shown in the bookmark sidebar, including bookmarks inside reordered folders.
- Two connections using the same identity and server now keep independent chat drafts. An acknowledgement in one tab no longer clears or unblocks a send in the other.
- Channel chat now checks the channel captured by the editor against the core's current channel before sending. A draft for a channel you have left is rejected instead of being sent to the new channel.
- An incoming chat message no longer appears twice when it is already included in the history page being loaded.
- Closing a background private chat keeps the selected conversation and its draft in view. Reopened chats retain their label when the peer is offline.
- Deleting the selected inactive shortcut profile now returns the editor to the active profile and its bindings.
- Switching shortcut profiles cancels a held push-to-talk key immediately; the configured release delay still applies to ordinary key-up.
- Settings checkboxes now display the value acknowledged by the application instead of retaining a local toggle state.
- Settings selectors now show the acknowledged value after a change. The whisper receive selector
no longer displays its previous mode after saving the new one.
- Restarting a tab's core from its menu now confirms which tab restarted. A failed restart is
reported as a failure before the caller receives its result.
- Closing or restarting a connection discards queued playback from that session without interrupting
another tab's microphone. Refusing to close the last tab preserves held push-to-talk and whisper.
- Whisper settings now explain read-only and damaged files. Failed list deletion preserves assigned
shortcuts, and Settings action buttons retain a clickable width on desktop.
- A delayed global shortcut release can no longer stop a newly held local push-to-talk or whisper
binding, or fire a local release-triggered action after the binding profile changes.
- Channel and server edit dialogs read current values before editing, retain drafts after rejection,
and close only on the matching server acknowledgement. Passwords are never prefilled.
- Added ordinary-channel S3 metadata browsing, taking precedence over HTTPFT when both are advertised.
The core accepts underscore-bearing command names and requires both matching list data and successful
status; malformed or timed-out replies are errors, not empty folders. An isolated official TS6 beta14
server verified an empty root listing and refused an ordinary guest upload grant. S3 file bytes,
remote mutations and the live-peer check remain unverified; HTTPFT stays blocked without legacy fallback.
- Verified two-way synthetic voice through the core CLI with silent disposable profiles. This did not
exercise official-client peers, physical microphones or speakers.
- A transport loss during a requested disconnect now completes the request as unconfirmed and
leaves the session disconnected. Unexpected connection loss still follows the reconnect path.
- A rejected connection command no longer tears down incoming voice. An expired capture frame is
dropped without stopping the microphone; a revoked session still cannot submit audio.
- Updated the desktop toolchain to Rust 1.100.0, Slint 1.19.1 (Skia m157.2), LiveKit WebRTC
bindings 0.4.2/0.3.55, Sonora 0.3.0 and Rubato 5.1.0. Local media and clipboard patches
are retained; old SDK build receipts do not certify the new source versions.
- Fixed native Windows build environment capture for non-ASCII values by selecting UTF-8 in the
child MSVC activation shell; verified against real vcvarsall with a synthetic Cyrillic value.
- Pinned LF checkout for native dependency patches and recipe sources so Windows line-ending
Generated
+1004 -650
View File
File diff suppressed because it is too large. Load diff
+13 -11
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["core", "dsp", "native", "xtask"]
exclude = ["core/vendor/tsclientlib", "core/vendor/tsproto", "dsp/vendor/sonora", "dsp/vendor/sonora-agc2", "native/vendor/libwebrtc-0.4.0", "native/vendor/webrtc-sys-0.3.53", "native/vendor/katex-rs-0.3.0", "native/vendor/mermaid-rs-renderer-0.3.1", "native/vendor/cpal-0.18.2", "native/vendor/i-slint-backend-android-activity-1.18.1"]
exclude = ["core/vendor/tsclientlib", "core/vendor/tsproto", "core/vendor/tsproto-packets", "dsp/vendor/sonora", "dsp/vendor/sonora-agc2", "native/vendor/libwebrtc-0.4.2", "native/vendor/webrtc-sys-0.3.55", "native/vendor/katex-rs-0.3.0", "native/vendor/mermaid-rs-renderer-0.3.1", "native/vendor/cpal-0.18.2", "native/vendor/i-slint-backend-android-activity-1.19.1"]
[workspace.package]
version = "0.1.7"
@@ -10,18 +10,19 @@ rust-version = "1.96"
publish = false
[workspace.dependencies]
base16ct = { version = "1", features = ["alloc"] }
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value", "preserve_order", "unbounded_depth"] }
thiserror = "2"
tokio = { version = "1", features = ["rt", "sync", "time", "macros"] }
slint = { version = "=1.18.1", default-features = false, features = ["std", "compat-1-18", "accessibility", "image-default-formats", "unstable-fontique-011"] }
slint-build = "=1.18.1"
slint = { version = "=1.19.1", default-features = false, features = ["std", "compat-1-18", "accessibility", "image-default-formats", "unstable-fontique-012"] }
slint-build = "=1.19.1"
cpal = "=0.18.2"
rubato = { version = "=5.0.1", default-features = false }
sonora = "=0.2.0"
sonora-ns = "=0.2.0"
libwebrtc = "=0.4.0"
webrtc-sys = "=0.3.53"
rubato = { version = "=5.1.0", default-features = false }
sonora = "=0.3.0"
sonora-ns = "=0.3.0"
libwebrtc = "=0.4.2"
webrtc-sys = "=0.3.55"
katex-native = "=0.1.1"
katex-rs = "=0.3.0"
mermaid-rs-renderer = { version = "=0.3.1", default-features = false }
@@ -29,16 +30,17 @@ cssparser = "=0.38.0"
[patch."https://github.com/ReSpeak/tsclientlib"]
tsproto = { path = "core/vendor/tsproto" }
tsproto-packets = { path = "core/vendor/tsproto-packets" }
[patch.crates-io]
sonora = { path = "dsp/vendor/sonora" }
sonora-agc2 = { path = "dsp/vendor/sonora-agc2" }
libwebrtc = { path = "native/vendor/libwebrtc-0.4.0" }
webrtc-sys = { path = "native/vendor/webrtc-sys-0.3.53" }
libwebrtc = { path = "native/vendor/libwebrtc-0.4.2" }
webrtc-sys = { path = "native/vendor/webrtc-sys-0.3.55" }
katex-rs = { path = "native/vendor/katex-rs-0.3.0" }
mermaid-rs-renderer = { path = "native/vendor/mermaid-rs-renderer-0.3.1" }
cpal = { path = "native/vendor/cpal-0.18.2" }
i-slint-backend-android-activity = { path = "native/vendor/i-slint-backend-android-activity-1.18.1" }
i-slint-backend-android-activity = { path = "native/vendor/i-slint-backend-android-activity-1.19.1" }
[profile.release]
lto = "thin"
+17 -10
View File
@@ -1,6 +1,6 @@
---
name: TeamsPeach
description: The installed TeamSpeak 6 client's own visual system, reproduced from its source values.
description: Native TeamsPeach's account-free visual contract, derived from TeamSpeak 6 reference evidence.
colors:
tsv-bg-dark: "#2b3346"
tsv-bg-light: "#f5f5f5"
@@ -100,10 +100,13 @@ components:
**North Star: "The official TeamSpeak 6 client, value for value."**
The owner asked for the installed TeamSpeak 6 client's design, without reinterpretation. Two earlier
TeamsPeach worlds (flat warm-neutral, then the Liquid Glass approximation) are retired. The target values
come from installed client 6.0.0.5163 (`main.css` sha256 `bc700401…`, `main.js` sha256 `9d6bea2e…`): theme
tokens from its webpack theme modules (`main.js` @92422 dark, @201685 light), scale tokens and component
geometry from `main.css`, layout constants from `main.js` (window slots @1273206). The extracted values
TeamsPeach worlds (flat warm-neutral, then the Liquid Glass approximation) are retired. The current
desktop visual reference is **TeamSpeak 6.0.0.5232**; see the [visual source map](docs/evidence/official-parity/visual-source-map.md)
for both manifest-checked bundle hashes, fixture scope, capture commands and comparison results.
The retained design values below are historically derived from **6.0.0.5163** (`main.css` sha256
`bc700401…`, `main.js` sha256 `9d6bea2e…`): webpack theme tokens (`main.js` @92422 dark, @201685 light),
scale and component geometry (`main.css`) and layout constants (`main.js` window slots @1273206).
Do not use those offsets as 5232 offsets. The extracted historical values
and source offsets are in `docs/evidence/official-parity/ts6spec-{shell,tree,chat,controls,settings}.md`.
Native stock theme data retains the official `--tsv-*` names in
`native/src/services/themes/stock.css`; `native/ui/` expresses the Slint geometry and presentation.
@@ -246,14 +249,18 @@ notifications opaque; forced colours use system tokens.
project links and installation details live on working subpages with back-focus restoration.
About retains TeamsPeach branding and real metadata; Report Issue targets the verified project tracker.
Content reporting, Terms and five source-position social tiles explicitly state their unavailable status.
- Whole-screen comparisons remain strict failures where state, content or geometry differs. The full
192-pair checkpoint passed 56; the subsequent four-panel 32-pair checkpoint still failed all whole-screen
comparisons. Runtime workflow success is not pixel parity. Build-specific evidence and residuals are in
`docs/evidence/official-parity/qa-parity-harness.md`.
- The current 5232 desktop comparisons use synthetic state, not a user account. Both native runs
completed all 20 scenes (dark/light × EN/RU at 1280×800), but neither passed a whole screen.
The strict comparator does not mask branding, account-only slots or caption differences.
The historical Electron 192-pair checkpoint passed 56; its subsequent four-panel 32-pair
checkpoint failed every whole-screen comparison. Runtime workflow success is not pixel parity.
See the [current visual source map](docs/evidence/official-parity/visual-source-map.md) and the
[historical QA record](docs/evidence/official-parity/qa-parity-harness.md).
## Do's and Don'ts
- **Do** take every new value from the installed client and cite its offset in the evidence specs.
- **Do** cite the source build and offset or measured scene for new values. Keep 5163 extractions
separate from 5232 capture evidence.
- **Do** keep native caption colors aligned with `--ts-new-header-bg` and `--tsv-font-color` where supported.
- **Do** retain stock token names and the explicitly supported native theme-import subset; no DOM fallback.
- **Don't** reinterpret, restyle or "improve" the official look; deviations above are product constraints.
+511 -3
View File
@@ -1,5 +1,511 @@
# TeamsPeach ↔ TeamSpeak 6 server features
## Current Windows account-free checkpoint (2026-11-26)
**Channel banner fetch (Windows):** On private classic beta14, `fetch_banner` returned the exact seeded 74-byte PNG and Slint painted its color inside the selected channel row. A restricted channel with the same file returned `PermissionsClientInsufficient`. Replacing the banner with a missing file cleared the artwork without changing the neighboring row or selection outline; the former banner token was rejected. An HTTPS reference produced no tree fetch action. Raw command validation also rejects zero and unknown fields. See the [live receipt](docs/evidence/official-parity/channel-fetch-banner-beta14.md) for scope and reproduction.
**Server host button (Windows):** On private beta14, the Slint editor rejected 1,025 ASCII characters in each of the tooltip, link URL, and image URL fields. Cancel preserved the seeded values. A second guest independently verified three single-field saves, a combined save, and exact restoration; fresh editors showed the acknowledged values. The 1,024-character editor limit is not a measured server limit. The `.invalid` URLs were never opened or downloaded. See the [host button receipt](docs/evidence/official-parity/server-host-button-beta14.md).
**Server host banner (Windows):** On private beta14, Slint rejected oversized URLs, invalid interval and mode values, and a wrong server-name confirmation. Cancel preserved both seeded URLs, interval 120, and mode 0. Each of the four controls saved alone, then all four saved together, and the original values were restored. A second guest independently read all four fields after each step, and fresh editors showed the acknowledged values. The URLs used `.invalid`; no browser or image fetch, rendering, or refresh timing was tested. See the [banner receipt](docs/evidence/official-parity/server-host-banner-beta14.md).
**Acknowledged channel edit across a live reconnect:** On private Windows beta14, a second guest confirmed the first Slint topic edit before the initiating tab disconnected. The same tab reconnected under a different guest identity and submitted a new edit to the same channel. Only completion delivery was gated. Releasing the original success left the replacement's busy draft, channel details, status, and pre-existing disconnect error unchanged. The replacement's own success closed its editor, and the observer still saw the replacement topic. This checks delayed delivery of a successful edit, not rollback or a disconnect before server acknowledgement. See the [live receipt](docs/evidence/official-parity/channel-edit-replacement-beta14.md).
**Server total file-transfer bandwidth (Windows):** On disposable beta14, the Slint editor rejected -1 and 9,007,199,254,740,992 independently for each field (editor range 0 through 9,007,199,254,740,991). Cancelling preserved the finite download/upload baseline of 1,048,576 / 2,097,152 bytes/s. A fresh editor and independent second-guest server_info confirmed a download-only edit, an upload-only edit, and a paired edit, with exact restoration after each save. No files were transferred, so this proves configuration and readback, not rate limiting or throughput. See the [snapshot receipt and fixture command](docs/evidence/official-parity/server-bandwidth-beta14.md).
**Server transfer quotas (Windows):** On disposable loopback beta14, the fixture granted only the additional quota permission and seeded finite download and upload quotas of 64 and 96 MByte. The Slint editor accepts integers from 0 through 9,007,199,254,740,991; the test rejected -1 and 9,007,199,254,740,992 for both fields and retained the invalid drafts with field errors. Cancelling preserved the seeded quotas. An independent server_info request from the second guest and a freshly opened editor both confirmed the saved values of 128 and 192 MByte, then exact restoration to 64 and 96 MByte. The test required those exact seeded wire values before editing; it did not convert an unlimited u64::MAX value, exercise quota enforcement, or transfer files. The focused test passed and the fixture stopped.
**Server capacity and reserved slots (Windows, 2026-11-28):** On a disposable loopback beta14 with permission to edit both fields, the Slint Server Settings form kept invalid drafts of -1 and 65536 with field errors for each input. Cancelling a valid draft preserved the original 8 maximum clients and 0 reserved slots. Saving 7 and 1 left six public slots for the two muted guests. A fresh editor and an independent server_info request from the second guest confirmed both saved values and their restoration to 8 and 0. The server name, welcome text, host message and host message mode remained unchanged. One focused test passed and the fixture stopped. Admission at capacity, use of reserved slots, permission loss, and reconnect were not exercised.
**Server host message:** Before integration, a guest granted b_virtualserver_modify_hostmessage on private beta14 used Edit Server to set a two-line host message and its mode. The editor rejected an 8193-character draft and mode values -1 and 4. Cancellation left original properties unchanged. A second guest read back the saved values and their restoration without a change to the server name or welcome message. This checks administration and readback, not display of the host message on login.
**Property-specific server edit permissions:** A guest on private beta14 could open Edit Server with only welcome-message rights. An attempted rename left the draft open with a visible server refusal. Saving a welcome-only edit succeeded; the other guest confirmed the unchanged name, updated welcome, then restoration. A separate authorized run verified rename and the next confirmation name. The offline connection worker rejected a delayed server_edit refusal delivered after session replacement without changing the replacement server. No live network disconnect was timed against a successful edit.
**Editing the server name and welcome message:** On private beta14 the Windows editor rejected overlong fields and did not accept the proposed new name as confirmation. Cancelling preserved both original values. Saving a new name and two-line welcome updated the detail title, properties and the confirmation name of the next editor on the same server UID. A second guest independently read both values, then verified their restoration. Only name and welcome permissions were added to the disposable fixture; no other server property was changed.
**Default channel and guest arrival:** On a private beta14 server the Windows Create Channel form made a permanent room the sole default. A fresh guest connecting without a channel landed there. Setting a second permanent room as default in Edit Channel transferred the flag without changing either ID; a second new identity landed in that room. Cancellation preserved the preceding default, and each reopened editor showed the saved flag. Neither guest had a saved channel or supplied a channel password. Server restart and bookmark-specific channel overrides were not exercised.
**Channel encryption setting:** On private beta14 the guest's explicit encrypted-channel creation was initially refused with missing permission 129. With b_channel_modify_make_codec_encrypted granted, selecting Enabled at creation produced channel_codec_is_unencrypted=0 in channel_info. Cancelling an edit preserved that flag; disabling and re-enabling encryption produced 1 and 0 respectively. Each fresh editor displayed the inverse of the server flag for the same channel ID. No voice packets were sent or inspected, and the virtual server encryption policy was not changed.
**Channel banner properties:** On private beta14 the native channel editor rejected a 1025-character address. Cancelling a draft preserved the initial URL and mode. Without b_channel_modify_banner the server refused the save (permission 119). With that permission the roster and reopened editor showed the test URL in modes 1 and 2, then an empty URL and mode 0 after clearing. The reserved .invalid address was not evidence of image loading or rendering.
**Channel codec latency factor:** On private beta14 the editor rejected 0 and 11, and cancellation preserved the original channel_info property for the same room ID. Saving a different allowed factor produced the explicitly chosen value in channel_info and in a freshly opened editor. The initial roster did not provide a value in the supported range; the form default was not counted as a server acknowledgement. No end-to-end audio delay was measured.
**Channel talk power threshold:** On private beta14 the moderator's Slint Edit Channel form rejected values outside the signed 32-bit range. Cancelling a change kept the room at 0 on both rosters; saving 50 updated both rosters and a newly opened editor. In that room the two input-muted guests then exercised requests, withdrawal, grant and revoke; the guest's unauthorized grant was refused. This verifies the field and protocol moderation state, not microphone speech.
**Permanent and semi-permanent channel types:** On private beta14 the Windows Slint picker created a room of each type. Cancelling creation left no visible room; cancelling a type change preserved the original roster value. Saving permanent to semi-permanent and semi-permanent to permanent kept each room's server-assigned ID. A fresh editor showed the acknowledged type. The server was not restarted between observations, so this verifies the two protocol flags and their UI, not retention after server restart.
**Temporary channel expiry:** On private beta14 both guests saw a temporary room created with a 30-second delete delay. The create form rejected -1; the edit form rejected 4294967296. Cancelling an edit preserved 30. After saving 4, a fresh editor and both rosters showed 4. Once the last occupant returned to the lobby, the empty room was still present one second later and then disappeared from both rosters. This checks delayed expiry, not exact timer precision. The fixture needed b_channel_modify_temp_delete_delay and i_channel_create_modify_with_temp_delete_delay set to 30 (permission ID 109).
**Creating and editing a channel across two guests:** After the owner created a protected temporary room and saved its topic on private beta14, another guest opened the same channel ID from its own tree. The server refused that guest's topic edit; the editor showed PermissionsClientInsufficient and retained the unsaved text until cancellation. Both rosters kept the owner's topic. A separate offline connection-worker regression delivered the old create and edit refusals after session replacement and observed TargetChanged without inserting a room or overwriting the replacement room's name or topic. This is not a timed network disconnect during a successful mutation.
**Regular channel group lifecycle:** On a channel-group-only private beta14 fixture, two identically labelled New Group actions initially led the test to request a server group; the server refused it. The create controls and editor titles now identify the group kind. The corrected Slint workflow created a regular channel group, renamed the same cgid, cancelled deletion, rejected the old name and deleted after exact confirmation. Independent lists from the second tab retained all other IDs and names. Separate offline tests held real core refusals across session replacement for create, rename and delete of both group kinds. Live network reconnect during the command, template/query group administration and membership changes were not exercised.
**Regular server group lifecycle:** Two private beta14 guests checked creation from Permission Groups, rename under the same new server group ID and deletion after one typed confirmation. Cancelling either edit preserved the group, and the old name did not confirm deletion after rename. Independent server-group lists from the second guest preserved every pre-existing ID and name. The initial rename was refused with permission 168 (i_group_modify_power). The successful fixture granted create and delete plus modify power 75. This run did not mutate channel groups or template/query groups.
**Refreshing sparse group lists:** On two private beta14 tabs the refresh projection consumed independently requested server-group and channel-group lists. When a wire row lacks its type, the matching typed roster for the same server and group kind supplies it only if the numeric ID and name agree. An explicitly invalid type or mismatched group fails the refresh; template and query rows do not gain regular-group actions. No group mutation was sent in this read-only trial.
**Administration context:** On two private beta14 tabs the rendered Permission Groups pane matched independent group-list and admin_context replies for the viewed generation and server UID. A partial-reply regression showed the catalog refusal without losing valid roster groups, and stale server identity or generation was rejected. The parser accepted an empty argument object and rejected an unknown property. The partial refusal was supplied in the regression test, not forced by changing server rights in the live run.
**Editing family capacity:** On private beta14 a temporary root room started with a client limit of 2 and family limit of 6. Cancelling inheritance retained 6. Saving inheritance changed the native roster value to `inherited`; turning it off and setting 4 restored a numeric family limit. The channel ID and its own limit of 2 remained unchanged, and fresh editors showed the acknowledged flag, numeric limit when applicable, and no unlimited-family flag. This tested editing and readback, not admission under the limit.
**Channel order on create and edit:** On private beta14 the Slint Create Channel form inserted a temporary root room first. Both guest rosters showed its predecessor as 0 and the former first room pointing to the new ID. Cancelling a subsequent edit preserved that chain. Selecting the former first room as predecessor and saving reversed the two links on both rosters without moving either guest. A newly opened editor showed the acknowledged predecessor ID. The fixture grants b_channel_create_with_sortorder and b_channel_modify_sortorder. A separate form test covered same-named siblings and clearing an obsolete predecessor on parent changes.
**Moving an occupied channel:** Cancelling Move Channel preserved the original parent and predecessor on both guest rosters. After confirmation, both guests saw the same temporary room ID as the first child of the lobby, with the occupant still inside. Reopening Move Channel showed the lobby ID and predecessor 0. The private fixture granted b_channel_modify_parent, b_channel_modify_sortorder and b_channel_create_child; the first move was refused with permission ID 86 (i_channel_max_depth). Setting this fixture-only depth limit to 2 allowed the move. Separate tests covered duplicate sibling labels, missing permission diagnostics and late replies across session replacement. No real network interruption was timed against the move.
**Deleting an occupied channel:** Two connected guests observed the same temporary root channel. In its Slint context menu, an incorrect confirmation name kept the editor open; cancellation left the creator in the room. A confirmed forced deletion by the other guest showed the server's PermissionsClientInsufficient error and left the room occupied. The creator's confirmed deletion returned the occupant to the lobby and removed the room ID from both rosters and both viewed trees before either guest disconnected. Separately, the connection actor rejected a delayed offline deletion refusal after session replacement with the same numeric room ID; it did not change the replacement selection or roster. No real network reconnect was timed against the server acknowledgement.
**Channel capacity at creation:** The private beta14 guest created temporary root channels with finite limits (2 and 6), both limits unlimited, and a finite client limit with family capacity inherited. A fresh editor for each server-assigned channel ID showed the requested mode. Invalid numeric bounds stayed in the draft and cancellation discarded the changes. This verifies the three capacity flags, not participant admission, enforcement in subchannels, or the full channel CRUD workflow.
**Bookmark display name:** Clearing the name in the Slint editor displayed the existing address under the same sidebar ID. A 65-character name was rejected before saving; a blocked preferences write preserved the prior record. Two restarts retained the fallback name and address. Separate store tests exercised plain bookmark fields, keybind migration and restored chord dispatch; they do not establish network login or OS shortcut delivery.
**Voice through the saved endpoints:** On private beta14, two native guests exchanged generated voice using a capture backend that accepted only the saved `qa-input` and a voice playback backend that accepted only `qa-output`. After each unmute the receiver produced at least three new non-silent blocks; after mute it drained to silence. Separate callback tests injected CPAL device loss during partial playback and after capture: playback returned silence, capture published no new block, and neither lost stream could resume. Session retirement and epoch changes rejected stale PCM in separate tests. This covers the Windows preference behavior, not physical hot-plug, acoustic echo cancellation or an official peer.
**Saving voice device choices:** Using an isolated device catalog, the Windows Slint selectors saved distinct input and output IDs. Attempts to switch to the system defaults during a failed preferences write left the file, both selectors and the acknowledged engine routes unchanged. Two restarts retained both choices without starting hardware. The input backend and missing-output connection checks below cover first use; this selector test did not stream PCM through either fixture ID.
**Saved voice devices at startup:** The Windows Connect form joined private beta14 with an unavailable output ID saved in the disposable profile. Without any test-side output selection, playback reported audio_device_missing, neither device started, and the acknowledged connection address was retained. In a separate offline test the first private capture attempt on each of two launches supplied the saved exact input ID to a test backend, which refused it without opening a microphone. These tests do not verify a successful physical device open or hot-plug.
**Voice output level:** The Windows Slint Audio control saved -200 dB. An attempted change to 0 dB failed on a blocked preferences write. After two restarts, the first incoming beta14 tone showed the sender talking but produced no non-silent samples at the synthetic receiver. Setting 0 dB restored sound; at -6 dB, mean block energy was between 20% and 31% of unity. Separate regressions verified live AGC and that master voice gain does not affect stream gain. No physical device or official peer participated.
**Connection retry after password refusal:** On private beta14 the Windows Connect form reported the failed login and retained the previously saved address. The tab remained disconnected, with no roster or audio device starts. A request with the retired session key returned TargetChanged. Reopening Connect on that tab showed an empty password field. The correct fixture password admitted the muted identity, and the acknowledged address survived a restart even though the explicitly selected playback device was unavailable. Separate tests checked pre-network argument rejection and capture handoff across viewed tabs.
**Microphone toolbar during a call:** On private beta14 the Slint toolbar callback unmuted, muted and unmuted the input owner while the second guest remained input-muted. Both rosters agreed on the sender's microphone flag. Muting revoked the original capture permit and the synthetic receiver drained to silence; unmuting issued a different permit and produced new non-silent output blocks. Two focused native tests passed, including the VAD settings regression. This verifies set_audio with generated voice, not a physical headset or an official peer.
**Unconfirmed microphone mapping:** On private beta14 two disposable guests stayed muted after both a toolbar unmute and a local unmute shortcut handler were refused with device_mapping_required. Both core replies and both rosters retained input/output mute. No capture permit was issued, neither audio device started and the mapping refusal preceded the microphone permission request. Three targeted Windows tests passed, including missing-device handoff and toolbar routing while viewing another tab. The test did not use a physical keyboard or a physical microphone.
**Transmit control from Audio settings:** On private beta14 the sender's Slint settings callbacks disabled PTT, enabled volume-gate VAD, changed its threshold, and disabled VAD again. The synthetic microphone continued producing the same tone. Both the sender's transmitting flag and the other guest's talking indicator went on in direct mode, off at 0 dB, on at -45 dB, off at 0 dB and back on when VAD was disabled. The existing PTT release-delay test passed on the same fixture. No physical microphone or speaker was opened.
**Transmit detector switch during a burst:** Two disposable clients on private beta14 used a generated 900 Hz tone and a synthetic receive output. Direct mode delivered the tone. Switching mid-burst to a -10 dB volume gate invalidated the old capture epoch and ended the burst without an explicit end_audio. Fresh below-threshold frames were accepted locally but produced neither a talking indication nor non-silent receiver blocks. Lowering the threshold to -40 dB preserved the epoch and made the same tone audible again. This checks the typed core command and receive path, not settings UI or physical capture.
**Playback DSP command boundary:** A fresh disconnected stdio core accepted both boolean values of agc. It returned bad_request for a missing field, null, a number, a string, and an extra key. Five separate native regressions covered partial and old playback blocks, wrong sample rate, privacy epochs, reconnect and saved device recovery. Combined with the live gain measurement below, this verifies set_playback_dsp on Windows with generated audio; it does not establish physical headset or official-client parity.
**Playback AGC during a call:** On private beta14 two disposable guests exchanged a generated quiet 1 kHz Opus tone. The receiver's Slint Audio settings callback switched the selected output profile off, on and off. In settled windows of at least 20 non-silent synthetic output blocks, mean block energy with AGC enabled was at least four times the first off window; the final off window was within 25% of baseline. The separate detached-UI voice test also passed. No physical device or official client participated.
**Playback AGC before connecting:** A ready disconnected core acknowledged the explicit output device's saved AGC setting and the template setting when no device override existed. No input or output device started. With identical generated Opus packets, a separate core test measured more than four times the reference energy for quiet audio after AGC settled; disabling AGC restored sample-identical PCM. Three focused core tests and two native tests passed. This does not verify a live settings toggle during a call, physical output or official-peer voice parity.
**Temporary server passwords:** On private beta14 the Windows panel created a disposable 300-second rule for the server's default channel. A separate list request confirmed the value (pw_clear), issuer, description, expiry and tcid=0. Cancelling deletion kept the rule; confirming removed it from the panel and the server. The test used a guest with b_virtualserver_modify_temporary_passwords and did not log passwords or test login with the issued credential. A separate WebQuery-created fixture record produced ClientInvalidId when read by the native guest; cross-issuer listing is not verified.
**Clearing the ban list:** On private beta14, the native panel required the displayed server name before deleting all bans. Incorrect input kept the dialog open; cancelling retained both seeded ban IDs. Correct confirmation cleared both rows, an independent ban_list request returned no rules, and the empty panel no longer offered the action. This test used a disposable server with exactly two known rules.
**Creating a timed ban:** On private beta14, the native Add Ban form rejected an empty target and a negative duration. Cancelling a valid draft left both seeded rules and IDs intact. Submitting a unique unused nickname pattern created one 60-second rule; the refreshed panel and an independent ban_list reply agreed on its ID and reason. No connected participant matched the pattern.
**Single ban deletion:** On private beta14 a guest with list and delete permission selected the one-hour fixture rule in the native ban panel. Cancelling preserved both original ban IDs. Confirming once removed only the selected ID; the refreshed panel and an independent ban_list request agreed that the permanent rule remained. No clear-all operation was issued.
**Ban list:** On private beta14 a guest with only ban-list read access opened Banned Users from the Slint server menu. The permanent and one-hour fixture rules matched the independent core reply, including their reasons, expiry and row IDs. Without read permission the panel showed PermissionsClientInsufficient and no rows. Separate tests covered malformed expiry, unknown arguments, panel closure and stale sessions. The native client did not create or delete a ban in these tests.
**Replacing a chat attachment:** On classic beta14, a disposable Windows guest chose a file with the native picker and received a ts3file link. Choosing another version under the same name produced the Replace action. Cancelling kept the original eight bytes; confirming uploaded the selected twenty bytes even after the local source changed again. The remote listing and both downloads agreed. Replacement required file delete power in the scratch channel in addition to upload, browse and download rights. A separate picker test rejected a selection from a retired session. Neither test exercised S3 or sent a chat message.
**Scheduler refusal recovery:** With a 2 MiB/s download budget, the scheduler configured the running tab for 1 MiB/s before dispatching a second tab's start or resume. In both cases the second core's simulated refusal propagated to the caller and the running tab received a 2 MiB/s configuration afterward. Three focused service tests passed. A separate classic beta14 test verified two overlapping 4 MiB downloads against the saved 1 MiB/s aggregate ceiling and compared both outputs with the source pattern. The refusal was injected only in the service test, not on the wire.
**Channel password edits:** Two disposable beta14 guests verified password rotation through the Slint channel editor. An oversized replacement stayed in the field with an error. Reopening after a successful change did not reveal the replacement. Submitting a blank password with a topic change preserved protection: the old password failed and the replacement admitted the second guest. Explicit removal cleared the protection flag on both rosters and the guest could rejoin without a password. No bookmark or server-login password was involved.
**Phonetic channel name:** On private beta14 the Slint Create Channel and Edit Channel forms rejected a 256-character phonetic name inline. Creating a temporary channel preserved its separate pronunciation in the roster and editor. Cancelling a replacement retained the original; saving it changed the pronunciation for the same server channel ID without changing the tree name or description. This covers the stored metadata, not speech synthesis.
**Opus codec selection:** On private beta14 an explicit Opus Music create was refused without the codec permission. With b_channel_create_modify_with_codec_opusmusic granted, the Slint Create Channel picker created a temporary root room with opus_music in the server roster. Cancelling an Opus Voice edit kept Music. Saving the change produced opus_voice for the same room ID and a fresh editor showed Opus Voice with the original description. This verifies channel_create.channel_codec and channel_edit.channel_codec for the two Opus modes, not legacy codecs or audio encoding and playback.
**Channel capacity at creation:** On private beta14 the disposable guest had b_channel_create_with_maxclients and b_channel_create_with_maxfamilyclients. The Slint toolbar form retained -2 and 2147483648 with field errors and discarded a cancelled draft. After creating a temporary root channel, Edit Channel for its roster ID showed 2 clients and 6 family clients, with unlimited and inherited modes off. This verifies the two numeric creation fields, not admission or child inheritance.
**Channel capacity edits:** On loopback beta14 the Slint editor saved limits of 3 for the channel and 4 for its family. Reopening showed both numbers with both unlimited switches off. Values below -1 and above 2147483647 produced field errors. Cancelling a draft that changed the numbers and switches preserved 3/4 with both switches off. After submitting unlimited mode for both, a fresh editor showed both switches on and both numbers at -1. This covers numeric limits and unlimited flags when editing a temporary root channel, not child inheritance or admission at capacity.
**Channel description at creation:** On private beta14 with b_channel_create_with_description granted to the disposable guest, the Windows Slint toolbar form retained an over-limit draft with an inline error and discarded a cancelled draft. Submitting a two-line description created a temporary root channel; a separate channel_description request for its roster ID and a newly opened Edit Channel form both returned the exact text. This covers the creation property, not other optional fields or the whole channel administration workflow.
**Withdrawn updates:** The loopback server first offered native 0.1.8 to a disposable 0.1.7 Windows installation. After download, the listing changed to only 0.1.6 and 0.1.7. A second check returned UpToDate, no offer, zero transferred bytes, an empty update cache and no installable package. No second package was requested. Six focused tests passed, including candidate selection and the About selector. Combined with the channel and integrity runs below, this covers checkForUpdates and updateChannel on this fixture, not an actual installer or a public-feed availability check.
**Explicit update download:** On the local Windows release fixture an active session deferred automatic download, while explicit download retrieved the offered package. A short response failed the size check and a changed payload failed SHA512. The short package left no cache entry, could not be installed and did not change the disposable executable. The fixture uses blocking reads on accepted connections. No installer was launched.
**Update channel:** The About selector changed Preview to Stable in a disposable Windows profile. Two restarts retained Stable in both the selector and updater. A failed attempt to save Preview left selection, service and file unchanged. With a loopback release fixture, switching channels cleared the previous offer and check time; a late Preview check or download did not publish into Stable. Nine focused tests passed, including checksum rejection and call-aware download deferral. The installed application was not replaced.
**Local profile persistence (Windows, 2026-11-28):** Nine focused Rust tests passed on disposable profiles. Slint kept duplicate-chord warnings in the correct profile when two profiles reused a binding ID. After restart the active profile's F9 push-to-mute worked and the previous profile's F8 did not start PTT. A 33rd profile was rejected without changing the saved file. Shortcut events were supplied at the native platform boundary; no system-wide registration or physical keyboard was exercised.
The offline folder editor covered generated IDs, unnamed labels, moving folders, depth and capacity limits, restart, failed saves and recovery of orphaned or cyclic parents. The Contacts Ignore and Chats Remove controls preserved UID-based filtering across restarts: a renamed blocked contact stayed blocked, but another UID with the same name and recycled client number was delivered. Incoming chat events were synthetic; live send and failed-send draft retention were not verified by these tests.
**Voice toolbar ownership (Windows beta14):** With the observer tab in view and the other tab owning input, the microphone button muted the input owner. The speaker button then restored and disabled that owner's output without unmuting its microphone. The toolbar and both server rosters agreed after each change; the observer kept both mute flags. No physical input or output was opened.
**Cross-tab deafen (Windows beta14):** While one tab transmitted continuous synthetic input, the native deafen action on the receiving tab stopped and then restored its talking indicator. Its microphone stayed muted. The sending tab retained its original capture permit, kept transmitting and kept producing fresh capture blocks through both changes. No physical devices were opened.
**Voice playback after UI detach (Windows beta14):** A receiver with a synthetic output rendered a tone from a second disposable core. The first burst drained to silence, the receiver released its UI attachment, and a fresh burst produced new non-silent output blocks without reattaching or replacing either session. Notifications and comfort noise were disabled. Separate mixer tests checked gain and isolation when closing a connection. No physical speaker or microphone was opened.
**Playback authorization:** On Windows, generated PCM stayed silent when the initial roster lacked a local client ID. An explicit boolean output_muted=false admitted the samples; a missing flag or the string "false" closed the route again. Separate mixer tests checked volume and the surviving connection's samples after another route retired. No physical speaker was opened.
**Native capture ingress on Windows:** The synthetic 48 kHz input passed through the capture worker, DSP and embedded core to another beta14 client. Separate tests checked the full 960-sample frame against the timestamp of its first half (200 ms inclusive), discarded stale frames without retiring a valid permit, and discarded partial frames on mute or rebind. During input handoff the old permit was unusable before the new core's acknowledgement; viewing a third tab did not transfer ownership. Generation changes invalidated the old capture epoch. These checks do not measure a physical microphone or speaker.
**Capture release during a 600 ms stall:** A core regression revoked the capture epoch with one frame queued, one dequeued, and one held by VAD. The transport guard rejected the dequeued frame immediately. After a 600 ms consumer stall, the queue contained only an end marker; the old dequeued and preroll frames could neither enter encoding nor pass the send guard. A fresh frame with the new epoch started a new VAD burst and passed the guard. No network or devices were used in this stall test; live PTT and whisper release were checked separately on beta14.
**PTT key on Windows:** The Audio recorder rejected Ctrl+F9 and a failed atomic save without replacing F8. Cancel restored the old binding. Saving F10 retained the new key across two restarts. On private beta14 with continuous synthetic input, the old F8 did not transmit; F10 started and ended speech at the receiver and respected the selected tail. This checks native local key events, not OS-wide registration.
**Overlapping PTT and Push to Mute (Windows beta14):** With F8 held and both peers reporting speech, F9 stopped transmission and cleared the receiver's talking indicator without changing the visible mute flags. Releasing F9 with F8 held restored speech; releasing F8 before F9 left both peers silent. A later F8 hold still transmitted. These were local native key events with a synthetic capture backend, not OS-wide shortcut registration.
**Local whisper keys on Windows beta14:** Two saved list shortcuts were driven through native platform key events with the receiver viewed and the sender owning input. F9 replaced F8; releasing F8 preserved the F9 route. Synthetic PCM sent through the current manager permit produced remote talking and a sender-matched entry in the receiver's whisper history. Releasing F9 revoked the permit and ended remote talking. Separate worker tests checked that capture blocks acquire the whisper epoch when bound and do not carry it into an ordinary rebind. No physical device or OS-wide shortcut registration was used.
**Group whisper delivery (Windows beta14):** Two disposable Rust cores shared the default Opus channel with receive policy set to Allow All. In current-channel mode, `duplex_qa --group-whisper` delivered tones and sender-matched whisper notifications for the receiver's server and channel groups. Between those deliveries, transmissions to an existing server group and channel group the receiver did not belong to produced no playback, talking start or whisper notification on that same connection. Both disconnects were confirmed. This does not exercise a Slint hotkey, a physical device or other channel scopes.
**Channel subscriptions across tabs (Windows beta14):** Two muted guests stayed in the lobby. From the first tab's tree menus, Unsubscribe All cleared both accessible test channels, Subscribe enabled only channel A, Unsubscribe cleared it, and Subscribe All enabled both. Each transition required a newer snapshot; the second tab retained its flags and menu actions. Subscription to a third channel with needed subscribe power 100 returned a visible PermissionsClientInsufficient; that channel remained unsubscribed on both tabs. Separate tests covered stale menu tokens, malformed stdio arguments and refusal ownership after a tab switch or replacement session. Reconnect during acknowledgement was not forced on the live server.
**Channel reads across deletion:** Protocol tests fed deletion of the requested channel, reuse of its ID and a replacement description before the pending acknowledgement. Both channel_info and channel_description rejected the original request; deleting an unrelated channel preserved the requested description. The Windows beta14 channel editor separately passed multiline and empty description readback. ID reuse was tested with protocol events, not by forcing reuse on beta14.
**Classic uploads on Windows (2026-11-27):** Two muted tabs restored a 1 MiB/s upload limit and two upload slots saved through Slint. Both 4 MiB uploads made simultaneous progress; the combined rate stayed within the configured ceiling plus 192 KiB sampling allowance. Lowering the slot count to one paused the newer same-tab upload while the older upload and the other tab finished. Explicit resume completed the paused upload. All five files were downloaded and compared byte for byte. The ignored test `two_connected_tabs_share_the_saved_upload_rate_and_slots` requires a disposable classic beta14 on `127.0.0.1:19987` with an empty channel named `TeamsPeach Upload QA` granting the two guests upload, browse and download rights in that channel. No HTTPFT or S3 result is implied.
**Permission Groups on Windows (2026-11-27):** On both tabs of a private beta14 fixture, the rendered rows matched the regular groups in independent server and channel group list replies. The row menus and creation actions retained the viewed connection and matched its permission hints. Separate model tests checked one-list replacement (including an empty reply), equal IDs across catalogs, invalid replies and late panel results. No group was created, renamed or deleted on the live server.
**Server Log on Windows:** On private beta14, granting only b_virtualserver_log_view allowed a guest to read the virtual server log. The displayed lines matched an independent forward read from position zero. The instance log remained inaccessible: the editor displayed PermissionsClientInsufficient and retained the submitted options. Cancelling or submitting invalid bounds did not open a log panel; switching tabs invalidated the old form. Separate tests covered literal text, order, metadata-only rows, empty and malformed replies. To reproduce the positive test, enable a private runtime log directory on the disposable fixture after bootstrap. No log contents were printed.
**Server Info on Windows:** Two muted beta14 guests opened the server tree row's menu in turn. The rendered name and welcome message matched a separate server_info response for each connection, and the edit action retained the viewed tab's session and server UID. Model tests rejected obsolete results after Back, a new connection generation or a different UID. No server settings were changed.
**Protected move destination:** On private beta14 the move confirmation opened with an empty secret field for a protected destination. An oversized multibyte password and a tab were rejected in the editor. Cancelling left the two guests in their original channels. A command-builder test checked that a 1024-byte password including surrounding spaces was preserved. This does not establish a successful server-authorized participant move.
**Move to Own Channel:** With two muted beta14 guests the action was absent in the same channel and available once the initiator entered a separate temporary channel. The unprotected destination had no password field. Cancellation and the server's permission refusal left both guests in place; submitting an open confirmation after the initiator changed channels reported a changed target. No successful privileged move was observed.
**Client database panel:** Without list permission the disposable beta14 guest saw PermissionsClientInsufficient and no database rows or active search target. With b_virtualserver_client_dblist and b_virtualserver_client_dbsearch, listing, nickname search and UID search returned the same roster nickname, UID and positive database ID in the same session. The Windows smoke located the rendered search selector and submitted each mode through the Slint callback; it did not drive the dropdown or Enter key. No database entry was edited or deleted. Separate tests covered page bounds, Unicode search limits and stale query results.
**Channel codec quality:** The create form rejected 11 and created a temporary channel at quality 5. The edit form restored 5, saved 7, and retained an invalid -1 with a field error. Cancelling a draft of 3 left quality 7 in both the server roster and a newly opened editor. The check exercised server properties, not encoded audio quality.
**Channel rename:** In the private beta14 channel editor, a 41-character name remained in the form with a validation error. Cancelling a replacement draft preserved the original name. A 40-character rename was acknowledged on the same channel ID in the roster, Slint tree and reopened editor; the topic and the lobby name stayed unchanged.
**Channel upload chooser on Windows:** The native multi-file dialog returned exact names and sizes for two regular files. Cancellation, a reconnect while the picker was open, and selection of 101 files produced no usable upload batch. The staging regression also verified that changing a source after selection dropped staged bytes and issued no tokens. Five focused checks passed. This covers selection and session ownership, not receipt of uploaded bytes by a server. Mobile pickers were not changed or tested.
**Download destinations across tabs:** With Always Ask saved, a restarted Windows runtime hid the default chooser but retained the approved folder. Cancelling a one-off picker queued nothing; a picker held across reconnect was rejected. The first tab downloaded into its one-off folder. With both guests connected, disabling Always Ask on the second tab restored the approved folder and published the same seeded bytes there. The first copy remained intact. No upload or mobile picker was exercised.
**Download slot reduction:** After restoring two download slots from disk, two guests on private classic beta14 ran three downloads: two on one tab and one on the other. Changing the limit to one in Slint paused the newer same-tab transfer without publishing its partial file. The older transfer and the independent tab finished; the paused transfer completed only after an explicit resume. All three 4 MiB files matched the source pattern. Upload slots were not exercised on the wire.
**Shared download rate:** After setting 1 MiB/s through Slint and restarting the runtime, two tabs downloaded separate copies of the same 4 MiB classic beta14 fixture. Both cores reported positive progress at the same time. From that sample to final publication, their remaining combined bytes fit the 1 MiB/s ceiling with 192 KiB of allowance for in-flight chunks and sampling. Both complete files matched the seeded pattern byte for byte. This covers limitDownload and downloadMiB, not a two-tab upload rate or a hard per-packet bandwidth limit.
**Channel file mutations on Windows (2026-11-27):** On private classic beta14, a guest opened the empty, non-default permanent channel named `TeamsPeach Directory QA` with directory creation, rename, delete and browse rights. The native browser created and renamed a folder; cancelling deletion preserved the renamed folder, and confirming deletion removed it. Independent root listings matched the browser after each operation. In a separate temporary channel, a permission refusal remained visible and the listing stayed empty. Cancelling a rename of a seeded file or submitting its original name also left it unchanged.
**Microphone handoff failure:** With two private beta14 guests, viewing the second tab left the first capture permit valid. Choosing Use Microphone for the second tab with an unavailable exact output endpoint reported the device error, revoked the original permit, left no usable new permit and started no devices. Notification output was configured as None. Seven focused Windows checks passed, including connect-form persistence and capture revocation. Successful PCM delivery across a live UI handoff was not tested here.
**Remembered connection address:** On private beta14, a Windows Connect form replaced the saved address only after the muted guest joined. With a missing exact WASAPI endpoint, the playback error remained visible, neither audio direction started, and a fresh runtime restored the new address without connecting. A separate offline Slint test covered cancellation, refusal and a blank second tab. These checks do not verify swapping microphone owners between live connections.
**Central Matrix exclusion:** The native server-chat test rendered a matrix: room URI as non-interactive text and a matrix.to HTTPS room link as an external-link confirmation. Cancelling that prompt preserved the exact server conversation and its unsent draft. Together with the empty offline Chats check, this covers the account-free boundary, not central or server-hosted Matrix transport. Neither a browser nor a Matrix server was contacted.
**Account and Remote Apps exclusions:** An isolated Slint window showed local identity settings, no Account or Remote Apps category, and a disabled account-only private-message setting with the account requirement. Attempting that setting and then sending from empty offline Chats left no conversation, tab, login dialog or active server connection. The ordinary server-chat Matrix notice was tested separately. This verifies the native UI boundary, not account interoperability or a network traffic audit. An empty chat alone does not establish what a stale central-room link does when another conversation is open.
**Block Incoming Whispers shortcut (excluded):** The reference declares ActivateBlock, DeactivateBlock and ToggleBlock without a demonstrated dispatcher. Importing those modes in a disposable version 2 shortcut profile produced an explicit diagnostic, no local down/up action, and no global registration candidates; the profile bytes and a working Reply Whisper chord were preserved. The supported receive-mode selector is separate. No OS global shortcut was registered.
**Whisper sender identity on Windows:** The native client records the UID and nickname captured by the receiving core. A later roster cannot turn an unknown sender or a recycled client number into a reply target. On private beta14, two diagnostic cores matched the receipt to the sender roster under Allow All, observed neither playback nor a receipt under Deny All, then received an identified whisper after re-enabling. The connected Slint receive selector persisted Deny All across profile reopen. Three core and four native regression checks passed separately. A physical Reply shortcut and live recipient-number reassignment were not exercised.
**Channel commander on Windows:** Slint rendering tests verified the compact lamp versus separate icon, the detailed-tree icon, and preference persistence in English/dark and Russian/light fixtures. On private beta14 the other guest's menu had no commander action. The server refused the self change with PermissionsClientInsufficient; both flags remained off and the old confirmation could not affect the replacement identity. Four native checks and two core checks passed. A successful authorized commander change on beta14 remains unverified.
**Country flags in the desktop tree:** The native Appearance switch `showCountryFlags` uses bundled flag-icons v7.3.2 4:3 SVGs; unsupported or missing codes produce neither an image nor a placeholder, and the image yields space to the name on crowded rows. The focused Windows Slint smoke checked the U.S. flag's blue canton and alternating red and light stripe pixels in English and Russian, dark and light, including compact and detailed tree rows and 900 × 800. Reopening restored the saved switch; a refused save retained the exact preference bytes and rendered state. Client order, selected channel, input owner and conversation stayed unchanged. Five focused checks passed, including the asset inventory and bundled MIT notice. See [asset provenance](LICENSES/NOTICE.md). The roster was synthetic; live server country metadata and mobile rendering were not tested.
**Participant volume:** On private beta14 the Slint fader applied -10 dB during the drag without saving it, then persisted it on release. Muting the peer did not change the listener's own gain. Reconnecting the listener restored -10 dB for the peer without restoring mute; Reset returned the gain to 0 dB and removed the stored modifier. Twelve native checks covered ordering, persistence and error handling. Three core tests covered two-speaker Opus mixing, stale queued audio and reused client numbers. No physical capture or playback device was used.
**Participant context on Windows:** On private beta14, two muted guests opened the self and peer menus on both tabs. Poke, volume, Connection Info and group availability matched independently queried capabilities for the selected client ID, UID and generation. The test inspected an eligible group choice without submitting it. Escape preserved selection and whisper targeting. A separate popup test verified one request per opening and rejection of stale responses after reopening. Five native and two core checks passed.
**Participant Poke on Windows:** Two muted guests used Slint's participant menu on private beta14. The server refused the long message with ParameterInvalidSize; the editor retained it and accepted a shorter correction. The destination recorded the exact literal message with the initiator's UID. Cancelled, locally oversized and stale drafts did not arrive. The replacement guest had the same display name but a different client ID; reused-ID rejection was tested separately. Five native checks and a real stdio byte-boundary test passed. No physical audio was used.
**Participant connection statistics:** The Windows Slint menu displayed the peer's server-assigned client ID and a numeric timing metric with units on private beta14. After changing tabs and reconnecting, the self panel used the new session. Escape dismissed the menu without changing selection or the whisper target. Separate tests checked English and Russian formatting, exact counters, empty and unscoped responses and client-number reuse. Seven native and three core checks passed; no physical audio was used.
**Participant Info on Windows:** On private beta14, two muted guests opened the rendered participant Info menus. The test compared displayed properties with targeted core reads, required nonempty version and platform for self, checked the peer result against the server's actual permission response, and verified tab-switch cleanup. A separate reconnect scenario checked the same tab with a new identity. Matching rows merge the last explicitly supplied value for each field; an empty field can clear it. An acknowledgement without a matching row fails. Ten native and two core tests passed. Physical devices were not used.
**Talk power on Windows:** On private beta14 the moderator granted and revoked talk power from a participant's Slint menu without a pending request. Both guests observed the new talker flag. A queue grant succeeded for a pending request, a withdrawn request was rejected locally, and an ordinary guest's manual grant was refused by the server without changing either roster. Four native checks and a stdio validation test passed. Queue identity checks occur before dispatch; the server remains authoritative. Both guests were muted.
**Away status and talk requests:** Two muted beta14 clients observed the submitted away message and return to online. Cancelling the Slint form left both rosters unchanged; reconnecting one recipient before submission prevented the old prompt from changing its replacement. In a temporary moderated channel, both clients observed talk requests with and without a message, grant and revocation, then withdrawal. The core stdio test verified Unicode length limits, rejected null and forbidden controls, and distinguished malformed requests from valid offline commands. No physical voice equipment was used.
**Disconnecting the viewed tab:** Two muted guests connected to private beta14. After the first tab reconnected, selecting it did not move the second tab's microphone ownership. Disconnect from the first tab's Slint menu removed only that guest from the surviving roster. A separate embedded-core test exercised capture revocation and handoff acknowledgement with generated PCM. The live test did not open physical audio devices or initiate its connections through the Slint Connect form.
**Partial snapshot import receipts:** Controlled apply tests verified retained acknowledgements after refusal or cancellation, failed icon transfers, reused icons, and renames followed by failed creation. The partial report lists the affected objects, fields and permissions without their values. A recycled transfer ID was not cancelled in the replacement session. On live beta14 the confirmed Skip run reported one skipped root, zero changes and an unchanged roster. The 32-test Windows run did not perform privileged live mutations.
**Applying the previewed snapshot:** The private beta14 Windows test opened two client snapshots with the same catalog ID. Stale Apply and Cancel actions could neither apply nor dismiss the replacement. Cancelling confirmation made no changes; an empty confirmation was rejected. Confirming the server UID with Skip reported one existing root skipped, zero changes and an unchanged channel roster. Service tests, not the live server, covered partial mutations, cancellation and reconnect. The focused run passed 29 tests.
**Snapshot export result:** Windows Save cancellation created no file. On classic desktop UI with a private beta14 server, selecting the channels section wrote a client JSON snapshot with one permanent channel; the partial report showed the saved filename and the channel-permission issue. Reopening that file displayed the expected catalog and server UID. Separate service tests covered all selected sections and variable substitution. A complete privileged export of groups and icons was not run on the live server.
**Snapshot cancellation:** Six focused tests verified early cancellation of export and apply, preservation of an acknowledged parent without creating its child, exact session ownership when a file-transfer number is reused, and presentation of a partial cancellation report. An export cancelled at job start created no output or core request. These cases used controlled service and UI-state tests; no live import modified a server.
**Snapshot progress:** On private beta14 the channels-only export finished with phase `channel`, 2 of 2 processed steps, one saved channel and one channel-permission issue. A completed count is not a claim that all steps succeeded. Separate tests checked stale jobs, connection and attachment changes, cancellation, and terminal report preservation. Twenty focused native tests passed. No snapshot changes were applied to the live server.
**Opening client snapshots:** The live Windows Open dialog showed the saved beta14 catalog and target server UID. Separate selection and codec tests rejected malformed JSON, server-side exports and oversized documents without creating import tokens. Reconnect invalidated the original selection. No import was applied to the live server.
**Channels-only snapshot on Windows:** A muted guest opened Export from the server menu on private beta14. Cancelling the real Save dialog created no file. A second export wrote the named JSON file with exactly the requested channels section. Its permanent channel hierarchy matched the current roster (one channel). The report was **partial**, with one channel-permission issue; progress was visible. Opening the saved file through the Windows Open dialog showed the matching catalog, metadata and target server UID in Slint. No snapshot was applied and no permissions were changed. This verifies the channel_list consumer, not a fully privileged export of every section.
**Channel Info on Windows:** On private beta14, a muted guest opened Channel Info from the temporary channel's Slint menu. The visible name, edited topic and multiline description matched the selected channel. Back cleared the details; selecting the lobby showed its own properties without joining it. Separate tests exercised out-of-order results, reconnection and invalid reply cardinality. A real stdio test rejected invalid arguments for channel_info, channel_description and channel_list before connection lookup. This verifies the Windows channel_info workflow, not all channel administration.
**Contact highlighting:** The Slint Appearance switch saved its disabled state across two restarts. Turning it back on marked the saved contact's tree row; a different UID reusing the same client number was not marked. This used isolated roster snapshots, not live presence or a screenshot comparison with the official client.
**Local contact editing on Windows:** The offline Slint test added a UID and name, rejected malformed and duplicate UIDs without changing memory or disk, set and cleared an alias, and restored the alias and ignore entry after restart. Ignoring stored the UID and original name, not the alias. Cancelling removal kept the contact; confirmed removal survived a second restart. A separate runtime test used ordered roster and chat events to distinguish UIDs even when the client number was reused. These checks cover the local contacts preference and its uid, name and alias fields, not cloud presence or live private chat interoperability.
**Copy download location on Windows:** Transfer Settings displays the saved path both immediately after selection and after restart. The copy action uses that setting, not the cached OS Downloads grant. A service test checked the empty and configured strings, and a Winit/Slint test activated Copy and observed os_actions_disabled in an isolated profile. The real Windows clipboard was neither read nor written. Two live download scenarios passed in the same revision; a third stopped at login with TS 3329 before its picker opened.
**Inline channel image on Windows:** A muted guest sent a ts3image link in the Slint channel chat on classic beta14. Activating it loaded the fixture PNG; its RGBA bytes matched the 2-by-1 red/green reference and the window painted red to the left of green. Reconnecting rejected a request from the retired session and stale asset results while accepting the replacement conversation's result. Three decoder checks covered size and format boundaries; a stdio check rejected invalid file_fetch_image requests. No HTTPFT, S3 or external image fetching was exercised.
**Pause, resume and cancel on Windows:** A muted guest downloaded `teamspeach-transfer-control.bin` from classic beta14 at a configured 1 MiB/s. The Slint row showed positive partial progress before Pause. Cancelling the paused transfer left the destination and staging empty. Resuming a second paused transfer published all 4 MiB, checked byte for byte. The fixture has 64 blocks of 65536 bytes: byte zero is the block index; other bytes at offset i are (i + (i >> 8)) modulo 256. One stdio test verified the ID bounds for all three commands, and four core loopback tests exercised resume offsets, cancellation and replaced partial files. This covers `command:file_pause`, `command:file_resume` and `command:file_cancel` on classic storage.
**Download failure and overwrite:** With classic beta14 the Slint file browser downloaded the selected file into the approved folder and reported 46 B / 46 B. Cancelling overwrite kept the existing bytes; confirming a one-off picker after reconnect did not enqueue a transfer. Three separate Windows tests verified that a partial staged write followed by StorageFull preserves the previous file, a cancelled copy leaves no partial replacement, and a replayed core event does not retry a failed export. The storage-full error was injected at the writer, not produced by filling a volume. This covers `preload:filesDownload` and `main-only-command:file_download` on classic storage.
**Transfer history on Windows:** After a real download from private beta14, the guest reopened the list from the file browser and saw 46 B / 46 B for the published file. Reconnecting on the same tab produced a fresh session key, an empty core transfer list and an empty Slint panel. Over stdio, an unexpected channel_id returned bad_request; empty arguments without a connection returned not_connected. This covers `command:file_transfers` on classic storage, not sustained transfer speed.
**Channel file list on Windows:** The guest opened the default channel's file browser from its Slint menu on private beta14. The listed filename and size matched the 46-byte fixture, and Download from that row produced the exact bytes. A separate live test rejected a stale picker after reconnect. The stdio test rejected invalid paths, unknown fields and out-of-range IDs before connection lookup; the largest valid channel ID reached the connection gate. This covers `command:file_list` on classic storage, not HTTPFT or S3.
**File chooser release:** The last-used directory hint retains only a path. Releasing an unused token drops the backing lease; attempting to download with the released token returns bad_request before dispatch and leaves existing bytes unchanged. A separately retained in-flight staging grant survives token release until the transfer reaches a terminal state. All 13 file-service tests passed. This verifies the native service equivalent of `preload:filesRelease`; the OS picker and reconnect case were verified separately.
**Transfer settings readback:** The Windows Slint controls saved 8 download slots, 2 upload slots and directional limits of 1.5 and 2.5 MiB/s. Restart restored all four fields, both limit switches, the prompt choice and the selected directory; a real beta14 guest download reached that directory. Four separate checks covered the numeric controls, divided rate configuration sent to two simulated core sessions, invalid or rejected changes, and persistence failure. This is UI and scheduler-command evidence, not a measured two-peer wire rate.
**One-off Windows download folder:** With Always Ask enabled, cancelling the system picker queued no transfer and created no output. Confirming a picker left open across a reconnect in the same tab returned `target_changed`. The replacement session downloaded the 46 fixture bytes only after a new selection, without changing the default folder. All three download-directory tests passed on private beta14 with classic file storage. This covers Windows `preload:filesChooseDownloadDir`.
**Windows default download folder:** Transfer Settings selected and cancelled through the system folder picker. After restart, a muted beta14 guest downloaded the fixture's 46 known bytes using classic file transfer into the selected folder. Cancelling an overwrite preserved the existing bytes without queuing a transfer. A separate restart test removed the selected folder and observed the restore error without recreating it or staging a download. To reproduce the positive test, provision `/teamspeach-download-smoke.bin` in the disposable server's default channel with `BYTES` from `native/src/smoke/download_folder_fixture.rs`; the guest needs list and read permission only. This covers Windows `preload:filesChooseDefaultDir`, not S3, uploads, or multi-tab limits.
**Recording destination on Windows:** Audio Settings opened the Windows folder picker. Selecting a disposable folder updated Settings; Cancel retained it, generic preferences could not replace it, and two fresh runtime launches restored it. Both beta14 recording exports landed in that folder. A separate service test rejected failed persistence and stale chooser results without granting access. This covers Windows `preload:pickRecordingFolder` and `preference:recordingFolder`, not Android or iOS document pickers.
**Recording commands on beta14:** The Slint panel started, paused, resumed and stopped a master take in a disposable destination. The track waveform, recorder status and info were checked against the silent PCM export and its timeline. Cancelling or submitting an invalid start left the destination untouched. During a second take, old buttons and a queued Stop could not pause or stop it; the first WAV remained byte-for-byte intact. Reconnection opened an idle recorder. Eleven native checks passed. A separate offline stdio test rejected malformed arguments for all seven recording commands with bad_request and preserved an existing file. No physical audio devices were opened.
**Publication consent and registration:** Old Slint callbacks and queued actions cannot start or stop a replacement capture even when the tab and source match. A registered Stop also checks the publication identity when the server stream ID and owner match. A delayed setup reply leaves a publisher in Starting after an early stream ID; a refusal releases its source and unregisters that ID. Eight Windows tests passed, including the beta14 generated-source publisher scenario. This did not exercise the OS picker, physical capture consent, or a real refusal displayed by the chooser workflow; `command:stream_setup` remains open.
**P2P signaling after an ICE restart:** `native_viewer_signaling_rollback_and_ice_restart` used two native Windows peers with host-only ICE. An early candidate waited for the remote offer, and the viewer sent its answer before local candidates. After rollback and renegotiation the viewer rejected a retired ICE username fragment and decoded a green frame on the new selected pair after decoding red on the original connection. Four focused regressions covered candidate routing and cancellation; 16 core protocol tests passed, including signaling object and byte limits. This verifies `command:stream_signal` with native peers, not official-client interoperability.
**Watching a closed P2P stream:** `slint_watch_admits_and_presents_generated_av_on_beta14` exercised Watch and Allow on the selected stream tiles. Before admission the viewer applied no offer and decoded no audio. After admission the viewer tile presented generated red pixels and its decoder received at least 30 matching blocks of a 1 kHz tone. A different observer cancelled before admission; using its stale action after disconnect did not start playback on the selected tab. This covers Windows `command:stream_join`, not physical devices or an official client.
**Channel-wide stream discovery:** On private beta14, `duplex_qa --stream-lifecycle` returned an empty list for a solitary client. After a second client connected, its untargeted request returned only the publisher and a matching P2P announcement. Targeted discovery returned the same stream. The observer's Slint Streams stage showed the registered ID, updated title and Watch action. Separate tests covered partial refusal, stale and overlapping requests, and an SFU announcement displayed without a P2P Watch action. The SFU case used fixture data, not a live SFU transport.
**Voluntary viewer leave on beta14:** With two viewers receiving generated video, the second left the stream. Its native peer was released, decoder statistics were no longer available and no decoded frame remained. The publisher retained only the first viewer, which received new magenta frames without rejoining. After a fresh join by the second viewer, stopping its old handle again did not interrupt the replacement. Separate tests covered one leave request across a delayed acknowledgement and rejected a stale UI close for the same stream ID. This verifies Windows `command:stream_leave`; physical audio and the official client were not exercised.
**Removing one of two active viewers:** In `approved_beta14_viewer_receives_generated_video`, the second viewer requested access again after refusal, was admitted, and decoded red and green frames. The publisher used that viewer's named Slint removal action. Only that viewer entered Removed, with no frame left to present. The publication remained live and the first viewer decoded three new blue frames before the publisher stopped it. Two separate publisher regressions verified that a reused client number does not transfer manual or queued removal to a replacement UID. This covers Windows `command:stream_remove` with generated video, not physical capture or an official peer.
**Stopping an active broadcast:** In the three-client Windows beta14 test, the publisher invoked Stop from the Slint tile for the registered stream while the admitted viewer was receiving video. The source rejected another frame, the publisher had no pending or admitted viewers, and the admitted viewer ended with no frame left to present. The refused viewer stayed declined. Fresh discovery from both viewers did not bring the stream back. This covers `command:stream_stop` for a generated source, not physical capture or an official client.
**Viewer admission and video on beta14:** In `approved_beta14_viewer_receives_generated_video` three muted native tabs connected to private beta14. From its Slint tile, the publisher admitted the first viewer to a closed publication. That viewer answered and decoded three red frames. The second viewer requested the same stream and received a refusal, sent no answer, and was not admitted. Only after the refusal did the source switch to green; the first viewer decoded three green frames without rejoining. Its departure emptied the publisher's viewer list. This covers Windows `command:stream_respond` with generated 64×48 video on the same host, not physical capture, audio delivery, or an official client.
**Viewer admission refusal on beta14:** In `duplex_qa --stream-lifecycle` the publisher received the observer's join request for its registered stream. The server acknowledged the negative response with an empty offer; the observer received the decline message for the same stream. A fresh targeted listing still returned the original publication, and its subsequent metadata update and stop were observed. Both disconnects were confirmed. No viewer was admitted and no media was sent in this run.
**Active publication editor:** On private beta14, `active_publisher_settings_cancel_and_update_on_beta14` opened the Slint editor from a registered publisher tile with a generated source. Cancelling kept the original title. Saving changed the tile title; the observer's fresh discovery returned the same stream ID and owner with the new title, 2700 Kbps and a viewer limit of 4. Editing does not grant or change the audio or video capture source. The separate core lifecycle check exercised audio metadata; this UI run did not change the audio flag or measure media delivery.
**Stream metadata updates on beta14:** In `duplex_qa --stream-lifecycle`, the observer requested the publisher's stream before the update and again after the server acknowledged it. The same stream ID and owner were returned with a new name, bitrate 2500 instead of 1000, viewer limit 3 instead of unlimited, and audio enabled instead of disabled. Both clients disconnected cleanly. Separate native publisher tests checked the last confirmed options before acknowledgement, admission during privacy changes, server refusal, and a late acknowledgement after disconnect. This measures advertised metadata, not encoded bitrate, actual audio delivery, or the rendered settings dialog.
**Stream registration on beta14:** Two muted disposable guests ran `duplex_qa --stream-lifecycle`. The publisher received its assigned ID in `notifystreamstarted`. The observer requested the publisher's stream list and received `notifystreaminfo` matching the ID, name and owner. Beta14 rejected an ID-only stop with TS 1542 (missing parameter). With `reason=1` it acknowledged the stop and the observer received `notifystreamstopped` for that exact stream ID. Both disconnects were confirmed. No viewer joined, and no audio or video was transmitted in this scenario.
**Audio and moving video on two local WebRTC peers:** The focused Windows test `decoded_tone_and_moving_video_on_local_peers` measured the generated 1 kHz tone in 43 of 46 decoded 10 ms audio blocks (22080 samples; normalized RMS 0.06233). A matching block requires more than 80% of its first-channel energy at 1 kHz and a minimum signal level. In the same run libvpx decoded 13 video frames and 12 increasing frame counters reached the display path. The source stop callback ran once. This verifies same-host audio and video transport before physical playback; it does not verify TeamSpeak signaling, an official client or a physical device.
**Two-colour WebRTC loopback:** The Windows `webrtc_smoke` example sent 14 generated 64×48 frames between two native PeerConnections. The software decoder reported libvpx and 14 decoded frames; the display path presented seven red frames followed by six green frames. The ended source rejected further input, its stop callback ran once, and the closed surface had no pending image. No physical audio device was started. Screenshots: `target/codec-fixtures/peer-loopback-red.png` and `peer-loopback-green.png` in the same directory. This tests local video transport, not audio delivery, TS6 server signaling, an official peer, AV1 or H264 High negotiation.
**Clock format:** On Windows, switching the Chats setting changed the time shown on an already loaded history row. After restart the saved format was restored; switching back updated the same row, and reopening the profile returned the original millisecond timestamp. Recent Server Events showed the same event in both clock formats in English and Russian, retaining its row ID and raw log. Seven focused tests passed using isolated profiles and fixture events.
**Server-target send on beta14:** In the extended Windows Slint send test, the two disposable guests exchanged the private and channel messages. Sending from the server conversation returned `PermissionsClientInsufficient`. The sender saw the refusal, with no own echo; revisiting that server conversation restored its unsent draft. No matching message was visible in the recipient's server conversation. This is evidence of server-target refusal, not successful broadcast. The live test and three focused core validation tests passed.
**Live private and channel text:** Two native tabs with different identities connected to private beta14. The Slint editor sent Unicode text to the exact private recipient and then to the joined temporary channel. In each case the sender saw one echo and its draft cleared after acknowledgement; the other tab displayed the exact text and sender UID in its own conversation. An 8193-byte draft was rejected locally and retained. This did not exercise server-target text, a denied send, or reassignment of a client number during delivery.
**Protected channel creation and join:** Two disposable guests used a private beta14 server. The holder's Slint Create Channel form retained the over-limit password with an inline error; cancelling the draft did not create a room or retain its secret on reopen. After submission both rosters showed the new temporary channel as protected. Selecting the row and cancelling the join prompt left the joiner in the lobby. An incorrect password opened an empty retry field with the localized refusal; the correct password moved the exact client on both rosters and both Slint trees. This covers channel_create.channel_password and command:join_channel on Windows, not bookmark login or physical audio.
**Channel subscriptions:** On private beta14, `channel_admin_qa --channel-subscriptions` verified single and all-channel subscribe/unsubscribe through fresh snapshots of the original, non-own lobby after explicitly clearing the connect-time subscribe-all mode. The server expired the generated temporary channel and confirmed disconnect. There was no second non-own channel to verify isolation. Without the explicit initial reset, the lobby showed unsubscribed after leaving it; subscribe was acknowledged but snapshot revision stayed at 4. Do not infer a transition from that acknowledgement. A separate Slint menu test using fixture snapshots checked individual and bulk command arguments and rejected stale menu IDs. Live UI permission refusal and reconnect before acknowledgement remain open.
**Chat preferences (Windows, isolated control events):** Four native tests passed. For `preference:chatOpenIncoming` an incoming private conversation stayed hidden with auto-open off, appeared as an unread background tab when enabled, and retained both messages. Neither the viewed room's draft nor the input-owning session changed. For `preference:chatIgnoredUsers` the contact's Ignore/Unignore actions controlled chat delivery by exact UID: explicit sender identity took precedence over the roster, while an absent sender UID used the preceding roster. A different UID using the same nickname and number remained visible. For `preference:chatShowModerationEvents` the visible timeline hid existing events when disabled and restored events received both before and during suppression. Only the two ordinary texts appeared in persisted channel history. Server control events were supplied by the fixture; no official peer or network delivery was tested.
**Connected Whisper settings:** Two native tabs on private beta14 changed the receive policy through the Slint selector and kept their connections. With the same saved F9 receiver list and input owner, the sender transmitted 42 synthetic frames under each policy. Deny All produced no remote talking or new whisper notification; switching back to Allow All restored remote talking and exactly one sender-matched notification. The frames were paced independently of UI rendering. A separate restart check restored the saved Deny All selection. No physical audio devices or OS-wide key registration were involved.
**Audio PTT checkbox:** The rendered checkbox, key binding and dependent controls followed the saved mode across two restarts. A failed save left the old mode intact. On private beta14 with VAD disabled, turning PTT off after key release resumed an already authorized synthetic input without another key press. Turning PTT back on stopped transmission and cleared the remote talking indicator; the next hold transmitted again. No physical device or global shortcut was used.
**Whisper through reconnect (Windows, beta14):** In `duplex_qa --whisper`, the receiver identified a 1450 Hz whisper from the live sender before that sender disconnected without stopping its whisper. After the sender reconnected, frames carrying the old tag triggered neither local transmission nor playback or a whisper notification. The receiver then decoded 42 ordinary 1750 Hz frames without a whisper notification. All three disconnects were acknowledged. This covers two diagnostic cores on loopback, not a physical shortcut, an official peer, or reassignment of the recipient's number.
**Sidebar preferences:** The Windows offline workflow `bookmark_sidebar_and_local_contact_reopen_without_network` covers `preference:savedServers` and `preference:bookmarkOrder`. It reopens the saved identity, nickname, channel and startup flags, checks the mixed folder/bookmark order after restart and preserves both disk and memory on a failed save. Duplicate and incomplete order writes are rejected. This does not verify bookmarked network login or a system password store.
**Moving bookmark folders:** The same Windows sidebar workflow moved the populated Outer folder under Archive through its Move form. After restarting the runtime and cancelling Archive deletion, it navigated the moved hierarchy and found the original folder and deep bookmark IDs. Confirmed removal deleted the subtree but retained Outside. This adds the folder-move case for `preference:bookmarkFolders`; the workflow uses shell actions, not physical pointer input.
**Client information readback:** On private TS6 beta14, `channel_admin_qa --client-info` returned version and platform for the exact roster client and rejected a mismatched UID locally. In `participant_info_menu_rejects_a_previous_session_target`, the Slint participant menu displayed version and platform for the first identity, cleared the details on disconnect, rejected the previous target after reconnect with a visible `target_changed` error, and opened fresh details for the second identity. A core regression separately covered disappearance or reuse of a client number before acknowledgement. The live menu test did not force a disconnect while a reply was in flight.
**Database identity readback on beta14:** With guest database search permission, `channel_admin_qa --client-database-id` returned the same positive database ID, UID and nickname from UID lookup and nickname search. Disconnect, core shutdown and profile cleanup succeeded. This was a read-only CLI check. In the original unprivileged run the UID lookup succeeded but the nickname search was refused with TS 2568.
**Directory search:** The Slint file browser filters the current listing without issuing a database search or a new file-list request. The test `directory_filter_keeps_file_targets_and_resets_on_navigation` matched a mixed-case Cyrillic name, kept the parent entry, included a new match after refresh and verified the selected file's original channel, path and session. Opening another directory cleared the filter. Three focused Windows tests passed; this did not exercise a network file transfer.
**Client database search and pagination:** Initial, searched and paginated results use the same server-context projection. Windows test `database_pages_and_search_results_keep_permission_and_target` checked the captured session and database ID, retained search/offset and enabled/disabled delete action for explicit allow/deny hints. Three projection and validation tests passed. No live database enumeration or deletion was attempted in this run.
**Connected nickname change:** On private TS6 beta14, `nickname_refusal_keeps_draft_and_retry_updates_only_own_identity` opened the tab's rename form with the current nickname, rejected a two-character draft locally and kept a refused duplicate nickname editable. On retry, both clients saw the trimmed new name with the original server-reported UID and client ID. Reopening the temporary profile confirmed that only the initiating local identity's nickname changed. The test binds server UIDs to the acknowledged client IDs rather than assuming a server-reported UID equals a local profile UID.
**Channel member disclosure:** The tree stores collapsed channel IDs under the server address in `collapsedChannels`. Collapsing hides direct members only: child channels and their members remain visible. A Windows Slint test exercised disclosure, two restarts, a different address reusing channel 7, and re-expansion on the original address in EN/dark and RU/light. The preference test checked pruning, isolation, rejection of malformed entries and preservation of disk and memory after a failed save. Three focused tests passed with fixture rosters; no network channel move or subscription was involved.
**Participant order in the desktop tree:** The Slint appearance test measured a participant and a nested channel under the same parent. Changing tree density kept their order. Turning off Show clients before channels then placed the subchannel above the participant without changing either row height or the selected channel. The order persisted after restart in EN/dark and RU/light. This exercised the rendered tree with a fixture roster, not a server-side move.
**Desktop tree style:** The Appearance selector now changes the rendered client rows. Compact uses 28 px rows, 22 px icons and 15 px nicknames; Detailed uses 40 px rows, 33 px icons and 14 px nicknames, following the [TS6 tree specification](docs/evidence/official-parity/ts6spec-tree.md). The Windows Slint test `tree_style_resizes_only_client_rows_and_survives_restart` measured the visible client and channel hit areas before the change, after the change on the same session, and after restart. The channel stayed 44 px high and channel 7 remained selected. Covered EN/dark and RU/light with fixture rosters, not full screenshot or live-audio parity.
**Display Size and the desktop sidebar:** `display_size_survives_failed_save_and_two_restarts` activated the real Appearance radio tiles in the Windows Slint software renderer. Small saved before the fix but left the collapsed footer at 62 px; after the fix Small, Medium and Large measured 52, 62 and 72 px wide, all 55 px high. In each EN/RU and dark/light combination, the first runtime restart restored Small, then Large was saved and a blocked atomic write for Medium returned `io`, leaving Large selected and `prefs.json` byte-for-byte unchanged. The second restart restored Large; the tile and footer also remained available at 900 x 800. The test dragged the sidebar closed from its default width and also exercised reopening it to 250 px and collapsing again in EN/dark. This was disconnected, using disposable profiles and fresh runtime/window instances within one test process, not a live voice/chat or official screenshot comparison.
**Default channel background:** The pinned 6.0.0.5232 bundle gates the no-image fill separately from the channel highlight (`main.js` character offset 3898723). Windows test `channel_background_updates_pixels_and_survives_failed_save_and_restart` actuated the native Appearance switch in English and Russian, light and dark, then measured the Slint software-rendered rows on an isolated synthetic roster. Disabling removed the default fill on selected and unselected channels and the idle spacer; selection outline, row bounds, order, and the client and server-header pixels stayed intact. Reopening the disposable profile restored Off; a refused atomic write returned `io`, kept all preference bytes, and preserved row paint within one RGB value after accounting for the visible error banner’s measured vertical offset. At 900 × 800 the rows and selection remained visible. The test used fresh runtime/window instances, not a new process, and did not exercise server-supplied banners, compact/mobile layout, or live media. This is native control-level evidence, not a whole-frame reference comparison.
**Server-backed channel banners:** The pinned 6.0.0.5232 tree gates the banner URL on Show Channel Banners and uses the separate default background when no banner is usable (`main.js` offsets 3885438 and 3898723). The native desktop tree follows that split for `ts3image://` raster banners. It requests the current channel through the existing `FetchBanner` core route, checks the viewed session and announced reference before accepting results, and never hands arbitrary URLs to Slint. The decoder accepts PNG, JPEG, GIF and WebP under the existing allocation and dimension limits; banner replies are capped at 4 MiB and retained rasters are reduced to at most 1024 × 128 RGBA pixels. With 64 entries this bounds the steady-state runtime raster cache at 32 MiB, excluding in-flight decode buffers and renderer copies. Failed loads are not cached; showing the row again or toggling banners back on permits a fresh request. Off clears cached images and invalidates outstanding results, even after re-enabling.
The Windows Slint test `channel_banners_render_replace_clear_and_follow_saved_visibility` used real encoded PNG replies at the offline transport boundary and exercised English and Russian in both stock themes. It measured the banner and an independent no-banner row, verified replacement, clearing, fallback behavior, unchanged selection outline and session ownership, persistence after reopening the runtime, and a refused atomic write that preserved the exact preference bytes. It also measured a 1600 × 400 source retained as 512 × 128, rejected SVG and external URL inputs, and exercised a late reply and same-reference retry in EN/dark. The test did not exercise real server file transfer, HTTP(S) banners, animated or full banner modes, mobile layout, a process restart, or whole-frame parity.
**Global shortcuts and OS settings:** The [installed settings review](docs/evidence/official-parity/ts6spec-settings.md) records TS6's Windows-specific OS page and shortcut registration feedback. TeamsPeach lists the OS page on other platforms too, with capability-specific availability. Global shortcuts use Windows, X11/portal or macOS Carbon backends; saving a binding is not proof of physical registration. Native taskbar status now uses the same hide-mode interpretation as the tray action. Windows test `taskbar_capability_tracks_the_selected_hide_mode` selected minimize, close, both and never: the capability flag followed all four settings. The lock-mute description now matches the handler: unlocking does not unmute the microphone. This test did not hide a window in the tray, lock the workstation or exercise physical shortcuts.
**Appearance and local privacy reference:** The [installed settings review](docs/evidence/official-parity/ts6spec-settings.md) describes theme, sizing, tree and chat styles, trusted sites and restoration of suppressed confirmations. Earlier static inspection found rendering consumers for display size, chat compactness, clients-before-channels and contact highlighting; later native evidence above covers other individual settings. Chat links pass through native URL classification and consent; remembered hosts are guarded by the flagged-site preference. The optional phishing-list refresh fetches the list, not the user's visited URLs. Reset Confirmations restores four preferences, but the inspected operation paths do not consult them; for example, clearing transfer history always prompts. These static comparisons are not proof of native visual parity, OS effects or confirmation suppression.
**Chat formatting and unread badges:** The [TS6 chat specification](docs/evidence/official-parity/ts6spec-chat.md) describes line-based formatting, BBCode and toolbar controls. TeamsPeach parses bounded typed nodes in `native/src/services/chat/parse.rs`, falls back to literal text on complexity overflow, and renders styled Slint runs, not HTML. Inactive conversations and messages arriving while older history is open contribute to unread counts. Returning to the latest messages clears the relevant conversation. The installed-client matrix identifies `setBadgeText`; native Windows uses a taskbar overlay, macOS a Dock label, and Linux a launcher signal on supported desktops. This comparison does not verify identical rendered text or a visible badge on those platforms.
**Notifications reference (2026-11-27):** The [installed settings review](docs/evidence/official-parity/ts6spec-settings.md) identifies a separate output selector and fader, group enablement, Listen and advanced per-event overrides. The official English locale names talking while muted (`settings.notifications.warnings.talking_while_muted`). TeamsPeach has the setting, sound and recent-event mapping, but its runtime has no muted-speech detector feeding that event. In particular, a rejected muted audio frame does not establish speech. Windows Listen/policy coverage is recorded below; the warning's source, setting and group acceptance remain open. Microphone capture policy has not been changed for this comparison.
**Recording mode preference (Windows, TS6 beta14):** The Audio settings selector saved Master. An invalid mode (4) returned `bad_request` and left Master selected. The same temporary profile was reopened twice; on the third launch the recording form offered Master by default. Choosing Multitrack and cancelling created no output. Reopening and submitting without changing the mode produced a finalized mode-2 manifest and a master WAV whose size matched the recorded timeline. Verified by `recording_panel_exports_a_paused_and_resumed_master` with a preapproved destination; the OS directory picker was not exercised.
**Local recording (Windows, TS6 beta14):** The installed English locale (`server.recording.*`, lines 2979–3005) names Master, Multitrack and Both, pause/resume, output folder, tracks and disk-overrun warnings. In `recording_panel_exports_a_paused_and_resumed_master` a real Winit/Slint window on loopback opened the recording form, selected Master, displayed track waveform data, paused, resumed, stopped and published the take through the Windows document adapter. The exported manifest contained mode 2, one pause and a positive frame count; the WAV length was exactly 44 + 2 bytes per frame (44-byte header plus 16-bit mono PCM). The take directory matched the start timestamp. This used a temporary profile and a preapproved temporary folder, not the OS picker or a physical microphone. Multitrack content, overflow, failed finalization and overwrite cancellation have separate checks.
**Stream volume control (Windows):** Moving the Slint slider previews gain on the selected viewer; releasing it or submitting the volume form saves a whole percentage for future viewers. A midpoint click dispatched approximately 0.5 gain. A disposable profile reopened at 0%, 43% and 100% after saving gains of 0, 0.426 and 1. Four focused UI, profile, viewer and PCM mixer tests passed. These checks used an isolated mixer, not live WebRTC or a physical output device.
**SFU stream offers (2026-11-27):** A mode-2 announcement now produces a stream tile with the localized SFU limitation and no P2P Watch action. A later metadata update can change one tile without disabling P2P streams from the same publisher. The media hub checks the latest announcement before registering a viewer or issuing a join. Windows tests `server_routed_stream_tile_has_no_p2p_watch_action` and `announced_sfu_mode_never_starts_a_p2p_join` passed with headless Slint and a recording signalling fixture. This verifies the inventory's explicit unsupported behavior, not mode-2 negotiation or media delivery.
**Channel description (Windows beta14, 2026-11-27):** The guest was refused creation with a description, then created a plain temporary channel. In the Slint editor it saved two lines, read them back via both the editor and `channel_description`, retained an oversized draft with an error, and cancelled an edit without changing the server value. Clearing the description returned an explicit empty string on a fresh read. The live test uses the same five-second request spacing as `channel_admin_qa`; an earlier unpaced edit hit `ClientIsFlooding`. Four core tests separately cover invalidation, including a pending read and an unrelated channel. Positive create-with-description is still unverified.
**Matrix reference (2026-11-27):** The [official chat review](docs/evidence/official-parity/ts6spec-chat.md) distinguishes the account-gated central/homebase path from decentralized server rooms using server identity and `MATRIXCHAT`. Central Matrix is outside the account-free contract. Rust detects server advertisement and displays a limitation in the ordinary server conversation; it does not perform discovery, Matrix login, invitation handling or sync. A classic server-target text send is not a Matrix room send. Neither the source review nor a Matrix-negative server proves positive Matrix interoperability.
**Stream reference (2026-11-27):** The [official client notes](docs/evidence/ts6-official-client.md) distinguish P2P offer/answer, ICE and realignment from mode-2 SFU access and mediasoup negotiation. Native P2P has session-bound discovery, per-viewer peers, capture consent and preview, renegotiation, decoder checks and bounded frame delivery. Fullscreen and pop-out reuse the existing stream. Compared to the [official settings](docs/evidence/official-parity/ts6spec-settings.md), the native stage has a vertical tile list, no source-resolution preset and one selected application-audio source rather than All/Exclude scopes. Native status is not a full RTC throughput panel. Server publication explicitly rejects SFU; on the receive side the inspected Watch action and hub did not check an advertised mode 2 before a P2P join. No successful SFU endpoint or live official-peer negotiation is claimed.
**File transport comparison (2026-11-27):** The [official storage evidence](docs/evidence/ts6-filetransfer-native.json) distinguishes legacy file verbs, HTTPFT and S3. TeamsPeach implements legacy TCP transfers and mutations. For ordinary S3 channels the active core requests channel-wide listings and signed GET/PUT URLs, correlates notifications and acknowledgements, and awaits upload completion; it does not fall back to legacy on unsupported mutations. HTTPFT-only storage remains unsupported. The historical matrix's combined blocked status is not the current S3 implementation status. The recorded empty S3 listing is not proof of populated listings, successful TeamSpeak-signed transfers or overwrite behavior; see the [bridge contract](docs/bridge.md).
**Device recovery UI (2026-11-27, supersedes the display gap in the reference comparison below):** After the first device enumeration, Audio and Notifications settings identify an absent or unconfigurable saved route and suggest reconnecting the device or selecting another. Before enumeration no absence is claimed. When the saved endpoint returns, the warning clears and its name reappears without a route-selection request. Windows headless Slint exercised capture, playback and notification choices (`saved_audio_device_recovers_without_switching_routes`); two focused tests passed. Physical device removal and recovery of an active stream were not exercised.
**TS3 file links (2026-11-27):** The installed TS6 English locale (lines 160–164) names download progress, disconnected/error states and Open File. TeamsPeach creates server- and channel-scoped links in its file browser and enables a file card's download action only in a conversation on the matching server UID. An IPv6 literal in brackets previously prevented detection of the copied URL. Windows test `copied_ipv6_file_link_reopens_the_same_chat_attachment` checks the browser encoder through chat attachment extraction, both bare and inside BBCode, including a nondefault port, encoded UID, spaces, plus sign, ampersand and brackets in the path/name. Three focused tests passed. No server transfer, OS file opening or visual card-state parity was exercised.
**Voice DSP, devices and 3D reference (2026-11-27):** The installed TS6 locale (`en.json` lines 5–12, 1689–1701), [Audio settings specification](docs/evidence/official-parity/ts6spec-settings.md) and [observed profile fields](docs/evidence/voice-official-source-20261029.json) identify per-device DSP, test capture/playback and independent notification routing. Native Audio settings apply capture AEC3/NS/AGC2, per-speaker playback AGC, ducking and comfort noise. Native typing attenuation uses local text-input events; the inspected native profiles have no TS6 `AgcExperimentalMode` equivalent. Explicit missing CPAL device IDs fail instead of silently selecting another endpoint; the native status does not reproduce the TS6 device-recovery prompt. No acoustic equivalence or physical hot-plug result follows from source inspection. The [historical 3D finding](docs/evidence/official-parity/final-feature-matrix.json) records a no-op Sound3D category without a corresponding settings surface; the native inventory preserves this exclusion, not a successful spatial-audio operation.
**Whisper reference (2026-11-27):** Installed TS6 `locales/en.json` lines 1849–1864 and 2047–2108 name block/reply/list hotkeys, client/channel and group targets, preview, history, Allow All and Deny All. TeamsPeach constructs `C2SWhisper` or `C2SWhisperNew` packets (`core/src/whisper.rs`); held routes and frames are bound to the current generation and epoch, with no ordinary-channel fallback. Preview is presentation only. Receive policy is configured before connecting and on ready cores: Deny All discards incoming whisper packets before decode and clears queued whisper audio (`core/src/audio.rs`). The official JS hooks `SetWhisperReceiveMode` and `HandleIgnoredWhisperEvent` do not establish a server-side refusal. TS6 declares block-hotkey labels without a demonstrated dispatch path; TeamsPeach offers reply, quick and list hotkeys and Deny All in settings, not a block shortcut. Static comparison, not a live recipient or reconnect test.
**Windows channel form on beta14 (2026-11-27):** `smoke::tabs::channel_create_from_toolbar_and_edit_on_beta14` used the actual Slint toolbar callback and editor on a headless desktop backend, an isolated identity and a live loopback server. For `admin-property:channel_create.channel_name` and `channel_create.channel_topic`, a 41-character name and 256-character topic remained in the draft with inline errors; cancellation discarded a valid draft, and a new form created the temporary root channel with the same name. Its row appeared in the tree and its topic was read back in Edit Channel. For `admin-property:channel_edit.channel_topic`, the editor retained the oversized draft with an error, cancellation preserved the old topic on reopen, and submission displayed the acknowledged new topic on reopen. Untouched optional overrides previously caused a guest permission refusal; codec and encryption now offer Server default. Five additional non-network editor/property tests passed. No physical display comparison, in-flight reconnect, nested-channel placement or privileged position change is claimed.
**Legacy chat send and local history reference (2026-11-27):** The [TS6 chat specification](docs/evidence/official-parity/ts6spec-chat.md) identifies private, channel and server targets and the native local-history methods. [Channel transport evidence](docs/evidence/official-parity/channel-text-target-evidence.json) distinguishes the channel ID in the client API from the classic wire command: mode 2 has no channel target. TeamsPeach checks the sender's current channel for mode 2 and the recipient UID for private messages before sending (`core/src/session.rs`); it does not promise delivery to another channel. Observed text events populate a profile-owned, paged history keyed by own identity, server UID and conversation (`native/src/services/chat_history.rs`). The installed locale's chat-history setting describes sidebar grouping and notification placement, not whether to persist messages. TS6 file-format compatibility, Matrix transport and end-to-end delivery are not established by this source comparison.
**TS6 server administration reference (2026-11-27):** Installed `client_ui/locales/en.json` lines 1181–1235, 1253–1427 and 1447–1545 identify ban and client database lists, categorized server settings, log filtering, privilege keys, temporary passwords and snapshots. In TeamsPeach, `native/src/app/server_actions/projection.rs` exposes list, create and delete actions for bans, keys and passwords, raw log lines and database search/pagination. Differences: no ban edit control, no copy control in those key/password lists, and no event-type or identity filter for server logs. Server Edit reads current properties and submits typed changes; its general/advanced form does not reproduce the official categories. Native snapshots support UID-bound import, conflict selection, cancellation and partial results, not the official per-element preview or revert control (see [snapshot comparison](docs/evidence/official-parity/ts6spec-snapshots.md)). This is a comparison of advertised controls and native source, not live administration acceptance.
**Channel creation reply (2026-11-27, `e6a8d2f`):** On an isolated TS6 beta14 server, `channel_admin_qa` received the new temporary root channel ID, read back its topic and codec quality, changed the topic without changing the name or quality, and read back both client and family limit edits. Invalid quality and stale generation were refused without changing properties. The guest could not place the channel under a parent (TS 2568); family inheritance and explicit sibling positioning remain unverified. Leaving the channel caused it to expire; disconnect, core exit and disposable-profile cleanup succeeded. This exercised core IPC, not the owning Slint dialog.
**Create Channel position:** The Windows Slint form dropped a previously selected root predecessor when the destination changed to channel 8. The resulting create commands distinguished no channel_order property, an explicit first position (0), and the second of two identically named siblings (13). Six focused create/move editor tests passed. No server mutation was attempted in this test.
**Channel CRUD reference comparison:** In the installed TS6 UI bundle (SHA-256 `352683c3eb1d674c6b0fe098ec8ba132b696739a33424080c9266b751de41537`), byte offsets 2199453, 1938146, 1936309, 1939071 and 1938521 identify create, property edit, move, delete and description calls respectively. The move wrapper compares parent and predecessor before calling native code; delete passes whether the channel contains clients or children. TeamsPeach uses explicit force and name confirmation on delete. The UI exposes a subscription permission hint; the underlying official subscription call was not established by this inspection. The native core supports subscribe/unsubscribe. The comparison does not establish a live move or delete on a server.
**Move Channel dialog:** A Windows Slint test opened the form at its current parent and predecessor, changed the parent, and selected the second of two identically named siblings. The resulting typed command targeted channel 42 with parent 8 and predecessor 13; the drag source and its subtree were not offered as destinations. Six focused editor tests passed. No channel move was sent to a server in this run.
**Channel order readback:** The core regression verified that channel properties retain their wire format while reporting the current parent and preceding sibling. The live check, `channel_admin_qa --channel-order`, requires a private beta14 fixture that permits creating a temporary channel at a specified position. The guest received TS 2568 on creation. Disconnect, core shutdown and profile cleanup succeeded, but neither relinking nor restoration was observed on the server.
**Legacy channel codecs:** The Windows Slint tab test observed the localized warning for Speex Narrowband, Wideband, Ultra-Wideband and CELT Mono in the visible interface. Selecting an adjacent Opus channel without joining it kept the warning. Viewing an Opus tab or joining an Opus channel cleared it. A separate core test checked that none of the four legacy codecs selects an encoder or produces decoded playback. On private beta14, WebQuery rejected channel creation for each legacy codec (0, 1, 2, 3) with TS 1538, while the same request for Opus Voice (4) succeeded and channelinfo confirmed the codec. The UI used fixture snapshots; a live legacy-channel join and outgoing packet count remain unverified.
**Voice transmission modes:** The installed TS6 settings distinguish continuous transmission, PTT, voice activation and PTT combined with voice activation. Its detector choices are Automatic, Volume Gate and Hybrid. Five Windows core tests exercised speech onset, level hysteresis and hangover, changes of detector, invalidation of buffered PCM and hybrid rejection of a loud non-speech tone. The native PTT configuration test separately verified that selecting PTT preserves the input device's VAD policy. This is a behavioral comparison, not a claim that TS6's internal detector thresholds match or that an official peer received the audio.
**PTT release delay (Windows beta14):** On repeated F8 holds with a continuous synthetic capture device, the sender stopped transmitting 127 ms after key-up at 100 ms, 523 ms at 500 ms, and 15 ms with delay off. The receiver's talking state ended after 158, 554 and 46 ms respectively. Focus loss during a 500 ms tail stopped the sender 15 ms after focus loss. These are observations from one loopback run, not audible speaker latency. Separate Slint and profile tests verified preset persistence across restart, rejection of 250 ms and cancellation on profile change.
**Talk request draft:** The isolated Windows Slint test rejected a 51-character message before emitting any action. With a valid 50-character draft, replacing the tab's session key made Submit show the changed-session notice without dispatching a request. Cancel retained the original target. The separate live reconnect run did not pass: beta14 returned ClientIsFlooding. This result covers the native editor, not a request in flight on the network.
**Withdrawn talk request:** On the private beta14 fixture, a moderator used a previously captured Grant action after both rosters had received the withdrawal. The native workflow reported target_changed with the pending-request error, and both rosters still showed no request and no talk power. A withdrawal racing with an already sent grant was not tested.
**Talk moderation on beta14:** Two muted Windows sessions joined a temporary channel with required talk power 50. Both rosters reported a positive timestamp for a request submitted without a message, then its withdrawal. A second request carried the entered text into the moderator's queue. Grant and revoke from that entry changed the requester's is_talker flag in both rosters. This exercised the native form and queue actions, not a physical hotkey, permission denial or reconnect during grant.
**Away with Message:** Two muted native sessions joined the same private loopback TS6 beta14 using different disposable identities. After cancelling the Slint form both rosters showed both clients online. After confirming a single message, both rosters reported both clients away with that message. The test injected a semantic shortcut event; it did not exercise OS chord registration or a physical keypress. No audio device was used.
With the next prompt open on the second tab, the first tab disconnected and reconnected. After confirmation, both live rosters showed the replacement online and the original second session away with the new message. The runtime reported the stale recipient rather than reporting complete success.
**Talk request queue:** The installed TS6 UI lists positive request timestamps in the local channel in descending order (bundle byte 4201898). The Windows native regression checked display order separately from the Grant Next shortcut: a withdrawn request disappears, an already granted peer or the local client is not chosen by the shortcut, and an unknown local channel yields no target. This verifies snapshot selection, not a live permission grant or a physical shortcut.
**Peer fader Alt-click:** The Windows software-rendered slider test pressed Alt before mouse-down and released Alt while dragging. The draft stayed at -12.5 dB until mouse-up, then returned to 0 dB with mute still enabled. No command was submitted by this gesture. The separate Reset action also cleared mute. This test did not use a live server or a physical output.
**Peer volume slider:** The Windows software-rendered Slint dialog accepted a pointer drag on the speaker slider without submitting an action. Cancel and reopen restored -12.5 dB. Reset submitted 0 dB and unmuted only after confirmation. The test checked all 421 half-decibel values against the inverse taper and the six official travel anchors. Three targeted dialog tests passed. This covered neither an installed live-peer context menu nor physical audio output.
**Local speaker volume:** The installed TS6 UI calls setClientVolumeModifier with server handler, client ID, dB and persistence flag (byte 1969424); its fader rounds to half-decibels over -200 to +10 dB (byte 3067840). The native store ignores an undecodable UID without losing other preferences or rewriting the profile on load. Five store tests and two core tests passed on Windows, including reused numeric IDs and decoded two-speaker mixing. This run did not exercise the desktop fader or physical audio output.
**Multiple connections and microphone ownership:** In the installed TS6 bundle, FindAudioInputServerConnectionHandler (byte 2517988) looks for an established handler with input hardware; automatic activation defaults off and restoration to the previous target defaults on. Three Windows native tests exercised acknowledged handoff, conditional restoration, and rejection of a late session reply. Returning to the already-active tab retained its permit and accepted the next PCM frame. These tests used embedded cores and simulated connected states, not live servers or a physical microphone.
**Server capability comparison:** The installed TS6 UI uses case-sensitive substring checks on capabilityExtensions (hasFeature, MATRIXCHAT at byte 2232606). The Windows core matched the snapshot and file backend across multi-row announcements, partial edits, explicit clearing and a fresh initserver without extensions. An S3 marker beyond the diagnostic display limit still selected S3. Six targeted core tests passed. No live server capture, transfer or two-tab microphone test was made in this check.
**Log directory (Windows):** Installation Details showed a missing-directory notice and no Open logs action on a fresh profile. With an empty logs directory in that same disposable profile, the action opened exactly that directory in Explorer. The isolated About regression also rejected a direct OpenLogs operation with os_actions_disabled while the directory existed and kept Diagnostics open. No log contents were inspected and no mobile export was tested.
**Theme folders (Windows):** From the native Appearance picker, Explorer confirmed the package-specific button opened the disposable profile's `extensions/org.fixture.folder` and the general button opened `extensions`. The isolated Slint regression invoked both actions and received `os_actions_disabled` before continuing through selection and restart. No mobile picker/share claim.
**Channel visibility transitions (2026-11-27):** Windows passed seven core event/snapshot tests, including a batched enter with a shared destination, a per-client override and a subsequent move with an explicit origin for an uncached client. Five native notification adapter tests passed: supervised moves into and out of the current channel and a kick into it selected the movement log and corresponding WAV file; subscription changes emitted no notification. These were packet and control fixtures, not a live server test, individual Listen preview, or physical playback.
**Reference comparison (2026-11-27):** The installed TS6 client UI bundle has SHA-256 `352683c3eb1d674c6b0fe098ec8ba132b696739a33424080c9266b751de41537`. Byte offsets here refer to that bundle, not the older matrix hash. At 4721953, Identity Details walks the bookmark tree and includes unassigned entries for the default identity. The Windows Slint reattachment test verified that a nested unassigned bookmark follows a change of default without acquiring an explicit UID. At 3920374 the official refusal dialog chooses the attempted identity before falling back to the default; at 3920620 it reconnects when the required quality is reached. The latter is **not verified** in TeamsPeach. At 2806802 the official theme step stores the selected theme; the offline username strings describe a local, unsynchronized name. The native account-free flow was verified separately below; this is not evidence of identical screen layout or a live official-client run.
**Identity security challenge:** A Windows client connected to an isolated TS6 beta14 server configured to require level 31. The server refused the nondefault level-9 identity. Windows UI Automation opened the resulting review button and observed the correct identity and target 31; both public identity records and the default were unchanged afterward. The native regression separately checked that restarting the tab invalidates the review action. This run did not attempt improvement to level 31 or a subsequent successful connection.
**Offline onboarding:** Both a fresh directory and an initialized empty profile persisted the light theme chosen in the Windows Slint form. A failed preferences write created no identity; retry succeeded, and restarting restored one UID and the selected appearance. This was exercised without network or physical audio.
**Identity list updates:** Windows Slint retained a nondefault UID and its related bookmark when replacing the window attachment, even with identical display names. Editing the nickname in the new window changed only that UID; switching to the default did not expose the other identity's bookmark. Two attachment tests passed. Creation, default selection, additive INI import and confirmed deletion were exercised in the separate identity workflows below.
**Identity improvement progress:** The Windows Slint regression for `preload:onIdentityProgress` ran two searches on the same disposable identity. A late cancellation for the first job did not stop the second or replace its displayed target and quality; the active Cancel stopped the correct job and its final search offset matched the persisted checkpoint.
**Identity export cancellation:** Windows UI Automation cancelled the private-key warning and confirmed no Save dialog opened. After accepting the warning, cancelling the native Save dialog left an existing backup unchanged and did not create a new INI. Together with the verified export/import UID round trip, this covers the Windows `preload:exportIdentity` contract.
**Identity import feedback:** The Windows picker accepted a generated TeamSpeak-format INI and reported one added UID. Importing it again reported one existing UID, and malformed input produced a visible error without changing the recipient's public vault or default. The core also accepted duplicates at full capacity and rejected an overflowing batch without partial writes.
**Identity backups (Windows):** A generated identity was exported from its selector context menu after the private-key warning and imported through the system file chooser into a second disposable profile. After restart, the public UID matched and the recipient's original default was unchanged. Five focused document/export tests passed, including preservation of the old backup after a partial write. These results do not establish mobile provider or power-loss guarantees.
**Theme ZIP import:** Windows opened the system file chooser from the native theme picker and installed the selected local archive. Reload retained the selected variant and its stylesheet hash; unsupported selectors produced a visible diagnostic. A second ZIP referencing an external stylesheet was refused before publication. Two focused tests also passed for external/escaping resources and archive confinement. This verifies the native supported subset, not arbitrary TS6 browser CSS or the mobile picker.
**Theme picker:** Windows UI Automation verified `preload:listThemes` after Reload: the package name and two variant names appeared together, and scrolling showed the diagnostic for a second invalid package. In an isolated native run, Preview applied the variant color, family and size while the stored selection remained null. ZIP installation is a separate contract.
**Theme links:** Windows UI Automation verified `preload:openThemeLink` against four local manifest entries (homepage, documentation, repository, email). Each action displayed its own destination, including trusted hosts and mail links, before cancellation. A second fixture without the optional web URLs did not expose their actions.
**Settings link verdict:** for `preload:privacyLinkThreat`, the same extension repository URL was opened up to the confirmation step in two disposable Windows profiles. A matching cached domain produced the malicious-site warning; no list produced the ordinary external-link warning. Both displayed the exact URL and were cancelled. Eight privacy service tests passed, including invalid-host rejection and cancellation without an open capability.
**Local phishing list:** `preload:privacyThreatStatus` was checked in the Windows trusted-sites view with no list and with an old cache from the expected source. The eight native privacy service tests also exercised fresh, failed-refresh and disabled states. The status says whether list data is available, not that an unlisted URL is safe.
**Theme selection:** Windows passed `selected_variant_survives_restart_and_restores_stock_on_removal` for `preload:selectTheme`. A locally installed variant kept its rendered background, font family and size across runtime restart. With the package withdrawn, Reload removed the saved selection, named the missing variant and restored stock colors and typography without changing its stylesheet.
The current visual reference is **TeamSpeak 6.0.0.5232**. The four reference manifests agree on the
served `main.js` and `main.css` SHA-256 fingerprints in the [visual source map and capture recipe](docs/evidence/official-parity/visual-source-map.md).
The 6.0.0.5163 extractions and earlier Electron results below are historical. The 5232 captures render
the official frontend and native Slint against a shared synthetic fixture, not a signed-in account,
user profile, or live connected session.
Scope is local and server functionality without a myTeamSpeak account: identity/bookmarks, server
tree and voice controls, channel/private chat, settings and permission-gated server tools and files.
Independent TeamsPeach branding, omitted myTeamSpeak/homebase account services and Remote Apps,
and native window captions are deliberate differences, not waivers for other layout mismatches.
Server-hosted Matrix chat and SFU streams are **not** account-only exclusions.
- **Visual:** `target/evidence/official-5232-pc/official/` contains five scenes in each of four
theme/locale combinations at 1280×800. Native runs `native-5232-pc-02` and `native-5232-pc-03`
each rendered 20/20. `compare-5232-pc-02/parity-report.json` and `compare-5232-pc-03/parity-report.json`
each record **0 passed, 20 failed, 0 blocked**. The strict whole-frame comparison is unmasked;
declared differences explain residuals but do not change the verdict.
- **Offline function:** `target/evidence/pc5232-functional-04/result.json` records 8 passed checks
and 28 captures: 12 settings categories, EN/RU and dark/light at widths 390/800/1280, rich chat,
PTT text-focus, capture denial, draft retention, two profile restarts and stale-session rejection.
No network, OS actions, physical capture or local peer transport was enabled. Separate focused
Windows gates recorded 109 native audio/tree tests, five DSP regression filters, three
`tsproto-packets` grammar tests and 44 core file/raw/session tests. These are scoped results,
not promoted entries in `native/compatibility.json`.
- **Server Matrix chat:** `current-contract:matrix-not-account` and the unsupported-state contract for `feature:chat.server_matrix` were exercised on Windows. `server_matrix_notice_tracks_advertisement_without_disabling_plain_chat` opens server chat in an isolated native window, flips the session's advertised chat capability and observes the notice appear and disappear while plain text input stays enabled without an account dialog. No Matrix room, login or transport was implemented or contacted.
- **Profile import:** `current-contract:profile-import` passed on Windows with generated profiles. Eight service tests cover external-key vault/default/hashcash preservation, corrupt or changing input, destination collision, password markers and explicit per-role device mapping. `cancelling_imported_bookmark_password_keeps_session_offline_after_restart` cancelled the actual Slint prompt on three launches, preserved the source hashes, history, bookmark order and password marker, and observed no active connection or audio start.
- **Bookmark sidebar and startup:** `schema-field:bookmarkOrder` and `current-contract:bookmarks-sidebar` passed the native `bookmark_sidebar_and_local_contact_reopen_without_network` workflow. For `preload:getStartupBookmarks`, Windows UI Automation observed the two password prompts in depth-first sidebar order in the running desktop executable even though their storage order was reversed. Both were cancelled before connecting.
- **Deliberate settings differences, TS6 5232:** the installed `main.js` matching the hash in the visual source map references the Account page (byte 1130212), Remote Apps page (1132687), analytics modes (4773285) and `skipUIPermissionChecks` (1104295). Windows UI Automation showed the twelve TeamsPeach categories, without Account, Remote Apps or Developer Options. Pointer activation of Privacy → More Information showed the read-only diagnostics explanation and no selectable analytics mode. This compares the user-visible settings; it is not a network telemetry audit.
- **Notifications and file settings:** Windows passed both core `disconnect_tests` (explicit
disconnect vs. reconnect and terminal phase classification), 49 selected native library tests,
and all four `notification_preferences` integration tests. The legacy `group_status` cue and its
stored values are preserved; the Status category has an independent switch.
`target/evidence/pc5232-notification-03/result.json` passed with 32 captures. Global Private Chat,
Global Group Chat, Incoming call and Outgoing call were captured separately and stayed disabled
on pointer and accessibility activation attempts. Persisted preferences and the existing
disconnected tab were unchanged; there were zero active sessions and no physical audio.
- **Sound coverage:** On 2026-11-27 the Windows Slint settings surface exposed six formerly missing advanced controls: moderator move in/out, kick in, server group assigned/revoked and permission error. Fifteen targeted Windows tests passed across the native library and notification preference integration tests. The PCM fixture exercises event and Listen output, repeats, the disabled sink and the silent fader for all 58 sounds; preference regressions cover legacy overrides, independent choices, hide/show and reopen. This brings 57 of 58 source cases through both individual Listen and sound policy with a supported trigger. Talking while muted has Listen and policy
coverage against a fixture, but no genuine speech trigger. The native local Recent Server Events
service and view projection were exercised with test inputs: 501 events with sound disabled,
500 retained and the newest 200 projected. Switching and closing tabs showed no cross-session
leakage; the local view is separate from the remote Server Log action.
- **Files scope:** focused tests checked that numeric steppers and typed input share the same step
and bounds, valid settings survive reopening, and invalid limits are rejected. This is not
end-to-end file I/O acceptance or proof that real transfers obey these settings. These results
do not establish installed-build or official-peer behavior or change any of the 718 pending
requirements in `native/compatibility.json`.
- **Direct whisper transport:** `cargo run --locked -p teamspeach-core --example duplex_qa -- --whisper`
ran two disposable Rust CLI peers against the private beta14. Sender and receiver agreed on the
recipient's live server UID. The receiver decoded 43 frames at 650 Hz with `whisper_received`;
deny mode suppressed both playback and the event at 900 Hz. Restoring allow mode delivered
40 frames at 1150 Hz. A stopped-epoch 1450 Hz tag produced no playback; subsequent ordinary
1750 Hz voice delivered 42 frames without a whisper event. Both disconnects were confirmed.
This checks core transport, not installed-client settings, official peers or physical audio.
- **Generated voice transport:** two core CLI peers exchanged paced 500 Hz and 900 Hz test tones
simultaneously through an isolated official TeamSpeak server beta 14 (100 sent frames per peer).
Spectral and exact sender checks matched 99/101 decoded frames B→A and 100/101 A→B; both peers
disconnected cleanly. No physical endpoint or official client peer was used.
- **Duplex voice and stall regression:** `cargo run --locked -p teamspeach-core --example duplex_qa`
exercised the actual QA core against the isolated localhost beta 14 server. A→B and B→A each
received 45 frames, with onset latency 14 ms and 21 ms respectively and 864 ms of overlap.
Release, mute, rejection while disconnected and a fresh reconnect were verified, with 3/3 clean
leaves. Separately, 112 Windows `media::audio` tests passed, including capture delayed beyond
200 ms during active playback and capture permit replacement. The reproducible tests confirm the
stalled-worker code-path fix; the reported physical WASAPI scenario was not independently observed.
- **S3 read-only listing:** against an isolated official TeamSpeak server beta 14, the core negotiated
`s3`, observed empty `b64_json` with `return_code` then ACK `id=0`, returned an empty root
(0 entries, 0 malformed, `read_only=true`, `list_supported=true`), and disconnected cleanly.
A separate direct SigV4 store PUT/list/GET recovered the seeded bytes (SHA-256
`c099147635c59787127aa7d9b9e247a5e0736f5e7a833bfb2732515e1ccdecae`). That is store evidence,
not a populated listing, upload, download or mutation through the TeamSpeak channel.
- **Open acceptance:** strict visual parity, populated S3 listings and positive signed transfers or
mutations through TeamSpeak, HTTPFT, live server-hosted Matrix/SFU, official-peer two-way voice
and physical audio, visible native captions/accessibility, installed desktop acceptance of this
build, and mobile/Asahi device checks. Generated voice and stall-regression tests do not establish
physical desktop voice acceptance or release readiness for this build.
## Native-only cutover and verification (2026-11-10)
The current product source is Rust/Slint with in-process Rust core services, native DSP, Skia and
@@ -222,9 +728,11 @@ not a claim about every server configuration. Evidence: `docs/evidence/official-
negotiation. `docs/evidence/official-parity/server-sfu-prerequisite.json` records a read-only check of the configured server's empty
SFU endpoint; it does not prove absence of an advertised runtime capability. No controlled SFU endpoint
has been exercised, so SFU remains blocked rather than falsely successful.
- **HTTPFT/S3:** `docs/evidence/ts6-filetransfer-native.json` and `docs/evidence/ts6-filetransfer-native-continuation.json` record
command arguments but not complete endpoint/base-URL binding, operation response envelopes, S3 payload
mapping or required headers/verb values. No controlled newer-storage server fixture is available.
- **Historical HTTPFT/S3 inspection (2026-11-01):** `docs/evidence/ts6-filetransfer-native.json` and
`docs/evidence/ts6-filetransfer-native-continuation.json` recorded command arguments but not complete
endpoint/base-URL binding, operation response envelopes, S3 payload mapping or required headers/verb
values. No controlled newer-storage server fixture was available at that checkpoint; see the
current checkpoint above for the separately observed empty S3 listing.
- **macOS implementations:** selected-application audio capture is not implemented; a CoreAudio/TCC
backend is still needed. Global shortcuts are explicitly unsupported by the non-Windows/non-Linux
branch of `core/src/hotkeys.rs`. These are implementation gaps, not merely unexecuted tests.
+7
View File
@@ -15,6 +15,13 @@
transformations and rights restrictions as a historical record, not a native asset inventory. Those renderer
sprites, masks and flag files are not migrated to the native resource bundle. The TeamsPeach application icon
is retained unchanged as `native/resources/icon.png`.
- Native roster flags use the original 4:3 SVGs from [flag-icons](https://github.com/lipis/flag-icons/tree/v7.3.2)
v7.3.2, MIT, Copyright (c) 2013 Panayiotis Lipiridis. The unmodified upstream licence is in
`native/resources/flags/LICENSE` (packaged as `resources/flags/LICENSE`). The
[npm release archive](https://registry.npmjs.org/flag-icons/-/flag-icons-7.3.2.tgz) has SHA-256
`9477c5252afe0e99dd2d4408b664c83e7c7c80785c7983751d5c7a020198a731`. The subset contains all 249
ISO 3166-1 entries and the two-letter geographic extensions `cp`, `dg`, `eu`, `ic`, and `xk`;
organization flags, longer regional codes, and the unknown placeholder are not bundled.
- Native microphone DSP uses the WebRTC-derived Sonora AEC3, noise suppression and adaptive AGC2 chain,
BSD-3-Clause. See `sonora-NOTICE.txt` and `dsp/vendor/provenance.json` for source/version and local patch
provenance. `denoise-THIRD-PARTY-NOTICES.txt` retains the historical DSP dependency and Rust standard-library
File diff suppressed because it is too large. Load diff
+16 -10
View File
@@ -7,22 +7,27 @@ chain according to the selected settings. There is no renderer WebAssembly ABI.
The noise-only filter-bank implementation remains a Rust-test-only behavioral
reference, not a second production capture stage.
Pinned Sonora packages include (all 0.2.0, BSD-3-Clause):
Pinned Sonora packages include (all 0.3.0, BSD-3-Clause):
sonora, sonora-aec3, sonora-agc2, sonora-common-audio,
sonora-fft, sonora-ns, sonora-simd.
Source: https://github.com/dignifiedquire/sonora
Commit: a024d6ef8351add55be5e8b1d6cc35f555787660 (per the published crates'
Commit: 1632d47c1e77d0857f9145bd175134b348541e11 (per the published crates'
.cargo_vcs_info.json)
Registry: crates.io; package checksums (SHA-256 of the .crate files)
sonora 0.2.0 2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250
sonora-ns 0.2.0 d511feef19302c716d245c4555087d161ba91c178735ea11107dcce0d0b7a86f
sonora-fft 0.2.0 27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012
sonora 0.3.0 d461e6c9ad112f8728919387a4bc5639fd28631f2070171efad38676e907edd8
sonora-aec3 0.3.0 f2809c3fda13f71deac22d0ddb6c02c493f254d3da2afe59a7e256a8f15bcffe
sonora-agc2 0.3.0 501b5dd3f8bdc8c983dc64a131cef22a429f3ff879d6f0007b8bfe46ec7b96aa
sonora-common-audio 0.3.0 2c05dfa300c14dc8498751ce2c5b87aad2acf1892d4f9d66b92ae2f372a83410
sonora-fft 0.3.0 ec3529f2cf748f1acc85d9403ffa08a3fe69dec6bf22383910b3bd21aca2fd26
sonora-ns 0.3.0 31c0a62e78419a174dbf9c9c01943c1ecd8c298a68d15c4fb4906cb19f0428b9
sonora-simd 0.3.0 f939d8e63a2a0baa7555294d7b09c5e3d382f28358755b920e13ad527658c8fa
sonora is a pure Rust port of the WebRTC Native Code audio processing module
(M145 plus later upstream fixes), via PulseAudio's webrtc-audio-processing
extraction. TeamsPeach vendors sonora and sonora-agc2 with local mono AGC2 and
limiter channel-adapter allocation/copy reductions. Exact modified files,
extraction. TeamsPeach vendors sonora and sonora-agc2, retaining local mono AGC2
borrowed-channel processing to avoid frame copies. Upstream 0.3.0's generic limiter
subsumes the former local limiter descriptor-allocation patch. Exact modified files,
upstream archive checksums and patch scope are in dsp/vendor/provenance.json;
upstream license and copyright texts are retained in each vendored package.
Other pinned Sonora packages use their registry sources. No end-to-end
@@ -30,9 +35,10 @@ allocation-free guarantee or bit-identical behavior with TeamSpeak's proprietary
DSP is claimed.
The native executable also uses the Rust standard library (core, alloc, std and
its bundled allocator and math routines), licensed MIT OR Apache-2.0. Historical
DSP dependency license texts are retained in denoise-THIRD-PARTY-NOTICES.txt;
that file is not a complete inventory of the native executable's dependencies.
its bundled allocator and math routines), licensed MIT OR Apache-2.0. Current
resolved DSP dependency license texts are in denoise-THIRD-PARTY-NOTICES.txt;
that file includes locked optional, build-time and target-specific dependencies
and is not a complete inventory of the native executable's dependencies.
License of the Sonora packages (BSD-3-Clause, verbatim):
+16 -7
View File
@@ -56,7 +56,7 @@ CI/release configuration is under `.gitea/workflows/`; an unexecuted configurati
### Native CI and releases
The workflows require matching native runners labelled `teamspeach-native-linux-x64` and
`teamspeach-native-linux-arm64`. Provision Rust 1.96.0, Python 3, LLVM/libclang, CMake, Ninja,
`teamspeach-native-linux-arm64`. Provision the Rust version from `rust-toolchain.toml`, Python 3, LLVM/libclang, CMake, Ninja,
Linux audio/window development libraries, Xvfb and D-Bus session tools before enabling them.
Set repository variables `NATIVE_LLVM_HOME`, `NATIVE_LIBCLANG_PATH` and `NATIVE_SKIA_SOURCE_DIR`
to existing tools and a dependency-synchronized Skia checkout containing `bin/gn`. Packaging also
@@ -250,9 +250,12 @@ native/platform acceptance case has passed. Consult FEATURE_COMPATIBILITY.md for
universal cross-platform or official-client interoperability proof.
9. Channel/server menus provide typed administration with explicit destructive confirmations and server
errors. Snapshot import is non-atomic: completed server changes are not rolled back by cancellation.
General file browsing/transfers support the legacy server transport; HTTPFT/S3 remain explicit gaps
with no speculative legacy fallback. Filesystem publication fails safely when required atomic/no-replace
semantics are unavailable. Native services approve recording/transfer destinations through chooser grants.
Channel files use legacy transfer on legacy servers. Ordinary channels can browse S3 metadata;
S3 takes precedence for listing when both S3 and HTTPFT are advertised. HTTPFT remains blocked,
with no fallback to legacy storage. S3 upload/download bytes and remote mutations have not been
verified live through TeamSpeak. Native services require chooser grants for recording and file
destinations and explicit confirmation for overwrite or destructive operations. Filesystem
publication fails safely when required atomic/no-replace semantics are unavailable.
File Transfer settings retain an approved download folder or ask every time, and apply upload/download
concurrency across all tabs (combined at most ten) plus shared directional rate limits. Limits apply to
active file/snapshot work without restarting streams; they are conservative ceilings, not bandwidth guarantees.
@@ -281,7 +284,7 @@ native/platform acceptance case has passed. Consult FEATURE_COMPATIBILITY.md for
IPC, page or remote-button binding is included.
- **Server icons:** the server administration pane lists, uploads, deletes and assigns icons through
legacy TeamSpeak file transfer. The server's permissions remain authoritative. A reconnect invalidates
the panel's mutation grant; HTTPFT/S3 storage is not silently treated as an empty icon collection.
the panel's mutation grant. Ordinary-channel S3 browsing does not enable S3 or HTTPFT server icons.
- **Noise reduction:** Settings → Audio has four levels saved per input device. The implementation is
independent DSP; selected settings and generated-media checks do not prove microphone sound quality
or bit-identical behavior with the official client.
@@ -354,8 +357,8 @@ An absolute, normalized `TEAMSPEACH_PROFILE_DIR` selects a separate root; do not
unreachable over SSH.
- Packages are unsigned. Windows SmartScreen warns about unsigned builds; macOS Gatekeeper would also
require attention for a future macOS build.
- The recorded two-way voice run used synthetic capture between two TeamsPeach clients. It does not
prove live microphone interoperability with the official TS6 client or operation on Asahi hardware.
- A two-way core CLI run verified synthetic voice with silent disposable profiles. It did not use real
microphones or playback devices and does not prove official-client peer or Asahi interoperability.
## Product and design
@@ -408,6 +411,12 @@ actions and are not release eligible. Generated media proves only its exercised
path. Live official peers, physical capture/playback, visible native windows, OS accessibility,
installed upgrades and Asahi/mobile hardware need separately authorized isolated checks.
The S3 result is scoped to an empty ordinary-channel listing on an isolated official TS6 beta14
server. An ordinary guest upload grant was refused; neither that refusal nor a separate direct object-store
readback proves TeamSpeak file transfers. The live-peer check is still pending; keep any separately
authorized probes and sanitized evidence in disposable profiles, channels and storage, away from user
credentials and files.
`native/compatibility.json` preserves 718 pending acceptance requirements, not pass marks. Historical
captures in `docs/evidence/` remain exact records of their original builds; they do not prove native parity.
Strict visual comparisons previously failed and are not converted to passes by the stack cutover.
+9 -4
View File
@@ -16,15 +16,19 @@ tsclientlib = { path = "vendor/tsclientlib", default-features = false, features
tsproto-packets = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
tsproto-types = { git = "https://github.com/ReSpeak/tsclientlib", rev = "ee3bc6f45a7137db7793ba5593a321df400d53e5" }
audiopus = "0.3.0-rc.0"
base64 = "0.22"
base64 = "0.23.1"
bytes = "1"
chrono = { version = "0.4", default-features = false }
futures = "0.3"
num-traits = "0.2"
reqwest = { version = "0.13", default-features = false, features = ["rustls", "stream"] }
# File identity (volume serial + index / dev + inode) for paused partial downloads; already in the lock.
same-file = "1.0.6"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value", "preserve_order"] }
sha-1 = "0.10"
md-5 = "0.10"
sha1 = "0.11.0"
md-5 = "0.11.0"
base16ct.workspace = true
# Same DER decoder tsproto-types uses for keys (already in the lock through it).
simple_asn1 = "0.6"
# Voice activation detector (pure Rust, embedded model; MIT OR Apache-2.0). Pinned: newer releases change the API.
@@ -35,6 +39,7 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
[target.'cfg(windows)'.dependencies]
# The #[implement] macro in app_audio_windows expands to absolute ::windows_core paths.
windows-core = "0.62.2"
windows = { version = "0.62.2", features = [
"Win32_Foundation",
@@ -58,5 +63,5 @@ windows-sys = { version = "0.61", features = [
[target.'cfg(target_os = "linux")'.dependencies]
dbus = { version = "0.9", features = ["vendored"] }
x11rb = "0.13"
x11rb = "0.14.0"
+3651 -328
View File
File diff suppressed because it is too large. Load diff
+848
View File
@@ -0,0 +1,848 @@
//! Connected administration QA for an already running, private TS6 beta14 fixture.
//! Set TEAMSPEACH_QA_CORE to an absolute path to a disposable teamspeach-core.exe,
//! then run `cargo run --locked -p teamspeach-core --example channel_admin_qa`.
//! The only endpoint is 127.0.0.1:19987. No credentials, devices or ServerQuery.
//! Pass `--channel-order` to check sibling readback on insertion and expiry only.
//! Pass `--client-database-id` to compare UID lookup and nickname search without modifying the server.
//! Pass `--client-info` to read the guest's own variables and reject a mismatched UID.
//! Pass `--channel-subscriptions` to check this guest's channel subscriptions.
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitCode, Stdio};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde_json::{json, Value};
const ENDPOINT: &str = "127.0.0.1:19987";
const CONTROL: Duration = Duration::from_secs(5);
const CONNECT: Duration = Duration::from_secs(12);
const POLL: Duration = Duration::from_millis(50);
// Leave a quiet window between ordinary server commands; do not retry flood refusals.
const WIRE_SPACING: Duration = Duration::from_secs(5);
const CLIENT_IS_FLOODING: u64 = 524;
const PERMISSION_DENIED: u64 = 2568;
const ORIGINAL_TOPIC: &str = "QA initial topic";
const UPDATED_TOPIC: &str = "QA edited topic";
const CODEC_QUALITY: u64 = 5;
const FAMILY_INHERITED: &str = "channel_flag_maxfamilyclients_inherited";
type Result<T, E = String> = std::result::Result<T, E>;
enum Reply {
Accepted(Value),
Refused(Value),
}
impl Reply {
fn require(self, cmd: &str) -> Result<Value> {
match self {
Self::Accepted(result) => Ok(result),
Self::Refused(refusal) => Err(rejection(cmd, &refusal)),
}
}
}
fn rejection(cmd: &str, refusal: &Value) -> String {
// IDs are diagnostic; the IPC error message/detail can contain real target data.
if let Some(id) = refusal["ts_error"]["id"].as_u64() {
if id == CLIENT_IS_FLOODING {
return format!("{cmd}: server flood-limited this request (TS {id}); not retried");
}
return format!("{cmd}: server refused (TS {id})");
}
let kind = match refusal["code"].as_str() {
Some("bad_request") => "bad_request",
Some("not_connected") => "not_connected",
Some("not_found") => "not_found",
Some("server_error") => "server_error without a TeamSpeak result",
_ => "unexpected IPC error",
};
format!("{cmd}: {kind}")
}
struct Core {
child: Child,
input: Option<mpsc::SyncSender<String>>,
written: mpsc::Receiver<bool>,
output: mpsc::Receiver<Value>,
sequence: u32,
state: Option<&'static str>,
snapshot: Value,
last_wire: Option<Instant>,
}
impl Core {
fn start(exe: &Path, root: &Path) -> Result<Self> {
let mut child = Command::new(exe)
.arg("--data-dir").arg(root.join("profile"))
.current_dir(root)
.env("TEAMSPEACH_LOG", "off")
.env("TMP", root).env("TEMP", root).env("TMPDIR", root)
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
.spawn().map_err(|e| format!("could not start diagnostic core ({:?})", e.kind()))?;
let mut stdin = child.stdin.take().expect("piped stdin");
let stdout = child.stdout.take().expect("piped stdout");
let (input, outgoing) = mpsc::sync_channel::<String>(1);
let (ack, written) = mpsc::sync_channel(1);
let (incoming, output) = mpsc::sync_channel(256);
let reader = thread::Builder::new().spawn(move || {
for line in BufReader::new(stdout).lines() {
let Ok(value) = line.and_then(|text| serde_json::from_str(&text).map_err(std::io::Error::other)) else {
break;
};
if incoming.try_send(value).is_err() {
break;
}
}
});
let writer = thread::Builder::new().spawn(move || {
while let Ok(line) = outgoing.recv() {
let ok = stdin.write_all(line.as_bytes()).is_ok();
if ack.send(ok).is_err() || !ok {
break;
}
}
});
let core = Self {
child, input: Some(input), written, output, sequence: 0, state: None, snapshot: Value::Null,
last_wire: None,
};
if reader.is_err() || writer.is_err() {
return Err("could not start core pipe workers".into());
}
let ready = core.read(Instant::now() + CONTROL, "ready")?;
ensure(ready["event"] == "ready" && ready["protocol"] == 1, "expected protocol 1 ready event")?;
Ok(core)
}
fn read(&self, deadline: Instant, stage: &str) -> Result<Value> {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(format!("{stage}: deadline exceeded"));
}
self.output.recv_timeout(remaining).map_err(|e| format!("{stage}: core stdout {e}"))
}
fn request(&mut self, cmd: &str, args: Value, deadline: Instant) -> Result<Reply> {
self.sequence += 1;
let id = self.sequence.to_string();
let line = format!("{}\n", json!({"id": id, "cmd": cmd, "args": args}));
if Instant::now() >= deadline
|| self.input.as_ref().is_none_or(|input| input.try_send(line).is_err())
|| self.written.recv_timeout(deadline.saturating_duration_since(Instant::now())) != Ok(true)
{
return Err(format!("{cmd}: core stdin write failed or timed out"));
}
loop {
let value = self.read(deadline, cmd)?;
if value["id"].as_str() == Some(id.as_str()) {
return match value["ok"].as_bool() {
Some(true) => Ok(Reply::Accepted(value["result"].clone())),
Some(false) if value["error"].is_object() => Ok(Reply::Refused(value["error"].clone())),
_ => Err(format!("{cmd}: malformed core reply")),
};
}
self.observe(value);
}
}
fn observe(&mut self, event: Value) {
match event["event"].as_str() {
Some("snapshot") => self.snapshot = event,
Some("state") => self.state = match event["state"].as_str() {
Some("connecting") => Some("connecting"),
Some("connected") => Some("connected"),
Some("disconnecting") => Some("disconnecting"),
Some("disconnected") => Some("disconnected"),
_ => None,
},
_ => {}
}
}
fn call(&mut self, cmd: &str, args: Value) -> Result<Value> {
self.request(cmd, args, Instant::now() + CONTROL)?.require(cmd)
}
fn wait_wire_spacing(&self) {
if let Some(last) = self.last_wire {
thread::sleep((last + WIRE_SPACING).saturating_duration_since(Instant::now()));
}
}
fn wire_request(&mut self, cmd: &str, args: Value, timeout: Duration) -> Result<Reply> {
self.wait_wire_spacing();
let reply = self.request(cmd, args, Instant::now() + timeout);
self.last_wire = Some(Instant::now());
reply
}
fn wire_call(&mut self, cmd: &str, args: Value) -> Result<Value> {
self.wire_request(cmd, args, CONTROL)?.require(cmd)
}
fn wait_for(&mut self, stage: &str, ready: impl Fn(&Value) -> bool) -> Result<()> {
let deadline = Instant::now() + CONTROL;
while !ready(&self.snapshot) {
let event = self.read(deadline, stage)?;
self.observe(event);
}
Ok(())
}
fn leave_and_close(&mut self) -> Result<()> {
// A failed action can still leave us connected. Shutdown runs even if the
// explicit disconnect failed; dropping stdin is the last graceful path.
let leave = if self.state == Some("connected") {
self.call("disconnect", json!({})).and_then(|result| {
ensure(self.state == Some("disconnected") && result["clean"] == true,
"disconnect did not receive server confirmation")
}).map(|()| println!("disconnect: ok (server confirmed)"))
} else {
Ok(())
};
let close = self.call("shutdown", json!({})).and_then(|_| {
match self.wait_exit(CONTROL)? {
Some(status) if status.success() => {
println!("shutdown: ok (core exited)");
Ok(())
}
_ => Err("core did not exit cleanly by its deadline".into()),
}
});
combine(leave, close)
}
fn wait_exit(&mut self, limit: Duration) -> Result<Option<std::process::ExitStatus>> {
let deadline = Instant::now() + limit;
loop {
let status = self.child.try_wait().map_err(|_| "could not query the diagnostic core process")?;
if status.is_some() || Instant::now() >= deadline {
return Ok(status);
}
thread::sleep(Duration::from_millis(10));
}
}
}
impl Drop for Core {
fn drop(&mut self) {
drop(self.input.take());
if !matches!(self.wait_exit(CONTROL), Ok(Some(_))) && self.child.kill().is_ok() {
let _ = self.wait_exit(CONTROL);
}
}
}
// Only constructed from this run's create result and a verified matching live
// name. No caller-supplied channel ID can reach the edit path, and no delete
// command is sent: the server expires the temporary channel after we leave it.
struct RunChannel<'a> {
id: u64,
name: &'a str,
generation: u64,
}
impl RunChannel<'_> {
fn row<'a>(&self, rows: &'a [Value]) -> Result<&'a Value> {
let row = rows.iter().find(|row| wire_id(row) == Some(self.id));
row.filter(|row| row["channel_name"].as_str() == Some(self.name))
.ok_or_else(|| "the generated channel is not visible with its original name".into())
}
fn listed(&self, core: &mut Core, deadline: Instant) -> Result<Value> {
let list = core.request("channel_list", json!({}), deadline)?.require("channel_list")?;
Ok(self.row(rows(&list)?)?.clone())
}
fn edit(&self, core: &mut Core, generation: u64, properties: Value) -> Result<Reply> {
let args = self.edit_args(core, generation, properties)?;
core.wire_request("channel_edit", args, CONTROL)
}
fn edit_args(&self, core: &mut Core, generation: u64, properties: Value) -> Result<Value> {
self.listed(core, Instant::now() + CONTROL)?;
self.check_live_generation(core)?;
Ok(json!({"generation": generation, "channel_id": self.id, "properties": properties}))
}
fn check_live_generation(&self, core: &Core) -> Result<()> {
ensure(core.state == Some("connected") && core.snapshot["generation"].as_u64() == Some(self.generation),
"live connection changed before mutating the generated channel")
}
fn move_under(&self, core: &mut Core, parent_id: u64) -> Result<Reply> {
self.listed(core, Instant::now() + CONTROL)?;
self.check_live_generation(core)?;
ensure(valid_parent(&core.snapshot, parent_id), "the original default channel is no longer a valid parent")?;
core.wire_request("channel_move", json!({"generation": self.generation, "channel_id": self.id, "parent_id": parent_id}), CONTROL)
}
fn info(&self, core: &mut Core) -> Result<Value> {
let result = core.wire_call("channel_info", json!({"channel_id": self.id}))?;
let rows = rows(&result)?;
ensure(rows.len() == 1, "channel_info did not return exactly one row")?;
Ok(self.row(rows)?.clone())
}
fn observe_row(&self, core: &mut Core, matches: impl Fn(&Value) -> bool) -> Result<Value> {
let deadline = Instant::now() + CONTROL;
loop {
let row = self.listed(core, deadline)?;
if matches(&row) || deadline.saturating_duration_since(Instant::now()) <= POLL {
return Ok(row);
}
thread::sleep(POLL);
}
}
fn wait_fields(&self, core: &mut Core, expected: &[(&str, &str)]) -> Result<Value> {
let matches = |row: &Value| expected.iter().all(|(key, value)| row[*key].as_str() == Some(*value));
let row = self.observe_row(core, matches)?;
ensure(matches(&row), "server acknowledged edit but live properties did not match")?;
Ok(row)
}
}
fn ensure(condition: bool, message: &str) -> Result<()> {
if condition { Ok(()) } else { Err(message.into()) }
}
fn combine(first: Result<()>, second: Result<()>) -> Result<()> {
match (first, second) {
(Err(first), Err(second)) => Err(format!("{first}; {second}")),
(first, second) => first.and(second),
}
}
fn rows(value: &Value) -> Result<&[Value]> {
value["rows"].as_array().map(Vec::as_slice).ok_or_else(|| "missing row list".into())
}
fn wire_id(row: &Value) -> Option<u64> {
row["cid"].as_str()?.parse().ok()
}
fn snapshot_channel(snapshot: &Value, id: u64) -> Option<&Value> {
snapshot["channels"].as_array()?.iter().find(|row| row["id"].as_u64() == Some(id))
}
fn own_channel(snapshot: &Value, own: u64) -> Option<u64> {
if snapshot["own_client_id"].as_u64() != Some(own) {
return None;
}
let channel = snapshot["own_channel_id"].as_u64().filter(|id| *id != 0)?;
snapshot_channel(snapshot, channel)?;
snapshot["clients"].as_array()?.iter()
.any(|client| client["id"].as_u64() == Some(own) && client["channel_id"].as_u64() == Some(channel))
.then_some(channel)
}
fn check_topic(stage: &str, row: &Value, expected: &str) -> Result<()> {
let field = row.get("channel_topic");
let text = field.and_then(Value::as_str);
if text == Some(expected) {
Ok(())
} else {
Err(format!("{stage}: channel row topic (present={}, string={}, matches=false)",
field.is_some(), text.is_some()))
}
}
fn check_quality(stage: &str, snapshot: &Value, id: u64, row: &Value) -> Result<()> {
let field = snapshot_channel(snapshot, id).and_then(|channel| channel.get("codec_quality"));
let quality = field.and_then(Value::as_u64);
if quality != Some(CODEC_QUALITY) {
return Err(format!("{stage}: snapshot codec quality (reported={}, integer={}, matches=false)",
field.is_some_and(|value| !value.is_null()), quality.is_some()));
}
// The raw row is sparse; require agreement only when the server reported it there.
if let Some(wire) = row.get("channel_codec_quality") {
let quality = wire.as_str().and_then(|text| text.parse::<u64>().ok());
if quality != Some(CODEC_QUALITY) {
return Err(format!("{stage}: channel row codec quality (present=true, wire_integer={}, matches=false)",
quality.is_some()));
}
}
Ok(())
}
fn check_local_refusal(reply: Reply, message: &str, generation: Option<u64>) -> Result<()> {
match reply {
Reply::Refused(error) if error["code"] == "bad_request" && error.get("ts_error").is_none()
&& error["message"] == message && error["detail"]["generation"].as_u64() == generation => Ok(()),
Reply::Refused(error) => Err(rejection("expected local validation", &error)),
Reply::Accepted(_) => Err("unexpected mutation acknowledgement".into()),
}
}
fn permission_probe(
core: &mut Core, channel: &RunChannel<'_>, label: &str, props: Value, expected: &[(&str, &str)],
) -> Result<Option<Value>> {
let before = channel.listed(core, Instant::now() + CONTROL)?;
match channel.edit(core, channel.generation, props)? {
Reply::Accepted(_) => {
let after = channel.wait_fields(core, expected).map_err(|err| format!("{label}: {err}"))?;
ensure(after["channel_topic"] == before["channel_topic"], "limit edit changed the topic")?;
let changed = expected.iter().any(|(key, _)| key.starts_with("channel_flag_") && before[*key] != after[*key]);
ensure(changed, "limit edit did not exercise a flag change")?;
println!("{label}: ok (server acknowledged, properties read back)");
Ok(Some(after))
}
Reply::Refused(error) if permission_denied(&error) => {
let after = channel.listed(core, Instant::now() + CONTROL)?;
ensure(after == before, "permission refusal was followed by a property change")?;
println!("{label}: refused (TS {PERMISSION_DENIED}; properties unchanged)");
Ok(None)
}
Reply::Refused(error) => Err(rejection(label, &error)),
}
}
fn permission_denied(error: &Value) -> bool {
error["code"] == "server_error" && error["ts_error"]["id"].as_u64() == Some(PERMISSION_DENIED)
}
fn report_inherited(label: &str, row: &Value, expected: &str) -> Result<()> {
match row.get(FAMILY_INHERITED) {
Some(value) if value.as_str() == Some(expected) => println!("{label}: ok (inherited flag read back)"),
Some(value) => return Err(format!("{label}: wrong inherited flag (present=true, string={}, matches=false)",
value.is_string())),
None => println!("{label}: unreported (server acknowledged; inherited flag not returned)"),
}
Ok(())
}
fn valid_parent(snapshot: &Value, id: u64) -> bool {
snapshot_channel(snapshot, id).is_some_and(|parent| parent["is_default"] == true && parent["channel_type"] == "permanent")
}
fn probe_inherited(core: &mut Core, channel: &RunChannel<'_>, lobby: u64) -> Result<()> {
const LABEL: &str = "family inheritance under a parent";
if !valid_parent(&core.snapshot, lobby) {
println!("{LABEL}: unverified (no valid default-channel parent)");
return Ok(());
}
// Move only our temporary channel. The default lobby is a parent reference,
// never the target of a write. Its properties and permissions stay untouched.
let before_move = channel.listed(core, Instant::now() + CONTROL)?;
match channel.move_under(core, lobby)? {
Reply::Accepted(_) => core.wait_for("generated channel under the default parent", |s| {
snapshot_channel(s, channel.id).is_some_and(|c| c["parent_id"].as_u64() == Some(lobby))
})?,
Reply::Refused(error) if permission_denied(&error) => {
ensure(channel.listed(core, Instant::now() + CONTROL)? == before_move,
"refused parent move changed the generated channel")?;
println!("{LABEL}: unverified (parent placement refused, TS {PERMISSION_DENIED}; channel unchanged)");
return Ok(());
}
Reply::Refused(error) => return Err(rejection("place generated channel under parent", &error)),
}
let before = channel.listed(core, Instant::now() + CONTROL)?;
if before[FAMILY_INHERITED] == "1" {
println!("{LABEL}: unverified (already inherited after placement; no explicit transition observed)");
return Ok(());
}
let properties = json!({"channel_flag_maxfamilyclients_unlimited": false, "channel_flag_maxfamilyclients_inherited": true});
match channel.edit(core, channel.generation, properties)? {
Reply::Accepted(_) => {
let after = channel.observe_row(core, |row| row[FAMILY_INHERITED] == "1")?;
report_inherited(LABEL, &after, "1")
}
Reply::Refused(error) if permission_denied(&error) => {
ensure(channel.listed(core, Instant::now() + CONTROL)? == before,
"permission refusal was followed by a property change")?;
println!("{LABEL}: refused (TS {PERMISSION_DENIED}; properties unchanged)");
Ok(())
}
Reply::Refused(error) => Err(rejection(LABEL, &error)),
}
}
fn check_first_sibling(core: &mut Core, sibling: u64, predecessor: u64) -> Result<()> {
let list = core.call("channel_list", json!({}))?;
let info = core.wire_call("channel_info", json!({"channel_id":sibling}))?;
for response in [&list, &info] {
let row = rows(response)?.iter().find(|row| wire_id(row) == Some(sibling)).ok_or("missing original sibling")?;
ensure(row["cpid"] == "0" && row["channel_order"].as_str().and_then(|v| v.parse().ok()) == Some(predecessor),
"channel property readback disagreed with the observed root sibling chain")?;
}
Ok(())
}
fn exercise_order(core: &mut Core, name: &str, lobby: u64, generation: u64, own: u64) -> Result<()> {
let first = core.snapshot["channels"].as_array().and_then(|rows| rows.iter().find(|row|row["parent_id"]==0 && row["order"]==0))
.and_then(|row|row["id"].as_u64()).ok_or("missing first root sibling")?;
let created = core.wire_call("channel_create", json!({"generation":generation,"parent_id":0,
"properties":{"channel_name":name,"channel_order":0}}))?;
let id=created["channel_id"].as_u64().filter(|id|*id!=0 && *id!=first).ok_or("missing temporary channel ID")?;
core.wait_for("first sibling relinked", |s| snapshot_channel(s,id).is_some_and(|r|r["channel_type"]=="temporary" && r["name"]==name && r["order"]==0)
&& snapshot_channel(s,first).is_some_and(|r|r["order"]==id))?;
check_first_sibling(core,first,id)?;
if own_channel(&core.snapshot,own)!=Some(id) {
core.wire_call("join_channel",json!({"channel_id":id}))?;
core.wait_for("own temporary channel joined",|s|own_channel(s,own)==Some(id))?;
}
core.wire_call("join_channel",json!({"channel_id":lobby}))?;
core.wait_for("temporary sibling expired",|s|own_channel(s,own)==Some(lobby) && snapshot_channel(s,id).is_none()
&& snapshot_channel(s,first).is_some_and(|r|r["order"]==0))?;
check_first_sibling(core,first,0)?;
println!("channel_list + channel_info: original sibling linked to new first channel, then restored on expiry");
Ok(())
}
fn subscription_step(
core: &mut Core, label: &str, target: Option<u64>, subscribe: bool,
matches: impl Fn(&Value) -> bool,
) -> Result<()> {
let (cmd, args) = match target {
Some(id) => ("channel_subscribe", json!({"channel_id": id, "subscribe": subscribe})),
None => ("channel_subscribe_all", json!({"subscribe": subscribe})),
};
let before = core.snapshot["rev"].as_u64().ok_or("missing snapshot revision")?;
// Cleanup may already be at the expected state. Test transitions are not.
let already_matches = matches(&core.snapshot);
match core.wire_request(cmd, args, CONTROL)? {
Reply::Accepted(_) => core.wait_for(label, |s| {
(already_matches || s["rev"].as_u64().is_some_and(|rev| rev > before)) && matches(s)
}).map_err(|error| {
let flags: Vec<_> = core.snapshot["channels"].as_array().into_iter().flatten()
.filter_map(|row| Some((row["id"].as_u64()?, row["subscribed"].as_bool()?))).collect();
format!("{error}; command acknowledged; snapshot revision {before} -> {}, channel subscription flags {flags:?}", core.snapshot["rev"])
}),
Reply::Refused(error) if permission_denied(&error) => {
Err(format!("{label}: unverified (server permission refusal, TS {PERMISSION_DENIED})"))
}
Reply::Refused(error) => Err(rejection(label, &error)),
}
}
fn exercise_subscriptions(core: &mut Core, name: &str, lobby: u64, generation: u64, own: u64) -> Result<()> {
ensure(valid_parent(&core.snapshot, lobby), "subscription target must be the original permanent lobby")?;
let lobby_name = snapshot_channel(&core.snapshot, lobby).and_then(|row| row["name"].as_str())
.ok_or("original lobby name missing")?.to_owned();
let list = core.call("channel_list", json!({}))?;
let existing = rows(&list)?;
ensure(existing.iter().any(|row| wire_id(row) == Some(lobby) && row["channel_name"] == lobby_name.as_str())
&& existing.iter().all(|row| wire_id(row).is_some() && row["channel_name"] != name),
"channel list did not verify the original lobby and unique temporary name")?;
let created = core.wire_call("channel_create", json!({"generation": generation, "parent_id": 0,
"properties": {"channel_name": name}}))?;
let id = created["channel_id"].as_u64().filter(|id| *id != 0 && existing.iter().all(|row| wire_id(row) != Some(*id)))
.ok_or("create did not return a new temporary channel ID")?;
let same_session = |s: &Value| s["generation"].as_u64() == Some(generation);
let temporary = |s: &Value| same_session(s) && snapshot_channel(s, id).is_some_and(|row| {
row["channel_type"] == "temporary" && row["name"] == name && row["parent_id"] == 0
});
core.wait_for("generated temporary channel", temporary)?;
if own_channel(&core.snapshot, own) != Some(id) {
core.wire_call("join_channel", json!({"channel_id": id}))?;
core.wait_for("enter generated temporary channel", |s| temporary(s) && own_channel(s, own) == Some(id))?;
}
// Let the connect-time subscribe-all and the move's book events settle
// before taking the baseline. The local read drains queued snapshots.
core.wait_wire_spacing();
core.call("channel_list", json!({}))?;
// The only client in the lobby at connect was us. Hold the temporary
// channel open while probing the now non-own lobby. Do not edit the lobby.
let in_scope = |s: &Value| temporary(s) && own_channel(s, own) == Some(id) && valid_parent(s, lobby)
&& snapshot_channel(s, lobby).is_some_and(|row| row["name"] == lobby_name.as_str())
&& s["clients"].as_array().is_some_and(|clients| clients.iter().all(|c| c["id"].as_u64() == Some(own)));
ensure(in_scope(&core.snapshot), "subscription target was not the empty original lobby in the same session")?;
let baseline: Vec<_> = core.snapshot["channels"].as_array().ok_or("missing snapshot channels")?.iter()
.filter(|row| row["id"].as_u64() != Some(id))
.map(|row| Ok((row["id"].as_u64().ok_or("missing channel ID")?,
row["subscribed"].as_bool().ok_or("missing channel subscription state")?)))
.collect::<Result<_>>()?;
let lobby_subscribed = baseline.iter().find(|(cid, _)| *cid == lobby).map(|(_, subscribed)| *subscribed)
.ok_or("subscription baseline did not include the original lobby")?;
let matches = |s: &Value, target: Option<u64>, value: bool| in_scope(s)
&& s["channels"].as_array().is_some_and(|channels| {
// Compare the stable ordered channel list; disappearance or a new
// channel makes this snapshot unsuitable as readback.
let others = channels.iter().filter(|row| row["id"].as_u64() != Some(id));
channels.len() == baseline.len() + 1 && others.zip(&baseline).all(|(row, &(cid, initial))| {
let expected = if target.is_none_or(|target| target == cid) { value } else { initial };
row["id"].as_u64() == Some(cid) && row["subscribed"].as_bool() == Some(expected)
})
});
let mut automatic = true; // The disposable core sends subscribe-all on connect.
let cases = (|| {
// Leaving the initially occupied lobby can leave a false book flag even while
// subscribe-all is active. Establish the starting server mode explicitly.
if !lobby_subscribed {
automatic = false;
subscription_step(core, "establish unsubscribed lobby", None, false, |s| matches(s, None, false))?;
for &(cid, subscribed) in &baseline {
if subscribed {
subscription_step(core, "restore other baseline subscription", Some(cid), true, |s| in_scope(s)
&& snapshot_channel(s, cid).is_some_and(|row| row["subscribed"] == true))?;
}
}
}
for subscribe in [!lobby_subscribed, lobby_subscribed] {
let label = if subscribe { "channelsubscribe" } else { "channelunsubscribe" };
let expected = |s: &Value| matches(s, Some(lobby), subscribe);
ensure(in_scope(&core.snapshot) && !expected(&core.snapshot), "no valid single-channel transition to observe")?;
subscription_step(core, label, Some(lobby), subscribe, expected)?;
println!("{label}: original non-own lobby subscribed={subscribe} in a new snapshot");
}
if baseline.len() > 1 {
println!("single-channel scope: {} other non-own channel(s) retained their initial flags", baseline.len() - 1);
} else {
println!("single-channel scope: isolation unverified (no second non-own channel)");
}
// Start with a direction that must change at least one visible channel.
let first_all = !baseline.iter().any(|&(_, subscribed)| subscribed);
for subscribe in [first_all, !first_all] {
let label = if subscribe { "channelsubscribeall" } else { "channelunsubscribeall" };
let expected = |s: &Value| matches(s, None, subscribe);
ensure(in_scope(&core.snapshot) && !expected(&core.snapshot), "no valid all-channel transition to observe")?;
automatic = subscribe;
subscription_step(core, label, None, subscribe, expected)?;
println!("{label}: subscribed={subscribe} for all {} observed non-own channel(s) in a new snapshot", baseline.len());
}
Ok(())
})();
let restore = (|| {
if cases.is_err() && core.state == Some("connected") {
core.wait_wire_spacing();
core.call("channel_list", json!({}))?;
}
ensure(core.state == Some("connected") && in_scope(&core.snapshot), "cannot restore subscriptions: fixture scope changed")?;
if !automatic {
subscription_step(core, "restore automatic subscriptions", None, true, |s| matches(s, None, true))?;
}
for &(cid, initial) in &baseline {
let expected = |s: &Value| in_scope(s) && snapshot_channel(s, cid).is_some_and(|row| row["subscribed"].as_bool() == Some(initial));
if !expected(&core.snapshot) {
subscription_step(core, "restore initial channel subscription", Some(cid), initial, expected)?;
}
}
ensure(matches(&core.snapshot, Some(lobby), lobby_subscribed), "initial non-own subscriptions were not restored")?;
println!("subscription cleanup: initial non-own flags restored");
Ok(())
})();
let leave = (|| {
ensure(core.state == Some("connected") && same_session(&core.snapshot) && valid_parent(&core.snapshot, lobby)
&& snapshot_channel(&core.snapshot, lobby).is_some_and(|row| row["name"] == lobby_name.as_str()),
"cannot return to the original lobby: fixture scope changed")?;
core.wire_call("join_channel", json!({"channel_id": lobby}))?;
core.wait_for("return to original lobby and observe temporary expiry", |s| {
same_session(s) && own_channel(s, own) == Some(lobby) && snapshot_channel(s, id).is_none()
})?;
println!("temporary channel cleanup: ok (left channel; server expired it)");
Ok(())
})();
combine(combine(cases, restore), leave)
}
enum Scenario { ChannelAdmin, ChannelOrder, ChannelSubscriptions, DatabaseId, ClientInfo }
fn exercise_client_info(core: &mut Core, own: u64, uid: &str) -> Result<()> {
let info = core.wire_call("client_info", json!({"client_id":own,"uid":uid}))?;
let fields = rows(&info)?;
ensure(!fields.is_empty() && fields.iter().all(|r| r["clid"].as_str().and_then(|v| v.parse::<u64>().ok()) == Some(own)),
"client info did not return rows scoped to the own client")?;
for key in ["client_version", "client_platform"] {
ensure(fields.iter().any(|r| r[key].as_str().is_some_and(|v| !v.is_empty())), "client info missing version or platform")?;
}
match core.request("client_info", json!({"client_id":own,"uid":"different-fixture-identity"}), Instant::now()+CONTROL)? {
Reply::Refused(error) if error["code"]=="target_changed" && error["ts_error"].is_null() => {},
_ => return Err("mismatched client UID did not return local target_changed".into()),
}
println!("client_info: own client version and platform received; mismatched UID refused locally");
Ok(())
}
fn exercise_database_id(core: &mut Core, name: &str, uid: &str) -> Result<()> {
let lookup = core.wire_call("client_database_id", json!({"uid":uid}))?;
let [row] = rows(&lookup)? else { return Err("UID lookup did not return one row".into()) };
ensure(row["cluid"].as_str() == Some(uid), "lookup returned a different UID")?;
let dbid = row["cldbid"].as_str().and_then(|v| v.parse::<u64>().ok()).filter(|id| *id > 0)
.ok_or("lookup did not return a positive database ID")?;
println!("client_database_id: exact roster UID and positive database ID");
let search = core.wire_call("client_database_find", json!({"pattern":name,"uid":false}))?;
let [found] = rows(&search)? else { return Err("unique test nickname did not return one row".into()) };
ensure(found["client_unique_identifier"].as_str() == Some(uid) && found["client_nickname"].as_str() == Some(name)
&& found["cldbid"].as_str().and_then(|v|v.parse::<u64>().ok()) == Some(dbid), "nickname search disagreed with UID lookup")?;
println!("client_database_find: nickname, UID and database ID agree");
Ok(())
}
fn exercise(core: &mut Core, name: &str, scenario: Scenario) -> Result<()> {
let profile = core.call("profile_get", json!({}))?;
ensure(profile["exists"] == false, "expected an empty disposable profile")?;
core.call("profile_create", json!({"nickname": name}))?;
let mute = core.call("set_audio", json!({"input_muted": true, "output_muted": true}))?;
ensure(mute["input_muted"] == true && mute["output_muted"] == true, "both mutes must be active before connect")?;
let connect = core.wire_request("connect", json!({"address": ENDPOINT}), CONNECT)?.require("connect")?;
let own = connect["own_client_id"].as_u64().filter(|id| *id != 0).ok_or("connect did not return an own client ID")?;
ensure(core.state == Some("connected"), "core did not reach connected state")?;
// Connect can be acknowledged before the own client and channel enter the book.
core.wait_for("initial channel and own-client roster", |s| own_channel(s, own).is_some())?;
let snapshot = &core.snapshot;
let generation = snapshot["generation"].as_u64().filter(|g| *g != 0).ok_or("connected snapshot has no generation")?;
let lobby = own_channel(snapshot, own).ok_or("missing initial channel")?;
let beta14 = snapshot["server"]["version"].as_str().is_some_and(|s| {
s.starts_with("6.") && s.split(|c: char| !c.is_ascii_alphanumeric()).any(|part| part.eq_ignore_ascii_case("beta14"))
});
ensure(beta14, "loopback endpoint did not report TS6 beta14")?;
ensure(snapshot_channel(snapshot, lobby).is_some_and(|c| c["is_default"] == true), "session did not start in the fixture's default channel")?;
ensure(snapshot["clients"].as_array().is_some_and(|clients| {
clients.len() == 1 && clients[0]["id"].as_u64() == Some(own)
&& clients[0]["client_type"] == "normal" && clients[0]["input_muted"] == true && clients[0]["output_muted"] == true
}), "connected snapshot did not show only the muted fixture client")?;
println!("connect: ok (loopback beta14; disposable guest; both mutes active)");
match scenario {
Scenario::ClientInfo => {
let uid = snapshot["clients"][0]["uid"].as_str().filter(|s|!s.is_empty()).ok_or("own roster UID missing")?.to_owned();
return exercise_client_info(core, own, &uid);
}
Scenario::ChannelOrder => return exercise_order(core, name, lobby, generation, own),
Scenario::ChannelSubscriptions => return exercise_subscriptions(core, name, lobby, generation, own),
Scenario::DatabaseId => {
let uid = snapshot["clients"][0]["uid"].as_str().filter(|s|!s.is_empty()).ok_or("own roster UID missing")?.to_owned();
return exercise_database_id(core, name, &uid);
}
Scenario::ChannelAdmin => {}
}
let server = core.wire_call("server_info", json!({}))?;
let server_rows = rows(&server)?;
ensure(server_rows.len() == 1 && server_rows[0].as_object().is_some_and(|row| !row.is_empty()),
"server_info did not return observed server properties")?;
println!("server_info: ok (read only)");
let list = core.call("channel_list", json!({}))?;
let existing = rows(&list)?;
ensure(existing.iter().any(|row| wire_id(row) == Some(lobby))
&& existing.iter().all(|row| wire_id(row).is_some() && row["channel_name"].as_str() != Some(name)),
"initial channel list cannot establish a unique writable target")?;
println!("channel_list: ok (baseline read only)");
let create = core.wire_call("channel_create", json!({"generation": generation, "parent_id": 0, "properties": {
"channel_name": name, "channel_topic": ORIGINAL_TOPIC, "channel_codec_quality": CODEC_QUALITY,
}}))?;
let id = create["channel_id"].as_u64().filter(|id| *id != 0 && existing.iter().all(|row| wire_id(row) != Some(*id)))
.ok_or("create did not return a newly generated channel ID")?;
let channel = RunChannel { id, name, generation };
core.wait_for("temporary channel and own-client roster", |s| {
snapshot_channel(s, id).is_some() && own_channel(s, own).is_some()
})?;
ensure(snapshot_channel(&core.snapshot, id).is_some_and(|c| c["channel_type"] == "temporary" && c["parent_id"] == 0
&& c["name"].as_str() == Some(name)), "created channel was not the generated root temporary channel")?;
if own_channel(&core.snapshot, own) != Some(id) {
core.wire_call("join_channel", json!({"channel_id": id}))?;
core.wait_for("enter generated channel", |s| own_channel(s, own) == Some(id))?;
}
let original = channel.info(core)?;
check_topic("create", &original, ORIGINAL_TOPIC)?;
check_quality("create", &core.snapshot, id, &original)?;
println!("channel_create + channel_info: ok (own root temporary channel, topic and codec quality read back)");
channel.edit(core, generation, json!({"channel_topic": UPDATED_TOPIC}))?.require("sparse channel_edit")?;
let edited = channel.wait_fields(core, &[("channel_topic", UPDATED_TOPIC)])?;
core.wait_for("edited channel snapshot", |s| snapshot_channel(s, id).is_some_and(|c| c["topic"] == UPDATED_TOPIC))?;
check_topic("sparse edit", &edited, UPDATED_TOPIC)?;
check_quality("sparse edit", &core.snapshot, id, &edited)?;
println!("sparse channel_edit: ok (topic changed; name and codec quality preserved)");
for (label, attempt, props, message, live_generation) in [
("invalid codec quality", generation, json!({"channel_topic": "invalid quality marker", "channel_codec_quality": 11}),
"channel_codec_quality must be an integer 0..=10", None),
("stale generation", generation.checked_add(1).ok_or("connection generation exhausted")?,
json!({"channel_topic": "stale generation marker"}), "connection changed; reload and confirm again", Some(generation)),
] {
// These two requests must be rejected locally without reaching the server.
let args = channel.edit_args(core, attempt, props)?;
check_local_refusal(core.request("channel_edit", args, Instant::now() + CONTROL)?, message, live_generation)
.map_err(|err| format!("{label}: {err}"))?;
let after = channel.listed(core, Instant::now() + CONTROL)?;
ensure(after == edited, "rejected edit changed live channel properties")?;
check_quality(label, &core.snapshot, id, &after)?;
println!("{label}: rejected (local bad_request; properties unchanged)");
}
let finite_clients = [("channel_maxclients", "3"), ("channel_flag_maxclients_unlimited", "0")];
let unlimited_clients = [("channel_maxclients", "-1"), ("channel_flag_maxclients_unlimited", "1")];
let (props, expected) = if edited["channel_flag_maxclients_unlimited"] == "0" {
(json!({"channel_maxclients": -1, "channel_flag_maxclients_unlimited": true}), &unlimited_clients)
} else {
(json!({"channel_maxclients": 3, "channel_flag_maxclients_unlimited": false}), &finite_clients)
};
let max_clients = permission_probe(core, &channel, "maximum clients / unlimited flag", props, expected)?;
let (family_limit, unlimited, wire_limit, wire_unlimited) = if edited["channel_flag_maxfamilyclients_unlimited"] == "0"
&& edited["channel_flag_maxfamilyclients_inherited"] == "0" {
(-1, true, "-1", "1")
} else {
(4, false, "4", "0")
};
let family = permission_probe(core, &channel, "family limit / unlimited flag",
json!({"channel_maxfamilyclients": family_limit, "channel_flag_maxfamilyclients_unlimited": unlimited,
"channel_flag_maxfamilyclients_inherited": false}),
&[("channel_maxfamilyclients", wire_limit), ("channel_flag_maxfamilyclients_unlimited", wire_unlimited)])?;
let written = max_clients.is_some() as usize + family.is_some() as usize;
println!("limit flag cases: {written} written and read back, {} refused", 2 - written);
if let Some(row) = family {
report_inherited("root family inheritance disabled", &row, "0")?;
probe_inherited(core, &channel, lobby)?;
} else {
println!("family inheritance: unverified (family-limit baseline refused)");
}
// Join the original default as this same client; never edit it or issue a
// delete verb. Only the generated temporary channel is expected to expire.
core.wire_call("join_channel", json!({"channel_id": lobby}))?;
core.wait_for("leave generated channel and observe its expiry", |s| {
own_channel(s, own) == Some(lobby) && snapshot_channel(s, id).is_none()
})?;
println!("temporary channel cleanup: ok (left channel; server expired it)");
Ok(())
}
fn run() -> Result<()> {
let mut args = std::env::args_os().skip(1);
let scenario = match (args.next(),args.next()) {
(None,None)=>Scenario::ChannelAdmin,
(Some(arg),None) if arg=="--channel-order"=>Scenario::ChannelOrder,
(Some(arg),None) if arg=="--channel-subscriptions"=>Scenario::ChannelSubscriptions,
(Some(arg),None) if arg=="--client-database-id"=>Scenario::DatabaseId,
(Some(arg),None) if arg=="--client-info"=>Scenario::ClientInfo,
_=>return Err("usage: channel_admin_qa [--channel-order | --channel-subscriptions | --client-database-id | --client-info]".into()),
};
let exe = std::env::var_os("TEAMSPEACH_QA_CORE").map(PathBuf::from)
.filter(|path| path.is_absolute() && path.is_file() && path.file_name().and_then(|n| n.to_str())
.is_some_and(|n| n.eq_ignore_ascii_case("teamspeach-core.exe")))
.ok_or("set TEAMSPEACH_QA_CORE to the absolute path of a disposable teamspeach-core.exe")?;
let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "invalid system clock")?.as_nanos();
let name = format!("PeachQA-{:x}-{stamp:x}", std::process::id());
let root = std::env::temp_dir().join(&name);
ensure(root.is_absolute(), "system temporary directory must be absolute")?;
fs::create_dir(&root).map_err(|_| "could not create unique scratch directory")?;
let result = (|| {
let mut core = Core::start(&exe, &root)?;
let cases = exercise(&mut core, &name, scenario);
let cleanup = core.leave_and_close();
combine(cases, cleanup)
})();
let profile = fs::remove_dir_all(&root).map_err(|_| "could not remove scratch profile".into());
if profile.is_ok() {
println!("scratch profile cleanup: ok");
}
combine(result, profile)
}
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("channel admin QA failed: {error}");
ExitCode::FAILURE
}
}
}
File diff suppressed because it is too large. Load diff
+333 -58
View File
@@ -24,6 +24,10 @@ pub mod extra;
/// Upper bound for rows collected for one list request.
pub const MAX_ROWS: usize = 10_000;
/// Maximum number of Unicode scalar values in a server or channel group name.
pub const MAX_GROUP_NAME_CHARS: usize = 128;
/// Inclusive limit for integer arguments shared with the reference command interface.
pub const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
const MAX_TEXT: usize = 8192;
const MAX_SHORT: usize = 1024;
@@ -89,7 +93,7 @@ const CHANNEL_CREATE: &[(&str, Kind)] = &[
("channel_codec_quality", Kind::Uint(10)),
("channel_maxclients", Kind::Int(-1, i32::MAX as i64)),
("channel_maxfamilyclients", Kind::Int(-1, i32::MAX as i64)),
("channel_order", Kind::Uint(u64::MAX)),
("channel_order", Kind::Uint(MAX_SAFE_INTEGER)),
("channel_codec_is_unencrypted", Kind::Bool),
("channel_delete_delay", Kind::Uint(u32::MAX as u64)),
("channel_flag_maxclients_unlimited", Kind::Bool),
@@ -102,7 +106,7 @@ const CHANNEL_CREATE: &[(&str, Kind)] = &[
];
/// Fields of `channeledit` (`ChannelEdit` declaration, minus `cid`).
const CHANNEL_EDIT: &[(&str, Kind)] = &[
("channel_order", Kind::Uint(u64::MAX)),
("channel_order", Kind::Uint(MAX_SAFE_INTEGER)),
("channel_name", CHANNEL_NAME),
("channel_topic", Kind::Str(255)),
("channel_flag_default", Kind::Bool),
@@ -147,18 +151,18 @@ const SERVER_EDIT: &[(&str, Kind)] = &[
("virtualserver_reserved_slots", Kind::Uint(u16::MAX as u64)),
("virtualserver_hostbanner_mode", Kind::Uint(2)),
("virtualserver_nickname", Kind::Str(MAX_SHORT)),
("virtualserver_max_download_total_bandwidth", Kind::Uint(u64::MAX)),
("virtualserver_max_upload_total_bandwidth", Kind::Uint(u64::MAX)),
("virtualserver_download_quota", Kind::Uint(u64::MAX)),
("virtualserver_upload_quota", Kind::Uint(u64::MAX)),
("virtualserver_max_download_total_bandwidth", Kind::Uint(MAX_SAFE_INTEGER)),
("virtualserver_max_upload_total_bandwidth", Kind::Uint(MAX_SAFE_INTEGER)),
("virtualserver_download_quota", Kind::Uint(MAX_SAFE_INTEGER)),
("virtualserver_upload_quota", Kind::Uint(MAX_SAFE_INTEGER)),
("virtualserver_antiflood_points_tick_reduce", Kind::Uint(u32::MAX as u64)),
("virtualserver_antiflood_points_needed_command_block", Kind::Uint(u32::MAX as u64)),
("virtualserver_antiflood_points_needed_ip_block", Kind::Uint(u32::MAX as u64)),
("virtualserver_codec_encryption_mode", Kind::Uint(2)),
("virtualserver_needed_identity_security_level", Kind::Uint(u8::MAX as u64)),
("virtualserver_default_server_group", Kind::Uint(u64::MAX)),
("virtualserver_default_channel_group", Kind::Uint(u64::MAX)),
("virtualserver_default_channel_admin_group", Kind::Uint(u64::MAX)),
("virtualserver_default_server_group", Kind::Uint(MAX_SAFE_INTEGER)),
("virtualserver_default_channel_group", Kind::Uint(MAX_SAFE_INTEGER)),
("virtualserver_default_channel_admin_group", Kind::Uint(MAX_SAFE_INTEGER)),
("virtualserver_complain_autoban_count", Kind::Uint(u32::MAX as u64)),
("virtualserver_complain_autoban_time", Kind::Uint(u32::MAX as u64)),
("virtualserver_complain_remove_time", Kind::Uint(u32::MAX as u64)),
@@ -353,11 +357,18 @@ fn check_opt(field: &str, value: &Option<String>, max: usize) -> Result<(), Erro
Ok(())
}
fn positive(field: &str, v: u64) -> Result<u64, ErrorObj> {
if v == 0 { Err(bad(format!("{field} must be positive"))) } else { Ok(v) }
fn nonnegative(field: &str, v: u64) -> Result<(), ErrorObj> {
if v > MAX_SAFE_INTEGER { Err(bad(format!("{field} exceeds the maximum safe integer"))) } else { Ok(()) }
}
fn generation(v: u64) -> Result<u64, ErrorObj> { positive("generation", v) }
fn positive(field: &str, v: u64) -> Result<(), ErrorObj> {
if v == 0 { Err(bad(format!("{field} must be positive"))) } else { nonnegative(field, v) }
}
pub(crate) fn generation(v: u64) -> Result<u64, ErrorObj> {
if !(1..=MAX_SAFE_INTEGER).contains(&v) { return Err(bad("generation must be a positive safe integer")); }
Ok(v)
}
/// Validates a property object against an allowlist and renders wire values.
fn properties(value: Map<String, Value>, allowed: &[(&'static str, Kind)]) -> Result<Vec<(&'static str, String)>, ErrorObj> {
@@ -442,11 +453,11 @@ struct GroupArgs { group_id: u64 }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AwayArgs { away: bool, #[serde(default)] message: Option<String> }
struct AwayArgs { away: bool, #[serde(default, deserialize_with = "crate::protocol::present_string")] message: Option<String> }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TalkRequestArgs { request: bool, #[serde(default)] message: Option<String> }
struct TalkRequestArgs { request: bool, #[serde(default, deserialize_with = "crate::protocol::present_string")] message: Option<String> }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -612,14 +623,20 @@ pub(crate) fn validate(command: &AdminCommand) -> Result<(), ErrorObj> {
if let C::Extra(c) = command { return c.validate(); }
if let Some(g) = command.generation() { generation(g)?; }
match command {
C::ChannelCreate { properties, .. } => properties.check_scope(PropertyScope::ChannelCreate)?,
C::ChannelCreate { properties, parent_id, .. } => {
properties.check_scope(PropertyScope::ChannelCreate)?;
nonnegative("parent_id", *parent_id)?;
}
C::ChannelEdit { channel_id, properties, .. } => {
properties.check_scope(PropertyScope::ChannelEdit)?;
positive("channel_id", *channel_id)?;
}
C::ServerEdit { properties, .. } => properties.check_scope(PropertyScope::ServerEdit)?,
C::ChannelMove { channel_id, parent_id, .. } => {
C::ChannelMove { channel_id, parent_id, order, .. } => {
nonnegative("parent_id", *parent_id)?;
if let Some(order) = order { nonnegative("order", *order)?; }
if parent_id == channel_id { return Err(bad("a channel cannot be its own parent")); }
if order.as_ref() == Some(channel_id) { return Err(bad("a channel cannot precede itself")); }
positive("channel_id", *channel_id)?;
}
C::ChannelDelete { channel_id, .. } | C::ChannelSubscribe { channel_id, .. }
@@ -653,6 +670,7 @@ pub(crate) fn validate(command: &AdminCommand) -> Result<(), ErrorObj> {
}
C::PrivilegeKeyDelete { token, .. } | C::PrivilegeKeyUse { token, .. } => check_str("token", token, 255, false)?,
C::TempPasswordAdd { password, description, duration_s, channel_id, channel_password, .. } => {
nonnegative("channel_id", *channel_id)?;
check_str("password", password, 255, false)?;
check_str("description", description, 255, true)?;
check_str("channel_password", channel_password, 255, true)?;
@@ -669,21 +687,62 @@ pub(crate) fn validate(command: &AdminCommand) -> Result<(), ErrorObj> {
// ------------------------------------------------------------ replies
#[derive(Debug)]
pub struct ClientInfoReply {
pub(crate) client_id: u16,
uid: String,
rows: Result<Vec<Row>, ErrorObj>,
}
impl ClientInfoReply {
pub(crate) fn new(client_id: u16, uid: String) -> Self {
Self { client_id, uid, rows: Ok(Vec::new()) }
}
fn collect(&mut self, raw: &RawNotification) {
let Ok(rows) = &mut self.rows else { return };
for row in &raw.items {
if row.get("clid").and_then(|v| v.parse::<u16>().ok()) != Some(self.client_id) { continue; }
if row.get("client_unique_identifier").is_some_and(|uid| uid != &self.uid) {
self.rows = Err(Self::target_changed());
return;
}
if rows.len() >= MAX_ROWS {
self.rows = Err(ErrorObj::new(ErrorCode::ServerError, "client information exceeds the row limit"));
return;
}
rows.push(row.clone());
}
}
fn target_changed() -> ErrorObj { ErrorObj::new(ErrorCode::TargetChanged, "client identity changed; reopen information") }
pub(crate) fn finish(self, current_uid: Option<&str>) -> Result<Value, ErrorObj> {
if current_uid != Some(self.uid.as_str()) { return Err(Self::target_changed()); }
let rows = self.rows?;
if rows.is_empty() { return Err(ErrorObj::new(ErrorCode::ServerError,"The server returned no information for the requested client")); }
Ok(json!({"rows": rows}))
}
}
/// How the answer to an admin command is assembled.
#[derive(Debug)]
pub enum Reply {
Ack,
/// Rows of `notify` collected until the command result; `key` filters rows by the first
/// entry's id (list notifications carry it there only).
/// Rows without an explicit scope inherit the last scope in this reply.
Rows { notify: &'static str, key: Option<(&'static str, String)>, rows: Vec<Row>, overflow: bool, accept: bool },
/// `channelcreate`: the id comes from our own `notifychannelcreated` with that name.
Created { name: String, invoker: u16, channel_id: Option<u64> },
/// Only an unambiguous creation by our client under the requested parent identifies the new channel.
Created { name: String, parent: u64, invoker: u16, channel_id: Option<u64>, ambiguous: bool },
/// `tokenadd`: the key comes from `notifytokenadd`.
Token { token: Option<String> },
GroupCreated { notify: &'static str, key: &'static str, name: String, group_id: Option<u64>, ambiguous: bool },
Token { token: Option<String>, ambiguous: bool },
GroupCreated { notify: &'static str, key: &'static str, name: String, group_type: u8, existing: std::collections::HashSet<u64>, group_id: Option<u64>, ambiguous: bool },
/// `channelgetdescription`: the description comes from `notifychanneledited`.
Description { channel_id: u64, description: Option<String> },
ChannelInfo { channel_id: u64 },
/// Keep the pending notification slot until the command result arrives.
ChannelReadDeleted,
ClientInfo(ClientInfoReply),
DatabaseId { uid: String, id: Option<u64>, ambiguous: bool },
/// `permissionlist` refresh before answering `admin_context`.
Context,
}
@@ -699,7 +758,9 @@ impl Reply {
Reply::Rows { notify, .. } => Some(notify),
Reply::Token { .. } => Some("notifytokenadd"),
Reply::GroupCreated { notify, .. } => Some(notify),
Reply::ChannelInfo { .. } | Reply::Description { .. } => Some("notifychanneledited"),
Reply::DatabaseId { .. } => Some("notifyclientdbidfromuid"),
Reply::ClientInfo(_) => Some("notifyclientupdated"),
Reply::ChannelInfo { .. } | Reply::Description { .. } | Reply::ChannelReadDeleted => Some("notifychanneledited"),
Reply::Created { .. } => Some("notifychannelcreated"),
_ => None,
}
@@ -708,47 +769,66 @@ impl Reply {
/// Feed a tapped notification.
pub fn collect(&mut self, raw: &RawNotification) {
match self {
Reply::Description { channel_id, .. } | Reply::ChannelInfo { channel_id }
if raw.name == "notifychanneldeleted" && raw.items.iter().any(|row| row.get("cid").and_then(|id| id.parse::<u64>().ok()) == Some(*channel_id)) => {
*self = Reply::ChannelReadDeleted;
}
Reply::ClientInfo(info) if raw.name == "notifyclientupdated" => info.collect(raw),
Reply::Rows { notify, key, rows, overflow, accept } if *notify == raw.name => {
// A continuation without the id belongs to the previous accepted notification.
if let Some((k, v)) = key {
match raw.items.first().and_then(|i| i.get(*k)) {
Some(id) => *accept = id == v,
None => {}
}
} else {
*accept = true;
}
if !*accept { return; }
for row in &raw.items {
if let Some((k, v)) = key {
if let Some(id) = row.get(*k) { *accept = id == v; }
if !*accept { continue; }
}
if rows.len() >= MAX_ROWS { *overflow = true; return; }
rows.push(row.clone());
}
}
Reply::Created { name, invoker, channel_id } if raw.name == "notifychannelcreated" && channel_id.is_none() => {
Reply::Created { name, parent, invoker, channel_id, ambiguous } if raw.name == "notifychannelcreated" => {
for row in &raw.items {
let mine = row.get("invokerid").and_then(|v| v.parse::<u16>().ok()) == Some(*invoker);
if mine && row.get("channel_name").map(String::as_str) == Some(name.as_str()) {
*channel_id = row.get("cid").and_then(|v| v.parse().ok());
if mine && row.get("channel_name") == Some(name) && row.get("cpid").and_then(|v| v.parse::<u64>().ok()) == Some(*parent) {
if let Some(id) = row.get("cid").and_then(|v| v.parse::<u64>().ok()).filter(|id| *id != 0) {
if channel_id.is_some_and(|old| old != id) { *ambiguous = true; }
*channel_id = Some(id);
}
}
}
}
Reply::GroupCreated { notify, key, name, group_id, ambiguous } if *notify == raw.name => {
Reply::GroupCreated { notify, key, name, group_type, existing, group_id, ambiguous } if *notify == raw.name => {
for row in &raw.items {
if row.get("name") == Some(name) {
if let Some(id) = row.get(*key).and_then(|v| v.parse::<u64>().ok()) {
if row.get("name") == Some(name) && row.get("type").and_then(|v| v.parse::<u8>().ok()) == Some(*group_type) {
if let Some(id) = row.get(*key).and_then(|v| v.parse::<u64>().ok()).filter(|id| *id != 0 && !existing.contains(id)) {
if group_id.is_some_and(|old| old != id) { *ambiguous = true; }
*group_id = Some(id);
}
}
}
},
Reply::Token { token } if raw.name == "notifytokenadd" => {
*token = raw.items.first().and_then(|i| i.get("token")).cloned();
Reply::DatabaseId { uid, id, ambiguous } if raw.name == "notifyclientdbidfromuid" => {
for row in &raw.items {
if row.get("cluid") != Some(uid) { continue; }
if let Some(found) = row.get("cldbid").and_then(|s| s.parse::<u64>().ok()).filter(|n| *n > 0) {
if id.is_some_and(|previous| previous != found) { *ambiguous = true; }
*id = Some(found);
}
}
}
Reply::Description { channel_id, description } if raw.name == "notifychanneledited" => {
Reply::Token { token, ambiguous } if raw.name == "notifytokenadd" && !*ambiguous => {
for value in raw.items.iter().filter_map(|row| row.get("token")) {
if value.trim().is_empty() || value.chars().count() > 255 || value.chars().any(char::is_control) { continue; }
match token {
Some(previous) if previous != value => { *ambiguous = true; break; }
None => *token = Some(value.clone()),
_ => {}
}
}
}
Reply::Description { channel_id, description } if matches!(raw.name.as_str(), "notifychanneledited" | "notifychanneldescriptionchanged") => {
for row in &raw.items {
if row.get("cid").and_then(|v| v.parse::<u64>().ok()) == Some(*channel_id) {
if let Some(d) = row.get("channel_description") { *description = Some(d.clone()); }
if raw.name == "notifychanneldescriptionchanged" { *description = None; }
else if let Some(d) = row.get("channel_description") { *description = Some(d.clone()); }
}
}
}
@@ -771,14 +851,18 @@ pub fn finish(reply: Reply) -> Result<Value, ErrorObj> {
format!("the server returned more than {MAX_ROWS} rows; the list is not complete"),
)),
Reply::Rows { rows, .. } => Ok(json!({ "rows": rows })),
Reply::DatabaseId { uid, id: Some(id), ambiguous: false } => Ok(json!({"rows":[{"cluid":uid,"cldbid":id.to_string()}]})),
Reply::DatabaseId { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "server did not return a unique database ID for the requested UID")),
Reply::GroupCreated { group_id: Some(id), ambiguous: false, .. } => Ok(json!({ "group_id": id })),
Reply::GroupCreated { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "group was accepted but its ID was not uniquely returned; reload groups before continuing").with_detail(json!({"created": true}))),
Reply::ChannelInfo { .. } => Err(ErrorObj::new(ErrorCode::Internal, "channel info is answered by the session")),
Reply::Created { channel_id, .. } => Ok(json!({ "channel_id": channel_id })),
Reply::Token { token: Some(token) } => Ok(json!({ "token": token })),
Reply::Token { token: None } => Err(ErrorObj::new(
Reply::ChannelInfo { .. } | Reply::ClientInfo(_) => Err(ErrorObj::new(ErrorCode::Internal, "target information is answered by the session")),
Reply::ChannelReadDeleted => Err(ErrorObj::new(ErrorCode::TargetChanged, "channel was deleted while its properties were being read")),
Reply::Created { channel_id: Some(id), ambiguous: false, .. } => Ok(json!({ "channel_id": id })),
Reply::Created { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "channel was accepted but its ID was not uniquely returned; reload channels before continuing").with_detail(json!({"created": true}))),
Reply::Token { token: Some(token), ambiguous: false } => Ok(json!({ "token": token })),
Reply::Token { .. } => Err(ErrorObj::new(
ErrorCode::ServerError,
"the server accepted the privilege key but did not send it; reload the list",
"the server accepted the privilege key but did not return one unique key; reload the list",
)
.with_detail(json!({ "created": true }))),
Reply::Description { description, .. } => Ok(json!({ "description": description })),
@@ -793,6 +877,7 @@ pub struct Live<'a> {
pub own_client: u16,
pub server_uid: &'a str,
pub channel: &'a dyn Fn(u64) -> Option<String>,
pub group_ids: &'a dyn Fn(extra::GroupKind) -> std::collections::HashSet<u64>,
}
/// Checks the destructive-action confirmation against the live target.
@@ -821,7 +906,7 @@ pub fn build(cmd: &AdminCommand, live: &Live) -> Result<(OutCommand, Reply), Err
let mut a = vec![("cpid", s(*parent_id))];
a.extend(properties.iter().map(|(k, v)| (*k, v.clone())));
let name = properties.iter().find(|(k, _)| *k == "channel_name").map(|(_, v)| v.clone()).unwrap_or_default();
(menu::command("channelcreate", &a), Reply::Created { name, invoker: live.own_client, channel_id: None })
(menu::command("channelcreate", &a), Reply::Created { name, parent: *parent_id, invoker: live.own_client, channel_id: None, ambiguous: false })
}
C::ChannelEdit { channel_id, properties, .. } => {
channel_exists(live, *channel_id, "channel")?;
@@ -885,7 +970,7 @@ pub fn build(cmd: &AdminCommand, live: &Live) -> Result<(OutCommand, Reply), Err
if *channel_id != 0 { channel_exists(live, *channel_id, "channel")?; }
let kind = match kind { PrivilegeKeyKind::ServerGroup => "0", PrivilegeKeyKind::ChannelGroup => "1" };
let a = [("tokentype", kind.into()), ("tokenid1", s(*group_id)), ("tokenid2", s(*channel_id)), ("tokendescription", description.clone())];
(menu::command("tokenadd", &a), Reply::Token { token: None })
(menu::command("tokenadd", &a), Reply::Token { token: None, ambiguous: false })
}
C::PrivilegeKeyDelete { token, confirm: c, .. } => {
confirm(c, token)?;
@@ -965,6 +1050,7 @@ mod tests {
fn direct_admin_and_permission_arguments_reject_invalid_values() {
use extra::{Command as E, GroupKind, Permission};
let invalid = [
AdminCommand::ChannelMove { generation: 1, channel_id: 9, parent_id: 0, order: Some(9) },
AdminCommand::BanDelete { generation: 0, ban_id: 1, confirm: "1".into() },
AdminCommand::SetAway { away: false, message: Some("reason".into()) },
AdminCommand::TalkRequest { request: true, message: Some("x".repeat(51)) },
@@ -992,7 +1078,72 @@ mod tests {
fn content(cmd: OutCommand) -> String { String::from_utf8(cmd.into_packet().content().to_vec()).unwrap() }
fn live<'a>(channel: &'a dyn Fn(u64) -> Option<String>) -> Live<'a> {
Live { own_client: 7, server_uid: "srv=", channel }
Live { own_client: 7, server_uid: "srv=", channel, group_ids: &|_| Default::default() }
}
#[test]
fn client_info_checks_identity_at_ack_even_when_updates_omit_uid() {
let mut missing = ClientInfoReply::new(7, "original=".into());
missing.collect(&crate::rawcmd::parse(b"notifyclientupdated clid=8 client_version=other").unwrap());
assert_eq!(missing.finish(Some("original=")).unwrap_err().code, ErrorCode::ServerError);
let collect = |extra: Option<&[u8]>| {
let mut r = Reply::ClientInfo(ClientInfoReply::new(7, "original=".into()));
r.collect(&crate::rawcmd::parse(b"notifyclientupdated clid=8 client_version=other|clid=7 client_version=test|client_platform=unscoped").unwrap());
if let Some(packet) = extra { r.collect(&crate::rawcmd::parse(packet).unwrap()); }
let Reply::ClientInfo(r) = r else { unreachable!() }; r
};
assert_eq!(collect(None).finish(Some("original=")).unwrap(), json!({"rows":[{"clid":"7","client_version":"test"}]}));
for uid in [None, Some("replacement=")] {
assert_eq!(collect(None).finish(uid).unwrap_err().code, ErrorCode::TargetChanged);
}
assert_eq!(collect(Some(b"notifyclientupdated clid=7 client_unique_identifier=replacement=")).finish(Some("original=")).unwrap_err().code, ErrorCode::TargetChanged);
}
#[test]
fn database_id_lookup_requires_the_requested_uid_and_one_positive_id() {
let cmd = parse_json("client_database_id", json!({"uid":"peer/one="})).unwrap();
let lookup = |packets: &[&[u8]]| {
let (_, mut reply) = build(&cmd, &live(&|_| None)).unwrap();
for packet in packets { reply.collect(&crate::rawcmd::parse(packet).unwrap()); }
finish(reply)
};
let foreign = br"notifyclientdbidfromuid cluid=other cldbid=9|cldbid=10".as_slice();
let zero = br"notifyclientdbidfromuid cluid=peer\/one= cldbid=0".as_slice();
let found = br"notifyclientdbidfromuid cluid=other cldbid=9|cluid=peer\/one= cldbid=17|cldbid=23".as_slice();
let conflict = br"notifyclientdbidfromuid cluid=peer\/one= cldbid=18".as_slice();
assert_eq!(lookup(&[foreign,zero]).unwrap_err().code, ErrorCode::ServerError);
assert_eq!(lookup(&[found,foreign,found]).unwrap(), json!({"rows":[{"cluid":"peer/one=","cldbid":"17"}]}));
assert_eq!(lookup(&[found,conflict]).unwrap_err().code, ErrorCode::ServerError);
}
#[test]
fn group_add_requires_a_unique_new_id_of_the_requested_type() {
use extra::GroupKind;
let group_ids = |kind| match kind {
GroupKind::Server => [4].into_iter().collect(),
GroupKind::Channel => [9].into_iter().collect(),
};
let state = Live { group_ids: &group_ids, ..live(&|_| None) };
for (kind, notify, key, old) in [("server", "notifyservergrouplist", "sgid", 4), ("channel", "notifychannelgrouplist", "cgid", 9)] {
let cmd = parse_json("group_add", json!({"generation":1,"kind":kind,"name":"Operators","type":1})).unwrap();
let begin = || build(&cmd, &state).unwrap().1;
let collect = |r: &mut Reply, id: u64, ty: u8| {
let packet = format!("{notify} {key}={id} type={ty} name=Operators");
r.collect(&crate::rawcmd::parse(packet.as_bytes()).unwrap());
};
let mut missing = begin();
collect(&mut missing, old, 1); collect(&mut missing, 0, 1); collect(&mut missing, 31, 0);
let error = finish(missing).unwrap_err();
assert_eq!(error.code, ErrorCode::ServerError);
assert_eq!(error.detail, Some(json!({"created":true})));
let mut unique = begin();
collect(&mut unique, old, 1); collect(&mut unique, 31, 0);
collect(&mut unique, 32, 1); collect(&mut unique, 32, 1);
assert_eq!(finish(unique).unwrap(), json!({"group_id":32}));
let mut ambiguous = begin();
collect(&mut ambiguous, 32, 1); collect(&mut ambiguous, 33, 1);
assert_eq!(finish(ambiguous).unwrap_err().detail, Some(json!({"created":true})));
}
}
#[test]
@@ -1068,7 +1219,7 @@ mod tests {
assert!(text.starts_with("channelcreate cpid=0 "), "{text}");
assert!(text.contains(&format!("channel_password={}", encode_password(b"secret").replace('/', "\\/"))), "{text}");
assert!(text.contains("channel_flag_password=1") && text.contains("channel_flag_permanent=1") && text.contains("channel_codec_quality=10"));
assert!(matches!(reply, Reply::Created { ref name, invoker: 7, channel_id: None } if name == "Lobby"));
assert!(matches!(reply, Reply::Created { ref name, parent: 0, invoker: 7, channel_id: None, .. } if name == "Lobby"));
}
#[test]
@@ -1114,6 +1265,60 @@ mod tests {
assert!(!text.contains("=pw"));
assert!(parse_json("server_edit", json!({"generation":2,"confirm":"srv=","properties":{"sid":1}})).is_err());
}
#[test]
fn server_client_limits_are_independent_typed_wire_properties() {
let command = parse_json("server_edit", json!({"generation":2,"confirm":"srv=","properties":{
"virtualserver_maxclients":1234,"virtualserver_reserved_slots":56}})).unwrap();
let wire = content(build(&command, &live(&|_| None)).unwrap().0);
assert_eq!(wire, "serveredit virtualserver_maxclients=1234 virtualserver_reserved_slots=56");
for field in ["virtualserver_maxclients", "virtualserver_reserved_slots"] {
for value in [0, 65535] {
let mut properties = Map::new();
properties.insert(field.into(), json!(value));
let command = parse_json("server_edit", json!({"generation":2,"confirm":"srv=","properties":properties})).unwrap();
assert_eq!(content(build(&command, &live(&|_| None)).unwrap().0), format!("serveredit {field}={value}"));
}
}
for (field, value) in [
("virtualserver_maxclients", json!(-1)),
("virtualserver_maxclients", json!(65536)),
("virtualserver_maxclients", json!(1.5)),
("virtualserver_maxclients", json!("12")),
("virtualserver_reserved_slots", json!(-1)),
("virtualserver_reserved_slots", json!(65536)),
("virtualserver_reserved_slots", json!(1.5)),
("virtualserver_reserved_slots", json!("12")),
] {
let mut properties = Map::new();
properties.insert(field.into(), value);
assert_eq!(parse_json("server_edit", json!({"generation":2,"confirm":"srv=","properties":properties})).unwrap_err().code, ErrorCode::BadRequest, "{field}");
}
}
#[test]
fn server_transfer_quotas_preserve_safe_integer_wire_values() {
for field in ["virtualserver_download_quota", "virtualserver_upload_quota"] {
let mut properties = Map::new();
properties.insert(field.into(), json!(MAX_SAFE_INTEGER));
let command = parse_json("server_edit", json!({"generation":2,"confirm":"srv=","properties":properties})).unwrap();
assert_eq!(content(build(&command, &live(&|_| None)).unwrap().0), format!("serveredit {field}={MAX_SAFE_INTEGER}"));
}
for (field, value) in [
("virtualserver_download_quota", json!(-1)),
("virtualserver_download_quota", json!(MAX_SAFE_INTEGER + 1)),
("virtualserver_download_quota", json!(1.5)),
("virtualserver_download_quota", json!("12")),
("virtualserver_upload_quota", json!(-1)),
("virtualserver_upload_quota", json!(MAX_SAFE_INTEGER + 1)),
("virtualserver_upload_quota", json!(1.5)),
("virtualserver_upload_quota", json!("12")),
] {
let mut properties = Map::new();
properties.insert(field.into(), value);
assert_eq!(parse_json("server_edit", json!({"generation":2,"confirm":"srv=","properties":properties})).unwrap_err().code, ErrorCode::BadRequest, "{field}");
}
}
#[test]
fn wire_shapes_match_declarations() {
@@ -1153,6 +1358,49 @@ mod tests {
}
}
#[test]
fn pending_channel_description_ignores_other_channels_and_drops_invalidated_text() {
let reply = || Reply::Description { channel_id: 8, description: None };
let collect = |r: &mut Reply, bytes: &[u8]| r.collect(&crate::rawcmd::parse(bytes).unwrap());
let mut r = reply();
collect(&mut r, b"notifychanneledited cid=8 channel_description=Old");
collect(&mut r, b"notifychanneldescriptionchanged cid=9");
collect(&mut r, b"notifychanneldeleted cid=9");
assert_eq!(finish(r).unwrap(), json!({"description":"Old"}));
let mut r = reply();
collect(&mut r, b"notifychanneledited cid=8 channel_description=Old");
collect(&mut r, b"notifychanneldescriptionchanged cid=8");
collect(&mut r, b"notifychanneledited cid=9 channel_description=Other");
assert_eq!(finish(r).unwrap(), json!({"description":null}));
let mut r = reply();
collect(&mut r, b"notifychanneledited cid=8 channel_description");
assert_eq!(finish(r).unwrap(), json!({"description":""}));
}
#[test]
fn pending_channel_reads_reject_reused_ids_after_deletion() {
for mut reply in [Reply::Description { channel_id: 8, description: Some("Old".into()) }, Reply::ChannelInfo { channel_id: 8 }] {
for packet in ["notifychanneldeleted cid=9|cid=8", "notifychannelcreated cid=8 channel_name=New", "notifychanneledited cid=8 channel_description=Replacement"] {
reply.collect(&crate::rawcmd::parse(packet.as_bytes()).unwrap());
}
assert_eq!(reply.notification(), Some("notifychanneledited"));
assert_eq!(finish(reply).unwrap_err().code, ErrorCode::TargetChanged);
}
}
#[test]
fn permission_rows_follow_each_explicit_scope_across_packet_boundaries() {
let mut reply = Reply::rows("notifyservergrouppermlist", Some(("sgid", 6)));
for packet in [
"notifyservergrouppermlist permid=1|sgid=7 permid=2|sgid=6 permid=3|permid=4|sgid=7 permid=5",
"notifyservergrouppermlist permid=6|sgid=6 permid=7",
"notifyservergrouppermlist permid=8",
] { reply.collect(&crate::rawcmd::parse(packet.as_bytes()).unwrap()); }
let value = finish(reply).unwrap();
let ids: Vec<_> = value["rows"].as_array().unwrap().iter().map(|row| row["permid"].as_str().unwrap()).collect();
assert_eq!(ids, ["3", "4", "7", "8"]);
}
#[test]
fn replies_collect_only_their_rows() {
let mut r = Reply::rows("notifyservergrouppermlist", Some(("sgid", 6)));
@@ -1162,14 +1410,41 @@ mod tests {
let rows = finish(r).unwrap();
assert_eq!(rows["rows"].as_array().unwrap().len(), 3);
let mut c = Reply::Created { name: "A b".into(), invoker: 7, channel_id: None };
let created = || Reply::Created { name: "A b".into(), parent: 0, invoker: 7, channel_id: None, ambiguous: false };
let mut c = created();
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=11 cpid=0 channel_name=A\sb invokerid=8").unwrap());
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=12 cpid=0 channel_name=A\sb invokerid=7").unwrap());
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=10 cpid=3 channel_name=A\sb invokerid=7").unwrap());
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=0 cpid=0 channel_name=A\sb invokerid=7").unwrap());
assert_eq!(finish(c).unwrap_err().code, ErrorCode::ServerError);
let own = crate::rawcmd::parse(br"notifychannelcreated cid=12 cpid=0 channel_name=A\sb invokerid=7").unwrap();
let mut c = created();
c.collect(&own);
c.collect(&own);
assert_eq!(finish(c).unwrap(), json!({"channel_id": 12}));
let mut c = created();
c.collect(&own);
c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=13 cpid=0 channel_name=A\sb invokerid=7").unwrap());
assert_eq!(finish(c).unwrap_err().code, ErrorCode::ServerError);
assert!(finish(Reply::Token { token: None }).is_err(), "no fake success without the key");
let mut t = Reply::Token { token: None };
t.collect(&crate::rawcmd::parse(br"notifytokenadd token=abc").unwrap());
assert_eq!(finish(t).unwrap(), json!({"token": "abc"}));
}
#[test]
fn token_add_requires_one_distinct_usable_key() {
let result = |packets: &[&[u8]]| {
let mut reply = Reply::Token { token: None, ambiguous: false };
for packet in packets { reply.collect(&crate::rawcmd::parse(packet).unwrap()); }
finish(reply)
};
let empty = br"notifytokenadd token".as_slice();
let one = br"notifytokenadd token|token=sample".as_slice();
let other = br"notifytokenadd token=different".as_slice();
assert_eq!(result(&[empty]).unwrap_err().detail, Some(json!({"created":true})));
assert_eq!(result(&[one, empty, one]).unwrap(), json!({"token":"sample"}));
for error in [result(&[one,other,one]), result(&[br"notifytokenadd token=sample|token=different"])] {
let error = error.unwrap_err();
assert_eq!(error.code, ErrorCode::ServerError);
assert_eq!(error.detail, Some(json!({"created":true})));
assert!(!error.message.contains("sample") && !error.message.contains("different"));
}
}
}
+14 -12
View File
@@ -56,26 +56,28 @@ impl Command {
|Self::GroupDelete{generation,..}|Self::GroupDeletePermissions{generation,..}|Self::ChannelDeletePermissions{generation,..}=>Some(*generation), _=>None,
}}
pub(super) fn validate(&self) -> Result<(),ErrorObj> {
let positive=|id:u64| if id==0 {Err(menu::bad("target ID must be positive"))}else{Ok(())};
let text=|s:&str,max:usize| if s.is_empty()||s.len()>max||s.chars().any(char::is_control){Err(menu::bad("invalid text argument"))}else{Ok(())};
if let Some(g)=self.generation(){positive(g)?;}
let positive=|id:u64| super::positive("target ID",id);
if let Some(g)=self.generation(){super::generation(g)?;}
match self {
Self::ServerLog{lines,..} if !(1..=1000).contains(lines)=>return Err(menu::bad("lines must be 1..1000")),
Self::ServerLog{lines,begin_pos,..}=>{
if !(1..=1000).contains(lines){return Err(menu::bad("lines must be 1..1000"));}
super::nonnegative("begin_pos",*begin_pos)?;
},
Self::ClientDatabaseList{duration,..} if !(1..=200).contains(duration)=>return Err(menu::bad("duration must be 1..200")),
Self::ClientDatabaseFind{pattern,..}=>text(pattern,255)?,
Self::ClientDatabaseId{uid}=>text(uid,128)?,
Self::ClientDatabaseFind{pattern,..}=>super::check_str("pattern",pattern,255,false)?,
Self::ClientDatabaseId{uid}=>super::check_str("uid",uid,128,false)?,
Self::ClientDatabaseDelete{client_database_id,confirm,..}=>{positive(*client_database_id)?;if confirm!=&client_database_id.to_string(){return Err(menu::bad("confirmation does not match the database ID"));}},
Self::GroupAdd{name,group_type,..}=>{text(name,128)?;if *group_type>2{return Err(menu::bad("type must be 0..2"));}},
Self::GroupRename{group_id,name,..}=>{positive(*group_id)?;text(name,128)?;},
Self::GroupAdd{name,group_type,..}=>{super::check_str("name",name,super::MAX_GROUP_NAME_CHARS,false)?;if *group_type>2{return Err(menu::bad("type must be 0..2"));}},
Self::GroupRename{group_id,name,..}=>{positive(*group_id)?;super::check_str("name",name,super::MAX_GROUP_NAME_CHARS,false)?;},
Self::GroupSetPermissions{group_id,permissions,kind,..}=>{positive(*group_id)?;validate_permissions(permissions,*kind==GroupKind::Server)?;},
Self::ChannelSetPermissions{channel_id,permissions,..}=>{positive(*channel_id)?;validate_permissions(permissions,false)?;},
Self::GroupDelete{group_id,confirm,..}=>{positive(*group_id)?;if confirm!=&group_id.to_string(){return Err(menu::bad("confirmation does not match the group ID"));}},
Self::GroupDeletePermissions{group_id,permissions,..}=>{positive(*group_id)?;validate_permission_ids(permissions)?;},
Self::ChannelDeletePermissions{channel_id,permissions,..}=>{positive(*channel_id)?;validate_permission_ids(permissions)?;},
Self::ChannelInfo{channel_id}=>positive(*channel_id)?,
Self::ClientInfo{client_id,uid}=>{positive(u64::from(*client_id))?;text(uid,128)?;},
Self::ClientInfo{client_id,uid}=>{positive(u64::from(*client_id))?;super::check_str("uid",uid,128,false)?;},
Self::ServerGroupAddClient{group_id,client_database_id,..}=>{positive(*group_id)?;positive(*client_database_id)?;},
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{positive(*group_id)?;text(uid,128)?;},
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{positive(*group_id)?;super::check_str("uid",uid,128,false)?;},
_=>{},
} Ok(())
}
@@ -86,12 +88,12 @@ impl Command {
Self::ClientDatabaseList{start,duration}=>(menu::command("clientdblist",&[("start",start.to_string()),("duration",duration.to_string())]),Reply::rows("notifyclientdblist",None)),
Self::ClientDatabaseFind{pattern,uid}=>{let mut c=menu::command("clientdbfind",&[("pattern",pattern.clone()),("-details",String::new())]);if *uid{c.write_arg("-uid",&"");}(c,Reply::rows("notifyclientdbfind",None))},
Self::ClientDatabaseDelete{client_database_id,..}=>(menu::command("clientdbdelete",&[("cldbid",s(*client_database_id))]),Reply::Ack),
Self::ClientDatabaseId{uid}=>(menu::command("clientgetdbidfromuid",&[("cluid",uid.clone())]),Reply::rows("notifyclientdbidfromuid",None)),
Self::ClientDatabaseId{uid}=>(menu::command("clientgetdbidfromuid",&[("cluid",uid.clone())]),Reply::DatabaseId{uid:uid.clone(),id:None,ambiguous:false}),
Self::ServerGroupList{}=>(menu::command("servergrouplist",&[]),Reply::rows("notifyservergrouplist",None)),
Self::ChannelGroupList{}=>(menu::command("channelgrouplist",&[]),Reply::rows("notifychannelgrouplist",None)),
Self::GroupAdd{kind,name,group_type,..}=>{
let (verb,notify,key)=group_names(*kind,"add");
(menu::command(verb,&[("name",name.clone()),("type",group_type.to_string())]),Reply::GroupCreated{notify,key,name:name.clone(),group_id:None,ambiguous:false})
(menu::command(verb,&[("name",name.clone()),("type",group_type.to_string())]),Reply::GroupCreated{notify,key,name:name.clone(),group_type:*group_type,existing:(live.group_ids)(*kind),group_id:None,ambiguous:false})
},
Self::GroupRename{kind,group_id,name,..}=>{let(verb,_,key)=group_names(*kind,"rename");(menu::command(verb,&[(key,s(*group_id)),("name",name.clone())]),Reply::Ack)},
Self::GroupSetPermissions{kind,group_id,permissions,..}=>{let(verb,_,key)=group_names(*kind,"perm");(permission_command(verb,key,*group_id,permissions,*kind==GroupKind::Server),Reply::Ack)},
+128 -6
View File
@@ -1,6 +1,105 @@
//! Session integration of server/channel administration (`admin.rs`, `docs/bridge.md` §4.6).
use super::*;
fn check_predecessor(
channel: Option<u64>, parent: u64, order: Option<u64>,
position_of: impl Fn(u64) -> Option<(u64, u64)>,
) -> Result<(), ErrorObj> {
if let Some(after) = order.filter(|id| *id != 0) {
if Some(after) == channel || position_of(after).map(|p| p.0) != Some(parent) {
return Err(ErrorObj::new(ErrorCode::TargetChanged, "preceding channel is no longer a sibling; reload the channel tree"));
}
}
Ok(())
}
fn move_changes_position(
moving: u64, parent: u64, order: Option<u64>, channel_count: usize,
position_of: impl Fn(u64) -> Option<(u64, u64)>,
) -> Result<bool, ErrorObj> {
let (old_parent, old_order) = position_of(moving)
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel is no longer visible"))?;
check_predecessor(Some(moving), parent, order, &position_of)?;
let mut ancestor = parent;
// Even an inconsistent book with a parent cycle must finish without a network write.
for _ in 0..channel_count {
if ancestor == 0 { break; }
if ancestor == moving { break; }
let Some((next, _)) = position_of(ancestor) else { break };
ancestor = next;
}
if ancestor == 0 { Ok(parent != old_parent || order != Some(old_order)) } else {
Err(ErrorObj::new(ErrorCode::TargetChanged, "destination is no longer a valid parent; reopen the move dialog"))
}
}
fn check_property_position(cmd: &admin::AdminCommand, position_of: impl Fn(u64) -> Option<(u64, u64)>) -> Result<(), ErrorObj> {
let (channel, parent, properties) = match cmd {
admin::AdminCommand::ChannelCreate { parent_id, properties, .. } => (None, Some(*parent_id), properties),
admin::AdminCommand::ChannelEdit { channel_id, properties, .. } => (Some(*channel_id), None, properties),
_ => return Ok(()),
};
let Some((_, order)) = properties.iter().find(|(key, _)| *key == "channel_order") else { return Ok(()) };
let order = order.parse::<u64>().map_err(|_| ErrorObj::new(ErrorCode::BadRequest, "invalid channel_order"))?;
if order == 0 { return Ok(()) }
let parent = parent.or_else(|| channel.and_then(&position_of).map(|p| p.0))
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel is no longer visible"))?;
check_predecessor(channel, parent, Some(order), position_of)
}
#[cfg(test)]
mod move_tests {
use super::*;
use std::collections::HashMap;
#[test]
fn channel_property_order_rechecks_current_siblings() {
use admin::{AdminCommand, Properties};
let commands = |order: Option<u64>| {
let mut fields = serde_json::Map::from_iter([("channel_name".into(), json!("Example"))]);
if let Some(order) = order { fields.insert("channel_order".into(), json!(order)); }
[AdminCommand::ChannelCreate { generation: 1, parent_id: 8, properties: Properties::channel_create(fields.clone()).unwrap() },
AdminCommand::ChannelEdit { generation: 1, channel_id: 42, properties: Properties::channel_edit(fields).unwrap() }]
};
let mut tree = HashMap::from([(8, (0, 0)), (42, (8, 0)), (13, (8, 42))]);
let ordered = commands(Some(13));
for cmd in &ordered { check_property_position(cmd, |id| tree.get(&id).copied()).unwrap(); }
for next in [Some((0, 8)), None] {
if let Some(pos) = next { tree.insert(13, pos); } else { tree.remove(&13); }
for cmd in &ordered {
assert_eq!(check_property_position(cmd, |id| tree.get(&id).copied()).unwrap_err().code, ErrorCode::TargetChanged);
}
}
let [create, edit] = commands(Some(42));
check_property_position(&create, |id| tree.get(&id).copied()).unwrap();
assert_eq!(check_property_position(&edit, |id| tree.get(&id).copied()).unwrap_err().code, ErrorCode::TargetChanged);
for cmd in commands(None).into_iter().chain(commands(Some(0))) {
check_property_position(&cmd, |_| panic!("no predecessor to look up")).unwrap();
}
}
#[test]
fn channel_move_rechecks_parent_and_predecessor_at_dispatch() {
let mut parents = HashMap::from([(42, 0), (8, 0), (13, 8), (99, 42)]);
let check = |parents: &HashMap<u64,u64>, parent, order| {
move_changes_position(42, parent, order, parents.len(), |id| parents.get(&id).copied().map(|p| (p, 0)))
};
assert!(check(&parents, 8, Some(13)).unwrap());
assert!(check(&parents, 8, Some(0)).unwrap());
assert!(check(&parents, 0, None).unwrap());
assert!(!check(&parents, 0, Some(0)).unwrap());
parents.insert(13, 0);
assert_eq!(check(&parents, 8, Some(13)).unwrap_err().code, ErrorCode::TargetChanged);
check(&parents, 0, Some(13)).unwrap();
parents.remove(&13);
assert_eq!(check(&parents, 0, Some(13)).unwrap_err().code, ErrorCode::TargetChanged);
parents.insert(8, 99);
assert_eq!(check(&parents, 8, Some(0)).unwrap_err().code, ErrorCode::TargetChanged);
parents.insert(99, 8);
assert_eq!(check(&parents, 8, None).unwrap_err().code, ErrorCode::TargetChanged);
}
}
impl Session {
pub(super) async fn admin(&mut self, id: &str, cmd: admin::AdminCommand) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
@@ -11,15 +110,25 @@ impl Session {
}
}
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
let position_of = |id| book.channels.get(&ChannelId(id)).map(|ch| (ch.parent.0, ch.order.0));
if let admin::AdminCommand::ChannelMove { channel_id, parent_id, order, .. } = &cmd {
let changes = move_changes_position(*channel_id, *parent_id, *order, book.channels.len(), position_of)?;
if !changes { return Ok(Some(json!({"changed": false}))); }
} else {
check_property_position(&cmd, position_of)?;
}
let (command, reply) = match &cmd {
admin::AdminCommand::Context => (menu::command("permissionlist", &[]), admin::Reply::Context),
admin::AdminCommand::Extra(admin::extra::Command::ChannelList {}) => {
let rows: Vec<_> = snapshot::ordered_channels(&book.channels).into_iter()
.filter_map(|(id, _)| c.extras.channel_properties(id.0).cloned()).collect();
.filter_map(|(id, _)| {
let channel = book.channels.get(&id)?;
c.extras.channel_properties(id, channel.parent, channel.order)
}).collect();
if rows.len() != book.channels.len() {
return Err(ErrorObj::new(ErrorCode::ServerError, "channel properties are incomplete; wait for the server channel list"));
}
return Ok(Some(json!({ "rows": rows })));
return Ok(Some(Value::from_iter([("rows", Value::Array(rows))])));
}
admin::AdminCommand::Extra(admin::extra::Command::ChannelInfo { channel_id }) => {
if !book.channels.contains_key(&ChannelId(*channel_id)) {
@@ -31,7 +140,7 @@ impl Session {
if book.clients.get(&ClientId(*client_id)).and_then(|client| client.uid.as_ref()).is_none_or(|current| current.to_string() != *uid) {
return Err(ErrorObj::new(ErrorCode::TargetChanged, "client identity changed; reopen information"));
}
(menu::command("clientgetvariables", &[("clid", client_id.to_string())]), admin::Reply::rows("notifyclientupdated", Some(("clid", u64::from(*client_id)))))
(menu::command("clientgetvariables", &[("clid", client_id.to_string())]), admin::Reply::ClientInfo(admin::ClientInfoReply::new(*client_id, uid.clone())))
}
admin::AdminCommand::TalkPower { target, grant, .. } => {
let client = book
@@ -46,7 +155,11 @@ impl Session {
other => {
let server_uid = book.server.public_key.get_uid();
let channel = |cid: u64| book.channels.get(&ChannelId(cid)).map(|ch| ch.name.clone());
let live = admin::Live { own_client: book.own_client.0, server_uid: &server_uid, channel: &channel };
let group_ids = |kind| match kind {
admin::extra::GroupKind::Server => book.server_groups.keys().map(|id| id.0).collect(),
admin::extra::GroupKind::Channel => book.channel_groups.keys().map(|id| id.0).collect(),
};
let live = admin::Live { own_client: book.own_client.0, server_uid: &server_uid, channel: &channel, group_ids: &group_ids };
admin::build(other, &live)?
}
};
@@ -68,14 +181,23 @@ impl Session {
};
let answer = match (reply, res) {
(admin::Reply::Context, res) => self.admin_context(res),
(admin::Reply::ClientInfo(info), Ok(())) => {
let current_uid = self.conn.as_ref().and_then(|c| c.con.get_state().ok())
.and_then(|book| book.clients.get(&ClientId(info.client_id)))
.and_then(|client| client.uid.as_ref()).map(|uid| uid.to_string());
info.finish(current_uid.as_deref())
}
(admin::Reply::ChannelInfo { channel_id }, Ok(())) => {
self.conn.as_ref().and_then(|c| c.extras.channel_properties(channel_id))
.map(|row| json!({ "rows": [row] }))
self.conn.as_ref().and_then(|c| {
let channel = c.con.get_state().ok()?.channels.get(&ChannelId(channel_id))?;
c.extras.channel_properties(channel.id, channel.parent, channel.order)
}).map(|row| Value::from_iter([("rows", Value::Array(vec![row]))]))
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "channel disappeared before its properties were read"))
}
(admin::Reply::Rows { notify: "notifyserverupdated", overflow: false, .. }, Ok(())) => {
self.conn.as_ref().map(|c| json!({ "rows": [c.extras.server_properties()] })).ok_or_else(not_connected)
}
(admin::Reply::DatabaseId { .. }, Err(e)) if e.error.to_u32() == Some(admin::DATABASE_EMPTY_RESULT) => Ok(json!({ "rows": [] })),
(admin::Reply::Rows { .. }, Err(e)) if empty(&e) => Ok(json!({ "rows": [] })),
(_, Err(e)) => Err(command_error(&e)),
(reply, Ok(())) => admin::finish(reply),
+104 -24
View File
@@ -390,12 +390,14 @@ impl Receiver {
if !deny {
return Vec::new();
}
let removed: Vec<u16> = self.whisperers.drain().collect();
let queues = self.handler.get_mut_queues();
for id in &removed {
queues.remove(&ClientId(*id));
self.dsp.remove(*id);
}
self.whisperers.clear();
let mut removed = Vec::new();
self.handler.get_mut_queues().retain(|id, queue| {
if !queue.has_pending_whisper() { return true; }
removed.push(id.0);
self.dsp.remove(id.0);
false
});
self.whisper_starts.clear();
removed
}
@@ -421,6 +423,13 @@ impl Receiver {
RxEvent::None
};
}
let started = match self.handler.handle_packet(ClientId(from), packet) {
Ok(started) => started,
Err(error) => {
debug!(%error, client = from, "audio packet not queued");
return RxEvent::None;
}
};
if whisper && !end {
if self.whisperers.insert(from) {
self.whisper_starts.push(from);
@@ -429,15 +438,7 @@ impl Receiver {
// An empty whisper packet ends the whisper spurt; ordinary voice ends whispering.
self.whisperers.remove(&from);
}
match self.handler.handle_packet(ClientId(from), packet) {
Ok(Some(id)) => RxEvent::Started(id.0),
Ok(None) => RxEvent::None,
Err(error) => {
// Late, duplicate or overflowing packets are normal jitter-buffer outcomes.
debug!(%error, client = from, "audio packet not queued");
RxEvent::None
}
}
started.map_or(RxEvent::None, |id| RxEvent::Started(id.0))
}
/// Pull 20 ms from every speaker's jitter buffer, apply local gains, and mix to mono.
@@ -537,6 +538,30 @@ mod tests {
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
}
#[test]
fn rejected_packets_cannot_start_or_interrupt_a_whisper_spurt() {
let mut rx = Receiver::new();
let mut encoder = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let packet = encoder.encode(&sine(&mut 0.0, 440.0)).unwrap();
let data = &packet.content()[3..];
let forward = |id, whisper| {
let audio = if whisper { AudioData::S2CWhisper { id, from: 7, codec: CodecType::OpusVoice, data } }
else { AudioData::S2C { id, from: 7, codec: CodecType::OpusVoice, data } };
InAudioBuf::try_new(Direction::S2C, OutAudio::new(&audio).into_vec()).unwrap()
};
rx.handle_packet(forward(1, false));
rx.handle_packet(forward(1, true));
assert_eq!(rx.take_whisper_starts().next(), None);
rx.handle_packet(forward(2, true));
assert!(rx.take_whisper_starts().eq([7]));
rx.handle_packet(forward(2, false));
rx.handle_packet(forward(3, true));
assert_eq!(rx.take_whisper_starts().next(), None);
rx.handle_packet(forward(4, false));
rx.handle_packet(forward(5, true));
assert!(rx.take_whisper_starts().eq([7]));
}
#[test]
fn generated_whisper_codec_routes_and_incoming_block() {
use crate::whisper::{Route, Whisper};
@@ -582,6 +607,30 @@ mod tests {
}
}
#[test]
fn denying_whispers_after_end_marker_purges_audio_without_muting_ordinary_speakers() {
let mut rx = Receiver::new();
let mut encoder = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let packet = encoder.encode(&sine(&mut 0.0, 440.0)).unwrap();
let payload = &packet.content()[3..];
let forward = |audio| InAudioBuf::try_new(Direction::S2C, OutAudio::new(&audio).into_vec()).unwrap();
for id in 0..6 {
rx.handle_packet(forward(AudioData::S2CWhisper { id, from: 7, codec: CodecType::OpusVoice, data: payload }));
rx.handle_packet(forward(AudioData::S2C { id, from: 8, codec: CodecType::OpusVoice, data: payload }));
}
rx.handle_packet(forward(AudioData::S2CWhisper { id: 6, from: 7, codec: CodecType::OpusVoice, data: &[] }));
assert_eq!(rx.set_deny_whispers(true), [7]);
let mut out = [0; FRAME_SAMPLES];
let mut heard = false;
for _ in 0..12 {
let mix = rx.mix(&mut out, |_| 1.0);
assert!(!mix.speakers.contains(&7));
heard |= mix.speakers.contains(&8) && out.iter().any(|s| s.unsigned_abs() > 500);
}
assert!(heard, "ordinary queued speech must remain audible");
assert!(matches!(rx.handle_packet(forward(AudioData::S2C { id: 7, from: 7, codec: CodecType::OpusVoice, data: payload })), RxEvent::Started(7)));
}
/// Offline real encoder/receiver proof for PCM captured by audit-voice-timed.mjs.
/// Explicit opt-in: no device, socket or playback is opened by this test.
#[test]
@@ -772,6 +821,27 @@ mod tests {
println!("LOCAL_VOLUME_SUBPROCESS {}\n{stdout}", output.status);
}
#[test]
fn disabling_playback_agc_restores_unmodified_decoded_pcm() {
let mut reference=Receiver::new();let mut adjusted=Receiver::new();
adjusted.set_playback_agc(true);
let mut encoder=TxEncoder::new(TxCodec::OpusVoice,6).unwrap();let mut phase=0.0;
let mut energies=[0u64;2];
for sequence in 0..96u16 {
if sequence==80 {adjusted.set_playback_agc(false);}
let mut frame=sine(&mut phase,440.0);for s in frame.iter_mut(){*s/=12;}
let packet=encoder.encode(&frame).unwrap();
let bytes=OutAudio::new(&AudioData::S2C{id:sequence,from:7,codec:CodecType::OpusVoice,data:&packet.content()[3..]}).into_vec();
let mut outputs=[[0i16;FRAME_SAMPLES];2];
for (i,rx) in [&mut reference,&mut adjusted].into_iter().enumerate(){
rx.handle_packet(InAudioBuf::try_new(Direction::S2C,bytes.clone()).unwrap());rx.mix(&mut outputs[i],|_|1.0);
if (64..80).contains(&sequence){energies[i]+=outputs[i].iter().map(|v|i64::from(*v).pow(2) as u64).sum::<u64>();}
}
if sequence>=80 {assert_eq!(outputs[0],outputs[1],"gain remained after AGC was disabled");}
}
assert!(energies[0]>0 && energies[1]>energies[0]*4,"quiet Opus speech was not amplified: {energies:?}");
}
#[test]
fn removed_client_discards_queued_audio_before_id_reuse() {
let mut rx = Receiver::new();
@@ -974,16 +1044,26 @@ mod tests {
}
#[test]
fn reset_rearms_unsupported_codec_report() {
fn legacy_codecs_neither_select_an_encoder_nor_enter_the_mix() {
let mut rx = Receiver::new();
let speex = || {
let out = OutAudio::new(&AudioData::S2C { id: 1, from: 9, codec: CodecType::SpeexWideband, data: &[1, 2, 3] });
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
};
assert!(matches!(rx.handle_packet(speex()), RxEvent::Unsupported { client_id: 9, .. }));
assert!(matches!(rx.handle_packet(speex()), RxEvent::None));
rx.reset();
assert!(matches!(rx.handle_packet(speex()), RxEvent::Unsupported { client_id: 9, .. }));
for (channel, wire) in [
(Codec::SpeexNarrowband, CodecType::SpeexNarrowband),
(Codec::SpeexWideband, CodecType::SpeexWideband),
(Codec::SpeexUltrawideband, CodecType::SpeexUltrawideband),
(Codec::CeltMono, CodecType::CeltMono),
] {
assert_eq!(TxCodec::for_channel(channel), None);
let packet = || {
let out = OutAudio::new(&AudioData::S2C { id: 1, from: 9, codec: wire, data: &[1, 2, 3] });
InAudioBuf::try_new(Direction::S2C, out.into_vec()).unwrap()
};
assert!(matches!(rx.handle_packet(packet()), RxEvent::Unsupported { client_id: 9, codec } if codec == wire));
assert!(matches!(rx.handle_packet(packet()), RxEvent::None));
let mut pcm = [i16::MAX; FRAME_SAMPLES];
assert!(rx.mix(&mut pcm, |_| 1.).speakers.is_empty());
assert_eq!(pcm, [0; FRAME_SAMPLES]);
rx.reset();
}
}
#[test]
+16 -1
View File
@@ -99,7 +99,7 @@ pub fn from_raw(raw: &RawNotification, extras: &RawExtras, own_client: Option<u1
"notifyclientmoved" => {
let Some(clid) = num(row, "clid") else { continue };
let (mut v, last) = client("client_move", clid);
v["from_channel_id"] = json!(last);
v["from_channel_id"] = json!(num::<u64>(row, "cfid").filter(|c| *c != 0).or(last));
v["to_channel_id"] = json!(num::<u64>(row, "ctid"));
out.push(v);
}
@@ -165,6 +165,21 @@ mod tests {
assert_eq!(ev[0]["to_channel_id"], Value::Null);
}
#[test]
fn batched_client_moves_keep_each_origin_and_shared_destination() {
let mut extras = RawExtras::default();
extras.apply(&parse(b"notifycliententerview ctid=5 clid=1|clid=2|clid=3 ctid=8").unwrap());
let moved = parse(b"notifyclientmoved ctid=9 reasonid=1 clid=2|clid=3|clid=4 cfid=7").unwrap();
let events = from_raw(&moved, &extras, None);
assert_eq!(events.len(), 3);
for (event, (client, from)) in events.iter().zip([(2, 5), (3, 8), (4, 7)]) {
assert_eq!(event["client_id"], client);
assert_eq!(event["from_channel_id"], from);
assert_eq!(event["to_channel_id"], 9);
assert_eq!(event["reason"], "moved");
}
}
#[test]
fn channel_and_talk_events() {
let mut x = RawExtras::default();
+306 -77
View File
@@ -1,4 +1,4 @@
//! Channel file browser over the legacy TeamSpeak file transfer protocol.
//! Channel file browser over classic TeamSpeak storage and S3 storage.
//!
//! Commands: `ftgetfilelist`, `ftcreatedir`, `ftrenamefile`, `ftdeletefile`, `ftinitdownload`,
//! `ftinitupload`, `ftstop`. Listing rows and transfer grants arrive as raw notifications
@@ -23,8 +23,8 @@
//! continued while its length and modification time are unchanged. On the server side only a size
//! change is observable; the legacy protocol has no content identity.
//!
//! The TeamSpeak 6 `HTTPFT` and `s3` storage branches are not implemented: servers that advertise
//! them in `virtualserver_capability_extensions` are reported, never silently treated as legacy.
//! Servers advertising `s3` support browsing and HTTPS uploads/downloads for ordinary channels;
//! mutations of the directory tree, legacy pause/resume and HTTPFT remain unsupported.
use std::collections::{BTreeMap, HashMap};
use std::fs::{File, OpenOptions};
@@ -43,7 +43,10 @@ use tokio::sync::{mpsc, watch};
use tokio::task::JoinHandle;
use crate::protocol::{ErrorCode, ErrorObj};
use crate::rawcmd::RawNotification;
use crate::rawcmd::{RawNotification, S3FileList};
pub(crate) mod s3;
pub(crate) mod s3_http;
/// Longest remote path accepted (characters).
pub const MAX_PATH_CHARS: usize = 512;
@@ -218,6 +221,11 @@ pub struct RateLimit {
next: tokio::sync::Mutex<Option<tokio::time::Instant>>,
}
impl RateLimit {
/// Pace an S3 I/O chunk using at most one second of the current rate allowance.
fn s3_chunk_len(&self, max: usize) -> usize {
let rate = self.bytes_per_second.load(Ordering::Acquire);
if rate == 0 { max } else { (max as u64).min(rate) as usize }
}
pub fn set(&self, bytes: u64) { self.bytes_per_second.store(bytes, Ordering::Release); }
pub async fn acquire(&self, bytes: usize) {
let mut next = self.next.lock().await;
@@ -235,7 +243,10 @@ fn args<T: serde::de::DeserializeOwned>(raw: Option<&RawValue>) -> Result<T, Err
}
fn channel(id: u64) -> Result<u64, ErrorObj> {
if id == 0 { Err(bad("channel_id must be a channel (not 0)")) } else { Ok(id) }
if !(1..=9_007_199_254_740_991).contains(&id) {
return Err(bad("channel_id must be a positive safe integer"));
}
Ok(id)
}
fn check_password(p: &str) -> Result<(), ErrorObj> {
@@ -255,7 +266,7 @@ fn check_host_path(field: &str, path: &Path) -> Result<(), ErrorObj> {
// Channel zero is reserved for the virtual server's icons (main-owned snapshots and icon manager),
// never the renderer's file browser. Only canonical `/icons/icon_<nonzero u32>` names are accepted.
fn transfer_channel(id: u64, path: &str) -> Result<u64, ErrorObj> {
if id != 0 { return Ok(id); }
if id != 0 { return channel(id); }
let icon = path.strip_prefix("/icons/icon_").unwrap_or("");
if icon.parse::<u32>().is_ok_and(|n| n != 0 && n.to_string() == icon) {
Ok(0)
@@ -354,7 +365,10 @@ pub(crate) fn validate(request: &mut Request) -> Result<(), ErrorObj> {
check_password(password)?; check_host_path("source", source)?;
}
Request::FetchImage { channel_id, path } => { channel(*channel_id)?; check_remote_item(path)?; }
Request::Cancel { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers => {}
Request::Cancel { transfer_id } | Request::Pause { transfer_id } | Request::Resume { transfer_id } => {
if *transfer_id == 0 { return Err(bad("transfer_id must be positive")); }
}
Request::Transfers => {}
}
Ok(())
}
@@ -457,19 +471,58 @@ pub fn local_component(name: &str) -> Result<(), ErrorObj> {
// ------------------------------------------------------------------ listing
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ListBackend { Legacy, S3 }
#[derive(Debug)]
enum ListData {
Legacy { entries: Vec<Value>, malformed: usize, overflow: bool, finished: bool },
S3(Option<Result<(Vec<Value>, usize), ErrorObj>>),
}
#[derive(Debug)]
pub struct ListJob {
pub req: String,
pub channel_id: u64,
pub path: String,
pub entries: Vec<Value>,
pub malformed: usize,
pub overflow: bool,
pub finished: bool,
data: ListData,
pub result_ok: bool,
pub started: Instant,
}
impl ListJob {
pub(crate) fn new(req: &str, channel_id: u64, path: String, backend: ListBackend) -> Self {
let data = match backend {
ListBackend::Legacy => ListData::Legacy { entries: Vec::new(), malformed: 0, overflow: false, finished: false },
ListBackend::S3 => ListData::S3(None),
};
Self { req: req.into(), channel_id, path, data, result_ok: false, started: Instant::now() }
}
pub(crate) fn backend(&self) -> ListBackend {
match self.data {
ListData::Legacy { .. } => ListBackend::Legacy,
ListData::S3(_) => ListBackend::S3,
}
}
pub(crate) fn acknowledge(&mut self) -> bool {
self.result_ok = true;
match &self.data {
ListData::Legacy { finished, .. } => *finished,
ListData::S3(result) => result.is_some(),
}
}
pub(crate) fn finish_legacy(&mut self) -> bool {
let ListData::Legacy { finished, .. } = &mut self.data else { return false; };
*finished = true;
self.result_ok
}
fn accepts_legacy_rows(&self) -> bool { matches!(self.data, ListData::Legacy { finished: false, .. }) }
}
/// Value of `key` in entry `i`; TeamSpeak sends arguments common to all entries only once.
fn field<'a>(items: &'a [BTreeMap<String, String>], i: usize, key: &str) -> Option<&'a str> {
items[i].get(key).or_else(|| items[0].get(key)).map(String::as_str)
@@ -616,6 +669,12 @@ pub enum Stage {
/// Halted by the user, a lowered concurrency limit or a server interruption; `file_resume`
/// continues it.
Paused,
/// A TeamSpeak S3 command is awaiting its correlated grant and ACK.
S3Init { handle: u16, since: Instant },
/// A signed HTTP request is streaming; there is no legacy ftid or pause/resume.
S3Running { task: StreamTask },
/// Storage accepted the PUT; TeamSpeak must acknowledge the upload notification.
S3Confirming { handle: u16, since: Instant },
}
/// Result of a `file_transfer_interrupted` status for a transfer.
@@ -677,12 +736,15 @@ async fn halted(rx: &mut watch::Receiver<bool>) {
pub struct Transfer {
pub id: u32,
pub direction: Direction,
pub(crate) backend: ListBackend,
pub channel_id: u64,
pub path: String,
pub cpw: String,
pub overwrite: bool,
pub local: Local,
pub total: u64,
/// The size of an S3 download becomes known only when the HTTPS response arrives.
pub s3_total: Option<Arc<AtomicU64>>,
pub stage: Stage,
pub server_ftid: Option<u16>,
pub confirmed: bool,
@@ -706,7 +768,8 @@ pub struct Transfer {
impl Transfer {
pub fn ftid(&self) -> Option<u16> {
match self.stage {
Stage::Queued | Stage::Paused => None,
Stage::Queued | Stage::Paused | Stage::S3Init { .. } | Stage::S3Running { .. }
| Stage::S3Confirming { .. } => None,
Stage::Init { ftid, .. }
| Stage::Running { ftid, .. }
| Stage::Pausing { ftid, .. }
@@ -720,15 +783,18 @@ impl Transfer {
pub fn state(&self) -> &'static str {
match self.stage {
Stage::Queued => "queued",
Stage::Init { .. } => "starting",
Stage::Running { .. } | Stage::Pausing { .. } | Stage::Lost { .. } => "running",
Stage::Confirming { .. } => "confirming",
Stage::Init { .. } | Stage::S3Init { .. } => "starting",
Stage::Running { .. } | Stage::Pausing { .. } | Stage::Lost { .. } | Stage::S3Running { .. } => "running",
Stage::Confirming { .. } | Stage::S3Confirming { .. } => "confirming",
Stage::Paused => "paused",
}
}
/// Counts against its channel's concurrency limit.
pub fn in_progress(&self) -> bool { matches!(self.stage, Stage::Init { .. } | Stage::Running { .. } | Stage::Confirming { .. }) }
pub fn in_progress(&self) -> bool {
matches!(self.stage, Stage::Init { .. } | Stage::Running { .. } | Stage::Confirming { .. }
| Stage::S3Init { .. } | Stage::S3Running { .. } | Stage::S3Confirming { .. })
}
/// `ftinit*` resume argument for a start: `None` starts fresh with the original overwrite flag;
/// `Some(bytes)` continues after a granted stream (download `seekpos`, upload `resume=1`).
@@ -814,8 +880,9 @@ impl Transfer {
"path": self.path,
"name": file_name(&self.path),
"state": state,
"bytes": self.progress.load(Ordering::Relaxed),
"total": self.total,
"bytes": self.progress.load(Ordering::Acquire),
"pause_supported": self.backend == ListBackend::Legacy && self.channel_id != 0,
"total": self.s3_total.as_ref().map_or(self.total, |n| n.load(Ordering::Acquire)),
});
if let Some(e) = error {
v["error"] = serde_json::to_value(e).expect("error serializes");
@@ -824,12 +891,12 @@ impl Transfer {
}
}
/// Dropping a transfer stops its I/O: the stream task is aborted, which closes the TCP stream and
/// lets the disk side delete its temporary file (a paused download's `Partial` deletes its own).
/// Dropping a transfer stops its I/O and lets the disk side delete its temporary file
/// (a paused download's `Partial` deletes its own).
impl Drop for Transfer {
fn drop(&mut self) {
self.commit.cancel();
if let Stage::Running { task, .. } | Stage::Pausing { task, .. } = &self.stage {
if let Stage::Running { task, .. } | Stage::Pausing { task, .. } | Stage::S3Running { task } = &self.stage {
task.abort();
}
}
@@ -858,8 +925,9 @@ pub struct Files {
pub stops: HashMap<u16, ()>,
pub transfers: Vec<Transfer>,
pub tombstones: HashMap<u16, Tombstone>,
/// Last `virtualserver_capability_extensions` seen (`None` until the server sent it).
pub capability_extensions: Option<String>,
/// Display text is bounded; backend selection uses the complete announcement.
capability_extensions: Option<String>,
storage_extensions: (bool, bool),
pub slots: Option<[usize; 2]>,
/// Increments whenever a transfer starts.
pub start_seq: u64,
@@ -902,30 +970,56 @@ impl Files {
pub fn index_of_id(&self, id: u32) -> Option<usize> { self.transfers.iter().position(|t| t.id == id) }
fn unsupported_storage(&self) -> ErrorObj {
ErrorObj::new(ErrorCode::MediaUnsupported, "This operation is unsupported by the server's HTTPFT/S3 storage backend")
.with_detail(self.storage())
}
/// Reject unsupported storage before issuing any legacy command or touching a local file.
pub fn require_legacy(&self) -> Result<(), ErrorObj> {
let ext = self.capability_extensions.as_deref().unwrap_or("");
if ext.contains("HTTPFT") || ext.contains("s3") {
return Err(ErrorObj::new(ErrorCode::MediaUnsupported, "This server advertises HTTPFT/S3 storage; the legacy file protocol cannot access it").with_detail(self.storage()));
}
if self.storage_extensions != (false, false) { return Err(self.unsupported_storage()); }
Ok(())
}
/// `virtualserver_capability_extensions` tokens relevant to file storage.
pub(crate) fn list_backend(&self, channel_id: u64) -> Result<ListBackend, ErrorObj> {
match self.storage_extensions {
(_, true) if channel_id != 0 => Ok(ListBackend::S3),
(false, false) => Ok(ListBackend::Legacy),
_ => Err(self.unsupported_storage()),
}
}
/// `virtualserver_capability_extensions` and operation support for ordinary channels.
pub fn storage(&self) -> Value {
// Same test as the official client: substring of the advertised extension list.
let ext = self.capability_extensions.as_deref().unwrap_or("");
let httpft = ext.contains("HTTPFT");
let s3 = ext.contains("s3");
let (httpft, s3) = self.storage_extensions;
json!({
"capability_extensions": self.capability_extensions,
"httpft": httpft,
"s3": s3,
// Do not issue legacy operations against a different storage backend.
"supported": !(httpft || s3),
"list_supported": s3 || !httpft,
"read_only": false,
"upload_supported": s3 || !httpft,
"download_supported": s3 || !httpft,
"pause_supported": !(s3 || httpft),
"mutation_supported": !(s3 || httpft),
})
}
/// Correlate by the exact S3 command handle, not by channel/path or a legacy completion.
/// Even a malformed notification waits for the ACK: a command rejection has the real TS error.
pub(crate) fn apply_s3_list(&mut self, reply: S3FileList<'_>) -> Option<u16> {
let handle = reply.handle?;
let job = self.lists.get_mut(&handle)?;
let ListData::S3(result @ None) = &mut job.data else { return None; };
*result = Some(match reply.payload {
Ok(payload) => s3::decode_list(&job.path, payload),
Err(message) => Err(ErrorObj::new(ErrorCode::ServerError, message)),
});
job.result_ok.then_some(handle)
}
/// Apply a tapped raw notification. Returns finished listings (handle) to answer.
pub fn apply_raw(&mut self, raw: &RawNotification) -> Vec<u16> {
let items = &raw.items;
@@ -934,8 +1028,10 @@ impl Files {
}
match raw.name.as_str() {
"initserver" | "notifyserverupdated" | "notifyserveredited" => {
if let Some(v) = items[0].get("virtualserver_capability_extensions") {
self.capability_extensions = Some(v.chars().take(1024).collect());
let extensions = items.iter().rev().find_map(|item| item.get("virtualserver_capability_extensions"));
if raw.name == "initserver" || extensions.is_some() {
self.storage_extensions = extensions.map_or((false, false), |v| (v.contains("HTTPFT"), v.contains("s3")));
self.capability_extensions = extensions.map(|v| v.chars().take(1024).collect());
}
Vec::new()
}
@@ -955,13 +1051,14 @@ impl Files {
for i in 0..items.len() {
let Some(handle) = self.list_for(items, i) else { continue };
let job = self.lists.get_mut(&handle).expect("found");
if job.entries.len() >= MAX_LIST_ENTRIES {
job.overflow = true;
let ListData::Legacy { entries, malformed, overflow, .. } = &mut job.data else { unreachable!() };
if entries.len() >= MAX_LIST_ENTRIES {
*overflow = true;
continue;
}
match list_entry(items, i) {
Some(v) => job.entries.push(v),
None => job.malformed += 1,
Some(v) => entries.push(v),
None => *malformed += 1,
}
}
Vec::new()
@@ -970,9 +1067,7 @@ impl Files {
let mut done = Vec::new();
for i in 0..items.len() {
if let Some(handle) = self.list_for(items, i) {
let job = self.lists.get_mut(&handle).expect("found");
job.finished = true;
if job.result_ok {
if self.lists.get_mut(&handle).expect("found").finish_legacy() {
done.push(handle);
}
}
@@ -987,13 +1082,13 @@ impl Files {
/// channel and path (only one listing per folder is ever pending).
fn list_for(&self, items: &[BTreeMap<String, String>], i: usize) -> Option<u16> {
if let Some(h) = field(items, i, "return_code").and_then(|r| r.parse::<u16>().ok()) {
if self.lists.get(&h).is_some_and(|j| !j.finished) {
if self.lists.get(&h).is_some_and(ListJob::accepts_legacy_rows) {
return Some(h);
}
}
let cid: u64 = field(items, i, "cid")?.parse().ok()?;
let path = field(items, i, "path")?;
self.lists.iter().find(|(_, j)| !j.finished && j.channel_id == cid && same_dir(&j.path, path)).map(|(h, _)| *h)
self.lists.iter().find(|(_, j)| j.accepts_legacy_rows() && j.channel_id == cid && same_dir(&j.path, path)).map(|(h, _)| *h)
}
pub fn list_pending(&self, channel_id: u64, path: &str) -> bool {
@@ -1026,9 +1121,11 @@ impl Files {
/// for an explicit resume).
pub fn next_startable(&self, direction: Direction) -> Option<usize> {
self.transfers.iter().position(|q| {
q.direction == direction
&& matches!(q.stage, Stage::Queued)
&& self.in_progress_of(direction, q.channel_id).len() < self.limit(direction, q.channel_id)
if q.direction != direction || !matches!(q.stage, Stage::Queued) { return false; }
let limit = self.limit(direction, q.channel_id);
self.transfers.iter()
.filter(|t| t.direction == direction && t.channel_id == q.channel_id && t.in_progress())
.take(limit).count() < limit
})
}
@@ -1043,7 +1140,7 @@ impl Files {
for (_, channel_id, direction) in channels {
let limit = self.limit(direction, channel_id);
for &i in self.in_progress_of(direction, channel_id).iter().skip(limit) {
if !matches!(self.transfers[i].stage, Stage::Confirming { .. }) {
if self.transfers[i].backend == ListBackend::Legacy && !matches!(self.transfers[i].stage, Stage::Confirming { .. }) {
out.push(self.transfers[i].id);
}
}
@@ -1063,7 +1160,7 @@ impl Files {
let excess = (running.len() + 1).saturating_sub(limit).min(running.len());
running[..excess]
.iter()
.filter(|&&i| !matches!(self.transfers[i].stage, Stage::Confirming { .. }))
.filter(|&&i| self.transfers[i].backend == ListBackend::Legacy && !matches!(self.transfers[i].stage, Stage::Confirming { .. }))
.map(|&i| self.transfers[i].id)
.collect()
}
@@ -1071,14 +1168,17 @@ impl Files {
/// Final answer for a completed listing.
pub fn list_result(job: ListJob, capabilities: Value, storage: Value) -> Result<Value, ErrorObj> {
if job.overflow {
return Err(ErrorObj::new(ErrorCode::ServerError, format!("the folder has more than {MAX_LIST_ENTRIES} entries; listing not complete")));
}
let (entries, malformed) = match job.data {
ListData::Legacy { overflow: true, .. } => return Err(ErrorObj::new(ErrorCode::ServerError,
format!("the folder has more than {MAX_LIST_ENTRIES} entries; listing not complete"))),
ListData::Legacy { entries, malformed, .. } => (entries, malformed),
ListData::S3(result) => result.expect("S3 list notification received")?,
};
Ok(json!({
"channel_id": job.channel_id,
"path": job.path,
"entries": job.entries,
"malformed": job.malformed,
"entries": entries,
"malformed": malformed,
"capabilities": capabilities,
"storage": storage,
}))
@@ -1086,16 +1186,16 @@ pub fn list_result(job: ListJob, capabilities: Value, storage: Value) -> Result<
/// Channel permission hints (`notifychannelpermhints`) for the file browser. Unknown hints (`None`)
/// mean the server decides, like the official client which treats missing hints as allowed.
pub fn capabilities(hints: Option<u64>) -> Value {
pub fn capabilities(hints: Option<u64>, s3: bool) -> Value {
let bit = |b: u64| hints.is_none_or(|h| h & b != 0);
json!({
"known": hints.is_some(),
"upload": bit(64),
"download": bit(128),
"delete": bit(256),
"rename": bit(512),
"delete": !s3 && bit(256),
"rename": !s3 && bit(512),
"browse": bit(1024),
"create_directory": bit(2048),
"create_directory": !s3 && bit(2048),
})
}
@@ -1187,6 +1287,8 @@ fn finalize(temp: &Path, target: &Path, overwrite: bool, name: &str) -> Result<(
#[derive(Debug)]
enum ToDisk {
Data(Vec<u8>, usize),
/// An owned HTTP frame, or a slice of one, can be staged without copying its bytes.
HttpData(bytes::Bytes),
Commit,
/// Halt: keep the temporary file open and hand it back.
Pause,
@@ -1234,6 +1336,10 @@ fn disk_writer(
while let Some(msg) = rx.blocking_recv() {
if control.0.load(Ordering::Acquire) == 1 { return Err(cancelled()); }
match msg {
ToDisk::HttpData(buf) => {
file.write_all(&buf).map_err(|e| io_err("cannot write the download", e))?;
written += buf.len() as u64;
}
ToDisk::Data(buf, n) => {
file.write_all(&buf[..n]).map_err(|e| io_err("cannot write the download", e))?;
written += n as u64;
@@ -1245,6 +1351,9 @@ fn disk_writer(
foreign = true;
return Err(ErrorObj::new(ErrorCode::Io, "the temporary download file was replaced; nothing was published"));
}
if file.metadata().map_err(|e| io_err("cannot inspect the download", e))?.len() != written {
return Err(ErrorObj::new(ErrorCode::Io, "the temporary download file changed; nothing was published"));
}
return if control.begin_commit() { Ok(false) } else { Err(cancelled()) };
}
ToDisk::Pause => {
@@ -1255,7 +1364,7 @@ fn disk_writer(
}
Err(cancelled())
})();
if foreign {
if foreign || (result.is_err() && !names_file(guard.0.as_ref().expect("armed"), &file)) {
guard.0 = None;
}
match result {
@@ -1600,10 +1709,7 @@ mod tests {
#[test]
fn listing_merges_shared_arguments_and_bounds_rows() {
let mut f = Files::default();
f.lists.insert(7, ListJob {
req: "r".into(), channel_id: 4, path: "/".into(), entries: vec![], malformed: 0,
overflow: false, finished: false, result_ok: false, started: Instant::now(),
});
f.lists.insert(7, ListJob::new("r", 4, "/".into(), ListBackend::Legacy));
let done = f.apply_raw(&raw("notifyfilelist", &[
&[("cid", "4"), ("path", "/"), ("return_code", "7"), ("name", "Doc"), ("size", "0"), ("datetime", "5"), ("type", "0")],
&[("name", "ü.txt"), ("size", "11984"), ("datetime", "1539276009"), ("type", "1"), ("incompletesize", "100")],
@@ -1612,13 +1718,14 @@ mod tests {
&[("name", "nested/file"), ("size", "1"), ("type", "1")],
]));
assert!(done.is_empty());
let job = &f.lists[&7];
assert_eq!(job.entries.len(), 2);
assert_eq!(job.malformed, 3);
assert_eq!(job.entries[0]["type"], "folder");
assert_eq!(job.entries[1]["name"], "ü.txt");
assert_eq!(job.entries[1]["incomplete_size"], 100);
f.lists.get_mut(&7).unwrap().result_ok = true;
let job = f.lists.get_mut(&7).unwrap();
let ListData::Legacy { entries, malformed, .. } = &job.data else { panic!("not a legacy list") };
assert_eq!(entries.len(), 2);
assert_eq!(*malformed, 3);
assert_eq!(entries[0]["type"], "folder");
assert_eq!(entries[1]["name"], "ü.txt");
assert_eq!(entries[1]["incomplete_size"], 100);
assert!(!job.acknowledge());
assert_eq!(f.apply_raw(&raw("notifyfilelistfinished", &[&[("cid", "4"), ("path", "/")]])), vec![7]);
}
@@ -1631,11 +1738,119 @@ mod tests {
assert_eq!(f.storage()["httpft"], true);
assert_eq!(f.storage()["supported"], false);
assert_eq!(f.require_legacy().unwrap_err().code, ErrorCode::MediaUnsupported);
assert_eq!(capabilities(Some((1_u64 << 48) | 128))["download"], true);
assert_eq!(capabilities(Some(1_u64 << 48))["download"], false);
assert_eq!(capabilities(Some(1024 | 64))["upload"], true);
assert_eq!(capabilities(Some(1024 | 64))["delete"], false);
assert_eq!(capabilities(None)["delete"], true);
assert_eq!(f.storage()["list_supported"], false);
assert!(f.list_backend(4).is_err());
f.apply_raw(&raw("initserver", &[&[("virtualserver_capability_extensions", "MATRIXCHAT,HTTPFT,s3")]]));
assert_eq!(f.list_backend(4).unwrap(), ListBackend::S3);
assert_eq!(f.list_backend(0).unwrap_err().code, ErrorCode::MediaUnsupported);
assert_eq!(f.require_legacy().unwrap_err().code, ErrorCode::MediaUnsupported);
assert_eq!(f.storage()["supported"], false);
assert_eq!(f.storage()["list_supported"], true);
assert_eq!(f.storage()["read_only"], false);
assert_eq!(f.storage()["upload_supported"], true);
assert_eq!(f.storage()["download_supported"], true);
assert_eq!(f.storage()["pause_supported"], false);
assert_eq!(f.storage()["mutation_supported"], false);
assert_eq!(capabilities(None, true)["browse"], true);
assert_eq!(capabilities(None, true)["upload"], true);
assert_eq!(capabilities(None, true)["download"], true);
assert_eq!(capabilities(Some(0), true)["browse"], false);
assert_eq!(capabilities(Some(0), true)["upload"], false);
assert_eq!(capabilities(Some(0), true)["download"], false);
for operation in ["delete", "rename", "create_directory"] {
assert_eq!(capabilities(None, true)[operation], false);
}
f.apply_raw(&raw("initserver", &[&[]]));
assert_eq!(f.list_backend(0).unwrap(), ListBackend::Legacy);
assert_eq!(f.storage()["list_supported"], true);
assert_eq!(f.storage()["read_only"], false);
assert_eq!(capabilities(Some((1_u64 << 48) | 128), false)["download"], true);
assert_eq!(capabilities(Some(1_u64 << 48), false)["download"], false);
assert_eq!(capabilities(Some(1024 | 64), false)["upload"], true);
assert_eq!(capabilities(Some(1024 | 64), false)["delete"], false);
assert_eq!(capabilities(None, false)["delete"], true);
}
fn s3_listing(path: &str) -> Files {
let mut files = Files::default();
files.lists.insert(7, ListJob::new("r", 4, path.into(), ListBackend::S3));
files
}
fn s3_notify(files: &mut Files, command: &[u8]) -> Option<u16> {
files.apply_s3_list(crate::rawcmd::s3_file_list(command).unwrap())
}
fn s3_list_answer(files: &mut Files) -> Result<Value, ErrorObj> {
list_result(files.lists.remove(&7).unwrap(), capabilities(None, true), files.storage())
}
#[test]
fn s3_listing_correlates_exact_handle_and_waits_for_ack_in_either_order() {
for ack_first in [false, true] {
let mut files = s3_listing("/");
files.lists.insert(8, ListJob::new("legacy", 4, "/".into(), ListBackend::Legacy));
if ack_first { assert!(!files.lists.get_mut(&7).unwrap().acknowledge()); }
assert_eq!(files.apply_raw(&raw("notifyfilelistfinished", &[&[("return_code", "7")]])), Vec::<u16>::new());
for foreign in [
br"notify_s3ft_file_list return_code=8 b64_json".as_slice(),
br"notify_s3ft_file_list return_code=9 b64_json chid=4 cid=4 path=\/",
br"notify_s3ft_file_list b64_json chid=4 cid=4 path=\/",
br"notify_s3ft_file_list return_code=x b64_json",
br"notify_s3ft_file_list return_code=7 return_code=9 b64_json",
] {
assert_eq!(s3_notify(&mut files, foreign), None);
}
assert!(!files.lists.get_mut(&8).unwrap().acknowledge());
assert_eq!(s3_notify(&mut files, br"notify_s3ft_file_list b64_json return_code=7"), ack_first.then_some(7));
assert_eq!(s3_notify(&mut files, br"notify_s3ft_file_list b64_json=broken return_code=7"), None);
if !ack_first { assert!(files.lists.get_mut(&7).unwrap().acknowledge()); }
assert_eq!(s3_list_answer(&mut files).unwrap()["entries"], json!([]));
}
}
#[test]
fn s3_listing_rejects_missing_malformed_and_truncated_payloads() {
for (command, message) in [
("notify_s3ft_file_list return_code=7", "missing b64_json"),
("notify_s3ft_file_list return_code=7 b64_json b64_json=e30=", "malformed S3 file list notification"),
("notify_s3ft_file_list return_code=7|b64_json", "malformed S3 file list notification"),
("notify_s3ft_file_list return_code=7 b64_json=e30", "invalid S3 file list base64"),
(r"notify_s3ft_file_list return_code=7 b64_json=e30=\", "invalid escape"),
("notify_s3ft_file_list return_code=7 b64_json=eyJjb250ZW50cyI6", "truncated S3 file list JSON"),
("notify_s3ft_file_list return_code=7 b64_json=e30=", "malformed S3 file list JSON"),
] {
let mut files = s3_listing("/");
assert_eq!(s3_notify(&mut files, command.as_bytes()), None);
assert!(files.lists.get_mut(&7).unwrap().acknowledge());
let error = s3_list_answer(&mut files).unwrap_err();
assert_eq!(error.code, ErrorCode::ServerError);
assert!(error.message.contains(message), "{error:?}");
}
}
#[test]
fn s3_listing_projects_whole_channel_response_to_requested_directory() {
use base64::{engine::general_purpose::STANDARD, Engine};
let payload = STANDARD.encode(br#"{"contents":[
{"key":"a/sub/nested.bin","size":1},
{"key":"a/file.bin","size":3,"last_modified":"2020-01-01T01:00:00+01:00"},
{"key":"a/empty/.tsfolder","size":0},
{"key":"ab/not-a-child","size":1},
{"key":"a/../bad","size":1}
]}"#);
let mut files = s3_listing("/a/");
assert!(!files.lists.get_mut(&7).unwrap().acknowledge());
let command = format!("notify_s3ft_file_list return_code=7 b64_json={}", payload.replace('/', r"\/"));
assert_eq!(s3_notify(&mut files, command.as_bytes()), Some(7));
let result = s3_list_answer(&mut files).unwrap();
assert_eq!(result["path"], "/a/");
assert_eq!(result["malformed"], 1);
assert_eq!(result["entries"], json!([
{ "name": "empty", "type": "folder", "size": 0, "datetime": 0 },
{ "name": "file.bin", "type": "file", "size": 3, "datetime": 1577836800 },
{ "name": "sub", "type": "folder", "size": 0, "datetime": 0 },
]));
}
#[test]
@@ -1729,7 +1944,7 @@ mod tests {
fn md5_hex(b: &[u8]) -> String {
use md5::{Digest, Md5};
format!("{:x}", Md5::digest(b))
base16ct::lower::encode_string(&Md5::digest(b))
}
fn parts(dir: &Path) -> usize {
@@ -1894,26 +2109,34 @@ mod tests {
#[tokio::test]
async fn upload_sends_exact_bytes_and_sees_server_close() {
let dir = scratch("ul");
let data = pattern(2 * CHUNK + 999);
let data = pattern(5 * CHUNK);
let src = dir.join("Ünïcødé source.bin");
std::fs::write(&src, &data).unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let len = data.len();
let (ready, receiving) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let mut key = [0u8; 32];
s.read_exact(&mut key).await.unwrap();
assert_eq!(&key, KEY);
let mut got = vec![0u8; len];
let started = Instant::now();
ready.send(()).unwrap();
s.read_exact(&mut got).await.unwrap();
assert!(started.elapsed() >= Duration::from_millis(240), "five chunks arrived above the configured 1 MiB/s upload limit");
let mut extra = [0u8; 1];
assert_eq!(s.read(&mut extra).await.unwrap(), 0, "client closes its write half after the file");
got
});
let (file, size) = prepare_upload(&src).unwrap();
let progress = Arc::new(AtomicU64::new(0));
let ended = upload(keyed(addr).await, file, size, 0, progress.clone(), Arc::default(), quiet()).await.unwrap();
let rate = Arc::new(RateLimit::default());
rate.set(1024 * 1024);
let stream = keyed(addr).await;
receiving.await.unwrap();
let ended = upload(stream, file, size, 0, progress.clone(), rate, quiet()).await.unwrap();
assert!(matches!(ended, Ended::Complete { closed: true }));
let got = server.await.unwrap();
assert_eq!(md5_hex(&got), md5_hex(&data));
@@ -2019,12 +2242,14 @@ mod tests {
let queued = |id: u32, direction: Direction, channel_id: u64| Transfer {
id,
direction,
backend: ListBackend::Legacy,
channel_id,
path: format!("/f{id}"),
cpw: String::new(),
overwrite: false,
local: Local::Upload { file: None, size: 0, modified: None },
total: 0,
s3_total: None,
stage: Stage::Queued,
server_ftid: None,
confirmed: false,
@@ -2075,12 +2300,14 @@ mod tests {
let running = |id: u32, direction: Direction, started: u64| Transfer {
id,
direction,
backend: ListBackend::Legacy,
channel_id: 7,
path: format!("/f{id}"),
cpw: String::new(),
overwrite: false,
local: Local::Upload { file: None, size: 0, modified: None },
total: 0,
s3_total: None,
stage: Stage::Init { ftid: id as u16, since: now },
server_ftid: None,
confirmed: false,
@@ -2124,12 +2351,14 @@ mod tests {
Transfer {
id: 9,
direction: if matches!(local, Local::Download { .. }) { Direction::Download } else { Direction::Upload },
backend: ListBackend::Legacy,
channel_id: 7,
path: "/i.bin".into(),
cpw: String::new(),
overwrite: false,
local,
total: 0,
s3_total: None,
stage,
server_ftid: Some(40),
confirmed: false,
+279
View File
@@ -0,0 +1,279 @@
//! TeamSpeak's S3 object metadata and channel file list projection.
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::marker::PhantomData;
use base64::{engine::general_purpose::STANDARD, Engine};
use serde::de::{value::MapAccessDeserializer, MapAccess, Visitor};
use serde::Deserialize;
use serde_json::{json, Value};
use super::{bad, check_remote_dir, remote_component, MAX_LIST_ENTRIES, MAX_PATH_CHARS};
use crate::protocol::{ErrorCode, ErrorObj};
const FOLDER_MARKER: &str = ".tsfolder";
// S3 limits the entire object key to 1,024 UTF-8 bytes, independent of the browser's char limit.
const MAX_KEY_BYTES: usize = 1024;
// The transport limits decompressed commands to 2 MiB. Also bound decoding here so a
// caller cannot allocate from an unbounded field independently of the transport.
const MAX_ENCODED_LIST_BYTES: usize = 2 * 1024 * 1024;
/// Largest object size representable exactly in the bridge's JSON consumers.
pub(super) const MAX_SAFE_SIZE: u64 = (1 << 53) - 1;
// Serde's default struct visitor also accepts positional arrays; the S3 format uses maps only.
struct JsonObject<T>(T);
impl<'de, T: Deserialize<'de>> Deserialize<'de> for JsonObject<T> {
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
struct ObjectVisitor<T>(PhantomData<T>);
impl<'de, T: Deserialize<'de>> Visitor<'de> for ObjectVisitor<T> {
type Value = T;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("a JSON object") }
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
T::deserialize(MapAccessDeserializer::new(map))
}
}
de.deserialize_map(ObjectVisitor(PhantomData)).map(Self)
}
}
/// Semantic fields from one channel-relative object; no wire envelope or transfer grant.
#[derive(Deserialize)]
#[serde(transparent)]
pub(crate) struct ListObject<'a>(#[serde(borrow)] JsonObject<ListObjectFields<'a>>);
#[derive(Deserialize)]
struct ListObjectFields<'a> {
#[serde(borrow)]
key: Cow<'a, str>,
size: u64,
/// Parsed Unix seconds, or `None` if the object timestamp was absent or unparseable.
#[serde(default, deserialize_with = "parse_timestamp")]
last_modified: Option<i64>,
}
#[derive(Deserialize)]
struct ListEnvelope<'a> {
#[serde(borrow)]
contents: Vec<ListObject<'a>>,
}
fn parse_timestamp<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<i64>, D::Error> {
#[derive(Deserialize)]
struct Timestamp<'a>(#[serde(borrow)] Cow<'a, str>);
Ok(Option::<Timestamp<'_>>::deserialize(deserializer)?.and_then(|Timestamp(text)| {
chrono::DateTime::parse_from_rfc3339(&text).ok().map(|time| time.timestamp())
}))
}
fn invalid_list(message: &'static str) -> ErrorObj { ErrorObj::new(ErrorCode::ServerError, message) }
/// The only TeamSpeak escape possible in standard base64 is `\/`.
fn unescape_base64(raw: &[u8]) -> Result<Cow<'_, [u8]>, ErrorObj> {
let mut parts = raw.split(|byte| *byte == b'\\');
let first = parts.next().expect("split returns at least one part");
let Some(second) = parts.next() else { return Ok(Cow::Borrowed(raw)); };
let mut encoded = Vec::with_capacity(raw.len() - 1);
encoded.extend_from_slice(first);
for part in std::iter::once(second).chain(parts) {
if !part.starts_with(b"/") { return Err(invalid_list("invalid escape in S3 file list base64")); }
encoded.extend_from_slice(part);
}
Ok(Cow::Owned(encoded))
}
/// Only a present, empty field stands for an empty channel. Nonempty data must decode to
/// the whole JSON envelope; neither decoding errors nor server contents escape into errors.
pub(super) fn decode_list(path: &str, raw: &[u8]) -> Result<(Vec<Value>, usize), ErrorObj> {
if raw.is_empty() { return project_list(path, true, &[]); }
if raw.len() > MAX_ENCODED_LIST_BYTES {
return Err(invalid_list("S3 file list exceeds the payload limit; listing not complete"));
}
let encoded = unescape_base64(raw)?;
let decoded = STANDARD.decode(encoded.as_ref()).map_err(|_| invalid_list("invalid S3 file list base64"))?;
let JsonObject(envelope): JsonObject<ListEnvelope<'_>> = serde_json::from_slice(&decoded).map_err(|error| {
if error.is_eof() { invalid_list("truncated S3 file list JSON") }
else { invalid_list("malformed S3 file list JSON") }
})?;
project_list(path, true, &envelope.contents)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Child {
File { size: u64, datetime: i64 },
Folder,
ConflictingFile,
ConflictingFolder,
}
fn validated_key(key: &str) -> Option<(&str, bool)> {
if key.len() > MAX_KEY_BYTES || (key.len() >= MAX_PATH_CHARS && key.chars().count() >= MAX_PATH_CHARS) {
return None;
}
let item = key.strip_suffix('/').unwrap_or(key);
let trailing_slash = item.len() != key.len();
let mut parts = item.split('/').peekable();
while let Some(part) = parts.next() {
remote_component(part).ok()?;
// A marker may only be a leaf object, never a user-addressable directory.
if part == FOLDER_MARKER && (trailing_slash || parts.peek().is_some()) {
return None;
}
}
Some((item, trailing_slash))
}
/// Return the direct children and malformed count for a canonical browser directory (`/a/`).
/// The caller must first validate the envelope, correlate it, and establish whether it succeeded.
/// The input is the whole channel's object list; never publish a partial result after overflow.
pub(crate) fn project_list(
path: &str, success: bool, contents: &[ListObject<'_>],
) -> Result<(Vec<Value>, usize), ErrorObj> {
if !success {
return Err(ErrorObj::new(ErrorCode::ServerError, "S3 file listing failed"));
}
check_remote_dir(path)?;
let relative_dir = &path[1..];
if !path.ends_with('/') || relative_dir.len() > MAX_KEY_BYTES
|| relative_dir.split('/').any(|part| part == FOLDER_MARKER)
{
return Err(bad("invalid S3 directory path"));
}
if contents.len() > MAX_LIST_ENTRIES {
return Err(ErrorObj::new(ErrorCode::ServerError,
format!("the channel has more than {MAX_LIST_ENTRIES} S3 objects; listing not complete")));
}
let mut malformed = 0;
let mut children = BTreeMap::new();
for ListObject(JsonObject(object)) in contents {
if object.size > MAX_SAFE_SIZE { return Err(invalid_list("invalid S3 file list object size")); }
let Some((key, trailing_slash)) = validated_key(&object.key) else {
malformed += 1;
continue;
};
let Some(relative) = key.strip_prefix(relative_dir).filter(|key| !key.is_empty()) else { continue };
let (name, child) = match relative.split_once('/') {
Some((folder, _)) => (folder, Child::Folder),
None if relative == FOLDER_MARKER => continue,
None if trailing_slash => (relative, Child::Folder),
None => (relative, Child::File { size: object.size, datetime: object.last_modified.unwrap_or(0) }),
};
children.entry(name).and_modify(|old| {
*old = match (*old, child) {
(a, b) if a == b => a,
(Child::Folder | Child::ConflictingFolder, _) | (_, Child::Folder) => Child::ConflictingFolder,
_ => Child::ConflictingFile,
};
}).or_insert(child);
}
// Keep colliding directories navigable, but never publish ambiguous file metadata.
// An ambiguous direct child contributes one malformed entry, independent of input order.
let mut entries = Vec::with_capacity(children.len());
for (name, child) in children {
let (kind, size, datetime) = match child {
Child::Folder => ("folder", 0, 0),
Child::File { size, datetime } => ("file", size, datetime),
Child::ConflictingFile => { malformed += 1; continue; }
Child::ConflictingFolder => { malformed += 1; ("folder", 0, 0) }
};
entries.push(json!({ "name": name, "type": kind, "size": size, "datetime": datetime }));
}
Ok((entries, malformed))
}
#[cfg(test)]
mod tests {
use super::*;
fn object(key: &str, size: u64, last_modified: Option<i64>) -> ListObject<'_> {
ListObject(JsonObject(ListObjectFields { key: Cow::Borrowed(key), size, last_modified }))
}
#[test]
fn rejects_oversize_and_structurally_invalid_wire_lists() {
let too_large = vec![b'A'; MAX_ENCODED_LIST_BYTES + 1];
assert!(decode_list("/", &too_large).unwrap_err().message.contains("payload limit"));
for wire in [r"[[]]", r#"{"contents":[["x",1,null]]}"#, r#"{"contents":[{"key":"x","size":9007199254740992}]}"#] {
assert_eq!(decode_list("/", STANDARD.encode(wire).as_bytes()).unwrap_err().code, ErrorCode::ServerError);
}
assert_eq!(unescape_base64(br"AA\/Z").unwrap().as_ref(), b"AA/Z");
}
#[test]
fn projects_only_direct_children_in_name_order() {
let contents = [
object("a/sub/nested/file", 9, None),
object("a/slash/", 9, Some(123)),
object("a/empty/.tsfolder", 0, Some(123)),
object("a/.tsfolder", 0, None),
object("a/\u{e9}.txt", 3, Some(100)),
object("a/b.txt", 8, None),
object("a/c.txt", 9, Some(-1)),
object("a/", 0, None),
object("a", 0, None),
object("ab/not-a-child", 1, None),
];
let (entries, malformed) = project_list("/a/", true, &contents).unwrap();
assert_eq!(malformed, 0);
assert_eq!(entries, vec![
json!({ "name": "b.txt", "type": "file", "size": 8, "datetime": 0 }),
json!({ "name": "c.txt", "type": "file", "size": 9, "datetime": -1 }),
json!({ "name": "empty", "type": "folder", "size": 0, "datetime": 0 }),
json!({ "name": "slash", "type": "folder", "size": 0, "datetime": 0 }),
json!({ "name": "sub", "type": "folder", "size": 0, "datetime": 0 }),
json!({ "name": "\u{e9}.txt", "type": "file", "size": 3, "datetime": 100 }),
]);
assert!(project_list("/a/empty/", true, &contents).unwrap().0.is_empty());
}
#[test]
fn rejects_unsafe_or_oversize_keys_before_inferring_folders() {
let four_bytes = "\u{1f642}".repeat(255);
let too_many_bytes = format!("{four_bytes}/abc\u{e9}");
let full_byte_limit = format!("{four_bytes}/abc");
let ascii = "a".repeat(255);
let too_many_chars = format!("{ascii}/{ascii}/a");
let too_long_name = "a".repeat(256);
let contents = [
object("/absolute", 1, None), object("parent/../file", 1, None),
object("parent//file", 1, None), object("parent/./file", 1, None),
object("parent\\file", 1, None), object("parent/\nfile", 1, None),
object("parent/.tsfolder/file", 1, None), object("parent/.tsfolder/", 1, None),
object("https://private.invalid/file?signature=secret", 1, None), object("", 1, None),
object(&too_many_bytes, 1, None), object(&too_many_chars, 1, None),
object(&too_long_name, 1, None), object(&full_byte_limit, 1, None),
];
let (entries, malformed) = project_list("/", true, &contents).unwrap();
assert_eq!(malformed, contents.len() - 1);
assert_eq!(entries, vec![json!({ "name": four_bytes, "type": "folder", "size": 0, "datetime": 0 })]);
assert!(project_list("/parent/../", true, &[]).is_err());
}
#[test]
fn resolves_path_and_metadata_collisions_independently_of_input_order() {
let mut contents = [
object("same", 7, Some(123)), object("same/.tsfolder", 0, None),
object("same/child", 7, None), object("duplicate", 2, None),
object("duplicate", 2, Some(0)), object("contradictory", 3, Some(456)),
object("contradictory", 4, Some(456)),
];
let projected = project_list("/", true, &contents).unwrap();
contents.reverse();
assert_eq!(project_list("/", true, &contents).unwrap(), projected);
assert_eq!(projected, (vec![
json!({ "name": "duplicate", "type": "file", "size": 2, "datetime": 0 }),
json!({ "name": "same", "type": "folder", "size": 0, "datetime": 0 }),
], 2));
}
#[test]
fn rejects_failed_or_overflowed_backend_lists() {
assert_eq!(project_list("/", false, &[object("file", 2, None)]).unwrap_err().code, ErrorCode::ServerError);
let contents: Vec<_> = (0..=MAX_LIST_ENTRIES).map(|_| object("nested/file", 2, None)).collect();
assert_eq!(project_list("/", true, &contents).unwrap_err().code, ErrorCode::ServerError);
assert_eq!(project_list("/", true, &[]).unwrap(), (vec![], 0));
}
}
+542
View File
@@ -0,0 +1,542 @@
//! Direct object-storage I/O. The correlated TeamSpeak grant supplies the only HTTP credential.
use std::fmt;
use std::fs::File;
use std::io::{self, Read};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime};
use bytes::Bytes;
use reqwest::header::{CONTENT_LENGTH, CONTENT_RANGE, IF_NONE_MATCH};
use reqwest::{Client, ClientBuilder, Response, StatusCode, Url};
use tokio::sync::{mpsc, oneshot, watch};
use crate::protocol::{ErrorCode, ErrorObj};
use super::{
bad, disk_writer, io_err, upload_source_unchanged, CancelOnDrop, CommitControl, Ended,
RateLimit, ToDisk, Written, BUFFERS, CHUNK, CONFIRM_DEADLINE, STALL_DEADLINE,
};
use super::s3::MAX_SAFE_SIZE;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
const TRANSFER_TIMEOUT: Duration = Duration::from_secs(60 * 60);
const MAX_URL_BYTES: usize = 16 * 1024;
/// An already-correlated grant. The URL must not be shown in diagnostics or bridge output.
pub(crate) struct SignedUrl(Url);
impl fmt::Debug for SignedUrl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("SignedUrl(<redacted>)") }
}
impl SignedUrl {
pub(crate) fn parse(raw: &str) -> Result<Self, ErrorObj> {
let invalid = || ErrorObj::new(ErrorCode::ServerError, "storage grant did not include a usable HTTPS URL");
if raw.len() > MAX_URL_BYTES || !raw.bytes().all(|b| b.is_ascii_graphic()) {
return Err(invalid());
}
let rest = raw.strip_prefix("https://").ok_or_else(invalid)?;
let authority = rest.split(['/', '?', '#']).next().expect("split returns at least one item");
if authority.is_empty() || authority.contains('@') || raw.contains('\\') {
return Err(invalid());
}
let url = Url::parse(raw).map_err(|_| invalid())?;
// Parsing must not rewrite parts of the signed request, e.g. encoded dot segments.
if !url.has_host() || url.fragment().is_some() || url.as_str() != raw {
return Err(invalid());
}
Ok(Self(url))
}
}
fn client_builder() -> ClientBuilder {
Client::builder()
.tls_backend_rustls()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.retry(reqwest::retry::never())
.referer(false)
.no_gzip().no_brotli().no_deflate().no_zstd()
.http1_only()
.pool_max_idle_per_host(0)
.connect_timeout(CONNECT_TIMEOUT)
.timeout(TRANSFER_TIMEOUT)
}
fn client() -> Result<Client, ErrorObj> {
client_builder().https_only(true).build()
.map_err(|_| ErrorObj::new(ErrorCode::Internal, "cannot initialize HTTPS storage transport"))
}
fn timeout() -> ErrorObj { ErrorObj::new(ErrorCode::Io, "storage transfer timed out") }
// In particular, do not format the reqwest error, its causes, the response body or headers.
// URLs, signature errors and redirects can all contain the presigned credential.
fn network_error(error: reqwest::Error) -> ErrorObj {
if error.is_timeout() { return timeout(); }
ErrorObj::new(ErrorCode::Io, "HTTPS storage transfer failed")
}
fn response_error(status: StatusCode, conditional_put: bool) -> ErrorObj {
let (code, message) = match status {
StatusCode::PRECONDITION_FAILED | StatusCode::CONFLICT if conditional_put =>
(ErrorCode::FileExists, "storage declined the upload without overwrite"),
StatusCode::NOT_FOUND => (ErrorCode::NotFound, "file was not found in storage"),
StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => (ErrorCode::ServerError, "storage declined the authorization"),
_ if status.is_redirection() => (ErrorCode::ServerError, "storage tried to redirect the request"),
_ => (ErrorCode::ServerError, "storage refused the request"),
};
ErrorObj::new(code, format!("{message} (HTTP {})", status.as_u16()))
}
fn size_error() -> ErrorObj { ErrorObj::new(ErrorCode::Io, "storage response did not match the expected file size") }
fn download_size(response: &Response, expected: Option<u64>) -> Result<u64, ErrorObj> {
let length = response.content_length();
if response.headers().contains_key(CONTENT_RANGE) ||
matches!((expected, length), (Some(expected), Some(length)) if expected != length)
{
return Err(size_error());
}
expected.or(length).filter(|&n| n <= MAX_SAFE_SIZE).ok_or_else(size_error)
}
pub(crate) struct Download {
pub id: u32,
pub dir: PathBuf,
pub name: String,
pub overwrite: bool,
pub expected_size: Option<u64>,
pub total: Arc<AtomicU64>,
pub progress: Arc<AtomicU64>,
pub control: Arc<CommitControl>,
pub rate: Arc<RateLimit>,
}
impl Download {
pub(crate) async fn run(self, url: SignedUrl) -> Result<Ended, ErrorObj> {
self.run_with(client()?, url).await
}
async fn run_with(self, client: Client, url: SignedUrl) -> Result<Ended, ErrorObj> {
let Self { id, dir, name, overwrite, expected_size, total, progress, control, rate } = self;
let _cancel = CancelOnDrop(Some(control.clone()));
super::local_component(&name)?;
let mut response = tokio::time::timeout(STALL_DEADLINE, client.get(url.0).send()).await
.map_err(|_| timeout())?.map_err(network_error)?;
if response.status() != StatusCode::OK {
return Err(response_error(response.status(), false));
}
let size = download_size(&response, expected_size)?;
total.store(size, Ordering::Release);
let (tx, rx) = mpsc::channel(BUFFERS);
let (back, _) = mpsc::channel(1);
let writer = tokio::task::spawn_blocking(move || disk_writer(dir, id, overwrite, name, rx, back, control, None));
let streamed = tokio::time::timeout(TRANSFER_TIMEOUT, async {
let mut remaining = size;
loop {
let Some(mut frame) = tokio::time::timeout(STALL_DEADLINE, response.chunk()).await
.map_err(|_| timeout())?.map_err(network_error)? else { break };
if frame.len() as u64 > remaining { return Err(size_error()); }
while !frame.is_empty() {
let n = rate.s3_chunk_len(frame.len().min(CHUNK));
rate.acquire(n).await;
let chunk = if n == frame.len() { std::mem::take(&mut frame) } else { frame.split_to(n) };
if tx.send(ToDisk::HttpData(chunk)).await.is_err() { return Ok(false); }
remaining -= n as u64;
progress.fetch_add(n as u64, Ordering::Release);
}
}
if remaining != 0 { return Err(size_error()); }
Ok(true)
}).await.unwrap_or_else(|_| Err(timeout()));
if matches!(streamed, Ok(true)) {
// Only an exact, fully received body can open the existing atomic publication gate.
let _ = tx.send(ToDisk::Commit).await;
}
drop(tx);
let written = writer.await.map_err(|_| ErrorObj::new(ErrorCode::Internal, "download staging task failed"))?;
streamed?;
match written? {
Written::Published => Ok(Ended::Complete { closed: true }),
Written::Paused(_) => Err(ErrorObj::new(ErrorCode::Internal, "HTTPS download did not publish")),
}
}
}
pub(crate) struct Upload {
pub file: File,
pub size: u64,
pub modified: Option<SystemTime>,
pub overwrite: bool,
pub progress: Arc<AtomicU64>,
pub rate: Arc<RateLimit>,
}
/// Return the backing buffer after the HTTP client writes or drops the last view of these bytes.
struct UploadChunk {
buf: Option<Vec<u8>>,
len: usize,
back: mpsc::Sender<Vec<u8>>,
}
impl AsRef<[u8]> for UploadChunk {
fn as_ref(&self) -> &[u8] { &self.buf.as_ref().expect("owned buffer")[..self.len] }
}
impl Drop for UploadChunk {
fn drop(&mut self) {
let _ = self.back.try_send(self.buf.take().expect("owned buffer"));
}
}
struct UploadBody {
rx: mpsc::Receiver<(Vec<u8>, usize)>,
back: mpsc::Sender<Vec<u8>>,
frame: Bytes,
remaining: u64,
progress: Arc<AtomicU64>,
rate: Arc<RateLimit>,
activity: watch::Sender<UploadActivity>,
}
impl UploadBody {
async fn next(mut self) -> Option<(io::Result<Bytes>, Self)> {
if self.remaining == 0 { return None; }
if self.frame.is_empty() {
let Some((buf, len)) = self.rx.recv().await else {
self.remaining = 0;
return Some((Err(io::Error::other("upload source ended early")), self));
};
self.frame = Bytes::from_owner(UploadChunk { buf: Some(buf), len, back: self.back.clone() });
}
let n = self.rate.s3_chunk_len(self.frame.len());
self.activity.send_replace(UploadActivity::Pacing);
self.rate.acquire(n).await;
let chunk = if n == self.frame.len() { std::mem::take(&mut self.frame) } else { self.frame.split_to(n) };
self.remaining -= n as u64;
self.progress.fetch_add(n as u64, Ordering::Relaxed);
self.activity.send_replace(if self.remaining == 0 { UploadActivity::AwaitingResponse } else { UploadActivity::Sending });
Some((Ok(chunk), self))
}
}
#[derive(Clone, Copy)]
enum UploadActivity { Sending, Pacing, AwaitingResponse }
async fn upload_watchdog(mut activity: watch::Receiver<UploadActivity>) -> ErrorObj {
loop {
let current = *activity.borrow_and_update();
let wait = match current {
UploadActivity::Sending => STALL_DEADLINE,
UploadActivity::AwaitingResponse => CONFIRM_DEADLINE,
// Waiting for a configured shared bandwidth allowance is not a network stall.
UploadActivity::Pacing => {
if activity.changed().await.is_err() { return timeout(); }
continue;
}
};
if !matches!(tokio::time::timeout(wait, activity.changed()).await, Ok(Ok(()))) {
return timeout();
}
}
}
fn read_upload(
mut file: File,
size: u64,
modified: Option<SystemTime>,
prepared: oneshot::Sender<Result<(), ErrorObj>>,
tx: mpsc::Sender<(Vec<u8>, usize)>,
mut back: mpsc::Receiver<Vec<u8>>,
source_error: Arc<OnceLock<ErrorObj>>,
) {
let ready = upload_source_unchanged(&file, size, modified);
let failed = ready.is_err();
if prepared.send(ready).is_err() || failed { return; }
let mut remaining = size;
while remaining != 0 {
let Some(mut buf) = back.blocking_recv() else { return };
let n = remaining.min(CHUNK as u64) as usize;
if let Err(e) = file.read_exact(&mut buf[..n]) {
let _ = source_error.set(io_err("cannot read the full upload source", e));
return;
}
remaining -= n as u64;
// Check before handing the HTTP client the final bytes that can commit the PUT.
if remaining == 0 {
if let Err(e) = upload_source_unchanged(&file, size, modified) {
let _ = source_error.set(e);
return;
}
}
if tx.blocking_send((buf, n)).is_err() { return; }
}
}
impl Upload {
pub(crate) async fn run(self, url: SignedUrl) -> Result<Ended, ErrorObj> {
self.run_with(client()?, url).await
}
async fn run_with(self, client: Client, url: SignedUrl) -> Result<Ended, ErrorObj> {
let Self { file, size, modified, overwrite, progress, rate } = self;
if size > MAX_SAFE_SIZE { return Err(bad("upload file is too large")); }
let (ready, prepared) = oneshot::channel();
let (tx, rx) = mpsc::channel(BUFFERS);
let (back, bufs) = mpsc::channel(BUFFERS);
for _ in 0..size.div_ceil(CHUNK as u64).min(BUFFERS as u64) {
back.try_send(vec![0; size.min(CHUNK as u64) as usize]).expect("capacity");
}
let source_error = Arc::new(OnceLock::new());
let source = source_error.clone();
let _reader = tokio::task::spawn_blocking(move || read_upload(file, size, modified, ready, tx, bufs, source));
tokio::time::timeout(STALL_DEADLINE, prepared).await.map_err(|_| timeout())?
.map_err(|_| ErrorObj::new(ErrorCode::Internal, "upload source task failed"))??;
let mut request = client.put(url.0).header(CONTENT_LENGTH, size);
if !overwrite { request = request.header(IF_NONE_MATCH, "*"); }
let initial = if size == 0 { UploadActivity::AwaitingResponse } else { UploadActivity::Sending };
let (activity, watch) = watch::channel(initial);
if size != 0 {
let body = UploadBody {
rx, back, frame: Bytes::new(), remaining: size, progress: progress.clone(), rate,
activity: activity.clone(),
};
request = request.body(reqwest::Body::wrap_stream(futures::stream::unfold(body, UploadBody::next)));
}
// Hold the activity sender even if the HTTP client drops the request body as soon as it
// sees response headers, so that headers (e.g. an early 412) decide the outcome.
let _activity = activity;
let response = tokio::select! {
biased;
result = request.send() => result.map_err(|e| source_error.get().cloned().unwrap_or_else(|| network_error(e)))?,
error = upload_watchdog(watch) => return Err(error),
};
if !response.status().is_success() { return Err(response_error(response.status(), !overwrite)); }
if progress.load(Ordering::Relaxed) != size {
return Err(source_error.get().cloned().unwrap_or_else(|| ErrorObj::new(ErrorCode::Io, "storage answered before the whole file was uploaded")));
}
Ok(Ended::Complete { closed: true })
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
const TARGET: &str = "/bucket/file%2B.bin?X-Amz-Signature=signature-secret&k=%2B%2F%25";
const CASE_TIMEOUT: Duration = Duration::from_secs(5);
struct Scratch(PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("tp-s3-{tag}-{}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
Self(dir)
}
fn parts(&self) -> usize {
std::fs::read_dir(&self.0).unwrap().filter(|e| e.as_ref().unwrap().path().extension().is_some_and(|e| e == "part")).count()
}
fn download(&self, expected_size: Option<u64>) -> Download {
Download {
id: 9, dir: self.0.clone(), name: "download.bin".into(), overwrite: false,
expected_size, total: Arc::default(), progress: Arc::default(), control: Arc::default(), rate: Arc::default(),
}
}
fn upload(&self, data: &[u8], overwrite: bool) -> Upload {
let path = self.0.join("upload.bin");
std::fs::write(&path, data).unwrap();
let (file, size) = super::super::prepare_upload(&path).unwrap();
let modified = file.metadata().unwrap().modified().ok();
Upload { file, size, modified, overwrite, progress: Arc::default(), rate: Arc::default() }
}
}
impl Drop for Scratch {
fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
}
// These byte-contract tests bypass only URL construction and the HTTPS-only scheme guard.
async fn fixture() -> (TcpListener, Client, SignedUrl) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let url = SignedUrl(Url::parse(&format!("http://{addr}{TARGET}")).unwrap());
(listener, client_builder().build().unwrap(), url)
}
async fn read_request(listener: TcpListener, verb: &str) -> (BufReader<TcpStream>, BTreeMap<String, String>) {
let (stream, _) = listener.accept().await.unwrap();
let mut stream = BufReader::new(stream);
let mut line = String::new();
stream.read_line(&mut line).await.unwrap();
assert_eq!(line, format!("{verb} {TARGET} HTTP/1.1\r\n"));
let mut headers = BTreeMap::new();
loop {
line.clear();
assert_ne!(stream.read_line(&mut line).await.unwrap(), 0, "short request headers");
if line == "\r\n" { break; }
let (name, value) = line.split_once(':').unwrap();
assert!(headers.insert(name.to_ascii_lowercase(), value.trim().to_owned()).is_none());
}
for name in ["authorization", "cookie", "proxy-authorization", "referer", "accept-encoding", "range"] {
assert!(!headers.contains_key(name));
}
(stream, headers)
}
#[test]
fn grants_must_be_https_and_remain_private() {
let url = SignedUrl::parse(&format!("https://storage.example{TARGET}")).unwrap();
assert_eq!(format!("{url:?}"), "SignedUrl(<redacted>)");
for bad in [
"http://storage.example/?sig=signature-secret",
"https://user:pw@storage.example/?sig=signature-secret",
"https://@storage.example/?sig=signature-secret",
"https://storage.example/a/%2e%2e/b?sig=signature-secret",
"https://storage.example/a?sig=signature-secret#fragment",
"https://storage.example/\t?sig=signature-secret",
] {
let error = SignedUrl::parse(bad).unwrap_err();
assert_eq!(error.code, ErrorCode::ServerError);
assert!(!format!("{error:?}").contains("signature-secret"));
}
}
#[tokio::test]
async fn put_sends_exact_length_and_conditional_header() {
tokio::time::timeout(CASE_TIMEOUT, async {
let dir = Scratch::new("put");
let large = vec![42; CHUNK * 5 + 17];
for (data, overwrite, response) in [
(large.as_slice(), false, "200 OK"),
(b"".as_slice(), true, "200 OK"),
(b"taken".as_slice(), false, "412 Precondition Failed"),
] {
let (listener, client, url) = fixture().await;
let upload = dir.upload(data, overwrite);
let progress = upload.progress.clone();
let server = async {
let (mut stream, headers) = read_request(listener, "PUT").await;
assert_eq!(headers["content-length"], data.len().to_string());
assert_eq!(headers.get("if-none-match").map(String::as_str), (!overwrite).then_some("*"));
assert!(!headers.contains_key("transfer-encoding"));
let mut received = vec![0; data.len()];
stream.read_exact(&mut received).await.unwrap();
assert_eq!(received, data);
let answer = format!("HTTP/1.1 {response}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
stream.get_mut().write_all(answer.as_bytes()).await.unwrap();
};
let (result, ()) = tokio::join!(upload.run_with(client, url), server);
if response.starts_with("200") {
assert!(matches!(result.unwrap(), Ended::Complete { .. }));
} else {
assert_eq!(result.unwrap_err().code, ErrorCode::FileExists);
}
assert_eq!(progress.load(Ordering::Relaxed), data.len() as u64);
}
}).await.unwrap();
}
#[tokio::test]
async fn get_checks_size_and_only_publishes_without_clobber() {
tokio::time::timeout(CASE_TIMEOUT, async {
let dir = Scratch::new("get");
let target = dir.0.join("download.bin");
for (reply, expected, error) in [
(b"Content-Length: 2\r\n\r\nhi".as_slice(), None, None),
(b"Content-Length: 3\r\n\r\nhi".as_slice(), Some(3), Some(ErrorCode::Io)),
(b"Content-Length: 2\r\n\r\nhi".as_slice(), Some(1), Some(ErrorCode::Io)),
(b"Transfer-Encoding: chunked\r\n\r\n2\r\nhi\r\n0\r\n\r\n".as_slice(), Some(1), Some(ErrorCode::Io)),
(b"Content-Length: 2\r\n\r\nhi".as_slice(), Some(2), Some(ErrorCode::FileExists)),
] {
let (listener, client, url) = fixture().await;
let download = dir.download(expected);
let (total, progress) = (download.total.clone(), download.progress.clone());
let server = async {
let (mut stream, _) = read_request(listener, "GET").await;
if error == Some(ErrorCode::FileExists) { std::fs::write(&target, b"keep").unwrap(); }
stream.get_mut().write_all(b"HTTP/1.1 200 OK\r\nConnection: close\r\n").await.unwrap();
stream.get_mut().write_all(reply).await.unwrap();
};
let (result, ()) = tokio::join!(download.run_with(client, url), server);
if let Some(error) = error {
assert_eq!(result.unwrap_err().code, error);
if error == ErrorCode::FileExists {
assert_eq!(std::fs::read(&target).unwrap(), b"keep");
} else {
assert!(!target.exists());
}
} else {
assert!(matches!(result.unwrap(), Ended::Complete { .. }));
assert_eq!(std::fs::read(&target).unwrap(), b"hi");
assert_eq!(total.load(Ordering::Acquire), 2);
assert_eq!(progress.load(Ordering::Acquire), 2);
std::fs::remove_file(&target).unwrap();
}
assert_eq!(dir.parts(), 0);
}
}).await.unwrap();
}
#[tokio::test]
async fn redirects_and_error_body_are_not_exposed() {
tokio::time::timeout(CASE_TIMEOUT, async {
let dir = Scratch::new("redirect");
let (listener, client, url) = fixture().await;
let server = async {
let (mut stream, _) = read_request(listener, "GET").await;
stream.get_mut().write_all(b"HTTP/1.1 307 Temporary Redirect\r\nLocation: /other?token=location-secret\r\nContent-Length: 11\r\n\r\nbody-secret").await.unwrap();
};
let (result, ()) = tokio::join!(dir.download(None).run_with(client, url), server);
let error = result.unwrap_err();
assert_eq!(error.code, ErrorCode::ServerError);
assert_eq!(error.message, "storage tried to redirect the request (HTTP 307)");
assert_eq!(dir.parts(), 0);
}).await.unwrap();
}
#[tokio::test]
async fn aborting_get_discards_incomplete_staging() {
tokio::time::timeout(CASE_TIMEOUT, async {
let dir = Scratch::new("abort");
let (listener, client, url) = fixture().await;
let download = dir.download(Some(4));
let (control, progress) = (download.control.clone(), download.progress.clone());
let task = tokio::spawn(download.run_with(client, url));
let (mut stream, _) = read_request(listener, "GET").await;
stream.get_mut().write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nhi").await.unwrap();
while progress.load(Ordering::Acquire) != 2 || dir.parts() != 1 { tokio::task::yield_now().await; }
assert!(control.cancel());
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
while dir.parts() != 0 { tokio::task::yield_now().await; }
assert!(!dir.0.join("download.bin").exists());
}).await.unwrap();
}
#[tokio::test]
async fn aborting_put_closes_connection_without_finishing_body() {
tokio::time::timeout(CASE_TIMEOUT, async {
let dir = Scratch::new("abort-put");
let (listener, client, url) = fixture().await;
let upload = dir.upload(b"not sent", false);
let rate = upload.rate.clone();
let progress = upload.progress.clone();
// Hold the pacing lock so no body can be yielded, even on a fast client.
let _pacing = rate.next.lock().await;
let task = tokio::spawn(upload.run_with(client, url));
let (mut stream, headers) = read_request(listener, "PUT").await;
assert_eq!(headers["content-length"], "8");
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
assert_eq!(stream.read(&mut [0u8; 1]).await.unwrap(), 0);
assert_eq!(progress.load(Ordering::Relaxed), 0);
}).await.unwrap();
}
}
+135 -40
View File
@@ -9,9 +9,12 @@ use std::sync::atomic::{AtomicU64, Ordering};
use futures::FutureExt;
use tsclientlib::{FileDownloadResult, FileUploadResult};
use crate::file_transfer::{self as ft, Direction, Ended, ListJob, Local, Partial, Request, Stage, Tombstone, Transfer};
use crate::file_transfer::{self as ft, Direction, Ended, ListBackend, ListJob, Local, Partial, Request, Stage, Tombstone, Transfer};
use crate::rawcmd::RawNotification;
#[path = "files_session/s3.rs"]
pub(super) mod s3;
/// Channel passwords travel hashed, like tsclientlib's own `download_file`/`upload_file`.
fn cpw(password: &str) -> String {
if password.is_empty() { String::new() } else { tsproto_types::crypto::encode_password(password.as_bytes()) }
@@ -29,8 +32,9 @@ fn ts_id(e: &tsclientlib::Error) -> Option<u32> {
}
/// Error of a failed transfer stream/status (`FiletransferFailed`).
fn stream_error(e: &tsclientlib::Error) -> ErrorObj {
fn stream_error(e: &tsclientlib::Error, name: &str) -> ErrorObj {
match e {
tsclientlib::Error::CommandError(ce) => init_error(ce, name),
tsclientlib::Error::FiletransferIo(_) => ErrorObj::new(ErrorCode::Io, e.to_string()),
_ => lib_error(ErrorCode::ServerError, e),
}
@@ -55,6 +59,15 @@ fn channel_known(c: &Conn, channel_id: u64) -> Result<(), ErrorObj> {
Ok(())
}
fn list_command(backend: ListBackend, channel_id: u64, path: &str, password: &str) -> OutCommand {
match backend {
ListBackend::Legacy => menu::command("ftgetfilelist", &[("cid", channel_id.to_string()), ("cpw", cpw(password)), ("path", path.into())]),
// Full clients send the same SHA-1/base64 channel password in chpw. S3 lists the entire
// channel; the requested browser directory is applied locally, never sent on the wire.
ListBackend::S3 => menu::command("s3ft_list_files", &[("chid", channel_id.to_string()), ("chpw", cpw(password))]),
}
}
/// `ftstop` for a granted transfer. An aborted upload's partial file is deleted on the server; a
/// paused one (`keep`, official haltTransfer without deleteUnfinishedFile) is kept for resume.
/// Cancelling a transfer that is already paused sends nothing, like the official
@@ -81,6 +94,9 @@ fn release(c: &mut Conn, ftid: u16, server_ftid: Option<u16>, direction: Directi
/// Remove a transfer that will not complete. Dropping the record aborts its I/O.
fn retire(c: &mut Conn, t: Transfer) {
if let Stage::S3Init { handle, .. } | Stage::S3Confirming { handle, .. } = t.stage {
c.s3_receipts.remove(&handle);
}
if let Some(ftid) = t.ftid() {
release(c, ftid, t.server_ftid, t.direction, false);
}
@@ -119,6 +135,18 @@ fn halt(c: &mut Conn, i: usize) -> Option<Value> {
/// doFileDownload/doFileUpload with resume: download `seekpos` = kept bytes, upload `resume=1`
/// without overwrite). On a send failure the transfer is removed and its `failed` event returned.
fn start(c: &mut Conn, i: usize, resume: bool) -> Result<Value, (Value, ErrorObj)> {
let t = &c.files.transfers[i];
match c.files.list_backend(t.channel_id) {
Ok(backend) if backend == t.backend => {}
Ok(_) => {
let e = ErrorObj::new(ErrorCode::MediaUnsupported, "file storage changed while the transfer was queued");
return Err((c.files.transfers.remove(i).event("failed", Some(&e)), e));
}
Err(e) => return Err((c.files.transfers.remove(i).event("failed", Some(&e)), e)),
}
if t.backend == ListBackend::S3 {
return s3::start(c, i);
}
let ftid = c.transfer_id();
let t = &c.files.transfers[i];
let resume_at = t.resume_args(resume);
@@ -187,7 +215,7 @@ fn init_command(direction: Direction, ftid: u16, channel_id: u64, path: &str, ha
impl Session {
pub(super) async fn files_request(&mut self, id: &str, request: Request) -> Result<Option<Value>, ErrorObj> {
if !matches!(&request, Request::Cancel { .. } | Request::Pause { .. } | Request::Resume { .. } | Request::Transfers | Request::Config { .. }) {
if matches!(&request, Request::Mkdir { .. } | Request::Rename { .. } | Request::Delete { .. } | Request::FetchImage { .. }) {
self.connected_conn()?.files.require_legacy()?;
}
match request {
@@ -197,8 +225,8 @@ impl Session {
c.files.slots = Some([download_slots, upload_slots]);
c.files.download_rate.set(download_limit);
c.files.upload_rate.set(upload_limit);
// Official updateConcurrentTransferLimits: a changed limit pauses each channel's
// excess in-progress transfers; they wait for an explicit resume.
// Legacy transfers pause when their slots are removed. S3 transfers cannot resume;
// they drain before the queue starts any more above the new limit.
let mut events = Vec::new();
if changed {
for transfer_id in c.files.over_limit() {
@@ -216,6 +244,9 @@ impl Session {
let c = self.connected_conn()?;
let i = c.files.index_of_id(transfer_id).ok_or_else(|| not_active(transfer_id))?;
let t = &c.files.transfers[i];
if t.backend == ListBackend::S3 {
return Err(ErrorObj::new(ErrorCode::MediaUnsupported, "S3 file transfers cannot be paused"));
}
if t.channel_id == 0 {
return Err(menu::bad("server icon transfers cannot be paused"));
}
@@ -230,23 +261,14 @@ impl Session {
Request::Resume { transfer_id } => self.files_resume(transfer_id).await,
Request::List { channel_id, path, password } => {
let c = self.connected_conn()?;
let backend = c.files.list_backend(channel_id)?;
if channel_id != 0 { channel_known(c, channel_id)?; }
if c.files.list_pending(channel_id, &path) {
return Err(menu::bad("a listing of this folder is already pending"));
}
let cmd = menu::command("ftgetfilelist", &[("cid", channel_id.to_string()), ("cpw", cpw(&password)), ("path", path.clone())]);
let cmd = list_command(backend, channel_id, &path, &password);
let handle = c.send(cmd).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.files.lists.insert(handle, ListJob {
req: id.into(),
channel_id,
path,
entries: Vec::new(),
malformed: 0,
overflow: false,
finished: false,
result_ok: false,
started: Instant::now(),
});
c.files.lists.insert(handle, ListJob::new(id, channel_id, path, backend));
Ok(None)
}
Request::Mkdir { channel_id, path, password } => {
@@ -269,16 +291,16 @@ impl Session {
self.files_simple(id, channel_id, cmd)
}
Request::Download { channel_id, password, path, dest_dir, subdirs, overwrite } => {
if channel_id != 0 { self.connected_conn().and_then(|c| channel_known(c, channel_id))?; }
let backend = self.files_transfer_backend(channel_id)?;
let name = ft::file_name(&path).to_owned();
let checked = name.clone();
let dir = tokio::task::spawn_blocking(move || ft::prepare_download(&dest_dir, &subdirs, &checked, overwrite))
.await
.map_err(internal)??;
self.files_enqueue(Direction::Download, channel_id, path, &password, overwrite, Local::Download { dir, name, overwrite, partial: None }, 0)
self.files_enqueue(backend, Direction::Download, channel_id, path, &password, overwrite, Local::Download { dir, name, overwrite, partial: None }, 0)
}
Request::Upload { channel_id, password, path, source, overwrite } => {
if channel_id != 0 { self.connected_conn().and_then(|c| channel_known(c, channel_id))?; }
let backend = self.files_transfer_backend(channel_id)?;
let (file, size, modified) = tokio::task::spawn_blocking(move || {
ft::prepare_upload(&source).map(|(file, size)| {
let modified = file.metadata().ok().and_then(|m| m.modified().ok());
@@ -287,7 +309,7 @@ impl Session {
})
.await
.map_err(internal)??;
self.files_enqueue(Direction::Upload, channel_id, path, &password, overwrite, Local::Upload { file: Some(file), size, modified }, size)
self.files_enqueue(backend, Direction::Upload, channel_id, path, &password, overwrite, Local::Upload { file: Some(file), size, modified }, size)
}
Request::Cancel { transfer_id } => self.files_cancel(transfer_id).await,
Request::FetchImage { channel_id, path } => {
@@ -302,6 +324,13 @@ impl Session {
}
}
fn files_transfer_backend(&mut self, channel_id: u64) -> Result<ListBackend, ErrorObj> {
let c = self.connected_conn()?;
let backend = c.files.list_backend(channel_id)?;
if channel_id != 0 { channel_known(c, channel_id)?; }
Ok(backend)
}
fn files_simple(&mut self, id: &str, channel_id: u64, cmd: OutCommand) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
// Channel 0 (server icons) is not a tree channel; the parser admitted only icon paths for it.
@@ -315,6 +344,7 @@ impl Session {
#[allow(clippy::too_many_arguments)]
fn files_enqueue(
&mut self,
backend: ListBackend,
direction: Direction,
channel_id: u64,
path: String,
@@ -331,6 +361,7 @@ impl Session {
let now = Instant::now();
let t = Transfer {
id,
backend,
direction,
channel_id,
path,
@@ -338,6 +369,7 @@ impl Session {
overwrite,
local,
total,
s3_total: None,
stage: Stage::Queued,
server_ftid: None,
confirmed: false,
@@ -363,10 +395,13 @@ impl Session {
.files
.index_of_id(transfer_id)
.ok_or_else(|| not_active(transfer_id))?;
if matches!(c.files.transfers[i].stage, Stage::Confirming { .. }) {
let t = &c.files.transfers[i];
if matches!(t.stage, Stage::Confirming { .. } | Stage::S3Confirming { .. })
|| t.direction == Direction::Upload && matches!(&t.stage, Stage::S3Running { task } if task.is_finished())
{
return Err(menu::bad("the upload is complete and awaiting the server's confirmation"));
}
if !c.files.transfers[i].commit.cancel() {
if !t.commit.cancel() {
return Err(menu::bad("the download is being committed and can no longer be cancelled"));
}
let t = c.files.transfers.remove(i);
@@ -382,6 +417,9 @@ impl Session {
let c = self.connected_conn()?;
let i = c.files.index_of_id(transfer_id).ok_or_else(|| not_active(transfer_id))?;
let t = &c.files.transfers[i];
if t.backend == ListBackend::S3 {
return Err(ErrorObj::new(ErrorCode::MediaUnsupported, "S3 file transfers cannot be resumed or force-started"));
}
if t.channel_id == 0 {
return Err(menu::bad("server icon transfers cannot be resumed"));
}
@@ -441,8 +479,10 @@ impl Session {
.and_then(|b| b.channels.get(&ChannelId(job.channel_id)))
.and_then(|ch| ch.permission_hints)
.map(|h| h.bits());
let s3 = job.backend() == ListBackend::S3;
let storage = c.files.storage();
let req = job.req.clone();
match ft::list_result(job, ft::capabilities(hints), c.files.storage()) {
match ft::list_result(job, ft::capabilities(hints, s3), storage) {
Ok(v) => self.out.ok(&req, v).await,
Err(e) => self.out.err(&req, e).await,
}
@@ -450,21 +490,27 @@ impl Session {
pub(super) async fn files_result(&mut self, handle: u16, res: Result<(), CommandError>) {
let Some(c) = &mut self.conn else { return };
if c.s3_receipts.contains_key(&handle) {
if let Some(event) = s3::acknowledge(c, handle, res) {
self.out.json(&event).await;
}
return;
}
if let Some(job) = c.files.lists.get_mut(&handle) {
match res {
Ok(()) => job.result_ok = true,
// An empty folder is answered with "database empty result set" and no rows.
Err(e) if e.error.to_u32() == Some(ft::TS_DATABASE_EMPTY_RESULT) => {
job.result_ok = true;
job.finished = true;
let ready = match res {
Ok(()) => job.acknowledge(),
// Only the legacy protocol uses "database empty result set" for an empty folder.
Err(e) if job.backend() == ListBackend::Legacy && e.error.to_u32() == Some(ft::TS_DATABASE_EMPTY_RESULT) => {
job.finish_legacy();
job.acknowledge()
}
Err(e) => {
let req = c.files.lists.remove(&handle).expect("present").req;
self.out.err(&req, command_error(&e)).await;
return;
}
}
if job.finished {
};
if ready {
self.files_answer_list(handle).await;
}
return;
@@ -496,6 +542,13 @@ impl Session {
}
}
pub(super) async fn files_s3_transfer(&mut self, reply: crate::rawcmd::S3TransferReply<'_>) {
let Some(c) = &mut self.conn else { return };
if let Some(event) = s3::notification(c, reply) {
self.out.json(&event).await;
}
}
pub(super) async fn files_raw(&mut self, raw: &RawNotification) {
let Some(c) = &mut self.conn else { return };
for handle in c.files.apply_raw(raw) {
@@ -503,6 +556,13 @@ impl Session {
}
}
pub(super) async fn files_s3_list(&mut self, reply: crate::rawcmd::S3FileList<'_>) {
let Some(c) = &mut self.conn else { return };
if let Some(handle) = c.files.apply_s3_list(reply) {
self.files_answer_list(handle).await;
}
}
pub(super) async fn files_download(&mut self, ftid: u16, result: FileDownloadResult) -> Option<FileDownloadResult> {
let Some(c) = &mut self.conn else { return Some(result) };
if let Some(tomb) = c.files.tombstones.remove(&ftid) {
@@ -646,7 +706,7 @@ impl Session {
return None;
}
let t = c.files.transfers.remove(i);
let event = t.event("failed", Some(&stream_error(&err)));
let event = t.event("failed", Some(&stream_error(&err, ft::file_name(&t.path))));
drop(t);
self.out.json(&event).await;
None
@@ -655,19 +715,19 @@ impl Session {
/// Answer every file request and fail every transfer of the current connection.
pub(super) async fn files_fail_all(&mut self, why: &str) {
let Some(c) = &mut self.conn else { return };
c.s3_receipts.clear();
let f = &mut c.files;
let reqs: Vec<String> = f.lists.drain().map(|(_, j)| j.req).chain(f.simple.drain().map(|(_, r)| r)).collect();
f.inits.clear();
f.stops.clear();
f.tombstones.clear();
let transfers: Vec<Transfer> = f.transfers.drain(..).collect();
let err = ErrorObj::new(ErrorCode::NotConnected, why);
// Abort every task before an output write can await, including tasks with a retained URL.
let events: Vec<Value> = f.transfers.drain(..).map(|t| t.event("failed", Some(&err))).collect();
for req in reqs {
self.out.err(&req, err.clone()).await;
}
for t in transfers {
let event = t.event("failed", Some(&err));
drop(t);
for event in events {
self.out.json(&event).await;
}
}
@@ -697,10 +757,16 @@ impl Session {
Stage::Running { task, .. } | Stage::Pausing { task, .. } if task.is_finished() => {
Some((&mut *task).now_or_never().expect("finished").unwrap_or_else(|e| Err(internal(e))))
}
Stage::S3Running { task } if task.is_finished() => {
Some((&mut *task).now_or_never().expect("finished").unwrap_or_else(|_| {
Err(ErrorObj::new(ErrorCode::Internal, "S3 transfer task failed"))
}))
}
_ => None,
};
enum Outcome {
Done,
ConfirmS3Upload,
Failed(ErrorObj),
/// Halted (`None`) or broken (`Some`) stream with its kept partial.
Stopped(Option<Partial>, Option<ErrorObj>),
@@ -708,6 +774,12 @@ impl Session {
}
let outcome = match finished {
Some(Err(e)) => Outcome::Failed(e),
Some(Ok(Ended::Complete { .. })) if t.backend == ListBackend::S3 => {
if t.direction == Direction::Upload { Outcome::ConfirmS3Upload } else { Outcome::Done }
}
Some(Ok(Ended::Paused(_) | Ended::Lost { .. })) if t.backend == ListBackend::S3 => {
Outcome::Failed(ErrorObj::new(ErrorCode::Io, "S3 file transfer ended before it completed"))
}
Some(Ok(Ended::Paused(partial))) => Outcome::Stopped(partial, None),
Some(Ok(Ended::Lost { error, partial })) => Outcome::Stopped(partial, Some(error)),
Some(Ok(Ended::Complete { closed })) if t.direction == Direction::Download || closed || t.confirmed => Outcome::Done,
@@ -720,6 +792,12 @@ impl Session {
Stage::Init { since, .. } if now - *since >= ft::GRANT_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not start the file transfer"))
}
Stage::S3Init { since, .. } if now - *since >= ft::GRANT_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not grant the S3 file transfer"))
}
Stage::S3Confirming { since, .. } if now - *since >= ft::CONFIRM_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not confirm the S3 upload"))
}
Stage::Running { .. } if now - t.last_change >= ft::STALL_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::Io, "file transfer stalled"))
}
@@ -738,13 +816,21 @@ impl Session {
match outcome {
Outcome::Done => {
let t = c.files.transfers.remove(i);
t.progress.store(t.total, Ordering::Relaxed);
if t.backend == ListBackend::Legacy { t.progress.store(t.total, Ordering::Relaxed); }
events.push(t.event("done", None));
}
Outcome::ConfirmS3Upload => match s3::confirm_upload(c, i, now) {
Ok(event) => {
events.push(event);
i += 1;
}
Err(e) => events.push(c.files.transfers.remove(i).event("failed", Some(&e))),
},
Outcome::Failed(e) => {
let t = c.files.transfers.remove(i);
events.push(t.event("failed", Some(&e)));
let ended = !matches!(t.stage, Stage::Running { .. } | Stage::Pausing { .. } | Stage::Init { .. } | Stage::Lost { .. });
let ended = !matches!(t.stage, Stage::Running { .. } | Stage::Pausing { .. } | Stage::Init { .. } | Stage::Lost { .. }
| Stage::S3Init { .. } | Stage::S3Confirming { .. });
if ended {
drop(t);
} else {
@@ -776,7 +862,7 @@ impl Session {
}
Outcome::Keep => {
let t = &mut c.files.transfers[i];
if matches!(t.stage, Stage::Running { .. }) && bytes != t.reported && now - t.last_emit >= ft::PROGRESS_INTERVAL {
if matches!(t.stage, Stage::Running { .. } | Stage::S3Running { .. }) && bytes != t.reported && now - t.last_emit >= ft::PROGRESS_INTERVAL {
t.reported = bytes;
t.last_emit = now;
events.push(t.event("running", None));
@@ -802,6 +888,15 @@ mod tests {
fn content(cmd: OutCommand) -> String { String::from_utf8(cmd.into_packet().content().to_vec()).unwrap() }
#[test]
fn s3_list_uses_channel_password_hash_and_sends_no_path() {
assert_eq!(content(list_command(ListBackend::S3, 9, "/some/folder/", "")), "s3ft_list_files chid=9 chpw");
assert_eq!(
content(list_command(ListBackend::S3, 9, "/", "abc")),
"s3ft_list_files chid=9 chpw=qZk+NkcGgWq6PiVxeFDCbJzQ2J0="
);
}
#[test]
fn server_icons_use_classic_wire_names_and_channels_stay_unchanged() {
let icon = "/icons/icon_3558086607".to_owned();
+207
View File
@@ -0,0 +1,207 @@
use super::*;
use crate::file_transfer::s3_http::{Download, SignedUrl, Upload};
use crate::rawcmd::{S3TransferKind, S3TransferReply};
use tsproto_packets::packets::{Direction as WireDirection, Flags, PacketType};
/// Both the successful command ACK and the exact object grant are required, in either order.
#[derive(Default)]
struct GrantReceipt {
acked: bool,
grant: Option<Result<SignedUrl, ErrorObj>>,
}
impl GrantReceipt {
fn ready(&self) -> bool { self.acked && self.grant.is_some() }
}
enum Awaiting {
Grant(GrantReceipt),
/// This notification is the business result; the server sends no successful ACK after it.
UploadDone,
}
pub(in crate::session) struct Receipt {
transfer_id: u32,
awaiting: Awaiting,
}
fn channel_command(name: &str, channel_id: u64, password: &str) -> OutCommand {
let mut cmd = OutCommand::new(WireDirection::C2S, Flags::empty(), PacketType::Command, name);
cmd.write_arg("chid", &channel_id);
cmd.write_arg("chpw", &password);
cmd
}
fn presign_command(direction: Direction, channel_id: u64, path: &str, hashed_password: &str, total: u64) -> OutCommand {
let mut cmd = channel_command("s3ft_getpresignedurl", channel_id, hashed_password);
// The channel/password header and the object request must be separate rows. The command
// sender appends return_code to the last row, as on the normal TS6 wire.
cmd.start_new_part();
cmd.write_arg("key", &path);
let (verb, length) = match direction {
Direction::Download => ("GET", 0),
Direction::Upload => ("PUT", total),
};
cmd.write_arg("verb", &verb);
cmd.write_arg("length", &length);
cmd
}
fn send(c: &mut Conn, cmd: OutCommand) -> Result<u16, ErrorObj> {
// Never relay raw packet errors from this path; fixed errors also keep passwords private.
c.send(cmd).map_err(|_| ErrorObj::new(ErrorCode::NotConnected, "could not send the S3 file command"))
}
pub(super) fn start(c: &mut Conn, i: usize) -> Result<Value, (Value, ErrorObj)> {
let t = &c.files.transfers[i];
let transfer_id = t.id;
let cmd = presign_command(t.direction, t.channel_id, &t.path, &t.cpw, t.total);
match send(c, cmd) {
Ok(handle) => {
c.s3_receipts.insert(handle, Receipt { transfer_id, awaiting: Awaiting::Grant(GrantReceipt::default()) });
c.files.start_seq += 1;
let t = &mut c.files.transfers[i];
t.started = c.files.start_seq;
t.stage = Stage::S3Init { handle, since: Instant::now() };
Ok(t.event("starting", None))
}
Err(e) => Err((c.files.transfers.remove(i).event("failed", Some(&e)), e)),
}
}
pub(super) fn confirm_upload(c: &mut Conn, i: usize, now: Instant) -> Result<Value, ErrorObj> {
let t = &c.files.transfers[i];
let transfer_id = t.id;
let cmd = channel_command("s3ft_upload_done_notification", t.channel_id, &t.cpw);
let handle = send(c, cmd)?;
c.s3_receipts.insert(handle, Receipt { transfer_id, awaiting: Awaiting::UploadDone });
let t = &mut c.files.transfers[i];
t.stage = Stage::S3Confirming { handle, since: now };
Ok(t.event("confirming", None))
}
fn failed(c: &mut Conn, i: usize, error: ErrorObj) -> Value {
c.files.transfers.remove(i).event("failed", Some(&error))
}
fn server_error(message: &'static str) -> ErrorObj { ErrorObj::new(ErrorCode::ServerError, message) }
fn apply_grant(c: &mut Conn, handle: u16, i: usize) -> Option<Value> {
let receipt = c.s3_receipts.remove(&handle)?;
let Awaiting::Grant(GrantReceipt { grant: Some(grant), .. }) = receipt.awaiting else { return None };
let url = match grant {
Ok(url) => url,
Err(e) => return Some(failed(c, i, e)),
};
let t = &mut c.files.transfers[i];
let task = match &mut t.local {
Local::Download { dir, name, overwrite, partial: None } => {
let total = Arc::new(AtomicU64::new(0));
t.s3_total = Some(total.clone());
tokio::spawn(Download {
id: t.id,
dir: std::mem::take(dir),
name: std::mem::take(name),
overwrite: *overwrite,
expected_size: None,
total,
progress: t.progress.clone(),
control: t.commit.clone(),
rate: c.files.download_rate.clone(),
}.run(url))
}
Local::Upload { file, size, modified } => {
let Some(file) = file.take() else {
return Some(failed(c, i, ErrorObj::new(ErrorCode::Internal, "S3 upload source is not open")));
};
tokio::spawn(Upload {
file,
size: *size,
modified: *modified,
overwrite: t.overwrite,
progress: t.progress.clone(),
rate: c.files.upload_rate.clone(),
}.run(url))
}
Local::Download { .. } => {
return Some(failed(c, i, ErrorObj::new(ErrorCode::Internal, "S3 downloads do not resume partial data")));
}
};
t.stage = Stage::S3Running { task };
Some(t.event("running", None))
}
pub(super) fn acknowledge(c: &mut Conn, handle: u16, result: Result<(), CommandError>) -> Option<Value> {
let receipt = c.s3_receipts.get_mut(&handle)?;
let i = c.files.index_of_id(receipt.transfer_id)?;
match result {
Err(e) => {
let error = match receipt.awaiting {
Awaiting::Grant(_) => init_error(&e, ft::file_name(&c.files.transfers[i].path)),
Awaiting::UploadDone => command_error(&e),
};
c.s3_receipts.remove(&handle);
Some(failed(c, i, error))
}
Ok(()) => {
if let Awaiting::Grant(grant) = &mut receipt.awaiting {
grant.acked = true;
if grant.ready() { return apply_grant(c, handle, i); }
}
None
}
}
}
pub(super) fn notification(c: &mut Conn, reply: S3TransferReply<'_>) -> Option<Value> {
let handle = reply.handle?;
let receipt = c.s3_receipts.get_mut(&handle)?;
let i = c.files.index_of_id(receipt.transfer_id)?;
match (&mut receipt.awaiting, reply.kind) {
(Awaiting::Grant(grant), S3TransferKind::Presign) if grant.grant.is_none() => {
let t = &c.files.transfers[i];
grant.grant = Some(reply.presigned_url(&t.path).map_err(server_error).and_then(|arg| {
let url = arg.get_str().map_err(|_| server_error("server returned an invalid S3 file grant"))?;
SignedUrl::parse(&url)
}));
if grant.ready() { return apply_grant(c, handle, i); }
None
}
(Awaiting::UploadDone, S3TransferKind::UploadDone) => {
c.s3_receipts.remove(&handle);
match reply.upload_success() {
Ok(true) => Some(c.files.transfers.remove(i).event("done", None)),
Ok(false) => Some(failed(c, i, server_error("server could not refresh the S3 file list after upload"))),
Err(message) => Some(failed(c, i, server_error(message))),
}
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn presign_keeps_channel_header_and_object_on_separate_rows() {
let get = presign_command(Direction::Download, 3, "/nested/a b", "", 987).into_packet();
assert_eq!(get.content(), br"s3ft_getpresignedurl chid=3 chpw|key=\/nested\/a\sb verb=GET length=0");
let put = presign_command(Direction::Upload, 3, "/nested/a b", &cpw("abc"), 987).into_packet();
assert_eq!(put.content(), br"s3ft_getpresignedurl chid=3 chpw=qZk+NkcGgWq6PiVxeFDCbJzQ2J0=|key=\/nested\/a\sb verb=PUT length=987");
let done = channel_command("s3ft_upload_done_notification", 3, "").into_packet();
assert_eq!(done.content(), b"s3ft_upload_done_notification chid=3 chpw");
}
#[test]
fn missing_either_part_does_not_settle_a_presign() {
let mut receipt = GrantReceipt::default();
assert!(!receipt.ready());
receipt.acked = true;
assert!(!receipt.ready());
receipt.grant = Some(Err(server_error("test failure")));
assert!(receipt.ready());
receipt.acked = false;
assert!(!receipt.ready());
}
}
+3 -3
View File
@@ -75,7 +75,7 @@ impl BindResult {
enum Event {
Bound { seq: u32, results: Vec<BindResult> },
Rebound { results: Vec<BindResult> },
Rebound { seq: u32, results: Vec<BindResult> },
Key { id: String, down: bool },
}
@@ -125,10 +125,10 @@ impl State {
self.registered.extend(results.iter().filter(|r| r.ok).map(|r| (r.id.clone(), false)));
out(serde_json::json!({ "event": "bound", "seq": seq, "results": results }))?;
}
Event::Rebound { results } => {
Event::Rebound { seq, results } => {
self.release_all(out)?;
self.registered.extend(results.iter().filter(|r| r.ok).map(|r| (r.id.clone(), false)));
out(serde_json::json!({ "event": "rebound", "results": results }))?;
out(serde_json::json!({ "event": "rebound", "seq": seq, "results": results }))?;
}
}
Ok(())
+1 -1
View File
@@ -231,7 +231,7 @@ impl Backend for Portal {
let trigger = properties.get("trigger_description").and_then(|v| v.0.as_str()).unwrap_or("").chars().take(128).collect();
(id, trigger)
}).collect();
events.push(Event::Rebound { results: self.results(&granted, true) });
events.push(Event::Rebound { seq: self.seq, results: self.results(&granted, true) });
}
}
}
+30 -8
View File
@@ -59,6 +59,11 @@ impl Action {
}}
}
pub fn bad(message: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest,message) }
pub const MAX_POKE_BYTES: usize = 1024;
pub const MAX_MOVE_PASSWORD_BYTES: usize = 1024;
pub fn valid_poke_message(message: &str) -> bool {
(1..=MAX_POKE_BYTES).contains(&message.len()) && !message.bytes().any(|byte| byte.is_ascii_control())
}
pub fn validate_target(t: &Target) -> Result<(), ErrorObj> {
if t.client_id == 0 || t.uid.is_empty() || t.uid.len()>128 || t.uid.chars().any(char::is_control) { return Err(bad("invalid client target")); }
Ok(())
@@ -74,16 +79,16 @@ pub fn parse_action(mut value: Value) -> Result<ActionRequest, ErrorObj> {
pub(crate) fn validate_action(request: &ActionRequest) -> Result<(), ErrorObj> {
validate_target(&request.target)?;
if request.generation == 0 { return Err(bad("generation is required")); }
crate::admin::generation(request.generation)?;
match &request.action {
Action::Poke{message} if message.is_empty() || message.len()>1024 || message.chars().any(char::is_control) =>return Err(bad("poke message must be 1..1024 bytes without controls")),
Action::Poke{message} if !valid_poke_message(message) =>return Err(bad("poke message must be 1..1024 UTF-8 bytes without ASCII controls")),
Action::KickChannel{reason}|Action::KickServer{reason}|Action::Ban{reason,..} if reason.len()>1024 || reason.chars().any(char::is_control)=>return Err(bad("reason must be at most 1024 bytes without controls")),
Action::Volume{db,..} if !crate::voice_dsp::valid_modifier_db(*db)=>return Err(bad("volume must be -200..10 dB in 0.5 dB steps")),
Action::ServerGroup{group_id,..}|Action::ChannelGroup{group_id,..} if *group_id==0=>return Err(bad("group_id must be positive")),
Action::ChannelGroup{channel_id,..}|Action::ChannelPermissions{channel_id}|Action::SetChannelPermission{channel_id,..} if *channel_id==0=>return Err(bad("channel_id must be positive")),
Action::SetClientPermission{permission_id,..}|Action::SetChannelPermission{permission_id,..} if *permission_id==0=>return Err(bad("permission_id must be positive")),
Action::MoveToOwnChannel{expected_channel_id:0,..}=>return Err(bad("expected_channel_id must be positive")),
Action::MoveToOwnChannel{password:Some(p),..} if p.len()>1024 || p.chars().any(char::is_control)=>return Err(bad("invalid channel password")),
Action::MoveToOwnChannel{expected_channel_id,..} if !(1..=crate::admin::MAX_SAFE_INTEGER).contains(expected_channel_id)=>return Err(bad("expected_channel_id must be a positive safe integer")),
Action::MoveToOwnChannel{password:Some(p),..} if p.len()>MAX_MOVE_PASSWORD_BYTES || p.chars().any(char::is_control)=>return Err(bad("invalid channel password")),
Action::Avatar{data}=>{avatar_bytes(data)?;},
_=>{},
}
@@ -190,7 +195,7 @@ fn cap(allowed:Option<bool>,source:&str)->Value {json!({"allowed":allowed,"reaso
pub fn tapped(name:&[u8])->bool{matches!(name,b"notifypermissionlist"|b"notifyclientneededpermissions"|b"notifyconnectioninfo"|b"notifyclientpermlist"|b"notifychannelclientpermlist")}
fn validate_live_identity(target:&Target,client_id:u16,uid:Option<&tsclientlib::UidBuf>)->Result<(),ErrorObj>{
if target.client_id!=client_id || uid.is_none_or(|uid|uid.to_string()!=target.uid){return Err(bad("client identity changed; reopen the menu"));}
if target.client_id!=client_id || uid.is_none_or(|uid|uid.to_string()!=target.uid){return Err(ErrorObj::new(ErrorCode::TargetChanged,"client identity changed; reopen the menu"));}
Ok(())
}
fn target_hint(own:bool,key:&str,hints:Option<u64>,bit:u64)->Value {
@@ -208,6 +213,13 @@ pub fn response_matches(row:&Row,response:&str,client_id:u16,dbid:u64,channel:Op
}
}
pub(crate) fn finish_read(target:&Target, current_uid:Option<&str>, response:&str, rows:Vec<Row>)->Result<Value,ErrorObj>{
if current_uid!=Some(target.uid.as_str()){return Err(ErrorObj::new(ErrorCode::TargetChanged,"client identity changed; reopen the menu"));}
if rows.len()>4096{return Err(ErrorObj::new(ErrorCode::ServerError,"server returned too many client data rows; result not complete"));}
if response=="notifyconnectioninfo" && rows.is_empty(){return Err(ErrorObj::new(ErrorCode::ServerError,"server returned no connection statistics for the requested client"));}
Ok(json!({"rows":rows}))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -248,6 +260,16 @@ mod tests {
assert!(!response_matches(&row,"notifychannelclientpermlist",2,8,Some(4)));
assert!(!response_matches(&row,"notifyconnectioninfo",2,8,None));
}
#[test] fn connection_statistics_require_a_current_uid_and_reported_rows(){
let target=Target{client_id:2,uid:"speaker=".into()};
let rows=||crate::rawcmd::parse(b"notifyconnectioninfo clid=2 connection_ping=7.25").unwrap().items;
for uid in [None,Some("replacement=")] {
assert_eq!(finish_read(&target,uid,"notifyconnectioninfo",rows()).unwrap_err().code,ErrorCode::TargetChanged);
}
assert_eq!(finish_read(&target,Some("speaker="),"notifyconnectioninfo",vec![]).unwrap_err().code,ErrorCode::ServerError);
assert_eq!(finish_read(&target,Some("speaker="),"notifyconnectioninfo",rows()).unwrap()["rows"][0]["connection_ping"],"7.25");
assert_eq!(finish_read(&target,Some("speaker="),"notifyclientpermlist",vec![]).unwrap(),json!({"rows":[]}));
}
#[test] fn all_mutation_fixtures_build_expected_wire_verbs(){
for (action,verb) in [
(Action::Poke{message:"hi".into()},"clientpoke"),
@@ -284,9 +306,9 @@ mod tests {
let first=tsclientlib::UidBuf(vec![1;20]); let second=tsclientlib::UidBuf(vec![2;20]);
let target=Target{client_id:42,uid:first.to_string()};
assert!(validate_live_identity(&target,42,Some(&first)).is_ok());
assert!(validate_live_identity(&target,42,Some(&second)).is_err());
assert!(validate_live_identity(&target,43,Some(&first)).is_err());
assert!(validate_live_identity(&target,42,None).is_err());
for (id,uid) in [(42,Some(&second)),(43,Some(&first)),(42,None)] {
assert_eq!(validate_live_identity(&target,id,uid).unwrap_err().code,ErrorCode::TargetChanged);
}
let mut persisted=HashMap::new(); persisted.insert(second.0.clone(),-6.0);
let mut volumes=LocalVolumes::default(); volumes.set(&first.0,-8.0,true);
assert_eq!(volumes.get(&first.0,&persisted),(-8.0,true)); assert_eq!(volumes.gain(&first.0,&persisted),0.0);
+2 -2
View File
@@ -13,7 +13,7 @@ impl Session {
pub(super) async fn client_action(&mut self, id: &str, request: ActionRequest) -> Result<Option<Value>, ErrorObj> {
let c=self.connected_conn()?;
if request.generation!=c.generation{return Err(menu::bad("connection changed; reopen the menu"));}
if request.generation!=c.generation{return Err(ErrorObj::new(ErrorCode::TargetChanged,"connection changed; reopen the menu"));}
let book=c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e))?;
let context=c.permissions.context(book,&request.target,c.generation)?;
let key=request.action.key();
@@ -45,7 +45,7 @@ impl Session {
MenuAction::Avatar{data}=>{
if c.avatar.is_some(){return Err(menu::bad("an avatar upload is already pending"));}
let data=menu::avatar_bytes(data)?;
let hash=format!("{:x}",Md5::digest(&data));
let hash=base16ct::lower::encode_string(&Md5::digest(&data));
let ftid=c.transfer_id();
let command=menu::command("ftinitupload",&[("clientftfid",ftid.to_string()),("name","/avatar".into()),("cid","0".into()),("cpw",String::new()),("size",data.len().to_string()),("overwrite","1".into()),("resume","0".into()),("proto","1".into())]);
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
+12 -1
View File
@@ -84,7 +84,8 @@ impl Out {
pub fn set_generation(&self, generation: u64) { self.inner.generation.store(generation, Ordering::Release); }
pub async fn control(&self, mut value: Value) {
if let Some(object) = value.as_object_mut().filter(|o| o.contains_key("event")) {
object.insert("generation".into(), Value::from(self.inner.generation.load(Ordering::Acquire)));
object.entry("generation".to_owned())
.or_insert_with(|| Value::from(self.inner.generation.load(Ordering::Acquire)));
}
let _ = self.inner.control.send(value).await;
}
@@ -122,6 +123,16 @@ impl Out {
mod tests {
use super::*;
#[tokio::test(flavor = "current_thread")]
async fn control_preserves_an_explicit_event_generation() {
let (out, mut control, _playback) = Out::new();
out.set_generation(8);
out.control(json!({"event":"whisper_received","generation":7})).await;
out.control(json!({"event":"talking"})).await;
assert_eq!(control.try_recv().unwrap()["generation"], 7);
assert_eq!(control.try_recv().unwrap()["generation"], 8);
}
#[tokio::test(flavor = "current_thread")]
async fn playback_discards_oldest_without_relabeling_reconnected_frames() {
let (out, _control, mut playback) = Out::new();
+28 -3
View File
@@ -874,9 +874,6 @@ impl Store {
}
other => other?,
};
if vault.entries.len() + parsed.len() > MAX_IDENTITIES {
return Err(StoreError::BadRequest(format!("at most {MAX_IDENTITIES} identities")));
}
let mut outcome = ImportOutcome { imported: Vec::new(), existing: Vec::new() };
let mut legacy_raised = None;
for p in parsed {
@@ -893,6 +890,9 @@ impl Store {
}
continue;
}
if vault.entries.len() >= MAX_IDENTITIES {
return Err(StoreError::BadRequest(format!("at most {MAX_IDENTITIES} identities")));
}
if vault.entries.is_empty() {
vault.default = p.uid.clone();
}
@@ -1419,6 +1419,31 @@ pub mod tests {
assert_eq!(store.load_identity().unwrap().unwrap().identity.counter(), high.counter());
}
#[test]
fn import_capacity_counts_new_uids_only_and_refuses_overflow_atomically() {
let dir = TempDir::new("import-capacity");
let store = Store::new(&dir.0);
let mut vault = Vault::empty();
for _ in 1..MAX_IDENTITIES {
vault.entries.push(Store::new_entry(Identity::new(EccKeyPrivP256::create(), 0), "Member".into(), String::new()));
}
vault.default = vault.entries[0].uid.clone();
{ let _guard = store.write_lock().unwrap(); store.write_vault(&vault).unwrap(); }
let existing = store.export_ini(&vault.default).unwrap();
let fresh = || format!("[Identity]\nid=New\nidentity=\"0V{}\"\n", EccKeyPrivP256::create().to_ts());
let last = fresh();
let before = snapshot(&dir.0);
assert!(matches!(store.import_ini(&[&existing, &last, &fresh()]), Err(StoreError::BadRequest(_))));
assert_eq!(snapshot(&dir.0), before);
let result = store.import_ini(&[&existing, &last, &last]).unwrap();
assert_eq!(result.existing, [vault.default.clone()]);
assert_eq!(result.imported.len(), 1);
assert_eq!(store.import_ini(&[&last]).unwrap().existing, result.imported);
let saved = store.list().unwrap();
assert_eq!(saved.identities.len(), MAX_IDENTITIES);
assert_eq!(saved.default_id.as_deref(), Some(vault.default.as_str()));
}
#[test]
fn ts_ini_export_import_roundtrip_and_no_key_duplicates() {
let a = TempDir::new("export");
+213 -34
View File
@@ -104,6 +104,10 @@ impl ErrorObj {
fn bad(msg: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, msg) }
fn check_identity_id(uid: &str) -> Result<(), ErrorObj> {
if crate::profile::valid_uid(uid) { Ok(()) } else { Err(bad("invalid identity_id")) }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextTarget {
@@ -120,7 +124,7 @@ pub enum Command {
Connect(ConnectArgs),
Disconnect { message: Option<String> },
JoinChannel { channel_id: u64, password: Option<String> },
SendText { target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<String>, message: String },
SendText { target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<String>, expected_channel_id: Option<u64>, message: String },
SetAudio { input_muted: Option<bool>, output_muted: Option<bool> },
/// `None` = direct transmission (push-to-talk / open microphone decided by the caller).
SetTransmit { vad: Option<GateMode> },
@@ -190,12 +194,23 @@ impl Command {
}
/// A command whose transport-independent arguments have been checked and normalized.
/// Only the core can unwrap it; callers must use [`validate_command`].
/// Callers can inspect it without changing it; only the core can unwrap it.
#[derive(Clone, Debug, PartialEq)]
pub struct ValidatedCommand(Command);
impl ValidatedCommand {
pub fn name(&self) -> &'static str { self.0.name() }
pub fn as_command(&self) -> &Command { &self.0 }
/// Bind the selected default to a connect that did not specify an identity.
pub fn bind_default_identity(&mut self, uid: &str) -> Result<(), ErrorObj> {
let Command::Connect(args) = &mut self.0 else { return Err(bad("identity binding requires connect")); };
if args.identity_id.is_some() { return Err(bad("identity_id is already set")); }
check_identity_id(uid)?;
args.identity_id = Some(uid.to_owned());
Ok(())
}
pub(crate) fn into_inner(self) -> Command { self.0 }
}
@@ -203,20 +218,25 @@ impl ValidatedCommand {
#[serde(deny_unknown_fields)]
pub struct ConnectArgs {
pub address: String,
#[serde(default)]
#[serde(default, deserialize_with = "present_string")]
pub server_password: Option<String>,
#[serde(default)]
#[serde(default, deserialize_with = "present_string")]
pub channel: Option<String>,
#[serde(default)]
#[serde(default, deserialize_with = "present_string")]
pub channel_password: Option<String>,
#[serde(default)]
#[serde(default, deserialize_with = "present_string")]
pub identity_id: Option<String>,
/// Nickname for this connection only (bookmark override); absent: the identity's
/// nickname/name. Validated by `Store::open_for_connect`; the identity is never changed.
#[serde(default)]
#[serde(default, deserialize_with = "present_string")]
pub nickname: Option<String>,
}
// Omission selects the default. An explicitly supplied null is not a string.
pub(crate) fn present_string<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<String>, D::Error> {
String::deserialize(deserializer).map(Some)
}
/// One parsed stdin line.
#[derive(Debug)]
pub enum Input {
@@ -242,10 +262,15 @@ struct Envelope<'a> {
id: Option<Cow<'a, str>>,
#[serde(borrow)]
cmd: Cow<'a, str>,
#[serde(default, borrow)]
#[serde(default, borrow, deserialize_with = "present_args")]
args: Option<&'a RawValue>,
}
// A missing field uses the default; an explicit null must still be checked.
fn present_args<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<&'de RawValue>, D::Error> {
<&RawValue>::deserialize(deserializer).map(Some)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Empty {}
@@ -259,7 +284,7 @@ struct NicknameArgs {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DisconnectArgs {
#[serde(default)]
#[serde(default, deserialize_with = "present_string")]
message: Option<String>,
}
@@ -279,18 +304,24 @@ struct SendTextArgs {
client_id: Option<u16>,
#[serde(default)]
expected_client_uid: Option<String>,
#[serde(default)]
expected_channel_id: Option<u64>,
message: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetAudioArgs {
#[serde(default)]
#[serde(default, deserialize_with = "present_bool")]
input_muted: Option<bool>,
#[serde(default)]
#[serde(default, deserialize_with = "present_bool")]
output_muted: Option<bool>,
}
fn present_bool<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<bool>, D::Error> {
bool::deserialize(deserializer).map(Some)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StreamListArgs {
@@ -414,6 +445,28 @@ fn check_stream_id(id: &str) -> Result<(), ErrorObj> {
Ok(())
}
// The original bridge measured string limits in UTF-16 units. Only SDP descriptions are multiline.
fn bounded_text(text: &str, min: usize, max: usize, multiline: bool) -> bool {
(min..=max).contains(&text.encode_utf16().count()) && !text.bytes().any(|b| {
(b < 0x20 || b == 0x7f) && !(multiline && matches!(b, b'\n' | b'\r' | b'\t'))
})
}
fn check_signal(value: &Value) -> Result<(), ErrorObj> {
let envelope = value.as_object().filter(|v| v.len() == 2).ok_or_else(|| bad("json must contain only cmd and args"))?;
let args = envelope.get("args").and_then(Value::as_object).ok_or_else(|| bad("json.args must be an object"))?;
let text = |key: &str, min, max, multiline| args.get(key).and_then(Value::as_str).is_some_and(|s| bounded_text(s, min, max, multiline));
let valid = match envelope.get("cmd").and_then(Value::as_str) {
Some("answer") => args.len() == 1 && text("answer", 1, 60_000, true),
Some("reconnectOffer") => args.len() == 1 && text("offer", 1, 60_000, true),
Some("iceCandidate") => args.len() == 3 && args.get("mLine").and_then(Value::as_u64).is_some_and(|n| n <= 9_007_199_254_740_991)
&& text("mid", 0, 64, false) && text("sdp", 0, 2048, false),
_ => return Err(bad("unknown outgoing stream signal")),
};
if !valid { return Err(bad("invalid arguments for outgoing stream signal")); }
Ok(())
}
/// Decodes base64 PCM straight into a frame without intermediate heap buffers.
pub fn decode_frame(b64: &str) -> Result<Box<Frame>, ErrorObj> {
let mut bytes = [0u8; FRAME_BYTES];
@@ -436,6 +489,9 @@ pub fn decode_frame(b64: &str) -> Result<Box<Frame>, ErrorObj> {
/// Parse one stdin line (without trailing newline).
pub fn parse_line(line: &str) -> Input {
if !line.trim_start().starts_with('{') {
return Input::Invalid { id: None, error: bad("request must be an object") };
}
let env: Envelope = match serde_json::from_str(line) {
Ok(e) => e,
Err(e) => {
@@ -448,6 +504,11 @@ pub fn parse_line(line: &str) -> Input {
}
};
if env.args.is_some_and(|raw| !raw.get().starts_with('{')) {
let id = if matches!(env.cmd.as_ref(), "audio_frame" | "audio_end") { None }
else { env.id.filter(|id| valid_id(id)).map(Cow::into_owned) };
return Input::Invalid { id, error: bad("args must be an object") };
}
// High-rate audio commands carry no id and get no response.
match env.cmd.as_ref() {
"audio_frame" => {
@@ -510,7 +571,7 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
}
"send_text" => {
let a: SendTextArgs = args_owned(raw)?;
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, message: a.message }
Command::SendText { target: a.target, client_id: a.client_id, expected_client_uid: a.expected_client_uid, expected_channel_id: a.expected_channel_id, message: a.message }
}
"set_audio" => {
let a: SetAudioArgs = args_owned(raw)?;
@@ -583,15 +644,28 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
let update = matches!(&command, Command::StreamUpdate(_));
match &mut command {
Command::Connect(a) => {
check_text("address", &a.address, 255, false)?;
check_opt("server_password", &a.server_password)?;
check_opt("channel", &a.channel)?;
check_opt("channel_password", &a.channel_password)?;
check_opt("identity_id", &a.identity_id)?;
for (field, value, min, max) in [
("address", Some(a.address.as_str()), 1, 255),
("server_password", a.server_password.as_deref(), 0, 255),
("channel", a.channel.as_deref(), 1, 512),
("channel_password", a.channel_password.as_deref(), 0, 255),
("nickname", a.nickname.as_deref(), 1, 64),
] {
if value.is_some_and(|s| !bounded_text(s, min, max, false)) { return Err(bad(format!("invalid {field}"))); }
}
if let Some(uid) = a.identity_id.as_deref() { check_identity_id(uid)?; }
}
Command::Disconnect { message } => check_opt("message", message)?,
Command::JoinChannel { password, .. } => check_opt("password", password)?,
Command::SendText { target, client_id, expected_client_uid, message } => {
Command::Disconnect { message } => {
if message.as_deref().is_some_and(|s| !bounded_text(s, 0, 80, false)) { return Err(bad("invalid disconnect message")); }
}
Command::JoinChannel { channel_id, password } => {
if *channel_id == 0 { return Err(bad("channel_id must be positive")); }
check_opt("password", password)?;
}
Command::SendText { target, client_id, expected_client_uid, expected_channel_id, message } => {
if expected_channel_id.is_some_and(|id| id == 0 || *target != TextTarget::Channel) {
return Err(bad("expected_channel_id must be positive and is only allowed for target channel"));
}
if message.is_empty() || message.len() > MAX_TEXT_BYTES { return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes"))); }
match (*target, *client_id) {
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
@@ -606,11 +680,19 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
}
Command::SetTransmit { vad } => crate::voice_dsp::validate_transmit(*vad)?,
Command::SetLocalVolumes(a) => crate::voice_dsp::validate_local_volumes(a)?,
Command::StreamJoin { stream_id, message, .. } => { check_stream_id(stream_id)?; check_opt("message", message)?; }
Command::StreamList { client_id: Some(0) } | Command::StreamJoin { client_id: 0, .. }
| Command::StreamSignal { client_id: 0, .. } | Command::StreamLeave { client_id: 0, .. }
| Command::StreamRespond { client_id: 0, .. } | Command::StreamRemove { client_id: 0, .. } => {
return Err(bad("client_id must be positive"));
}
Command::StreamJoin { stream_id, message, .. } => {
check_stream_id(stream_id)?;
if message.as_deref().is_some_and(|s| !bounded_text(s, 0, 200, false)) { return Err(bad("invalid stream join message")); }
}
Command::StreamSignal { stream_id, json, .. } => {
check_stream_id(stream_id)?;
let value: Value = serde_json::from_str(json).map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
if !value.is_object() { return Err(bad("json must be an object")); }
check_signal(&value)?;
let compact = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
if compact.len() > MAX_SIGNAL_JSON_BYTES { return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes"))); }
*json = compact;
@@ -625,19 +707,17 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
return Err(bad("invalid stream metadata (only P2P is supported)"));
}
}
Command::StreamRespond { stream_id, client_id, decision, offer, message } => {
Command::StreamRespond { stream_id, decision, offer, message, .. } => {
check_stream_id(stream_id)?;
check_text("message", message, 200, true)?;
if *client_id == 0 || *decision == offer.is_empty() || offer.len() > 60000
if *decision == offer.is_empty() || offer.len() > 60000
|| offer.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) || message.chars().any(char::is_control) {
return Err(bad("invalid stream join response"));
}
}
Command::StreamRemove { stream_id, client_id } => {
check_stream_id(stream_id)?;
if *client_id == 0 { return Err(bad("client_id must be nonzero")); }
}
Command::StreamRemove { stream_id, .. } => check_stream_id(stream_id)?,
Command::FetchIcon { icon_id: 0 } => return Err(bad("icon_id 0 means no icon")),
Command::FetchBanner { channel_id: 0 } => return Err(bad("channel_id must be positive")),
Command::ClientContext(a) => crate::menu::validate_target(a)?,
Command::ClientAction(a) => crate::menu::validate_action(a)?,
Command::Admin(a) => crate::admin::validate(a)?,
@@ -721,6 +801,19 @@ mod tests {
}
}
#[test]
fn fetch_banner_requires_only_a_positive_channel_id() {
let parse = |args: &str| parse_line(&format!(r#"{{"id":"banner","cmd":"fetch_banner","args":{args}}}"#));
assert!(matches!(parse(r#"{"channel_id":7}"#), Input::Request {
cmd: ValidatedCommand(Command::FetchBanner { channel_id: 7 }), ..
}));
for bad in [r#"{}"#, r#"{"channel_id":0}"#, r#"{"channel_id":-1}"#, r#"{"channel_id":1.5}"#,
r#"{"channel_id":"7"}"#, r#"{"channel_id":7,"url":"https://banner.invalid/"}"#] {
assert!(matches!(parse(bad), Input::Invalid { error, .. } if error.code == ErrorCode::BadRequest), "{bad}");
}
assert_eq!(validate_command(Command::FetchBanner { channel_id: 0 }).unwrap_err().code, ErrorCode::BadRequest);
}
#[test]
fn requests_need_valid_id_and_known_args() {
assert!(matches!(
@@ -748,6 +841,37 @@ mod tests {
}
}
#[test]
fn typed_connect_accepts_the_reference_field_limits() {
let pair = "\u{10000}";
let mut args = ConnectArgs {
address: pair.repeat(127) + "x", channel: Some(pair.repeat(256)),
identity_id: Some("test/9PZ9vww/Bpf5vJxtJhpz80=".into()), nickname: Some(pair.repeat(32)),
server_password: Some("x".repeat(255)), channel_password: Some(String::new()),
};
assert!(validate_command(Command::Connect(args.clone())).is_ok());
args.channel.as_mut().unwrap().push('x');
assert_bad(Command::Connect(args));
}
#[test]
fn default_identity_binding_requires_a_valid_uid_and_omission() {
let args = ConnectArgs { address: "localhost".into(), server_password: None, channel: None,
channel_password: None, identity_id: None, nickname: None };
let mut command = validate_command(Command::Connect(args.clone())).unwrap();
assert_eq!(command.bind_default_identity("").unwrap_err().code, ErrorCode::BadRequest);
assert_eq!(command.as_command(), &Command::Connect(args.clone()));
let uid = "test/9PZ9vww/Bpf5vJxtJhpz80=";
let chosen = Command::Connect(ConnectArgs { identity_id: Some(uid.into()), ..args });
command.bind_default_identity(uid).unwrap();
assert_eq!(command.as_command(), &chosen);
assert_eq!(command.bind_default_identity(uid).unwrap_err().code, ErrorCode::BadRequest);
let mut explicit = validate_command(chosen.clone()).unwrap();
assert_eq!(explicit.bind_default_identity(uid).unwrap_err().code, ErrorCode::BadRequest);
assert_eq!(explicit.as_command(), &chosen);
}
#[test]
fn connect_rejects_non_string_nickname_overrides() {
let parse = |args: Value| parse_line(&serde_json::json!({"id":"c","cmd":"connect","args":args}).to_string());
@@ -798,10 +922,19 @@ mod tests {
assert_eq!(validate_command(command).unwrap_err().code, ErrorCode::BadRequest);
}
#[test]
fn join_requires_a_positive_channel_in_both_transports() {
let join = |channel_id| Command::JoinChannel { channel_id, password: None };
let Input::Invalid { error, .. } = parse_line(r#"{"id":"j","cmd":"join_channel","args":{"channel_id":0}}"#) else { panic!("zero channel accepted") };
assert_eq!(error.code, ErrorCode::BadRequest);
assert_eq!(error, validate_command(join(0)).unwrap_err());
assert_eq!(validate_command(join(1)).unwrap().into_inner(), join(1));
}
#[test]
fn direct_private_text_requires_exact_target_and_uid() {
let private = |client_id, expected_client_uid| Command::SendText {
target: TextTarget::Client, client_id, expected_client_uid, message: "hello".into(),
target: TextTarget::Client, client_id, expected_client_uid, expected_channel_id: None, message: "hello".into(),
};
assert_bad(private(None, Some("uid".into())));
assert_bad(private(Some(0), Some("uid".into())));
@@ -812,27 +945,73 @@ mod tests {
assert_eq!(valid.name(), "send_text");
assert_eq!(valid.into_inner(), private(Some(7), Some("uid".into())));
for target in [TextTarget::Channel, TextTarget::Server] {
assert_bad(Command::SendText { target, client_id: Some(7), expected_client_uid: None, message: "hello".into() });
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), message: "hello".into() });
assert_bad(Command::SendText { target, client_id: Some(7), expected_client_uid: None, expected_channel_id: None, message: "hello".into() });
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: Some("uid".into()), expected_channel_id: None, message: "hello".into() });
for message in [String::new(), "я".repeat(MAX_TEXT_BYTES / 2 + 1)] {
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, message });
assert_bad(Command::SendText { target, client_id: None, expected_client_uid: None, expected_channel_id: None, message });
}
}
let Input::Invalid { error, .. } = parse_line(r#"{"id":"t","cmd":"send_text","args":{"target":"client","client_id":7,"message":"hello"}}"#) else { panic!() };
assert_eq!(error, validate_command(private(Some(7), None)).unwrap_err());
}
#[test]
fn expected_channel_id_is_a_guard_only_for_channel_text() {
for (target, channel) in [(TextTarget::Channel, 0), (TextTarget::Server, 7), (TextTarget::Client, 7)] {
let private = target == TextTarget::Client;
assert_bad(Command::SendText { target, client_id: private.then_some(2), expected_client_uid: private.then(|| "peer".into()),
expected_channel_id: Some(channel), message: "draft".into() });
}
let Input::Request { cmd, .. } = parse_line(r#"{"id":"t","cmd":"send_text","args":{"target":"channel","expected_channel_id":7,"message":"draft"}}"#) else { panic!("valid guarded send rejected") };
assert!(matches!(cmd.into_inner(), Command::SendText { expected_channel_id: Some(7), .. }));
}
#[test]
fn stream_operations_reject_zero_client_at_the_shared_boundary() {
for cmd in [Command::StreamList { client_id: Some(0) },
Command::StreamJoin { stream_id: "s1".into(), client_id: 0, message: None },
Command::StreamLeave { stream_id: "s1".into(), client_id: 0 },
Command::StreamSignal { stream_id: "s1".into(), client_id: 0, json: r#"{"cmd":"answer","args":{"answer":"v=0"}}"#.into() },
Command::StreamRemove { stream_id: "s1".into(), client_id: 0 },
Command::StreamRespond { stream_id: "s1".into(), client_id: 0, decision: false, offer: String::new(), message: String::new() }] {
assert_bad(cmd);
}
assert!(validate_command(Command::StreamList { client_id: None }).is_ok());
assert!(matches!(parse_line(r#"{"id":"z","cmd":"stream_signal","args":{"stream_id":"s1","client_id":0,"json":{"cmd":"answer","args":{"answer":"v=0"}}}}"#), Input::Invalid { .. }));
}
#[test]
fn direct_signaling_checks_objects_and_compact_byte_limit() {
let signal = |json| Command::StreamSignal { stream_id: "s1".into(), client_id: 7, json };
for json in ["[]", "null", "42", "\"string\"", "{"] { assert_bad(signal(json.into())); }
let compact = format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 8));
let prefix = r#"{"args":{"answer":""#;
let suffix = r#""},"cmd":"answer"}"#;
let available = MAX_SIGNAL_JSON_BYTES - prefix.len() - suffix.len();
let payload = "\\t".repeat(available / 2) + &"a".repeat(available % 2);
let compact = format!("{prefix}{payload}{suffix}");
let padded = format!(" {compact}{}", " ".repeat(MAX_SIGNAL_JSON_BYTES));
assert_eq!(validate_command(signal(padded)).unwrap().into_inner(), signal(compact));
assert_bad(signal(format!(r#"{{"x":"{}"}}"#, "x".repeat(MAX_SIGNAL_JSON_BYTES - 7))));
assert_bad(signal(format!("{prefix}{payload}x{suffix}")));
assert_bad(Command::StreamSignal { stream_id: "bad\n".into(), client_id: 7, json: "{}".into() });
}
#[test]
fn outgoing_signal_shapes_and_join_messages_match_bridge() {
let signal = |value: Value| Command::StreamSignal { stream_id: "s1".into(), client_id: 7, json: value.to_string() };
for valid in [serde_json::json!({"cmd":"reconnectOffer","args":{"offer":"v=0\r\n"}}),
serde_json::json!({"cmd":"iceCandidate","args":{"mLine":0,"mid":"","sdp":""}})] {
assert!(validate_command(signal(valid)).is_ok());
}
for invalid in [serde_json::json!({"cmd":"offer","args":{"offer":"v=0"}}), serde_json::json!({"cmd":"answer","args":{"answer":""}}),
serde_json::json!({"cmd":"answer","args":{"answer":"v=0"},"other":true}), serde_json::json!({"cmd":"answer","args":{"answer":"v=0","sdp":"other"}}),
serde_json::json!({"cmd":"iceCandidate","args":{"mLine":"0","mid":"0","sdp":"x"}}), serde_json::json!({"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"x\n"}})] {
assert_bad(signal(invalid));
}
let join = |s: String| Command::StreamJoin { stream_id:"s1".into(), client_id:7, message:Some(s) };
assert!(validate_command(join("x".repeat(200))).is_ok());
assert_bad(join("x".repeat(201))); assert_bad(join("a\tb".into())); assert_bad(join("\u{10000}".repeat(101)));
}
#[test]
fn direct_publisher_metadata_and_join_response_are_validated() {
let args = StreamPublishArgs { stream_id: None, name: "Screen".into(), stream_type: 3,
+152 -3
View File
@@ -6,7 +6,7 @@
use std::collections::BTreeMap;
use tsproto_packets::commands::{CommandItem, CommandParser};
use tsproto_packets::commands::{CommandArgumentValue, CommandItem, CommandParser};
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
/// Outgoing verbs the bridge may send (never caller-chosen names).
@@ -80,7 +80,8 @@ pub fn publish_stream(a: &crate::protocol::StreamPublishArgs) -> OutCommand {
}
pub fn stop_stream(stream_id: &str) -> OutCommand {
build(StreamVerb::StopStream, &[("id", stream_id)])
// beta14 requires the reason even for a publisher ending its own stream (LEFT = 1).
build(StreamVerb::StopStream, &[("id", stream_id), ("reason", "1")])
}
pub fn respond_stream(stream_id: &str, client_id: u16, decision: bool, offer: &str, message: &str) -> OutCommand {
@@ -108,11 +109,13 @@ pub fn tap(name: &[u8]) -> bool {
|| crate::admin::tapped(name)
|| crate::events::tapped(name)
|| crate::file_transfer::tapped(name)
|| S3TransferKind::from_name(name).is_some()
|| matches!(
name,
b"channellist"
| b"notifychannelcreated"
| b"notifychanneledited"
| b"notifychanneldescriptionchanged"
| b"notifychanneldeleted"
| b"notifycliententerview"
| b"notifyclientupdated"
@@ -126,6 +129,152 @@ pub fn is_stream_notification(name: &str) -> bool {
|| matches!(name, "notifyjoinstreamrequest" | "notifyrespondjoinstreamrequest" | "notifyremovedfromstream" | "notifysfuaccessinfo")
}
/// The S3 list envelope is a single row. Retain a raw slice so an unsolicited reply never needs
/// to unescape, allocate or decode its payload. An ambiguous handle cannot be matched to a job.
pub(crate) struct S3FileList<'a> {
pub handle: Option<u16>,
pub payload: Result<&'a [u8], &'static str>,
}
pub(crate) fn s3_file_list(content: &[u8]) -> Option<S3FileList<'_>> {
let (name, parser) = CommandParser::new(content);
if name != b"notify_s3ft_file_list" { return None; }
let mut return_code = None;
let mut payload = None;
let mut ambiguous_handle = false;
let mut malformed = false;
for item in parser {
match item {
CommandItem::NextCommand => malformed = true,
CommandItem::Argument(arg) => match arg.name() {
b"return_code" => ambiguous_handle |= return_code.replace(arg.value().get_raw()).is_some(),
b"b64_json" => malformed |= payload.replace(arg.value().get_raw()).is_some(),
_ => {}
},
}
}
let handle = return_code.filter(|code| !ambiguous_handle && code.iter().all(u8::is_ascii_digit))
.and_then(|code| std::str::from_utf8(code).ok()?.parse().ok());
let payload = if malformed { Err("malformed S3 file list notification") } else { payload.ok_or("S3 file list notification is missing b64_json") };
Some(S3FileList { handle, payload })
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum S3TransferKind { Presign, UploadDone }
impl S3TransferKind {
fn from_name(name: &[u8]) -> Option<Self> {
match name {
b"notify_presigned_urls" => Some(Self::Presign),
b"notify_s3ft_upload_done" => Some(Self::UploadDone),
_ => None,
}
}
}
pub(crate) fn is_s3_transfer_notification(content: &[u8]) -> bool {
S3TransferKind::from_name(CommandParser::new(content).0).is_some()
}
/// Keep credentials in their wire representation until this exact command owns the reply.
pub(crate) struct S3TransferReply<'a> {
pub kind: S3TransferKind,
pub handle: Option<u16>,
parser: CommandParser<'a>,
}
pub(crate) fn s3_transfer(content: &[u8]) -> Option<S3TransferReply<'_>> {
let (name, parser) = CommandParser::new(content);
let kind = S3TransferKind::from_name(name)?;
let mut codes = parser.clone().filter_map(|item| match item {
CommandItem::Argument(arg) if arg.name() == b"return_code" => Some(arg.value().get_raw()),
_ => None,
});
let handle = codes.next().filter(|code| codes.next().is_none() && code.iter().all(u8::is_ascii_digit))
.and_then(|code| std::str::from_utf8(code).ok()?.parse().ok());
Some(S3TransferReply { kind, handle, parser })
}
impl<'a> S3TransferReply<'a> {
/// Only one key was requested. Do not use a URL from any other file or an ambiguous row.
pub fn presigned_url(self, expected_key: &str) -> Result<CommandArgumentValue<'a>, &'static str> {
const INVALID: &str = "server returned an invalid S3 file grant";
let mut matched = None;
let mut key = None;
let mut url = None;
let mut finish_row = |key: Option<CommandArgumentValue<'a>>, url: Option<CommandArgumentValue<'a>>| {
if let Some(url) = url.filter(|url| !url.get_raw().is_empty()) {
if key.and_then(|key| key.get_str().ok()).as_deref() != Some(expected_key) || matched.replace(url).is_some() {
return Err(INVALID);
}
}
Ok(())
};
for item in self.parser {
match item {
CommandItem::NextCommand => finish_row(key.take(), url.take())?,
CommandItem::Argument(arg) => {
let field = match arg.name() {
b"key" => &mut key,
b"url" => &mut url,
_ => continue,
};
if field.replace(arg.value().clone()).is_some() { return Err(INVALID); }
}
}
}
finish_row(key, url)?;
matched.ok_or("server did not return an S3 file grant")
}
pub fn upload_success(self) -> Result<bool, &'static str> {
const INVALID: &str = "server returned an invalid S3 upload confirmation";
let mut success = None;
for item in self.parser {
if let CommandItem::Argument(arg) = item {
if arg.name() != b"success" { continue; }
let value = match arg.value().get_raw() {
b"0" => false,
b"1" => true,
_ => return Err(INVALID),
};
if success.replace(value).is_some() { return Err(INVALID); }
}
}
success.ok_or(INVALID)
}
}
#[cfg(test)]
mod s3_transfer_tests {
use super::*;
#[test]
fn presign_matches_its_handle_and_object_row() {
let raw = br"notify_presigned_urls return_code=17 url|key=\/dir\/a\sb\pc url=opaque";
let reply = s3_transfer(raw).unwrap();
assert_eq!(reply.kind, S3TransferKind::Presign);
assert_eq!(reply.handle, Some(17));
assert!(reply.presigned_url("/dir/a b|c").is_ok());
assert!(s3_transfer(raw).unwrap().presigned_url("/other").is_err());
assert!(s3_transfer(br"notify_presigned_urls return_code=17|key=\/a url=one|key=\/a url=two")
.unwrap().presigned_url("/a").is_err());
assert!(s3_transfer(br"notify_presigned_urls return_code=17|key=\/a|url=opaque")
.unwrap().presigned_url("/a").is_err());
}
#[test]
fn malformed_or_ambiguous_business_replies_cannot_report_success() {
let reply = s3_transfer(b"notify_s3ft_upload_done success=1 return_code=3|return_code=4").unwrap();
assert_eq!(reply.handle, None);
let success = |raw: &[u8]| s3_transfer(raw).unwrap().upload_success();
assert_eq!(success(b"notify_s3ft_upload_done success=0 return_code=3"), Ok(false));
assert_eq!(success(b"notify_s3ft_upload_done success=1 return_code=3"), Ok(true));
assert!(success(b"notify_s3ft_upload_done success=1 success=0 return_code=3").is_err());
assert!(success(b"notify_s3ft_upload_done return_code=3").is_err());
}
}
/// A parsed raw command: name plus one unescaped key/value map per `|`-separated entry.
#[derive(Debug, PartialEq)]
pub struct RawNotification {
@@ -218,7 +367,7 @@ mod tests {
assert_eq!(std::str::from_utf8(&content(respond_stream("7", 4, false, "", "not_authorized"))).unwrap(),
"respondjoinstreamrequest id=7 clid=4 decision=0 offer msg=not_authorized");
assert_eq!(std::str::from_utf8(&content(remove_stream_client("7", 4))).unwrap(), "removeclientfromstream id=7 clid=4 reason=4");
assert_eq!(std::str::from_utf8(&content(stop_stream("7"))).unwrap(), "stopstream id=7");
assert_eq!(std::str::from_utf8(&content(stop_stream("7"))).unwrap(), "stopstream id=7 reason=1");
}
#[test]
+6
View File
@@ -1064,6 +1064,12 @@ impl Recorder {
}
Err(TrySendError::Full(msg)) => {
self.dropped_chunks += 1;
// Dropped ticks are written as silence, including at the end of the WAV.
for track in &mut self.tracks {
if track.first_bucket + track.peaks.len() as u64 == tick + 1 {
if let Some(peak) = track.peaks.back_mut() { *peak = 0; }
}
}
match self.dropped_ranges.last_mut() {
Some(r) if r[1] == tick => r[1] = tick + 1,
_ => self.dropped_ranges.push([tick, tick + 1]),
+4 -2
View File
@@ -385,7 +385,7 @@ fn slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment() {
let mut dropped_reports = 0;
const TICKS: u64 = 60;
for tick in 0..TICKS {
let f: Frame = [(tick as i16) + 1; FRAME_SAMPLES];
let f: Frame = [((tick as i16) + 1) * 256; FRAME_SAMPLES];
match rec.end_tick(&f, ident, &LOBBY) {
TickOutcome::Overflow { .. } => dropped_reports += 1,
TickOutcome::Ok => {}
@@ -395,6 +395,7 @@ fn slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment() {
let dropped = rec.info()["droppedChunks"].as_u64().unwrap();
assert!(dropped > 0 && dropped < TICKS, "dropped={dropped}");
assert!(dropped_reports >= 1);
let waveform = rec.waveform(0, 0).unwrap();
assert!(finish_wait(rec, "stopped").ok);
let dir = session_dir(&base);
let m = manifest(&dir);
@@ -413,7 +414,8 @@ fn slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment() {
for t in 0..ticks {
let v = w.samples[(t * 960) as usize];
let was_dropped = ranges.iter().any(|(a, b)| (*a..*b).contains(&t));
assert_eq!(v, if was_dropped { 0 } else { t as i16 + 1 }, "tick {t}");
assert_eq!(v, if was_dropped { 0 } else { (t as i16 + 1) * 256 }, "tick {t}");
assert_eq!(waveform["peaks"][t as usize], json!(peak_of(&[v; FRAME_SAMPLES])), "waveform at tick {t}");
}
let _ = fs::remove_dir_all(&base);
}
+6 -2
View File
@@ -2,7 +2,7 @@
use std::{collections::HashMap, path::PathBuf, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}, thread};
use serde_json::Value;
use tokio::sync::{mpsc, oneshot};
use crate::{audio::{AudioIn, AudioInQueue, CapturedFrame}, locks, output::{Out, PlaybackReceiver}, profile::Store, protocol::{validate_command, Command, ErrorCode, ErrorObj, Input}, session::Session};
use crate::{audio::{AudioIn, AudioInQueue, CapturedFrame}, locks, output::{Out, PlaybackReceiver}, profile::Store, protocol::{validate_command, Command, ErrorCode, ErrorObj, Input, ValidatedCommand}, session::Session};
pub struct CoreConfig { pub data_dir: PathBuf, pub connection_dir: PathBuf }
#[derive(Debug, thiserror::Error)]
@@ -43,7 +43,11 @@ impl Drop for PendingRequest {
impl CoreHandle {
pub async fn request(&self, command: Command) -> Result<Value, ErrorObj> {
let command = validate_command(command)?;
self.request_validated(validate_command(command)?).await
}
/// Send a command that has already passed shared protocol validation.
pub async fn request_validated(&self, command: ValidatedCommand) -> Result<Value, ErrorObj> {
let commands = self.commands.as_ref().ok_or_else(stopped)?;
let id = self.next_request.fetch_add(1, Ordering::Relaxed).to_string();
let (reply, receiver) = oneshot::channel();
+200 -33
View File
@@ -115,6 +115,16 @@ enum Phase {
Disconnecting { req: Option<String>, deadline: Instant },
}
impl Phase {
fn state(&self) -> &'static str {
match self {
Self::Connecting { .. } => "connecting",
Self::Connected => "connected",
Self::Disconnecting { .. } => "disconnecting",
}
}
}
enum Pending {
Simple { req: String },
MenuContext { req: String, target: Target },
@@ -164,6 +174,7 @@ struct Conn {
gains: menu::LocalVolumes,
avatar: Option<AvatarUpload>,
files: crate::file_transfer::Files,
s3_receipts: HashMap<u16, files_session::s3::Receipt>,
}
struct AvatarUpload {
@@ -363,8 +374,11 @@ impl Session {
self.out.json(&v).await;
}
async fn emit_state(&self, state: &str, address: Option<&str>, reason: Option<ErrorObj>) {
async fn emit_state(&self, state: &str, address: Option<&str>, reason: Option<ErrorObj>, previous: Option<&Phase>) {
let mut v = json!({ "event": "state", "state": state, "address": address });
if let Some(phase) = previous {
v["previous_state"] = json!(phase.state());
}
if let Some(c) = &self.conn {
v["identity_id"] = json!(c.identity.uid);
}
@@ -422,7 +436,7 @@ impl Session {
Command::Connect(args) => self.connect(&id, args).await,
Command::Disconnect { message } => self.disconnect(Some(id.clone()), message).await,
Command::JoinChannel { channel_id, password } => self.join_channel(&id, channel_id, password),
Command::SendText { target, client_id, expected_client_uid, message } => self.send_text(&id, target, client_id, expected_client_uid.as_deref(), &message),
Command::SendText { target, client_id, expected_client_uid, expected_channel_id, message } => self.send_text(&id, target, client_id, expected_client_uid.as_deref(), expected_channel_id, &message),
Command::SetAudio { input_muted, output_muted } => self.set_audio(&id, input_muted, output_muted).await,
Command::SetTransmit { vad } => self.set_transmit(vad).await.map(Some),
Command::SetLocalVolumes(update) => self.set_local_volumes(update).map(Some),
@@ -571,13 +585,14 @@ impl Session {
gains: menu::LocalVolumes::default(),
avatar: None,
files: Default::default(),
s3_receipts: HashMap::new(),
ft_waiting: VecDeque::new(),
ft_active: HashMap::new(),
ft_in_flight: 0,
next_ftid: 1,
server_port,
});
self.emit_state("connecting", Some(&args.address), None).await;
self.emit_state("connecting", Some(&args.address), None, None).await;
Ok(None)
}
@@ -606,7 +621,7 @@ impl Session {
}
let address = c.address.clone();
c.phase = Phase::Disconnecting { req, deadline: Instant::now() + DISCONNECT_TIMEOUT };
self.emit_state("disconnecting", Some(&address), None).await;
self.emit_state("disconnecting", Some(&address), None, None).await;
Ok(None)
}
}
@@ -632,7 +647,7 @@ impl Session {
Ok(None)
}
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<&str>, message: &str) -> Result<Option<Value>, ErrorObj> {
fn send_text(&mut self, id: &str, target: TextTarget, client_id: Option<u16>, expected_client_uid: Option<&str>, expected_channel_id: Option<u64>, message: &str) -> Result<Option<Value>, ErrorObj> {
let target = match (target, client_id) {
(TextTarget::Server, _) => MessageTarget::Server,
(TextTarget::Channel, _) => MessageTarget::Channel,
@@ -641,6 +656,11 @@ impl Session {
};
let c = self.connected_conn()?;
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
if let Some(expected) = expected_channel_id {
if book.clients.get(&book.own_client).map(|client| client.channel.0) != Some(expected) {
return Err(ErrorObj::new(ErrorCode::TargetChanged, "own channel changed before sending the message"));
}
}
if let Some(cid) = client_id {
let current = book.clients.get(&ClientId(cid)).and_then(|client| client.uid.as_ref());
if current.is_none_or(|uid| Some(uid.to_string()).as_deref() != expected_client_uid) {
@@ -654,7 +674,11 @@ impl Session {
}
async fn set_audio(&mut self, id: &str, input_muted: Option<bool>, output_muted: Option<bool>) -> Result<Option<Value>, ErrorObj> {
if input_muted.is_some() || output_muted.is_some() { self.audio_in.invalidate(); }
if input_muted.is_none() && output_muted.is_none() {
self.emit_audio_state().await;
return Ok(Some(self.audio_state()));
}
self.audio_in.invalidate();
if let Some(m) = input_muted {
self.flags.input_muted = m;
}
@@ -680,13 +704,9 @@ impl Session {
if let Some(m) = output_muted {
part = part.set_output_muted(m);
}
if input_muted.is_none() && output_muted.is_none() {
Ok(Some(self.audio_state()))
} else {
let handle = c.send(part).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.pending.insert(handle, Pending::SetAudio { req: id.to_owned() });
Ok(None)
}
let handle = c.send(part).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.pending.insert(handle, Pending::SetAudio { req: id.to_owned() });
Ok(None)
}
// Applied through ConnectOptions at the next (re)connect.
_ => Ok(Some(self.audio_state())),
@@ -963,13 +983,19 @@ impl Session {
}
let ignored = c.rx.set_deny_whispers(self.whisper.deny_incoming);
let event = c.rx.handle_packet(packet);
let whisper_starts: Vec<u16> = c.rx.take_whisper_starts().collect();
for cid in ignored {
self.out.json(&json!({ "event": "talking", "client_id": cid, "talking": false })).await;
}
for cid in whisper_starts {
// Official `onWhisperStart`: feeds the reply history and the whisper notification.
self.out.json(&json!({ "event": "whisper_received", "client_id": cid })).await;
for cid in c.rx.take_whisper_starts() {
// Capture the sender from this connection before another roster update can recycle the ID.
let client = c.con.get_state().ok().and_then(|book| book.clients.get(&ClientId(cid)));
let uid = client.and_then(|client| client.uid.as_ref()).filter(|uid| !uid.0.is_empty())
.map(|uid| format!("{}", &**uid));
let nickname = client.map(|client| client.name.as_str()).filter(|name| !name.is_empty());
self.out.control(json!({
"event": "whisper_received", "generation": c.generation, "client_id": cid,
"uid": uid, "nickname": nickname,
})).await;
}
match event {
RxEvent::None => {}
@@ -990,6 +1016,10 @@ impl Session {
}
}
StreamItem::RawCommandCopy(content) => {
if let Some(reply) = rawcmd::s3_transfer(&content) {
self.files_s3_transfer(reply).await;
return;
}
let Some(c) = &mut self.conn else { return };
let Some(raw) = rawcmd::parse(&content) else { return };
c.permissions.apply(&raw);
@@ -1047,7 +1077,15 @@ impl Session {
self.ft_finish(handle.0, err).await;
}
StreamItem::UnknownCommand(cmd) => {
let Some(raw) = rawcmd::parse(cmd.data().packet().content()) else { return };
let content = cmd.data().packet().content();
// The raw tap already delivered S3 transfer receipts. Never parse their credentials
// into the general notification pipeline.
if rawcmd::is_s3_transfer_notification(content) { return; }
if let Some(reply) = rawcmd::s3_file_list(content) {
self.files_s3_list(reply).await;
return;
}
let Some(raw) = rawcmd::parse(content) else { return };
if rawcmd::is_stream_notification(&raw.name) {
// Payloads (SDP/ICE/tokens) are never logged.
debug!(name = %raw.name, entries = raw.items.len(), "stream notification");
@@ -1057,6 +1095,12 @@ impl Session {
}
}
StreamItem::DisconnectedTemporarily(reason) => {
if let Some(Phase::Disconnecting { req, .. }) = self.conn.as_mut().map(|c| &mut c.phase) {
// The transport has queued a reconnect, but the user already asked to leave.
let respond = req.take().map(|r| (r, json!({ "clean": false })));
self.close_conn(None, respond).await;
return;
}
warn!(?reason, "connection lost, tsclientlib reconnects");
self.fail_pending("connection lost before the server answered").await;
self.fail_media("connection lost before the download finished").await;
@@ -1075,7 +1119,7 @@ impl Session {
tsclientlib::TemporaryDisconnectReason::Timeout(t) => format!("timeout: {t}"),
tsclientlib::TemporaryDisconnectReason::Serverstop => "server stopped".to_owned(),
};
self.emit_state("connecting", Some(&address), Some(ErrorObj::new(ErrorCode::NotConnected, msg)))
self.emit_state("connecting", Some(&address), Some(ErrorObj::new(ErrorCode::NotConnected, msg)), None)
.await;
}
}
@@ -1105,6 +1149,8 @@ impl Session {
async fn on_book_events(&mut self, events: Vec<Event>) {
let Some(c) = &mut self.conn else { return };
let own = c.con.get_state().map(|b| b.own_client).ok();
let moved = c.connected() && c.con.get_state().ok().and_then(|book| book.clients.get(&book.own_client))
.is_some_and(|me| revoke_capture_on_move(&self.audio_in, me.id, me.channel, &events));
let mut texts = Vec::new();
for e in &events {
match e {
@@ -1134,10 +1180,13 @@ impl Session {
info!(own_client = ?own_id, "connected");
self.emit_snapshot().await;
self.emit_audio_state().await;
self.emit_state("connected", Some(&address), None).await;
self.emit_state("connected", Some(&address), None, None).await;
if let Some(r) = req {
self.out.ok(&r, json!({ "own_client_id": own_id })).await;
}
} else if moved {
// The host renews its microphone permit on the new own-channel snapshot.
self.emit_snapshot().await;
}
for t in texts {
self.out.json(&t).await;
@@ -1145,7 +1194,7 @@ impl Session {
}
async fn on_result(&mut self, handle: u16, res: Result<(), CommandError>) {
if self.conn.as_ref().is_some_and(|c| c.files.owns_handle(handle)) {
if self.conn.as_ref().is_some_and(|c| c.files.owns_handle(handle) || c.s3_receipts.contains_key(&handle)) {
self.files_result(handle, res).await;
return;
}
@@ -1177,11 +1226,13 @@ impl Session {
Err(e)=>self.out.err(&req,e).await,
}
},
Pending::MenuRead { req, target, rows, .. } => match res {
Pending::MenuRead { req, target, response, rows, .. } => match res {
Err(e)=>self.out.err(&req,command_error(&e)).await,
Ok(())=>match c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e)).and_then(|b|c.permissions.context(b,&target,c.generation)) {
Ok(_) if rows.len()>4096=>self.out.err(&req,ErrorObj::new(ErrorCode::ServerError,"server returned too many permission rows; result not complete")).await,
Ok(_)=>self.out.ok(&req,json!({"rows":rows})).await,
Ok(())=>match c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e)).and_then(|book| {
let uid=book.clients.get(&ClientId(target.client_id)).and_then(|client|client.uid.as_ref()).map(|uid|uid.to_string());
menu::finish_read(&target,uid.as_deref(),response,rows)
}) {
Ok(reply)=>self.out.ok(&req,reply).await,
Err(e)=>self.out.err(&req,e).await,
},
},
@@ -1328,7 +1379,7 @@ impl Session {
self.out.err(r, err).await;
}
self.tx.encoder = None;
self.emit_state("disconnected", Some(&c.address), reason).await;
self.emit_state("disconnected", Some(&c.address), reason, Some(&c.phase)).await;
if let Some((r, v)) = respond {
self.out.ok(&r, v).await;
}
@@ -1452,8 +1503,8 @@ impl Session {
async fn tx_frame(&mut self, frame: &CapturedFrame) {
if !self.audio_in.validate(frame) { return; }
let whisper = frame.whisper;
// Capture queued before push-to-whisper must not escape to the ordinary channel.
if whisper.is_none() && self.whisper.active_epoch().is_some() {
// Neither stale whisper audio nor pre-whisper ordinary audio may alter the current spurt.
if whisper != self.whisper.active_epoch() {
return;
}
self.tx.burst_open = true;
@@ -1598,11 +1649,9 @@ impl Session {
if c.connected() {
let end = match spurt {
None => Some(audio::end_of_voice(enc.codec())),
// A cleared route has nobody left to tell.
Some(epoch) => self
.whisper
.route_mut(epoch, c.generation)
.filter(|r| !r.is_empty())
// The roster can change between the last frame and key release.
Some(epoch) => c.con.get_state().ok()
.and_then(|book| self.whisper.route_for_send(epoch, c.generation, book))
.map(|r| audio::end_of_whisper(enc.codec(), r)),
};
if let Some(end) = end {
@@ -1688,6 +1737,14 @@ impl Session {
}
}
fn revoke_capture_on_move(queue: &AudioInQueue, own: ClientId, channel: ChannelId, events: &[Event]) -> bool {
let moved = events.iter().any(|e| matches!(e, Event::PropertyChanged {
id: PropertyId::ClientChannel(id), old: tsclientlib::events::PropertyValue::ChannelId(old), ..
} if *id == own && *old != channel));
if moved { queue.invalidate(); }
moved
}
fn text_event(target: MessageTarget, invoker: &Invoker, message: &str) -> Value {
let (target, to) = match target {
MessageTarget::Server => ("server", None),
@@ -1708,3 +1765,113 @@ fn text_event(target: MessageTarget, invoker: &Invoker, message: &str) -> Value
}
v
}
#[cfg(test)]
mod disconnect_tests {
use super::*;
use crate::profile::tests::TempDir;
#[test]
fn only_an_own_channel_move_revokes_old_audio() {
use tsclientlib::{AudioSendGuard, AudioSendMetadata};
let queue = AudioInQueue::new();
let frame = CapturedFrame { pcm: [9; FRAME_SAMPLES], captured_at: Instant::now(), connection_generation: queue.generation(), capture_epoch: queue.epoch(), whisper: None };
assert!(queue.try_push(frame.clone()));
let change = |id, old| Event::PropertyChanged { id: PropertyId::ClientChannel(ClientId(id)), old: tsclientlib::events::PropertyValue::ChannelId(ChannelId(old)), invoker: None, extra: Default::default() };
assert!(!revoke_capture_on_move(&queue, ClientId(1), ChannelId(5), &[change(2, 4), change(1, 5)]));
assert!(queue.validate(&frame));
let metadata = AudioSendMetadata { captured_at: frame.captured_at, capture_epoch: frame.capture_epoch, connection_generation: frame.connection_generation };
assert!(revoke_capture_on_move(&queue, ClientId(1), ChannelId(6), &[change(1, 5)]));
queue.with_valid_audio(&metadata, &mut || panic!("transport sent old-channel PCM"));
assert!(!queue.try_push(frame.clone()));
assert!(matches!(queue.pop(), Some(AudioIn::End)));assert!(queue.pop().is_none());
assert!(queue.try_push(CapturedFrame { capture_epoch: queue.epoch(), ..frame }));
}
#[tokio::test]
async fn server_stop_reconnects_only_without_an_explicit_disconnect() {
for leaving in [false, true] {
let dir = TempDir::new("server-stop");
let store = Store::new(&dir.0);
store.create("Disconnect Test").unwrap();
let (out, mut events, _playback) = Out::new();
let mut session = Session::new(store, out, Arc::new(AudioInQueue::new()));
let args = serde_json::from_value(json!({"address":"127.0.0.1:9987"})).unwrap();
session.connect("join", args).await.unwrap();
// Drive session events directly; the transport's connect future is never polled.
session.conn.as_mut().unwrap().phase = Phase::Connected;
if leaving { session.disconnect(Some("leave".into()), None).await.unwrap(); }
while events.try_recv().is_ok() {}
session.on_item(StreamItem::DisconnectedTemporarily(tsclientlib::TemporaryDisconnectReason::Serverstop)).await;
let mut states = Vec::new();
let mut replies = Vec::new();
while let Ok(event) = events.try_recv() {
if event["event"] == "state" { states.push(event["state"].clone()); }
if event["id"] == "leave" { replies.push(event); }
}
if leaving {
assert!(session.conn.is_none());
assert_eq!(states, [json!("disconnected")]);
assert_eq!(replies, [json!({"id":"leave", "ok":true, "result":{"clean":false}})]);
} else {
assert!(matches!(session.conn.unwrap().phase, Phase::Connecting { req: None }));
assert_eq!(states, [json!("connecting")]);
assert!(replies.is_empty());
}
}
}
#[tokio::test]
async fn whisper_receipt_without_a_roster_entry_does_not_infer_sender_identity() {
use tsproto_packets::packets::{AudioData, CodecType, Direction, InAudioBuf, OutAudio};
let dir = TempDir::new("unknown-whisper-sender");
let store = Store::new(&dir.0);
store.create("Whisper Test").unwrap();
let (out, mut events, _playback) = Out::new();
let mut session = Session::new(store, out, Arc::new(AudioInQueue::new()));
let args = serde_json::from_value(json!({"address":"127.0.0.1:9987"})).unwrap();
session.connect("join", args).await.unwrap();
let generation = session.conn.as_ref().unwrap().generation;
// Drive receipt handling with no book data, as when audio precedes the sender's roster entry.
let audio = OutAudio::new(&AudioData::S2CWhisper { id: 1, from: 7, codec: CodecType::OpusVoice, data: &[1, 2, 3] });
let audio = InAudioBuf::try_new(Direction::S2C, audio.into_vec()).unwrap();
session.on_item(StreamItem::Audio(audio)).await;
let receipt = std::iter::from_fn(|| events.try_recv().ok())
.find(|event| event["event"] == "whisper_received").unwrap();
assert_eq!(receipt, json!({
"event": "whisper_received", "generation": generation, "client_id": 7,
"uid": null, "nickname": null,
}));
}
#[tokio::test]
async fn terminal_state_preserves_which_phase_failed_or_finished() {
for (phase, previous_state, transport_error, expected_code) in [
(Phase::Connecting { req: Some("join".into()) }, "connecting", false, Some("not_connected")),
(Phase::Connecting { req: Some("join".into()) }, "connecting", true, Some("connect_failed")),
(Phase::Connected, "connected", true, Some("not_connected")),
(Phase::Disconnecting { req: None, deadline: Instant::now() }, "disconnecting", true, Some("not_connected")),
(Phase::Disconnecting { req: None, deadline: Instant::now() }, "disconnecting", false, None),
] {
let dir = TempDir::new("terminal-state-phase");
let store = Store::new(&dir.0);
store.create("Disconnect Test").unwrap();
let (out, mut events, _playback) = Out::new();
let mut session = Session::new(store, out, Arc::new(AudioInQueue::new()));
let args = serde_json::from_value(json!({"address":"127.0.0.1:9987"})).unwrap();
session.connect("join", args).await.unwrap();
session.conn.as_mut().unwrap().phase = phase;
if transport_error {
session.on_conn_error(tsclientlib::Error::NotConnected).await;
} else {
session.on_stream_end().await;
}
let event = std::iter::from_fn(|| events.try_recv().ok())
.find(|event| event["event"] == "state" && event["state"] == "disconnected").unwrap();
assert_eq!(event["previous_state"], previous_state);
assert_eq!(event["reason"]["code"].as_str(), expected_code);
assert_eq!(event["generation"], 1);
}
}
}
+104 -15
View File
@@ -31,8 +31,6 @@ pub struct RawExtras {
channels: HashMap<u64, ChannelExtra>,
clients: HashMap<u16, ClientExtra>,
server_properties: BTreeMap<String, String>,
/// Raw `virtualserver_capability_extensions` of `initserver`; `None` = not announced.
capability_extensions: Option<String>,
}
/// Server features exactly as the official client derives them (`hasFeature`, installed
@@ -67,10 +65,8 @@ struct ChannelExtra {
impl ChannelExtra {
fn merge(&mut self, item: &BTreeMap<String, String>) {
for (key, value) in item {
if key.starts_with("channel_") || matches!(key.as_str(), "cid" | "cpid") {
if key == "cid" || (key.starts_with("channel_") && !matches!(key.as_str(), "channel_order" | "channel_password")) {
self.properties.insert(key.clone(), value.clone());
} else if key == "order" {
self.properties.insert("channel_order".into(), value.clone());
}
}
if let Some(u) = item.get("channel_banner_gfx_url") {
@@ -159,9 +155,14 @@ fn non_empty(s: &str) -> Option<String> { (!s.is_empty()).then(|| s.to_owned())
impl RawExtras {
pub fn server_properties(&self) -> &BTreeMap<String, String> { &self.server_properties }
/// Ordinary channel fields observed on this connection, not a ServerQuery snapshot.
pub fn channel_properties(&self, channel_id: u64) -> Option<&BTreeMap<String, String>> {
self.channels.get(&channel_id).map(|c| &c.properties)
/// The book also relinks siblings that did not receive an individual move notification.
pub fn channel_properties(&self, channel_id: ChannelId, parent: ChannelId, order: ChannelId) -> Option<Value> {
let fields = &self.channels.get(&channel_id.0)?.properties;
let mut row = serde_json::Map::with_capacity(fields.len() + 2);
row.extend(fields.iter().map(|(k, v)| (k.clone(), Value::String(v.clone()))));
row.insert("cpid".into(), Value::String(parent.0.to_string()));
row.insert("channel_order".into(), Value::String(order.0.to_string()));
Some(Value::Object(row))
}
/// myTeamSpeak avatar URLs of a client (`(variant, url)`), empty if none.
pub fn client_myts_avatars(&self, client_id: u16) -> &[(u32, String)] {
@@ -198,12 +199,12 @@ impl RawExtras {
let mut changed = false;
match raw.name.as_str() {
"initserver" | "notifyserverupdated" | "notifyserveredited" => {
if raw.name == "initserver" { self.server_properties.clear(); }
for item in &raw.items {
for (key, value) in item {
if key.starts_with("virtualserver_") { self.server_properties.insert(key.clone(), value.clone()); }
}
if let Some(value) = item.get("virtualserver_capability_extensions") {
self.capability_extensions = Some(value.clone());
if key.starts_with("virtualserver_") && !matches!(key.as_str(), "virtualserver_password" | "virtualserver_keypair") {
self.server_properties.insert(key.clone(), value.clone());
}
}
}
changed = true;
@@ -222,14 +223,22 @@ impl RawExtras {
changed = true;
}
}
"notifychanneldescriptionchanged" => {
for (cid, _) in cids() {
if let Some(channel) = self.channels.get_mut(&cid) {
changed |= channel.properties.remove("channel_description").is_some();
}
}
}
"notifychanneldeleted" => {
for (cid, _) in cids() {
changed |= self.channels.remove(&cid).is_some();
}
}
"notifycliententerview" => {
let shared_channel = raw.items.first().and_then(|item| item.get("ctid")).and_then(|v| v.parse().ok());
for (clid, item) in clids() {
let mut e = ClientExtra::default();
let mut e = ClientExtra { channel: shared_channel, ..ClientExtra::default() };
e.merge(item);
self.clients.insert(clid, e);
changed = true;
@@ -478,6 +487,7 @@ pub fn build(book: &Connection, rev: u64, extras: &RawExtras) -> Value {
let mut cgroups: Vec<&ChannelGroup> = book.channel_groups.values().collect();
cgroups.sort_by_key(|g| (g.sort_id, g.id.0));
let s = &book.server;
let extensions = extras.server_properties.get("virtualserver_capability_extensions").map(String::as_str);
json!({
"event": "snapshot",
"rev": rev,
@@ -501,8 +511,8 @@ pub fn build(book: &Connection, rev: u64, extras: &RawExtras) -> Value {
"default_channel_admin_group": extras.server_properties.get("virtualserver_default_channel_admin_group").and_then(|value| value.parse::<u64>().ok()),
// Raw string or null when the server did not announce it; features are null then too
// (unknown), never false.
"capability_extensions": extras.capability_extensions,
"features": server_features(extras.capability_extensions.as_deref()),
"capability_extensions": extensions,
"features": server_features(extensions),
},
"own_client_id": own,
"own_channel_id": own_channel,
@@ -518,6 +528,85 @@ mod tests {
use super::*;
use crate::rawcmd;
#[test]
fn admin_property_readback_omits_credentials_but_preserves_password_flags() {
let mut extras = RawExtras::default();
for verb in ["initserver", "notifyserveredited", "notifyserverupdated"] {
let packet = format!("{verb} virtualserver_name=Room virtualserver_flag_password=1 virtualserver_password=fixture virtualserver_keypair=fixture");
extras.apply(&rawcmd::parse(packet.as_bytes()).unwrap());
let row = extras.server_properties();
assert_eq!(row["virtualserver_name"], "Room");
assert_eq!(row["virtualserver_flag_password"], "1");
assert!(!row.contains_key("virtualserver_password") && !row.contains_key("virtualserver_keypair"));
}
for verb in ["channellist", "notifychannelcreated", "notifychanneledited"] {
let packet = format!("{verb} cid=8 channel_name=Room channel_flag_password=1 channel_password=fixture");
extras.apply(&rawcmd::parse(packet.as_bytes()).unwrap());
let row = extras.channel_properties(ChannelId(8), ChannelId(0), ChannelId(0)).unwrap();
assert_eq!(row["channel_name"], "Room");
assert_eq!(row["channel_flag_password"], "1");
assert!(row.get("channel_password").is_none());
}
}
#[test]
fn channel_description_invalidation_distinguishes_unknown_from_empty() {
let mut extras = RawExtras::default();
let apply = |extras: &mut RawExtras, bytes: &[u8]| {
let raw = rawcmd::parse(bytes).unwrap();
assert!(rawcmd::tap(raw.name.as_bytes()));
extras.apply(&raw)
};
apply(&mut extras, b"channellist cid=8 channel_name=One channel_description=Old|cid=9 channel_name=Two channel_description=Keep");
assert!(apply(&mut extras, b"notifychanneldescriptionchanged cid=8"));
let row = |extras: &RawExtras, id| extras.channel_properties(ChannelId(id), ChannelId(0), ChannelId(0)).unwrap();
let stale = row(&extras, 8);
assert!(stale.get("channel_description").is_none());
assert_eq!(stale["channel_name"], "One");
assert_eq!(row(&extras, 9)["channel_description"], "Keep");
assert!(!apply(&mut extras, b"notifychanneldescriptionchanged cid=42"));
apply(&mut extras, b"notifychanneledited cid=8 channel_description");
assert_eq!(row(&extras, 8)["channel_description"], "");
}
#[test]
fn channel_readback_uses_current_sibling_position_and_retains_extra_fields() {
let mut extras = RawExtras::default();
extras.apply(&rawcmd::parse(b"channellist cid=8 cpid=2 channel_order=3 channel_name=Music channel_banner_mode=2").unwrap());
extras.apply(&rawcmd::parse(b"notifychanneledited cid=8 channel_topic=Updated").unwrap());
let row = extras.channel_properties(ChannelId(8), ChannelId(0), ChannelId(7)).unwrap();
assert_eq!(row, json!({"cid":"8", "cpid":"0", "channel_order":"7", "channel_name":"Music", "channel_banner_mode":"2", "channel_topic":"Updated"}));
extras.apply(&rawcmd::parse(b"notifychanneldeleted cid=8").unwrap());
assert!(extras.channel_properties(ChannelId(8), ChannelId(0), ChannelId(0)).is_none());
}
#[test]
fn file_backend_and_snapshot_follow_complete_capability_announcements() {
use crate::file_transfer::{Files, ListBackend};
let mut extras = RawExtras::default();
let mut files = Files::default();
let advertised = format!("{}HTTPFT,s3", "extension,".repeat(104));
let announcement = format!("notifyserverupdated virtualserver_name=Test|virtualserver_capability_extensions={advertised}");
for (command, expected, backend) in [
(announcement.as_str(), Some(advertised.as_str()), ListBackend::S3),
("notifyserveredited virtualserver_name=Renamed", Some(advertised.as_str()), ListBackend::S3),
("notifyserveredited virtualserver_capability_extensions", Some(""), ListBackend::Legacy),
("initserver virtualserver_capability_extensions=s3", Some("s3"), ListBackend::S3),
("initserver virtualserver_name=Other", None, ListBackend::Legacy),
] {
let raw = rawcmd::parse(command.as_bytes()).unwrap();
extras.apply(&raw);
files.apply_raw(&raw);
let current = extras.server_properties().get("virtualserver_capability_extensions").map(String::as_str);
assert_eq!(current, expected);
assert_eq!(server_features(current)["file_transfer_s3"], json!(expected.map(|v| v.contains("s3"))));
let storage = files.storage();
assert_eq!(storage["httpft"], expected.is_some_and(|v| v.contains("HTTPFT")));
assert_eq!(storage["capability_extensions"], json!(expected.map(|v| v.chars().take(1024).collect::<String>())));
assert_eq!(files.list_backend(4).unwrap(), backend);
}
}
#[test]
fn raw_extras_track_banners_and_streaming() {
let mut x = RawExtras::default();
+40
View File
@@ -478,6 +478,46 @@ pub mod tests {
assert!(held.iter().all(Option::is_none));
}
#[test]
fn released_capture_cannot_restart_after_a_stalled_consumer() {
use crate::audio::{AudioIn, AudioInQueue};
use tsclientlib::{AudioSendGuard, AudioSendMetadata};
let queue = AudioInQueue::new();
let mut vad = VoiceGate::new(GateMode::VolumeGate { level_db: -30.0 });
assert_eq!(vad.push_captured(&captured_frame(&queue, 1)), Decision::Hold);
assert!(queue.try_push(captured_frame(&queue, 2)));
let Some(AudioIn::Frame(dequeued)) = queue.pop() else { panic!("missing dequeued frame") };
assert!(queue.try_push(captured_frame(&queue, 3)));
let metadata = |f: &CapturedFrame| AudioSendMetadata {
captured_at: f.captured_at, capture_epoch: f.capture_epoch, connection_generation: f.connection_generation,
};
// The last frame may already be encoded and awaiting socket readiness at key-up.
let pending_send = metadata(&dequeued);
let epoch = queue.invalidate();
queue.with_valid_audio(&pending_send, &mut || panic!("revoked packet sent before stall"));
std::thread::sleep(std::time::Duration::from_millis(600));
let mut preroll = std::array::from_fn(|_| None);
assert_eq!(vad.take_captured_preroll(&mut preroll), 1);
for frame in [dequeued, preroll[0].take().unwrap()] {
assert!(queue.with_valid_frame(&frame, || panic!("stale PCM encoded")).is_none());
queue.with_valid_audio(&metadata(&frame), &mut || panic!("stale PCM sent"));
}
assert!(matches!(queue.pop(), Some(AudioIn::End)));
assert!(queue.pop().is_none(), "release must discard the queued frame");
vad.reset();
let fresh = captured_frame(&queue, 20_000);
assert_eq!(fresh.capture_epoch, epoch);
assert!(queue.try_push(fresh));
let Some(AudioIn::Frame(fresh)) = queue.pop() else { panic!("missing fresh frame") };
assert_eq!(vad.push_captured(&fresh), Decision::Start);
assert_eq!(vad.take_captured_preroll(&mut preroll), 0);
let mut sent = false;
queue.with_valid_audio(&metadata(&fresh), &mut || sent = true);
assert!(sent, "fresh burst blocked after release");
}
#[test]
fn captured_preroll_is_revoked_by_every_routing_boundary() {
let queue = crate::audio::AudioInQueue::new();
+7 -3
View File
@@ -65,14 +65,18 @@ fn parse<T: for<'de> Deserialize<'de>>(raw: Option<&RawValue>) -> Result<T, Erro
#[serde(deny_unknown_fields)]
struct TransmitArgs {
mode: String,
#[serde(default)]
#[serde(default, deserialize_with = "crate::protocol::present_string")]
detector: Option<String>,
#[serde(default)]
#[serde(default, deserialize_with = "crate::protocol::present_string")]
sensitivity: Option<String>,
#[serde(default)]
#[serde(default, deserialize_with = "present_level")]
level_db: Option<f32>,
}
fn present_level<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<f32>, D::Error> {
f32::deserialize(d).map(Some)
}
/// `set_transmit`: `{mode:"direct"}` or `{mode:"vad", detector?: "automatic"|"volume_gate"|"hybrid",
/// sensitivity?: "high"|"normal"|"low" (automatic/hybrid), level_db: -50..=50 (volume_gate/hybrid)}`.
/// `None` = direct transmission.
+12 -13
View File
@@ -10,20 +10,19 @@ impl Session {
/// the old mode is sent under the new one. A changed sensitivity or level of the same detector (the
/// user moving the VAD level slider) applies from the next frame without interrupting speech.
pub(super) async fn set_transmit(&mut self, mode: Option<GateMode>) -> Result<Value, ErrorObj> {
let same_detector = matches!((mode, self.vad.as_ref()), (Some(new), Some(state))
if std::mem::discriminant(&new) == std::mem::discriminant(&state.gate.mode()));
if same_detector {
let state = self.vad.as_mut().expect("checked above");
state.gate.set_mode(mode.expect("checked above"));
} else {
let epoch = self.audio_in.invalidate();
self.tx_end().await;
match (mode, self.vad.as_mut()) {
(None, _) => self.vad = None,
(Some(m), Some(state)) => state.gate.set_mode(m),
(Some(m), None) => self.vad = Some(Box::new(VadState { gate: VoiceGate::new(m), route: None })),
match (mode, self.vad.as_mut()) {
(None, None) => (),
(Some(new), Some(state)) if std::mem::discriminant(&new) == std::mem::discriminant(&state.gate.mode()) => state.gate.set_mode(new),
_ => {
let epoch = self.audio_in.invalidate();
self.tx_end().await;
match (mode, self.vad.as_mut()) {
(None, _) => self.vad = None,
(Some(m), Some(state)) => state.gate.set_mode(m),
(Some(m), None) => self.vad = Some(Box::new(VadState { gate: VoiceGate::new(m), route: None })),
}
info!(epoch, "transmit queue invalidated for a mode change");
}
info!(epoch, "transmit queue invalidated for a mode change");
}
let result = voice_dsp::transmit_result(mode);
info!(mode = %result["mode"], detector = %result["detector"], sensitivity = %result["sensitivity"], level_db = %result["level_db"], "transmit mode applied");
+26 -5
View File
@@ -509,7 +509,7 @@ pub fn resolve(spec: &TargetSpec, view: &View) -> Result<Route, ErrorObj> {
ENTRY_CHANNEL if e.uuid == view.server_uid => {
if let Some(channel) = view.find_channel_by_path(&e.name) {
ids.channel(channel);
for c in view.clients.iter().filter(|c| c.channel == channel) {
for c in view.clients.iter().filter(|c| c.channel == channel && c.uid.is_some_and(|uid| !uid.is_empty())) {
ids.client(c.id);
}
}
@@ -528,10 +528,13 @@ pub fn resolve(spec: &TargetSpec, view: &View) -> Result<Route, ErrorObj> {
TargetSpec::Group { group_type, target_mode, group_id, server_uuid } => {
let by_group = *group_type == GROUP_SERVER_GROUP || *group_type == GROUP_CHANNEL_GROUP;
let target_id = if by_group {
if server_uuid.is_empty() || *server_uuid != view.server_uid || group_id.is_empty() || group_id == "0" {
if server_uuid.is_empty() || *server_uuid != view.server_uid {
return Err(invalid_list("group whisper list targets another server or no group"));
}
group_id.parse::<u64>().map_err(|_| invalid_list("group id is not a number"))?
if !group_id.bytes().all(|b| b.is_ascii_digit()) {
return Err(invalid_list("group id must be a positive decimal number"));
}
group_id.parse::<std::num::NonZeroU64>().map_err(|_| invalid_list("group id must be a positive decimal number"))?.get()
} else {
// Protocol: the id is ignored for channel commander / all clients (ts3protocol.md).
0
@@ -541,8 +544,8 @@ pub fn resolve(spec: &TargetSpec, view: &View) -> Result<Route, ErrorObj> {
TargetSpec::Ids { clients, channel_ids } => {
let mut ids = IdsBuilder::new();
for r in clients {
let expected = r.uid.as_deref().map(uid_bytes);
if view.client(r.id).is_some_and(|c| c.uid == expected.as_deref()) {
let Some(uid) = r.uid.as_deref().filter(|uid| !uid.is_empty()) else { continue };
if view.client(r.id).and_then(|c| c.uid).is_some_and(|current| current == uid_bytes(uid)) {
ids.client(r.id);
}
}
@@ -797,6 +800,12 @@ mod tests {
};
assert_eq!(resolve(&group(0, "6", SERVER), &v).unwrap(), Route::Group { whisper_type: 0, target: 1, target_id: 6 });
assert_eq!(resolve(&group(1, "8", SERVER), &v).unwrap(), Route::Group { whisper_type: 1, target: 1, target_id: 8 });
assert_eq!(resolve(&group(1, "008", SERVER), &v).unwrap(), Route::Group { whisper_type: 1, target: 1, target_id: 8 });
for id in ["00", "00000000000000000000", "+1", "18446744073709551616"] {
for kind in [GROUP_SERVER_GROUP, GROUP_CHANNEL_GROUP] {
assert_eq!(resolve(&group(kind, id, SERVER), &v).unwrap_err().detail, Some(json!({ "whisper": "invalid_list" })));
}
}
for invalid in [group(0, "6", "other"), group(0, "0", SERVER), group(1, "", SERVER), group(0, "x", SERVER), group(1, "8", "")] {
assert_eq!(resolve(&invalid, &v).unwrap_err().detail, Some(json!({ "whisper": "invalid_list" })));
}
@@ -821,6 +830,18 @@ mod tests {
assert_eq!(resolve(&empty, &v).unwrap_err().detail, Some(json!({ "whisper": "no_targets" })));
}
#[test]
fn unidentified_clients_are_not_individual_whisper_targets() {
let mut v = view();
v.clients[2].uid = None; // Bob is the only occupant of Games.
v.clients[3].uid = Some(b"");
let clients = vec![ClientRef { id: 3, uid: None }, ClientRef { id: 4, uid: Some(String::new()) }];
let direct = TargetSpec::Ids { clients, channel_ids: vec![] };
assert_eq!(resolve(&direct, &v).unwrap_err(), no_targets());
let list = TargetSpec::List { entries: vec![Entry { kind: ENTRY_CHANNEL, uuid: SERVER.into(), name: "Games".into() }] };
assert_eq!(ids(&resolve(&list, &v).unwrap()), (vec![2], vec![]));
}
#[test]
fn too_many_resolved_targets_are_refused() {
let names: Vec<String> = (0..300).map(|i| format!("c{i}")).collect();
+432
View File
@@ -99,6 +99,36 @@ fn cli(args: &[&std::ffi::OsStr]) -> (i32, Value) {
(out.status.code().unwrap(), v)
}
#[test]
fn invalid_recording_commands_leave_destination_and_status_untouched() {
let profile = TempDir::new("recording-protocol");
let destination = profile.0.join("takes");
std::fs::create_dir(&destination).unwrap();
let existing = destination.join("existing.wav");
std::fs::write(&existing, b"previous take").unwrap();
let mut core = Core::start(&profile.0);
for (cmd, args) in [
("recording_start", json!({"directory":destination,"mode":4})),
("recording_stop", json!({"force":true})),
("recording_pause", json!({"track_id":0})),
("recording_resume", json!({"track_id":0})),
("recording_status", json!({"session":0})),
("recording_info", json!({"track_id":0})),
("recording_waveform", json!({"track_id":0,"from_bucket":-1})),
] {
let (reply, events) = core.request(cmd, cmd, args);
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
assert!(!events.iter().any(|e| e["event"].as_str().is_some_and(|s| s.starts_with("recording_"))), "{cmd}: {events:?}");
}
let (reply, _) = core.request("status", "recording_status", json!({}));
assert_eq!(reply["result"], json!({"isRecording":false,"isPaused":false}));
let (reply, _) = core.request("info", "recording_info", json!({}));
assert_eq!(reply["result"], json!({"isRecording":false}));
core.shutdown();
assert_eq!(std::fs::read(existing).unwrap(), b"previous take");
assert_eq!(std::fs::read_dir(destination).unwrap().count(), 1);
}
#[test]
fn identity_lifecycle_over_stdio() {
let dir = TempDir::new("life");
@@ -228,9 +258,26 @@ fn base64_silence() -> String { "A".repeat(2560) }
fn client_menu_commands_are_validated_and_never_fake_success_offline() {
let dir=TempDir::new("menu-offline");
let mut core=Core::start(&dir.0);
let (unknown, _) = core.request("unknown", "unknown_request_qa", json!({}));
assert_eq!(unknown["ok"], false);
assert_eq!(unknown["error"]["code"], "unknown_command");
let (r,_)=core.request("ctx","client_context",json!({"client_id":42,"uid":"fixture"}));
assert_eq!(r["error"]["code"],"not_connected");
for args in [json!({"client_id":0,"uid":"fixture"}),json!({"client_id":65536,"uid":"fixture"}),
json!({"client_id":42,"uid":""}),json!({"client_id":42,"uid":"fixture","unexpected":true})] {
let (reply,_) = core.request("invalid-context","client_context",args);
assert_eq!(reply["error"]["code"],"bad_request","{reply}");
}
let (r,_)=core.request("invalid-stats","client_action",json!({"client_id":42,"uid":"fixture","generation":9_007_199_254_740_992u64,"action":"connection_info"}));
assert_eq!(r["error"]["code"],"bad_request","{r}");
for flag in [None,Some(json!(1)),Some(Value::Null)] {
let mut args=json!({"client_id":42,"uid":"fixture","generation":1,"action":"commander"});
if let Some(flag)=flag {args["enabled"]=flag;}
let (reply,_) = core.request("invalid-commander","client_action",args);
assert_eq!(reply["error"]["code"],"bad_request","{reply}");
}
let actions=[
json!({"action":"move_to_own_channel","expected_channel_id":9_007_199_254_740_991u64}),
json!({"action":"poke","message":"fixture"}),json!({"action":"connection_info"}),
json!({"action":"commander","enabled":true}),json!({"action":"server_group","group_id":6,"enabled":true}),
json!({"action":"channel_group","group_id":7,"channel_id":1}),json!({"action":"client_permissions"}),
@@ -246,6 +293,8 @@ fn client_menu_commands_are_validated_and_never_fake_success_offline() {
assert_eq!(r["error"]["code"],"not_connected","{r}");
}
for (i,args) in [
json!({"client_id":42,"uid":"fixture","generation":1,"action":"move_to_own_channel","expected_channel_id":0}),
json!({"client_id":42,"uid":"fixture","generation":1,"action":"move_to_own_channel","expected_channel_id":9_007_199_254_740_992u64}),
json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","value":3,"muted":false}),
json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":10.5,"muted":false}),
json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":-3.25,"muted":false}),
@@ -260,6 +309,389 @@ fn client_menu_commands_are_validated_and_never_fake_success_offline() {
core.shutdown();
}
#[test]
fn connect_and_disconnect_validate_arguments_before_network_io() {
let dir = TempDir::new("connection-args");
let mut core = Core::start(&dir.0);
for (field, value) in [
("address", json!("x".repeat(256))), ("address", json!("localhost\n")),
("channel", json!("")), ("channel", json!("x".repeat(513))),
("nickname", json!("x".repeat(65))), ("identity_id", Value::Null), ("identity_id", json!("other")),
("server_password", json!("x".repeat(256))), ("channel_password", json!("bad\tpassword")),
] {
let mut args = json!({"address":"127.0.0.1"}); args[field] = value;
let (reply, events) = core.request("invalid-connect", "connect", args);
assert_eq!(reply["error"]["code"], "bad_request", "{field}: {reply}");
assert!(!events.iter().any(|e| e["state"] == "connecting"));
}
let limit = "\u{10000}".repeat(40);
for args in [json!({"message":format!("{limit}x")}), json!({"message":"\r"}), json!({"message":null})] {
let (reply, _) = core.request("invalid-disconnect", "disconnect", args);
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
}
for valid in [json!({}), json!({"message":""}), json!({"message":limit})] {
let (reply, _) = core.request("valid-disconnect", "disconnect", valid);
assert_eq!(reply["error"]["code"], "not_connected", "{reply}");
}
core.shutdown();
}
#[test]
fn database_list_rejects_invalid_pages_before_connection_lookup() {
let dir = TempDir::new("database-pages");
let mut core = Core::start(&dir.0);
for (args, expected) in [
(json!({"start":0,"duration":1}), "not_connected"),
(json!({"start":u32::MAX,"duration":200}), "not_connected"),
(json!({"start":0,"duration":0}), "bad_request"),
(json!({"start":0,"duration":201}), "bad_request"),
(json!({"start":4294967296_u64,"duration":1}), "bad_request"),
(json!({"start":0,"duration":1,"unexpected":false}), "bad_request"),
] {
let (reply, _) = core.request("page", "client_database_list", args);
assert_eq!(reply["error"]["code"], expected, "{reply}");
}
core.shutdown();
}
#[test]
fn client_database_text_bounds_count_unicode_scalars_before_dispatch() {
let dir=TempDir::new("database-text-limits");
let mut core=Core::start(&dir.0);
for (cmd,field,max,mut args) in [
("client_database_find","pattern",255,json!({"uid":false})),
("client_database_id","uid",128,json!({})),
("client_info","uid",128,json!({"client_id":1})),
("server_group_member_add_uid","uid",128,json!({"generation":1,"group_id":1})),
] {
let limit="я".repeat(max-1)+"\u{1f3b5}";
for (value,expected) in [(limit.clone(),"not_connected"),(format!("{limit}x"),"bad_request"),
(String::new(),"bad_request"),("a\u{85}b".into(),"bad_request")] {
args[field]=json!(value);
let (reply,_)=core.request("text-boundary",cmd,args.clone());
assert_eq!(reply["error"]["code"],expected,"{cmd}.{field}: {reply}");
}
}
core.shutdown();
}
#[test]
fn unicode_group_names_are_validated_before_connecting() {
let dir=TempDir::new("unicode-group-names");
let mut core=Core::start(&dir.0);
let limit="я".repeat(127)+"\u{1f3b5}";
for (cmd,mut args) in [("group_add",json!({"generation":1,"kind":"server","type":1})),
("group_rename",json!({"generation":1,"kind":"channel","group_id":3}))] {
for (name,code) in [(limit.clone(),"not_connected"),(format!("{limit}x"),"bad_request"),("line\nbreak".into(),"bad_request")] {
args["name"]=json!(name);
let (reply,_)=core.request("group-name",cmd,args.clone());
assert_eq!(reply["error"]["code"],code,"{cmd}: {reply}");
}
}
core.shutdown();
}
#[test]
fn admin_ids_and_log_offsets_respect_the_safe_integer_boundary_before_connecting() {
let dir=TempDir::new("admin-integer-boundary");
let mut core=Core::start(&dir.0);
const MAX:u64=(1<<53)-1;
for (cmd,property,mut args) in [
("channel_create","channel_order",json!({"generation":1,"parent_id":0,"properties":{"channel_name":"Fixture"}})),
("channel_edit","channel_order",json!({"generation":1,"channel_id":2,"properties":{}})),
("server_edit","virtualserver_download_quota",json!({"generation":1,"confirm":"Fixture","properties":{}})),
("server_edit","virtualserver_default_server_group",json!({"generation":1,"confirm":"Fixture","properties":{}})),
] {
for (value,expected) in [(MAX,"not_connected"),(MAX+1,"bad_request")] {
args["properties"][property]=json!(value);
let (reply,_)=core.request("property-boundary",cmd,args.clone());
assert_eq!(reply["error"]["code"],expected,"{property}: {reply}");
}
}
for (cmd, field, mut args) in [
("channel_description", "channel_id", json!({})),
("channel_move", "parent_id", json!({"generation":1,"channel_id":2})),
("channel_move", "order", json!({"generation":1,"channel_id":2,"parent_id":0})),
("channel_create", "parent_id", json!({"generation":1,"properties":{"channel_name":"Fixture"}})),
("channel_info", "channel_id", json!({})),
("server_group_perm_list", "group_id", json!({})),
("temp_password_add", "channel_id", json!({"generation":1,"password":"fixture","duration_s":60})),
("server_log", "begin_pos", json!({"lines":1,"reverse":false,"instance":false})),
] {
for (value,expected) in [(MAX,"not_connected"),(MAX+1,"bad_request")] {
args[field]=json!(value);
let (reply,_)=core.request("boundary",cmd,args.clone());
assert_eq!(reply["error"]["code"],expected,"{cmd}.{field}: {reply}");
}
}
core.shutdown();
}
#[test]
fn talk_power_validates_its_captured_target_before_dispatch() {
let dir = TempDir::new("talk-power-args");
let mut core = Core::start(&dir.0);
let valid = json!({"generation":9_007_199_254_740_991u64,"client_id":65535,"uid":"peer=","grant":false});
for (field,value) in [("generation",json!(0)),("generation",json!(9_007_199_254_740_992u64)),
("client_id",json!(0)),("client_id",json!(65536)),("uid",json!("")),("grant",json!(1)),("unexpected",json!(true))] {
let mut args = valid.clone(); args[field] = value;
let (reply,_) = core.request("invalid", "talk_power", args);
assert_eq!(reply["error"]["code"], "bad_request", "{field}: {reply}");
}
let (reply,_) = core.request("valid", "talk_power", valid);
assert_eq!(reply["error"]["code"], "not_connected", "{reply}");
core.shutdown();
}
#[test]
fn status_messages_are_optional_but_must_be_valid_when_present() {
let dir=TempDir::new("status-message-args");
let mut core=Core::start(&dir.0);
for (cmd, flag, max) in [("set_away", "away", 80), ("talk_request", "request", 50)] {
let limit="\u{10000}".repeat(max);
for (enabled,msg) in [(true,Value::Null),(true,json!(format!("{limit}x"))),
(true,json!("bad\u{85}message")),(false,json!(""))] {
let mut args=json!({"message":msg});args[flag]=enabled.into();
let (reply,_) = core.request("invalid-status",cmd,args);
assert_eq!(reply["error"]["code"],"bad_request","{cmd}: {reply}");
}
for (enabled,msg) in [(true,Some(limit)),(false,None)] {
let mut args=json!({});args[flag]=enabled.into();
if let Some(msg)=msg {args["message"]=msg.into();}
let (reply,_) = core.request("valid-status",cmd,args);
assert_eq!(reply["error"]["code"],"not_connected","{cmd}: {reply}");
}
}
core.shutdown();
}
#[test]
fn poke_validates_utf8_bytes_before_connection_lookup() {
let dir = TempDir::new("poke-args"); let mut core = Core::start(&dir.0);
let exact = "\u{10000}".repeat(256);
for (message, expected) in [(String::new(),"bad_request"),(format!("{exact}x"),"bad_request"),
("no\nline".into(),"bad_request"),("no\u{7f}del".into(),"bad_request"),(exact,"not_connected")] {
let (reply,_) = core.request("poke", "client_action", json!({"client_id":2,"uid":"peer=","generation":1,"action":"poke","message":message}));
assert_eq!(reply["error"]["code"],expected,"{reply}");
}
core.shutdown();
}
#[test]
fn client_info_requires_explicit_client_identity() {
let dir = TempDir::new("client-info-args"); let mut core = Core::start(&dir.0);
for args in [json!({"client_id":0,"uid":"peer="}),json!({"client_id":65536,"uid":"peer="}),json!({"client_id":7}),json!({"client_id":7,"uid":""}),json!({"client_id":7,"uid":"peer=","unknown":true})] {
let (reply,_) = core.request("invalid-info","client_info",args); assert_eq!(reply["error"]["code"],"bad_request","{reply}");
}
let (reply,_) = core.request("offline-info","client_info",json!({"client_id":7,"uid":"peer="}));
assert_eq!(reply["error"]["code"],"not_connected","{reply}"); core.shutdown();
}
#[test]
fn transmit_stdio_distinguishes_missing_fields_from_null() {
let dir = TempDir::new("transmit-args");
let mut core = Core::start(&dir.0);
for mode in ["direct", "vad"] {
for field in ["detector", "sensitivity", "level_db"] {
let mut args = json!({"mode":mode});
args[field] = Value::Null;
let (reply, _) = core.request("invalid-transmit", "set_transmit", args);
assert_eq!(reply["error"]["code"], "bad_request", "{mode}.{field}: {reply}");
}
}
for (args, expected) in [
(json!({"mode":"direct"}), json!({"mode":"direct"})),
(json!({"mode":"vad"}), json!({"mode":"vad","detector":"automatic","sensitivity":"normal"})),
(json!({"mode":"vad","detector":"volume_gate","level_db":12.5}), json!({"mode":"vad","detector":"volume_gate","level_db":12.5})),
] {
let (reply, _) = core.request("valid-transmit", "set_transmit", args);
assert_eq!(reply["result"], expected, "{reply}");
}
core.shutdown();
}
#[test]
fn playback_dsp_stdio_requires_an_explicit_boolean_agc() {
let dir = TempDir::new("playback-dsp-args");
let mut core = Core::start(&dir.0);
for args in [json!({}), json!({"agc": null}), json!({"agc": 1}), json!({"agc": "false"}), json!({"agc": true, "gain": 1})] {
let (reply, _) = core.request("invalid-dsp", "set_playback_dsp", args);
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
}
for enabled in [true, false] {
let (reply, _) = core.request("valid-dsp", "set_playback_dsp", json!({"agc": enabled}));
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(reply["result"]["agc"], enabled);
}
core.shutdown();
}
#[test]
fn audio_flag_updates_are_partial_and_reject_explicit_null() {
let dir = TempDir::new("audio-flag-args");
let mut core = Core::start(&dir.0);
for (args, muted, deafened) in [(json!({"input_muted":true}), true, false),
(json!({"output_muted":true}), true, true), (json!({"input_muted":false}), false, true)] {
let (reply, _) = core.request("set", "set_audio", args);
assert_eq!(reply["result"], json!({"input_muted":muted,"output_muted":deafened,"transmitting":false}));
}
for invalid in [json!({"input_muted":null,"output_muted":false}),json!({"output_muted":null}),json!({"input_muted":"false"})] {
let (reply, _) = core.request("invalid", "set_audio", invalid);
assert_eq!(reply["error"]["code"], "bad_request");
}
let (reply, events) = core.request("read", "set_audio", json!({}));
assert_eq!(reply["result"], json!({"input_muted":false,"output_muted":true,"transmitting":false}));
assert!(events.iter().any(|e| e["event"]=="audio_state" && e["input_muted"]==false && e["output_muted"]==true));
core.shutdown();
}
#[test]
fn channel_queries_validate_arguments_before_connection_lookup() {
let dir = TempDir::new("channel-query-args");
let mut core = Core::start(&dir.0);
for cmd in ["channel_info", "channel_description", "channel_list"] {
let valid = if cmd == "channel_list" { json!({}) } else { json!({"channel_id": 1}) };
let mut extra = valid.clone(); extra["unexpected"] = json!(true);
for args in [extra, json!({"channel_id":0})] {
let (reply, _) = core.request("invalid", cmd, args);
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
}
let (reply, _) = core.request("valid", cmd, valid);
assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}");
}
core.shutdown();
}
#[test]
fn stdio_requires_objects_without_dispatching_positional_commands() {
let dir = TempDir::new("object-envelope");
let mut core = Core::start(&dir.0);
for (cmd, args) in [("profile_create", json!(["Positional"])), ("channel_description", json!([1])),
("admin_context", json!([])), ("shutdown", Value::Null)] {
let (reply, _) = core.request("invalid", cmd, args);
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
}
for input in [json!(["unexpected", "shutdown", {}]), json!({"id":"ignored", "cmd":"audio_end", "args":[]})] {
core.send(input);
let event = core.next();
assert_eq!(event["event"], "error", "{event}");
assert_eq!(event["error"]["code"], "bad_request");
assert!(event.get("id").is_none());
}
core.send(json!({"id":"alive", "cmd":"profile_get"}));
let profile = core.next();
assert_eq!(profile["id"], "alive");
assert_eq!(profile["ok"], true, "{profile}");
assert_eq!(profile["result"]["exists"], false, "{profile}");
core.shutdown();
}
#[test]
fn whisper_commands_reject_invalid_epochs_and_targets_before_connection_lookup() {
let dir = TempDir::new("whisper-args");
let mut core = Core::start(&dir.0);
let target = json!({"kind":"ids", "clients":[], "channel_ids":[1]});
for (cmd, args) in [
("whisper_start", json!({"epoch":0,"target":target})),
("whisper_start", json!({"epoch":1,"target":{"kind":"ids","clients":[],"channel_ids":[],"extra":true}})),
("whisper_stop", json!({"epoch":0})),
("whisper_stop", json!({"epoch":4294967296_u64})),
("whisper_stop", json!({"epoch":1,"extra":true})),
] {
let (reply, _) = core.request("invalid", cmd, args);
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
}
let (reply, _) = core.request("unheld", "whisper_stop", json!({"epoch":u32::MAX}));
assert_eq!(reply["result"], json!({"epoch":u32::MAX,"stopped":false}));
core.shutdown();
}
#[test]
fn channel_subscriptions_validate_arguments_before_connection_lookup() {
const SINGLE: &str = "channel_subscribe";
const ALL: &str = "channel_subscribe_all";
const MAX_CHANNEL_ID: u64 = (1 << 53) - 1;
let dir = TempDir::new("channel-subscription-args");
let mut core = Core::start(&dir.0);
for (cmd, args) in [
(SINGLE, json!({"channel_id": 1, "subscribe": true})),
(SINGLE, json!({"channel_id": MAX_CHANNEL_ID, "subscribe": false})),
(ALL, json!({"subscribe": true})),
(ALL, json!({"subscribe": false})),
] {
let (reply, _) = core.request("valid-subscription", cmd, args);
assert_eq!(reply["ok"], false, "{cmd}: {reply}");
assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}");
}
for (cmd, args) in [
(SINGLE, json!({"subscribe": true})),
(SINGLE, json!({"channel_id": 0, "subscribe": true})),
(SINGLE, json!({"channel_id": -1, "subscribe": false})),
(SINGLE, json!({"channel_id": 1.5, "subscribe": true})),
(SINGLE, json!({"channel_id": "1", "subscribe": true})),
(SINGLE, json!({"channel_id": MAX_CHANNEL_ID + 1, "subscribe": false})),
(SINGLE, json!({"channel_id": 1})),
(SINGLE, json!({"channel_id": 1, "subscribe": null})),
(SINGLE, json!({"channel_id": 1, "subscribe": 1})),
(SINGLE, json!({"channel_id": 1, "subscribe": "false"})),
(SINGLE, json!({"channel_id": 1, "subscribe": false, "generation": 1})),
(SINGLE, json!([1, false])),
(ALL, json!({})),
(ALL, json!({"subscribe": null})),
(ALL, json!({"subscribe": 0})),
(ALL, json!({"subscribe": "true"})),
(ALL, json!({"channel_id": 1, "subscribe": false})),
(ALL, json!([true])),
] {
let (reply, _) = core.request("invalid-subscription", cmd, args.clone());
assert_eq!(reply["ok"], false, "{cmd} with {args}: {reply}");
assert_eq!(reply["error"]["code"], "bad_request", "{cmd} with {args}: {reply}");
}
core.shutdown();
}
#[test]
fn file_browser_rejects_invalid_list_before_connection() {
let dir = TempDir::new("file-list-boundary");
let mut core = Core::start(&dir.0);
for args in [json!({"channel_id":0,"path":"/"}), json!({"channel_id":9_007_199_254_740_992u64,"path":"/"}),
json!({"channel_id":1,"path":"/a/../b"}), json!({"channel_id":1,"path":"/","unexpected":true})] {
let (reply, _) = core.request("invalid-list", "file_list", args);
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
}
let (reply, _) = core.request("valid-list", "file_list", json!({"channel_id":9_007_199_254_740_991u64,"path":"/"}));
assert_eq!(reply["error"]["code"], "not_connected", "{reply}");
for args in [json!({"channel_id":0,"path":"/image.png"}), json!({"channel_id":1,"path":"/images/"}),
json!({"channel_id":1,"path":"/image.png","destination":"unapproved"})] {
let (reply, _) = core.request("invalid-image", "file_fetch_image", args);
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
}
let (reply, _) = core.request("invalid-history", "file_transfers", json!({"channel_id":1}));
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
let (reply, _) = core.request("offline-history", "file_transfers", json!({}));
assert_eq!(reply["error"]["code"], "not_connected", "{reply}");
core.shutdown();
}
#[test]
fn transfer_controls_validate_the_id_before_connection_lookup() {
let dir = TempDir::new("transfer-control-ids");
let mut core = Core::start(&dir.0);
for cmd in ["file_cancel", "file_pause", "file_resume"] {
for id in [0, u64::from(u32::MAX) + 1] {
let (reply, _) = core.request("invalid-id", cmd, json!({"transfer_id":id}));
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
}
for id in [1, u32::MAX] {
let (reply, _) = core.request("valid-id", cmd, json!({"transfer_id":id}));
assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}");
}
}
core.shutdown();
}
#[test]
fn publisher_commands_validate_through_real_stdio_without_server() {
let dir = TempDir::new("publisher");
+26 -1
View File
@@ -33,13 +33,38 @@ async fn embedded_identity_survives_repeated_worker_lifetimes() {
again.shutdown().await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn transmit_mode_invalidates_frames_only_on_detector_change() {
use teamspeach_core::{audio::CapturedFrame, protocol::FRAME_SAMPLES, vad::GateMode};
let profile = Profile::new();
let (core, _events) = spawn(profile.config(1)).unwrap();
let direct = core.audio_epoch();
let frame = |capture_epoch| CapturedFrame { pcm: [1; FRAME_SAMPLES], captured_at: std::time::Instant::now(),
connection_generation: core.connection_generation(), capture_epoch, whisper: None };
let result = core.request(Command::SetTransmit { vad: None }).await.unwrap();
assert_eq!(result["mode"], "direct");
assert!(core.push_audio(frame(direct)));
core.request(Command::SetTransmit { vad: Some(GateMode::VolumeGate { level_db: -30. }) }).await.unwrap();
let vad = core.audio_epoch();
assert!(!core.push_audio(frame(direct)));
core.request(Command::SetTransmit { vad: Some(GateMode::VolumeGate { level_db: -25. }) }).await.unwrap();
assert!(core.push_audio(frame(vad)));
core.request(Command::SetTransmit { vad: None }).await.unwrap();
assert!(!core.push_audio(frame(vad)));
core.shutdown().await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn native_requests_validate_before_session_dispatch() {
use teamspeach_core::protocol::{ErrorCode, TextTarget};
let profile = Profile::new();
let (core, _events) = spawn(profile.config(1)).unwrap();
for (id, expected) in [(0, ErrorCode::BadRequest), (1, ErrorCode::NotConnected)] {
let error = core.request(Command::JoinChannel { channel_id: id, password: None }).await.unwrap_err();
assert_eq!(error.code, expected);
}
let error = core.request(Command::SendText { target: TextTarget::Client, client_id: None,
expected_client_uid: None, message: "private".into() }).await.unwrap_err();
expected_client_uid: None, expected_channel_id: None, message: "private".into() }).await.unwrap_err();
assert_eq!(error.code, ErrorCode::BadRequest);
let error = core.request(Command::StreamSignal { stream_id: "s1".into(), client_id: 1, json: "[]".into() }).await.unwrap_err();
assert_eq!(error.code, ErrorCode::BadRequest);
+22 -3
View File
@@ -7,9 +7,9 @@
- Authors: Flakebi and the ReSpeak contributors.
- License: dual MIT OR Apache-2.0 — see `tsclientlib/LICENSE-MIT` and
`tsclientlib/LICENSE-APACHE` (copied verbatim from the upstream repository root).
- `tsclientlib` and `tsproto` are vendored from that revision. `ts-bookkeeping`,
`tsproto-packets` and `tsproto-types` remain pinned git dependencies. The root workspace
patch selects the local `tsproto` for every consumer.
- `tsclientlib`, `tsproto` and `tsproto-packets` are vendored from that revision.
`ts-bookkeeping` and `tsproto-types` remain pinned git dependencies. The root workspace
patches select the local `tsproto` and `tsproto-packets` for every consumer.
### Local modifications
@@ -41,6 +41,7 @@ the historical patch alone no longer reproduces the complete tree.
6. `src/lib.rs`: `AudioSendMetadata`, `AudioSendGuard` and `send_audio_guarded` forward
original capture time, connection generation and privacy epoch to the transport. Ordinary
`send_audio` remains for non-capture end markers and existing third-party callers.
7. `src/audio.rs`: `AudioQueue::has_pending_whisper` identifies decoder and jitter-buffer state that must be discarded when the receiver switches to Deny All, even after a whisper end marker arrived.
## `tsproto/`
@@ -51,3 +52,21 @@ socket send attempt, including a retry after backpressure, the guard synchronize
invalidation and refuses expired or revoked packets. Guarded media is bounded separately from
unmodified acknowledgement/control/end-marker traffic. This prevents muted or previous-session
audio from escaping merely because it was encoded before a privacy boundary.
## `tsproto-packets/`
The six package files come from upstream `utils/tsproto-packets/` at the revision above;
`LICENSE-MIT` and `LICENSE-APACHE` are copied verbatim from the upstream root. This crate
has no sibling dependencies to re-pin. A local `[workspace]` lets the regression tests
run independently of the application workspace.
`src/commands.rs` now accepts `_` alongside ASCII alphanumerics in command names, so
TeamSpeak 6 commands such as `notify_s3ft_file_list` retain their wire names. A name still
ends at an ASCII space or at the end of the input. Argument-only input, multipart
separators and escaping are unchanged.
Run the public API regression tests from the repository root:
```sh
cargo test --manifest-path core/vendor/tsproto-packets/Cargo.toml --test command_grammar
```
+7
View File
@@ -209,6 +209,13 @@ impl AudioQueue {
pub fn get_decoder(&self) -> &Decoder { &self.decoder }
pub fn is_whispering(&self) -> bool { self.whispering }
/// A whisper may still play from buffered packets, decoded samples or loss concealment.
pub fn has_pending_whisper(&self) -> bool {
self.whispering || self.packet_buffer.iter().any(|p| {
matches!(p.packet.data().data(), AudioData::S2CWhisper { data, .. } if data.len() > 1)
})
}
/// Size is in samples.
fn add_buffer_size(&mut self, size: usize) {
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
+172
View File
@@ -0,0 +1,172 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "omnom"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66562a92c66d5937e9d549597c2d3cafe3d2367dd08dc257da730587c2cfc218"
dependencies = [
"memchr",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "self_cell"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "tsproto-packets"
version = "0.1.0"
dependencies = [
"base64",
"bitflags",
"num-derive",
"num-traits",
"omnom",
"self_cell",
"serde",
"thiserror",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "tsproto-packets"
version = "0.1.0"
authors = ["Flakebi <flakebi@t-online.de>"]
description = "Parse and serialize TeamSpeak packets and commands."
repository = "https://github.com/ReSpeak/tsclientlib/tree/master/utils/tsproto-packets"
readme = "README.md"
keywords = ["teamspeak3", "ts3"]
license = "MIT OR Apache-2.0"
edition = "2018"
include = [
"/Cargo.toml",
"/README.md",
"/src/*.rs",
]
[dependencies]
base64 = "0.22"
bitflags = "2"
num-derive = "0.4"
num-traits = "0.2"
omnom = "3"
self_cell = "1"
serde = { version = "1", features = ["derive"] }
thiserror = "2"
# Keep standalone packet regression tests out of the application's package set.
[workspace]
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017-2020 tsclientlib contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+10
View File
@@ -0,0 +1,10 @@
# tsproto-packets [![docs.rs](https://docs.rs/tsproto-packets/badge.svg)](https://docs.rs/tsproto-packets)
`tsproto-packets` parses and serializes TeamSpeak packets and commands.
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
+10
View File
@@ -0,0 +1,10 @@
# tsproto-packets [![docs.rs](https://docs.rs/tsproto-packets/badge.svg)](https://docs.rs/tsproto-packets)
{{readme}}
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
+294
View File
@@ -0,0 +1,294 @@
use std::borrow::Cow;
use std::str::{self, FromStr};
use crate::{Error, Result};
/// Parses arguments of a command.
#[derive(Clone, Debug)]
pub struct CommandParser<'a> {
data: &'a [u8],
index: usize,
}
#[derive(Clone, Debug)]
pub enum CommandItem<'a> {
Argument(CommandArgument<'a>),
/// Pipe symbol marking the start of the next command.
NextCommand,
}
#[derive(Clone, Debug)]
pub struct CommandArgument<'a> {
name: &'a [u8],
value: CommandArgumentValue<'a>,
}
#[derive(Clone, Debug)]
pub struct CommandArgumentValue<'a> {
raw: &'a [u8],
/// The number of escape sequences in this value.
escapes: usize,
}
impl<'a> CommandParser<'a> {
/// Returns the name and arguments of the given command.
#[inline]
pub fn new(data: &'a [u8]) -> (&'a [u8], Self) {
let mut name_end = 0;
while name_end < data.len() {
let byte = data[name_end];
if !byte.is_ascii_alphanumeric() && byte != b'_' {
if byte == b' ' {
break;
}
// Not a command name
name_end = 0;
break;
}
name_end += 1;
}
(&data[..name_end], Self { data, index: name_end })
}
fn cur(&self) -> u8 { self.data[self.index] }
fn cur_in(&self, cs: &[u8]) -> bool { cs.contains(&self.cur()) }
/// Advance
fn adv(&mut self) { self.index += 1; }
fn at_end(&self) -> bool { self.index >= self.data.len() }
fn skip_space(&mut self) {
while !self.at_end() && self.cur_in(b"\x0b\x0c\t\r\n ") {
self.adv();
}
}
}
impl<'a> Iterator for CommandParser<'a> {
type Item = CommandItem<'a>;
fn next(&mut self) -> Option<Self::Item> {
self.skip_space();
if self.at_end() {
return None;
}
if self.cur() == b'|' {
self.adv();
return Some(CommandItem::NextCommand);
}
let name_start = self.index;
while !self.at_end() && !self.cur_in(b" =|") {
self.adv();
}
let name_end = self.index;
if self.at_end() || self.cur() != b'=' {
return Some(CommandItem::Argument(CommandArgument {
name: &self.data[name_start..name_end],
value: CommandArgumentValue { raw: &[], escapes: 0 },
}));
}
self.adv();
let value_start = self.index;
let mut escapes = 0;
while !self.at_end() {
if self.cur_in(b"\x0b\x0c\t\r\n| ") {
break;
}
if self.cur() == b'\\' {
escapes += 1;
self.adv();
if self.at_end() || self.cur_in(b"\x0b\x0c\t\r\n| ") {
break;
}
}
self.adv();
}
let value_end = self.index;
Some(CommandItem::Argument(CommandArgument {
name: &self.data[name_start..name_end],
value: CommandArgumentValue { raw: &self.data[value_start..value_end], escapes },
}))
}
}
impl<'a> CommandArgument<'a> {
#[inline]
pub fn name(&self) -> &'a [u8] { self.name }
#[inline]
pub fn value(&self) -> &CommandArgumentValue<'a> { &self.value }
}
impl<'a> CommandArgumentValue<'a> {
fn unescape(&self) -> Vec<u8> {
let mut res = Vec::with_capacity(self.raw.len() - self.escapes);
let mut i = 0;
while i < self.raw.len() {
if self.raw[i] == b'\\' {
i += 1;
if i == self.raw.len() {
return res;
}
res.push(match self.raw[i] {
b'v' => b'\x0b',
b'f' => b'\x0c',
b't' => b'\t',
b'r' => b'\r',
b'n' => b'\n',
b'p' => b'|',
b's' => b' ',
c => c,
});
} else {
res.push(self.raw[i]);
}
i += 1;
}
res
}
#[inline]
pub fn get_raw(&self) -> &'a [u8] { self.raw }
#[inline]
pub fn get(&self) -> Cow<'a, [u8]> {
if self.escapes == 0 { Cow::Borrowed(self.raw) } else { Cow::Owned(self.unescape()) }
}
#[inline]
pub fn get_str(&self) -> Result<Cow<'a, str>> {
if self.escapes == 0 {
Ok(Cow::Borrowed(str::from_utf8(self.raw)?))
} else {
Ok(Cow::Owned(String::from_utf8(self.unescape())?))
}
}
#[inline]
pub fn get_parse<E, T: FromStr>(&self) -> std::result::Result<T, E>
where
E: From<<T as FromStr>::Err>,
E: From<Error>,
{
Ok(self.get_str()?.as_ref().parse()?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::packets::{Direction, Flags, OutCommand, PacketType};
use std::str;
/// Parse and write again.
fn test_loop_with_result(data: &[u8], result: &[u8]) {
let (name, parser) = CommandParser::new(data);
let name = str::from_utf8(name).unwrap();
let mut out_command =
OutCommand::new(Direction::S2C, Flags::empty(), PacketType::Command, name);
println!("\nParsing {}", str::from_utf8(data).unwrap());
for item in parser {
println!("Item: {:?}", item);
match item {
CommandItem::NextCommand => out_command.start_new_part(),
CommandItem::Argument(arg) => {
out_command.write_arg(
str::from_utf8(arg.name()).unwrap(),
&arg.value().get_str().unwrap(),
);
}
}
}
let packet = out_command.into_packet();
let in_str = str::from_utf8(result).unwrap();
let out_str = str::from_utf8(packet.content()).unwrap();
assert_eq!(in_str, out_str);
}
/// Parse and write again.
fn test_loop(data: &[u8]) { test_loop_with_result(data, data); }
const TEST_COMMANDS: &[&str] = &[
"cmd a=1 b=2 c=3",
"cmd a=\\s\\\\ b=\\p c=abc\\tdef",
"cmd a=1 c=3 b=2|b=4|b=5",
"initivexpand2 l=AQCVXTlKF+UQc0yga99dOQ9FJCwLaJqtDb1G7xYPMvHFMwIKVfKADF6zAAcAAAAgQW5vbnltb3VzAAAKQo71lhtEMbqAmtuMLlY8Snr0k2Wmymv4hnHNU6tjQCALKHewCykgcA== beta=\\/8kL8lcAYyMJovVOP6MIUC1oZASyuL\\/Y\\/qjVG06R4byuucl9oPAvR7eqZI7z8jGm9jkGmtJ6 omega=MEsDAgcAAgEgAiBxu2eCLQf8zLnuJJ6FtbVjfaOa1210xFgedoXuGzDbTgIgcGk35eqFavKxS4dROi5uKNSNsmzIL4+fyh5Z\\/+FWGxU= ot=1 proof=MEUCIQDRCP4J9e+8IxMJfCLWWI1oIbNPGcChl+3Jr2vIuyDxzAIgOrzRAFPOuJZF4CBw\\/xgbzEsgKMtEtgNobF6WXVNhfUw= tvd time=1544221457",
"clientinitiv alpha=41Te9Ar7hMPx+A== omega=MEwDAgcAAgEgAiEAq2iCMfcijKDZ5tn2tuZcH+\\/GF+dmdxlXjDSFXLPGadACIHzUnbsPQ0FDt34Su4UXF46VFI0+4wjMDNszdoDYocu0 ip",
// Well, that's more corrupted packet, but the parser should be robust
"initserver virtualserver_name=Server\\sder\\sVerplanten \
virtualserver_welcomemessage=This\\sis\\sSplamys\\sWorld \
virtualserver_platform=Linux \
virtualserver_version=3.0.13.8\\s[Build:\\s1500452811] \
virtualserver_maxclients=32 virtualserver_created=0 \
virtualserver_nodec_encryption_mode=1 \
virtualserver_hostmessage=Lé\\sServer\\sde\\sSplamy \
virtualserver_name=Server_mode=0 virtualserver_default_server \
group=8 virtualserver_default_channel_group=8 \
virtualserver_hostbanner_url virtualserver_hostmessagegfx_url \
virtualserver_hostmessagegfx_interval=2000 \
virtualserver_priority_speaker_dimm_modificat",
"channellist cid=2 cpid=0 channel_name=Trusted\\sChannel \
channel_topic channel_codec=0 channel_codec_quality=0 \
channel_maxclients=0 channel_maxfamilyclients=-1 channel_order=1 \
channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 \
channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 \
channel_delete_delay=0 channel_flag_maxclients_unlimited=0 \
channel_flag_maxfamilyclients_unlimited=0 \
channel_flag_maxfamilyclients_inherited=1 \
channel_needed_talk_power=0 channel_forced_silence=0 \
channel_name_phonetic channel_icon_id=0 \
channel_flag_private=0|cid=4 cpid=2 \
channel_name=Ding\\s•\\s1\\s\\p\\sSplamy´s\\sBett channel_topic \
channel_codec=4 channel_codec_quality=7 channel_maxclients=-1 \
channel_maxfamilyclients=-1 channel_order=0 \
channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 \
channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 \
channel_delete_delay=0 channel_flag_maxclients_unlimited=1 \
channel_flag_maxfamilyclients_unlimited=0 \
channel_flag_maxfamilyclients_inherited=1 \
channel_needed_talk_power=0 channel_forced_silence=0 \
channel_name_phonetic=Neo\\sSeebi\\sEvangelion channel_icon_id=0 \
channel_flag_private=0", //|cid=6 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s2\\s\\p\\sThe\\sBook\\sof\\sHeavy\\sMetal channel_topic channel_codec=2 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=4 channel_flag_permanent=1 channel_flag_semi_permanent=0 channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 channel_delete_delay=0 channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=Not\\senought\\sChannels channel_icon_id=0 channel_flag_private=0|cid=30 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s3\\s\\p\\sSenpai\\sGef\xc3\xa4hrlich channel_topic channel_codec=2 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=6 channel_flag_permanent=1 channel_flag_semi_permanent=0 channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 channel_delete_delay=0 channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=The\\strashcan\\shas\\sthe\\strash channel_icon_id=0 channel_flag_private=0",
"notifychannelsubscribed cid=2|cid=4 es=3867|cid=5 es=18694|cid=6 es=18694|cid=7 es=18694|cid=11 es=18694|cid=13 es=18694|cid=14 es=18694|cid=16 es=18694|cid=22 es=18694|cid=23 es=18694|cid=24 es=18694|cid=25 es=18694|cid=30 es=18694|cid=163 es=18694",
"notifypermissionlist group_id_end=0|group_id_end=7|group_id_end=13|group_id_end=18|group_id_end=21|group_id_end=21|group_id_end=33|group_id_end=47|group_id_end=77|group_id_end=82|group_id_end=83|group_id_end=106|group_id_end=126|group_id_end=132|group_id_end=143|group_id_end=151|group_id_end=160|group_id_end=162|group_id_end=170|group_id_end=172|group_id_end=190|group_id_end=197|group_id_end=215|group_id_end=227|group_id_end=232|group_id_end=248|permname=b_serverinstance_help_view permdesc=Retrieve\\sinformation\\sabout\\sServerQuery\\scommands|permname=b_serverinstance_version_view permdesc=Retrieve\\sglobal\\sserver\\sversion\\s(including\\splatform\\sand\\sbuild\\snumber)|permname=b_serverinstance_info_view permdesc=Retrieve\\sglobal\\sserver\\sinformation|permname=b_serverinstance_virtualserver_list permdesc=List\\svirtual\\sservers\\sstored\\sin\\sthe\\sdatabase",
// Server query
"cmd=1 cid=2",
"channellistfinished",
// With newlines
"sendtextmessage text=\\nmess\\nage\\n return_code=11",
];
#[test]
fn loop_test() {
for cmd in TEST_COMMANDS {
test_loop(cmd.as_bytes());
}
}
#[test]
fn optional_arg() {
test_loop(b"cmd a");
test_loop(b"cmd a b=1");
test_loop_with_result(b"cmd a=", b"cmd a");
test_loop_with_result(b"cmd a= b=1", b"cmd a b=1");
}
#[test]
fn no_slash_escape() {
let in_cmd = "clientinitiv alpha=giGMvmfHzbY3ig== omega=MEsDAgcAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC/50= ot=1 ip";
let out_cmd = "clientinitiv alpha=giGMvmfHzbY3ig== omega=MEsDAgcAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITsC\\/50= ot=1 ip";
test_loop_with_result(in_cmd.as_bytes(), out_cmd.as_bytes());
}
}
+62
View File
@@ -0,0 +1,62 @@
//! `tsproto-packets` parses and serializes TeamSpeak packets and commands.
use std::fmt;
use thiserror::Error;
pub mod commands;
pub mod packets;
type Result<T, E = Error> = std::result::Result<T, E>;
pub const S2C_HEADER_LEN: usize = 11;
pub const C2S_HEADER_LEN: usize = 13;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Base64(#[from] base64::DecodeError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
ParseInt(#[from] std::num::ParseIntError),
#[error(transparent)]
Utf8(#[from] std::str::Utf8Error),
#[error(transparent)]
StringUtf8(#[from] std::string::FromUtf8Error),
#[error("Invalid init step {0}")]
InvalidInitStep(u8),
#[error("Invalid audio codec {0}")]
InvalidCodec(u8),
#[error("Packet content is too short (length {0})")]
PacketContentTooShort(usize),
#[error("Packet is too short (length {0})")]
PacketTooShort(usize),
#[error("Cannot parse command ({0})")]
ParseCommand(String),
#[error("Got a packet with unknown type ({0})")]
UnknownPacketType(u8),
#[error("Tried to parse a packet from the wrong direction")]
WrongDirection,
#[error("Wrong mac, expected TS3INIT1 but got {0:?}")]
WrongInitMac(Vec<u8>),
#[error("Wrong packet type ({0:?})")]
WrongPacketType(packets::PacketType),
}
pub struct HexSlice<'a, T: fmt::LowerHex + 'a>(pub &'a [T]);
impl<'a> fmt::Display for HexSlice<'a, u8> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Hex[")?;
if let Some((l, m)) = self.0.split_last() {
for b in m {
write!(f, "{:02x} ", b)?;
}
write!(f, "{:02x}", l)?;
}
write!(f, "]")
}
}
File diff suppressed because it is too large. Load diff
+48
View File
@@ -0,0 +1,48 @@
use tsproto_packets::commands::{CommandItem, CommandParser};
#[test]
fn accepts_underscore_and_legacy_alphanumerics_in_command_names() {
for input in [b"notify_s3ft_file_list".as_slice(), b"initivexpand2", b"Az09", b"_x_"] {
let (name, mut args) = CommandParser::new(input);
assert_eq!(name, input);
assert!(args.next().is_none());
}
}
#[test]
fn preserves_arguments_when_there_is_no_command_name() {
for (input, expected_key) in [
(b"client_name=123".as_slice(), b"client_name".as_slice()),
(b" client_name=123", b"client_name"),
(b"invalid-name=123", b"invalid-name"),
(b"invalid\xff=123", b"invalid\xff"),
] {
let (name, mut args) = CommandParser::new(input);
assert!(name.is_empty());
let Some(CommandItem::Argument(arg)) = args.next() else {
panic!("expected the first argument in {input:?}");
};
assert_eq!(arg.name(), expected_key);
assert_eq!(arg.value().get_raw(), b"123");
assert!(args.next().is_none());
}
}
#[test]
fn preserves_multipart_arguments_and_escapes_after_underscore_command() {
let (name, mut args) = CommandParser::new(br"notify_s3ft_file_list name=\v\f\t\r\n\p\s\/\\|name=next");
assert_eq!(name, b"notify_s3ft_file_list");
let Some(CommandItem::Argument(first)) = args.next() else {
panic!("expected the first list entry");
};
assert_eq!(first.name(), b"name");
assert_eq!(first.value().get_raw(), br"\v\f\t\r\n\p\s\/\\");
assert_eq!(first.value().get_str().unwrap(), "\x0b\x0c\t\r\n| /\\");
assert!(matches!(args.next(), Some(CommandItem::NextCommand)));
let Some(CommandItem::Argument(second)) = args.next() else {
panic!("expected the second list entry");
};
assert_eq!(second.name(), b"name");
assert_eq!(second.value().get_raw(), b"next");
assert!(args.next().is_none());
}
+128 -35
View File
@@ -59,7 +59,7 @@ Request (stdin):
(high-rate, never answered; an `id` there is ignored).
- `cmd`: one of the commands in §4. Unknown `cmd` → `unknown_command`.
- `args`: object; may be omitted when a command takes no arguments.
Unknown argument keys are rejected (`bad_request`).
Explicit `null`, positional arrays and unknown argument keys are rejected (`bad_request`).
Response (stdout), exactly one per request with `id`:
@@ -105,7 +105,7 @@ branch on human-readable message wording.
| `not_connected` | command needs an active connection |
| `already_connected` | `connect` while connecting/connected |
| `connect_failed` | could not connect (resolve, timeout, server refused …; `ts_error` when the server sent one) |
| `server_error` | server answered a command with an error (`ts_error` set) |
| `server_error` | server rejected a command (`ts_error` set), or its required response data was invalid or did not arrive by the deadline (§4.19) |
| `audio_format` | `audio_frame.pcm` not 1920 bytes after base64 decode |
| `audio_overflow` | outgoing PCM queue full, oldest frames dropped (event, throttled ≤1/s) |
| `audio_muted` | `audio_frame` while input or output muted; frames discarded (event, once per burst) |
@@ -165,7 +165,7 @@ Nickname rules: after trimming, 3–30 Unicode scalar values, no control charact
### 4.4 `connect` — `{address, server_password?, channel?, channel_password?, identity_id?, nickname?}`
- `address`: `host`, `host:port`, `[v6]:port` (default port 9987). Not a path.
- `server_password`: optional string.
- String limits at the request boundary count UTF-16 code units: address 1–255, server and channel passwords 0–255, channel 1–512, nickname override 1–64. These fields reject ASCII control characters and DEL. Omit optional fields rather than supplying JSON null.
- `channel`: optional initial channel, either numeric channel id string `"cid:12"` or a
path `"Parent/Child"`.
- `identity_id`: selected vault UID; omitted selects the default. Server-demanded proof-of-work is handled by the bounded identity CLI, not automatically during connect.
@@ -198,6 +198,8 @@ against every program running as that user. Platform hardware key-store acceptan
### 4.5 `disconnect` — `{message?: string}`
An explicit message is single-line and at most 80 UTF-16 code units; the empty string is allowed.
Sends a clean `clientdisconnect` and waits (≤ 3 s) for the server. Result
`{"clean": true}` when the server confirmed, `{"clean": false}` on timeout or when a
pending connect attempt was abandoned. `not_connected` if idle. Emits
@@ -205,12 +207,13 @@ pending connect attempt was abandoned. `not_connected` if idle. Emits
### 4.6 `join_channel` — `{channel_id: number, password?: string}`
Moves self (`clientmove`). Result `{}` after the server confirms; snapshot follows.
Moves self (`clientmove`). A zero channel ID returns `bad_request` before checking the connection or sending anything. Result `{}` after the server confirms; snapshot follows.
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, expected_client_uid?: string, message: string}`
### 4.7 `send_text` — `{target: "channel"|"server"|"client", client_id?: number, expected_client_uid?: string, expected_channel_id?: number, message: string}`
`client_id` and `expected_client_uid` are required iff `target = "client"`. Native rechecks the UID immediately before sending, otherwise `target_changed`. Message 1–8192 bytes UTF-8;
TeamSpeak escaping is done by the core. Result `{}` after server confirmation.
For channel chat the native client supplies `expected_channel_id`. This is a positive ID checked against the core's current own channel before enqueue. A mismatch returns `target_changed`; the field never addresses another channel. Diagnostic requests may omit it to send to the current channel.
The server echoes our own messages as `text` events (verified live for private messages:
the sender receives exactly one `text` with `to_client_id` = recipient); the core adds no
synthetic echo.
@@ -222,6 +225,9 @@ flags (`client_input_muted` / `client_output_muted`) when connected, and the cor
gates: while `input_muted || output_muted` outgoing frames are discarded; while
`output_muted` no `audio` events are emitted. Allowed when disconnected (applied at
next connect). Result = audio state object; emits `audio_state`.
Omitting a flag preserves its previous value. Explicit null is not a boolean and
returns `bad_request`. With neither flag supplied, the command reports state without
updating the server, ending a transmission, or revoking the current capture permit.
Initial state at process start: both `false`.
### 4.9 `audio_frame` — `{pcm: string, whisper?: u32}` (no `id`, no response)
@@ -260,14 +266,23 @@ The ignored Rust `captured_speech_quality_matrix` accepts `TEAMSPEACH_AUDIT_PCM`
`TEAMSPEACH_AUDIT_OUT` for real encoding/receiving at quality 0/6/10, both codecs and a context reset.
File-fed/generated media does not prove natural microphone quality, private DSP identity or Asahi hardware.
A separate two-way core CLI run with silent disposable profiles verified synthetic voice over the
server: 99 of 101 received frames matched the expected 900 Hz tone and 100 of 101 matched the
expected 500 Hz tone in the reverse direction. No real microphone or playback device was used;
official-client peer and acoustic/device validation remain pending.
### 4.10 `audio_end` — no args (no `id`, no response)
Ends the current transmission burst (core sends the TeamSpeak end-of-voice packet). In mode
`vad` it also discards the detector state and preroll when capture or the native audio service stops
forwarding.
For a native capture release the connection manager invalidates the old epoch and queues the end marker together. An input acknowledgement that arrives after release cannot reinstall the old capture route. The stdio audio_end marker remains ordered with preceding frames.
### 4.11 `set_transmit` — `{mode: "direct"|"vad", detector?: "automatic"|"volume_gate"|"hybrid", sensitivity?: "high"|"normal"|"low", level_db?: number}`
Omit optional fields to use their defaults. An explicit JSON null for detector, sensitivity or level_db is a bad_request in either mode.
Selects who decides when voice is sent. `direct` (initial state at process start): every
forwarded frame is sent. `vad`: voice activation in the core (`core/src/vad.rs`) with the
official TS6 VAD modes (our own implementations, not TS6's native code):
@@ -295,7 +310,7 @@ changes between `direct`/`vad` or to another detector: before answering such a c
discards frames still queued from the previous mode and ends any open burst; the native audio service
forwards nothing until it has this answer. A `set_transmit` that only changes `sensitivity` or
`level_db` of the active detector (the user moving the VAD level slider) applies from the next
frame without discarding audio or ending the spurt.
frame without discarding audio or ending the spurt. Reapplying `direct` when already in direct mode also preserves the capture epoch and does not end the current burst.
Result `{"mode":"direct"}`, `{"mode":"vad","detector":"automatic","sensitivity":"normal"}`,
`{"mode":"vad","detector":"volume_gate","level_db":-30}` or
`{"mode":"vad","detector":"hybrid","sensitivity":"normal","level_db":-30}`.
@@ -325,6 +340,8 @@ Result `{"agc": bool}`.
### 4.12 `stream_list` — `{client_id?: number}`
Stream commands that address a client require a positive 16-bit client ID. Zero is rejected by both the embedded API and the JSON bridge before dispatch; it is not a broadcast selector.
TS6 screenshare discovery. Sends `requeststreaminfo clid=<id>` for `client_id`, or for
every other client in our current channel when omitted. Result:
@@ -341,6 +358,7 @@ So: "is streaming" ⇔ the `notifystreaminfo` item has `id`.
### 4.13 `stream_join` — `{stream_id: string, client_id: number, message?: string}`
Sends `joinstreamrequest id=<stream_id> clid=<client_id> msg=<message|our nickname> is_remove=0`.
An explicitly supplied join message is single-line and at most 200 UTF-16 code units, as in the historical client contract.
Result `{}` (or `server_error`). The SDP offer arrives as `stream` event
`notifyrespondjoinstreamrequest` (`decision=1`, `offer=<sdp>`).
@@ -351,6 +369,7 @@ Examples of `json`: `{"cmd":"answer","args":{"answer":"<sdp>"}}`,
`{"cmd":"iceCandidate","args":{"mLine":0,"mid":"0","sdp":"candidate:..."}}`.
Publisher ICE restart responses use `{"cmd":"reconnectOffer","args":{"offer":"<sdp>"}}`.
Shared core validation accepts only `answer`, `iceCandidate`, and `reconnectOffer`, never arbitrary signaling commands.
The outbound envelope and its arguments reject additional fields. SDP descriptions allow tab and line breaks and are limited to 60000 UTF-16 units. ICE uses a nonnegative safe integer `mLine` and single-line strings `mid` (64 units) and `sdp` (2048 units). Incoming alias handling is separate.
Max serialized `json` size 60 KiB (the whole stdin line is capped at 256 KiB). Result `{}` or `server_error`.
### 4.15 `stream_leave` — `{stream_id: string, client_id: number}`
@@ -369,7 +388,7 @@ unlimited), and `audio` is boolean, serialized as `1`/`0`.
|---|---|---|
| `stream_setup` | none | `setupstream name type bitrate accessibility mode viewer_limit audio` |
| `stream_update` | `stream_id` (required) | `updatestream id name type bitrate accessibility mode viewer_limit audio` |
| `stream_stop` | only `stream_id` | `stopstream id` |
| `stream_stop` | only `stream_id` | `stopstream id reason=1` (publisher left) |
| `stream_respond` | only `stream_id, client_id, decision, offer, message` | `respondjoinstreamrequest id clid decision offer msg` |
| `stream_remove` | only `stream_id, client_id` | `removeclientfromstream id clid reason=4` |
@@ -498,7 +517,12 @@ participant kicks, bans or permission/group mutations.
### 4.19 Channel file browser: `file_list`, `file_mkdir`, `file_rename`, `file_delete`, `file_download`, `file_upload`, `file_cancel`, `file_transfers`, `file_fetch_image`
Legacy TeamSpeak file transfer (`ftgetfilelist`, `ftcreatedir`, `ftrenamefile`, `ftdeletefile`, `ftinitdownload`, `ftinitupload`, `ftstop`), implemented in `core/src/file_transfer.rs` and `core/src/files_session.rs`. Every command needs an established connection (`not_connected` otherwise) and a channel the client can see (`not_found`). The native service-only snapshot exception permits `channel_id:0` for listing `/icons/` and transferring `/icons/icon_<u32 CRC32>`; UI file operations still require a nonzero channel. `channel_password` is optional; it travels as base64(SHA-1), like tsclientlib's own transfers, and an empty one is sent as the bare `cpw` flag.
Channel file operations are implemented in `core/src/file_transfer.rs` and `core/src/files_session.rs`.
They require an established connection (`not_connected` otherwise); commands addressing a channel
require it to be visible (`not_found`). The legacy backend uses `ftgetfilelist`, `ftcreatedir`,
`ftrenamefile`, `ftdeletefile`, `ftinitdownload`, `ftinitupload` and `ftstop`. Trusted native icon
and snapshot services can address legacy `/icons/` and `/icons/icon_<u32 CRC32>` at `channel_id:0`;
ordinary channel operations require a nonzero channel ID.
Remote paths are UTF-8, start with `/`, are at most 512 characters, and every component is non-empty, not `.` or `..`, and contains no control character or backslash. A folder path (`file_list`) is normalized to `/` or `/a/b/`. A file or folder path (`file_mkdir`, `file_rename`, `file_delete`, `file_download`, `file_upload`, `file_fetch_image`) has no trailing slash and is not the root.
@@ -514,17 +538,48 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
| `file_transfers` | `{}` | `{transfers:[record…], storage}` |
| `file_fetch_image` | `{channel_id, path}` | `{mime, bytes, data}` (base64; same pipeline and limits as §4.17 channel banners) |
**`file_list` details**
- The server's empty-folder answer (error 0x0501 "database empty result set") becomes an empty `entries`.
- Rows of `notifyfilelist` are matched by the echoed `return_code`, or else by channel and path. Only one listing per folder may be pending; a second one is `bad_request`.
- Arguments sent once for all `|`-joined entries are inherited by the later entries.
- A row is counted in `malformed` instead of being returned if any of these hold: the name is invalid, `type` is not `0` (folder) or `1` (file), or size/datetime are not numbers.
- More than 10 000 rows is an error, never a truncated list.
- The listing fails if the server does not complete it within 20 s.
**`file_list`: status and data**
**`capabilities`** are the full-width `u64` channel permission hints (`notifychannelpermhints`): `{known, upload, download, delete, rename, browse, create_directory}`. Unknown hints count as allowed, as in the official client; the server decides. No narrowing cast discards high bits.
- Both backends allow only one pending listing per channel and normalized directory; a duplicate is
`bad_request`. A listing ends in `server_error` after 20 s if the required status or data is
missing, never success with a synthetic empty list.
- Legacy sends `ftgetfilelist` with `cid`, `path` and `cpw`. It correlates `notifyfilelist` rows
and `notifyfilelistfinished` by echoed `return_code` or by channel and path. Rows separated by
`|` inherit shared arguments from the first row. The successful command result and list completion
are separate; the legacy status `0x0501` (database empty result set) is an explicit empty result.
Invalid names, types other than `0` (folder) or `1` (file), or invalid numeric fields count in
`malformed` rather than becoming entries. A list exceeding 10,000 entries fails, not truncates.
- S3 sends `s3ft_list_files` with `chid` and `chpw`, without a path. For both backends the channel
password is base64(SHA-1); an empty password is sent as a bare `cpw` or `chpw` flag. TeamSpeak
command names accept ASCII letters, digits and `_` so `notify_s3ft_file_list` is recognized
under its exact name, with normal argument escaping unchanged.
- S3 list data comes from a single `notify_s3ft_file_list` matched by the exact numeric `return_code`.
Missing, ambiguous or unrelated codes cannot complete a job. Success requires both that data and
the successful command acknowledgement (`error id=0`), in either order. A rejected command keeps
its TeamSpeak error even when data arrived first. An explicitly present but empty `b64_json` means
an empty channel; a missing, malformed or truncated payload is `server_error` after a successful
acknowledgement, not an empty channel.
- Nonempty S3 data is TeamSpeak-unescaped standard base64 of a JSON object with `contents`. The core
projects only the direct children of the requested directory from the channel-wide object list;
prefixes and `.tsfolder` markers supply directory entries, not downloadable marker files. Invalid
keys and ambiguous children contribute to `malformed`; structurally invalid data, an encoded value
over 2 MiB, or more than 10,000 objects fails the whole listing.
**`storage`** is `{capability_extensions, httpft, s3, supported}`. It is computed from `virtualserver_capability_extensions` (tapped from `initserver`/`notifyserverupdated`/`notifyserveredited`) using the official substring test. Known `HTTPFT` or `s3` advertisements cause every file operation except transfer inspection/cancellation to fail with `media_unsupported` and storage detail **before any legacy command or local disk side effect**. No UI override falls back to a different store. Unknown/unannounced capability flags retain legacy requests and authoritative server errors; they do not prove newer-storage support.
**`capabilities`** are derived from the full-width `u64` channel permission hints
(`notifychannelpermhints`): `{known, upload, download, delete, rename, browse, create_directory}`.
Unknown hints let the server decide, as in the official client; neither a permission hint nor a
storage flag proves an operation succeeded. For S3, directory mutation hints are suppressed.
**`storage`** reports `capability_extensions`, `httpft`, `s3` and operation support. The backend
flags are case-sensitive substring checks for `HTTPFT` and `s3` in
`virtualserver_capability_extensions` from `initserver`, `notifyserverupdated` or `notifyserveredited`.
Backend selection uses the full announcement; the file browser's diagnostic string retains at most 1024 characters. Partial edits retain the flags when the property is absent. A new initserver starts a new baseline even when it has no capability property.
The compatibility field `supported` indicates legacy storage, not whether the browser can list;
use `list_supported` for ordinary channels and do not infer other operations from it. When both
flags are set, an ordinary channel lists with S3. HTTPFT without S3 is blocked, and neither flag
permits a legacy retry for a newer store. The core returns `media_unsupported` with storage detail
for operations that backend cannot perform, before issuing any legacy command or touching local
files. Absent or unrecognized flags retain legacy requests and authoritative server errors.
**Host paths belong only at the trusted core boundary.** Native file services resolve session/purpose-owned chooser grants before constructing download/upload commands; UI fields cannot provide arbitrary paths.
- `dest_dir` is an absolute, existing folder.
@@ -537,7 +592,8 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
- `source` must be a regular file. Its size is measured once and sent in `ftinitupload`. Exactly that many bytes are streamed; a file that shrinks fails the upload.
- With `overwrite:false` a server-side "file already exists" (0x0802) fails the transfer with code `file_exists`.
**Transfers**
**Legacy TCP transfers**
- Native scheduling allocates app-global directional slots (combined maximum ten); at most 512 native records per connection.
- Transfer ids are bridge-visible `u32` values, unique per connection.
- Lifecycle: `queued` → `starting` (`ftinit*` sent) → `running` (stream granted) → [`confirming`, upload only] → `done` | `failed` | `cancelled`.
@@ -556,10 +612,27 @@ Remote paths are UTF-8, start with `/`, are at most 512 characters, and every co
- A grant that arrives after the cancel is dropped and stopped.
- Progress is emitted at most every 250 ms while bytes move.
Not implemented (explicit limits):
- The TeamSpeak 6 `HTTPFT` and `s3` branches. Exact recovered constructor arguments, bounded RIP-relative/native-function continuation, and unresolved endpoint/payload semantics are in `docs/evidence/ts6-filetransfer-native.json` and `docs/evidence/ts6-filetransfer-native-continuation.json`. These are static interoperability evidence, not server acknowledgements.
- Resume/pause.
- Drag-and-drop upload without a purpose-bound native resource grant.
**Newer storage limits and evidence**
- S3 listing does not enable folder creation, rename/move, delete, pause/resume, inline images,
file-link copying, avatars or server/snapshot icon operations. Listing success is metadata only,
not evidence of uploading, downloading or mutating through TeamSpeak. HTTPFT is blocked; there
is no fallback to legacy TCP or to direct object-store access.
- The isolated official TS6 Server beta14 run negotiated `s3`, received a matching notification
with an empty `b64_json` followed by status `0`, and returned `entries:[]`, `malformed:0`,
`storage.s3:true`, `storage.list_supported:true` and `storage.read_only:true` for channel 1's
root. The client disconnected cleanly. This records the tested build's result, not a guarantee
for other operations. A subsequent ordinary guest upload grant was refused by the fixture;
this verifies rejection, not a successful grant or file transfer. Nonempty listing, file bytes
and remote mutations through TeamSpeak remain unverified live. A separate direct SigV4
seed/list/readback is not TeamSpeak channel evidence. Live-peer validation remains pending.
- [Native file-transfer notes](evidence/ts6-filetransfer-native.json) and their
[continuation](evidence/ts6-filetransfer-native-continuation.json) are historical static evidence;
recovered constructors or endpoint arguments alone do not establish a working operation.
- Keep live checks separately authorized, on disposable channels/profiles/storage with explicitly
approved actions and scoped evidence output. Retain only sanitized status, counts, byte lengths
and fixture hashes; no credentials, signed URLs, private files or unrelated server state.
- Drag-and-drop upload without a purpose-bound native resource grant remains unavailable.
### `file_transfer` (event)
@@ -567,7 +640,10 @@ Not implemented (explicit limits):
New error codes (§3): `file_exists` (target name exists and replacing it was not confirmed; `detail.name`), `transfer_cancelled`.
Native chooser and overwrite-confirmation continuations capture/recheck the originating SessionKey before use. Grants bind purpose and session; delayed/revoked results cannot start work on a replacement connection. Isolated tests use disposable resources without OS dialogs/folder opening.
Native chooser and overwrite-confirmation continuations capture and recheck the originating
`SessionKey`. Grants bind purpose and session; delayed or revoked results cannot start work on a
replacement connection. Destructive actions and overwrite require explicit user confirmation.
Isolated tests use disposable resources without OS dialogs or folder opening.
Native regression requirements include real loopback bytes/hash, cancellation, Unicode, empty/short/conflicting files and deterministic cancellation/publication gates in `core/src/file_transfer.rs` and native file services. Existence is not an execution result.
@@ -594,42 +670,50 @@ Regression requirements include approved-destination persistence, rejected UI pa
Every mutation below is answered only after its real server command result. Permission hints never manufacture success. Requests capture a server connection ID in native service and its native `generation`; stale mutations fail. Read replies are `{rows:[wire-key/string-value objects]}`, not HTML. Only one reader per notification type is allowed in flight; over 10,000 rows fails rather than silently truncating. Empty database/permission-list replies become empty rows.
For a scoped list, each explicit scope ID applies from that row onward, including across packet boundaries. Rows before the first scope ID and rows belonging to a different scope are excluded.
`admin_context {}` returns `{generation,server_uid,own_client_id,catalog_received,permissions,permissions_catalog,permission_error?}`. Permissions are the official named hint values (null if unknown); catalog entries are `{id,name,description}`.
For an isolated Windows beta14 fixture at `127.0.0.1:19987`, set `TEAMSPEACH_QA_CORE` to the absolute diagnostic core executable and run `cargo run --locked -p teamspeach-core --example channel_admin_qa`. It checks a newly created temporary channel, edit acknowledgements and independent readbacks. A missing wire property is unreported, not false. A server permission refusal is reported separately from an accepted write.
Pass `-- --client-database-id` for the read-only database identity check. It looks up the disposable guest's roster UID and compares the result with an independent nickname search. Both commands must succeed for the scenario to pass; a fixture that denies database searches cannot verify the comparison.
Pass `-- --client-info` to read the guest's client version and platform and verify local rejection of a mismatched UID for the same client number.
| Command | Arguments / result |
|---|---|
| `channel_create` | `{generation,parent_id,properties}` → `{channel_id}` from own channel-created event |
| `channel_edit` | `{generation,channel_id,properties}` |
| `channel_move` | `{generation,channel_id,parent_id,order?}` |
| `channel_create` | `{generation,parent_id,properties}` → `{channel_id}` from the client's own channel-created notification matching name and parent. A nonzero `channel_order` must still be a child of `parent_id` at dispatch. If the server accepted creation but no unique positive ID was received, the error detail contains `created: true`; refresh the tree instead of retrying creation. |
| `channel_edit` | `{generation,channel_id,properties}`; a nonzero `channel_order` must still be a sibling distinct from the edited channel. A stale predecessor returns `target_changed` without sending the edit. |
| `channel_move` | `{generation,channel_id,parent_id,order?}`; parent 0 means server root, order 0 means first. A nonzero predecessor must still belong to the destination parent. A missing or cyclic destination ancestry, a destination below the moving channel, or a stale predecessor is refused before sending. An exact match of parent and explicit predecessor returns `{"changed":false}` locally, without a server request. An omitted order does not qualify. |
| `channel_delete` | `{generation,channel_id,force,confirm}`; confirm exact current channel name |
| `channel_subscribe` / `channel_subscribe_all` | `{channel_id,subscribe}` / `{subscribe}` |
| `channel_description` | `{channel_id}` → `{description}` |
| `channel_list` / `channel_info` | `{}` / `{channel_id}`; observed channel wire properties, info refreshes description |
| `client_info` | `{client_id,uid}`; checks current UID, requests `clientgetvariables` |
| `channel_description` | `{channel_id}` → `{description}`: a string (including the empty string) if reported; null if not received or invalidated before acknowledgement. A description-change notice invalidates only that channel's cached text until a fresh value arrives. |
| `channel_list` / `channel_info` | `{}` / `{channel_id}`; observed channel properties except `channel_password`. The password flag is retained. `cpid` and `channel_order` come from the current tree as decimal strings; info refreshes description |
| `client_info` | `{client_id,uid}`; requests `clientgetvariables` only for a matching live identity. Only rows explicitly naming the requested client number are collected. A conflicting UID in a row, disappearance of the client, or reassignment of its number before a successful acknowledgement returns `target_changed` instead of client information. |
| `set_away` | `{away,message?}`; message only when away, ≤80 characters |
| `talk_request` | `{request,message?}`; message only when requesting, ≤50 characters |
| `talk_power` | `{generation,client_id,uid,grant}`; UID checked against live target |
| `server_info` | `{}`; `servergetvariables`/`notifyserverupdated` |
| `server_info` | `{}`; `servergetvariables`/`notifyserverupdated`; excludes `virtualserver_password` and `virtualserver_keypair` |
| `server_edit` | `{generation,confirm,properties}`; confirm exact server UID |
| `ban_list` | `{}` |
| `ban_add` | `{generation,ip?,name?,uid?,duration_s,reason?}`; at least one target; 0 seconds permanent |
| `ban_delete` / `ban_delete_all` | `{generation,ban_id,confirm}` / `{generation,confirm}`; confirm decimal ID / `all_bans` |
| `privilege_key_list` | `{}` |
| `privilege_key_add` | `{generation,kind:"server_group"|"channel_group",group_id,channel_id?,description?}`; channel ID iff channel group; → `{token}` |
| `privilege_key_add` | `{generation,kind:"server_group"|"channel_group",group_id,channel_id?,description?}`; channel ID iff channel group. Returns `{token}` only for one distinct usable key. Repeated reports of that key are accepted; missing or conflicting keys after acknowledgement give an error with `created: true`. Reload the list before taking further action. |
| `privilege_key_use` / `privilege_key_delete` | `{generation,token}` / `{generation,token,confirm}`; confirm exact token |
| `temp_password_list` | `{}` |
| `temp_password_list` | `{}`; beta14 returns `rows` with `pw_clear`, `desc`, `nickname`, `start` and `end` (Unix seconds), and `tcid` (0 for the server default). Rows contain credentials; do not log them. |
| `temp_password_add` | `{generation,password,description?,duration_s,channel_id?,channel_password?}`; positive duration |
| `temp_password_delete` | `{generation,password,confirm}`; confirm exact password |
| `server_log` | `{lines:1..1000,reverse,instance,begin_pos}`; `logview` → source rows including `last_pos/file_size/l` |
| `client_database_list` | `{start:u32,duration:1..200}` |
| `client_database_find` | `{pattern,uid:bool}`; `clientdbfind -details [-uid]` |
| `client_database_delete` | `{generation,client_database_id,confirm}`; confirm decimal database ID |
| `client_database_id` | `{uid}`; rows with `cluid/cldbid` |
| `client_database_id` | `{uid}`; returns one row with the exact requested `cluid` and a positive decimal-string `cldbid`. Duplicate reports of the same ID are accepted. A successful command result without a unique matching ID is an error; the server's explicit database-empty result returns an empty list. |
| `server_group_list` / `channel_group_list` | `{}` |
| `server_group_perm_list` / `channel_group_perm_list` | `{group_id}` |
| `channel_perm_list` | `{channel_id}` |
| `server_group_client_list` | `{group_id}`; sends `-names` to include UID/nickname |
| `group_add` | `{generation,kind:"server"|"channel",name,type:0|1|2}` → `{group_id}`; missing/ambiguous resulting ID fails with created detail |
| `group_add` | `{generation,kind:"server"|"channel",name,type:0|1|2}` → `{group_id}`. The group list must identify one positive ID not present in the live book for this kind before dispatch, matching the requested name and type. Repeated rows for the same ID are allowed. If creation was accepted but no unique ID was identified, the error detail contains `created: true`; reload the list instead of retrying creation. |
| `group_rename` | `{generation,kind,group_id,name}` |
| `group_set_permissions` | `{generation,kind,group_id,permissions:[{id:string,value:i32,negate?,skip?}]}`; 1..512 rows; negate/skip only server group |
| `channel_set_permissions` | `{generation,channel_id,permissions:[{id:string,value:i32}]}` |
@@ -650,9 +734,13 @@ Native snapshot orchestration in `native/src/services/snapshots.rs` uses ordinar
### 4.22 Whisper routes
A client number is not an identity. An individual recipient needs a nonempty UID matching the live roster. A missing, empty or mismatched UID omits that recipient; if nothing resolves, the command returns `no_targets`. An explicitly targeted channel remains a channel target even when an occupant has no visible UID.
`whisper_start {epoch:u32,target}` resolves a route against the live connection; epoch must be nonzero. Target is `{kind:"list",entries:[{type:1|2,uuid,name}]}`, `{kind:"group",group_type:0..3,target_mode:0..6,group_id,server_uuid}`, or `{kind:"ids",clients:[{id,uid}],channel_ids:[…]}`. At most 255 resolved clients and channels. `whisper_stop {epoch}` stops that route; `set_whisper_receive {mode:"allow_all"|"deny_all"}` controls incoming whispers.
`audio_frame` accepts optional `whisper:epoch`; stale/stopped/other-generation tags drop, never fall back to ordinary voice. Untagged queued frames also drop while a whisper route is held. Transitions end the previous spurt and discard capture queued before the transition. Incoming `whisper_received {client_id}` feeds reply history; receive deny mode removes queued whispers. This is real TeamSpeak whisper packet routing, not local recipient filtering.
`audio_frame` accepts optional `whisper:epoch`; stale/stopped/other-generation tags drop, never fall back to ordinary voice. Untagged queued frames also drop while a whisper route is held. Transitions end the previous spurt and discard capture queued before the transition. Receive deny mode removes queued whispers.
`whisper_received` carries the receiver's connection `generation` and the sender's numeric `client_id`. When known, `uid` and `nickname` identify the sender at receipt; a later roster cannot supply missing identity. An unidentified whisper can notify but cannot become a reply target. Reply requires the original UID and client number to still match in the same session.
### Local recording (`recording_*`)
@@ -671,6 +759,8 @@ Events: `recording_state {isRecording, isPaused, outputDirectory, mode, reason?,
Files (`<directory>/<label>[_N]/`): `NN <name>.wav` per track (48 kHz mono s16le; `00 master.wav`, `NN capture - <nick>.wav`, client tracks by nickname, `(k)` for a concurrent second connection of the same UID), `… (part N).wav` past the 4 GiB RIFF limit, and `session.json` (`finalized:false` until stop) with per-track speech segments `{startFrame, endFrame, startEpochMs, clientId, nickname, channelId, channelName, whisper}`, pauses, `droppedRanges`, `endReason`, `errors`.
`totalBytes` counts PCM payload bytes across all WAV tracks and parts, excluding each 44-byte RIFF header. The final event and `session.json` report the same count. To compare it with a WAV reader, sum `frames × channels × bytes_per_sample` across the files, not their filesystem lengths.
Signal paths: client tracks = each speaker's decoded audio before local volume (official: "individual tracks stay untouched"); capture = frames this connection actually encoded and sent (after mute/PTT/VAD); master = the local playback mix with local volumes plus the sent capture. A full disk queue (2 s) drops whole 20 ms ticks, counts them and pads them with silence so tracks stay aligned. Headers are refreshed every 2 s. TeamsPeach's file layout/format is its own; the official native format is not published.
Starting a second recorder while prior files finalize is refused. Dropped capture includes queued TX discarded on pause/stop; dropped tails are padded through declared timelines, empty master is a valid 44-byte WAV. Header-finalization errors keep finalized false, are recorded, and actual final file bytes are recomputed. Multitrack taps are pre-gain/pre-AGC; master is post-client-gain/AGC plus sent capture, not native device output gain.
@@ -698,6 +788,9 @@ See §1.
{"event":"state","state":"connecting|connected|disconnecting|disconnected",
"address":"10.10.10.160:9987","reason":{"code":"...","message":"...","ts_error":{...}}}
```
A terminal `disconnected` event reports `previous_state` (`connecting`, `connected`, or
`disconnecting`). Use it to distinguish a failed connection attempt, a dropped live session,
and a requested exit without guessing from the error text.
`reason` only on `disconnected` when not user-initiated (kicked, banned, timeout,
server shutdown, connect failure) and on an automatic-reconnect `connecting`. For a
server-closed connection `reason.detail.reason` is one of `kicked`, `banned`,
@@ -0,0 +1,11 @@
# Bookmark passwords in Windows Slint
Scope: `preload:getBookmarkPasswordState`, `preload:setBookmarkPassword`, and `preload:revealBookmarkPassword` in the [native compatibility inventory](../../native/compatibility.json). The test used an isolated profile, two freshly generated synthetic credentials, and the real Windows DPAPI backend. It did not connect to a server, use the clipboard, open the owner's profile, or log the credential values.
- **State:** The rendered bookmark editor showed separate server and channel hints for re-entry required, saved, and absent, with empty password inputs. Cancelling the reveal picker did not expose either value; explicitly choosing an unconverted legacy slot was refused with `password_required`. Saving one purpose cleared only its own re-entry requirement.
- **Set/clear:** The dedicated password form saved both purposes. After reopening, explicit reveal returned the correct value for each purpose, while another bookmark at the same address returned `not_saved`. Cancelling channel clear kept both slots; confirming it removed only the channel slot, including after another reopen. Changing the exact address through Edit Bookmark invalidated the old slots. A paused save aimed at the old address was refused with `target_changed` and did not recreate a slot.
- **Reveal:** The explicit picker used the selected bookmark, address and purpose. The reveal dialog was read-only and closed on Cancel. When actual DPAPI output was held and the bookmark address changed via Slint, releasing the old result returned `target_changed` without reopening the secret dialog. Only local completion delivery was paused; DPAPI itself was real.
**UI receipt:** `target/bookmark-password-ui.log`: exact `smoke::bookmark_schema::passwords::bookmark_password_ui_shows_metadata_and_guards_dpapi_operations`, **1 passed, 0 failed, 0 ignored; 8.85 s** (Windows x64, `webrtc,test-harness`). The Slint software-renderer test skips HWND-dependent attachment.
**Separate service receipt:** `target/secret-backend-evidence/test.log` reports five passes, including actual DPAPI unprotect failure retaining saved metadata, and simulated open/seal refusal preserving the existing index and re-entry marker. Windows reports backend availability as unchecked before explicit access; no locked operating-system keyring or non-Windows backend was exercised by the UI run. The refusal simulation is not evidence of a real locked keyring.
+23
View File
@@ -0,0 +1,23 @@
# Windows bookmark schema verification
The scope is the ten `schema-field:bookmark.*` entries below in [native/compatibility.json](../../native/compatibility.json). `bookmark.name`, folder-object fields and `bookmarkOrder` are not new acceptance claims. The Windows runs used generated identities, disposable profiles and synthetic password input. No owner profile or secret values were used in the receipts.
| Field ID suffix | Evidence and scope |
| --- | --- |
| `id` | The owning Slint create form generated a valid ID; editing and moving reused it and the same sidebar row after two reopens. It is deliberately not a writable field. Schema writes rejected malformed, oversize, wrong-type and duplicate IDs. |
| `address` | Slint rejected a control character and overlength input, trimmed a valid edit, and retained the previous object and disk bytes after a blocked save. The live runtime used the saved loopback address. Changing it invalidated both DPAPI slots; a refused change preserved both files. |
| `identity_id` | The actual vault picker selected a nondefault identity, displayed it after two reopens, and could clear the override. The live connection reported the saved vault UID for each tab. Invalid encodings and types were refused. This is not a comparison of the vault UID to the live server UID. |
| `folder` | The Move dialog placed the bookmark in the selected existing folder; both reopens displayed it there, not at root. Missing/wrong-type folder IDs were rejected. Existing folder tests separately cover cycles and maximum depth. |
| `nickname` | Slint rejected too short, over 30 Unicode scalars and control characters. It trimmed the override, reopened it and allowed clearing. A stale editor could not overwrite a newer saved name. The initiator's live own-client row reported the saved override. |
| `channel` | Slint bounded and trimmed the text and allowed clearing. The channel-tree action inserted the nested path and rejected a second submission after replacement of the captured session. On both live starts the own roster reported the configured room. |
| `auto_connect` | The Slint toggles were saved and reopened. On both live starts, the nested bookmark connected before the root bookmark despite reversed storage order; the disabled bookmark did not get a tab. |
| `auto_connect_muted` | On both live starts, the first core's audio state and its own server-fed roster had input muted, output unmuted. On both manual reconnects the same bookmark did not apply startup mute. The code awaits `SetAudio` before dispatching `Connect`, and core connection options use those flags. No trace of wire packet order or independent peer observation is claimed. |
| `server_password_encrypted` | Canonical legacy input was stripped and prompted first; malformed/noncanonical input did not activate import and generic writes refused a canonical value too. Re-entering and saving used real Windows DPAPI; the native consumer recovered the bound secret on two reopens without another prompt, then the isolation policy stopped before network I/O. |
| `channel_password_encrypted` | The same checks applied separately to the second prompt and channel-bound DPAPI slot. Neither legacy ciphertext key nor plaintext appeared in the live JSON preference or secret index. No authenticated server/channel join using either re-entered password was exercised. |
## Receipts
- `target/bookmark-schema-verification.log`, offline section: **10 passed**, including `bookmark_schema_editor_keeps_identity_and_folder_after_two_reopens`, `bookmark_schema_bad_patches_leave_profile_unchanged`, `bookmark_schema_captured_channel_rejects_a_replacement_session`, `bookmark_schema_reenters_both_legacy_slots_through_real_dpapi`, malformed legacy import, native profile reopens and three actual DPAPI tests. The live case was ignored in this invocation and run separately below.
- `target/bookmark-schema-live.log`: exact `smoke::bookmark_schema::bookmark_schema_startup_consumes_saved_fields_on_beta14`, **1 passed in 57.53 s**. Both runtime restarts and both manual activations completed. The [disposable runner](../../native/tests/fixtures/beta14-server-admin.ps1) disabled Query for the guest phase. Teardown found zero listeners on UDP 19987 and TCP 30053/19080 and zero private fixture runtime directories.
The editor tests use the real Slint dialog callbacks, not Windows native input automation. The live test drives the real application runtime by attaching a generation directly after the Slint saves; a headless Slint window does not exercise HWND integration. The roster checks are from the initiator's own server-fed row; a usable independent peer readback was not obtained. The captured-channel replacement uses synthetic roster events. No physical audio endpoints opened. Scope does not include simultaneous preference and new-password writes as a single transaction, Linux/macOS secret stores, or mobile UI.
@@ -0,0 +1,42 @@
# Linux Secret Service isolation preflight
Checked from `work/integration-verified` at `0ee62be668` using the existing Ubuntu x86_64 WSL2 distribution. No packages were installed, no configuration was changed, and no host session bus or credential store was contacted.
## Observed readiness
- `dbus-run-session`, `dbus-daemon`, and `gdbus` were available. Ubuntu reported `dbus-daemon` and `dbus-bin` installed at `1.14.10-4ubuntu4.1`.
- Ubuntu reported `gnome-keyring` as `unknown ok not-installed`. `gnome-keyring-daemon` was absent from the system PATH and was not executable at the checked `/usr/bin`, `/usr/libexec`, or `/usr/lib/gnome-keyring` paths. `libsecret-tools` had no package record and `secret-tool` was absent from the system PATH; the CLI is not required by the Rust backend.
- Cargo and rustc proxies existed in the conventional WSL user Rustup bin directory, but were not on the cleaned system PATH. No offline crate-cache or Linux build check was needed: no disposable GNOME Secret Service provider was available.
- The preflight below printed `Private session bus started with isolated HOME/XDG; org.freedesktop.secrets owner: absent.` It queried only the private bus daemon and did not activate a secret service. It did not exercise an actual backend operation, a locked collection, or preservation across lock/unlock.
## Metadata and operation limits
Source inspection: `native/src/services/secrets/linux.rs` reports `linux_secret_service`, `Unchecked`, and `checked_on_user_action` without opening D-Bus. `SecretStore::password_state` reads only the stored binding and migration marker. The bookmark editor projects address change, required re-entry, known platform unavailability, or saved/unsaved metadata; on Linux a saved hint does not imply that the collection is unlocked or the credential readable.
On explicit save, the Linux backend refuses a locked default collection before creating an item. Reveal refuses a matching locked search result without requesting secret bytes. Both branches return `storage_unavailable`; the secret-store index is not replaced by a failed seal. Reveal presents no password when it fails. Explicit Connect can ask for one-use input after a refusal; this does not persist that input as a replacement credential. These are code-path conclusions, not results from a Linux keyring test. No global or last-known lock indicator was added; an operation refusal does not establish the current lock state of all collections.
The missing prerequisite for a real test is a runnable GNOME Keyring Secret Service provider that can create and explicitly lock a disposable collection on a fresh private session bus. The actual Rust backend would also need an existing runnable offline test build or the dependencies to build a focused harness. No Windows DPAPI or simulated-backend result is counted as Linux proof.
## Verified Reusable Preflight
Run from a Windows shell with Bash-style here-documents. This is a private-bus prerequisite check, not a backend acceptance test:
```bash
wsl.exe -d Ubuntu -- /usr/bin/env -i PATH=/usr/local/bin:/usr/bin:/bin /bin/sh -s <<'SH'
set -eu
umask 077
root=$(mktemp -d /tmp/teamspeach-secret-preflight.XXXXXXXX)
trap 'rm -rf -- "$root"' EXIT
export HOME="$root/home"
export XDG_CONFIG_HOME="$root/config" XDG_DATA_HOME="$root/data" XDG_CACHE_HOME="$root/cache" XDG_STATE_HOME="$root/state" XDG_RUNTIME_DIR="$root/runtime"
mkdir -m 700 "$HOME" "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_CACHE_HOME" "$XDG_STATE_HOME" "$XDG_RUNTIME_DIR"
test -z "${DBUS_SESSION_BUS_ADDRESS:-}"
dbus-run-session -- /bin/sh -eu -c '
test -n "${DBUS_SESSION_BUS_ADDRESS:-}"
test -d "$HOME" && test -d "$XDG_RUNTIME_DIR"
reply=$(gdbus call --session --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.NameHasOwner org.freedesktop.secrets)
test "$reply" = "(false,)"
printf "Private session bus started with isolated HOME/XDG; org.freedesktop.secrets owner: absent.\n"
'
SH
```
@@ -0,0 +1,23 @@
# Native chat image auto-download on Windows
Scope: [`preference:autoDownloadImages`](../../native/compatibility.json#L3111), verified from `ba589e3a15` plus the focused changes in the detached `auto-images-verify` worktree. This preference applies to eligible TeamSpeak server-file images (`ts3image://`), not to images embedded directly from web URLs. The test used a synthetic `images.example` roster and injected a deterministic 2-by-1 PNG at the fetch call, after the normal server, channel, and file-access checks. The production raster decoder and Slint timeline consumed the result.
| Case | Observed result |
| --- | --- |
| Default off | The chat showed the visible **Load server image: manual.png** control with no painted fixture and zero transport calls. Activating the control produced exactly one request for `/manual.png` on channel 7 in the owning session. Slint decoded the expected opaque red and green pixels and painted both inside the timeline. |
| Enabled and reopened | Activating the real **Automatically download images** checkbox saved `true`. The mounted conversation fetched `/automatic.png` once without a click. In a fresh conversation after reopening the disposable profile, the saved setting caused exactly one automatic request; the image painted in the timeline without a manual load. |
| Policy remains enforced | A benign HTTPS image URL and an `about:blank` image reference appeared as inert text with no image action. When the roster advertised HTTPFT, automatic loading was suppressed despite the setting being on. Activating its manual control displayed the HTTPFT limitation. None of those cases reached the injected transport. |
**Receipt:** `auto-images-verify/target/native-auto-download-images-final.log`: **4 passed, 0 failed, 0 ignored, 844 filtered out; 4.08 s**. The initial smoke also passed; the first run had a stale decoder error-string assertion, now aligned with the shared decoder without weakening either format rejection. The final run left zero entries in disposable `TEMP`. The generated roster disconnected before each shutdown.
The fixture used no DNS, network transport, live service, owner profile, or audio hardware. It does not verify real file-transfer interoperability or claim support for loading arbitrary web images.
Use Windows x64 MSVC, pinned read-only `LK_CUSTOM_WEBRTC`, a worktree-local `CARGO_TARGET_DIR`, and disposable `TEMP`/`TMP`.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact --test-threads=1 --nocapture `
smoke::auto_images::server_image_autoload_respects_preference_and_policy_after_restart `
app::runtime::file_actions::chat::tests::inline_image_decodes_rgb_png_to_opaque_rgba `
app::runtime::file_actions::chat::tests::inline_image_rejects_svg_and_ico `
ui::chat::policy::tests::files_are_scoped_and_traversal_is_refused
```
@@ -0,0 +1,21 @@
# Windows native capture selection cancellation
Worktree `work/stream-setup`, based on `6ab51d5fb061889259cc5b850078b995dd6abc04`. This records the device-free Slint portion of `preload:cancelCaptureSelection` and `command:stream_setup`; neither compatibility entry is changed.
## Shipped path
The desktop Go Live button (`native/ui/shell.slint:713`) invokes `CaptureChoose`. The runtime enumerates a source catalog and the shared Slint `ShellDialog` renders the source selector and Cancel button (`native/ui/dialogs.slint:199`, `:229`). Windows uses libwebrtc screen/window enumeration in a worker MTA and adds camera descriptors. The macOS and Linux Wayland desktop path instead lists a system-picker entry without starting a desktop capturer; the OS picker is deferred to Preview (`native/src/media/stream/capture.rs:401`, `:440`, `:476`). Windows and non-Wayland Linux choose a listed screen/window directly. Mobile uses separate platform capture adapters.
Confirming a source only exposes Preview; submitting Preview configuration is the first acquisition boundary. Start requires a private preview and is a separate publication step. A cancelled chooser now removes its exact session/flow and discards its catalog. Cancelling Preview configuration also drops the selected source and removes its detail actions. A retired prompt cannot fall through to a new chooser or acquisition and a mismatched Cancel cannot dismiss a newer capture prompt.
## Observed
```text
cargo test --quiet --locked --offline -p teamspeach-native --lib --no-default-features --features webrtc,test-harness slint_capture_selection_cancel_revokes_only_its_flow -- --nocapture
```
**1 passed, 0 failed** (Windows x64, 2.12 s test body). The test ran in the isolated worktree with its own Cargo target and a fresh disposable profile. It used the real Slint app and runtime, pointer events over visible Go Live and footer buttons, and pointer/keyboard input on the real source selector. Two synthetic rosters supplied session state without connecting to a server. The test confirmed open/Cancel/reopen, a fresh unselected chooser, explicit source confirmation without Start, a second tab's Cancel preserving the first selection, Preview configuration Cancel removing the first selection/actions, and rejection of stale runtime intents. The capture adapter returned only an inert catalog, counted four enumerations and zero acquisition/Start attempts, and the actual stream hub had no publisher on either tab. Audio input/output starts were both zero.
Follow-up on base `f1455937413ba336dff39a579886126d897ba34e`: the same targeted test passed again (**1 passed, 0 failed**, 2.30 s test body). With the replacement chooser open, it submitted its current editor ID first with the retired flow target, then with the current target but the wrong operation. After each submission, a navigation action on the same runtime queue confirmed command processing before the test asserted that the same Slint prompt was still open. The subsequent visible Submit still completed the correct selection. The disposable profile now uses the OS temporary directory and does not depend on the workspace Cargo target layout.
This does not exercise OS enumeration, picker/consent success or refusal, release of a live physical preview, actual Start/setup acknowledgement, or a server refusal presented in Slint. No real screen, camera, audio device, beta14 fixture, external server, or owner profile was used.
+18
View File
@@ -0,0 +1,18 @@
# Native Mermaid autoload (Windows)
Scope: [`preference:chatMermaidAutoload`](../../native/compatibility.json#L3067), integration base `ba589e3a15`. The installed 6.0.0.5232 bundles matched the hashes in the [visual source map](official-parity/visual-source-map.md). `main.js` at character 1801650 admits automatic work only outside Never and below the simple-complexity threshold; at 2929854 it leaves other graphs in the manual state. Native now applies the same cutoff (score below 90) before queuing work, so a complex graph shows Load Diagram rather than a policy refusal presented as a render failure. Each diagram has one Load or Retry control, and the image fits its allocated row.
| Captured state at 1480 x 1100 | Observed in Slint |
|---|---|
| `never-untouched.png` | Selected Never in the rendered Chats combobox before opening cold history. Three Load Diagram controls, zero rendered images. |
| `only-simple.png`, `only-simple-reopened.png` | The two-node flowchart autoloaded before and after reopening; the 16-stage flowchart stayed as source with one Load Diagram control. The malformed message displayed its source and Retry. |
| `manual-and-retry.png` | Activated Retry and Load Diagram via the rendered controls. The complex graph rendered within the viewport; the malformed source remained with `unexpected token 'not a Mermaid diagram' at 1:1; expected unknown or missing Mermaid diagram header`. Two images and one Retry control were visible. |
**Final receipt:** Windows x64 MSVC, locked/offline, `-p teamspeach-native --lib --target x86_64-pc-windows-msvc --no-default-features --features webrtc,test-harness`, **4 passed, 0 failed, 0 ignored, 845 filtered out; 8.66 s**. Log and captures: `target/chat-mermaid-evidence/run3/`. Exact tests:
- `smoke::chat_mermaid::mermaid_preference_controls_rendered_diagrams_and_manual_recovery`
- `services::chat::diagrams_tests::queue_serializes_start_times_and_cache_retry_and_generation`
- `services::chat::diagrams_tests::cancellation_during_font_or_layout_work_preserves_next_render_geometry`
- `smoke::chat::chat_style_reflows_history_without_losing_live_selection_or_draft`
The worker checks reused the existing cache, retry, serial-start, stale-generation and glyph-geometry regressions. They also confirmed that an explicitly cancelled ticket delivers no event and that a one-operation budget aborts a benign graph while later renders keep their geometry. Cancellation was verified at the worker boundary, not through an on-screen Cancel command or by timing an in-flight UI render. The UI used a disposable profile, synthetic roster and local history fixtures only. No external server, network asset, owner profile, new hostile input, other platform, or pixel parity comparison was exercised.
+18
View File
@@ -0,0 +1,18 @@
# Native chat style (Windows)
[`preference:chatStyle`](../../native/compatibility.json#L2671), integration base `059b0c906d`. The installed TeamSpeak 6.0.0.5232 bundle matched both SHA-256 fingerprints in the [visual source map](official-parity/visual-source-map.md). Its `main.js` at character 3103274 places the compact clock and sender in the same message row; `main.css` at 509428 and 510633 styles those inline items. Native Detailed retains the separate sender/timestamp header and bubble; Compact uses the existing inline layout and 65 px timestamp column. The measurements below are native, not an official screenshot comparison.
| 1280 x 800 Slint capture | Rendered rows | Total row height | Bubbles | Inline timestamps |
|---|---:|---:|---:|---:|
| `detailed-initial.png`, `detailed-restored.png` | 4 (2 headers, 2 messages) | 136 px | 2 | 0 |
| `compact-live.png`, `compact-saved.png`, `compact-reopened.png` | 2 (2 messages) | 50 px | 0 | 2 at 65 px wide |
The test switched Appearance > Chats > Style using the rendered combobox and checked the save acknowledgment. Across Detailed to Compact, back to Detailed, and again to Compact, the same selected conversation and two message IDs remained. Bold, italic, and inline-code spans retained their rendering flags. The two-message text selection stayed `Bold and italic\nKeep code here`; Detailed-only headers no longer leak into the selected text. The native composer retained `Unsent draft` and the reverse byte selection `(anchor 12, caret 7)` after each return from Settings. Slint's cursor notification no longer redraws from the old draft during an edit, and selection-only changes update the offsets used when the composer remounts.
After runtime shutdown and reopening the disposable profile, Compact and the same stored message IDs returned. The reopened chat was resolved from the same history scope using a fresh synthetic roster; unsent draft and text selection were empty, as expected for transient UI state. The test did not assert restoration of conversation navigation, drafts, or selections across process restarts. No external server, owner profile, clipboard, or physical audio was used.
**Receipt:** `target/chat-style-evidence/run5/test.log`, **3 passed, 0 failed, 0 ignored, 842 filtered out; 7.30 s**. The same directory contains the captures and `layout.json`. Windows x64 MSVC, locked and offline, `-p teamspeach-native --lib --target x86_64-pc-windows-msvc --no-default-features --features webrtc,test-harness`; exact tests under `smoke::chat`:
- `chat_style_reflows_history_without_losing_live_selection_or_draft`
- `chat_clock_switch_updates_loaded_row_and_preserves_history_on_restart`
- `concurrent_tabs_keep_separate_drafts_and_pending_sends`
+19
View File
@@ -0,0 +1,19 @@
# Native chat toolbar visibility (Windows)
[`preference:chatToolbarVisibility`](../../native/compatibility.json#L3056), from integration base `d436d87f71`. The installed TeamSpeak 6.0.0.5232 bundle matched both SHA-256 fingerprints in the [visual source map](official-parity/visual-source-map.md). `main.js` at character 3296874 shows Dynamic when editing or when the draft is nonempty; 3297738 suppresses toolbar pointer focus. The native composer now uses the full draft for that visibility check, not just the editable block, and formatting-toolbar clicks no longer take focus from it.
| Chats setting | Observed in the 1280 x 800 Slint window |
|---|---|
| Hidden (`inactive`) | No toolbar or visible Bold button when idle, focused, typing, or selecting text. It remained hidden on reopen. |
| Dynamic (`dynamic`) | Hidden on reopen with an empty, unfocused composer. Focusing the empty composer showed the 31 px toolbar. Typing and selecting kept it visible; blurring a nonempty draft kept it visible. Clearing the draft kept the toolbar open until blur, then hid it. |
| Always Visible (`always-visible`) | The 31 px toolbar was present on the initial default profile and after saving and reopening, even with an empty, unfocused composer. |
The test selected each mode through the rendered Chats combobox and verified the saved value in memory and on disk. Clicking More opened and closed the tool list without taking focus or changing `Keep draft` or its byte selection `(anchor 10, caret 5)`. Each live mode change retained the active conversation, draft, and selected range when returning from Settings. An explicit native blur may collapse the selection to the caret; it did not alter the text or caret offset. The test did not expect unsent drafts or selections to persist across restarts.
**Receipt:** `target/chat-toolbar-evidence/run2/test.log`: **3 passed, 0 failed, 0 ignored, 843 filtered out; 12.88 s**. The Windows x64 MSVC run used `webrtc,test-harness`, `--locked --offline`, and selected these exact tests:
- `smoke::chat_toolbar::toolbar_modes_follow_focus_and_drafts_and_survive_reopen`
- `smoke::chat::chat_style_reflows_history_without_losing_live_selection_or_draft`
- `smoke::chat::concurrent_tabs_keep_separate_drafts_and_pending_sends`
Captures are in the same directory, including `inactive-selected.png`, `dynamic-focused-empty.png`, `dynamic-blurred-draft.png`, `dynamic-blurred-cleared.png`, and `always-reopened.png`. The run used a disposable profile, local fixture roster, and offscreen Slint input only. No clipboard, network, owner profile, physical audio, mobile renderer, or full official screenshot comparison was exercised.
+24
View File
@@ -0,0 +1,24 @@
# Native Key Bindings on Windows
Scope: [`preload:getKeybinds`](../../native/compatibility.json#L136), from integration base `96b6f2aaef` with the contact evidence commit `3e750fe` already present. The shipped Rust/Slint settings page now names the active profile independently of the inspected profile. Global registration reports how many combinations the backend accepted out of those it attempted. A queued update is not a successful registration; unavailable and waiting states do not claim success. An earlier profile's receipt is not displayed as the new profile's result.
| Exact test | Observed result |
| --- | --- |
| `smoke::key_profiles::duplicate_chord_warning_stays_in_the_profile_that_owns_it` | Key Bindings showed the Clean and Conflict profiles, kept Clean active while inspecting Conflict, and projected both duplicate warnings only into Conflict's rows. With OS actions disabled the page displayed “No global shortcuts registered.” |
| `smoke::key_profiles::exact_checkbox_changes_modifier_matching_and_survives_restart` | Activated the rendered checkbox and observed its checked state after restart. In-process matching accepted the exact chord and stopped accepting extra modifiers. No physical key was pressed. |
| `smoke::key_profiles::windows_registration_results_render_without_key_input` | In a disposable test process, the production Windows adapter accepted Ctrl+Alt+Shift+F23 and reported `in_use` for Ctrl+Alt+Shift+F24, reserved by that same process. The production runtime consumed the result and Slint rendered “1 of 2 combinations registered.” The test stopped the adapter, released its reservation, then reacquired and released both chords to check cleanup. |
| `services::keybinds::tests::default_global_adapter_never_registers_and_stop_synthetically_releases` | The default adapter stayed inert without explicit opt-in; synthetic cleanup released the test runtime's held global state. |
**Receipt:** `target/native-get-keybinds-final.log`: **4 passed, 0 failed, 0 ignored, 836 filtered out; 1.82 s**. The disposable `TEMP` directory had zero entries after the run. The first run's Windows case stopped before registration because the fixture tried to start the idle adapter outside Tokio; the final run starts it inside a Tokio context.
The Windows smoke opted in only the adapter and used real, short-lived `RegisterHotKey` registrations. It did not exercise ordinary OS-enabled startup, key activation, global keyboard hooks, input injection, audio hardware, another application, or other operating systems. Each profile was disposable. For separate account-free contact and badge observations, see [Local contacts and public badges contract](native-tree-badges.md#local-contacts-and-public-badges-contract); those tests were not rerun here.
Use Windows x64 MSVC, pinned read-only `LK_CUSTOM_WEBRTC`, and disposable `TEMP`/`TMP`. Run the Windows registration fixture only explicitly, on a desktop where the two test chords are free. The fixture checks availability before testing and never removes another process's registration.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact --include-ignored --test-threads=1 --nocapture `
services::keybinds::tests::default_global_adapter_never_registers_and_stop_synthetically_releases `
smoke::key_profiles::duplicate_chord_warning_stays_in_the_profile_that_owns_it `
smoke::key_profiles::exact_checkbox_changes_modifier_matching_and_survives_restart `
smoke::key_profiles::windows_registration_results_render_without_key_input
```
+27
View File
@@ -0,0 +1,27 @@
# Native identity request evidence
Scope: `preload:identityRequest` on Windows x64, in the `work/appearance` worktree. The legacy Electron `identity:request` channel is not present in the native UI. Identities uses generated Slint callbacks, issued row tokens, and Rust `SettingsAction`, `Operation`, and `Field` variants. The service calls the typed core vault API. There is no string-action parser in this path and no editable identity UID.
The delete route now checks that the requested UID resolves to a vault entry before presenting a destructive confirmation. The delete service still validates the exact UID and its use/reference guards at commit time. The existing smoke now saves Russian through Appearance, declines the restart prompt, then reopens the disposable profile before checking localized Identities controls.
## Observed results
The `identity-workflows` scenario exited successfully with **15 passing checks**, no reported error, and no network, OS actions or physical capture:
- Creation selected its new UID without replacing the previous default. Rename and nickname edits retained that UID. Equal display names did not merge the identities, and setting the new default left exactly one default.
- A fabricated row token was ignored by the shipped Slint bridge; the next category navigation acknowledged in order with no additional identity request. An unknown string action is unrepresentable at the typed native boundary. The separate core diagnostic CLI parser was not exercised.
- A syntactically valid but absent UID returned `not_found` on both Default and Delete; Delete opened no confirmation. The existing identity roster, default, vault bytes and preferences stayed unchanged.
- Confirming with the other existing UID was rejected visibly by the dialog. Sending the same mismatch through the typed runtime submit route independently returned `target_changed`. The subsequent correct confirmation still honored the bookmark and active core-use guards.
- An improvement for the selected UID reached a requested level of 11 and reported 12. Cancel and resume preserved the same key and UID, and the checkpoint survived reopening the profile. Cancel acknowledged in 129 ms and 86 ms against a 3,000 ms bound in this run. These numbers are observations, not guaranteed levels or timings.
The smoke operates on an isolated profile and reopens fresh runtime/window instances within the same process. It does not verify Electron IPC, live server identity changes, desktop clipboard success, or successful private-key import/export. Vault bytes and keys were compared in memory only; no private key material was emitted in the report.
## Reproduction and receipts
From `C:/Users/Admin/tmp/tp-wt/appearance`, use the read-only MSVC launcher `C:/Users/Admin/Desktop/projects/TeamsPeach/target/tools/build-native.cmd` to run Cargo. Set `CARGO_TARGET_DIR` to the worktree's `target/display-size-build`, `TEMP` and `TMP` to `target/identity-request-evidence/temp`, `CARGO_PROFILE_DEV_DEBUG=0`, and `CARGO_INCREMENTAL=0`. Create a fresh output directory and pass its absolute path and a fresh profile leaf within it:
```text
cargo run --locked --offline -p teamspeach-native --bin teamspeach --target x86_64-pc-windows-msvc --no-default-features --features test-harness -- --smoke identity-workflows --profile-dir <absolute-output>/profile --output <absolute-output>
```
This run used `target/identity-request-evidence/run1`. The sanitized receipt is `target/identity-request-evidence/run1/result.json`; the full command log is `target/identity-request-evidence/run1.log`. The generated profile was removed after the run.
+19
View File
@@ -0,0 +1,19 @@
# Ignored-user rendered UI evidence
## Scope
`native/src/smoke/contact_edit.rs::ignored_contact_controls_and_list_roundtrip_after_restart` exercises the native Slint UI using the existing software-renderer test platform and a temporary profile.
The test selects **Ignore User** from the visible contact context menu, restarts the app, and verifies the rendered Chats ignored-list row has the saved display name and exact UID (`NAME\nUID`). It also runs the isolated incoming-message fixture with the original UID and a different UID sharing its nickname, then selects **Stop Ignoring User** from the restored contact's visible context menu. A further restart confirms the ignored row is absent and the empty-list text is rendered. Preference bytes are checked around both writes.
Existing `ignored_users_survive_restart_and_remove_by_uid` remains unchanged and continues covering removal from the ignored-list button, failed-save atomicity, and delivery/history behavior. The runtime consumer regression also retains missing-UID roster fallback, reused client ID, late explicit ignored UID, post-unignore delivery, and history assertions.
## Verification
On the isolated `work/ignored-users` worktree, the focused Windows test command was run with `--offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- ignored_ --test-threads=1`; it reported **5 passed, 0 failed**. The selected tests included the new rendered UI regression and the existing restart/removal UI regression.
The Windows run on integration merge `946fc937342cd513330877874d5517aacd5b674a` (reviewed tip `a8157ab58d`) selected six exact tests with `webrtc,test-harness`, locked and offline. **6 passed, 0 failed, 0 ignored** in 10.41 seconds: rendered menu/list restart, list-button removal, exact-UID delivery, removed-contact scoping, invalid preference atomicity, and the language process restart. Full output is in the integration worktree at `target/ignored-users-ui-post-merge.log`.
## Limits
This is software-rendered Slint interaction with the test-harness fixture and disposable profile. It does not verify OS-native dialogs, a live server, real network traffic, or hardware behavior.
+24
View File
@@ -0,0 +1,24 @@
# Native key binding capture on Windows
Scope: [`preload:setKeybindCapture`](../../native/compatibility.json#L220), verified from `059b0c906d` plus the capture changes in the detached `keybind-capture-verify` worktree. The recorder now keeps the captured chord and its target under one lock through completion. A blur or another recorder cannot replace the target between reading the chord and saving it. Recorder events stay in capture handling and do not enter normal key matching or typing feedback.
| Exact test | Observed result |
| --- | --- |
| `smoke::key_profiles::keybind_capture::recorder_releases_then_restores_only_current_windows_bindings` | Activated the rendered binding button. The Windows backend acknowledged an empty binding set during each capture, and test-owned `RegisterHotKey` probes confirmed the formerly occupied chord was free. **Done:** a recorder-only F18 preview replaced F17; only F18 registered. **Cancel:** switching profiles during capture kept all registrations suspended; cancel registered only the new active profile's F19 and preserved the saved bytes after profile selection. **Blur:** a recorder-only F16 preview was discarded, the recorder closed, and only F19 returned. The duplicate F16 and local-only F20 never registered. All chords used Ctrl+Alt+Shift. The bound hold actions did not change the transmission counter; only the expected focus-loss invalidation occurred. The adapter stopped and all five combinations could be reacquired and released. |
| `smoke::key_profiles::audio_ptt_recorder_recovers_and_rebinds_across_two_restarts` | Existing offline PTT recorder regression passed, including cancel, invalid modifiers, save recovery and restart. It uses recorder-scoped test events, not real Windows input. |
| `services::keybinds::tests::recorder_cancel_has_no_partial_binding` | Cancel clears a partial chord; the recorder completes only on the final release. |
| `services::keybinds::tests::cancellation_ends_holds_never_fires_triggers` | In-process cancellation ends existing holds without firing release-trigger shortcuts. |
**Receipt:** `keybind-capture-verify/target/native-keybind-capture-final.log`: **4 passed, 0 failed, 0 ignored, 840 filtered out; 7.93 s**. Disposable `TEMP` had zero entries afterward. The earlier fixture run reached the blur assertion but counted the normal focus-loss invalidation as a hold action; the final test checks that invalidation separately.
The opt-in Windows test used a disposable profile and granted OS permission only to the registration adapter. It used no global monitoring or hooks, system input injection, physical devices, owner profile, or other application. Synthetic events went only to the app's recorder and focus paths. This does not exercise physical input, ordinary OS-enabled desktop startup, or other platforms.
Use Windows x64 MSVC, pinned read-only `LK_CUSTOM_WEBRTC`, an isolated `CARGO_TARGET_DIR`, and disposable `TEMP`/`TMP`. The opt-in smoke checks availability of its five test chords before starting.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact --include-ignored --test-threads=1 --nocapture `
smoke::key_profiles::keybind_capture::recorder_releases_then_restores_only_current_windows_bindings `
smoke::key_profiles::audio_ptt_recorder_recovers_and_rebinds_across_two_restarts `
services::keybinds::tests::recorder_cancel_has_no_partial_binding `
services::keybinds::tests::cancellation_ends_holds_never_fires_triggers
```
+22
View File
@@ -0,0 +1,22 @@
# Native exact-match shortcut setting on Windows
Scope: [`preload:setKeybindExact`](../../native/compatibility.json#L160), verified from `0eda270473` with the new exact-specific smoke in the detached `keybind-exact-verify` worktree. No production UI or status code changed.
| Exact test | Observed result |
| --- | --- |
| `smoke::key_profiles::keybind_exact::checkbox_persists_and_windows_owns_only_allowed_modifier_combinations` | Activated the rendered Slint checkbox in both directions. Checked the saved setting by reopening the profile and confirmed the checked and unchecked states on subsequent runtime launches. For Ctrl+Alt+F20, the local matcher accepted all four tested modifier combinations in nonexact mode and only the base combination in exact mode. The production Windows backend acknowledged four registrations in nonexact mode (base, Shift, Win, Shift+Win) and one in exact mode (base). Independent `RegisterHotKey` probes during each registration confirmed which combinations were held or free. All four could be reacquired and were released after each run. |
| `smoke::key_profiles::exact_checkbox_changes_modifier_matching_and_survives_restart` | Existing Slint and in-process regression passed: enabling exact mode survives restart, and Ctrl+F8 still matches while Ctrl+Shift+F8 no longer does. This test does not register Windows shortcuts. |
| `services::keybinds::tests::expansion_reserves_exact_chords_and_respects_limit` | Existing expansion regression passed: explicit chords take precedence over generated variants, and the request is capped at 64. This is a service-level limit check, not a 64-chord Windows test. |
**Receipt:** `keybind-exact-verify/target/native-keybind-exact.log`: **3 passed, 0 failed, 0 ignored, 840 filtered out; 2.34 s**. Disposable `TEMP` was empty afterward.
The opt-in Windows test used a disposable profile, preflighted only its four F20 combinations, and stopped the registration worker before the next settings change. The adapter was kept outside the application's action consumer and delivered zero action events. Local matching was checked with direct matcher calls, not system input. No physical presses, input injection, global hook or monitoring, other application interaction, owner profile, or hardware was used. Ordinary OS-enabled startup and other platforms were not tested.
Use Windows x64 MSVC, pinned read-only `LK_CUSTOM_WEBRTC`, an isolated `CARGO_TARGET_DIR`, and disposable `TEMP`/`TMP`. Run only when the four test combinations are available.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact --include-ignored --test-threads=1 --nocapture `
smoke::key_profiles::keybind_exact::checkbox_persists_and_windows_owns_only_allowed_modifier_combinations `
smoke::key_profiles::exact_checkbox_changes_modifier_matching_and_survives_restart `
services::keybinds::tests::expansion_reserves_exact_chords_and_respects_limit
```
+10
View File
@@ -0,0 +1,10 @@
# Native keybind registration status
Scope: [`preload:onKeybindStatus`](../../native/compatibility.json#L244), integration base `0eda270473`. The Global switch still records the requested preference. The binding's subtitle reports whether its primary chord was actually registered and names the backend; a refusal shows the backend's error on that row. The aggregate count is still a count of all attempted combinations, including extra-modifier variants where applicable. Per-binding status is scoped to the active profile and the matching configured binding.
Windows x64 MSVC, `webrtc,test-harness`: **2 passed, 0 failed, 0 ignored, 841 filtered out; 3.00 s**. Exact tests:
- `smoke::key_profiles::windows_registration_results_render_without_key_input`: the production adapter registered Ctrl+Alt+Shift+F23. The test owned the reservation for Ctrl+Alt+Shift+F24; its row rendered `Not registered (windows_registerhotkey)` and the backend's `in_use` error with the Windows detail (`os error 1409`). The other row was registered and the aggregate was `1 of 2 combinations registered`. Releasing the reservation and binding again cleared the old receipt while pending. A newer Windows acknowledgment made the F24 row read `Registered (windows_registerhotkey)` and the aggregate `2 of 2 combinations registered`. Replaying the earlier receipt through the production acceptance path as both `bound` and `rebound` left the newer receipt and rendered state unchanged. After stopping the adapter, the test reacquired and released both chords to verify cleanup.
- `smoke::key_profiles::duplicate_chord_warning_stays_in_the_profile_that_owns_it`: the duplicate warning stayed in its owning profile when a different profile was active; the OS-disabled view did not claim registration.
Artifacts: `target/keybind-status-evidence/run1/test.log`, `registration-conflict.png`, and `registration-recovered.png` (1280 x 1600 software-rendered Slint). The test opted in only its adapter and used a disposable profile. It used no keyboard monitoring, hooks, input injection, or shortcut actions. The Windows registration replies were real; the delayed replies were explicitly replayed for the generation check. No Mac, Linux portal, regular OS-enabled startup, or keyboard activation was exercised.
+28
View File
@@ -0,0 +1,28 @@
# Native public badge evidence
Integration base: `1fe5baba05`. Scope: `preload:badgeInfo` and `preload:badgeArt` in `native/compatibility.json`. The native participant context menu opens Badge Showcase in the existing detail pane. The action reads the current participant's legacy roster announcement, deduplicates up to three valid UUIDs, and binds the request to the viewed session and participant UID. This is a public catalog lookup, not verification of account badge ownership.
The badge service validates the protobuf catalog and restricts artwork to the existing fixed public origin or supported cache paths. The showcase requests detailed artwork for known IDs; its worker validates the SVG, disables resource resolvers, and produces at most a 128 x 128 premultiplied RGBA buffer for Slint. Unknown IDs, malformed announcements, and unavailable artwork do not produce a replacement badge or alter OS unread counts.
## Observed Windows result
**3 passed, 0 failed, 833 filtered out** (2.84 s test body). The caller opened the rendered participant menu, activated Badge Showcase, and inspected accessible labels and the software-rendered frame at 1280 x 900. The isolated profile loaded metadata and art from the native cache seeded through the production catalog parser, lookup, and cache writer using a deterministic in-process transport. The running app had network and OS actions disabled. No real user profile, TeamSpeak cache, or network source was read by the tests.
| Input | Observed result |
|---|---|
| `0005232e-538e-4cb2-93b6-d7d83e873829` | `PietSmiet` and `Description`; `_details.svg` fixture decoded from 1024 x 512 to 128 x 64; painted sample RGBA `(41, 172, 99, 255)` |
| `22222222-2222-2222-2222-222222222222` | Known fixture metadata, but invalid cached image showed `Artwork unavailable` without an image |
| `11111111-1111-1111-1111-111111111111` | Valid UUID absent from the catalog; `Unknown`, UUID and `Artwork unavailable` without an image |
| `not-a-uuid` | `Badge information unavailable`, with no artwork or badge row |
The additional exact component checks verified fixed-origin URL selection, protobuf deduplication, and cache reopening/provenance. The existing `ArtworkSource::Network` label in the transport-fixture test denotes the injected response path, not a live HTTP observation. The rendered artwork was a generated fixture shape, not an authentic online badge image. No online catalog availability, ownership, redemption, signed badge parsing, tree-row icons, mobile layout, or OS badge behavior is claimed.
## Reproduction
Run from the integration worktree with its own `CARGO_TARGET_DIR`, temporary `TEMP`/`TMP`, pinned Windows MSVC/WebRTC launcher, and a fresh directory in `TEAMSPEACH_BADGE_EVIDENCE` for screenshots. The run used `CARGO_PROFILE_DEV_DEBUG=0`, `CARGO_PROFILE_TEST_DEBUG=0`, `CARGO_INCREMENTAL=0`, and `TEAMSPEACH_SLINT_TEST_CHILD=smoke::public_badges::participant_showcase_renders_cached_public_badges_and_unavailable_states`.
```text
cargo test --locked --offline -p teamspeach-native --lib --target x86_64-pc-windows-msvc --no-default-features --features webrtc,test-harness -- --exact --test-threads=1 --nocapture services::badges::tests::catalog_artwork_cache_restart_and_provenance_are_real services::badges::tests::protobuf_preserves_first_valid_badge_and_fixed_origin_artwork smoke::public_badges::participant_showcase_renders_cached_public_badges_and_unavailable_states
```
Artifacts: `target/public-badge-evidence/run1/test.log`, `target/public-badge-evidence/run1/badge-showcase.png`, and `target/public-badge-evidence/run1/badge-unavailable.png`.
+21
View File
@@ -0,0 +1,21 @@
# Native rich chat composer on Windows
Verified from integration base `d436d87f71` plus the dedicated composer smoke in the detached `rich-composer-verify` worktree. No production source or toolbar code changed.
| Compatibility ID | Coverage |
| --- | --- |
| [`preference:chatRichTextEditor`](../../native/compatibility.json#L3045) | Verified in this Windows Slint fixture. The actual composer toggle was disabled during preedit and usable after commit. Switching from hybrid to raw retained the full source and the same backwards selection, translated from block-relative to full-source byte offsets. Editing, composing, bold formatting, undo, and actual refused-send retention were checked in both modes. Raw mode was observed on disk and after restarting the runtime and mounting the composer again. |
| [`current-contract:rich-editor-current`](../../native/compatibility.json#L8092) | Partial evidence only. Both modes preserved source and selection after refusal. Switching to a second conversation preserved both drafts independently and restored the original backwards selection when returning. Hybrid rendered a bold preview run and a benign `about:blank` link label with no action; raw exposed the same literal source with no preview rows. This is not full coverage of hostile previews, system IME behavior, or the broader emoji and slash completion workflow. |
The main smoke focused the actual Slint `TextInput` and dispatched in-window `UpdateComposition` and `CommitComposition` events. Preedit left committed text and selection unchanged; the commit replaced the selection with Japanese text. The test sent the normal Slint formatting, undo, and Enter events. A synthesized roster enabled the app's chat UI while the production core remained disconnected, so each send received a real `not connected to a server` refusal. Neither source nor selection was cleared. No server, network request, external link activation, OS-level input injection, system IME, or physical audio/input device was used. The profile was disposable and the generated roster was disconnected before shutdown.
**Receipt:** `rich-composer-verify/target/native-rich-composer-run.log`: **3 passed, 0 failed, 0 ignored, 843 filtered out; 5.16 s**. After testing the disposable `TEMP` contained zero entries. The two preceding runs uncovered fixture setup errors (Slint key conversion and the canonical `always-visible` value); neither produced a pass for the new smoke.
Use x64 MSVC, pinned read-only `LK_CUSTOM_WEBRTC`, a worktree-local `CARGO_TARGET_DIR`, and disposable `TEMP`/`TMP`.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact --test-threads=1 --nocapture `
smoke::rich_composer::rich_composer_preserves_native_selection_composition_and_refused_drafts `
smoke::chat::concurrent_tabs_keep_separate_drafts_and_pending_sends `
smoke::chat::chat_style_reflows_history_without_losing_live_selection_or_draft
```
@@ -0,0 +1,17 @@
# Native password backend refusal evidence
Windows x64, integration base `b8b13bbd75`. Tested only generated data in disposable application directories. No workstation lock, keyring changes, network, or user profile data.
`SecretStore::password_state` reads the index and migration marker, not the backend. `saved` records a matching bookmark/purpose/address binding, not decryptability. `required` records import re-entry, independently of `saved`. Windows DPAPI always reports `Unchecked` here; this is not a lock probe. Known unavailable metadata is limited to conditions such as an unsupported platform or an unbound Android application. Those platform conditions were inspected, not exercised on Windows.
An explicit save uses DPAPI with UI forbidden; a failed `CryptProtectData` maps to `storage_unavailable` and has no plaintext fallback. Explicit reveal maps `ERROR_NOT_LOGGED_ON` and `NTE_BAD_KEY_STATE` to `storage_unavailable`; other DPAPI unprotect failures map to `password_unreadable`. No actual OS availability refusal was induced. The existing behavior needed no change; private call-site injection lets tests exercise the service's failure handling without changing OS state or production API.
- Simulated open and seal refusal returned `storage_unavailable`. Failed replacement and failed save into an import-required slot preserved the index and migration marker byte-for-byte and across reopening. A required slot returned `password_required` before reaching the backend.
- Actual DPAPI roundtrip and tamper rejection passed. A structurally valid index with invalid DPAPI bytes remained `saved=true` and `Unchecked` before and after explicit reveal returned `password_unreadable`; no bytes were rewritten.
- A filesystem write failure after successful DPAPI sealing followed the separate `transaction_recovery_required` path. Reopening recovered the previous credential. Opening/reading metadata for an empty profile created no secret index.
**Windows result:** 5 passed, 0 failed, 829 filtered out (0.01 s test body). Log: `target/secret-backend-evidence/test.log`. Run from the integration worktree with its own `CARGO_TARGET_DIR`, disposable `TEMP`/`TMP`, pinned WebRTC toolchain, and `CARGO_PROFILE_DEV_DEBUG=0`, `CARGO_PROFILE_TEST_DEBUG=0`, `CARGO_INCREMENTAL=0`:
```text
cargo test --locked --offline -p teamspeach-native --lib --target x86_64-pc-windows-msvc --no-default-features --features webrtc,test-harness -- --exact services::secrets::tests::backend_refusal_keeps_saved_password_and_required_marker services::secrets::tests::actual_dpapi_unreadable_blob_remains_saved_metadata services::secrets::tests::actual_dpapi_isolated_roundtrip_and_tamper_rejection services::secrets::tests::actual_dpapi_failed_atomic_save_preserves_disk_and_requires_reopen services::secrets::tests::open_status_and_not_saved_do_not_touch_os_keyrings_or_create_secret_file
```
+26
View File
@@ -0,0 +1,26 @@
# Native shortcut edits on Windows
Scope: [`preload:setKeybinds`](../../native/compatibility.json#L148), verified from `7db69358fd` plus the shortcut changes in the detached `set-keybinds-verify` worktree.
The Key Bindings editor now keeps all warnings when a binding has multiple conflicts. A missing whisper-list target is shown as unselected, even when another list is available. The existing conflict filter still excludes those bindings from registration.
| Exact test | Observed result |
| --- | --- |
| `smoke::key_profiles::edited_profile_reopens_with_conflicts_excluded_from_windows_registration` | Opened the binding editor through the Slint callback and saved Ctrl+Alt+Shift+F23 in place of Ctrl+Alt+Shift+F19 using the real Done action. Supplied only the pending chord value, not key input. After restart, Slint rendered F23, the two duplicate/PTT warnings for each affected row, and the missing-list warning with no selected replacement list. The other profile still showed Ctrl+Alt+Shift+F21. Full `keybinds.json` comparisons after save and restart found only the intended chord change. The Windows backend returned exactly two successful registrations: the edited binding and the dedicated F24 push-to-talk binding. It did not attempt either conflicting F24 binding or the missing-list binding. The adapter stopped and emitted no action events. |
| `smoke::key_profiles::duplicate_chord_warning_stays_in_the_profile_that_owns_it` | Inspecting the conflicting profile left the clean profile active and showed the warnings only in the owning profile. |
| `services::keybinds::tests::invalid_binding_edits_and_failed_save_preserve_previous_bindings` | Validation and a failed save preserved the previous binding state on disk and in memory. |
| `services::keybinds::tests::conflicts_block_both_duplicates_ptt_and_missing_list` | The runtime conflict check still blocked both duplicate bindings and identified the PTT and missing-list cases. |
**Receipt:** `set-keybinds-verify/target/native-set-keybinds.log`: **4 passed, 0 failed, 0 ignored, 837 filtered out; 2.31 s**. The worktree-local disposable `TEMP` was empty after the run.
The Windows test was explicitly opted in. It ran with a disposable profile and held the real registrations only until the backend receipt arrived. The adapter was outside the application's action consumer; no keyboard monitoring hook, key injection, real action trigger, audio hardware, other application, or owner profile was used. Physical key capture, ordinary OS-enabled startup, and other platforms were not tested.
Use the x64 MSVC environment, pinned read-only `LK_CUSTOM_WEBRTC`, an isolated `CARGO_TARGET_DIR` and disposable `TEMP`/`TMP`. The two real registrations require free Ctrl+Alt+Shift+F23 and F24 combinations.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact --include-ignored --test-threads=1 --nocapture `
smoke::key_profiles::edited_profile_reopens_with_conflicts_excluded_from_windows_registration `
smoke::key_profiles::duplicate_chord_warning_stays_in_the_profile_that_owns_it `
services::keybinds::tests::invalid_binding_edits_and_failed_save_preserve_previous_bindings `
services::keybinds::tests::conflicts_block_both_duplicates_ptt_and_missing_list
```
+24
View File
@@ -0,0 +1,24 @@
# Native preference writes on Windows
Scope: [`preload:setPrefs`](../../native/compatibility.json), verified from `1883ab95d5` plus the three test changes. The legacy IPC contract is covered by Rust/Slint's typed settings controls and the native preference service; there is no new IPC endpoint. No production code changed.
| Exact test | Observed result |
| --- | --- |
| `smoke::display_size::display_size_survives_failed_save_and_two_restarts` | Activated real Slint Display Size radios and checked the selected radio, in-memory preference, on-disk value and sidebar geometry after saving and across two runtime restarts. With a directory blocking `prefs.json.tmp`, the Medium selection was refused with `io`. A visible shell banner carried the exact error message, Large remained selected, and the preference file was byte-for-byte unchanged. The second restart retained Large. This ran in English and Russian, for light and dark themes. |
| `services::prefs::tests::generic_preference_patch_rejects_protected_fields_atomically` | Rejected an unknown setting (`bad_request`), a forged absolute `recordingFolder` (`capability_required`), and each of the two legacy `savedServers` ciphertext fields (`secret_write_forbidden`). Every case ran alone and mixed with a valid change from Small to Large. Each refusal preserved the entire in-memory value and the exact file bytes. The dedicated setter still persisted a disposable destination across reopen; a generic patch could not clear it. |
| `ui::settings::tests::recording_destination_has_only_a_read_only_label_and_chooser_intent` | The shipped Audio settings builder presented the destination as a read-only label and the only destination action as `Operation::ChooseRecordingDirectory`, not a generic field edit. The runtime routes that typed action to the [directory-grant workflow](../../native/src/app/runtime/file_actions/io.rs), which checks a desktop chooser grant before calling the dedicated setter. The test did not open an OS picker. |
| `services::prefs::tests::migrations_preserve_voice_choices_layout_and_confirmation` | Existing load-time preference normalization still passed. |
The preference service already stages the patch and validates it before persistence; it publishes the new in-memory values only after persistence succeeds. This run needed no atomicity fix. It did not exercise an OS permission prompt, real password storage, recording, a server connection, or audio hardware. The smoke used `AppConfig::isolated`; test waits checked that neither audio endpoint started. The password inputs were dummy base64, and no owner profile or user keyring was used.
**Receipt:** Windows x64 MSVC, detached verification snapshot `set-prefs-verify`, independent Cargo output and pinned read-only WebRTC. `target/native-set-prefs.log`: **4 passed, 0 failed, 0 ignored, 834 filtered out; 6.88 s**. The disposable `TEMP` directory had zero entries after testing.
With the x64 Visual Studio environment, pinned `LK_CUSTOM_WEBRTC`, a worktree-local `CARGO_TARGET_DIR`, disposable `TEMP`/`TMP`, and `CARGO_PROFILE_DEV_DEBUG=0`, `CARGO_PROFILE_TEST_DEBUG=0`, `CARGO_INCREMENTAL=0`:
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact --test-threads=1 --nocapture `
services::prefs::tests::generic_preference_patch_rejects_protected_fields_atomically `
services::prefs::tests::migrations_preserve_voice_choices_layout_and_confirmation `
ui::settings::tests::recording_destination_has_only_a_read_only_label_and_chooser_intent `
smoke::display_size::display_size_survives_failed_save_and_two_restarts
```
+21
View File
@@ -0,0 +1,21 @@
# Native sidebar icon mode (Windows)
Scope: [`preference:sidebarIconMode`](../../native/compatibility.json#L2682), integration base `6b10e0b174`. The installed TeamSpeak 6.0.0.5232 JS and CSS matched the hashes in the [visual source map](official-parity/visual-source-map.md). `main.js` at character 2731865 computes the detailed sidebar mode as Large or Large When Collapsed with a collapsed sidebar; the render passes it to Activities and Resources at 2734869 and 2736537. The appearance options are Small, Large, and Large When Collapsed at 4600670 onward. `main.css` at 26104 defines the 33 px large and 22 px standard icon tokens, and at 423205 aligns the detailed primary icon with the standard slot. This is a sidebar row icon setting, not a server-tree badge setting.
Native now uses the saved setting for connection and bookmark activity glyphs. It keeps the existing 44 px rows, visible captions in the expanded sidebar, accessible row names on the rail, and separate branding and action icons.
| Saved mode | Expanded sidebar (420 px) | Collapsed rail (62 px) | Expanded at 900 px window width |
|---|---:|---:|---:|
| Small | 22 px | 22 px | 22 px |
| Large | 33 px | 33 px | 33 px |
| Adaptive | 22 px | 33 px | 22 px |
The rendered Appearance combobox selected the localized popup option and the test checked its save receipt and exact saved mode. The table held on Windows in English and Russian, in dark and light, immediately and after reopening each saved mode. At 900 x 800 the expanded sidebar clamped to 385 px without overwriting the saved 420 px width. Both connections and both bookmarks remained in order; expanded captions did not overlap the glyphs, and collapsed rows retained their accessible labels. The viewed tab stayed selected, the other connection kept input ownership, and the same channel conversation and checkpoint message remained through each live change. Each reopen reconstructed the fixture roster and reselected its channel; this is not a claim of live connection or voice restoration across restarts.
**Receipt:** Windows x64 MSVC, locked/offline, `webrtc,test-harness`, **3 passed, 0 failed, 0 ignored, 848 filtered out; 104.41 s**. Exact tests:
- `smoke::sidebar_icon_mode::sidebar_icon_modes_render_and_reopen_without_changing_ownership`
- `smoke::tabs::bookmark_disclosure_restores_hidden_rows_after_restart`
- `smoke::tabs::desktop_pane_drags_remain_visible_and_persist_across_restart`
Log and captures: `target/sidebar-icon-evidence/run5/`, including `ru-light-reopened-large-expanded.png`, `ru-light-reopened-adaptive-rail.png`, and `en-dark-clamped-small-expanded.png`. The run used disposable profiles and offscreen Slint with synthetic rosters only. Neither audio endpoint started. No network, owner profile, OS settings, external window, mobile layout, or full official screenshot comparison was exercised.
@@ -0,0 +1,15 @@
# Native P2P stream setup: cancelled registration
Windows x64; branch `work/stream-setup`, base `caf29f4`. The isolated worktree kept the output in its own `target/` and used the existing prebuilt WebRTC dependency.
`notifystreamstarted` supplies the publishing client ID and assigned stream ID, not the setup request identity. A replacement used to take the same tab's publisher slot after local cancellation but before the old start notification arrived. The chooser and the slot reservation now refuse a replacement while the cancelled setup is unresolved. The source stops immediately; the old publisher keeps ownership of the late ID and sends `stopstream` for it. The slot can be reused once that command has completed, or after the old server session is gone. The raw command schema is unchanged.
Command (Visual Studio x64 environment, with `CARGO_TARGET_DIR` set to the isolated `target/`):
```text
cargo test --locked --offline -p teamspeach-native --lib --no-default-features --features webrtc publisher_
```
Result: **13 passed, 0 failed** in the isolated worktree after resuming from the partial dependency build. The new hub-level regression exercises cancellation before the setup reply, blocks reuse before the late ID and during unregister, verifies one stop for the old ID, and then reserves a fresh publisher without an ID. The existing early-ID regression still checks that setup acceptance is required for `Live` and that refusal releases the source. Both use in-process signaling fixtures, not a running server. The earlier attempt in the primary checkout timed out during dependency setup; no test result came from that attempt.
Not exercised here: the real OS source chooser, its no-capture-until-Preview boundary, physical capture consent, or a real server refusal rendered by the chooser workflow. No beta14 fixture, network connection, real device, or owner profile was used. `command:stream_setup` remains pending.
@@ -0,0 +1,11 @@
# Stream setup integration receipt
`work/integration-verified`: merged reviewed stream tip `41d0a387e1493dedaaa1f5ed55d32ef2bab8c374` (including `f1455937413ba336dff39a579886126d897ba34e`) into `4bfdc5cf448eb25d1f99d195b6b9536d5e63397b`. Tested merge: `eb27e9c89662b0b33adb6db84ad807ffbf292108`. The merge was automatic. Relative to the first parent, the runtime changes are scoped to capture selection, its prompt guards and its detail cleanup; the integrated language and channel editor reconnect code was retained.
Windows x64, integration-local Cargo target and temporary output, existing prebuilt WebRTC dependency read-only. Verification command:
```text
cargo test --locked --offline --target x86_64-pc-windows-msvc -p teamspeach-native --lib --no-default-features --features webrtc,test-harness -- --exact smoke::capture_selection::slint_capture_selection_cancel_revokes_only_its_flow media::stream::signal::tests::publisher_late_setup_id_is_unregistered_before_slot_reuse ui::shell::tests::admin_editor_slint_keeps_draft_until_matching_server_ack --test-threads=1
```
All three passed: 0 failures, 0 ignored, 2.18 s test body. Local full log: `target/stream-setup-post-merge.log`. This run covered the rendered, catalog-only capture chooser, publisher late-ID ownership, and adjacent Slint channel/server editor acknowledgement handling. It did not rerun language or live reconnect acceptance, open OS capture, use a device, or contact beta14 or an external server. No compatibility status change or push.
+22
View File
@@ -0,0 +1,22 @@
# Native tab events on Windows
Scope: [`preload:onEvent`](../../native/compatibility.json), whose criterion covers state, snapshot and text delivery to the owning tab or conversation, including detach and reconnect. The native client consumes typed connection events; no Electron event dispatcher was added.
| Case | Evidence |
| --- | --- |
| Two live sessions | The existing Slint text smoke connected two distinct, muted test identities to private loopback beta14. Each tab's server snapshot reported its own client ID and the two expected guests. Both snapshots observed the temporary room and each tab joined it. Private and channel messages appeared exactly once in the sender and recipient conversations, with the expected sender UID. The server-chat attempt was refused by guest permissions and left its draft intact; successful server-chat delivery is not claimed. |
| Detach and reconnect | The extended live smoke received one channel message with no UI attached. It then disconnected only the recipient, verified that the sender stayed in the room, and reconnected the recipient's original tab under a newer session and generation. Reattaching Slint restored the earlier and detached messages once each. Another live channel message rendered once in the replacement conversation, with no replay of either earlier message. |
| Stale controls | The live smoke also submitted a synthetic text control through `fixture_control` with the retired recipient key. It got `TargetChanged`, and no such text appeared in the replacement conversation. Separately, the existing reducer test injected stale state, snapshot and text controls with a mismatched core generation or worker incarnation and checked that none reached the event sink. These are controlled injections, not delayed network packets. |
**Receipts:** `target/native-tab-events.log` records `app::connections::tests::state_transitions_revoke_sessions_and_ignore_foreign_generation_and_worker`, **1 passed, 0 failed**. A second Cargo invocation encountered an unrelated, concurrent `ClientBadges` enum change; it did not produce a live result. The [fixture runner](../../native/tests/fixtures/beta14-server-admin.ps1) ran the exact `smoke::chat::send_text_delivers_exact_private_and_channel_messages_on_beta14` test from the binary already built for the reducer check. `target/native-tab-events-live.log` records **1 passed, 0 failed, 0 ignored; 41.78 s**. Teardown found zero fixture UDP/TCP listeners and zero disposable temp directories. No owner profile, remote server, or audio hardware was used.
## Reproduce
Use x64 MSVC, a worktree-local `CARGO_TARGET_DIR` and disposable `TEMP`/`TMP`. Set `LK_CUSTOM_WEBRTC` to the pinned WebRTC build and `TEAMSPEACH_BETA14_RELEASE` to the staged Windows beta14 release. The exact live test needs free UDP 19987 and TCP 30053/19080; the runner disables Query before guest connections.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact app::connections::tests::state_transitions_revoke_sessions_and_ignore_foreign_generation_and_worker
$runner = (Resolve-Path 'native/tests/fixtures/beta14-server-admin.ps1').Path
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $runner"
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --include-ignored --test-threads=1 --nocapture --exact smoke::chat::send_text_delivers_exact_private_and_channel_messages_on_beta14
```
+24
View File
@@ -0,0 +1,24 @@
# Native tab request on Windows
The [`preload:request` criterion](../../native/compatibility.json) covers a typed request tied to a tab, validation at the accepted string boundary, profile-only routing, and rejection of an old result after reconnect. Native Slint sends typed intents to the connection manager; it has no generic Electron dispatcher. The standalone core binary is the retained string-based stdio boundary.
| Criterion | Observed evidence |
| --- | --- |
| Acknowledged result belongs to the requesting tab | Fresh Windows beta14 `participant_info_menu_reads_exact_muted_beta14_guest` passed. With two muted guests on separate tabs, Slint's Client Info result matched the independently requested rows for the captured client ID and UID. Switching from A to B removed A's title and properties from the rendered pane before B requested its own result. The test also checks guest-to-peer permission outcomes without modifying permissions. |
| Invalid string command and arguments | Fresh standalone core `client_menu_commands_are_validated_and_never_fake_success_offline` passed. The process returned `unknown_command` for an unsupported name and `bad_request` for malformed known command arguments; a valid scoped request on the disconnected core returned `not_connected`. No identity or secret was needed for this check. |
| Profile-only operations | Fresh Slint `reattached_identity_details_keep_nondefault_uid_and_its_bookmarks` passed using a disposable vault. A typed nickname edit updated only the selected nondefault UID; changing the default reassigned the implicit bookmark in the identity view without writing an explicit UID. The settings actions use `ProfileServices.identities`, not the tab request path. This does not remove profile commands from the standalone diagnostic binary. |
| Reconnect before the old result reaches the UI | Reused the [channel edit replacement evidence](official-parity/channel-edit-replacement-beta14.md) and integration receipt `target/channel-crud-edit-replacement-live.log` at ancestor `802bd302731c2e43dce8f35851387acf19a83f29` (1 passed, 75.33 s). The connection manager, controller, gate and exact smoke were unchanged; the runtime and UI diffs kept the successful completion ownership checks and fence. The server had already accepted the write; the test held delivery of its completion, not socket traffic. This test was not rerun for the current slice. |
**Fresh receipt:** `target/native-tab-request.log`: stdio **1 passed** (0.28 s), typed Slint identity **1 passed** (1.76 s), and exact live two-tab Slint result **1 passed** (48.76 s). The runner stopped the fixture and removed its runtime. The outer cleanup check found no fixture listeners (UDP 19987 and TCP 30053/19080) but returned nonzero because it counted one empty MSBuild scratch directory; that directory and its temporary parent were removed separately. The run used only disposable state and loopback; no physical audio endpoints opened.
## Reproduce
From the integration worktree with x64 MSVC active, set `LK_CUSTOM_WEBRTC` to the existing pinned archive, `CARGO_TARGET_DIR` to the worktree's `target/`, and `TEMP` and `TMP` to a disposable directory. The live step needs a separately staged Windows beta14 release in `TEAMSPEACH_BETA14_RELEASE` and free fixture ports.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-core --test bridge_smoke -- --exact client_menu_commands_are_validated_and_never_fake_success_offline
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact smoke::identities::reattached_identity_details_keep_nondefault_uid_and_its_bookmarks
$runner = (Resolve-Path 'native/tests/fixtures/beta14-server-admin.ps1').Path
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $runner"
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --include-ignored --test-threads=1 --nocapture --exact smoke::tabs::participant_info_menu_reads_exact_muted_beta14_guest
```
+19
View File
@@ -0,0 +1,19 @@
# Native theme preference (Windows)
Scope: [`preference:theme`](../../native/compatibility.json#L2638) and, separately, [`preference:userStyle`](../../native/compatibility.json#L2825). Tested from integration base `7db69358fd` with the selection fix below and the concurrently integrated shortcut changes. The Windows MSVC `webrtc,test-harness` run used isolated profiles and software-rendered Slint at 1280 x 800.
| Contract | Fresh observation |
|---|---|
| `theme`: pass in the exercised native scope | Activated the rendered Dark, Light, and System radios. After the first reopen, Light was selected and painted `(245, 245, 245, 255)`; after the second, System was selected and painted the same light color after a synthetic platform event. System also followed a dark event and painted `(43, 51, 70, 255)`. A blocked atomic save (`io`) and invalid mode (`bad_request`) left the System radio, painted dark background, in-memory value, and exact preference bytes unchanged. |
| `userStyle`: pass in the exercised native scope | The local picker previewed Plum without saving and then chose it. The settings background painted `(128, 80, 128, 255)`, and the live package title requested Consolas at 18 px from the 19 px theme base. The first reopen retained all three. A blocked save (`io`) and a listed variant with a non-UTF-8 stylesheet (`css`) retained Plum, appearance, and exact preference bytes. Reload applied the edited stylesheet: `(48, 112, 128, 255)` and Georgia at 20 px from a 21 px base, with the same saved key and bytes. The second reopen retained the updated appearance. Removing the package and reloading cleared the missing key, displayed a diagnostic, and restored the stock background. |
Selection now resolves the candidate before saving `userStyle` and publishes that same resolution after a successful save. Previously an unresolvable stylesheet could produce an error after its key had already been saved.
**Fresh receipt:** `target/theme-preference-evidence/run2/test.log`: **4 passed, 0 failed, 0 ignored, 838 filtered out; 11.06 s**. Captures are in the same directory. The run selected only these tests:
- `smoke::theme_selection::stock_theme_modes_paint_and_survive_two_reopens_and_rejected_edits`
- `smoke::theme_selection::selected_variant_survives_restart_and_restores_stock_on_removal`
- `services::themes::tests::package_scan_selection_persistence_and_missing_diagnostic`
- `services::themes::tests::five_minute_cache_refresh_and_late_selection`
**Reused evidence:** the existing [Theme ZIP import receipt](../../FEATURE_COMPATIBILITY.md#L421) covers native chooser installation, a visible unsupported-selector warning, refusal of external stylesheet references before publication, and the focused resource and archive confinement checks. The [supported subset](../themes.md#supported-css-subset-not-a-browser-engine) is parsed as data; the product has no CSS or JavaScript execution host. Those rejection checks and the OS chooser were not repeated. The fresh run used local installed fixtures and synthetic desktop theme events; it made no network requests or OS theme changes. Font assertions verify the live native text item's request, not backend glyph identity, font registration, or cross-platform rendering.
+32
View File
@@ -0,0 +1,32 @@
# Native tree badge evidence
Scope: `preference:showBadges` in `native/compatibility.json`. The native Appearance switch controls compact public badge icons on desktop participant rows; Badge Showcase remains separately available and loads detailed artwork. The tree shows no placeholder for unknown UUIDs, malformed announcements, or unavailable artwork. A roster announcement selects public artwork; it is not proof of badge ownership.
## Reference and retry behavior
The installed 6.0.0.5232 bundle matched both SHA-256 fingerprints in [the visual source map](official-parity/visual-source-map.md). `main.js` offsets 3904162 and 3908288 gate the inline group icons with `show_server_badges`; offset 4131354 uses a separate detailed Showcase. The stock 16 px icon edge comes from `main.css` offsets 411703 and 616945 (24 px row height minus two 2 px vertical pads and the icon's 4 px inset); offsets 407154 and 407784 resolve the inter-icon gap to 6 px. Native reserves room for the title and existing status marks and omits excess icons when they do not fit. This is source correspondence and targeted native capture, not a full pixel comparison of the official tree.
Each viewed server snapshot is parsed once for tree badges while it remains current. Unrelated app snapshots reuse that projection; lookup checks session, client number, and exact UID. Up to 200 public UUIDs share cached decoded art and one Slint image per UUID, with one eight-ID batch in flight. Failures are retained during the current enabled interval unless evicted by the cache bound. Off → On clears negative entries and ignores late negative results from the previous interval; successful results stay reusable. Local artwork is checked again on re-enable; the underlying catalog and artwork service still applies its network retry cooldown.
## Observed Windows result
The focused run passed all eight exact tests (0 failed, 0 ignored, 831 filtered out, 30.37 s). At 1280 x 1100, `reopen-1-off.png` showed no compact icons; `retried-on.png` showed two on the marked participant and one on the shared participant, with the country flag, contact highlight, and owner status marks still visible. The test measured 16 x 16 px icons, a 6 px gap, and center samples of RGBA `(41, 172, 99, 255)`. `reopen-2-on.png` captured the persisted enabled state. The badge squares were generated fixture artwork, not live public artwork. The run did not exercise real network recovery or compare full screenshots against the official client.
Artifacts: `target/tree-badge-evidence/run5/`.
## Local contacts and public badges contract
**Pass at `96b6f2aaef`**, for the Windows native, account-free scope of [`current-contract:contacts-badges-current`](../../native/compatibility.json#L8081). The rows below reuse exact tests from the eight-pass receipt above; no additional scenario was needed.
| Matrix requirement | Direct native observation |
|---|---|
| Add and alias a local UID contact; restart | [`offline_contact_editing_persists_across_restarts`](../../native/src/smoke/contact_edit.rs#L171) added the UID and name through the rendered Contacts UI, set and cleared the alias, and checked the saved UID and alias on reopen. The visible alias fell back to the saved name when cleared. |
| Presence comes from connected snapshots | The reopened contact had no session and rendered the localized offline label in that same test. With a connected synthetic roster, [`contact_sort_uses_saved_mode_after_two_restarts`](../../native/src/smoke/tabs.rs#L3762) showed the present UID under alias `Zulu` with the `Fixture` server subtitle, ahead of absent `Alpha` in presence order after both reopens. [`sessions_for`](../../native/src/services/contacts.rs#L96) reads only connected snapshots and matches exact UIDs. |
| Highlight only the saved UID | [`contact_highlight_follows_uid_and_saved_appearance_setting`](../../native/src/smoke/contact_edit.rs#L477) preserved the disabled setting across reopens, highlighted the saved UID after re-enable, and left a different UID reusing the same client number unmarked. |
| View public badge art; retain tree behavior on reopen | [`participant_showcase_renders_cached_public_badges_and_unavailable_states`](../../native/src/smoke/public_badges.rs#L28) opened Badge Showcase with tree badges off and painted cached `PietSmiet` fixture art (RGBA `41,172,99,255`); unknown, unreadable, and malformed cases showed no replacement artwork. [`tree_badges_follow_appearance_across_reopens_and_rejected_edits`](../../native/src/smoke/tree_badges.rs#L79) verified that the tree's off and on states persisted across reopens and the replacement UID inherited neither the icon nor the highlight. |
These are separate checks with disposable profiles and synthetic rosters. They do not claim live server or catalog access, cloud contacts or presence, badge ownership, or redemption.
## Reproduction
Use the isolated Windows MSVC `webrtc,test-harness` build and the exact tests recorded in `target/tree-badge-evidence/run5/test.log`. The tree test drives the rendered `Show User Badges` switch across two reopens, samples the actual 16 px icon pixels, and checks failed save, invalid input, UID replacement, disconnect, and recovery after explicit re-enable. It keeps the same successfully decoded raster on retry. The separate Showcase test opens the participant menu and checks detailed artwork with the tree badges preference off. The tests use disposable profiles and synthetic legacy roster events; they do not use live servers, a production profile, or the official cache.
+20
View File
@@ -0,0 +1,20 @@
# Native Windows window state
Scope: [`preload:getWindowState`](../../native/compatibility.json#L952) and [`preload:onWindowState`](../../native/compatibility.json#L964), verified on Windows from `6b10e0b174` plus the changes in the detached `window-state-verify` worktree. No legacy IPC endpoint or custom caption buttons were added.
| ID | Windows evidence |
| --- | --- |
| `preload:getWindowState` | The native handle and the mounted Slint root agreed on normal, maximized, restored, borderless fullscreen, and restored again. Maximized and minimized flags come from Win32; fullscreen comes from the installed borderless frame and client bounds covering the current monitor, not from the last fullscreen request. The test separately checked the real caption style and Win32 maximized state on its own HWND. |
| `preload:onWindowState` | Native maximize/restore system commands sent directly to the owned HWND and borderless fullscreen requests through the desktop handle updated the mounted Slint properties. When the attachment was dropped, its handle stopped returning state and rejected further actions with `ui_destroyed`. The retained old HWND was maximized after a replacement attached; neither the detached Slint view nor the replacement view adopted that state. The replacement then changed and restored independently. |
The Windows observer publishes changed state to the current Slint generation without polling on UI ticks. Fullscreen and minimized observations are not persisted as ordinary window placement. Windows keeps ownership of native caption controls. The test inspected the actual window style and used the native commands backing the maximize and restore controls; it did not click the title bar or use system input injection.
**Receipt:** `window-state-verify/target/native-window-state-final.log`: **1 passed, 0 failed, 0 ignored, 849 filtered out; 0.49 s**. The parent test ran the same exact case in a separate visible Winit/software child process (0.46 s in the child). Both fixture HWNDs were destroyed, the disposable runtime shut down with no connections or audio devices started, and `TEMP` was empty afterward.
Only the desktop window adapter was enabled for the disposable profile. No user window, input hook, keyboard injection, screen capture, or OS configuration was used. The test used borderless fullscreen, not exclusive fullscreen. Mobile scene state and other operating systems were not verified here.
Use Windows x64 MSVC, pinned read-only `LK_CUSTOM_WEBRTC`, an isolated `CARGO_TARGET_DIR`, and disposable `TEMP`/`TMP`. Run explicitly in a Windows desktop session that can show the fixture windows.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --exact --include-ignored --test-threads=1 --nocapture smoke::window_state::owned_windows_report_actual_state_and_stop_at_detach
```
@@ -0,0 +1,20 @@
# Native channel CRUD evidence map
The [native `feature:channel.crud` gate](../../../native/compatibility.json) asks for native UI operations and acknowledged readback, destructive cancellation without mutation, visible permission refusal, and isolation across reconnect. The [official matrix](final-feature-matrix.json) records historical controlled verification; that is not a substitute for these native runs. Prior receipt numbers below refer to archived local test output; see the [Windows handoff](../../mobile-port-progress.md) and [compatibility notes](../../../FEATURE_COMPATIBILITY.md) for fixture context.
| Behavior | Prior native test and receipt | Observed on private Windows beta14 |
| --- | --- | --- |
| Create and edit | `channel_create_from_toolbar_and_edit_on_beta14` (`789`); `protected_channel_join_from_tab_keeps_lobby_until_password_accepted` (`870`) | The form rejected invalid input. Cancel did not create the draft room or change the saved edit. Successful create/edit appeared in the tree, roster and reopened editor. A guest edit refusal kept the draft and left the owner's topic unchanged on both tabs. |
| Description | `channel_create_from_toolbar_and_edit_on_beta14` (`789`); `channel_create_description_is_read_back_on_beta14` (`793`) | Multiline readback in the editor, Channel Info and a separate description request; cancel preserved it and clearing returned an explicit empty string. Authorized create-with-description also passed, superseding the older unverified note. |
| Move | `moving_an_occupied_channel_preserves_its_id_and_updates_both_guests` (`853`) | Cancel preserved the parent and order; the accepted move preserved the occupied channel ID and both guests saw the new position. The earlier insufficient-depth run (`852`) displayed permission ID 86; it was not a passing denial-and-no-change scenario. |
| Delete | `deleting_an_occupied_channel_requires_its_name_and_updates_both_guests` (`848`) | Wrong name and cancellation preserved the room. A guest refusal was visible; authorized deletion removed the occupied room from both trees. |
| Subscribe and unsubscribe | `channel_subscriptions_follow_the_owning_beta14_tab` (`716`) | Single and bulk toggles produced newer snapshots while the peer tab stayed unchanged. Restricted subscribe visibly failed and left the flags unchanged. |
| Older stale replies | `create_and_edit_channel_replies_cannot_cross_a_session_boundary`, `move_reply_cannot_update_a_replacement_session_with_the_same_channel_id`, and `delete_reply_cannot_update_a_replacement_session_with_the_same_channel_id` (`869`) | The connection tests held offline refusals and delivered them after simulated session replacement. They did not exercise successful live mutations. |
## Exact live reconnect receipt on integration
Tested merge `802bd302731c2e43dce8f35851387acf19a83f29`, with `ec580edc90adef7e6d9c0feee2979b6dd04a19be` as its second parent. The exact [replacement smoke](../../../native/src/smoke/channel_edit_replacement.rs), `smoke::tabs::channel_edit_replacement::acknowledged_channel_edit_cannot_complete_replacement_editor_on_beta14`, used locked, offline Cargo with `webrtc,test-harness`, the [checked-in disposable runner](../../../native/tests/fixtures/beta14-server-admin.ps1), and the existing pinned WebRTC build. Result: **1 passed, 0 failed, 0 ignored, 816 filtered out, 75.33 s**. Full local output: `target/channel-crud-edit-replacement-live.log`. The runner reported shutdown and directory removal; the independent teardown check found zero listeners on UDP 19987 and TCP 30053/19080 and zero fixture runtime directories.
The connected observer read `Fixture seed` and then `Fixture seed / original edit` on channel 2 before the initiator disconnected. The same native tab reconnected under another identity (session 0 to 1, generation 1 to 2) and saved `Fixture seed / original edit / replacement edit`. With both successful results held, the [test-only gate](../../../native/src/app/runtime/channel_edit_test_gate.rs) released the original result and waited for the runtime-to-Slint effect fence. The replacement editor stayed busy with its exact draft; the channel row, details, status and errors did not change. Only the replacement result closed that editor. The independent observer still read the replacement topic. The [source-branch receipt](channel-edit-replacement-beta14.md) documents the fixture and reproduction command.
This verifies **successful topic edit completion delivered after a real reconnect**. The server had already accepted the first write, so no network packet was delayed, no disconnect before server acknowledgement was tested, and no write was rolled back. The reconnect case does not cover other mutations, exhaustive properties or permission blocks, or voice behavior. The native gate and its status are unchanged.
@@ -0,0 +1,31 @@
# Successful channel edit delivered after reconnect
The Windows Slint smoke used a private 6.0.0-beta14 loopback server. Bootstrap WebQuery created permanent scratch channel `Channel Edit Receipt QA` with topic `Fixture seed` and granted `b_channel_modify_topic` to the disposable guest group. Query was disabled for the live scenario. Both guests were muted; the shared harness checked that no audio devices opened.
The Windows test-only gate holds a successful result for the exact editor ID and target after the normal controller returns, just before it sends `ServerEditorComplete`. It does not delay socket traffic or inject replies. Upon release, an ordered marker follows the event through the runtime's snapshot publication and Slint effect pump.
| Checkpoint | Observation |
| --- | --- |
| Before the first edit | The observer's `channel_info` on channel 2 reported `Fixture seed`. |
| First success held | The observer read `Fixture seed / original edit` before the initiator disconnected. It stayed connected and saw the original guest leave. |
| Same tab, new connection | Session 0 became 1, generation 1 became 2, and the initiator UID changed. The observer UID stayed the same. The replacement opened Channel Info and a distinct editor for the same channel; both initially showed `Fixture seed / original edit`. |
| Replacement success held | The actual Slint edit box was busy with `Fixture seed / original edit / replacement edit`. The replacement roster and the independent observer also had that newer server topic. The separately queried Channel Info panel had shown the preceding topic; it was not the edit box or the persisted-topic check. |
| Old success released | The replacement editor remained open and busy with its exact draft. The pre/post comparison covered the channel row, detail labels and values, viewed tab, input owner, shell and runtime status and errors, and dialog error. The test permits only an empty shell error or the normal changed-target notice already present at baseline; whichever is present must stay identical. The first run observed `The captured server or client has changed` at baseline before the original success was released. |
| Replacement success released | The replacement's own result closed its editor. The observer again read `Fixture seed / original edit / replacement edit`. The original write was not rolled back; the second write superseded it. |
The observer used its own connected core. Its `channel_info` returns the topic from that core's server-fed roster, with a wire request for the channel description. It does not read the initiator's cache or use WebQuery for the topic.
The exact offline, locked test reported **1 passed, 0 failed, 812 filtered out** in 75.49 s using pinned WebRTC. The fixture stopped and removed its private runtime. An independent check found zero UDP listeners on 19987, zero TCP listeners on 30053 and 19080, and zero matching private runtime directories. This covers a successful topic edit and delayed completion delivery, not channel create/delete, loss of the socket before acknowledgement, or exhaustive CRUD parity.
## Reproduce
Use the [checked-in runner](../../../native/tests/fixtures/beta14-server-admin.ps1) with a separately staged Windows beta14 release. The worktree path must not contain spaces when setting the Cargo runner below, and the three fixture ports must be free. The runner creates fresh private state and a temporary bootstrap key; no credentials or executables are checked in.
```powershell
$env:TEAMSPEACH_BETA14_RELEASE = 'C:/path/to/staged/beta14/release'
$env:LK_CUSTOM_WEBRTC = 'C:/path/to/pinned/webrtc'
$env:CARGO_TARGET_DIR = Join-Path $PWD 'target/cargo-capacity'
$runner = (Resolve-Path 'native/tests/fixtures/beta14-server-admin.ps1').Path
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $runner"
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --include-ignored --test-threads=1 --nocapture --exact smoke::tabs::channel_edit_replacement::acknowledged_channel_edit_cannot_complete_replacement_editor_on_beta14
```
@@ -0,0 +1,32 @@
# Windows beta14 `command:fetch_banner` receipt
Base: `b370474999` on `work/integration-verified`. The compatibility entry requires a positive channel ID, rejection of unknown fields, server-authorized fetching, selected-channel artwork, and a fallback on missing or failed artwork without opening arbitrary URLs.
**Pass on private classic beta14.** The runner seeded an 8 x 2 PNG in disposable classic storage and advertised a `ts3image://` reference on the scratch channel. A real native guest retrieved the exact 74 bytes, MIME `image/png`, SHA-256 `fbedfd286063b8b7ad2108d4c6b67107330671d3b8fa88a89bfb2a94b6aa92bc`. The selected channel row painted RGB `[213, 37, 107]`; its neighbor stayed `[27, 35, 54]` and the selection outline stayed `[21, 136, 250]`.
- The same PNG in a restricted channel returned beta14's `PermissionsClientInsufficient`; the fixture did not override that restriction.
- A channel without a banner returned `not_found`. A missing file returned beta14's `FileNotFound`. Changing the reference removed the old image without changing the adjacent row or selection outline, and replaying the former token did not restore it.
- An advertised `.invalid` HTTPS URL did not produce a Slint tree fetch action. Calling the core returned `external_media`. The runtime was isolated with public network services and OS actions disabled; the test-only switch enabled the real banner request on the fixed loopback session. No HTTP or browser navigation was used.
- The parser test accepted a positive channel ID and rejected a missing, zero, negative, fractional, or string ID and an extra `url` field. The live test also rejected a typed zero ID as `bad_request`.
The live test passed in 34.59 s (1 passed, 824 filtered out); the core parser test passed (1 passed, 261 filtered out). The runner stopped the server and removed its private runtime. The post-run check found zero listeners on UDP 19987 and TCP 30053/19080 and zero matching private runtime directories. Local logs: `target/fetch-banner-live-3.log`, `target/fetch-banner-protocol.log`. Screenshots: `target/fetch-banner-live/fetch-banner-live.png` and `target/fetch-banner-live/fetch-banner-missing.png`.
This receipt covers only `command:fetch_banner` on Windows classic beta14. It does not claim a `command:fetch_server_banner` or `preference:showChannelBanners` pass, HTTP image fetching, a cross-session or late in-flight network response test, or S3/HTTPFT parity. The stale case here is a token for a live channel whose advertised reference was replaced. Compatibility status entries were left unchanged.
## Reproduce
Use a staged Windows beta14 release and pinned WebRTC. Keep UDP 19987 and TCP 30053/19080 free. The runner uses private temporary state and an ephemeral bootstrap key; Query is off while the client test runs.
```powershell
$env:TEAMSPEACH_BETA14_RELEASE = 'C:/path/to/staged/beta14/release'
$env:LK_CUSTOM_WEBRTC = 'C:/path/to/pinned/webrtc'
$env:CARGO_TARGET_DIR = Join-Path $PWD 'target'
$env:TEAMSPEACH_CHANNEL_BANNER_EVIDENCE = Join-Path $PWD 'target/fetch-banner-live'
$runner = (Resolve-Path 'native/tests/fixtures/beta14-server-admin.ps1').Path
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $runner"
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --include-ignored --test-threads=1 --nocapture --exact smoke::channel_banners::live::fetch_banner_renders_classic_beta14_channel_row
Remove-Item Env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-core --lib protocol::tests::fetch_banner_requires_only_a_positive_channel_id -- --exact
```
Use a worktree path without spaces for the Cargo runner variable.
@@ -0,0 +1,33 @@
# Windows beta14 server bandwidth settings
The focused Slint test passed on Windows with TeamSpeak Server 6.0.0-beta14, two disposable muted guests, classic file transfer, and an additional `b_virtualserver_modify_ft_settings` grant for the fixture guest group. Bootstrap WebQuery checked the finite seed, then shut down before the guest scenario. The replacement server was verified to listen only on 127.0.0.1 UDP 19987 and TCP 30053, with public listing off and Query disabled. There were no file transfers, and no rate limiting or throughput was measured.
## Passing snapshots
The peer values below came from independent native `server_info` requests. Both inputs also matched those values when the initiating guest reopened the editor after each operation. Each invalid submission was isolated to its field: -1 and 9,007,199,254,740,992 retained their respective drafts and produced field errors; the other input retained its baseline without an error. The editor's declared range is 0 through 9,007,199,254,740,991 inclusive. The test refused to substitute a default for a missing or unlimited baseline.
| Stage | Download (bytes/s) | Upload (bytes/s) |
| --- | ---: | ---: |
| Bootstrap and first peer read | 1,048,576 | 2,097,152 |
| After cancel | 1,048,576 | 2,097,152 |
| Download only | 3,145,728 | 2,097,152 |
| Restored | 1,048,576 | 2,097,152 |
| Upload only | 1,048,576 | 4,194,304 |
| Restored | 1,048,576 | 2,097,152 |
| Both fields | 3,145,728 | 4,194,304 |
| Restored | 1,048,576 | 2,097,152 |
The test reported 1 passed, 0 failed, 811 filtered out, in 143.97 s. The runner reported shutdown and private runtime removal. An independent post-run check found zero UDP listeners on 19987, zero TCP listeners on 30053 and 19080, and zero matching private bandwidth runtime directories.
## Reproduce
From a worktree path without spaces in Windows PowerShell, point `TEAMSPEACH_BETA14_RELEASE` at a separately staged Windows beta14 release containing `tsserver.exe`, its DLLs, `sql/` and `serverquerydocs/`. Set `LK_CUSTOM_WEBRTC` to the pinned custom WebRTC build. The three fixture ports must be free. The [checked-in runner](../../../native/tests/fixtures/beta14-server-admin.ps1) creates an owner-only runtime, generates an ephemeral bootstrap key, seeds both limits, runs just the focused test, then stops the server and removes the runtime. No existing server profile, credentials, or executables are stored in this repository.
```powershell
$env:TEAMSPEACH_BETA14_RELEASE = 'C:/path/to/staged/beta14/release'
$env:LK_CUSTOM_WEBRTC = 'C:/path/to/pinned/webrtc'
$env:CARGO_TARGET_DIR = Join-Path $PWD 'target/cargo-bandwidth'
$runner = (Resolve-Path 'native/tests/fixtures/beta14-server-admin.ps1').Path
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $runner"
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --include-ignored --test-threads=1 --nocapture --exact smoke::tabs::server_capacity::server_transfer_bandwidth_roundtrip_on_beta14
```
@@ -0,0 +1,37 @@
# Windows beta14 server host banner settings
The disposable loopback fixture granted `b_virtualserver_modify_hostbanner` to the guest group. Bootstrap WebQuery verified both seeded URLs, the 120-second interval, and mode 0 before disabling Query. The initiating editor acted only on the expected fixture, original session and server UID. The second guest used independent `server_info` requests. Server name, welcome text, host message and its mode, capacity, reserved slots, and listing state were unchanged on every peer read.
Slint rejected 1025 ASCII characters in either URL field, `-1`, `4294967296`, and `1.5` for the interval, and `-1` and `3` for mode. Invalid drafts stayed in their fields. The editor's declared numeric ranges are 0 to 4,294,967,295 for the interval and 0 to 2 for mode; the tested server-accepted intervals were 120, 180 and 240 seconds, not the whole editor range. A valid combined draft with the wrong confirmation name stayed open with an error and then was cancelled.
The table shows independent peer reads. URL paths below all share the prefix `https://banner.invalid`. A fresh editor also showed the changed control after each single-field save and all four fields after cancellation, combined save, and restoration.
| Stage | Link path | Image path | Interval (s) | Mode |
| --- | --- | --- | ---: | ---: |
| Seed and cancel | /base | /base.png | 120 | 0 |
| Link only | /single | /base.png | 120 | 0 |
| Image only | /single | /single.png | 120 | 0 |
| Interval only | /single | /single.png | 180 | 0 |
| Mode only | /single | /single.png | 180 | 1 |
| Combined | /pair | /pair.png | 240 | 2 |
| Restored | /base | /base.png | 120 | 0 |
The exact offline, locked test with pinned WebRTC passed: **1 passed, 0 failed, 813 filtered out** in 151.29 s. The runner stopped beta14 and removed its private runtime. A post-run check found no listener on UDP 19987 or TCP 30053/19080, and no matching private runtime directory. These are field values and wire readback, not evidence of link activation, an image download, rendering, or refresh timing.
## Integration rerun
On `work/integration-verified`, merge `655e82075613f379d96b6a13da6de9d3e9c269ac` integrated source commit `a31367cc51740e56e259e6a39d0064ec7b2ee285`. The exact command below was rerun with the integration worktree's `target/` and pinned WebRTC: **1 passed, 0 failed, 819 filtered out** in 151.73 s. The second guest confirmed cancellation, all four independent saves, the combined save and exact restoration. Full local output: `target/host-banner-post-merge.log`. The runner removed its private runtime, and the independent cleanup check found zero fixture listeners and zero matching runtime directories.
## Reproduce
Use the [checked-in runner](../../../native/tests/fixtures/beta14-server-admin.ps1) with a separately staged Windows beta14 release. The worktree path must not contain spaces when setting the Cargo runner below, and the three fixture ports must be free. The runner uses a fresh private runtime and temporary bootstrap key; no credentials or executables are checked in.
```powershell
$env:TEAMSPEACH_BETA14_RELEASE = 'C:/path/to/staged/beta14/release'
$env:LK_CUSTOM_WEBRTC = 'C:/path/to/pinned/webrtc'
$env:CARGO_TARGET_DIR = Join-Path $PWD 'target/cargo-capacity'
$runner = (Resolve-Path 'native/tests/fixtures/beta14-server-admin.ps1').Path
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $runner"
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --include-ignored --test-threads=1 --nocapture --exact smoke::tabs::server_capacity::host_banner::server_host_banner_roundtrip_on_beta14
```
@@ -0,0 +1,40 @@
# Windows beta14 server host button settings
The disposable loopback fixture granted only `b_virtualserver_modify_hostbutton` in addition to the default guest rights. Bootstrap WebQuery confirmed all three seeded fields before Query was turned off. The actual Slint inputs rejected and retained 1,025 ASCII characters in each field, with an error only on the field under test. The editor's declared limit is 1,024 characters; beta14 accepted the short values below, but its maximum length was not measured and the oversized drafts were not sent to the server.
The second guest read all three properties through independent `server_info` calls. The rest of the checked server text and banner settings and the listing flag stayed unchanged. A fresh editor showed the changed field after each single save and all three values after cancel, the combined save, and restoration. Each URL path below is prefixed by `https://button.invalid`.
| Stage | Tooltip | Link path | Image path |
| --- | --- | --- | --- |
| Seed and cancel | Fixture base button | /base | /base.png |
| Tooltip only | Fixture single button | /base | /base.png |
| Link only | Fixture single button | /single | /base.png |
| Image only | Fixture single button | /single | /single.png |
| Combined | Fixture combined button | /combined | /combined.png |
| Restored | Fixture base button | /base | /base.png |
The exact offline, locked Windows test with pinned WebRTC passed: **1 passed, 0 failed, 814 filtered out** in 138.70 s. The runner stopped beta14 and removed its runtime; the post-run check found zero listeners on UDP 19987 and TCP 30053/19080 and zero matching private runtime directories. This was configuration and readback only: no browser launch, link activation, image fetch, or rendering was exercised.
## Integration checks
Merge `e94e6c770f4eabd12da488698bebf5a109be01e0` integrated `8a5afa2814fabb4e2e02559bd4fab3ac932d0025` into `work/integration-verified`. The only conflict was smoke registration; it retained the existing Host Message and Host Banner cases alongside Host Button. The live beta14 result above is from the originating `work/capacity-native` commit, not a post-merge live rerun. No fixture was started for these integration checks.
The offline Slint regression passed (**1 passed, 0 failed, 822 filtered out**, 0.02 s). It checks draft retention and acknowledgement matching for the shared channel and server editors with in-process results, not a live host button save. The exact ignored host button filter listed **1 test, 0 benchmarks**, verifying registration without running it. Both commands used pinned `LK_CUSTOM_WEBRTC` and the integration worktree's `target/`; local logs are `target/host-button-integrated-editor.log` and `target/host-button-integrated-registration.log`.
```powershell
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --test-threads=1 --exact ui::shell::tests::admin_editor_slint_keeps_draft_until_matching_server_ack
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --list --include-ignored --exact smoke::tabs::server_capacity::host_button::server_host_button_roundtrip_on_beta14
```
## Reproduce
Use the [checked-in runner](../../../native/tests/fixtures/beta14-server-admin.ps1) with a staged Windows beta14 release, pinned WebRTC, and the fixture ports free. The Cargo runner path must not contain spaces.
```powershell
$env:TEAMSPEACH_BETA14_RELEASE = 'C:/path/to/staged/beta14/release'
$env:LK_CUSTOM_WEBRTC = 'C:/path/to/pinned/webrtc'
$env:CARGO_TARGET_DIR = Join-Path $PWD 'target/cargo-capacity'
$runner = (Resolve-Path 'native/tests/fixtures/beta14-server-admin.ps1').Path
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUNNER = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File $runner"
cargo test --offline --locked --target x86_64-pc-windows-msvc -p teamspeach-native --no-default-features --features webrtc,test-harness --lib -- --include-ignored --test-threads=1 --nocapture --exact smoke::tabs::server_capacity::host_button::server_host_button_roundtrip_on_beta14
```
@@ -1,4 +1,79 @@
# TeamsPeach selector → official TeamSpeak 6 source map (visual cutover, 2026-11-01)
# TeamSpeak 6 visual reference and historical selector source map
## Current account-free desktop reference (6.0.0.5232)
The Windows reference ran the installed **TeamSpeak 6.0.0.5232** Vue frontend from
`html/client_ui` in an isolated, offscreen reference runner; it did not run the official native client.
The `served` fields of all four `target/evidence/official-5232-pc/official/*/manifest-chat-full.json`
files record these SHA-256 fingerprints:
| Bundle | SHA-256 |
|---|---|
| `main.js` | `352683c3eb1d674c6b0fe098ec8ba132b696739a33424080c9266b751de41537` |
| `main.css` | `ae349aa2f33da6ae6e638c211e758e9a6cd1da2d07399701453a52ed7a2ac72d` |
These screenshots are not user-account state. A shared canonical fixture supplies synthetic
connected server/tree, chat and device data; no real server session, normal profile, account login
or media device is used. The reference-only `pair-report.json` records a passing instrument self-test
and fixture equality, not a visual pass. It records five blocked requests, 15 unanswered bridge calls
and 11 page errors per variant; the requested scenes were captured, but unprovided services were not tested.
Reference and native coverage: dark/light × EN/RU at 1280×800, with full channel chat (`main`),
Alex private chat (`private`), Alex's client context menu (`menu`), and the top of Audio and
Appearance settings. The account-free product retains independent branding and omits account-only
sidebar actions, account/homebase settings and Remote Apps. Native caption presentation is not
tested offscreen. The native comparator scores the entire frame even where differences are declared.
### Capture and compare from the repository root
The reference runner is a **QA-only** export of the historical scripts, with Node/Electron and
`playwright-core` available. This does not restore Electron to the product. The official `html/client_ui`
must match the pinned hashes; the fixture is a local synthetic evidence artifact, not a dependency
on the official profile. The recorded artifact names below are examples: use fresh output paths
for reruns and update the corresponding comparator inputs.
```powershell
New-Item -ItemType Directory -Path target/reference-ui-5232-tools -ErrorAction Stop | Out-Null
git archive --output=target/reference-ui-5232-tools/runner.tar eb24965076599267687c8c4dd6f24f22953b15f6 scripts/official-pair-capture-offscreen.mjs scripts/lib
tar -xf target/reference-ui-5232-tools/runner.tar -C target/reference-ui-5232-tools
$fixture = 'C:/Users/Admin/tmp/teamspeach-exact-design-20261101/expanded-reference/fixture-data.json'
node target/reference-ui-5232-tools/scripts/official-pair-capture-offscreen.mjs --official-only --out target/evidence/official-5232-pc --themes dark,light --locales en,ru --sizes 1280x800 --screens main,private,settings:audio,settings:appearance,menu --fixture $fixture
$out = Join-Path (Get-Location) 'target/evidence/native-5232-pc-03'
New-Item -ItemType Directory -Path $out -ErrorAction Stop | Out-Null
$env:TEAMSPEACH_PC_PARITY_FIXTURE = $fixture
$env:TEAMSPEACH_SMOKE_NO_NETWORK = '1'
$env:TEAMSPEACH_SMOKE_NO_OS_ACTIONS = '1'
$env:TEAMSPEACH_SMOKE_NO_PHYSICAL_CAPTURE = '1'
$env:TEAMSPEACH_PROFILE_DIR = Join-Path $out 'profile'
cargo run --locked -p teamspeach-native --bin teamspeach --target x86_64-pc-windows-msvc --no-default-features --features test-harness -- --smoke pc-parity --profile-dir $env:TEAMSPEACH_PROFILE_DIR --output $out
python native/tools/compare_desktop_parity.py --official target/evidence/official-5232-pc/official --native target/evidence/native-5232-pc-03/native --out target/evidence/compare-5232-pc-03
```
The native capture receipt is `native-5232-pc-03/parity.json`; scene JSON/PNGs are under its
`native/` directory. The comparator requires Python with Pillow and an output directory that
does not yet exist. It writes `parity-report.json`, whole-frame and region diff images and threshold
masks under the compare root. A pixel differs if any RGB channel delta exceeds 16/255, the pixel
limit is 0.5%, and independently measured region geometry must match within 1 px. Crops share
official coordinates without alignment, resizing or masking. Missing geometry is not a pass.
Both `-02` and `-03` completed 20/20 native captures; both compare reports record **0 passed,
20 failed, 0 blocked**. Whole-frame differing pixel ratios across the four variants were:
| Scene | `compare-5232-pc-02` | `compare-5232-pc-03` |
|---|---:|---:|
| Main | 12.88–15.68% | 7.36–8.85% |
| Private chat | 5.81–7.10% | 4.83–5.88% |
| Client context menu | 50.90–76.44% | 8.98–10.99% |
| Audio settings | 11.14–12.90% | 11.18–13.12% |
| Appearance settings | 13.47–16.30% | 11.64–13.37% |
These offscreen captures do not establish strict visual parity, installed-window behavior or
functional interoperability. See [FEATURE_COMPATIBILITY.md](../../../FEATURE_COMPATIBILITY.md)
for the separate functional evidence and open acceptance gates.
## Historical source map (6.0.0.5163, visual cutover 2026-11-01)
Source: installed TeamSpeak 6.0.0.5163, `html/client_ui/main.css` (sha256 `bc700401d04954d0…`) and
`main.js` (sha256 `9d6bea2ee5333086…`), read-only. `css@N` = main.css character offset; `D@N` / `L@N` =
@@ -0,0 +1,9 @@
# Protected bookmark on Windows beta14
`smoke::bookmark_schema::protected_bookmark_restarts_and_rechecks_lookup_target_on_beta14` exercises the [native `preload:connectBookmark` contract](../../native/compatibility.json) on a disposable loopback TeamSpeak Server 6.0.0-beta14 fixture. The [runner](../../native/tests/fixtures/beta14-server-admin.ps1) bootstraps a password-protected server and a separate password-protected, non-default room, confirms both protections, and disables Query before running the exact test. The generated passwords are distinct and passed only to the test process, not placed on its command line or recorded in the receipt.
The normal Slint bookmark editor saved both passwords to Windows DPAPI. The smoke reopened the same disposable profile and activated the rendered bookmark row. It checked the selected vault identity in core connection state and the nickname and protected room in the initiator's server-fed own-client roster. Separate saved bookmarks swapping one password at a time showed that the channel password did not admit server login, and the server password did not admit the protected channel. The required legacy re-entry prompt cancelled with zero bookmark `Connect` dispatches and no session change.
The stale case paused the result of a real DPAPI server-password lookup. A second activation connected the same tab with a new generation while the original request was paused. Releasing the old result returned `target_changed`, kept the replacement in the protected room, and did not dispatch an extra `Connect`. The test pauses only local delivery of the lookup result; it does not mock the join or delay network traffic.
**Windows integration receipt:** `target/protected-bookmark-beta14.log`: **1 passed, 0 failed, 0 ignored; 15.14 s**. The test removed its client profile, the runner removed the server runtime, and independent teardown found zero fixture listeners (UDP 19987, TCP 30053 and 19080) and zero disposable temp directories. Startup microphone-only mute and acknowledgement ordering are covered separately in the [bookmark schema evidence](bookmark-schema-windows.md); this run covers manual activation. Headless Slint uses the ordinary UI binding but skips HWND-dependent attachment. No physical audio devices, independent peer readback, mobile secret store, or public server were tested.
+9 -3
View File
@@ -1,6 +1,8 @@
# Localization
TeamsPeach defaults to **English**, independently of the operating-system language. Settings → Appearance → Language selects English or Russian. The native preference is persisted by the Rust preferences service; catalog presentation belongs to the UI, not the protocol or capture worker.
TeamsPeach defaults to **English**, independently of the operating-system language. Settings → Appearance → Language saves English or Russian as the language for the next launch. The picker shows the saved value immediately; the running catalog changes only when the app starts again. On desktop, a successful change away from the running language offers a restart. Cancel dismisses the prompt without undoing the save, and the warning remains under the picker. A failed save keeps the previous value and does not open a prompt. Mobile uses the saved language at the next launch without a desktop relaunch prompt.
The manifest-pinned TeamSpeak 6.0.0.5232 `main.js` initializes its catalog from `navigator.language` (character offsets 1424854 and 1445824). Its Appearance setter saves via `application.language`, then offers a restart only when the selection differs from the running language (4597988). The Cancel callback does not write the preference. These observations come from the pinned bundle, not a live TeamSpeak relaunch.
## Native files and boundaries
@@ -19,9 +21,9 @@ Use `Catalog::new(Language::En)` or the current snapshot's catalog, then `text(k
The formatter performs one substitution pass: inserted content containing braces is not interpreted as another template. Plural messages use language-specific categories and `other`; Russian integer suffixes are not English suffix rules. Fractions use `other`. Catalog key and placeholder parity remain required. The native formatter's English/key fallback and retained unresolved placeholders are not evidence that missing translations are acceptable: missing keys/parameters need authoring coverage and must never be mistaken for success.
Bind Slint text, accessibility names, tooltips and placeholders from the current catalog/model. Dynamic messages must be regenerated from stable keys and raw values when language changes, not translated by matching previously painted wording. Avoid rebuilding forms in ways that discard unsaved input, selection, undo state or focus.
Bind Slint text, accessibility names, tooltips and placeholders from the running catalog/model. The settings selection displays the stored language while the rest of the application continues using its startup catalog. Avoid rebuilding forms in ways that discard unsaved input, selection, undo state or focus.
Language changes never translate server/channel names, nicknames, OS device names, chat content, media or descriptions. App-created notices are localized separately from incoming data. Error explanations are selected by stable machine code, with verbatim server/OS/backend detail after the explanation where useful. Unknown codes remain visible errors. Native chooser titles, filters and application-owned confirmation labels use the current saved language; OS-owned controls follow the OS language.
Language changes never translate server/channel names, nicknames, OS device names, chat content, media or descriptions. App-created notices are localized separately from incoming data. Error explanations are selected by stable machine code, with verbatim server/OS/backend detail after the explanation where useful. Unknown codes remain visible errors. Native chooser titles, filters and application-owned confirmation labels use the running language; OS-owned controls follow the OS language.
## Adding a language
@@ -38,6 +40,10 @@ Language changes never translate server/channel names, nicknames, OS device name
The native report `target/evidence/native-offline-ui-03/result.json` records EN/RU, dark/light and 390/800/1280 logical-pixel settings coverage, controlled combobox values and profile restarts. See FEATURE_COMPATIBILITY.md for the complete scope and limitations. No additional execution is claimed by this documentation update.
The focused Windows Slint test `language_applies_and_survives_process_restart` clicks real dropdown options at 900×800 (English to Russian in dark mode and Russian to English in light mode). It checks that only `language` changes on disk, the selected caption changes before the restart prompt is answered, and the surrounding labels remain in the running language. Cancel keeps the saved choice. Confirm reaches the desktop relaunch policy gate, which refuses OS actions in the smoke runtime. A separate process opens the same disposable profile and renders the saved language; a blocked reverse write returns `io` with no prompt and preserves the selector, active catalog and exact preference bytes. The test does not spawn a production replacement process or establish live voice/chat continuity. Native uses the shared confirmation dialog, not the reference’s anchored popup geometry.
The recent-server-events smoke starts a disposable profile in each language and checks that the existing event and its canonical timestamp survive clock-format changes and a saved language change without an in-process translation.
### Historical development runs, 2026-10-24
The removed browser implementation passed 14 targeted localization tests and its Windows x64 hidden-runtime scenario on Electron 44.9.3. Evidence is retained in `docs/evidence/runtime/i18n-2026-10-24/`: fresh English, seven categories and both real-device context menus in both languages, live notice translation, Russian persistence, return to English, no capture, unchanged UID/nickname/audio/unrelated preferences, preserved connection draft, and no horizontal overflow at 880×560. Temporary profiles were deleted. This is historical evidence, not a native pass.
+679
View File
@@ -2,6 +2,685 @@
Обновлено: **2026-11-11**. Принятая Windows-база фиксируется тегом **`desktop-baseline-0.1.7-20261111`** в `main` (предыдущий HEAD `5ce12714acc306f6055bf1e9db3282c5af7704cb`). Дальнейшая мобильная разработка — `feature/mobile-port` от этой базы. Единственный application host — Rust/Slint; результаты ниже отделены от первоначального read-only исследования.
## Сводка интеграции Windows, 2026-11-28
Ветка `work/integration-verified` от `caf29f4`: основные результаты интеграции.
- `92aef5d4` добавляет тесты точного формирования `serveredit` для лимита клиентов, резерва и квот. Живые проверки формы из `b1b3496a38` описаны ниже; в интеграционном прогоне beta14 не запускался.
- `a8157ab58d` фиксирует границу слияния `work/ignored-users`: меню контакта и список Chats проверены после перезапуска, прежние проверки по точному UID и удаления сохранены. [Итоговый прогон](evidence/native-ignored-users-ui.md) включает также перезапуск с сохранённым языком.
- `6ab51d5fb` удерживает слот отменённой публикации до снятия поздно назначенного ID или завершения сеанса. [Границы проверки](evidence/native-stream-setup-cancelled-registration.md) сохраняются.
- `43d13d0436` переносит масштаб Display Size на свёрнутую боковую панель, не меняя сохранённый признак сворачивания, и включает уточнённые маркеры предпросмотра. Проверка и размеры записаны в [матрице совместимости](../FEATURE_COMPATIBILITY.md).
- `5b55d159f7` подключает `showChannelBackground` к дереву. Два адресных теста на слиянии `9ba82dd229` прошли: в EN/RU и светлой/тёмной темах проверены заливка каналов, сохранение контура выделения, перезапуск, отказ записи и лампа командира. Использован тестовый список каналов без сервера; журнал `target/channel-background-post-merge.log`.
- `09768a2113` добавляет флаги стран в дерево. На слиянии `43fab1649a` прошли пять автономных проверок: пиксели флага США и отсутствие подстановки для неизвестного или пустого кода в EN/RU и обеих темах, отказ записи и перезапуск, каталог и лицензия, заливка каналов и лампа командира. Все 254 SVG и MIT LICENSE совпали с `flag-icons` 7.3.2. Проверка использовала тестовый список участников; журнал `target/country-flags-post-merge.log`.
- `showBadges` теперь управляет значками участников в дереве Slint, не отключая Badge Showcase. Повторное включение заново проверяет недоступные значки, сохраняя уже загруженные. Восемь автономных тестов Windows прошли; [снимки и границы проверки](evidence/native-tree-badges.md).
- Для `preload:setPrefs` четыре автономных теста Windows подтвердили сохранение Display Size после перезапуска, отсутствие изменений при отказе записи и запрет обхода защищённых полей. [Протокол проверки](evidence/native-set-prefs.md).
- Для `preload:getKeybinds` Slint показывает активный профиль отдельно от просматриваемого, точное совпадение, конфликты и результат регистрации. Четыре адресных теста Windows прошли: `RegisterHotKey` принял F23 и отклонил F24, занятый тем же тестовым процессом; обе комбинации освобождены, клавиши не нажимались. [Протокол проверки](evidence/native-get-keybinds.md). Отдельно: [свидетельство Contacts и значков](evidence/native-tree-badges.md#local-contacts-and-public-badges-contract) на `96b6f2aaef`, без нового прогона.
- Для `preload:setKeybinds` редактор сохранил новое сочетание после перезапуска, не меняя второй профиль. Все предупреждения о конфликтах видны; Windows зарегистрировала только исправленное сочетание и выделенный PTT, без срабатываний действий. Четыре адресных теста прошли. [Свидетельство и границы](evidence/native-set-keybinds.md).
- Для `preload:setKeybindExact` оба состояния переключателя сохранились после перезапуска. Windows зарегистрировала четыре сочетания F20 с дополнительными модификаторами при выключенном точном совпадении и только основное сочетание при включённом. Все регистрации освобождены; физические нажатия не проверялись. Три адресных теста прошли. [Свидетельство и границы](evidence/native-keybind-exact.md).
- Для `preload:setKeybindCapture` Slint открыл редактор, а Windows освободила сочетания на время записи. После сохранения, отмены со сменой профиля и потери фокуса вернулись только разрешённые сочетания текущего профиля. Четыре адресных теста прошли; срабатываний действий и физических нажатий не было, все регистрации освобождены. [Свидетельство и границы](evidence/native-keybind-capture.md).
- `chatStyle`: на Windows те же два сообщения заняли 136 px в Detailed и 50 px в Compact. При смене стиля сохранились беседа, выделение и черновик; после перезапуска восстановились стиль и история. [Измерения и снимки](evidence/native-chat-style.md).
- `chatToolbarVisibility`: Slint проверил все три режима при вводе, выделении и перезапуске. Dynamic оставляет панель при непустом черновике без фокуса; кнопка More не забирает фокус и не меняет выделение. Три адресных теста прошли. [Снимки и границы проверки](evidence/native-chat-toolbar.md).
- `autoDownloadImages`: при выключенной настройке запросов не было до кнопки Load; после включения и перезапуска Slint автоматически показал PNG из тестового транспорта. Веб-изображения и HTTPFT не дошли до транспорта. Четыре адресных теста Windows прошли без сети. [Свидетельство и границы](evidence/native-auto-download-images.md).
- `sidebarIconMode`: в Windows Slint размеры значков подключений и закладок составили 22/33 px; Adaptive использует 33 px только на свёрнутой панели. Все три режима проверены после перезапуска в EN/RU и двух темах; ширина ограничивается без потери строк. Три адресных теста прошли. [Измерения и снимки](evidence/native-sidebar-icon-mode.md).
- `8a5afa2814` интегрирован слиянием `e94e6c770f`: регистрация точного теста Host Button подтверждена, один автономный тест ожидания подтверждения в Slint прошёл. Живой beta14 не запускался повторно; [исходный прогон и проверки интеграции](evidence/official-parity/server-host-button-beta14.md) записаны отдельно.
- Из `f9cdcdd453` на базе `87cfa59252` перенесены только проверка UID перед удалением, сценарий Identities и [его свидетельство](evidence/native-identity-request.md). Windows `--smoke identity-workflows` с `webrtc,test-harness` подтвердил все 15 проверок: точный UID, имя, выбор по умолчанию, улучшение, отказ для отсутствующего UID и несовпадающего подтверждения. Журнал: `target/identity-request-integration/test.log`; отчёт: `target/identity-request-integration/run/result.json`. Временный профиль удалён. Живой сервер, CLI ядра и успешный импорт/экспорт не проверялись; правки и свидетельство beta14 сохранены.
- На базе `fb5ce198f0` проверен `preload:connectBookmark`: Slint сохранил два отдельных пароля через DPAPI, после перезапуска закладка открыла защищённую комнату beta14. Подмена каждого пароля не дала войти в соответствующую цель. Отмена и запоздалый ответ хранилища после смены сеанса не отправили `Connect`. Одноразовый стенд и профиль удалены; точный тест прошёл. [Проверки и границы](evidence/protected-bookmark-windows.md).
- На базе `b8b13bbd75` проверены статус, запись и показ паролей закладки в Slint с Windows DPAPI. Статус не раскрывает пароль; очистка одного назначения пережила перезапуск. Смена адреса отклонила запоздалые запись и показ. Один адресный UI-тест прошёл; реальная блокировка системного хранилища не проверялась. [Свидетельство и отдельные проверки хранилища](evidence/bookmark-password-windows.md).
- На базе `0ee62be668` проверен `preload:request`: результат Client Info на двух вкладках beta14 не переходил из A в B; stdio вернул `unknown_command` и `bad_request`, а редактор идентичностей использовал типизированный профильный сервис. Три адресных теста прошли. Для запоздалого результата после переподключения использовано прежнее свидетельство с проверенной родословной кода. [Команды и границы](evidence/native-tab-request.md).
- На базе `1fe5baba05` проверен `preload:onEvent`: две вкладки beta14 получили свои состояния, снимки и сообщения; после отсоединения Slint и переподключения получателя сообщения показаны по одному разу. Отдельно отклонены внедрённые события старого сеанса. [Два адресных прогона и границы](evidence/native-tab-events.md).
- На базе `b370474999` проверен `command:fetch_banner`: приватный classic beta14 выдал точные 74 байта PNG, а Slint нарисовал цвет в выбранной строке канала. Сервер отказал гостю без права скачивания. При отсутствующем файле изображение исчезло; старый токен отклонён, HTTPS-адрес не стал действием дерева. Проверки живого пути и аргументов прошли; стенд снят. [Снимки, границы и команды](evidence/official-parity/channel-fetch-banner-beta14.md).
- Из `302ba80958` на базе `c4fe77d128` перенесены только изменения баннеров каналов. При совмещении остались ветви флагов стран, лампы командира, фон без изображения, редактор кнопки сервера и выбор источника захвата. Один адресный прогон под Windows с `webrtc,test-harness` дал **7 passed, 0 failed, 817 filtered out** (83.78 с). Журнал: `target/channel-banner-integration/test.log`, снимки: `target/channel-banner-integration/{en,ru}-{dark,light}-*.png`. Тест подал настоящие PNG через автономную тестовую границу транспорта: штатный декодер и дерево Slint подтвердили замену, очистку, сохранение видимости, отказ записи и отбрасывание позднего результата. Живой сервер, передача файлов, HTTP(S)-баннеры и физический захват не проверялись. Тест редактора проверял сохранение черновика до совпадающего подтверждения, а не живой Host Button.
Для повторения из worktree интеграции: активировать MSVC и закреплённый WebRTC через `target/tools/build-native.cmd` исходной копии (только чтение), выставить `CARGO_TARGET_DIR` на `target/` worktree, `TEMP` и `TMP` на локальный временный каталог, `TEAMSPEACH_CHANNEL_BANNER_EVIDENCE` на свежий локальный каталог снимков, `CARGO_PROFILE_DEV_DEBUG=0`, `CARGO_PROFILE_TEST_DEBUG=0` и `CARGO_INCREMENTAL=0`. Точные аргументы Cargo для одного прогона:
```text
cargo test --locked --offline -p teamspeach-native --lib --target x86_64-pc-windows-msvc --no-default-features --features webrtc,test-harness -- --exact --test-threads=1 --nocapture smoke::channel_banners::channel_banners_render_replace_clear_and_follow_saved_visibility smoke::channel_background::channel_background_updates_pixels_and_survives_failed_save_and_restart smoke::channel_commander::commander_lamp_appearance_persists_in_both_languages_and_themes smoke::country_flags::country_flags_render_only_known_codes_and_persist_across_restart ui::shell::country_flags::tests::pinned_inventory_loads_and_omits_unsupported_codes ui::shell::tests::admin_editor_slint_keeps_draft_until_matching_server_ack smoke::capture_selection::slint_capture_selection_cancel_revokes_only_its_flow
```
Из исходной рабочей копии перенесены только тест и записи о HostMessage. Стенд и его параметры в ветку не включены.
## Возврат к разработке на ПК, 2026-11-26
Windows, база `a31367cc51`: на отдельном beta14 проверены подсказка, ссылка и адрес изображения кнопки сервера. Форма Slint отклонила 1025 символов ASCII в каждом поле. Отмена сохранила исходные значения; второй гость подтвердил отдельные правки, совместное сохранение и точное восстановление. Новый редактор показал сохранённые значения. Адресный тест прошёл, стенд остановлен. Максимальную длину на сервере не измеряли, адреса `.invalid` не открывали. [Снимки и команда повторения](evidence/official-parity/server-host-button-beta14.md).
Windows, база `ec580edc90`: на отдельном beta14 проверены адрес ссылки, адрес изображения, интервал и режим баннера сервера. Slint отклонил слишком длинные адреса, недопустимые числа и неверное имя подтверждения. Отмена сохранила исходный набор; второй гость подтвердил четыре отдельные правки, совместное сохранение и точное восстановление. Новый редактор показал сохранённые значения. Адресный тест прошёл, стенд остановлен. Адреса `.invalid` не открывались, загрузка, отрисовка и частота обновления изображения не проверялись. [Снимки и команда повторения](evidence/official-parity/server-host-banner-beta14.md).
Windows, база `9c242d790f`: на отдельном beta14 второй гость подтвердил запись темы канала до фактического отключения инициатора. Та же вкладка подключилась с другой идентичностью и отправила новую тему для того же канала. Тест задерживал только доставку успешных ответов. Старый ответ не закрыл новый диалог и не изменил черновик, сведения или уже показанное сообщение об отключении; собственный ответ закрыл диалог. Адресный тест прошёл, стенд остановлен. Откат серверной правки и обрыв до подтверждения не проверялись. [Свидетельство и команда повторения](evidence/official-parity/channel-edit-replacement-beta14.md).
Windows, база `b1b3496a38`: на отдельном beta14 проверены `virtualserver_max_download_total_bandwidth` и `virtualserver_max_upload_total_bandwidth`. Форма отклонила −1 и 9 007 199 254 740 992 отдельно для каждого поля. Отмена сохранила исходные 1 048 576 / 2 097 152 байт/с. Новый редактор и независимый `server_info` второго гостя подтвердили отдельные правки, сохранение обоих полей вместе и точное восстановление после каждого сохранения. Адресный тест прошёл, стенд остановлен. Файлы не передавались, ограничение скорости не измерялось. [Снимки и команда повторения](evidence/official-parity/server-bandwidth-beta14.md).
Windows, база `978cb3283c`: на отдельном beta14 проверены `server_edit.virtualserver_download_quota` и `server_edit.virtualserver_upload_quota`. Стенд задал конечные исходные квоты 64/96 Мбайт, форма Slint отклонила −1 и 9 007 199 254 740 992 при допустимом диапазоне от 0 до 9 007 199 254 740 991 включительно. Отмена сохранила исходные значения. Новый редактор и независимый `server_info` второго гостя подтвердили сохранение 128/192 Мбайт и точное восстановление 64/96 Мбайт. Безлимитное значение `u64::MAX` не преобразовывали; передачу файлов и применение квоты к трафику не проверяли. Адресный тест прошёл, стенд остановлен.
Windows, 2026-11-28, база `caf29f4`: проверены `server_edit.virtualserver_maxclients` и `server_edit.virtualserver_reserved_slots`. На изолированном beta14 форма Slint отклонила −1 и 65536 для обоих полей. Отмена сохранила 8/0, после сохранения 7/1 осталось шесть общедоступных мест. Новый редактор и независимый `server_info` второго гостя подтвердили 7/1 и восстановление 8/0. Имя, приветствие, сообщение хоста и его режим не изменились. Один адресный тест прошёл, стенд остановлен; вход при заполнении, использование резерва, потеря прав и переподключение не проверялись.
Windows, база `caf29f4`: до интеграции проверены `virtualserver_hostmessage` и `virtualserver_hostmessage_mode`. На отдельном beta14 второй гость подтвердил отмену, запись и восстановление; имя сервера и приветствие не изменились. Форма отклонила 8193 символа и режимы −1 и 4. Адресный тест прошёл. Показ сообщения при подключении не проверялся.
Windows, база `fb779cf`: закрыт `command:server_edit`. Право на переименование больше не определяет доступ ко всему редактору. На стенде с правом только на приветствие сервер отказал в смене имени, черновик остался в форме; второй гость подтвердил успешное изменение приветствия и восстановление. Отдельно проверена замена сеанса до обработки старого ответа. В первом прогоне пять тестов прошли, тест разрешённого переименования получил отказ из-за выбранного режима стенда; на ServerTextQA он прошёл отдельно. Стенды остановлены.
Windows, база `b0e6062`: проверены `server_edit.virtualserver_name` и `virtualserver_welcomemessage`. Исправлены заголовок сведений и имя в следующем подтверждении после переименования. На приватном beta14 второй гость подтвердил отмену, сохранение имени и многострочного приветствия и восстановление исходных значений. Прошли два адресных теста; остальные свойства сервера в этом прогоне не проверялись.
Windows, база `6738124`: проверен `channel_flag_default` при создании и редактировании. На отдельном beta14 после отмены сохранялся прежний канал по умолчанию. После сохранения снимок содержал ровно один флаг, новый редактор показывал его, и новый гость без явного канала попадал в выбранную комнату. Проверено с разными идентичностями при создании первой комнаты и назначении второй. Адресный тест прошёл; перезапуск сервера и переопределение канала закладкой не проверялись.
Windows, база `6f9a330`: проверен `channel_codec_is_unencrypted` при создании и редактировании комнаты. На beta14 без права 129 получен отказ. После выдачи b_channel_modify_make_codec_encrypted отмена сохранила 0, отключение и повторное включение дали 1 и 0 в channel_info и соответствующее состояние переключателя. Тест прошёл; голосовой трафик и политика шифрования сервера не проверялись.
Windows, база `d99a722`: проверены `channel_edit.channel_banner_gfx_url` и `channel_edit.channel_banner_mode`. До выдачи права 119 сервер отказал в сохранении. С правом b_channel_modify_banner снимок и повторно открытая форма подтвердили URL в режимах 1 и 2, затем очистку и режим 0. Отмена сохранила исходные значения; адрес длиной 1025 символов отклонён. Адресный тест beta14 прошёл; загрузка и отрисовка изображения не проверялись.
Windows, база `b0fc91f`: проверен `channel_edit.channel_codec_latency_factor`. Исходный снимок не дал коэффициент в диапазоне 1…10. Форма отклонила 0 и 11, отмена сохранила исходное поле channel_info, а после сохранения отдельный запрос и новая форма показали выбранное значение. Адресный тест beta14 прошёл. Фактическая задержка голоса не измерялась.
Windows, база `e696e7c`: закрыт `channel_edit.channel_needed_talk_power`. Тест очереди на выступление теперь задаёт порог через редактор Slint. Выход за границы i32 отклонён, отмена сохранила 0, сохранение 50 подтверждено обеими вкладками и новой формой. Адресный тест beta14 прошёл, включая запрос, отзыв и выдачу права говорить. Физическая передача звука не проверялась.
Windows, база `95e028d`: проверены оба флага permanent и semi_permanent в формах создания и редактирования канала. На отдельном beta14 созданы комнаты обоих типов, отмена сохранила прежний тип, смена в каждом направлении подтверждена снимком ядра и повторно открытым редактором по тому же ID. Адресный тест прошёл; сохранность комнат после перезапуска сервера не проверялась.
Windows, база `a8b6359`: проверены `channel_create.channel_delete_delay` и `channel_edit.channel_delete_delay`. Создание с задержкой 30 секунд требовало числового права 109; после изменения на 4 обе вкладки и новый редактор подтвердили значение. После выхода последнего гостя пустая комната сохранялась через секунду, затем исчезла у обоих. Адресный тест beta14 прошёл; точность таймера отдельно не измерялась.
Windows, база `8e11486`: закрыты команды `channel_create` и `channel_edit`. На beta14 отказ гостю при правке темы чужого канала сохранил черновик с ошибкой в редакторе; обе вкладки оставили подтверждённую тему владельца. Отдельно проверена доставка отказов старому сеансу при повторном использовании ID. Последний прогон: два адресных теста прошли. Дополнительные свойства канала и реальный обрыв сети при успешном сохранении этим прогоном не проверялись.
Windows, база `2b16a6c`: подтверждены `group_add`, `group_rename`, `group_delete` для обычных серверных групп и групп каналов. Разные подписи создания и заголовки EN/RU устраняют неоднозначность выбора вида. Вторая вкладка подтвердила ID и имена до и после каждой операции; отмена сохранила запись. В последнем живом прогоне прошли три теста, отдельно три теста устаревших ответов и один тест протокольных ограничений. Стенд остановлен. Шаблонные и Query-группы не изменялись.
Windows, база `6368b84`: в панели групп удаление больше не требует повторного подтверждения. На beta14 две вкладки проверили создание, отмену и сохранение переименования, неверное имя, отмену и подтверждение удаления обычной серверной группы. Второй гость подтвердил ID и сохранность остальных групп. Для переименования потребовалось право 168, а отдельных флагов rename в каталоге beta14 нет. Два адресных теста прошли. Группы каналов не изменялись; общие group_add/rename/delete остаются открытыми.
Windows, база `62ab189`: обновление групп принимает строки beta14 без типа только при совпадении вида списка, ID и имени в снимке текущего сервера. Восемь адресных тестов прошли, включая обработку списков с двух гостевых вкладок и отбрасывание несовпадающих строк. Изменение групп на сервере в этот прогон не входило.
Windows, база `c4b40fb`: закрыт `command:admin_context`. Панель групп показывает ошибку чтения каталога, сохраняя доступные строки. На двух вкладках beta14 сверены контексты с UID сервера и поколением; отдельные тесты проверили частичный отказ, чужой UID, старое поколение и лишнее поле команды. Три нативных теста и один тест ядра прошли. Стенд остановлен.
Windows, база `cb8c81c`: закрыт `channel_edit.channel_flag_maxfamilyclients_inherited`. В канале с лимитами 2 и 6 отмена сохранила 6; после сохранения ядро показало `inherited`, затем конечный лимит 4. При каждом переходе повторно открытый редактор подтвердил режим, а собственный лимит канала остался 2. Два адресных теста beta14 прошли. Заполнение канала участниками не проверялось.
Windows, база `86d3b17`: закрыты `channel_create.channel_order` и `channel_edit.channel_order`. На приватном beta14 создание комнаты первой и последующая перестановка после прежнего первого соседа подтверждены по обеим ссылкам порядка у двух гостей. Отмена сохранила порядок, повторно открытая форма показала сохранённый ID. Прошли два адресных теста. Локальный режим стенда ChannelOrderQA выдаёт только дополнительные права на сортировку при создании и редактировании; стенд остановлен.
Windows, база `4b96891`: закрыт `command:channel_move`. Новый локальный режим стенда ChannelMoveQA разрешает перенос, сортировку и дочерние каналы с глубиной до 2. При меньшей глубине beta14 сообщил недостающее право 86; нативный клиент теперь показывает полученный ID. Отмена сохранила позицию на обеих вкладках, подтверждение перенесло занятый канал под лобби без смены ID; новый редактор показал родителя и первого предшественника (0). Прошли три адресных теста и отдельно две проверки устаревших ответов. Стенд остановлен; скрипт стенда в target не входит в коммит.
Windows, база `32b7617`: закрыт `command:channel_delete`. На приватном beta14 проверены неверное имя, отмена, видимый отказ другому гостю и успешное удаление занятого канала создателем. До отключения обе вкладки показали лобби без удалённого ID. Два сценария beta14 прошли в отдельных процессах Slint. Отдельно три адресных теста проверили запоздалые ответы, включая отказ офлайн-ядра после замены сеанса с тем же ID канала. Стенд остановлен; фактический сетевой разрыв в момент удаления не моделировался.
Windows, база `883a926`: на приватном beta14 проверены три флага вместимости при создании временного корневого канала: конечные лимиты, безлимитные и наследование семейного лимита. Редактор Slint теперь принимает пустое имя закладки: после сохранения и двух перезапусков виден адрес. Прошёл 21 адресный тест, включая отказ записи и восстановление привязок клавиш. Стенд остановлен. Фактический вход участников сверх лимита, регистрация клавиш в ОС и полный CRUD каналов этим прогоном не проверялись.
Windows, база `f434008`: проверены `preference:inputDeviceId` и `preference:outputDeviceId`. На приватном beta14 тон прошёл через точные тестовые ID: у приёмника появлялся новый PCM после каждого unmute и наступала тишина после mute. Прошли три проверки маршрута и сохранения, отдельно четыре проверки потери устройства и устаревших блоков. Стенд остановлен. Потеря устройства моделировалась ошибкой CPAL; физический hot-plug, акустическое эхо и официальный peer не проверялись.
Windows, база `97e08a9`: селекторы Slint сохранили разные ID входа и выхода из тестового каталога. Отказ записи не изменил файл, выбор в интерфейсе или применённые маршруты. Оба ID пережили два перезапуска без запуска устройств. Прошли три адресных теста; успешная передача PCM через выбранную пару в этом прогоне не проверялась.
Windows, база `4777f73`: сохранённые inputDeviceId и outputDeviceId передаются аудиодвижку при запуске, до первого открытия устройства. На beta14 при недоступном выходе клиент показал audio_device_missing, не подменил динамик и сохранил успешное подключение. На двух запусках первый запрос тестового захвата получил точный ID входа. Последний прогон: три адресных теста прошли; отдельно прошли два теста выхода и интерфейса. Физическая гарнитура и hot-plug не проверялись.
Windows, база `580cf60`: закрыт preference:outputLevelDb. Микшер применяет сохранённый уровень до первого соединения. После двух перезапусков и отказа записи при −200 дБ синтетический выход молчал с первого кадра; при 0 дБ звук вернулся, при −6 дБ энергия составила 20–31% от уровня при 0 дБ. Прошли три адресных теста; стенд beta14 остановлен.
Windows, база `2e5f628`: закрыт command:connect. После неверного пароля beta14 вкладка сохранилась, старый ключ сессии был отклонён, lastAddress не изменился. Повторный вход с верным паролем через ту же вкладку прошёл; после перезапуска форма показала подтверждённый адрес. Прошли один тест на стенде, два теста изоляции вкладок и один тест stdio. Стенд остановлен, физические аудиоустройства не открывались.
Windows, база `4920784`: закрыт command:set_audio. На локальном beta14 оба списка участников подтвердили переключение микрофона владельца ввода. При mute старое разрешение захвата отозвано, выход второго гостя затих; при unmute выдано новое разрешение и снова получены звуковые блоки. Прошли два адресных теста. Использованы синтетические вход и выход, стенд остановлен.
Windows, база `06702a0`: кнопка и горячая клавиша включения микрофона проверяют сопоставление устройства до отправки unmute. На локальном beta14 при отказе оба ядра и оба списка участников сохранили mute, разрешение захвата не выдавалось и аудиоустройства не открывались. Прошли три адресных теста. Стенд остановлен; физическая клавиатура не проверялась.
Windows, база `ef383ba`: закрыт command:set_transmit. На локальном beta14 настройки захвата Slint управляли передачей непрерывного синтетического тона: в прямом режиме передача шла, при пороге VAD 0 дБ прекращалась, при −45 дБ возобновлялась. Состояния подтвердили отправитель и другой гость. Прошли два адресных теста, включая задержку отпускания PTT; стенд остановлен, физические аудиоустройства не открывались.
Windows, база `c3b1082`: исправлена проверка аргументов set_transmit. Для direct и vad явно заданный null в detector, sensitivity или level_db возвращает bad_request; пропущенные поля и дробный порог 12.5 сохраняют прежнее поведение. Прошли два адресных теста: парсер и запросы к процессу ядра через stdio. Управление режимом через настройки захвата остаётся отдельной проверкой.
Windows, база `79eacbe`: на beta14 проверено переключение set_transmit во время передачи без явного end_audio. Порог −10 дБ остановил тестовый тон, кадр старого поколения был отклонён. При −40 дБ тот же тон снова дошёл до синтетического выхода без смены поколения захвата. Адресный тест прошёл, стенд остановлен. Команду подавало ядро тестового отправителя; управление через настройки микрофона этим прогоном не проверено.
Windows, база `da827f1`: закрыт command:set_playback_dsp. Один тест stdio проверил оба булевых значения и пять некорректных запросов. Пять нативных тестов проверили границы воспроизведения и восстановление выбранного устройства. Вместе с измерением AGC на beta14 это подтверждает нативный путь с синтетическим звуком, но не физические устройства и не официальный клиент.
Windows, база `fa38d4c`: на локальном beta14 проверено переключение AGC через обработчик настроек Slint во время соединения. На синтетическом выходе энергия одного и того же тихого тона при включении выросла не менее чем в четыре раза; после выключения вернулась в пределах 25% от исходной. Прошли два адресных теста, включая воспроизведение после отсоединения UI. Стенд остановлен. Физические устройства и официальный клиент не использовались.
Windows, база `e954707`: перед подключением ядро получает AGC выбранного выходного профиля. Изменения настройки передаются также готовым неподключённым ядрам. Прошли три теста ядра и два нативных: выбор профиля устройства, возврат к шаблону и усиление тихого синтетического Opus с восстановлением исходного PCM после выключения. Физические устройства не открывались. Сквозной тест переключателя во время звонка остаётся открытым.
Windows, база `87ab448`: закрыты temp_password_list, temp_password_add и temp_password_delete для записи, созданной текущим гостем beta14. В панели проверены выбор канала по умолчанию, срок 300 секунд, автор, отмена удаления и подтверждённое удаление. Три адресных теста прошли. Для записи от WebQuery сервер вернул ClientInvalidId; вход по временному паролю не проверялся. Стенд остановлен.
Windows, база `49536d3`: закрыт command:ban_delete_all. В панели банов добавлена очистка с вводом имени выбранного сервера. На локальном beta14 неверное подтверждение не прошло, отмена сохранила оба ID, а после подтверждения независимый запрос вернул пустой список. Один адресный тест прошёл, стенд остановлен.
Windows, база `5a4d2ed`: закрыт command:ban_add. На beta14 форма отклонила пустую цель и отрицательный срок. Отмена сохранила два исходных бана с прежними ID. После сохранения панель и отдельный запрос подтвердили новую запись, срок 60 секунд и причину. Адресный тест прошёл, стенд остановлен. Блокировка подключённого участника не проверялась.
Windows, база `d56b097`: закрыт command:ban_delete. Убрано повторное подтверждение при удалении строки бана. На beta14 отмена сохранила оба ID, подтверждение удалило только выбранный временный бан, постоянный сохранил прежний ID. Прошёл адресный тест, стенд остановлен. Массовое удаление не проверялось.
Windows, база `21752a8`: закрыт command:ban_list. На beta14 панель показала постоянный и временный баны; гость без права чтения увидел отказ без строк. Проверены неизвестное поле запроса, некорректный срок и запоздалые ответы после закрытия панели или смены сервера. Стенд остановлен. Создание и удаление банов из клиента не проверялись.
Windows, база `33a8f26`: закрыты preload:filesUpload и main-only-command:file_upload для классического хранилища. Ядро распознаёт коллизию имени и при позднем ответе сервера; окно передач сохраняет выбранную копию вложения для подтверждённой замены. На beta14 проверены отмена, замена, листинг и обратное скачивание, отдельно проверен выбор файла после переподключения. Оба адресных теста прошли, стенд остановлен. S3 и отправка сообщения в чат не проверялись.
Windows, база `8c1ae84`: закрыт main-only-command:file_config. Три теста сервиса подтвердили распределение лимитов и возврат полной полосы первой вкладке после отказа второй при старте и возобновлении. Отдельный тест на classic beta14 подтвердил общий лимит и содержимое двух файлов по 4 МиБ. Стенд остановлен; отказ проверялся отдельно на уровне команд.
Windows, база `67e592c`: закрыто channel_edit.channel_password. Два гостя beta14 проверили сохранение защиты при пустом поле, отказ для старого пароля, вход с новым и вход без пароля после явного снятия защиты. Тест дождался обоих отключений в менеджере и интерфейсе; физические аудиоустройства не открывались. Один адресный тест прошёл, стенд остановлен.
Windows, база `866d37b`: ядро больше не сохраняет channel_password, virtualserver_password и virtualserver_keypair в кэше свойств для channel_list, channel_info и server_info. Флаги защиты сохранены. Прошли три теста ядра на тестовых уведомлениях и один тест заполнения редактора; реальные секреты не использовались.
Windows, база `04734b1`: закрыты channel_create.channel_name_phonetic и channel_edit.channel_name_phonetic. На beta14 редактор и данные канала подтвердили сохранение фонетического имени, отмену следующей правки и успешную замену без переименования канала в дереве. Обе формы отклонили 256 символов. Один адресный тест прошёл, стенд остановлен. Синтез речи не проверялся.
Windows, база `f7dc6cb`: закрыты channel_create.channel_codec и channel_edit.channel_codec для Opus Music и Opus Voice. На beta14 создание с Music потребовало права b_channel_create_modify_with_codec_opusmusic. Отмена сохранила Music, после сохранения Voice список каналов и новый редактор показали Voice. Один адресный тест прошёл, стенд остановлен. Передача аудио не проверялась.
Windows, база `e8f18d5`: закрыты числовые поля channel_create.channel_maxclients и channel_create.channel_maxfamilyclients. На beta14 форма создания отклонила значения вне диапазона, отменила черновик и сохранила лимиты 2 и 6; новая форма редактирования того же канала показала оба значения. Один адресный тест прошёл, стенд остановлен.
Windows, база `4a0f6d8`: закрыты поля channel_edit.channel_flag_maxclients_unlimited и channel_edit.channel_flag_maxfamilyclients_unlimited. Отмена сохранила оба конечных лимита и выключенные переключатели; после сохранения безлимитного режима новая форма показала оба переключателя включёнными и значения -1. Адресный тест beta14 прошёл, стенд остановлен.
Windows, база `34e07df`: закрыты числовые поля channel_edit.channel_maxclients и channel_edit.channel_maxfamilyclients. На beta14 редактор восстановил лимиты 3 и 4 после сохранения и отмены следующей правки; выход за границы дал ошибки в полях. Один адресный тест прошёл, стенд остановлен. Наследование и вход при заполнении канала не проверялись.
Windows, база `7ee33dc`: закрыто поле admin-property:channel_create.channel_password. Форма Slint отклонила пароль сверх лимита, отменила черновик и создала временный защищённый канал на beta14. Второй гость остался в лобби после неверного пароля и вошёл с верным; обе вкладки подтвердили переход. Один адресный тест прошёл, стенд остановлен.
Windows, база `815c7c4`: закрыто поле admin-property:channel_create.channel_description. На локальном beta14 гостю добавлено право b_channel_create_with_description. Адресный тест формы Slint прошёл: после создания многострочный текст совпал с отдельным ответом ядра по ID канала и значением в заново открытом редакторе. Стенд остановлен.
Windows, база `dd433fa`: после отзыва скачанного релиза повторная проверка обнуляет прогресс, удаляет кэш и не предлагает текущую либо более старую версию. Прошли шесть адресных тестов. Вместе с проверками канала и целостности закрыты preload:checkForUpdates и preference:updateChannel на локальном стенде; установка не выполнялась.
Windows, база `fa0546e`: закрыт preload:downloadUpdate на локальном HTTP-стенде. Семь адресных тестов прошли: ручная загрузка при активном соединении, отложенная автоматическая загрузка, отказ при неверном размере или SHA512, отмена старого запроса. Укороченный пакет не попал в кэш и не изменил тестовый исполняемый файл; установка не проверялась.
Windows, база `20e99f0`: при переключении канала обновлений сбрасывается время проверки старого канала. Закрыт preload:setUpdateChannel: выбор Stable из панели «О программе», два перезапуска, отказ записи и устаревшие ответы Preview проверены. Девять адресных тестов прошли на временном профиле и loopback; установщик не запускался.
Windows, база `d2617e4`: исправлены предупреждения о конфликте клавиш между разными профилями и подписи безымянных папок в диалоге перемещения закладок. Прошли девять адресных тестов нативного клиента; закрыты поля id, name и parent папок закладок. Проверены маршрутизация клавиш после перезапуска и локальная блокировка сообщений по UID. Системная регистрация клавиш, физическая клавиатура и живой чат в этот прогон не входили.
Windows, база `17089bc`: в панели базы клиентов можно выбрать ник или UID и отправить запрос по Enter. На beta14 оба режима вернули ту же запись, что и список. Прошли три теста: поиск, защита от устаревшего ответа, локальный фильтр файлов. Тест нашёл переключатель в дереве Slint и вызвал обработчик отправки; выбор мышью и Enter не имитировались. Стенд остановлен.
Windows, база `bf6adcd`: закрыты client_database_list и client_database_find. На приватном beta14 список и поиск Slint показали одинаковую запись гостя (имя, UID, ID базы). Отдельный CLI-прогон подтвердил совпадение поиска по UID и нику. Прошли четыре нативных теста и два теста stdio. Записи базы не менялись, стенд остановлен; действие client_database_id из UI этим не проверено.
Windows, база `f453f48`: при просмотре соседней вкладки кнопки микрофона и динамика Slint меняли флаги владельца ввода. Оба списка участников beta14 подтвердили выключение микрофона, включение и выключение звука; у наблюдателя флаги не изменились. Прошёл один адресный тест. Включение физического микрофона не проверялось, стенд остановлен.
Windows, база `6dfaf45`: заглушение и повторное включение звука другой вкладки не отзывают разрешение захвата отправителя. На beta14 проверены сохранение разрешения, продолжение передачи и смена состояния получателя. Прошли три нативных теста; стенд остановлен. Физические устройства не использовались.
Windows, база `a47bebf`: пустой set_audio во время передачи вернул transmitting=true и сохранил действующее разрешение захвата. Частичное обновление оставляет второй флаг без изменений; явный null отклоняется. Прошли один тест stdio и два нативных теста, включая передачу через beta14. Физические устройства не открывались, стенд остановлен.
Windows, база `0064353`: закрыт preload:onAudio. После первого сигнала и паузы до тишины получатель отсоединил UI; второй сигнал через beta14 дал новые ненулевые блоки на тестовом выходе без повторного подключения. Прошли четыре адресных нативных теста, включая усиление голоса и изоляцию вкладок. Физические устройства не открывались, стенд остановлен.
Windows, база `a1bf10f`: исправлено разрешение воспроизведения по неполному снимку и audio_state. Проверка отсчётов микшера различает тишину, явное снятие заглушения и повторное закрытие маршрута. Прошли четыре проверки микшера и три интеграционных теста привязки звука. Отсоединение UI в этот прогон не входило.
Windows, база `aab5a34`: закрыт preload:sendAudioFrame для нативного тракта. На beta14 проверена передача синтетического сигнала через DSP и ядро. Отдельно проверены возраст всего кадра, сброс половины кадра при смене разрешения и отзыв предыдущего владельца до подтверждения нового. Прошли пять нативных тестов и три теста ядра. Физический микрофон не использовался; стенд остановлен.
Windows, база `4aaab8f`: закрыт preload:endAudio для нативного пути. После отзыва разрешения и паузы потребителя на 600 мс очередь сохранила только маркер конца; извлечённый кадр и кадр из VAD не прошли к отправке. Свежий кадр с новой меткой начал новую передачу. Прошли четыре теста ядра. Пауза проверена без сети; живые остановки PTT и шёпота проверялись отдельно.
Windows, база `0f5551a`: приватный beta14 отклонил создание каналов с кодеками 0, 1, 2 и 3 (WebQuery 1538). Контрольный канал с кодеком 4 создан, значение подтверждено channelinfo. Проверка живого входа в Speex/CELT и отсутствия исходящих пакетов остаётся открытой; стенд остановлен.
Windows, база `9cbf0bd`: закрыт pttEnabled. После отпускания клавиши выключение PTT восстановило передачу уже разрешённого синтетического ввода, а включение остановило её у обоих клиентов beta14. Прошли два адресных теста, включая перезапуск Slint и отказ при сохранении. Физические устройства не открывались.
Windows, база `ef5c9a8`: закрыт pttCode. В настройках аудио видны состояние записи, ошибка и отмена. После Ctrl+F9 и ошибки записи сохранилась F8; F10 пережила два перезапуска. На beta14 старая F8 не передавала звук, новая F10 передавала с заданной задержкой. Прошли три нативных теста. Физические устройства и системная регистрация не проверялись.
Windows, база `59d5a92`: F9 (Push to Mute) остановила передачу по F8 без изменения флагов микрофона. Отпускание F9 возобновило звук только при удерживаемой F8; при обратном порядке оба клиента остались в тишине. Устранена лишняя перенастройка ввода при закрытии передачи. Прошли три нативных теста, включая две вкладки beta14 с синтетическим микрофоном. Стенд остановлен.
Windows, база `639b8b7`: повторное нажатие PTT после окончания задержки возобновляет ранее активный, разрешённый ввод в той же сессии. На локальном beta14 с непрерывным синтетическим сигналом отправитель завершил TX через 127/523/15 мс при 100/500/Off; при потере фокуса через 15 мс после события. Прошли три адресных теста; измерены состояния двух клиентов, не слышимая задержка физического устройства. Стенд остановлен.
Windows, база `0e6b285`: отпускание экранной кнопки PTT не отзывает разрешение захвата, пока удерживается другая клавиша или действует заданная задержка. Повторное отпускание не продлевает таймер, отмена удержаний отзывает разрешение сразу. Прошли четыре адресных теста, включая Slint и перезапуск настроек. Момент последнего переданного аудиокадра здесь не измерялся.
Windows, база `d8e40b4`: на двух вкладках beta14 переключатель Deny All подавил речь и уведомление для шёпота по F9; Allow All восстановил речь и одно уведомление от отправителя. В обоих случаях отправитель подтвердил передачу. Для синтетического PCM использованы отдельные часы 20 мс, без физических устройств. Прошли три нативных проверки, включая перезапуск, и две проверки ядра.
Windows, база `bbd2c35`: закрыты whisper_start и whisper_stop. В нативном клиенте метка шёпота привязывается вместе с разрешением захвата. На beta14 две локальные клавиши заменяли маршрут; отпускание старой не остановило новую. Синтетический звук через разрешение менеджера появился в истории получателя, последующее отпускание отозвало разрешение. Прошли пять нативных тестов и тест stdio. Без запуска физических устройств и регистрации системных клавиш.
Windows, база `ea957ec`: в `duplex_qa --group-whisper` получатель в том же канале с Allow All не получил звук, признак речи или уведомление для двух чужих групп (серверной и канальной). Отправки в его собственные группы до и после этих попыток доставлены; сервер подтвердил оба отключения. Без изменения прав или физических устройств.
Windows, база `748e760`: проверка `duplex_qa --group-whisper` через приватный beta14 подтвердила доставку серверной и канальной группам в текущем канале. Проверены ID маршрута, декодированный тон и событие с UID отправителя, подтверждены оба отключения. Это две копии Rust-ядра, без физического аудио и клавиш Slint.
Windows, база `bf8f819`: при смене типа группы список шёпота сохраняет выбранный сервер, сбрасывает старую группу и область доставки. Действие выбора группы привязано к типу каталога. Прошли тест Slint с перезапуском, тест формирования команды и интеграционный тест сохранения списка. Групповая доставка через сервер не проверялась.
Windows, база `d77d0c3`: при разрешении маршрута группового шёпота нулевой ID с ведущими нулями, знак плюс и переполнение отклоняются. Схема сохранённых черновиков не менялась. Прошли два теста ядра на разрешение групп и формат пакета; доставка группе на сервере не проверялась.
Windows, база `8be4404`: при завершении шёпота ядро проверяет адресатов по текущему списку, как и при передаче звука. Прошли четыре теста маршрута и пакетного формата, затем duplex_qa --whisper на приватном beta14 с тремя подтверждёнными отключениями. Повторное использование ID проверено тестом маршрута, не принудительно на сервере.
Windows, `82a72e2`: после исправления приёмника запущен `duplex_qa --whisper` с двумя заново собранными stdio-ядрами на beta14. Allow All дал 43 кадра с верным отправителем, Deny All не дал ни воспроизведения, ни уведомления, после возврата к Allow All пришли 42 кадра. Устаревшая метка отброшена после остановки и переподключения; обычная речь после переподключения не создала запись шёпота. Сервер подтвердил все три отключения. Без устройств и горячих клавиш Slint.
Windows, база `6d5e016`: отклонённые буфером голосовые пакеты больше не начинают и не прерывают входящий шёпот. Четыре теста ядра прошли, включая дубликаты пакетов Opus, очистку очереди при Deny All и событие без записи участника в списке. Проверена обработка пакетов; межклиентская доставка на сервере в этом прогоне не проверялась.
Windows, база `0e7d0b9`: закрыт server_log. С правом b_virtualserver_log_view строки в панели совпали с независимым запросом; чтение журнала экземпляра получило отказ с сохранением полей. Исправлено отображение флажков сразу после редактирования. Прошли четыре нативных теста; содержимое строк не выводилось, стенд остановлен.
Windows, база `0d7edae`: stdio проверяет форму JSON до диспетчеризации. Позиционный запрос, массив аргументов и явный null отклоняются; невалидный shutdown не завершает процесс, а чтение профиля без поля args работает. Прошли 19 тестов парсера/stdio и 19 процессных тестов bridge_smoke. Встроенный Rust API не менялся.
Windows, база `49cfd53`: подписка на третий ограниченный канал beta14 вернула видимый PermissionsClientInsufficient и не изменила флаги обеих вкладок. Запоздавший отказ привязан к целевой вкладке, поколению сессии и текущему UI. Прошли три нативных теста; смена сессии при обработке отказа проверена моделью, не принудительным сетевым разрывом.
Windows, база `1d5e4ba`: четыре команды подписки из меню Slint проверены новыми снимками двух каналов на beta14; подписки второй вкладки не изменились. Обе stdio-команды отклоняют позиционные массивы. Прошли две проверки нативного клиента и одна stdio. Живой отказ в правах и переподключение до подтверждения не моделировались.
Windows, база `e15858b`: импорт keybinds v2 учитывает пропущенные дубликаты UUID профилей и привязок в диагностике, оставляет первую запись и не переписывает исходный файл при открытии. Пять тестов прошли, включая резервную копию v1 и восстановление точного совпадения после перезапуска. Физическая регистрация Windows не проверялась.
Windows, база `c8cbf46`: ядро отклоняет ожидающий ответ channel_info/channel_description при удалении целевого канала. Повторное использование ID проверено последовательностью протокольных событий; в живом beta14 проверено редактирование и чтение описания, не повторное использование ID. Прошли три теста ядра, один stdio и четыре нативных. Стенд остановлен.
Windows, база `d72c273`: на отдельном канале classic beta14 подтверждены file_mkdir, file_rename и file_delete из нативного браузера. После каждой операции состояние сверено отдельным запросом списка; отмена удаления сохранила папку. Временный канал без прав по-прежнему вернул видимый отказ. Три адресных теста прошли, стенд остановлен.
Windows, база `f76a7fb`: проверены uploadSlots, limitUpload и uploadMiB на отдельном канале classic beta14. После перезапуска две вкладки делили 1 МиБ/с; снижение числа слотов с двух до одного приостанавливало более позднюю передачу в той же вкладке до явного возобновления. Пять файлов по 4 МиБ скачаны обратно и совпали побайтно. Прошли четыре теста. До выдачи прав на тестовый канал сервер возвращал PermissionsClientInsufficient; стенд остановлен.
Windows, база `aff60b9`: панель прав сохраняет обе категории и действия создания при обновлении одного списка. На двух гостевых вкладках beta14 проверены имена, ID обычных групп и действия меню по независимым ответам сервера. Прошли семь адресных тестов; обновление после изменения группы проверено на тестовых ответах, без записи на сервер.
Windows, база `8e9f28c`: форма журнала принимает число строк, позицию, порядок и флаг экземпляра. На beta14 проверены отмена, ошибки границ, видимый отказ гостю с сохранением полей и отклонение формы прежней вкладки. Прошли пять нативных тестов и тест stdio на границу позиции; содержимое журнала в отчёт не выводилось. Положительный ответ авторизованному пользователю на живом сервере не проверен.
Windows, база `5e73b78`: закрыт `command:server_info`. На двух вкладках beta14 панель показала имя и приветствие из отдельных ответов сервера, а действие редактирования сохранило нужную сессию и UID. Проверены закрытие панели и отбрасывание устаревших результатов в модели; пустой, неоднозначный и чужой ответ не открывает редактор. Прошли четыре нативных теста и тест ядра на аргументы. Серверные настройки не менялись.
Windows, база `cebac97`: форма переноса в защищённый канал проверяет пароль до отправки. На приватном beta14 поле открылось пустым, неверные значения остались с ошибкой, отмена не переместила участника. Отдельно проверена передача в команду пароля длиной 1024 байта с пробелами по краям. Прошли три нативных проверки и тест stdio. Перенос с разрешением сервера не подтверждён.
Windows, база `534f9b5`: после ответа на перенос участника проверяется исходная сессия, но не прежнее местоположение участника. Тест с обновлением списка до обработки ответа подтвердил, что повторная отправка запрещена, подтверждение принимается, а после замены сессии отклоняется. Прошли четыре адресных теста. Это проверка порядка событий, не успешного переноса на живом сервере.
Windows, база `baea1f7`: команда переноса участника привязана к исходной сессии, UID, номеру участника и каналу назначения. На двух гостях beta14 проверены отсутствие действия в общем канале, форма без пароля для открытого канала, отмена, серверный отказ и отклонение устаревшего подтверждения. Прошли четыре нативных теста и проверка stdio для границ ID. Успешный перенос с правами не подтверждён.
Windows, база `d687e35`: форма переименования серверной и канальной групп показывает имя выбранной строки. Пробелы по краям удаляются, пустое и неизменённое имена не отправляются, изменённое имя сохраняет исходный ID и сессию в команде формы. Прошли три теста нативного клиента. Запись группы на живом сервере не проверялась.
Windows, база `6f1ffc3`: список клиентов, поиск и пагинация проверяют номер запроса, окно, сессию и UID сервера. Тест модели подтвердил отбрасывание ответов в обратном порядке, после «Назад» и после замены сервера. Прошли пять проверок, включая панель гостя beta14. Положительный ответ на поиск от сервера с разрешённым доступом не подтверждён.
Windows, база `c3f3c43`: исправлен устаревший тест байтового лимита поиска. Нативная панель передаёт 255 символов без усечения, 256-й отклоняется. На beta14 открытие базы клиентов из меню сервера вернуло гостю PermissionsClientInsufficient; окно показало отказ без строк и без активного поиска. Три теста прошли; успешные list/find на сервере не подтверждены.
Windows, база `8072e6f`: для шаблона поиска по базе клиентов (255 символов) и UID административных запросов (128) ядро проверяет длину в символах Unicode. Три теста ядра и тест нативного поиска прошли; stdio отклонил пустую строку, управляющий символ и превышение на один символ до подключения. Живые ответы базы клиентов не проверялись.
Windows, база `d1b611a`: ядро и поля создания/переименования групп считают длину имени в символах Unicode, предел 128. Прошли два теста ядра и один тест форм. В stdio допустимое многобайтное имя дошло до not_connected; превышение предела и перевод строки дали bad_request. Изменение реальных серверных групп не проверялось.
Windows, база `1213468`: административные ID и смещение server_log, порядок каналов и семь числовых свойств server_edit ограничены по эталонному контракту. На границе 2^53−1 проверка stdio дошла до not_connected, а 2^53 отклонено до соединения. Прошли четыре теста ядра и три теста нативного клиента. Серверные квоты и группы на живом сервере не менялись.
Windows, база `bff5c33`: проверено поле `channel_codec_quality` в обеих формах. Beta14 вернул 5 после создания и 7 после редактирования того же канала. Значения 11 и −1 остались в форме с ошибкой; отмена изменения на 3 оставила на сервере 7. Прошли три адресных теста, звук не измерялся.
Windows, база `90bcf5d`: закрыт `admin-property:channel_edit.channel_name`. Форма удержала имя длиной 41 символ с ошибкой; отмена сохранила прежнее имя. Новое имя длиной 40 символов подтверждено в списке beta14 по прежнему ID, в дереве Slint и при повторном открытии редактора. Тема канала и имя лобби не изменились. Три адресных теста прошли.
Windows, база `a0c3318`: закрыт `preload:filesChooseUpload`. Диалог отправки файлов канала поддерживает множественный выбор. Пять проверок подтвердили точные имена и размеры, отмену, отказ для устаревшей сессии и для 101 файла, а также очистку временных копий при изменении источника. Файлы не отправлялись на сервер; мобильные диалоги не менялись.
Windows, база `49c747e`: закрыты `file-setting:alwaysAsk` и `file-setting:approvedDownloadDir`. После перезапуска проверены отмена выбора папки и отклонение выбора для прежней сессии. Первая вкладка скачала файл в разовую папку, вторая после выключения запроса использовала сохранённую; байты обеих копий проверены. Первоначальный групповой запуск получил ConnectFailedBanned до проверки второго сценария; адресный тест с интервалом между подключениями прошёл на том же beta14 без изменения прав и ограничений.
Windows, база `5f71304`: при проверке свободного слота ядро считает только активные передачи нужного направления и канала до заданного лимита, без построения и сортировки списка. Прошли тесты выбора следующей передачи и порядка паузы/возобновления; производительность не измерялась.
Windows, база `37552c2`: закрыт `file-setting:downloadSlots`. После перезапуска две вкладки начали три загрузки на классическом beta14. Уменьшение числа слотов с двух до одного через Slint приостановило более позднюю загрузку первой вкладки; после завершения остальных она оставалась на паузе до явного возобновления. Все три файла совпали с исходными байтами. Три адресных теста прошли; uploadSlots в этом сценарии не проверялся.
Windows, база `b41b2d7`: закрыты `file-setting:limitDownload` и `file-setting:downloadMiB`. Две вкладки после перезапуска одновременно скачали по 4 МиБ на классическом beta14. Проверены общий лимит 1 МиБ/с с допуском на блоки и выборку, а также точные байты обеих копий. Прошли три теста; скорость одновременной отправки не измерялась.
Windows, база `e1a07a2`: форма переименования файла открывается с текущим именем; отмена и подтверждение того же имени оставили список сервера неизменным. На классическом beta14 создание папки во временном канале вернуло видимый PermissionsClientInsufficient, повторный file_list пуст. Прошли три проверки. Успешные file_mkdir, file_rename и file_delete не подтверждены; права гостя не менялись.
Windows, база `a6684d3`: на двух гостях beta14 просмотр второй вкладки не менял разрешение первой. При передаче микрофона с недоступным выходом ошибка устройства видна, разрешения отозваны и ни одно аудиоустройство не запущено. Исправлены преждевременные флаги активности, первичное применение маршрута уведомлений и ложная ошибка отсутствующего разрешения у заглушённой вкладки. Прошли семь проверок. Положительная передача PCM при смене владельца в живом окне не проверена.
Windows, база `3396dcb`: закрыт `preference:lastAddress`. Вход из формы Winit подтверждён списком гостей beta14. Ошибка отсутствующего выхода видна и не мешает запомнить адрес, после перезапуска поле восстановлено. Две адресные проверки прошли, запуска аудиоустройств не было. Смена владельца микрофона между живыми вкладками остаётся открытой.
Windows, база `b684eca`: исправлено восстановление сохранённого адреса в форме подключения первой пустой вкладки. Тест Slint на двух запусках подтвердил отмену редактирования, отказ при отключённой сети, отсутствие записи при отказе и пустое поле второй вкладки. На протяжении теста не было активных серверов или запуска аудио. Успешную запись lastAddress через форму на beta14 и полную проверку command:connect не заявляем.
Windows, база `be3654f`: закрыт `feature:chat.central_matrix` как исключение. В открытом серверном чате ссылка `matrix:` неактивна, а `https://matrix.to/` вызывает подтверждение внешней ссылки; отмена сохраняет адресата и черновик. Два теста Slint прошли в отдельных процессах, без сети и внешнего браузера. Серверные комнаты Matrix этим не реализованы.
Windows, база `a8fc57c`: проверены исключения `feature:myts.account_cloud` и `feature:remote_apps` в настройках Slint с одноразовым профилем. Попытка включить облачные личные сообщения оставила клиент без входа и без соединения; пустой Chats не создал беседу при попытке отправки. Прошли три теста, включая отдельный сценарий объявления серверного Matrix. Для `feature:chat.central_matrix` не проверен переход по адресу комнаты при открытой серверной беседе.
Windows, база `149bad2`: закрыт `feature:whisper.block_hotkey` как проверенное исключение. Три режима блокировки из TS6 не регистрируются и не обрабатывают нажатие; действительная привязка ответа и исходные байты профиля v2 сохранены. Причина отражена в диагностике. Прошли три теста загрузки профилей и диспетчеризации, без глобальной регистрации в Windows.
Windows, база `9c0ddd4`: обработчик «Ответить на шёпот» передаёт ядру номер и UID именно того подключения, которое прислало шёпот. Два теста прошли: при двух подключениях с одним UID выбран только отправитель; при смене владельца номера до отправки ядро вернуло `no_targets`. Отказ и событие приёма сохранили ожидаемые уведомления. Проверка использовала тестовый список участников, без системной клавиши и сети.
Публикация: повторный push обновил `origin/feature/desktop-parity` с `b685597` до `20240c1`, включая исправления статуса командира и истории шёпота. Отказ аутентификации ниже относится к первой попытке.
Windows, база `d145043`: история шёпота использует UID отправителя на момент приёма; замена клиента с тем же номером проверена нативным тестом. На закрытом beta14 `duplex_qa --whisper` подтвердил получение с UID, отсутствие звука и события при запрете, возврат приёма и 3/3 отключения. Отдельно прошли тест настройки на двух вкладках, три теста ядра и четыре нативных теста. Системную клавишу ответа не нажимали. Стенд остановлен; push в feature/desktop-parity отклонён при аутентификации.
Windows, база `d9570f3`: закрыт `preference:channelCommanderAsLamp` по отрисовке Slint и восстановлению настройки. Для `client-action:commander` проверены меню собственной строки, отказ гостю на beta14 и устаревшее подтверждение; положительное изменение флага не подтверждено. Прошли четыре нативные и две проверки ядра. Стенд остановлен.
Windows, база `b266f4f`: закрыты `preload:setClientVolume` и `client-action:volume`. На beta14 проверены движение ползунка, сохранение при отпускании, локальный mute, переподключение и сброс. Прошли 12 нативных и три проверки ядра. Два источника Opus проверялись отдельно в микшере, без физических устройств. Стенд остановлен.
Windows, база `62bb67b`: закрыт `command:client_context`. На beta14 доступность действий и групп в меню обоих клиентов совпала с ответами ядра. Повторное открытие и устаревшие ответы проверены отдельно. Прошли пять нативных и две проверки ядра. Права не менялись; стенд остановлен.
Windows, база `256e10a`: закрыт `client-action:poke`. На beta14 отказ ParameterInvalidSize сохранил черновик; исправленный текст дошёл с точным UID отправителя. Отмена, превышение 1024 байт и смена адресата не привели к доставке. Прошли пять нативных тестов и тест stdio; стенд остановлен.
Windows, база `89a2b21`: закрыт `client-action:connection_info`. На beta14 проверено отображение статистики другого участника и своей после переподключения. Единицы измерения и точные 64-битные счётчики проверены отдельно. Прошли семь нативных и три проверки ядра; стенд остановлен.
Windows, база `0b4a707`: закрыт `command:client_info`. Карточка Slint привязана к запросу, вкладке, номеру клиента и UID; частичные ответы не стирают ранее полученные поля. Прошли десять нативных проверок, включая два сценария на beta14, и два теста ядра. Стенд остановлен.
Windows, база `c80219b`: закрыты `command:talk_power` и `feature:client.away_talkpower`. На beta14 проверены ручная выдача и отзыв без заявки, выдача из очереди, устаревшая заявка и отказ обычному гостю. После интервала между сценариями четыре нативных теста прошли; отдельно прошла проверка stdio. Физический звук не использовался, ограничения сервера не менялись; стенд остановлен.
Windows, база `380e9d4`: проверены `command:set_away` и `command:talk_request`. На beta14 обе вкладки увидели изменения статуса и запрос права голоса, включая его отзыв. Явный null и неверные сообщения отклоняются до подключения; прошли тест stdio и тест протокольных команд. Физический звук не использовался; стенд остановлен.
Windows, база `389e26d`: закрыт `command:disconnect`. На beta14 отключение через меню просмотренной вкладки удалило выбранного гостя из списка сервера, вторая вкладка сохранила подключение и роль владельца микрофона. Прошли живой тест и отдельная проверка передачи разрешения между вкладками. Физический звук не использовался. Вход через форму Slint не проверен; стенд остановлен.
Windows, база `f41e064`: менеджер вкладок проверяет запрос до изменения маршрута микрофона. Неверные connect/disconnect оставили действительными прежнюю сессию, владельца и разрешение; ядро приняло следующий сгенерированный PCM-кадр с тем же разрешением. Прошли 20 тестов ядра и 13 тестов менеджера. Физические устройства и переключение микрофона через Slint между живыми подключениями не проверялись.
Windows, база `c12cf21`: ограничения полей connect/disconnect сверены с историческим валидатором. Ядро отклоняет неверные строки и UID до подключения. Прошли 18 тестов протокола и профиля и один тест stdio. Проверка двух вкладок с переключением микрофона из Slint остаётся открытой.
Windows, база `6bf4de7`: закрыт `current-contract:snapshot-partial`. Частичный отчёт перечисляет подтверждённые изменения без значений свойств и разрешений. Отказ и отмена загрузки иконки проверены на уровне сервиса. На beta14 режим Skip показал один пропуск и ноль изменений. Прошли 32 теста; стенд остановлен.
Windows, база `75514f1`: закрыт `preload:snapshotApply`. На beta14 два файла с одинаковым ID каталога не поделили кнопки Apply/Cancel. Подтверждение UID с режимом Skip дало один пропуск, ноль изменений и прежний список каналов. Проверки частичных изменений и отмены выполнялись на уровне сервиса. Прошли 29 тестов; стенд остановлен.
Windows, база `5f3cf5f`: закрыт `preload:snapshotExport`. Частичный экспорт показывает имя сохранённого файла рядом с предупреждением. Прошли четыре проверки, включая Save/Open на beta14; в живом снимке один канал и одна ошибка чтения прав. Полный привилегированный экспорт всех разделов на сервере не выполнялся. Стенд остановлен.
Windows, база `1796838`: закрыт `preload:snapshotCancel` по шести проверкам сервиса и состояния интерфейса. Ранняя отмена не отправила запросов и не создала файл. Частичный отчёт сохранил ID уже созданного канала, дочерний канал не создавался. Живой сервер не изменялся.
Windows, база `e47a81d`: закрыт `preload:onSnapshotProgress`. На beta14 последнее событие задания сообщило 2/2 обработанных шага, один канал и одну ошибку прав. Прошли 20 проверок прогресса, отмены, смены сессии и итогового отчёта. Стенд остановлен; на живом сервере выполнялись только экспорт и открытие файла.
Windows, база `160ba55`: закрыт `preload:snapshotOpen`. Корректный файл открыт через системный диалог; неверный формат и файл свыше 32 МиБ не получили токена. Для обычных файлов размер проверяется до чтения содержимого. Прошли четыре проверки выбора, декодера и смены сессии.
Windows, база `c912eb3`: живой тест экспорта и открытия снимка прошёл. Отмена Save не оставила файла; выбранный JSON содержал один постоянный канал из реального списка beta14. Отчёт частичный: одна ошибка чтения прав канала. После Open панель показала правильные каталог и UID сервера. Импорт не применялся; стенд остановлен.
Windows, база `89cf170`: отмена предпросмотра снимка отзывает токен выбранного файла. Запоздалое подтверждение не отправило команду изменения сервера; повторный выбор и новое подтверждение применили изменение один раз. Прошли 12 тестов сервиса снимков. Проверка использовала тестовый обработчик команд, не живой сервер.
Windows, база `89cf170`: экспорт проверяет связи родителя и предшественника до запросов свойств. Потерянные узлы, циклы и неоднозначный порядок не превращаются в неполный снимок с пометкой об успехе. Прошли 11 тестов сервиса; живой экспорт через системный диалог этим прогоном не проверен.
Windows, база `4fee4c0`: экспорт снимка сверяет ID единственной строки свойств с ID экспортируемого канала. При неверном ответе отчёт частичный; соседний канал сохранён со своим описанием. Прошли 10 тестов сервиса снимков. Системный диалог экспорта не проверялся.
Windows, база `061bb2d`: закрыт `command:channel_info`. На beta14 из меню временного канала Slint прочитаны имя, тема и многострочное описание; при выборе лобби прежние свойства не остались. Шесть нативных тестов и одна отдельная проверка stdio прошли. Стенд остановлен.
Windows, база `96d9c45`: проверен `preference:highlightContacts` в Slint после двух перезапусков. Подсветка строки следует за UID, а не номером клиента. Прошли две проверки контактов на изолированном профиле и синтетическом списке участников.
Windows, база `2e45637`: восемь автономных проверок контактов прошли. Форма Slint сохраняет UID, имя и псевдоним после перезапуска; отмена удаления сохраняет запись, подтверждённое удаление переживает следующий запуск. В меню доступно только актуальное действие игнорирования, устаревшая команда удалённого контакта не меняет список. Сеть, устройства и буфер обмена не использовались.
Windows, база `b7635de`: показ и копирование папки загрузки используют одно сохранённое значение. Три автономные проверки прошли: пустой и сохранённый путь, отказ Slint и платформы при запрещённом доступе к буферу. Системный буфер не трогали. Из трёх сетевых сценариев два прошли, третий остановлен на входе с TS 3329; стенд выключен. Положительная запись в системный буфер не подтверждена.
Windows, база `de99c5f`: файловый браузер учитывает запрет переименования для «Переместить» и запрет просмотра или скачивания для «Скачать папку». Четыре теста модели меню прошли. Проверка отображения разрешений не заменяет живое выполнение mkdir/rename/delete; эти команды остаются открытыми.
Windows, база `b4e084d`: закрыт `command:file_fetch_image` для классического beta14. Проверены байты и отрисовка PNG в окне Slint, а также отбрасывание устаревших результатов после переподключения. Ограничения размеров проверяются до декодирования растра. Прошли четыре нативных проверки и тест stdio. Стенд остановлен.
Windows, база `c6cb353`: проверены `file_pause`, `file_resume` и `file_cancel` из панели Slint на классическом beta14. Отмена частично скачанного файла не оставила ни результата, ни временного файла; продолжение второй передачи дало точные 4 МиБ. Прошли живой тест, проверка границ ID через stdio и четыре теста ядра. Стенд остановлен.
Windows, база `67b2fc6`: для `preload:filesDownload` и `main-only-command:file_download` подтверждены скачивание и прогресс на beta14, отмена перезаписи и устаревшего выбора папки. Три отдельные проверки прошли для ошибки StorageFull после частичной записи, отмены копирования и повторного события после ошибки экспорта. Реальный том не заполнялся.
Windows, база `a3ee6cc`: после скачивания из файлового браузера beta14 повторно открытая панель передач показала 46 B / 46 B. Переподключение той же вкладки оставило пустой список в ядре и в Slint. Адресный тест прошёл; стенд остановлен.
Windows, база `8d4daf4`: закрыт `command:file_list` для классического хранилища. Меню канала Slint открыло список на beta14, размер строки совпал с 46 байтами файла, скачивание из этой строки дало точное содержимое. Прошли два сценария Slint и тест stdio для границы ID. Стенд остановлен.
Windows, база `e25263e`: закрыт `preload:filesRelease` на уровне файлового сервиса. Подсказка последней папки хранит только путь. После release повторная загрузка с этим токеном отклонена без команды ядру и без изменения прежнего файла. Активная передача удерживает собственное разрешение до завершения. Прошли 13 тестов файлового сервиса.
Windows, база `ba6cae3`: проверен `preload:filesSettings`. После перезапуска в Slint восстановились папка, запрос пути, слоты 8/2 и лимиты 1,5/2,5 МиБ/с. Прошли пять тестов, включая скачивание с beta14 и проверку распределения настроек между двумя тестовыми сессиями ядра. Сетевая скорость одновременно работающих клиентов не измерялась. Стенд остановлен.
Windows, база `e7951f1`: закрыт `preload:filesChooseDownloadDir`. Разовый выбор папки не переживает переподключение той же вкладки. Новый выбор сохранил 46 байт, не изменив постоянную папку. Прошли три проверки на классическом beta14; стенд остановлен.
Windows, база `6712e6d`: проверен `preload:filesChooseDefaultDir`. Два теста Slint: после перезапуска гостевой клиент beta14 получил 46 ожидаемых байт в выбранную папку; отсутствующая папка вызвала ошибку без подстановки другого пути. Классический стенд получил исходный файл при создании; загрузка гостем на сервер не разрешена, S3 не проверен. Стенд остановлен.
Windows, база `9a518bd`: выбор папки записи проверен из настроек звука через системный диалог. Отмена и попытка записи через общие настройки путь не изменили; после двух перезапусков оба WAV экспортированы в выбранную папку. Прошли два теста; стенд beta14 остановлен. Мобильные диалоги не проверялись.
Windows, база `5916610`: проверены семь команд `recording_*`. Панель Slint запрашивает статус ядра; старый Stop не останавливает вторую запись. На beta14 сверены форма сигнала, длительность и WAV, сохранность первого файла и чистое состояние после переподключения. Прошли 11 нативных проверок и отдельный тест stdio на неверные аргументы. Физический звук не использовался; стенд остановлен.
Windows, база `dc3e596`: Preview/Start/Stop привязаны к конкретному выбору источника, а Live требует и ID, и подтверждения setup. Прошли восемь тестов, включая сгенерированный источник на beta14. Для полного `command:stream_setup` остаются системный выбор источника и видимый отказ в этом сценарии. Стенд остановлен.
Windows, база `1fe05c0`: закрыт `command:stream_signal`. Два локальных WebRTC-пира проверили ранний ICE, порядок ответа, откат SDP и смену ICE-соединения по декодированным кадрам. Четыре отдельные регрессии и 16 тестов протокола прошли. Нулевой ID участника отклоняется до отправки; поиск по всему каналу без ID сохранён. Официальный клиент не участвовал.
Windows, база `b685597`: закрыт `command:stream_join`. На приватном beta14 после нажатия «Смотреть» и допуска издателем проверены красные пиксели в карточке Slint и тон 1 кГц на декодере выбранного зрителя. Отмена до допуска и действие отключённого зрителя не запустили просмотр на другой вкладке. Прошли два теста; стенд остановлен. Физические устройства и официальный клиент не проверялись.
Windows, база `59a2878`: закрыт `command:stream_list`. При открытии раздела клиент запрашивает потоки своего канала; параллельный запрос выбранного участника не отменяется. На beta14 прошли общий и адресный поиск, а также открытие списка из Slint; всего в адресном наборе нативного клиента прошли девять тестов. SFU проверен на тестовом объявлении. Стенд остановлен.
Windows, база `8630542`: закрыт `command:stream_leave`. На beta14 добровольный выход освободил пир и кадры выбранного зрителя, не прервав видео у другого. Повторный выход по старому объекту не закрыл новый просмотр. Прошли живой тест и две регрессии для задержанного подтверждения и закрытия окна. Источник сгенерирован; стенд остановлен.
Windows, база `039af3f`: закрыт `command:stream_remove`. При двух допущенных зрителях на beta14 исключение по имени в карточке Slint отключило только выбранного: второй продолжил получать новые синие кадры. UID проверен по двум серверным спискам. Два отдельных теста подтвердили защиту от повторной выдачи номера. Стенд остановлен.
Windows, база `8004c01`: закрыт `command:stream_stop`. На beta14 Stop из карточки Slint завершил выбранную публикацию во время передачи видео. Источник отклонил следующий кадр, просмотр завершился без оставшегося кадра, повторный поиск с обеих вкладок не обнаружил поток. Физический захват не использовался; стенд остановлен.
Windows, база `f7601e7`: закрыт `command:stream_respond`. На beta14 издатель разрешил просмотр первому зрителю и отказал второму. После отказа первый зритель получил три новых зелёных кадра без переподключения. Первоначальный запуск остановился на `ConnectFailedBanned` до проверки допуска; отдельный запуск с интервалом между подключениями прошёл на том же стенде без изменения серверных ограничений. Стенд остановлен.
Windows, база `402d8ff`: прошли два изолированных теста Slint на закрытом beta14. В `approved_beta14_viewer_receives_generated_video` зритель дождался допуска, издатель разрешил просмотр из карточки Slint, после ответа WebRTC зритель получил три красных кадра. Выход зрителя очистил список допущенных. Использован сгенерированный источник; звук, третья вкладка зрителя и официальный клиент не проверялись.
Windows, база `1e2856e`: `duplex_qa --stream-lifecycle` подтвердил на закрытом beta14 доставку заявки издателю и отказа без SDP зрителю. После отказа наблюдатель заново нашёл тот же поток; обновление, остановка и оба отключения прошли. Положительное решение и передача медиа этим сценарием не проверены.
Windows, база `f563d2b`: редактор действующей публикации Slint привязан к ID потока и UID издателя. В тесте на beta14 отмена сохранила исходное имя, после сохранения вторая вкладка подтвердила новое имя, битрейт 2700 и лимит 4 у того же потока. Прошёл также тест карточки без WebRTC. Источник сгенерирован; смена устройства или аудиозахвата не проверялась.
Windows, база `e52db5b`: на beta14 наблюдатель перечитал имя, битрейт, лимит зрителей и признак аудио у того же потока после подтверждения `stream_update`. В нативном издателе прошли проверки отложенного подтверждения, отказа, ограничений доступа и отключения во время запроса (24 теста сигнализации, отдельно 2 теста ядра). Проверен снимок состояния издателя, не видимое окно настроек и не фактическая скорость передачи.
Windows, база `c27a425`: на beta14 прошёл `duplex_qa --stream-lifecycle`. Наблюдатель подтвердил регистрацию и остановку потока по ID; без `reason=1` сервер отвергал остановку с TS 1542. Оба отключения подтверждены. Отдельно прошли тест сериализации ядра и две проверки нативного поиска. Подключение зрителя и медиа через эту сигнализацию пока не проверены.
Windows, база `f0ed160`: тест `decoded_tone_and_moving_video_on_local_peers` прошёл на двух нативных WebRTC-пирах. После декодера тон 1 кГц обнаружен в 43 из 46 блоков; одновременно показаны 12 кадров с возрастающим счётчиком. Аудиовыход закрыт, TeamSpeak-сигнализация и официальный клиент не использовались.
Windows, база `6053e8b`: `webrtc_smoke` прошёл с локальным архивом WebRTC. Из 14 отправленных кадров libvpx декодировал 14, на выходе проверены 7 красных и 6 зелёных кадров. Источник после остановки отклонил новый кадр, callback вызван один раз. Это два локальных пира без TeamSpeak-сервера, физического захвата и передачи аудио.
Windows, база `5933297`: остановка зарегистрированной публикации по своему `clid` освобождает источник сразу. До получения ID начало и остановка обрабатываются в порядке получения; события старого издателя не перенаправляются новому. Прошли 22 теста каталога и сигнализации с тестовыми источниками. Реальный захват и передача на сервер не проверялись.
Windows, база `5e646fc`: подтверждение и отклонение заявки на просмотр сверяют UID из меню до изменения очереди. Проверка повторной выдачи номера подтвердила, что оба устаревших действия сохраняют заявку нового зрителя, а подтверждение по актуальному UID работает. Прошли 19 тестов сигнализации; живой обмен WebRTC в этом прогоне не проверялся.
Windows, база `aa88f78`: ручное исключение зрителя передаёт UID из выбранного пункта меню и сверяет его до локального исключения и перед отправкой. Прошли 19 тестов сигнализации: устаревшее действие не заблокировало нового зрителя, а актуальное действие сработало. Это проверка издателя с тестовым пиром, не живой серверный прогон.
Windows, база `85e559d`: при смене приватности издатель закрывает отозванные соединения до сетевого ожидания и повторно сверяет UID перед отправкой. Тест подтвердил, что новый владелец переиспользованного номера не получает команду удаления, а трансляция не останавливается. Прошли 18 тестов сигнализации с тестовыми пирами; сквозная проверка через живой сервер остаётся открытой.
Windows, база `6fea1a8`: хаб немедленно завершает просмотры указанного автора при `notifystreamstopped` без ID потока. Тест проверил два просмотра одного автора, независимый просмотр другого автора и повторное открытие потока с тем же ID. Прошли 19 тестов каталога и сигнализации; реальные медиапотоки не использовались.
Windows, база `5417970`: просмотрщик больше не принимает некорректный тип `clid` за отсутствие адресата. Прошли 16 тестов сигнализации: неверные адресаты не создали пир и не завершили ожидание; следующий корректный ответ был принят. Это проверка состояний на тестовых пирах, не передача видеопотока.
Windows, база `dfb60d7`: отказ ядра при отправке локального ICE-кандидата после ответа переводит просмотрщик в Failed с причиной, закрывает пир и вызывает выход один раз. Прошли 15 тестов сигнализации с тестовыми пирами. Реальная передача видео в этом прогоне не проверялась.
Windows, база `335466b`: исходящие `stream_signal` и текст `stream_join` проверяются по схеме исторического клиента. Прошли четыре проверки ядра и два теста нативной сигнализации. Реальные WebRTC-пиры, изображение и звук этим прогоном не проверялись.
Windows, база `6ac0967`: семь тестов прошли для `chatUse24hTime` и связанных строк истории. Формат 12/24 ч меняется у загруженного сообщения и в журнале событий; после перезапуска исходная метка времени сохранена. Журнал проверен на русском и английском с тестовыми событиями.
Windows, база `4244adf`: расширенный тест чата на закрытом beta14 подтвердил видимый отказ гостю в серверном чате и сохранение черновика после ухода с вкладки и возврата. Личное и канальное сообщения доставлены. Успешную широковещательную отправку этот прогон не доказывает. Отдельно прошли три проверки валидации ядра.
Windows, база `390261e`: прошёл `send_text_delivers_exact_private_and_channel_messages_on_beta14`. Две временные identity проверили личную и канальную доставку из редактора Slint, единственное эхо у отправителя и сохранение слишком длинного черновика. Отправка в серверный чат этим прогоном не проверена.
Windows, база `2af19bc`: прошёл `protected_channel_join_from_tab_keeps_lobby_until_password_accepted` на закрытом beta14. Подтверждены выбор без перехода, отмена, видимый отказ при неверном пароле и переход по верному паролю на обеих вкладках. Закрыт `command:join_channel`.
Windows, база `0ef6447`: два теста ядра подтвердили отказ для `join_channel(0)` до проверки подключения. Тест Slint подтвердил выбор действия подписки и защиту от устаревшего пункта меню. На beta14 четыре переключения подписок подтверждены снимками после явного сброса автоподписки; без сброса первый вызов получил подтверждение без нового снимка. Второго чужого канала не было. Подробности в FEATURE_COMPATIBILITY.md.
Windows, база `c0835c6`: четыре адресных теста чата прошли с изолированными событиями. Подтверждены `chatOpenIncoming`, `chatIgnoredUsers` и `chatShowModerationEvents`. Исправлены фильтрация уже полученных событий модерации и игнорирование сообщения без явного UID, когда отправитель известен из списка участников. Сетевой обмен в этих тестах не проверялся.
Windows, база `20e6008`: прошли два отдельных теста настроек Slint. Audio PTT сохраняет состояние после перезапуска и при ошибке записи. Whispers на двух подключённых вкладках beta14 подтвердил три смены режима и сохранение последнего. Прямого чтения политики из каждого ядра нет; обмен аудио через эти вкладки и физические клавиши не проверялись.
На Windows прошёл расширенный `bookmark_sidebar_and_local_contact_reopen_without_network`: перенос непустой папки через форму, проверка вложенных ID после перезапуска, отмена и подтверждение удаления. Для локальных предпочтений подтверждены `savedServers`, `bookmarkOrder` и `bookmarkFolders`; подключение по закладке и хранилище паролей сюда не входят.
Windows, база `8a98e3d`: `duplex_qa --whisper` прошёл на закрытом beta14. При отключении отправитель передавал шёпот; после его переподключения старая метка не дала звука или события, обычный голос доставлен. Все три отключения подтверждены, стенд остановлен. Получатель не менялся, физический звук не использовался.
Windows, база `90c28ee`: для личного адреса шёпота требуется непустой UID из списка участников. Участник без UID не добавляется по временному номеру даже при раскрытии сохранённого канала; адрес самого канала сохраняется. Регрессия: `unidentified_clients_are_not_individual_whisper_targets`. Живое повторное использование номера не проверено.
Windows, база `533b2b2`: ядро обрабатывает все строки `notifytokenadd` до подтверждения. Пустая строка не затирает полученный ключ, повтор одного значения допустим, два разных значения не выдаются как успешный результат. Три адресных теста ядра прошли с тестовыми значениями. Живая выдача ключей и проверка формы остаются открытыми.
Windows, база `509bbb8`: тест `participant_info_menu_rejects_a_previous_session_target` прошёл через меню Slint на loopback beta14. В двух последовательных сессиях показаны версия и платформа своего участника; при отключении старые сведения очищены. После подключения второй identity действие из первой сессии получило видимую ошибку `target_changed`. Стенд остановлен. Разрыв соединения до прихода ответа в этом тесте не моделировался.
Windows, база `c849105`: `client_info` сверяет номер и UID участника до отправки и при подтверждении. На beta14 `channel_admin_qa --client-info` получил версию и платформу; подстановка другого UID отклонена локально. Три теста ядра и один тест нативного клиента прошли. Стенд остановлен; повторное использование номера при ожидании ответа проверено тестом ядра, а не живым переподключением.
Windows, база `60d1953`: отдельный режим `channel_admin_qa --client-database-id` собран и запущен на loopback beta14. Поиск по UID вернул одну строку с точным UID гостя и положительным ID базы. Независимый поиск по нику получил TS 2568, сценарий завершился кодом 1. Сервер подтвердил отключение, ядро завершено, временный профиль удалён, стенд остановлен. Полная сверка и проверка через UI остаются открытыми.
Windows, база `25575d1`: ядро сопоставляет `client_database_id` с точным UID в уведомлении и требует один положительный ID базы. Три адресных теста прошли; живой поиск через интерфейс в этом прогоне не проверялся.
Windows, база `d841530`: для `group_add` ядро исключает ранее известные ID групп нужной категории и сверяет имя и тип ответа. Проверены нулевой ID, повтор одного нового ID и неоднозначный ответ. Прошли три теста ядра и два теста импорта снимков. Создание серверной или канальной группы на живом стенде этим прогоном не подтверждено.
Windows, база `643d0e4`: поиск в браузере файлов фильтрует загруженные имена, сохраняет переход к родителю и сбрасывается при смене каталога. Тест Slint проверил обновление списка, регистр кириллицы и цель контекстного меню. Прошли три адресных теста; сетевой обмен файлами не проверялся.
Windows, база `3a8e15e`: поиск и перелистывание базы клиентов используют тот же контекст прав, что и первая страница. Три адресных теста прошли, включая сохранение смещения, строки поиска, ID записи и сессии. Живой запрос базы и удаление записи не проверялись.
Windows, база `d5ba657`: в списках прав ядро учитывает каждый явно указанный ID и не смешивает строки разных групп при смене ID внутри пакета. Три адресных теста прошли, включая продолжение списка в следующем пакете. Это проверка разбора протокола, не живое изменение прав.
Windows, база `e9f375c`: проверен `command:rename` на двух временных identity и локальном beta14. Форма сохранила занятый ник после отказа и закрылась после успешной повторной отправки. Оба списка участников показали новое имя с прежним серверным UID, а после открытия профиля изменился только ник нужной локальной identity. Тест `nickname_refusal_keeps_draft_and_retry_updates_only_own_identity` прошёл; стенд остановлен.
Windows, база `f804bef`: сворачивание скрывает непосредственных участников, сохраняется в `collapsedChannels` по адресу сервера и не скрывает подканалы. Три адресных теста прошли: Slint с двумя перезапусками и повтором номера канала на другом адресе, атомарность сохранения и регрессия порядка и размеров дерева. Проверены EN/dark и RU/light на снимках тестовых серверов.
Windows, база `3db0766`: для `showClientsBeforeChannels` проверены координаты участника и подканала в одном дереве до и после переключения, а также после перезапуска. Плотность не изменила порядок; смена порядка не изменила высоту строк и выбранный канал. Тест `tree_style_resizes_only_client_rows_and_survives_restart` прошёл для EN/dark и RU/light.
Windows, база `faf9f95`: выбор `treeStyle` в настройках оформления теперь меняет строки участников в дереве Slint. Прошёл `tree_style_resizes_only_client_rows_and_survives_restart`: 40 и 28 px для участника, 44 px для канала в обоих режимах; выбранный канал сохранился. Проверены EN/dark и RU/light с повторным запуском. Это измерение отображённых строк тестового сервера, не полное визуальное сравнение клиента.
Windows, база `2c8a47d`: исправлен статус трёх режимов скрытия в панели задач и описание микрофона после разблокировки. Тест `taskbar_capability_tracks_the_selected_hide_mode` прошёл в отдельном окне Windows с временным профилем. Реальная блокировка, физические горячие клавиши и скрытие в трее не проверялись. Семь статических сверок TS6 по уведомлениям, чату, оформлению, приватности, клавишам и ОС записаны в FEATURE_COMPATIBILITY.md. Триггер речи при выключенном микрофоне остаётся открытым.
Windows, база `2e3b271`: тест `recording_panel_exports_a_paused_and_resumed_master` прошёл после двух перезапусков с одним временным профилем. Master выбран в настройках; режим 4 отклонён, отмена Multitrack не создала файлов и не изменила выбор. На beta14 записан и экспортирован Master с одной паузой. Стенд остановлен. Системный выбор каталога этой проверкой не покрыт.
Windows, база `7729f26`: форма начала записи выбирает режим без произвольного имени папки. Клиент передаёт локальную метку времени, при недоступном часовом поясе ядро использует UTC. Тест `recording_panel_exports_a_paused_and_resumed_master` прошёл в настоящем окне Winit/Slint на локальном beta14: старт, дорожка Master, пауза, продолжение, остановка, экспорт, одна пауза в манифесте и совпадение размера WAV с числом кадров. Временная папка была заранее разрешена. Качество физического входа и системный picker не проверялись; стенд остановлен.
Windows, база `d59bebd`: отпускание ползунка и подтверждение формы сохраняют громкость следующего просмотра в `streamVolume`; во время движения меняется только текущий просмотр. Проверены события Slint, чтение 0%, 43% и 100% после повторного открытия временного профиля и изолированный микшер. Четыре адресных теста прошли. Живой WebRTC и физический аудиовыход не проверялись.
Windows, база `d5b9541`: ползунок и форма громкости трансляции используют диапазон проигрывателя 0–100%. Нажатие в середине видимого ползунка Slint передало выбранному просмотру примерно 0,5. Три адресных теста интерфейса, проигрывателя и микшера прошли. Сохранение после перезапуска и живое воспроизведение WebRTC не проверялись.
Windows, база `8a8f52d`: карточка потока режима 2 показывает ограничение SFU и убирает просмотр; медиасервис не отправляет P2P join для такого объявления. Отдельный P2P-поток того же участника остаётся доступен. Прошли тест карточек Slint и тест команд сигнализации. Живой SFU и сборка с WebRTC этим прогоном не проверялись.
Windows, база `89a930d`: уведомление об изменении описания канала сбрасывает устаревший текст в кеше и ожидающем ответе только для указанного канала. Четыре теста ядра прошли. Живой тест Slint на beta14 подтвердил многострочное редактирование, отмену, очистку и повторное чтение пустой строки. Гостевое создание с описанием отклонено; отдельный быстрый прогон редактирования получил ClientIsFlooding, а с интервалом стенда завершился успешно. Сверки файловых протоколов, Matrix и потоков зафиксированы в FEATURE_COMPATIBILITY.md.
2026-11-27, Windows, база `0354a6f`: настройки микрофона, воспроизведения и уведомлений показывают недоступное сохранённое устройство только после получения каталога. Возврат устройства восстанавливает имя без запроса смены маршрута. Два адресных теста прошли, включая представление Slint; физический hot-plug и работа активного потока не проверялись.
2026-11-27, Windows, база `010e6b4`: ссылки `ts3file://` с IPv6 из браузера файлов распознаются в чате. Прошли три теста, включая кодирование и чтение пути и UID; сетевую загрузку не проверяли. Сверки voice.dsp/devices/3d, whisper.all/receive_mode_transport/block_hotkey и chat.ts3file_links записаны в FEATURE_COMPATIBILITY.md отдельно от исполнения на оборудовании.
2026-11-27, Windows, база `a25bd6b`: исправлен отказ гостю beta14 при создании обычного канала через Slint. Форма не отправляет нетронутые необязательные поля; кодек и шифрование имеют явный выбор серверного значения. Через headless Slint и реальный beta14 проверены имя и тема при создании и тема при редактировании, ошибки длины, отмена и чтение после сохранения. Живой тест и пять адресных тестов свойств прошли, стенд остановлен. Смена сессии до ответа и физическое отображение не проверялись. Сверки TS6 server.admin, chat.server_plain_send и chat.history_local записаны в FEATURE_COMPATIBILITY.md отдельно от приёмки.
2026-11-27, Windows, `e6a8d2f`: живой `channel_admin_qa` подтвердил ID нового временного корневого канала на beta14, чтение свойств, изменение темы и обоих лимитов, отклонение устаревшего поколения и недопустимого качества. Первому запуску стенда не хватило времени, подключение не состоялось; повтор со стендом, удерживаемым до конца теста, прошёл. Вложение в родителя отклонено (TS 2568), наследование не подтверждено. Канал автоматически удалён после выхода, профиль удалён, стенд остановлен. Это проверка IPC; сценарий через видимый интерфейс остаётся открытым.
Windows, база `95ebf37`: подтверждение создания канала сопоставляется с автором, именем и родителем. Отсутствие однозначного положительного ID после принятия команды возвращает ошибку с `created: true`. Повтор одного ID допустим. Прошли три адресных теста ядра и нативный тест `post_create_icon_uses_only_acknowledged_child_id`; живой сервер в этой проверке не участвовал.
Windows, база `b3f73c3`: ядро сверяет ненулевой `channel_order` при создании и редактировании канала с текущим деревом перед отправкой. Удалённый или перемещённый в другую ветку сосед и ссылка редактируемого канала на себя отклоняются. Четыре адресных теста ядра прошли; сетевой запрос и ответ сервера в этом прогоне не проверялись.
Windows, база `3c828e3`: при создании канала смена родителя очищает позицию и ограничивает список предшественников его детьми. Тест Slint проверил три команды для родителя 8: без `channel_order`, с явным 0 и с ID 13 второго одноимённого соседа. Прошли шесть адресных тестов. Применение этих команд сервером в этом прогоне не проверялось.
Windows, база `8930007`: завершена сверка `channel.crud` с установленным TS6. Ядро возвращает `{"changed":false}` без сетевой команды только при совпадении родителя и явного предшественника. Три адресных теста прошли. Положительный ответ сервера на перенос и удаление этой сверкой не подтверждён.
Windows, база `9b19e96`: ядро перед отправкой `channel_move` проверяет, что предшественник всё ещё принадлежит выбранному родителю и новая ветка не замыкает цикл. Три адресных теста прошли, включая исчезновение или перемещение предшественника, перенос родителя в исходное поддерево и допустимую первую позицию. Серверное подтверждение переноса в этот прогон не входило.
Windows, база `cc3cb27`: диалог переноса канала показывает текущего родителя и предшественника. При смене родителя предлагает первую позицию и только соседние каналы. Тест Slint выбрал второй из двух одноимённых каналов и получил `channel_id=42, parent_id=8, order=13`. Шесть адресных тестов прошли. Это проверка формы и аргументов команды, не подтверждение перемещения на сервере.
Windows, база `be1d308`: сценарий `channel_admin_qa --channel-order` собран и запущен с актуальным диагностическим ядром. Гость beta14 получил TS 2568 на `channel_create` с явной позицией. Проверка порядка завершилась кодом 1; отключение подтверждено сервером, временный профиль удалён, стенд остановлен с кодом 0. Живой результат изменения порядка не установлен.
Windows, база `981c486`: ответы `channel_list` и `channel_info` берут родителя и предыдущий соседний канал из актуальной модели дерева. Адресный тест `channel_readback_uses_current_sibling_position_and_retains_extra_fields` прошёл: сохранены дополнительные свойства, позиция обновлена, удалённый канал не возвращается. Живое перемещение и показ позиции в окне в этом прогоне не проверялись.
Windows, база `827f2c3`: окно сервера показывает название Speex/CELT по текущему каналу открытой вкладки. Прошли `codec_warning_follows_joined_channel_on_viewed_tab` и `legacy_codecs_neither_select_an_encoder_nor_enter_the_mix`. Снимки для окна тестовые; пункт живого входа в legacy-канал остаётся открытым.
Windows, база `ced85a3`: при отзыве захвата менеджер один раз инвалидирует каждое затронутое ядро; инвалидация сама ставит маркер конца реплики. Два теста нативного менеджера и три теста очереди и буфера VAD прошли. Запоздалое подтверждение не восстановило отозванный маршрут, новое подтверждение разрешило следующий кадр. Это проверка встроенного ядра, не измерение сетевого или акустического окончания реплики.
Windows, база `2a0a95f`: исправлен повторный `set_transmit direct`. Тест `transmit_mode_invalidates_frames_only_on_detector_change` прошёл через встроенное ядро: повтор direct сохранил допуск кадра, смена direct/VAD в обе стороны отозвала старый допуск. Сеть и физические устройства в этом тесте не использовались.
Windows, `0e6bfb7`: завершена сверка `voice.transmit_modes` с настройками установленного TS6. Пять адресных тестов ядра прошли на PCM. Проверены открытие по речи, порог громкости, гибридный режим, смена детектора и сброс накопленных кадров. Это не измерение задержки PTT по сети и не проверка на официальном клиенте.
Windows, база `f1e7d8d`: исправлен выбор задержки отпускания PTT в Audio. Значение 500 мс сохраняется при отключении и после двух перезапусков; 250 мс отклоняется без изменения настроек. Отключение и смена профиля отменяют ожидающий таймер. Прошли четыре адресных теста; задержка слышимого звука у удалённого участника не измерялась.
Windows, база `afac6cf`: прошёл изолированный тест `talk_request_draft_rejects_invalid_length_and_replaced_session`. Форма отклонила сообщение из 51 символа и не отправила допустимый черновик после замены сессии вкладки. Живой прогон переподключения не принят: сервер вернул `ClientIsFlooding`. Стенд остановлен; успешные проверки заявки, выдачи и отзыва из предыдущих прогонов остаются отдельными результатами.
Windows, база `20a36d0`: после получения отзыва заявки действие «Дать слово» проверяет актуальные ID, UID, канал и наличие запроса. Тест `talk_request_form_and_withdrawal_reach_peer` на beta14 прошёл: старое действие вернуло `target_changed`, в обоих списках право слова осталось выключенным. Отзыв после отправки команды и серверный отказ по правам в этом прогоне не проверялись.
Windows, база `2780adc`: поле сообщения в заявке на слово теперь необязательное. Живой тест `talk_request_form_and_withdrawal_reach_peer` прошёл на beta14 в канале с порогом 50: обе сессии увидели пустую заявку и её отзыв, затем заявку с текстом, выдачу и снятие права слова. Физическая клавиша, отказ в правах и переподключение во время выдачи не проверялись.
Windows, база `3daa2fd`: живой тест `away_message_reaches_both_loopback_sessions` прошёл с переподключением первой вкладки во время ввода. Обе копии списка участников показали новую сессию онлайн и подтверждённое сообщение у второй. Устаревшая цель показана как ошибка; рассылка остальным не прерывается. Публикация предыдущего коммита не прошла аутентификацию origin.
2026-11-27, Windows, база `220119e`: исправлена рассылка статуса «Отойти с сообщением» из одной формы по сессиям, подключённым на момент вызова. Тест `away_message_reaches_both_loopback_sessions` прошёл на закрытом TS6 beta14: обе вкладки увидели у обоих участников online после отмены и одинаковое away-сообщение после подтверждения. Проверялось событие горячей клавиши, не физический аккорд; стенд остановлен.
2026-11-27, Windows, база `4dd514e`: список запросов слова сортируется от новых к старым, как в установленном TS6. Горячая клавиша выбирает самую раннюю действующую заявку другого участника своего канала. Адресный тест прошёл, включая отмену заявки и отсутствие текущего канала. Выдача прав на живом сервере в этом прогоне не проверялась.
2026-11-27, Windows, база `764e3dc`: Alt+щелчок по регулятору собеседника возвращает 0 дБ, сохраняя заглушение. Тест `speaker_gain_drag_cancel_and_reset` прошёл в отрисованном окне, включая отпускание Alt до кнопки мыши. Расширенная проверка на живом собеседнике остаётся открытой.
2026-11-27, Windows, база `49b9ce5`: диалог локальной громкости получил ползунок со шкалой TS6. Тест отрисованного окна проверил перетаскивание, отмену, повторное открытие и сброс на 0 дБ со снятием заглушения после подтверждения. Проверены все 421 значения шкалы; три адресных теста прошли. Подключённый собеседник и физический выход не использовались.
2026-11-27, Windows, база `abdcbf1`: при загрузке локальной громкости ошибочный UID больше не блокирует применение корректных записей. Хранилище сообщает о пропуске и не переписывает файл при чтении. Прошли пять тестов хранилища и два теста ядра, включая повторное использование числового ID и смешивание декодированного звука двух участников. Экранный регулятор и физический выход не проверялись.
2026-11-27, Windows, база `373bd3d`: возврат на вкладку с уже действующим разрешением на захват не прерывает передачу при включённом автопереключении. Три теста прошли со встроенными ядрами: передача владения, восстановление прежнего владельца и отказ устаревшему ответу. Состояния подключения моделировались, физический микрофон и два живых сервера не проверялись.
2026-11-27, Windows, база `a215ceb`: выбор файлового протокола использует полное объявление возможностей; текст файловой диагностики по-прежнему ограничен 1024 символами. Новое initserver сбрасывает прежние свойства сервера, частичное обновление сохраняет отсутствующие поля. Прошли шесть тестов ядра. Живая проверка двух вкладок и владельца микрофона не входила в этот прогон.
2026-11-27, Windows, база `ab3508c`: проверен `preload:openLogs` на странице сведений об установке. При отсутствии logs показано объяснение без кнопки, при наличии Проводник подтвердил точный каталог временного профиля. Тест about_workflows подтвердил отказ прямого вызова в изолированном режиме. Содержимое журналов не читалось, мобильный экспорт не проверялся.
2026-11-27, Windows, база `4fb47fb`: для каждого установленного пакета тем в Appearance доступна его папка. Проводник подтвердил каталог пакета и общий каталог extensions по отдельности. В изолированном режиме обе операции получили os_actions_disabled; адресный тест выбора, перезапуска и удаления темы прошёл. Мобильное открытие не проверялось.
2026-11-27, Windows, база `bab7c93`: добавлены шесть расширенных настроек звука для переноса и исключения в канал, серверных групп и отказа в правах. В старых профилях прежний выбор действует до изменения отдельного события. Прошли 15 адресных тестов; UI Automation обнаружил все шесть элементов выбора в запущенном приложении. PCM проверен на изолированном выходе, физическое воспроизведение не проверялось. Для предупреждения о речи при выключенном микрофоне по-прежнему нет проверки с настоящим источником речи.
2026-11-27, Windows, база `2b176cc`: исправлены исходные каналы при групповом входе клиентов и уведомления о переходах между подписанными и неподписанными каналами. Прошли семь тестов событий и снимков ядра и пять тестов нативного обработчика. Проверены журнал и выбор WAV по событиям; живой сервер, физическое воспроизведение и кнопки прослушивания не проверялись.
2026-11-27, Windows: после базы `582fe2d` исправлено отображение связанных закладок в Details. Адресный тест `reattached_identity_details_keep_nondefault_uid_and_its_bookmarks` прошёл: вложенная закладка без UID следует за текущей идентичностью по умолчанию без изменения записи. SHA-256 эталонного TS6 и смещения записаны в FEATURE_COMPATIBILITY.md. Эталон повторяет подключение при достижении требуемого уровня; для TeamsPeach этот переход остаётся непроверенным.
Windows, feature:identity.security_level_improve: структурированный отказ connect_failed с required_security_level показывает действие для UID неудачной попытки. Переход открывает Details этой идентичности и подставляет требуемый уровень; улучшение и повторное подключение не запускаются автоматически. Три адресных теста прошли, включая отказ уровня 31 для недефолтного UID, отклонение устаревшего действия после перезапуска вкладки и изоляцию старой отмены поиска. Проверка перехода использовала событие отказа в тестовом runtime; живой сервер с повышенным порогом в этом прогоне не использовался.
На `4ca8678` выполнен также живой прогон: изолированный TS6 beta14 подтвердил через `serverinfo` требуемый уровень 31; при тесте Query был выключен, сервер слушал только loopback. Windows-клиент подключался недефолтной идентичностью уровня 9. После отказа кнопка открыла в настройках именно её с целью 31. Состав публичного хранилища, уровень и UID по умолчанию остались прежними. Тестовый профиль удалён, стенд завершился с кодом 0. Поиск до уровня 31 и успешное переподключение не проверялись.
Windows, feature:onboarding.offline: проверены пустой каталог и ранее инициализированный профиль без идентичностей. В обоих случаях выбор светлой темы дошёл до окна Slint и сохранился с тем же UID после перезапуска. Принудительная ошибка записи настроек оставила форму открытой и хранилище идентичностей пустым. Повторная отправка после устранения ошибки создала единственную идентичность. Два адресных теста прошли с выключенными сетью и физическим аудио.
Windows, preload:onIdentitiesChanged: в тесте reattached_identity_details_keep_nondefault_uid_and_its_bookmarks новая привязка окна сохранила выбранный недефолтный UID при одинаковых именах двух идентичностей. В Details показана связанная с ним закладка; изменение ника затронуло только выбранный UID. При выборе другой идентичности чужая закладка не показывалась. Прошли оба теста смены окна; работа выполнялась на временных профилях без сети.
Windows, preload:onIdentityProgress: тест old_cancel_cannot_stop_or_relabel_a_new_identity_search прошёл в нативном окне с одним временным UID. После отмены поиска с целью 99 начат поиск с целью 100. Старая команда отмены не остановила второй поиск: его счётчик продолжил расти, а отображаемый уровень и цель относились к новой задаче. Отмена из текущего окна завершила работу, сохранённая позиция совпала с итоговым результатом. Сеть и физические устройства не использовались.
Windows, preload:exportIdentity: проверена отмена на обоих этапах в отдельном временном профиле. После Cancel в предупреждении о приватном ключе системный Save не открылся. В двух отдельных диалогах Save введены путь существующего файла и путь нового INI; после Cancel содержимое существующего файла и состав каталога не изменились. Успешный перенос и совпадение UID проверены ранее. Тестовое окно закрыто, профиль и каталог удалены.
Windows, preload:importIdentity: системный диалог выбора INI проверен на новой идентичности, повторном импорте и повреждённом файле. Окно показало «добавлено 1, уже в профиле 0», затем «0, 1»; повреждённый INI дал видимую ошибку, публичные данные и UID по умолчанию не изменились. Два теста ядра прошли: дубликаты не занимают места при лимите 256, пакет с лишним новым UID не записывается частично. Оба временных профиля и тестовые INI удалены.
Windows, identity-action:export/import: в двух временных профилях проверен перенос через настоящие системные диалоги. После предупреждения о приватном ключе исходный клиент сохранил INI; второй клиент импортировал его и после перезапуска вернул оба публичных UID с прежним UID по умолчанию. Ключи в вывод не попадали; оба профиля и INI удалены. Пять адресных тестов прошли, включая ошибку после частичной записи при замене старой копии. Desktop экспортирует из памяти через закрытый временный файл в выбранном каталоге. Мобильные провайдеры и восстановление после отключения питания не проверялись.
Windows, identity-action:delete: в окне Slint удалена одна из двух тестовых идентичностей с одинаковым именем после подтверждения точного UID. Выбор удалённого UID сброшен; окно показало оставшуюся идентичность, изменение её ника сохранилось при полном перезапуске. После перезапуска в хранилище остался только исходный UID по умолчанию. Два адресных теста прошли, включая проверку общего профиля двух вкладок. Отказ удаления используемого UID покрыт отдельной проверкой pc5232-identity-cancel-02.
Windows, локальный профиль: тест offline_profile_is_shared_by_tabs_but_not_by_detached_editors прошёл через форму первого запуска и Details при двух открытых вкладках. До создания профиля попытка открыть соединение отклонена. Обе вкладки показали изменённый ник, оба ядра вернули его и один UID через profile_get. После смены окна старый редактор не изменил профиль и не получил новое значение; после полного перезапуска сохранились ник, UID и единственная идентичность. Подключённый к серверу rename и отказ сервера этим тестом не проверялись.
Windows, preload:onCoreStatus: менеджер публикует Starting перед созданием нового worker при перезапуске. Вкладка показывает состояние неработающего ядра и не предлагает подключение до Ready. Три адресных теста прошли. На уровне менеджера занятие временного слота дало Failed и Disconnected, соседняя вкладка ответила на profile_get, снятие блокировки позволило восстановить Ready. В отдельном тесте окна Slint выбор со старым SessionKey после перезапуска дал target_changed, цикл приложения продолжил работать, соседняя вкладка выбиралась и отвечала. Быстрое промежуточное Starting не измерялось как отдельный отрисованный кадр.
Windows, голосовое ядро: собственное событие ClientChannel с изменившимся каналом отзывает очередь и разрешение отправки ранее захваченных кадров, после чего снимок публикуется без обычной задержки. Три адресных теста teamspeach-core прошли: проверены собственный и чужой перенос, повторное уведомление без смены канала, блокировка отправки со старым разрешением и приём кадра с новым. Физический микрофон и сетевой переход не проверялись.
Windows: contact_sort_uses_saved_mode_after_two_restarts проверил сортировку из настройки Chats. В негруппированном списке локальный псевдоним Alpha (офлайн) был выше Zulu (онлайн) при алфавитном порядке. После отключения настройки и двух перезапусков первым отображался онлайн-контакт Zulu. Присутствие взято из тестового снимка сервера; облачные сервисы не использовались. Вместе с проверкой независимого раскрытия групп прошли два теста.
Windows: настройки показа и группировки офлайн-контактов проверены через элементы Slint на трёх запусках. Отключение показа скрывает контакты без непрочитанных сообщений и сам элемент группировки, не сбрасывая выбор. При повторном включении показан локальный псевдоним, затем отдельная офлайн-группа при включении группировки. Три адресных теста прошли, включая исключение для непрочитанных сообщений.
Windows: свёрнутая группа контактов показывает суммарное число непрочитанных личных сообщений. В тесте contact_disclosures_restore_online_and_offline_independently проверено доступное имя заголовка Online Contacts (1) и сохранение непрочитанного у контакта после выхода с сервера. Использовались события тестового сервера без сети и аудио.
Windows: список контактов суммирует непрочитанные личные сообщения по UID на всех серверных вкладках из состояния уведомлений. Три адресных теста прошли: контакт с непрочитанным сообщением виден после ухода с сервера даже без открытой переписки; чтение на одном сервере не снимает счётчик другого. Проверка использовала тестовые события без сети и аудио.
Windows, контакты: заголовки онлайн- и офлайн-групп независимо сохраняют состояние раскрытия. В тесте Slint два контакта распределены по снимку тестового сервера; нажатия и два перезапуска сохранили видимость правильной группы и активную вкладку, без запуска аудио. Также прошёл интеграционный сценарий добавления, переименования, отклонения ошибочных правок и удаления локального контакта. Облачное присутствие не использовалось.
Windows: заголовок списка закладок сохраняет savedServersCollapsed. В окне Slint проверены сворачивание указателем, отсутствие строк после перезапуска и повторное открытие с сохранённой закладкой во всех сочетаниях EN/RU и светлой/тёмной темы. Выбранная вкладка и владелец ввода не менялись. Два теста боковой панели прошли.
Windows: ширины sidebarWidth и serverPaneWidth теперь сохраняются целыми числами; старые значения в виде 280.0/470.0 также восстанавливаются. Перетаскивание серверной панели ограничено максимумом хранилища (1600 px). Тест desktop_pane_drags_remain_visible_and_persist_across_restart прошёл для EN/RU и тёмной/светлой темы: проверены геометрия после указателя и перезапуска, сужение с 2600 до 1024 px без потери сохранённой ширины и неизменность активной вкладки и владельца ввода. Профили были отключены от серверов.
Сверка themes.extensions с TS6 5232: подтверждены ключ идентификатор//вариант, сброс отсутствующего выбора, кэш 300 секунд и сортировка вариантов по имени. Сортировка исправлена в нативном списке; тест Slint с обратным порядком в манифесте прошёл на Windows. Ограничение Slint поддерживаемыми токенами CSS сохраняется.
Кодеки на Windows: прошли `legacy_codecs_neither_select_an_encoder_nor_enter_the_mix` и `encode_decode_mix_roundtrip_both_codecs`. Для Speex NB/WB/UWB и CELT Mono проверены отсутствие выбранного TX-кодека и отклонение входящих пакетов с указанием исходного кодека, без активных говорящих и без PCM в микшере. Сброс приёмника позволяет снова сообщить об ошибке того же client ID. Это модульная проверка, не вход в legacy-канал и не измерение исходящих сетевых пакетов; `current-contract:speex-celt` остаётся открытым.
Windows: проверен импорт ZIP темы через реальный системный диалог. Вариант появился в списке и остался выбранным после Reload, хеш установленного CSS совпал с исходным. Неизвестный селектор показан как проигнорированный; второй пакет с внешним @import отклонён до установки. Два теста ядра обработки тем в teamspeach-native подтвердили отказ для внешних ресурсов и выходящих за каталог путей. Это результат Windows для поддерживаемого подмножества, не совместимость с произвольным CSS.
Windows, список тем: после Reload в работающем клиенте видны название пакета, два его варианта и ошибка соседнего некорректного пакета. Ссылки показаны один раз на пакет. Адресный тест Slint подтвердил предпросмотр без изменения userStyle, сохранение оформления при выборе и возврат стандартной темы при удалении. Проверка не охватывает системный диалог импорта ZIP.
Windows: проверен `preload:openThemeLink`. Временный пакет темы объявлял домашнюю страницу, документацию, репозиторий и почту. У каждой кнопки Windows UI Automation наблюдала диалог с соответствующим полным адресом и отменила переход, включая доверенный домен и mailto. Во втором профиле без homepage и docsUrl обе кнопки отсутствовали. Внешнее приложение для проверки не запускалось.
Проверка ссылок из настроек: в двух временных профилях один и тот же URL репозитория темы получил предупреждение о вредоносном домене при наличии домена в локальном кэше и обычное подтверждение при отсутствии списка. Точный URL остался виден; в обоих диалогах нажата отмена. Восемь тестов политики privacy прошли, включая отклонение некорректных DNS-имён и сохранение обычного подтверждения для IPv4/IPv6. Внешнюю страницу не открывали.
Windows, Privacy → Manage trusted sites: добавлен статус локального списка фишинговых доменов. В двух временных профилях при недоступном обновлении Windows UI Automation показала отдельно отсутствие списка и использование сохранённой копии. Восемь тестов сервиса privacy прошли, включая успешное обновление и сохранение предыдущего списка при ошибке. Статус источника не является вердиктом безопасности для отдельной ссылки.
Темы Windows: после удаления выбранного пакета Reload теперь выводит его имя и сообщает о возврате стандартной темы. Проверено в отдельном окне через UI Automation. Тест `selected_variant_survives_restart_and_restores_stock_on_removal` прошёл: после перезапуска сохранились цвет отрисованных пикселей, семейство Consolas и размер 19 px; после удаления пакета восстановлены стандартные значения, исходный CSS не изменился. Это не проверка импорта ZIP или загрузки шрифтов из пакета.
Локальный `main` синхронизирован с `origin/main` (`05e8d34`); `feature/mobile-port` обновлена до `da1f867`, без слияния в desktop. Для ПК выборочно перенесены обработка ошибок команды без остановки входящего звука и различение просроченного кадра и отзыва разрешения на микрофон. Изменения нативного аудиотракта не требуют отката обновлённых зависимостей.
После переноса четырёх адресных проверок `teamspeach-native` на `x86_64-pc-windows-msvc` (`--no-default-features`, цели `--lib --test audio_binding --test connections`) прошли все четыре: отклонение отдельного кадра, остановка только отозванного источника, отсутствие захвата без разрешения и сохранение входящего звука при нетерминальной ошибке. Физический микрофон и сервер не использовались.
Исправлена гонка ручного выхода с `DisconnectedTemporarily` в `core/src/session.rs`: вместо автопереподключения с потерей ID запроса ядро закрывает транспорт и отвечает `clean: false`. Windows-тест `server_stop_reconnects_only_without_an_explicit_disconnect` прошёл: `Serverstop` без запроса оставляет reconnect, после запроса выдаёт один ответ и состояние `disconnected`. В сетевой проверке исправленного stdio-ядра использованы временные профили, вход и выход звука отключены. `10.10.10.160:9987` и `voice.teamspeak.com:9987` прошли `connecting → connected → disconnecting → disconnected`, процессы завершились с кодом 0. Результат `disconnect`: соответственно `clean: true` и `clean: false`; причина отсутствия подтверждения на публичном сервере не установлена. Серверы не останавливались, голос не проверялся.
По последующему указанию владельца обновление библиотек и инструментов ПК предшествует исправлению ядра. На `main` обновлены Rust 1.100.0, Slint 1.19.1/Skia m157.2, привязки WebRTC 0.4.2/0.3.55 и Sonora 0.3.0 с переносом локальных патчей. На Windows `cargo test --locked -p teamspeach-core -p teamspeach-denoise --lib`: ядро 207 passed / 1 ignored, DSP 18 passed. Это не приёмка окна или связи. Установленный клиент и профиль не изменялись.
`xtask deps` и `xtask build --target x86_64-pc-windows-msvc` завершились успешно: Windows release EXE со стандартными Skia и WebRTC, без test-harness. Отдельно прошёл `cargo check --locked -p teamspeach-native --no-default-features` для Windows x64. Это новая проверка сборки, но не ручная приёмка голоса или установленной версии.
## Проверка паритета ПК с TeamSpeak 6.0.0.5232, 2026-11-26
- Актуальный визуальный эталон — **TeamSpeak 6.0.0.5232**; 6.0.0.5163 и его значения смещений —
исторический источник. [Карта эталона](evidence/official-parity/visual-source-map.md) содержит
SHA-256 обоих бандлов из четырёх манифестов, точные команды и пути reference/native/compare.
Снимки сделаны с общей синтетической сценой, не с аккаунта или пользовательского профиля.
- Dark/light × EN/RU, 1280×800: основной вид с чатом канала, личный чат, контекстное меню,
настройки Audio и Appearance. В каждом из двух прогонов 20/20 нативных сцен отрисованы;
строгий результат каждого — **0 passed / 20 failed / 0 blocked** (`target/evidence/compare-5232-pc-02/parity-report.json`
и `target/evidence/compare-5232-pc-03/parity-report.json`). Исключения продукта (свой бренд,
отсутствие myTeamSpeak/homebase и Remote Apps) не маскируются при сравнении всего кадра.
- Отдельный `target/evidence/pc5232-functional-04/result.json`: 8 проверок и 28 снимков, включая
12 разделов настроек, EN/RU, dark/light, ширины 390/800/1280, PTT при фокусе текста, безопасный
rich chat, отказ захвата и перезапуск временного профиля. Без сети, действий ОС и реальных устройств.
- Уведомления и настройки передачи файлов: на Windows прошли 2 теста ядра `disconnect_tests`,
49 выбранных библиотечных тестов `teamspeach-native` и 4 интеграционных теста
`notification_preferences`. Старый звуковой параметр `group_status` сохранён, переключатель
категории Status работает независимо. `target/evidence/pc5232-notification-03/result.json`:
успешный изолированный прогон, 32 снимка. Global Private Chat, Global Group Chat, Incoming call
и Outgoing call остались недоступны после попыток активации указателем и через accessibility;
каждый снят отдельно. Сохранённые настройки и уже открытая отключённая вкладка не изменились,
активных сеансов и физического аудио не было.
- Проверку по критерию индивидуально доступного Listen и звуковой политики прошёл 51 из 58 случаев:
у шести нет своего варианта Listen, для речи при выключенном микрофоне нет реального речевого
триггера. Локальный журнал на тестовых событиях принял 501 событие без звука, сохранил 500 и
показал последние 200. Переключение и закрытие вкладок не смешивают сеансы; это не серверный
`Server Log`. Для файлов проверены шаговые кнопки, общий с ручным вводом шаг и границы,
сохранение настроек после повторного открытия и отклонение недопустимых значений. Это не
сквозная приёмка файловых операций, установленной сборки или официального клиента; статусы
718 требований в `native/compatibility.json` не менялись.
- Последующая Windows release-сборка (`xtask build`, Skia + WebRTC) успешно слинкована; запуск `teamspeach.exe --version` вернул `TeamsPeach 0.1.7 (Rust + Slint)`. Это сборка из рабочего дерева, не установка или приёмка на физической гарнитуре.
- В `target/evidence/pc5232-identity-cancel-02/result.json` проверены создание, выбор по UID при одинаковых именах, сохранение ключа, уровня, закладки и ника после перезапуска, отказ удаления используемой идентичности и отмена экспорта из меню указателем и клавиатурой. Отмена активного поиска подтверждена за 172 мс и за 180 мс после перезапуска; второй поиск продолжился с контрольной точки первого. Отдельно прошли `about_workflows` и `bookmark_contact_workflows` (3 теста). Это не подтверждение экспорта через системный диалог, изменения ника на сервере или визуального паритета.
- Административные формы: 9 адресных Windows-тестов (`admin_editor_`, `server_edit_`, `channel_admin_tests`) прошли. `channel_admin_qa` с отдельным beta14 подтвердил создание временного канала, смену темы без изменения имени/качества кодека, отказ по неверному качеству и старому поколению, чтение обычного и семейного лимита. `channel_flag_maxfamilyclients_inherited` у корневого канала не прислан; перенос под родителя гостю запрещён (TS 2568). Канал исчез после выхода; сервер подтвердил отключение. Рабочий сервер не менялся.
- Отдельно два CLI-клиента ядра через изолированный официальный beta 14 одновременно передали
по 100 кадров с тонами 500/900 Гц: 99/101 и 100/101 декодированных кадров совпали по спектру и
идентификатору отправителя; оба клиента отключились штатно. Реальных устройств и официального клиента
в этой проверке не было.
- `cargo run --locked -p teamspeach-core --example duplex_qa` с QA-ядром и изолированным beta 14 на
localhost: A→B и B→A по 45 кадров, начало через 14 и 21 мс соответственно, 864 мс одновременной
передачи. Проверены отпускание PTT, mute, отказ после отключения и новый сеанс при повторном
подключении; 3/3 штатных выхода. Отдельно прошли 112 тестов `media::audio` на Windows, в том числе
задержка захвата более 200 мс при активном воспроизведении и замена разрешения на захват. Эти
воспроизводимые тесты подтверждают исправление пути `Audio worker stalled` в коде; сценарий на
реальном WASAPI-устройстве независимо не наблюдался, готовность сборки и приёмка не подтверждены.
- Два CLI-клиента прошли `duplex_qa -- --whisper` на закрытом beta14; 15 тестов ядра с фильтром `whisper` прошли. Проверены разрешение и запрет приёма, восстановление приёма и отбрасывание устаревшего кадра без передачи в обычный канал. Стенд остановлен. Проверка не включает окно настроек, системный ввод или физическое аудио.
- Чат на изолированном beta14: два CLI-клиента получили подтверждения и точный текст для текущего канала и личного сообщения с проверкой ID и серверного UID. Несовпадающий UID дал `target_changed`, четыре недопустимых набора аргументов дали `bad_request`; общесерверный текст гостю запрещён (TS 2568). Оба клиента отключились штатно. Отдельный тест Slint `concurrent_tabs_keep_separate_drafts_and_pending_sends` подтвердил независимость черновиков двух вкладок при одинаковой истории и ответах в обратном порядке. Это не проверка установленного клиента и не доказательство доставки в произвольный канал.
- После перехода обоих CLI-клиентов из лобби во временный канал beta14 ядро отклонило `send_text` с прежним `expected_channel_id` (`target_changed`). Сообщение с текущим ID сервер подтвердил, второй клиент получил только контрольный текст. Оба клиента отключились штатно, стенд остановлен. Прошли два теста валидации протокола и два теста нативного клиента на устаревший канал и независимость черновиков. Проверка относится к известному ядру каналу перед отправкой, не к доставке в произвольный канал.
- При пересечении загрузки последней страницы и записи входящего сообщения окно не добавляет повторно строку, которая уже вошла в страницу. На Windows прошли `latest_page_and_live_append_show_each_record_once`, `restart_pagination_and_scope_isolation` (641 запись, два повторных открытия) и `interrupted_and_damaged_lines_keep_indices`.
- `preload:chatHistoryPage`: в Slint кнопка «Ранее» открыла записи 5–104, затем 0–4; «Последние» вернула 105–204. Проверены индекс и текст каждой записи, личная запись не попала в историю канала. Тест `older_and_latest_buttons_page_only_the_selected_history` прошёл на Windows: файлы истории и приложение реальные, список участников тестовый, без сети и запуска аудиоустройств.
- `preload:chatHistoryList` и `preload:chatHistorySetOpen`: закрытие фоновой личной вкладки оставило выбранный чат и его черновик на месте. После повторного открытия и перезапуска runtime сохранились подпись собеседника и его прежнее сообщение. Разговоры другой идентичности и другого сервера не появились. Девять оконных тестов Slint прошли вместе на Windows; каждый использовал отдельный процесс для платформы Slint. Профили временные, список участников тестовый, без сети и физических аудиоустройств.
- `preload:chatHistoryAppend`: тест `private_history_tabs_restore_labels_and_preserve_the_selected_draft` прошёл на Windows с входящими личными сообщениями и эхом собственной отправки, поданными как события `text`. После двух перезапусков runtime проверены точный текст, UID автора, признак собственной отправки и отсутствие дубликатов. Другие разговоры, идентичности и серверы сохранили только свои записи. События синтетические; запись и повторное чтение выполнены реальным хранилищем.
- Запись: `recording_finalized` с `ok:false` не разрешает экспорт. Панель показывает ошибку, скрывает «Показать» и позволяет явно начать новую запись. Проверено, что существующий файл назначения и неполный файл в staging не меняются. На Windows прошли 4 адресных теста нативного клиента и 4 теста ядра: пауза/продолжение, длина WAV, waveform и ошибка записи. Полный сценарий через системный выбор каталога и установленный UI не проверялся.
- На изолированном beta14 проверены команды ядра `recording_start` (режим 3), pause/resume, info/status, waveform и stop с ожиданием `recording_finalized`. На паузе счётчик остался на 42 240 кадрах; в итоговой мастер-дорожке 84 480 кадров. Обнаружено по 25 блоков по 20 мс на 650 и 1300 Гц до и после паузы; тон 1000 Гц, поданный на паузе, отсутствовал. Сумма PCM по дорожкам, `session.json` и событие завершения совпали: 324 480 байт без заголовков WAV. Сервер подтвердил отключение. Это проверка CLI и файлов, не системного выбора каталога или физического микрофона.
- Доступ к каталогу записи теперь сохраняется после ответа `recording_stop`: его освобождает `recording_finalized` для соответствующего пути либо подтверждённая остановка ядра. На Windows семь тестов прошли, включая смену каталога после Stop, позднее событие другой записи и перезапуск worker. Это проверка lifetime разрешений; системные разрешения Android/iOS не проверялись.
- Панель записи показывает «Завершение записи» между `Stop` и результатом writer. Тест `failed_recording_finalization_does_not_authorize_export` прошёл на Windows: проверены кнопки паузы и продолжения, отсутствие действий записи и экспорта при финализации и игнорирование позднего ответа `recording_info`. Проверка использует модель панели, не системный диалог выбора каталога.
- При экспорте нескольких файлов записи все замены подтверждаются до первого копирования. Финализация запускает экспорт в задаче приложения, чтобы цикл событий мог показать диалог и обработать ответ. На Windows прошли три адресных теста, включая `cancel_second_recording_overwrite_keeps_all_destination_files`: после подтверждения первого файла и отмены второго исходные и целевые файлы не изменились. Это не гарантия группового отката при ошибке ввода-вывода во время копирования.
- `finalized_recording_exports_wav_and_manifest_byte_for_byte` прошёл на Windows с `--ignored`: штатный рекордер записал пять блоков по 960 кадров; до уведомления о финализации каталог экспорта отсутствовал. После него Windows-адаптер опубликовал `00 master.wav` и `session.json`, оба побайтно совпали с оригиналами. В WAV 9 600 байт PCM и 44 байта заголовка. Профиль и каталоги временные, сеть отключена; системный выбор каталога и физическое аудио не проверялись.
- При переполнении очереди WAV блок сохраняется тишиной; теперь соответствующий пик `recording_waveform` также нулевой. На Windows прошли `slow_disk_drops_whole_ticks_truthfully_and_keeps_alignment` (сверка каждого пика с PCM итогового WAV) и `waveform_reports_peaks_per_tick` (обычный сигнал). Это проверка ядра без устройств.
- Панель записи Rust/Slint показывает последние 64 блока формы сигнала отдельно для каждой дорожки. Канонический путь staging берётся из разрешения, переданного ядру; чужая или повторная финализация не разрешает экспорт текущей записи. На Windows шесть адресных тестов `teamspeach-native` прошли с `test-harness`: выравнивание пиков, поздний ответ после закрытия панели, пиксели двух дорожек Slint при обновлении и удалении, отказ финализации, отмена замены и побайтный экспорт WAV/манифеста. Эталон inline-дорожек микшера: 5232 `main.js` (байты 4465339, 4469377, 4474782), `main.css` (652446). Это не попиксельное сравнение всего микшера; физические устройства и системный диалог в этих тестах не использовались.
- Серверный `MATRIXCHAT`: в обычном серверном чате показано пояснение о неподдерживаемых комнатах при `server.features.chat=true`. Windows `smoke::chat::` (4 теста) проверил появление и исчезновение сообщения при смене объявления, доступность ввода и отсутствие диалога входа. Контракты `current-contract:matrix-not-account` и `feature:chat.server_matrix` проверены только в части явного ограничения. Сеанс Matrix не устанавливался.
- `current-contract:profile-import`: на Windows прошли 8 адресных сервисных проверок и 3 проверки диалогов, включая отмену пароля импортированной закладки на первом запуске и после двух перезапусков. Устранено повторное открытие отменённого запроса из запоздалого снимка. Проверены неизменность маркера пароля, UID, истории и порядка закладок; профиль владельца не использовался.
- Проверены лимиты файлов: 4 адресных Windows-теста нативного планировщика подтвердили распределение между двумя вкладками после перезапуска сервиса и сохранение прежних настроек при отказе. На уровне ядра `download_rate_limit_paces_real_bytes_and_can_be_disabled` и `upload_sends_exact_bytes_and_sees_server_close` проверили реальные байты через TCP loopback при 1 МиБ/с. Для upload приёмник проверяет пять блоков по 64 КиБ, порог 240 мс, целостность и закрытие пишущей стороны. `transfer_slots_are_counted_per_channel_and_direction` проверил независимость очередей каналов и направлений. Одновременные сетевые передачи на двух серверных вкладках не выполнялись.
- Автоподключение перебирает закладки в порядке боковой панели, включая вложенные папки, вместо исходного порядка массива `savedServers`. Семь тестов `services::bookmarks::tests::` прошли на Windows, включая перестановку папки перед ранее созданной корневой закладкой. Проверены порядок обхода и сборка вызывающего runtime; сетевой автозапуск двух серверов в этом тесте не выполнялся.
- Отдельная проверка на `76795c6`: запущен собранный Windows `teamspeach.exe` с временным профилем и двумя защищёнными закладками на loopback. Через Windows UI Automation в основном окне `TeamsPeach` отменены запросы `QA Nested`, затем `QA Outside`, хотя `savedServers` содержал обратный порядок. За 600 мс после второй отмены запрос не повторился. `bookmark_sidebar_and_local_contact_reopen_without_network` отдельно подтвердил порядок после перезапуска, копию сразу после оригинала, отмену/подтверждение удаления поддерева и отсутствие запуска аудио в изолированном runtime. Не проверялась успешная авторизация на двух серверах.
- Сопоставлены `myts.account_cloud`, `remote_apps`, `privacy.analytics` и `dev.options` с установленным JS-бандлом TS6 5232 (SHA-256 совпал с visual source map). В обычном Windows-окне открыты Settings → Privacy → More Information: объяснение диагностики доступно, режима сбора выбрать нельзя. У Account, Remote Apps и Developer Options нет категории. Это проверка интерфейса; не измерялись сетевые запросы. UI Automation в этой сборке не предоставила Invoke для кнопки Privacy; переход проверен указателем.
- Нативная проверка `whisper-settings`: `target/evidence/pc5232-whisper-settings-03/result.json` и 5 кадров. Подтверждены `deny_all`, сохранение списков после перезапуска runtime, предупреждения для повреждённого файла и файла новой версии, отсутствие запуска аудио. `whisper_list_workflows` проверил отмену и подтверждение удаления, сохранность несвязанных сочетаний и восстановление при ошибке записи. В About возврат фокуса к лицензии и выпуску проверен повторной активацией через Enter. Эти проверки не подтверждают визуальное совпадение с официальным клиентом.
- `preload:setWhisperReceiveMode`: `target/evidence/pc5232-whisper-settings-05/result.json` подтверждает выбор `allow_all`, затем `deny_all` указателем в Slint. Для обоих режимов показанное значение совпало с `whisper.json`, после перезапуска runtime сохранился `deny_all`. Отдельно `target/evidence/pc5232-identity-choice-01/result.json` прошёл с тем же исправленным компонентом выбора. Доставка звука проверялась отдельным CLI-сценарием, не из этого окна.
- Профили горячих клавиш: адресный тест Slint и тест хранилища прошли на Windows. Создание второго профиля не меняет активный; имя длиннее 64 символов отклоняется. После подтверждённого удаления неактивного профиля редактор сразу показывает активный; его UUID, новое имя и локальная привязка F8 сохранились после перезапуска runtime. Системные сочетания не регистрировались.
- `preload:activateKeybindProfile`: при смене активного профиля удерживаемый PTT завершился без таймера; обычное отпускание в том же тесте сохранило настроенную задержку 500 мс. После активации старый F8 не срабатывал, новый F9 управлял push-to-mute, выбранный профиль сохранился после перезапуска runtime. Прошли 12 адресных тестов Windows с синтетическим вводом; физическая передача звука не проверялась.
- Точное совпадение: флажок Slint переключён через действие доступности. Локальный обработчик принимал Ctrl+F8 в обоих режимах, Ctrl+Shift+F8 только без точного совпадения; после перезапуска runtime настройка сохранилась. Два адресных теста прошли, включая ограничение числа вариантов регистрации. Системный backend Windows не регистрировал сочетания в этом сценарии; `preload:setKeybindExact` остаётся открытым.
- `current-contract:speex-celt` не закрыт: изолированный beta14 отклонил обе попытки создания временного канала с `channel_codec=0` (Speex Narrowband) и `3` (CELT Mono), TS 1538 `ParameterInvalid`. Вход в такой канал и отсутствие TX не проверены; гостевой клиент отключился штатно, стенд остановлен.
- Windows, вкладки: 5 адресных тестов библиотеки и 7 интеграционных из `connections` и `audio_binding` прошли. Восемь отдельных ядер созданы менеджером без сети; в окне Slint вкладки `c1`–`c8` выбирались указателем без смены владельца ввода и без запуска аудио. Девятый запрос отклонён с видимой ошибкой. Отказ закрыть последнюю вкладку не снимает PTT/whisper; при принятом закрытии или перезапуске очередь аудио старой сессии отзывается. Сетевой диалог, физический микрофон и подключение к официальному клиенту не проверялись.
- Два дополнительных теста менеджера: между сменой владельца ввода A→B и обработкой подтверждения B нет активного разрешения на захват, старая эпоха A недействительна, просмотр C не меняет владельца; после подтверждения кадр принимает только B. При повторном использовании слота запоздавшие события закрытой вкладки не меняют подписку, новая вкладка отвечает на `profile_get`. Ядра и очереди реальные, сетевое состояние тестовое, физический ввод не запускался.
- При неудачном перезапуске worker состояние вкладки публикуется как `Failed` до ответа, а не как штатное `Stopped`. Проверено реальной блокировкой временного слота: соседнее ядро продолжило отвечать, после снятия блокировки повторный запуск вернул `Ready`. Это проверка менеджера, не сценарий перезапуска через установленный UI с незавершённым запросом.
- `preload:restartCore`: три адресных теста прошли. В окне Slint перезапуск через контекстное меню отключённой вкладки показал подтверждение с её именем. Менеджер отдельно отбросил задержанный ответ прежнего ядра после перезапуска; соседняя вкладка продолжала отвечать. Проверка была изолированной, без сети и физических устройств.
- На изолированном официальном beta 14 ядро получило только пустой S3-каталог в режиме чтения.
Отдельный PUT/list/GET напрямую в хранилище не доказывает передачу или изменение файлов через
TeamSpeak. Открыты визуальный паритет, положительные S3-операции через TeamSpeak, HTTPFT,
серверные Matrix/SFU, двусторонний голос с официальным клиентом и приёмка установленной версии
этой сборки. Эти результаты не меняют принятую ранее базу 0.1.7 и не заменяют проверки Android/iOS
на устройствах. [Подробности](../FEATURE_COMPATIBILITY.md#current-windows-account-free-checkpoint-2026-11-26).
## Принятая Windows-база и мобильная ветка
- Пользователь явно подтвердил в форме: **проверил подключение, вход в канал и голос в обе стороны, принимает установленную Windows 0.1.7 и разрешает baseline/push**. Desktop acceptance gate снят; это ручная приёмка владельца, не новый автоматический тест.
+2
View File
@@ -55,6 +55,8 @@ Remote URLs and `@import` are rejected, including escaped spellings; local refer
## Historical source observations
The installed 6.0.0.5232 bundle (SHA-256 in the visual source map) still resolves a variant by splitting its key at the first `//` (`getThemeForIdentifier`, byte 1165264), clears missing selections (`applyUserStyle`, 1164894), and caches installed metadata for 300 seconds unless forced (`refreshAvailableUserStyles`, 1165673). Its picker sorts variant names by JavaScript string order (getter following byte 4625402). The Windows Slint picker uses the same UTF-16 ordering; its rendered selection test includes variants declared in reverse order. The official client installs a stylesheet link, whereas the native client imports only supported values into Slint.
The installed TS6 6.0.0.5163 `html/client_ui/main.js` (SHA-256 `9d6bea2e…9b82c39`) supplied the original contract:
- `applyUserStyle` @1369504 inserted the selected stylesheet and reset missing selection to stock.
+2 -2
View File
@@ -15,8 +15,8 @@ path = "src/lib.rs"
# Native capture uses sonora AEC3, noise suppression and adaptive AGC2 together.
# The standalone noise-only behavioral reference is compiled only for Rust tests.
[dependencies]
sonora = "=0.2.0"
sonora.workspace = true
[dev-dependencies]
sonora-ns = "=0.2.0"
sonora-ns.workspace = true
+5 -1
View File
@@ -3,6 +3,9 @@
//! Sonora owns the split/filter/synthesis path. Never put another noise suppressor
//! or OS/WebRTC AEC in front of this processor. The caller supplies the actual
//! post-gain playout mix, aligned to the capture clock, before capture processing.
//! Both PCM boundaries use normalized `f32` in [-1, 1]. Sonora's `AudioBuffer`
//! handles conversion to and from FloatS16 internally; scaling by 32768 at the
//! wrapper boundary would double-convert and saturate ordinary microphone PCM.
//!
//! Sonora's integrated NS also enables its split-band high-pass filter. The test-only
//! noise-only reference does not; waveform equivalence to that wrapper is not promised.
@@ -24,6 +27,7 @@ pub struct CaptureSettings {
/// `None` disables NS; `Some(0..=3)` means Low / Moderate / High / Very High.
pub noise_suppression: Option<u8>,
/// Enables adaptive digital AGC2, not hardware microphone-volume control.
/// Uses Sonora's speech- and noise-aware gain and limiter, without fixed pre-gain.
pub automatic_gain_control: bool,
}
@@ -145,7 +149,7 @@ impl CaptureProcessor {
})
}
/// Analyze the actual post-gain playout mix; this never modifies the supplied PCM.
/// Analyze the actual, normalized post-gain playout PCM without modifying it.
///
/// `delay_ms` includes hardware delay, queued samples and resampler latency. Reject
/// out-of-range delay rather than silently continuing with Sonora's clamped estimate.
+182
View File
@@ -274,3 +274,185 @@ fn invalid_settings_never_construct_a_processor() {
}), Err(CaptureError::InvalidNoiseSuppressionLevel(actual)) if actual == level));
}
}
fn stage_combinations() -> impl Iterator<Item = CaptureSettings> {
[false, true].into_iter().flat_map(|echo_cancellation| {
[None, Some(0), Some(1), Some(2), Some(3)].into_iter().flat_map(move |noise_suppression| {
[false, true].into_iter().map(move |automatic_gain_control| CaptureSettings {
echo_cancellation,
noise_suppression,
automatic_gain_control,
})
})
})
}
#[test]
fn normalized_float_matches_integer_sonora_at_every_enabled_stage_boundary() {
// Sonora's mono i16 path widens samples directly to FloatS16. Use matching
// integer and normalized float inputs to detect missing or double scaling.
const PCM16_SCALE: f32 = 32768.0;
const DELAY_MS: i32 = 20;
let quantize = |sample: f32| (sample * PCM16_SCALE).round() as i16;
let normalize = |sample: i16| f32::from(sample) / PCM16_SCALE;
for settings in stage_combinations() {
let mut processor = CaptureProcessor::new(settings).unwrap();
let stream = StreamConfig::new(48_000, 1);
let mut integer = AudioProcessing::builder()
.config(configuration(settings).unwrap())
.capture_config(stream)
.render_config(stream)
.build();
let mut seed = 0x71ab_2309;
let mut render_history = [[0_i16; FRAME_SAMPLES]; 2];
let mut render_output = [0_i16; FRAME_SAMPLES];
let mut expected = [0_i16; FRAME_SAMPLES];
let mut output_energy = 0.0;
for frame in 0..120 {
let render = if frame < 90 { noise(&mut seed, 0.15).map(quantize) } else { [0; FRAME_SAMPLES] };
let delayed_render = &mut render_history[frame % 2];
let input = match frame {
0..=9 | 90..=119 => [0; FRAME_SAMPLES],
10..=39 => harmonic(frame, 0.002).map(quantize),
40..=69 => {
// A matching echo 20 ms later makes reverse scaling observable in capture.
let voice = harmonic(frame, 0.08);
std::array::from_fn(|index| quantize(voice[index] + 0.5 * normalize(delayed_render[index])))
}
70..=79 => std::array::from_fn(|index| if index % 2 == 0 { i16::MAX } else { i16::MIN }),
_ => [512; FRAME_SAMPLES],
};
*delayed_render = render;
let mut actual = input.map(normalize);
processor.process_render(&render.map(normalize), DELAY_MS).unwrap();
integer.set_stream_delay_ms(DELAY_MS).unwrap();
integer.process_render_i16(&render, &mut render_output).unwrap();
processor.process_capture(&mut actual).unwrap();
integer.process_capture_i16(&input, &mut expected).unwrap();
assert_normalized(&actual);
for (index, (&actual, &expected)) in actual.iter().zip(&expected).enumerate() {
// The integer result rounds and saturates at +32767, not +32768.
assert!(
(actual * PCM16_SCALE - f32::from(expected)).abs() <= 1.0,
"float/i16 scale mismatch: {settings:?}, frame {frame}, sample {index}: {actual} vs {expected}"
);
}
output_energy += energy(&actual);
}
assert!(output_energy > 0.001, "pipeline discarded the entire probe: {settings:?}");
}
}
#[test]
fn startup_and_sustained_silence_do_not_generate_audio_in_any_stage_combination() {
for settings in stage_combinations() {
let mut processor = CaptureProcessor::new(settings).unwrap();
// Cross the AGC VAD's 1.5 s reset period as well as startup.
for frame in 0..200 {
processor.process_render(&[0.0; FRAME_SAMPLES], 0).unwrap();
let mut silence = [0.0; FRAME_SAMPLES];
processor.process_capture(&mut silence).unwrap();
assert!(silence.iter().all(|&sample| sample == 0.0), "generated audio: {settings:?}, frame {frame}");
}
}
}
#[test]
fn agc_does_not_wind_up_in_silence_and_quiet_onset_does_not_clip() {
let settings = CaptureSettings { automatic_gain_control: true, ..BYPASS };
for silent_frames in [0, 1200] {
let mut processor = CaptureProcessor::new(settings).unwrap();
for frame in 0..silent_frames {
let mut silence = [0.0; FRAME_SAMPLES];
processor.process_capture(&mut silence).unwrap();
assert!(silence.iter().all(|&sample| sample == 0.0), "generated audio before onset: frame {frame}");
}
let mut input_energy = 0.0;
let mut output_energy = 0.0;
let mut peak = 0.0_f32;
for frame in 0..30 {
let mut samples = harmonic(frame, 0.002);
input_energy += energy(&samples);
processor.process_capture(&mut samples).unwrap();
assert_normalized(&samples);
peak = samples.iter().fold(peak, |peak, sample| peak.max(sample.abs()));
output_energy += energy(&samples);
}
let gain_db = 10.0 * (output_energy / input_energy).log10();
// Sonora starts at 15 dB of adaptive gain and changes it at 6 dB/s.
assert!((6.0..18.0).contains(&gain_db), "{silent_frames} silent frames: {gain_db:.2} dB");
assert!(peak < 0.05, "quiet onset became loud after {silent_frames} silent frames: {peak}");
for frame in 0..50 {
let mut silence = [0.0; FRAME_SAMPLES];
processor.process_capture(&mut silence).unwrap();
assert!(silence.iter().all(|&sample| sample == 0.0), "generated audio after onset: frame {frame}");
}
}
}
#[test]
fn full_scale_impulses_and_polarity_steps_remain_bounded_and_decay_to_silence() {
for settings in [
CaptureSettings { automatic_gain_control: true, ..BYPASS },
CaptureSettings { noise_suppression: Some(1), ..BYPASS },
CaptureSettings::default(),
] {
let mut processor = CaptureProcessor::new(settings).unwrap();
let mut transient_energy = 0.0;
let mut tail_energy = 0.0;
for frame in 0..400 {
let mut samples = match frame {
0 | 100 => {
let mut impulse = [0.0; FRAME_SAMPLES];
impulse[0] = if frame == 0 { 1.0 } else { -1.0 };
impulse
}
1..=9 => [1.0; FRAME_SAMPLES],
10..=19 => [-1.0; FRAME_SAMPLES],
20..=29 => std::array::from_fn(|index| if index % 2 == 0 { 1.0 } else { -1.0 }),
_ => [0.0; FRAME_SAMPLES],
};
processor.process_render(&[0.0; FRAME_SAMPLES], 0).unwrap();
processor.process_capture(&mut samples).unwrap();
// Full-scale input may engage Sonora's hard limiter. Bounded output
// here does not imply the absence of clipping.
assert_normalized(&samples);
if frame < 120 {
transient_energy += energy(&samples);
} else if frame >= 300 {
tail_energy += energy(&samples);
}
}
assert!(transient_energy > 0.0, "pipeline muted the transient probe: {settings:?}");
assert!(tail_energy < 1e-6, "transient persisted in silence: {settings:?}, energy {tail_energy}");
}
}
#[test]
fn integrated_noise_suppression_attenuates_dc_without_rail_clipping() {
for level in 0..=3 {
let settings = CaptureSettings { noise_suppression: Some(level), ..BYPASS };
let mut processor = CaptureProcessor::new(settings).unwrap();
let mut tail_energy = 0.0;
let mut input_energy = 0.0;
for frame in 0..200 {
let mut samples = [0.1; FRAME_SAMPLES];
if frame >= 150 {
input_energy += energy(&samples);
}
processor.process_capture(&mut samples).unwrap();
assert_normalized(&samples);
assert!(samples.iter().all(|sample| sample.abs() < 1.0), "DC clipped: level {level}, frame {frame}");
if frame >= 150 {
tail_energy += energy(&samples);
}
}
// Sonora's split-band HPF has finite DC rejection. Use its upstream
// 47.3 dB criterion instead of requiring exact zeros at steady state.
let attenuation_db = 10.0 * (input_energy / tail_energy).log10();
assert!(
attenuation_db >= 47.3,
"insufficient integrated HPF/NS DC rejection at level {level}: {attenuation_db:.2} dB"
);
}
}
+12 -12
View File
@@ -1,29 +1,29 @@
{
"schema": 1,
"upstream_revision": "a024d6ef8351add55be5e8b1d6cc35f555787660",
"upstream_revision": "1632d47c1e77d0857f9145bd175134b348541e11",
"packages": [
{
"name": "sonora",
"version": "0.2.0",
"version": "0.3.0",
"registry": "https://crates.io",
"archive": "https://static.crates.io/crates/sonora/sonora-0.2.0.crate",
"sha256": "2e1ce442ab5cb392c4067b8f2cced20be4cf12e479f6dfbf44acbe9b14ac9250",
"archive": "https://static.crates.io/crates/sonora/sonora-0.3.0.crate",
"sha256": "d461e6c9ad112f8728919387a4bc5639fd28631f2070171efad38676e907edd8",
"path_in_vcs": "crates/sonora",
"modified_sources": ["src/gain_controller2.rs"],
"patch": "Mono AGC2 noise analysis uses a stack channel descriptor. Adaptive gain, fixed gain and limiter borrow AudioBuffer::channel_mut(0), eliminating caller-side per-frame channel/sample Vec allocation and copy-back. Multichannel processing remains the upstream path. Includes mono-vs-identical-stereo signal equivalence test."
"patch": "Preserve the mono AGC2 stack channel descriptors and direct AudioBuffer::channel_mut(0) processing, avoiding the upstream reusable-buffer copy for mono. Multichannel uses the 0.3.0 reusable owned-buffer pipeline. Retains the mono-vs-identical-stereo signal equivalence test and standalone sonora-agc2 path patch."
},
{
"name": "sonora-agc2",
"version": "0.2.0",
"version": "0.3.0",
"registry": "https://crates.io",
"archive": "https://static.crates.io/crates/sonora-agc2/sonora-agc2-0.2.0.crate",
"sha256": "9a93a9fa8373a33e61a7fb441d8a9e725ac6024079d2c77a845cf6abe1790b9f",
"archive": "https://static.crates.io/crates/sonora-agc2/sonora-agc2-0.3.0.crate",
"sha256": "501b5dd3f8bdc8c983dc64a131cef22a429f3ff879d6f0007b8bfe46ec7b96aa",
"path_in_vcs": "crates/sonora-agc2",
"modified_sources": ["src/limiter.rs"],
"patch": "Mono limiter level estimation uses a stack immutable channel descriptor rather than collecting Vec<&[f32]>. Multichannel processing and numerical operations remain unchanged."
"modified_sources": [],
"patch": "The former mono limiter descriptor-allocation patch is subsumed by upstream 0.3.0: generic channel views pass directly to compute_level_of_channels without collecting a Vec for either mono or multichannel. The public borrowed-slice entry point used by the local sonora mono path remains available."
}
],
"scope": "This removes the inspected AGC2 mono channel-adapter allocations/copies; it is not an allocation-free guarantee for the complete Sonora APM or its other dependencies.",
"source": "Copied installed pinned registry sources, retaining upstream Cargo manifests, lockfiles, license, README and VCS metadata; registry .cargo-ok extraction markers omitted.",
"verification": "Tests added, not executed by delegated worker. Parent runs verification after integration."
"source": "Official 0.3.0 registry archives, retaining upstream files and licenses; mono behavioral/performance patch rebased rather than dropped. Standalone sonora Cargo manifest and lock retain the local sonora-agc2 path patch.",
"verification": "Source migration only. Retained local equivalence test and included upstream release tests; no builds, tests, formatters or cargo update executed by delegated worker. Parent runs verification after integration."
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"git": {
"sha1": "a024d6ef8351add55be5e8b1d6cc35f555787660"
"sha1": "1632d47c1e77d0857f9145bd175134b348541e11"
},
"path_in_vcs": "crates/sonora-agc2"
}
+214 -110
View File
@@ -10,24 +10,52 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bit-set"
version = "0.8.0"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.8.0"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269"
dependencies = [
"borsh",
"serde",
]
[[package]]
name = "bitflags"
version = "2.13.1"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "borsh"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
dependencies = [
"borsh-derive",
"bytes",
"cfg_aliases",
]
[[package]]
name = "borsh-derive"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
dependencies = [
"once_cell",
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "bytemuck"
@@ -40,26 +68,55 @@ dependencies = [
[[package]]
name = "bytemuck_derive"
version = "1.11.0"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 3.0.9",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures",
"rand_core",
]
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "cpufeatures"
version = "0.3.0"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
@@ -73,7 +130,7 @@ dependencies = [
"proc-macro2",
"quote",
"structmeta",
"syn",
"syn 2.0.119",
]
[[package]]
@@ -94,10 +151,16 @@ dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"syn",
"syn 2.0.119",
"unicode-xid",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "errno"
version = "0.3.14"
@@ -120,18 +183,6 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getrandom"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"libc",
"r-efi 5.3.0",
"wasip2",
]
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -140,14 +191,31 @@ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi 6.0.0",
"r-efi",
"rand_core",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "libc"
version = "0.2.189"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "linux-raw-sys"
@@ -155,6 +223,12 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -177,12 +251,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"zerocopy",
"toml_edit",
]
[[package]]
@@ -196,16 +270,17 @@ dependencies = [
[[package]]
name = "proptest"
version = "1.11.0"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
dependencies = [
"bit-set",
"bit-vec",
"bitflags",
"chacha20",
"core_detect",
"num-traits",
"rand",
"rand_chacha",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
@@ -228,12 +303,6 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "r-efi"
version = "6.0.0"
@@ -242,38 +311,25 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.5"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"getrandom",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.5"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_xorshift"
version = "0.4.0"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core",
]
@@ -295,9 +351,9 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.4"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
@@ -324,9 +380,39 @@ version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "sonora-agc2"
version = "0.2.0"
version = "0.3.0"
dependencies = [
"bytemuck",
"derive_more",
@@ -340,9 +426,9 @@ dependencies = [
[[package]]
name = "sonora-common-audio"
version = "0.2.0"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6635bc61b24807ceac93ad0807b1292b6b0620caa6cd360d3be89fc616b833cc"
checksum = "2c05dfa300c14dc8498751ce2c5b87aad2acf1892d4f9d66b92ae2f372a83410"
dependencies = [
"derive_more",
"sonora-simd",
@@ -350,15 +436,18 @@ dependencies = [
[[package]]
name = "sonora-fft"
version = "0.2.0"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27e272c70f34363afb5382dd1818c05f8f63ef6785635736a14e9ccbbb5ba012"
checksum = "ec3529f2cf748f1acc85d9403ffa08a3fe69dec6bf22383910b3bd21aca2fd26"
dependencies = [
"sonora-simd",
]
[[package]]
name = "sonora-simd"
version = "0.2.0"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7cf0804e4752a5562262e143014f53043080ead4cd5a98f9278d3ceaf32d868"
checksum = "f939d8e63a2a0baa7555294d7b09c5e3d382f28358755b920e13ad527658c8fa"
dependencies = [
"cpufeatures",
]
@@ -372,7 +461,7 @@ dependencies = [
"proc-macro2",
"quote",
"structmeta-derive",
"syn",
"syn 2.0.119",
]
[[package]]
@@ -383,7 +472,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.119",
]
[[package]]
@@ -397,6 +486,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -404,7 +504,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
@@ -420,7 +520,37 @@ dependencies = [
"proc-macro2",
"quote",
"structmeta",
"syn",
"syn 2.0.119",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.19+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [
"winnow",
]
[[package]]
@@ -442,7 +572,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.119",
]
[[package]]
@@ -462,9 +592,9 @@ checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicode-ident"
version = "1.0.24"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-xid"
@@ -481,15 +611,6 @@ dependencies = [
"libc",
]
[[package]]
name = "wasip2"
version = "1.0.4+wasi-0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "windows-link"
version = "0.2.1"
@@ -506,27 +627,10 @@ dependencies = [
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "zerocopy"
version = "0.8.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"
dependencies = [
"proc-macro2",
"quote",
"syn",
"memchr",
]
+8 -4
View File
@@ -13,7 +13,7 @@
edition = "2024"
rust-version = "1.91"
name = "sonora-agc2"
version = "0.2.0"
version = "0.3.0"
build = false
autolib = false
autobins = false
@@ -37,6 +37,10 @@ repository = "https://github.com/dignifiedquire/sonora"
name = "sonora_agc2"
path = "src/lib.rs"
[[test]]
name = "published_signatures"
path = "tests/published_signatures.rs"
[dependencies.bytemuck]
version = "1"
features = ["derive"]
@@ -46,13 +50,13 @@ version = "2"
features = ["debug"]
[dependencies.sonora-common-audio]
version = "0.2.0"
version = "0.3.0"
[dependencies.sonora-fft]
version = "0.2.0"
version = "0.3.0"
[dependencies.sonora-simd]
version = "0.2.0"
version = "0.3.0"
[dependencies.tracing]
version = "0.1"
Loaded 100 of 986 files, more files were not shown because too many files have changed in this diff. Show more