Author SHA1 Message Date
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
bit9992 05e8d34bcf Record accepted Windows native baseline and Android CI build route
native-ci / native-linux (teamspeach-native-linux-arm64, aarch64-unknown-linux-gnu) (push) Canceled after 0s
native-ci / native-linux (teamspeach-native-linux-x64, x86_64-unknown-linux-gnu) (push) Canceled after 0s
2026-11-11 11:32:53 +03:00
bit9992 5ce12714ac Refresh Understand graph for native-only Rust Slint architecture
native-ci / native-linux (teamspeach-native-linux-arm64, aarch64-unknown-linux-gnu) (push) Canceled after 0s
native-ci / native-linux (teamspeach-native-linux-x64, x86_64-unknown-linux-gnu) (push) Canceled after 0s
2026-11-10 18:28:52 +03:00
bit9992 a761afaa43 Record native cutover verification and environment blockers 2026-11-10 18:25:25 +03:00
bit9992 220852f8cb Remove Electron and make Rust Slint the sole native client 2026-11-10 17:53:53 +03:00
omar eb24965076 Implement Rust and Slint native client migration and fix desktop startup
ci / linux-arm64-cross (push) Successful in 4m7s
ci / linux-x64 (push) Successful in 4m42s
2026-11-10 15:45:24 +03:00
omar 0d11f8f99d wip: checkpoint TS6 interface parity and working settings for handoff
ci / linux-arm64-cross (push) Successful in 33m19s
ci / linux-x64 (push) Failing after 46m53s
2026-11-08 15:54:28 +03:00
omar c4707c4e8e release: prepare v0.1.7 verified editor and interface update
ci / linux-arm64-cross (push) Successful in 3m24s
ci / linux-x64 (push) Successful in 4m10s
release / linux-arm64 (push) Successful in 7m47s
release / linux-x64 (push) Successful in 8m6s
release / appimage-startup (push) Successful in 14s
release / publish (push) Successful in 20s
2026-11-02 13:44:55 +03:00
omar a4c9e7e102 docs: record authorized muted server capability probe
ci / linux-arm64-cross (push) Successful in 3m57s
ci / linux-x64 (push) Successful in 5m6s
2026-11-02 13:33:58 +03:00
omar 21085b967d docs: record native server-chat request constructors
ci / linux-arm64-cross (push) Successful in 3m44s
ci / linux-x64 (push) Successful in 3m48s
2026-11-02 12:58:34 +03:00
omar d0202247ce docs: distinguish server-hosted Matrix from account chat
ci / linux-x64 (push) Successful in 3m24s
ci / linux-arm64-cross (push) Successful in 3m45s
2026-11-02 12:39:28 +03:00
omar e4681bef35 chat: preserve source keyboard editing and list transitions 2026-11-02 12:15:05 +03:00
omar f618d8bce9 chat: add safe hybrid Markdown editing with strict CSP
ci / linux-arm64-cross (push) Successful in 3m22s
ci / linux-x64 (push) Successful in 3m32s
2026-11-02 11:32:31 +03:00
omar 3ee2bef7ce ui: match light controls and narrow chat reference layouts 2026-11-02 11:05:28 +03:00
omar 72e4ad63a8 release: prepare v0.1.6 and run ARM test subprocesses through qemu
ci / linux-x64 (push) Successful in 6m10s
ci / linux-arm64-cross (push) Successful in 6m32s
release / linux-arm64 (push) Successful in 7m22s
release / linux-x64 (push) Successful in 8m12s
release / appimage-startup (push) Successful in 18s
release / publish (push) Successful in 20s
2026-11-02 11:01:56 +03:00
omar c75c8f3d74 release: prepare v0.1.5 verified account-free snapshot
release / linux-x64 (push) Failing after 59s
ci / linux-x64 (push) Failing after 1m9s
ci / linux-arm64-cross (push) Failing after 4m15s
release / linux-arm64 (push) Successful in 4m36s
release / appimage-startup (push) Skipped
release / publish (push) Skipped
2026-11-02 10:50:54 +03:00
omar 8336f01be7 feat: match identity and transfer settings with real category controls 2026-11-02 10:18:20 +03:00
omar a1f5e43f5f feat: add protected bookmark credentials and startup options 2026-11-02 09:49:29 +03:00
omar 7108026544 test: await persisted state and exercise expanded desktop panels 2026-11-01 22:16:17 +03:00
omar cf42de67e2 feat: add account-free settings and server management panels 2026-11-01 22:14:32 +03:00
omar 672540499c fix(i18n): match original Russian bookmark guidance 2026-11-01 19:54:54 +03:00
omar 33721aee7b fix(ui): match measured empty-chat prompt geometry
Use the actual 22px glyph and secondary-pane contrast background. Packaged dark/en captures at1553x998 and880x800 completed without harness errors; wide chat region passes. Whole-screen parity still fails bookmark/tree and narrow residuals.
2026-11-01 19:52:53 +03:00
omar ceecbb790a docs: record source parity evidence and remaining acceptance gaps
Document accumulated interoperability findings and current source-backed design. Record build-specific visual results, matched acceleration policy, passing packaged behavior checks, and explicit native/ARM and strict visual acceptance limits. No complete 1:1 claim.
2026-11-01 19:47:52 +03:00
omar e6464bc4ed feat: checkpoint account-free client workflows and source-matched UI
Preserve accumulated client implementation since v0.1.4, including local identities, multi-server state, chat, administration, audio and streaming controls. Refine official-source layout, original artwork, responsive composer overflow, settings navigation and chat scroll anchoring.

Current verification: Node suite passes; isolated packaged chat and responsive control smokes pass without device capture. Native core is reused, not rebuilt in this pass. Strict whole-screen visual parity remains incomplete; no 1:1 or cross-platform acceptance claim. Local checkpoint only; no release or push.
2026-11-01 19:43:18 +03:00
omar 0486ad361f v0.1.4 released: evidence, changelog date; vad tests assert window remainders and sensitivity decisions
ci / linux-x64 (push) Successful in 2m56s
ci / linux-arm64-cross (push) Successful in 4m2s
2026-10-24 10:07:25 +03:00
omar 4b1257a84d Evidence: 0.1.4 CI excerpts (x64, ARM64 qemu) and packaged Windows smokes from 0923b32
ci / linux-x64 (push) Successful in 4m32s
ci / linux-arm64-cross (push) Successful in 5m18s
2026-10-24 09:57:23 +03:00
omar 0923b32841 Transmit race tests: settle with setImmediate (fixture timers are unreferenced; Node 22 ended the loop)
ci / linux-x64 (push) Successful in 2m48s
ci / linux-arm64-cross (push) Successful in 2m48s
release / linux-arm64 (push) Successful in 6m21s
release / linux-x64 (push) Successful in 6m51s
release / appimage-startup (push) Successful in 14s
release / publish (push) Successful in 19s
2026-10-24 09:50:56 +03:00
omar 3d623329b3 Transmit mode: only the latest set_transmit answer counts; forwarding terminology; 0.1.4
ci / linux-x64 (push) Failing after 33s
ci / linux-arm64-cross (push) Successful in 3m8s
An older answer (same settings or a restarted core) could re-enable forwarding while a newer mode
change was pending. Requests and core restarts now start a new epoch. Renderer stats count frames
forwarded to the core. v0.1.3 was tagged but never released.
2026-10-24 09:45:49 +03:00
omar a924d792b4 VAD docs: startup buffer latency stated precisely; smoke-voice-vad --exe
ci / linux-arm64-cross (push) Successful in 2m48s
ci / linux-x64 (push) Successful in 2m53s
release / linux-arm64 (push) Successful in 4m15s
release / linux-x64 (push) Successful in 4m38s
release / appimage-startup (push) Successful in 15s
release / publish (push) Failing after 9s
2026-10-24 09:31:27 +03:00
omar b7951e0693 Voice activation (core voice detector, set_transmit handshake), transmission mode in Settings → Audio, atomic prefs commit, ARM64 unit tests under qemu; version 0.1.3
ci / linux-x64 (push) Successful in 2m50s
ci / linux-arm64-cross (push) Successful in 2m50s
2026-10-24 09:29:46 +03:00
omar 8439fe062e Evidence: v0.1.2 release, packaged 0.1.2 smokes, updater E2E logs (rc.1→rc.2, rc.2→0.1.2)
ci / linux-arm64-cross (push) Successful in 2m19s
ci / linux-x64 (push) Successful in 2m41s
2026-10-24 07:41:41 +03:00
omar 9e7483601b Updater harness: hash the pending update file; updater RC proof notes
ci / linux-arm64-cross (push) Successful in 2m18s
ci / linux-x64 (push) Successful in 3m20s
release / linux-arm64 (push) Successful in 4m12s
release / linux-x64 (push) Successful in 4m30s
release / appimage-startup (push) Successful in 14s
release / publish (push) Successful in 19s
2026-10-24 07:30:23 +03:00
omar f97a651c87 TeamsPeach 0.1.2
ci / linux-arm64-cross (push) Successful in 2m51s
ci / linux-x64 (push) Successful in 3m9s
2026-10-24 07:28:47 +03:00
omar 2cf63f5d88 Evidence: packaged 0.1.2-rc.2 (ed2e123) smokes
ci / linux-x64 (push) Successful in 3m3s
ci / linux-arm64-cross (push) Successful in 2m34s
2026-10-24 07:15:35 +03:00
omar ed2e123404 Release candidate 0.1.2-rc.2
ci / linux-x64 (push) Successful in 3m45s
ci / linux-arm64-cross (push) Successful in 2m50s
release / linux-arm64 (push) Successful in 4m8s
release / linux-x64 (push) Successful in 4m36s
release / appimage-startup (push) Successful in 13s
release / publish (push) Successful in 19s
2026-10-24 07:13:20 +03:00
omar 6b8994f1cb Use the application icon asset as the in-app brand mark; drop the old inline peach; smoke checks the decoded image
ci / linux-arm64-cross (push) Successful in 2m53s
ci / linux-x64 (push) Successful in 4m54s
2026-10-24 07:12:44 +03:00
1633 changed files with 1025287 additions and 17897 deletions

No files matched your search

+3
View File
@@ -12,3 +12,6 @@ LIBOPUS_NO_PKG = "1"
# with Windows 10+ (no VCRUNTIME140.dll). cc/cmake-rs see `crt-static` and build libopus with /MT.
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
[target.aarch64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
+3
View File
@@ -0,0 +1,3 @@
# Native dependency recipes verify exact source bytes on every build host.
native/patches/** text eol=lf
xtask/src/*.rs text eol=lf
+167
View File
@@ -0,0 +1,167 @@
# Trusted manual runs only, on an administrator-provisioned Linux x64 runner.
# This job never installs host tools, signs production packages, publishes, or uses a device.
name: android-ci
on:
workflow_dispatch:
permissions:
contents: read
defaults:
run:
shell: bash
working-directory: ${{ github.workspace }}/android-${{ github.run_id }}
jobs:
android-arm64:
runs-on: teamspeach-android-linux-x64
env:
CARGO_TERM_COLOR: never
TARGET: aarch64-linux-android
EXPECTED_REVISION: ${{ github.sha }}
CI_RUN_ID: ${{ github.run_id }}
CARGO_TARGET_DIR: ${{ github.workspace }}/android-${{ github.run_id }}/target
GRADLE_USER_HOME: ${{ github.workspace }}/android-${{ github.run_id }}/.gradle-ci
ANDROID_HOME: ${{ vars.ANDROID_SDK_ROOT }}
ANDROID_SDK_ROOT: ${{ vars.ANDROID_SDK_ROOT }}
JAVA_HOME: ${{ vars.ANDROID_JAVA_HOME }}
LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
TEAMSPEACH_GRADLE_DISTRIBUTION: ${{ vars.ANDROID_GRADLE_DISTRIBUTION }}
TEAMSPEACH_BUNDLETOOL: ${{ vars.ANDROID_BUNDLETOOL }}
steps:
- uses: actions/checkout@v4
with:
path: android-${{ github.run_id }}
clean: true
persist-credentials: false
- name: Require provisioned Linux Android tools (no host installation)
run: |
set -euo pipefail
test "$(uname -s)" = Linux
test "$(uname -m)" = x86_64
test "$(git rev-parse HEAD)" = "$EXPECTED_REVISION"
: "${ANDROID_SDK_ROOT:?set ANDROID_SDK_ROOT to installed SDK36 with build-tools/36.0.0 and NDK28.2.13676358}"
: "${JAVA_HOME:?set ANDROID_JAVA_HOME to installed JDK17+ (JDK21 is supported)}"
: "${LLVM_HOME:?set NATIVE_LLVM_HOME to installed LLVM}"
: "${LIBCLANG_PATH:?set NATIVE_LIBCLANG_PATH to the matching libclang directory}"
: "${SKIA_SOURCE_DIR:?set NATIVE_SKIA_SOURCE_DIR to a dependency-synchronized Skia checkout}"
: "${TEAMSPEACH_GRADLE_DISTRIBUTION:?set ANDROID_GRADLE_DISTRIBUTION to local gradle-8.14.3-bin.zip}"
: "${TEAMSPEACH_BUNDLETOOL:?set ANDROID_BUNDLETOOL to local bundletool.jar}"
export ANDROID_NDK_ROOT="$ANDROID_SDK_ROOT/ndk/28.2.13676358"
export ANDROID_NDK_HOME="$ANDROID_NDK_ROOT"
export PATH="$JAVA_HOME/bin:$LLVM_HOME/bin:$ANDROID_SDK_ROOT/build-tools/36.0.0:$PATH"
for tool in cargo rustc rustup git cmake ninja python3 pkg-config clang clang++ ar llvm-strip llvm-readelf java javac jar keytool jarsigner sh zipalign aapt2 apksigner; do
command -v "$tool"
done
test -f "$ANDROID_SDK_ROOT/platforms/android-36/android.jar"
test -f "$ANDROID_NDK_ROOT/source.properties"
test -x "$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang"
test -f "$SKIA_SOURCE_DIR/BUILD.gn"
test -x "$SKIA_SOURCE_DIR/bin/gn"
test -d "$SKIA_SOURCE_DIR/third_party/externals"
test -f "$TEAMSPEACH_BUNDLETOOL"
test -d "$(rustc --print target-libdir --target "$TARGET")"
# A clean checkout and run-specific Cargo/Gradle/output trees prevent stale
# packages or dependency receipts from another job/revision being selected.
test ! -e target
test ! -e dist/android
test ! -e .gradle-ci
python3 - <<'PY'
import hashlib, os, pathlib, re, subprocess
ndk = pathlib.Path(os.environ['ANDROID_NDK_ROOT'], 'source.properties').read_text()
assert re.search(r'^Pkg\.Revision\s*=\s*28\.2\.13676358\s*$', ndk, re.M), 'NDK must match Gradle ndkVersion'
java = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT, text=True)
assert int(re.search(r'version "(\d+)', java)[1]) >= 17, 'JDK17+ is required'
assert list(pathlib.Path(os.environ['LIBCLANG_PATH']).glob('libclang.so*')), 'matching LLVM libclang.so is required'
properties = pathlib.Path('platform/android/gradle/wrapper/gradle-wrapper.properties').read_text()
expected = re.search(r'^distributionSha256Sum=(\w+)$', properties, re.M)[1]
with open(os.environ['TEAMSPEACH_GRADLE_DISTRIBUTION'], 'rb') as source:
digest = hashlib.sha256()
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
assert digest.hexdigest() == expected, 'local Gradle zip checksum mismatch'
# No signing configuration is consumed from a dedicated runner's environment.
for name in ('TEAMSPEACH_ANDROID_KEYSTORE', 'TEAMSPEACH_ANDROID_STORE_PASSWORD', 'TEAMSPEACH_ANDROID_KEY_ALIAS', 'TEAMSPEACH_ANDROID_KEY_PASSWORD'):
assert name not in os.environ, 'remove production signing environment from this unsigned runner'
PY
echo "ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT" >> "$GITHUB_ENV"
echo "ANDROID_NDK_HOME=$ANDROID_NDK_HOME" >> "$GITHUB_ENV"
echo "$JAVA_HOME/bin" >> "$GITHUB_PATH"
echo "$LLVM_HOME/bin" >> "$GITHUB_PATH"
echo "$ANDROID_SDK_ROOT/build-tools/36.0.0" >> "$GITHUB_PATH"
echo "SKIA_GN_COMMAND=$SKIA_SOURCE_DIR/bin/gn" >> "$GITHUB_ENV"
echo "SKIA_NINJA_COMMAND=$(command -v ninja)" >> "$GITHUB_ENV"
- name: Check workspace version and packaging behavior
run: |
set -euo pipefail
cargo run --locked -p xtask -- check-version
cargo test --locked -p xtask
- name: Build pinned Android WebRTC from source on Linux
run: cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME"
- name: Build and verify harness first, then unsigned production (full Skia + WebRTC)
run: |
set -euo pipefail
for variant in harness production; do
if [ "$variant" = harness ]; then harness=true; else harness=false; fi
out="dist/android/$variant"
cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --test-harness "$harness"
# Explicit online dependency resolution supports a fresh Gradle cache.
# Bootstrap still requires the local checksum-pinned zip; SDK downloads stay disabled.
cargo run --locked -p xtask -- package --target "$TARGET" --out "$out" --test-harness "$harness" --gradle-online true
cargo run --locked -p xtask -- verify-package --target "$TARGET" --out "$out" --test-harness "$harness"
cp "$CARGO_TARGET_DIR/$TARGET/release/native-build.json" "$out/$TARGET/native-build.json"
cp native/native-deps.lock.json "$out/$TARGET/native-deps.lock.json"
cp "target/native-deps/$TARGET/provenance.json" "$out/$TARGET/dependency-provenance.json"
python3 - "$out" "$harness" <<'PY'
import hashlib, json, os, pathlib, subprocess, sys
out = pathlib.Path(sys.argv[1])
harness = sys.argv[2] == 'true'
target = os.environ['TARGET']
revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
assert revision == os.environ['EXPECTED_REVISION'], 'checkout revision changed'
receipt = json.loads((out / target / 'package-report.json').read_text())
verification = json.loads((out / target / 'verification.json').read_text())
assert receipt['testOnly'] == harness and receipt['sourceBuild']['testHarness'] == harness
assert verification['passed'] is True
assert {a['kind'] for a in receipt['artifacts']} == ({'apk'} if harness else {'apk', 'aab'})
assert all(a['signing'] == ('android-debug-test' if harness else 'unsigned-not-installable') and not a['release_eligible'] for a in receipt['artifacts'])
files = [out / a['name'] for a in receipt['artifacts']]
files += [out / target / name for name in ('package-report.json', 'verification.json', 'native-build.json', 'native-deps.lock.json', 'dependency-provenance.json')]
hashes = {}
for path in files:
with path.open('rb') as source:
digest = hashlib.sha256()
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
hashes[str(path.relative_to(out))] = digest.hexdigest()
(out / 'build-info.json').write_text(json.dumps({'schema': 1, 'revision': revision, 'run_id': os.environ['CI_RUN_ID'], 'target': target, 'testHarness': harness, 'gradleOnline': True, 'deviceAcceptance': 'not exercised', 'publicationAuthorized': False, 'sha256': hashes}, indent=2) + '\n')
PY
done
- name: Retain installable test-only ARM64 harness and exact receipts
uses: actions/upload-artifact@v3
with:
name: android-harness-arm64
path: |
android-${{ github.run_id }}/dist/android/harness/*-harness-test.apk
android-${{ github.run_id }}/dist/android/harness/build-info.json
android-${{ github.run_id }}/dist/android/harness/aarch64-linux-android/*.json
if-no-files-found: error
- name: Retain unsigned production ARM64 APK and store AAB (not installable)
uses: actions/upload-artifact@v3
with:
name: android-production-unsigned-arm64
path: |
android-${{ github.run_id }}/dist/android/production/*-unsigned.apk
android-${{ github.run_id }}/dist/android/production/*-unsigned.aab
android-${{ github.run_id }}/dist/android/production/build-info.json
android-${{ github.run_id }}/dist/android/production/aarch64-linux-android/*.json
if-no-files-found: error
+61 -85
View File
@@ -1,9 +1,6 @@
# Continuous integration on the self-hosted Gitea runner (Linux x64 container jobs).
# Everything runs inside the job container; nothing is installed on the runner host.
# Triggers are trusted only: pushes to main by maintainers and manual dispatch. There is deliberately no
# pull_request trigger: the repository is public and the runner sits on a private network, so outside
# contributions are reviewed first and then validated by a maintainer (push to main or workflow_dispatch).
name: ci
# Trusted pushes/manual runs only: public pull requests must not execute on private runners.
# Runner administrators provision the native SDKs/tools; jobs never install on the host.
name: native-ci
on:
push:
@@ -13,102 +10,81 @@ on:
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
linux-x64:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
native-linux:
strategy:
fail-fast: false
matrix:
include:
- target: x86_64-unknown-linux-gnu
runner: teamspeach-native-linux-x64
- target: aarch64-unknown-linux-gnu
runner: teamspeach-native-linux-arm64
runs-on: ${{ matrix.runner }}
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "2"
TARGET: ${{ matrix.target }}
LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
LK_CUSTOM_WEBRTC: ${{ github.workspace }}/target/native-deps/${{ matrix.target }}/webrtc
steps:
- uses: actions/checkout@v4
- name: System packages (container only)
- name: Require explicitly provisioned source and native tools
run: |
apt-get update
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
xvfb xauth libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libgbm1 libgtk-3-0 \
libasound2 libxss1 libxshmfence1 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libpango-1.0-0
set -euo pipefail
: "${LLVM_HOME:?set NATIVE_LLVM_HOME to installed LLVM}"
: "${LIBCLANG_PATH:?set NATIVE_LIBCLANG_PATH to the libclang directory}"
: "${SKIA_SOURCE_DIR:?set NATIVE_SKIA_SOURCE_DIR to a dependency-synchronized Skia checkout}"
test -x "$LLVM_HOME/bin/clang"
test -f "$SKIA_SOURCE_DIR/BUILD.gn"
test -x "$SKIA_SOURCE_DIR/bin/gn"
echo "$LLVM_HOME/bin" >> "$GITHUB_PATH"
command -v cargo
command -v cmake
command -v ninja
command -v python3
command -v xvfb-run
command -v dbus-run-session
echo "SKIA_GN_COMMAND=$SKIA_SOURCE_DIR/bin/gn" >> "$GITHUB_ENV"
echo "SKIA_NINJA_COMMAND=$(command -v ninja)" >> "$GITHUB_ENV"
- name: Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Native version gate
run: cargo run --locked -p xtask -- check-version
- name: glibc baseline
run: ldd --version | sed -n 1p
- name: Gitea transport unit tests (mocked HTTP, no publication)
run: python3 -m unittest discover -s xtask -p test_publish_release.py
- name: Node dependencies
run: npm ci
- name: Provision pinned WebRTC sources and archive
run: cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs "$CARGO_BUILD_JOBS"
- name: Unit tests (desktop)
run: npm test
- name: Build full native app and update helper (Skia + WebRTC defaults)
run: cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --jobs "$CARGO_BUILD_JOBS"
- name: Core tests
run: cargo test --manifest-path core/Cargo.toml --locked
- name: Rust workspace tests on matching native architecture
run: cargo test --locked --workspace --target "$TARGET" --jobs "$CARGO_BUILD_JOBS"
- name: Core release build
run: cargo build --manifest-path core/Cargo.toml --release --locked
- name: Build explicit native test harness
run: cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --jobs "$CARGO_BUILD_JOBS" --test-harness true
- name: Core binary architecture
run: node scripts/binary-arch.mjs core/target/release/teamspeach-core --expect linux-x64
- name: Native offline UI smoke (not updater end-to-end acceptance)
run: dbus-run-session -- xvfb-run -a cargo run --locked -p xtask -- smoke --target "$TARGET" --scenario offline-ui --out "native-smoke-$TARGET"
- name: Core identity smoke (stdio, offline)
run: node scripts/core-smoke.mjs core/target/release/teamspeach-core
- name: Native historical profile migration smoke
run: dbus-run-session -- xvfb-run -a cargo run --locked -p xtask -- smoke --target "$TARGET" --scenario migration --out "native-migration-$TARGET"
- name: Electron UI smoke (Xvfb, offline, disposable profile)
env:
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out
- name: Updater engine behaviour (Xvfb, emulated release host)
run: xvfb-run -a node --test test/update-engine.test.mjs
- name: Upload smoke evidence
- name: Upload measured native smoke evidence
if: always()
uses: actions/upload-artifact@v3
with:
name: ci-smoke-linux-x64
path: smoke-out/
if-no-files-found: ignore
linux-arm64-cross:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "2"
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
CC_aarch64_unknown_linux_gnu: aarch64-linux-gnu-gcc
CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++
AR_aarch64_unknown_linux_gnu: aarch64-linux-gnu-ar
steps:
- uses: actions/checkout@v4
- name: Cross toolchain and user-mode emulator (container only, no binfmt)
run: |
apt-get update
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user
- name: Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Core cross build (aarch64-unknown-linux-gnu)
run: cargo build --manifest-path core/Cargo.toml --release --locked --target aarch64-unknown-linux-gnu
- name: Core binary architecture
run: node scripts/binary-arch.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --expect linux-arm64
- name: Required glibc symbols
run: aarch64-linux-gnu-objdump -T core/target/aarch64-unknown-linux-gnu/release/teamspeach-core | grep -o 'GLIBC_[0-9.]*' | sort -Vu | tail -n1
- name: 16 KiB page compatibility (Asahi) of the core ELF
run: node scripts/elf-pagesize.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --page 16384
- name: Core identity smoke under qemu-aarch64 (emulated, not native hardware)
run: node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
name: native-ci-${{ matrix.target }}
path: |
native-smoke-${{ matrix.target }}/
native-migration-${{ matrix.target }}/
if-no-files-found: warn
+106 -182
View File
@@ -1,8 +1,7 @@
# Release builds on the self-hosted Gitea runner (Linux x64 job containers).
# - workflow_dispatch: build + verify packages, keep them as run artifacts (no release).
# - tag v*: same, then publish a Gitea release with the packages, only if every build job succeeded.
# Windows x64 packages are built on a Windows machine and attached separately (see README).
name: release
# Trusted tag pushes publish only after both native architectures and release assembly pass.
# Manual dispatch builds/verifies and retains artifacts without publication.
# These labels require preprovisioned matching-ISA native runners (no emulated acceptance).
name: native-release
on:
push:
@@ -17,213 +16,138 @@ defaults:
shell: bash
jobs:
linux-x64:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
native-linux:
strategy:
fail-fast: false
matrix:
include:
- target: x86_64-unknown-linux-gnu
runner: teamspeach-native-linux-x64
- target: aarch64-unknown-linux-gnu
runner: teamspeach-native-linux-arm64
runs-on: ${{ matrix.runner }}
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "2"
TARGET: ${{ matrix.target }}
LLVM_HOME: ${{ vars.NATIVE_LLVM_HOME }}
SKIA_SOURCE_DIR: ${{ vars.NATIVE_SKIA_SOURCE_DIR }}
LIBCLANG_PATH: ${{ vars.NATIVE_LIBCLANG_PATH }}
LK_CUSTOM_WEBRTC: ${{ github.workspace }}/target/native-deps/${{ matrix.target }}/webrtc
steps:
- uses: actions/checkout@v4
- name: Version gate (tag = package.json = core/Cargo.toml)
run: node scripts/check-version.mjs
- name: System packages (container only)
- name: Require explicit native source/tool provisioning
run: |
set -euo pipefail
apt-get update
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
xvfb xauth libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libgbm1 libgtk-3-0 \
libasound2 libxss1 libxshmfence1 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libpango-1.0-0
: "${LLVM_HOME:?set NATIVE_LLVM_HOME to installed LLVM}"
: "${LIBCLANG_PATH:?set NATIVE_LIBCLANG_PATH to the libclang directory}"
: "${SKIA_SOURCE_DIR:?set NATIVE_SKIA_SOURCE_DIR to a dependency-synchronized Skia checkout}"
test -x "$LLVM_HOME/bin/clang"
test -f "$SKIA_SOURCE_DIR/BUILD.gn"
test -x "$SKIA_SOURCE_DIR/bin/gn"
echo "$LLVM_HOME/bin" >> "$GITHUB_PATH"
for tool in cargo cmake ninja python3 xvfb-run dbus-run-session linuxdeploy appimagetool unsquashfs llvm-readelf; do
command -v "$tool"
done
echo "SKIA_GN_COMMAND=$SKIA_SOURCE_DIR/bin/gn" >> "$GITHUB_ENV"
echo "SKIA_NINJA_COMMAND=$(command -v ninja)" >> "$GITHUB_ENV"
- name: Rust toolchain
- name: Tag must match native workspace version
run: cargo run --locked -p xtask -- check-version
- name: Provision pinned WebRTC sources and archive
run: cargo run --locked -p xtask -- deps --target "$TARGET" --llvm-dir "$LLVM_HOME" --jobs "$CARGO_BUILD_JOBS"
- name: Rust workspace tests on matching native architecture
run: cargo test --locked --workspace --target "$TARGET" --jobs "$CARGO_BUILD_JOBS"
- name: Build explicit native smoke harness with default Skia and WebRTC
run: cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --jobs "$CARGO_BUILD_JOBS" --test-harness true
- name: Native offline UI and historical profile migration smoke
run: |
set -euo pipefail
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
dbus-run-session -- xvfb-run -a cargo run --locked -p xtask -- smoke --target "$TARGET" --scenario offline-ui --out "native-smoke-$TARGET"
dbus-run-session -- xvfb-run -a cargo run --locked -p xtask -- smoke --target "$TARGET" --scenario migration --out "native-migration-$TARGET"
- name: Tests
- name: Rebuild production native app and update helper (no test harness)
run: cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME" --skia-source "$SKIA_SOURCE_DIR" --jobs "$CARGO_BUILD_JOBS"
- name: Package and inspect real native archive payloads
run: |
set -euo pipefail
npm ci
npm test
cargo test --manifest-path core/Cargo.toml --locked
cargo run --locked -p xtask -- package --target "$TARGET" --out dist/native
cargo run --locked -p xtask -- verify-package --target "$TARGET" --out dist/native
cp native/native-deps.lock.json "dist/native/$TARGET/native-deps.lock.json"
- name: Core release build and checks
run: |
set -euo pipefail
cargo build --manifest-path core/Cargo.toml --release --locked
node scripts/binary-arch.mjs core/target/release/teamspeach-core --expect linux-x64
node scripts/core-smoke.mjs core/target/release/teamspeach-core
- name: Electron UI smoke (Xvfb, offline)
env:
TEAMSPEACH_SMOKE_EXTRA_ARGS: --no-sandbox
run: xvfb-run -a node scripts/smoke-ui.mjs --out smoke-out
- name: Updater engine behaviour (Xvfb, real electron-updater, emulated release server)
run: xvfb-run -a node --test test/update-engine.test.mjs
- name: Package
run: node scripts/dist.mjs --os linux --arch x64
- name: Update feed matches the packages (name, size, sha512, version)
run: node scripts/update-feed-check.mjs --version "$(node -p "require('./package.json').version")" dist/*-linux.yml
- name: Package report (ELF layout of every packaged binary incl. the AppImage runtime)
run: |
set -euo pipefail
report=dist/build-info-linux-x64.txt
# sed consumes all input, so ldd never gets SIGPIPE under pipefail (head -n1 caused exit 141).
ldd --version | sed -n 1p > "$report"
git rev-parse HEAD >> "$report"
node scripts/elf-pagesize.mjs dist/linux-unpacked dist/TeamsPeach-*.AppImage --page 4096 --json dist/elf-report-linux-x64.json > elf.txt
cat elf.txt >> "$report"
sha256sum dist/*.AppImage dist/*.tar.gz dist/*-linux.yml >> "$report"
cat "$report"
- uses: actions/upload-artifact@v3
- name: Upload native release bundle and exact provisioning receipt
uses: actions/upload-artifact@v3
with:
name: teamspeach-linux-x64
name: teamspeach-native-${{ matrix.target }}
path: |
dist/*.AppImage
dist/*.tar.gz
dist/build-info-linux-x64.txt
dist/elf-report-linux-x64.json
dist/*-linux.yml
dist/native/TeamsPeach-*.AppImage
dist/native/TeamsPeach-*.tar.gz
dist/native/*.yml
dist/native/native-manifest.json
dist/native/${{ matrix.target }}/package-report.json
dist/native/${{ matrix.target }}/verification.json
dist/native/${{ matrix.target }}/native-deps.lock.json
if-no-files-found: error
linux-arm64:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
env:
CARGO_TERM_COLOR: never
CARGO_BUILD_JOBS: "2"
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
CC_aarch64_unknown_linux_gnu: aarch64-linux-gnu-gcc
CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++
AR_aarch64_unknown_linux_gnu: aarch64-linux-gnu-ar
- name: Upload measured native smoke evidence
if: always()
uses: actions/upload-artifact@v3
with:
name: native-release-smoke-${{ matrix.target }}
path: |
native-smoke-${{ matrix.target }}/
native-migration-${{ matrix.target }}/
if-no-files-found: warn
assemble:
needs: [native-linux]
runs-on: teamspeach-native-linux-x64
steps:
- uses: actions/checkout@v4
- name: Version gate (tag = package.json = core/Cargo.toml)
run: node scripts/check-version.mjs
- name: Cross toolchain and user-mode emulator (container only, no binfmt)
run: |
set -euo pipefail
apt-get update
apt-get install -y --no-install-recommends build-essential cmake curl ca-certificates git \
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user
- name: Rust toolchain
run: |
set -euo pipefail
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable --target aarch64-unknown-linux-gnu
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Core cross build and checks
run: |
set -euo pipefail
cargo build --manifest-path core/Cargo.toml --release --locked --target aarch64-unknown-linux-gnu
node scripts/binary-arch.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --expect linux-arm64
node scripts/elf-pagesize.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --page 16384
node scripts/core-smoke.mjs core/target/aarch64-unknown-linux-gnu/release/teamspeach-core --wrapper "qemu-aarch64 -L /usr/aarch64-linux-gnu"
- name: Package
run: |
set -euo pipefail
npm ci
node scripts/dist.mjs --os linux --arch arm64
node scripts/update-feed-check.mjs --version "$(node -p "require('./package.json').version")" dist/*-linux-arm64.yml
- name: 16 KiB page check of every packaged ELF incl. the AppImage runtime (Asahi)
run: |
set -euo pipefail
report=dist/build-info-linux-arm64.txt
echo "glibc of build sysroot: $(dpkg-query -W -f='${Version}' libc6-dev-arm64-cross)" > "$report"
git rev-parse HEAD >> "$report"
node scripts/elf-pagesize.mjs dist/linux-arm64-unpacked dist/TeamsPeach-*-arm64.AppImage --page 16384 --json dist/elf-report-linux-arm64.json > elf.txt
cat elf.txt >> "$report"
sha256sum dist/*.AppImage dist/*.tar.gz dist/*-linux-arm64.yml >> "$report"
cat "$report"
- uses: actions/upload-artifact@v3
with:
name: teamspeach-linux-arm64
path: |
dist/*.AppImage
dist/*.tar.gz
dist/build-info-linux-arm64.txt
dist/elf-report-linux-arm64.json
dist/*-linux-arm64.yml
if-no-files-found: error
# The AppImage runtime must start on a stock system: run it in a slim container without development
# packages (no unversioned libz.so), natively for x64 and under qemu-aarch64 for arm64.
appimage-startup:
needs: [linux-x64, linux-arm64]
runs-on: ubuntu-latest
container:
image: node:22-bookworm-slim
steps:
- uses: actions/download-artifact@v3
with:
path: artifacts
- name: x64 AppImage runtime starts without development packages
run: |
set -euo pipefail
echo "zlib files present:"; ls /usr/lib/x86_64-linux-gnu/ | grep '^libz\.' || true
app=$(ls artifacts/teamspeach-linux-x64/TeamsPeach-*.AppImage)
chmod +x "$app"
"$app" --appimage-version
- name: arm64 AppImage runtime starts under qemu-aarch64 (emulated)
run: |
set -euo pipefail
dpkg --add-architecture arm64
apt-get update
apt-get install -y --no-install-recommends qemu-user libc6:arm64 zlib1g:arm64
echo "arm64 zlib files present:"; ls /usr/lib/aarch64-linux-gnu/ | grep '^libz\.' || true
app=$(ls artifacts/teamspeach-linux-arm64/TeamsPeach-*-arm64.AppImage)
chmod +x "$app"
qemu-aarch64 -L / "$app" --appimage-version
name: teamspeach-native-x86_64-unknown-linux-gnu
path: artifacts/teamspeach-native-x86_64-unknown-linux-gnu
- uses: actions/download-artifact@v3
with:
name: teamspeach-native-aarch64-unknown-linux-gnu
path: artifacts/teamspeach-native-aarch64-unknown-linux-gnu
- name: Gitea transport unit tests (mocked HTTP, no publication)
run: python3 -m unittest discover -s xtask -p test_publish_release.py
- name: Merge strict native manifests and recheck every package digest
run: cargo run --locked -p xtask -- prepare-release --out artifacts
- uses: actions/upload-artifact@v3
with:
name: native-release-manifest
path: artifacts/native-manifest.json
if-no-files-found: error
publish:
needs: [linux-x64, linux-arm64, appimage-startup]
needs: [native-linux, assemble]
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
container:
image: node:22-bookworm
runs-on: teamspeach-native-linux-x64
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v3
with:
path: artifacts
- name: Publish release (draft → upload all → publish)
name: teamspeach-native-x86_64-unknown-linux-gnu
path: artifacts/teamspeach-native-x86_64-unknown-linux-gnu
- uses: actions/download-artifact@v3
with:
name: teamspeach-native-aarch64-unknown-linux-gnu
path: artifacts/teamspeach-native-aarch64-unknown-linux-gnu
- name: Validate packages, create draft, upload, verify remote hashes, publish
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
TAG: ${{ github.ref_name }}
run: |
set -euo pipefail
node scripts/check-version.mjs
cat > notes.md <<'EOF'
Linux x64 and Linux ARM64 (aarch64) are built in CI: tests, offline core check, ELF alignment check
(16 KiB pages for ARM64, including the AppImage runtime), see build-info-*.txt.
ARM64 is checked statically and under qemu, not on Apple Silicon. Packages are not signed.
Windows x64 is built on the developer machine from the same commit and attached separately
(provenance in *-win-x64-local-build-info.txt).
Automatic updates (from the first updater-capable version on): Windows x64 NSIS installation and
Linux AppImage install from this release's latest*.yml / <channel>*.yml feeds after user confirmation;
zip and tar.gz users are notified and replace files manually.
EOF
node scripts/publish-release.mjs artifacts notes.md
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITHUB_REF: ${{ github.ref }}
GITHUB_SERVER_URL: ${{ github.server_url }}
GITHUB_REPOSITORY: ${{ github.repository }}
run: cargo run --locked -p xtask -- publish-release --out artifacts
-68
View File
@@ -1,68 +0,0 @@
# Manual end-to-end proof of the AppImage self-update between two PUBLISHED releases (Linux x64).
# Downloads the older release's AppImage anonymously, runs it in a disposable profile under Xvfb with
# APPIMAGE_EXTRACT_AND_RUN, lets it update itself from git.eeee.moe and checks version + identity afterwards.
# Uses no secrets; never runs on pull requests.
name: update-e2e
on:
workflow_dispatch:
inputs:
from_tag:
description: Older updater-capable release tag (e.g. v0.1.2-rc.1)
required: true
to_tag:
description: Newer release tag the old one must update to (e.g. v0.1.2-rc.2)
required: true
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
appimage-x64:
runs-on: ubuntu-latest
container:
image: node:22-bookworm
steps:
- uses: actions/checkout@v4
- name: System packages (container only)
run: |
set -euo pipefail
apt-get update
apt-get install -y --no-install-recommends ca-certificates curl xvfb xauth libnss3 libatk1.0-0 \
libatk-bridge2.0-0 libcups2 libdrm2 libgbm1 libgtk-3-0 libasound2 libxss1 libxshmfence1 \
libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libpango-1.0-0
- name: Test driver (playwright-core)
run: npm ci
- name: Download the older published AppImage (anonymous)
env:
FROM_TAG: ${{ inputs.from_tag }}
run: |
set -euo pipefail
[[ "$FROM_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "bad tag $FROM_TAG"; exit 2; }
mkdir -p old
curl -fsSL -o "old/TeamsPeach-${FROM_TAG#v}.AppImage" \
"https://git.eeee.moe/TeamsPeach/client/releases/download/${FROM_TAG}/TeamsPeach-${FROM_TAG#v}.AppImage"
sha256sum old/*.AppImage
- name: Self-update end to end
env:
FROM_TAG: ${{ inputs.from_tag }}
TO_TAG: ${{ inputs.to_tag }}
run: |
set -euo pipefail
[[ "$TO_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "bad tag $TO_TAG"; exit 2; }
xvfb-run -a node scripts/update-e2e.mjs --from "old/TeamsPeach-${FROM_TAG#v}.AppImage" --to-tag "$TO_TAG" --out update-e2e-out
cat update-e2e-out/result.json
- uses: actions/upload-artifact@v3
if: always()
with:
name: update-e2e
path: update-e2e-out/
+7 -2
View File
@@ -1,7 +1,12 @@
# dependencies and build output
node_modules/
# Understand analysis intermediates are local; publish only the durable graph and baseline.
.ua/tmp/
.ua/.trash-*/
.ua/intermediate/*
!.ua/intermediate/scan-result.json
dist/
core-bin/
# Native Cargo artifacts
target/
core/target/
# local runtime data, logs and identities
+98
View File
@@ -0,0 +1,98 @@
{
"schemaVersion": 2,
"generatedAt": "2026-11-01",
"title": "Design System: TeamsPeach",
"extensions": {
"shadows": [
{ "name": "context-menu", "value": "1px 1px 2px 0 rgba(0, 0, 0, 0.2)", "purpose": "Official .ts-context-menu shadow; menus, device menus and composer submenus." },
{ "name": "notification", "value": "#000 4px 8px 5px 0 at opacity .25", "purpose": "Official .ts-notification ::after plate shadow for toasts." }
],
"motion": [
{ "name": "tree-pill", "value": "150ms ease-out (32ms while hovered)", "purpose": "Channel pill growth from 7/10 to 4/7 insets." },
{ "name": "action-magnify", "value": "100ms ease-out scale(1.15)", "purpose": "Toolbar and status-bar icon hover." },
{ "name": "stream-controls", "value": "opacity 120ms, transform 80ms", "purpose": "Stream tile control bar reveal." },
{ "name": "toast-entrance", "value": "180ms cubic-bezier(0.16, 1, 0.3, 1)", "purpose": "Single toast entrance; disabled with reduced motion." }
],
"breakpoints": [
{ "name": "pane-compressed", "value": "440px", "purpose": "Official tsv-view-size-category-h-compressed: 10px side padding." },
{ "name": "settings-in-sidebar", "value": "900px", "purpose": "The same settings categories node moves into sidebar resources below this width." },
{ "name": "sidebar-collapse", "value": "200px", "purpose": "Sidebar slot snaps to the 62px rail below this width." }
],
"slots": {
"sidebar": "270px default, 420 max, 52/62/72px rail for Small/Medium/Large",
"server": "500px default, 220 min",
"detail": "flexible, 295 min"
},
"source": "TeamSpeak 6.0.0.5163 installed client: main.css sha256 bc700401d04954d0…, main.js sha256 9d6bea2ee5333086…; extracted values in docs/evidence/official-parity/."
},
"components": [
{
"name": "Filled action",
"kind": "button",
"refersTo": "button-filled",
"description": "Official .tsv-button-filled: blue gradient pill for the primary action.",
"html": "<button class=\"ds-filled\">Connect</button>",
"css": ".ds-filled{font:450 15px/22px 'Noto Sans',sans-serif;padding:4px 20px;min-height:26px;border:0;border-radius:100px;background:linear-gradient(60deg,#0058FF,#1365BB);color:#fff;cursor:pointer}.ds-filled:hover{background:#1c82cc}.ds-filled:focus-visible{outline:2px solid #1588FA;outline-offset:2px}.ds-filled:disabled{opacity:.4;cursor:default}"
},
{
"name": "Toolbar pill",
"kind": "toolbar",
"description": "Official central toolbar: 26px pill on --tsv-bg, icon buttons split by 1px strong-bg lines.",
"html": "<div class=\"ds-pill\"><button aria-label=\"Microphone\"><svg width=\"22\" height=\"22\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\"><rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\"/><path d=\"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21\"/></svg></button><button aria-label=\"Speakers\"><svg width=\"22\" height=\"22\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\"><path d=\"M4.5 9.5v5h3.8l4.7 4V5.5l-4.7 4z\"/></svg></button></div>",
"css": ".ds-pill{display:inline-flex;height:26px;padding:0 20px 0 10px;border-radius:100px;background:#2b3346}.ds-pill button{position:relative;padding:0 10px 0 0;border:0;background:none;color:#fff;cursor:pointer}.ds-pill button:not(:last-child)::after{content:'';position:absolute;right:4px;top:2px;bottom:2px;width:1px;background:#0B1124}.ds-pill button[aria-pressed=true]{color:#CC3838}"
},
{
"name": "Labelled field",
"kind": "input",
"description": "Official ts-text-input: 26px, tsv-bg fill, 1.5px transparent border turning tint on focus.",
"html": "<label class=\"ds-field\">Server address<input placeholder=\"address or address:9987\"></label>",
"css": ".ds-field{display:grid;gap:4px;font:450 14px/18px 'Noto Sans',sans-serif;color:#fff}.ds-field input{font:inherit;min-height:26px;padding:2px 10px;border:1.5px solid transparent;border-radius:4px;background:#2b3346;color:#fff}.ds-field input::placeholder{color:#697A97}.ds-field input:focus-visible{outline:none;border-color:#1588FA}"
},
{
"name": "Settings category list",
"kind": "nav",
"description": "44px rows; selection fill #282F40 with a 4px tint bar and tinted icon.",
"html": "<nav class=\"ds-nav\"><button>Identity</button><button aria-current=\"page\">Audio</button><button>Video</button></nav>",
"css": ".ds-nav{display:grid;padding:8px 10px 8px 20px;background:#2b3346}.ds-nav button{position:relative;font:450 14px 'Noto Sans',sans-serif;min-height:44px;text-align:left;padding:0 20px;border:0;border-radius:4px;background:transparent;color:#fff;cursor:pointer}.ds-nav button:hover{background:#222A3C}.ds-nav button[aria-current]{background:#282F40}.ds-nav button[aria-current]::after{content:'';position:absolute;left:0;top:6px;bottom:6px;width:4px;border-radius:100px;background:#1588FA}"
},
{
"name": "Group tag",
"kind": "chip",
"description": "Server-group name beside a nickname in the tree: header-bg chip, 13px subtitle text.",
"html": "<span class=\"ds-group\">Admin</span>",
"css": ".ds-group{display:inline-block;max-width:14ch;padding:0 5px;border-radius:6px;background:#1C2539;color:#697A97;font:450 13px/17px 'Noto Sans',sans-serif;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}"
},
{
"name": "Settings section",
"kind": "card",
"refersTo": "settings-section",
"description": "Official .ts-widget-wrapper: header-bg, radius 15, 8px 20px padding, 15px semibold title.",
"html": "<section class=\"ds-card\"><h2>Microphone</h2><p>Capture device</p></section>",
"css": ".ds-card{display:grid;gap:16px;padding:8px 20px 20px;border-radius:15px;background:#1C2539;color:#fff;font:450 14px/18px 'Noto Sans',sans-serif}.ds-card h2{margin:8px 0 0;font-size:15px;line-height:19px;font-weight:600}.ds-card p{margin:0;color:#697A97;font-size:13px}"
}
],
"narrative": {
"northStar": "The official TeamSpeak 6 client, value for value",
"overview": "TeamsPeach targets the installed TeamSpeak 6 interface using extracted theme tokens, source component geometry and the three-slot window. The independent name/icon, local offline onboarding and omission of account-bound surfaces are deliberate exceptions. Source matching does not itself prove rendered or functional identity.",
"keyCharacteristics": [
"Navy dark theme (#2b3346 / #222A3C / #121A2C) with #1588FA tint; matching official light theme.",
"Three slots: 270px sidebar (62px rail), 500px server tree, flexible detail pane.",
"Noto Sans at 15/19 weight 450; official row heights 44/40/30/23.",
"Depth from the official background ladder, not shadows."
],
"rules": [
{ "name": "The Source Rule", "body": "Take target values from the installed official client with offsets in docs/evidence/official-parity/; verify actual composition with isolated screenshots and document differences.", "section": "overview" },
{ "name": "The Account-Free Rule", "body": "Omit cloud-only controls (bell, contacts, presence, Setup Chat) rather than showing controls that do nothing.", "section": "components" }
],
"dos": [
"Do keep native caption overlay colours equal to the window-bar token.",
"Do keep stock --tsv-* tokens at (0,1,0) specificity for local theme files.",
"Do document every deviation from the official client in DESIGN.md."
],
"donts": [
"Don't reinterpret or restyle the official look.",
"Don't ship TeamSpeak logos, label artwork or bundle files.",
"Don't claim feature parity from visual parity."
]
}
}
+104
View File
@@ -0,0 +1,104 @@
# .understandignore — patterns for files/dirs to exclude from analysis
# Syntax: same as .gitignore (globs, # comments, ! negation, trailing / for dirs)
# Lines below are suggestions — uncomment to activate.
# Use ! prefix to force-include something excluded by defaults.
#
# Built-in defaults (always excluded unless negated):
# node_modules/, .git/, dist/, build/, obj/, *.lock, *.min.js, etc.
#
# --- From .gitignore (uncomment to exclude) ---
# core-bin/
# core/target/
# identity*.ini
# teamspeach-identity*.ini
# smoke-out/
# smoke-voice-out/
# probe-stream-out/
# loopback-out/
# .env
# .env.*
# .DS_Store
# Thumbs.db
# --- Detected directories (uncomment to exclude) ---
# docs/
# scripts/
# test/
# --- Test file patterns (uncomment to exclude) ---
# JS / TS
# *.test.*
# *.spec.*
# *.snap
# C# / .NET
# **/*Tests.cs
# **/*Test.cs
# **/*Fixture.cs
# **/*.Tests.csproj
# Java / Kotlin
# **/src/test/**
# **/*Test.java
# **/*IT.java
# **/*Spec.kt
# Go
# **/*_test.go
# C++
# **/*_test.cc
# **/*_test.cpp
# **/*_test.cxx
# **/*Test.cc
# **/*Test.cpp
# **/*_unittest.cc
# **/*_unittest.cpp
# **/*_browsertest.cc
# **/*_benchmark.cc
# **/*Benchmark.cpp
# Python
# **/test_*.py
# **/*_test.py
# **/tests.py
# **/conftest.py
# Rust
# **/tests.rs
# **/test_*.rs
# **/*_test.rs
# **/bench_*.rs
# **/*_bench.rs
# Ruby
# **/*_spec.rb
# **/*_test.rb
# **/test_*.rb
# **/spec_helper.rb
# **/test_helper.rb
# **/rails_helper.rb
# Swift
# **/Tests/**/*.swift
# **/Specs/**/*.swift
# Исключения исследования мобильного порта; тесты и исходники остаются в карте.
**/.env*
**/*.pem
**/*.key
**/*.p12
**/*.pfx
**/identity*.ini
**/teamspeach-identity*.ini
**/credentials*
**/secrets.json
**/vendor/**
**/assets/**
**/resources/**
docs/evidence/**
native/compatibility.json
native/native-deps.lock.json
core/THIRD_PARTY_NOTICES.md
LICENSES/denoise-THIRD-PARTY-NOTICES.txt
package-lock.json
.impeccable/**
# Граф и его baseline не являются исходниками приложения.
.ua/**
.understand-anything/**
+4
View File
@@ -0,0 +1,4 @@
{
"autoUpdate": false,
"outputLanguage": "ru"
}
+70603
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
{
"lastAnalyzedAt": "2026-11-10T19:23:30.715637+00:00",
"gitCommitHash": "5ce12714acc306f6055bf1e9db3282c5af7704cb",
"version": "1.0.0",
"analyzedFiles": 372,
"workingTreeSnapshot": true,
"workingTreeFiles": [
".gitea/workflows/android.yml",
"AGENTS.md",
"CHANGELOG.md",
"README.md",
"docs/mobile-port-assessment.md",
"docs/mobile-port-progress.md",
"platform/android/build.gradle.kts",
"xtask/src/main.rs",
"xtask/src/package.rs"
],
"fingerprintBaselineCommit": "a761afaa43dddbdf78c70afb2546c79c3b1289e5",
"note": "Граф актуализирован по незакоммиченному рабочему дереву. Штатный incremental save отказал из-за dirty tree; fingerprints/scan baseline оставлены прежними для следующего воспроизводимого обновления после коммита."
}
+21
View File
@@ -0,0 +1,21 @@
# Работа над мобильным портом
## Native-only архитектура
- Единственный клиент — `native/` (Rust + Slint), протокольное ядро подключается через `core::runtime`. Electron/Node/Chromium UI и npm-сборка удалены; не возвращать их как временный host.
- Сборка, упаковка и smoke выполняются через Cargo/`xtask`. Общие ресурсы клиента находятся в `native/resources/`; версию задаёт Cargo workspace.
- Native-only не означает, что все платформы проверены. Фиксировать отдельно compile/package/runtime и реальные Android/iOS/device результаты; не переносить старые Electron passes в native acceptance.
- Android: выбран полный build/package в Linux CI (`.gitea/workflows/android.yml`); на Windows — разработка и установка APK через Platform-Tools. WSL/Docker/локальный Linux для этого маршрута не требуются; не предлагать их установку по умолчанию. Pinned WebRTC Android source-build остаётся Linux-only на CI, не обещать локальную Windows-сборку простой заменой путей.
- iOS требует macOS + Xcode/Apple SDK и соответствующий signing, локально или на отдельном macOS CI. Android workflow не доказывает iOS-готовность.
- Desktop acceptance gate: до явного подтверждения пользователя о проверенной установленной Windows-версии не выполнять push. После подтверждения зафиксировать desktop-baseline; дальнейшая мобильная работа не должна менять desktop-поведение без отдельного запроса. Изменения общих core/DSP/services проверять на desktop-регрессии; по возможности изолировать mobile-specific код.
- Windows 0.1.7 принята владельцем 2026-11-11 (подключение, канал, двусторонний голос); baseline — `desktop-baseline-0.1.7-20261111`. `main` — проверенная база, дальнейшая Android/iOS-разработка — `feature/mobile-port`. Приёмка Windows не означает Android/iOS acceptance; не менять desktop-поведение без отдельного запроса.
## Переносимая память
- В начале новой сессии прочитать `docs/mobile-port-progress.md` и относящиеся к задаче разделы `docs/mobile-port-assessment.md`. Эти документы — переносимая память проекта, а не память чата.
- Сопоставить записанную ревизию с текущим HEAD и рабочим деревом, включая staged, unstaged и относящиеся к задаче untracked-изменения. Перепроверять затронутые выводы и ссылки, а не перечитывать весь репозиторий.
- Использовать `codebase-knowledge-builder` при изучении новой подсистемы или существенном изменении ранее изученной; не запускать полный разбор ради мелкой правки. Существенные выводы подтверждать исходниками, отделяя факты, предположения и неизвестное.
- После существенных изменений обновлять соответствующие знания, ссылки на исходники, ревизию и сведения о реально проведённых проверках. Статический разбор не доказывает работоспособность на Android/iOS.
- Перед завершением сессии обновлять краткую передачу состояния в `docs/mobile-port-progress.md`, если появились новые решения, результаты или блокеры; не дублировать в ней весь разбор.
- Не перезапускать Understand-Anything каждую сессию. Использовать `.ua/knowledge-graph.json` как навигацию; обновлять при изменении архитектуры, предпочитая инкрементальное обновление. Проверять метаданные и не выдавать старый граф за актуальный. Автообновление графа оставлять выключенным без отдельного разрешения.
- Исследовательская стадия не разрешает менять исходники, запускать приложение, сборку, установочные скрипты или тесты. Для этого требуется отдельное разрешение. Не читать секреты и не помещать их в документы или граф; сохранять чужие инструкции и изменения.
+657 -1
View File
@@ -1,6 +1,661 @@
# Changelog
## 0.1.2 — unreleased
## Unreleased
- 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
conversion cannot invalidate exact patch checksums; expected lock hashes remain unchanged.
- Added a manual Android CI route producing separate full-feature ARM64 test-harness APK and unsigned
production APK/AAB bundles with source/build/dependency receipts. Windows developers do not need WSL.
Android packaging keeps offline Gradle by default; CI opts into dependency resolution explicitly and
isolates each package's Gradle outputs. CI runner provisioning and device acceptance remain unverified.
- Removed the Electron application, npm manifests and browser-only test/build tooling. Rust/Slint
is now the only application; native resources and versioning no longer depend on the removed tree.
Retained native profile migration and diagnostic core CLI. This cutover is not mobile runtime acceptance.
- Started the native implementation with one Cargo workspace and lockfile and pinned Rust 1.96.0.
Core/DSP dependency resolutions are preserved; the later native-only cutover removes the reference host.
- Added the native compatibility inventory; entries remain pending, not claims of feature completion.
Initial Slint software and Skia windows were exercised with a real pointer Close action;
this does not establish native voice, video, mobile support or whole-client migration completion.
- Extracted the protocol core into an embedded library with validated typed commands, joined session
lifetimes, generation-stamped events, bounded PCM and capture guards at the actual UDP-send boundary.
Diagnostic stdio remains independently usable for core inspection.
- Ported native profile import, local stores and session-bound file/icon/snapshot services. Imports retain
the original profile, preserve identity keys/UIDs and require bookmark passwords once again. Native
secret/preference pair commits recover interrupted writes; unknown staging directories are never discarded.
Windows isolated DPAPI and migration/restart smoke passed; other OS key stores and live mutations remain
separate verification gates. Snapshot format stays 0.0.1; native About labels legacy notices as historical.
- Added worker-owned CPAL audio, bounded timestamped callback queues, drift-aware Rubato conversion,
integrated Sonora AEC/NS/AGC and independent notification sinks. Capture/output revocation survives
queue congestion; source expiry remains attached through resampling to hardware presentation.
Controlled DSP/queue/permission and native worker smoke passed (generated PCM, no physical devices).
Official-peer voice, acoustic echo cancellation and mobile/Asahi hardware remain unverified.
- Added pinned source-built native WebRTC provisioning, checked desktop/mobile capture adapters and
generation-bound TS6 viewer/publisher state machines. Windows x64 CXX bridge compilation passed.
The production software decoder factory decoded synthetic H264 High, AV1, VP8 and VP9 fixtures;
all four 64×48 I420 outputs exactly matched independent FFmpeg decoding. Sustained native playback,
official TS6 peers, physical capture, hardware decode and other platforms remain separate gates.
- Proved a device-free native PeerConnection loopback through the real sender/decoder/display path
(13 decoded frames, 12 presented, terminal cleanup). Isolated WebRTC Opus symbols from the voice
core's existing codec without weakening linker checks or rewriting unrelated assembly objects.
- Rebuilt Privacy, Video, Notifications and About in the original section order. Unsupported account,
telemetry, Cisco/backend and content-report options are explicitly unavailable, never fake preferences.
Working Chromium decoder controls and installation/project details moved to linked subpages with
back-focus restoration. Report Issue uses the project's verified issue list through the external-link guard.
- Preserved native decoder-policy restart, notification overrides, trusted-site management and local
changelog/license navigation. Corrected narrow Russian update-row overlap without hiding status.
- Restored original selector wrapping, selected-preview radius clipping and whisper action tints.
Permission lists now reserve their source toolbar space and wrap badges without losing long-name
truncation; private-info descriptions and empty group states use the source sizing and spacing.
- Fixed channel right-click opening Whisper settings and silently staging a target. The normal channel
menu now leaves the current view and whisper state unchanged; only its explicit Add to Whisperlist
action stages the channel, behind the existing connection/session validity guard.
- Moved identity export and UID copy into the selected identity's context menu. Export keeps its
private-key confirmation. Disconnected nickname edits use identity Details; connected nickname
edits use the own-client information header. Removed the duplicate bookmark settings manager;
bookmarks remain editable in the sidebar.
- Language changes are saved for restart, with a cancelable restart confirmation. File-transfer
settings use the source defaults, shared rate limits and per-channel concurrency limits.
- Added generation-bound group deletion and explicit group/channel permission removal, plus the
channel icon picker. A refused icon after successful channel creation cannot create the channel
a second time; stale form/session responses do not apply to another view.
- About reports actual build metadata. Corrected identity slider layout, device-selector caption
overlap, broadcast tab/thumbnail geometry and transfer-row spacing. Migrated affected smoke scripts.
- Matched the detail header's source flex grouping, restored full-height administration panels and
bottom pagination, corrected client-list wrapping, group-badge spacing and server-info typography.
Audio device captions and broadcast title chips now use measured original text metrics.
- Whole-client pixel parity is not established; reference comparisons retain their original thresholds.
## 0.1.7 — 2026-11-02
- Matched light-theme toolbar/header/composer icon colors, header separators and chevron placement
to the installed reference. Corrected narrow chat width and input placeholder spacing.
All eight main-screen EN/RU, dark/light and wide/narrow fixture comparisons passed; this does not
establish whole-client parity or native-platform interoperability.
- Replaced the plain chat textarea with one local CodeMirror editor and the persisted Rich Text Editor
toggle. Hybrid preview uses the existing safe TS Markdown renderer; switching modes retains text,
selection and undo, while switching conversations isolates draft history. Toolbar/slash/emoji edits,
Enter/Shift+Enter, IME and refused-send preservation were exercised in the packaged offscreen app.
Constructed stylesheets keep the application CSP strict; no inline-style exception was added.
- Added the original editor's bold, italic, link, inline-code and code-block keyboard bindings.
Corrected the notification output selector's missing bottom margin using the original component rule.
- Matched list/quote authoring controls: Shift+Enter continuation, ordered/task item transitions,
Tab/Shift+Tab indentation, empty-item exit and Escape-then-Tab focus escape. Fenced code is not
mistaken for a list; quoted fences retain their quote prefix.
## 0.1.6 — 2026-11-02
Current development snapshot; full visual parity and native Asahi verification remain unfinished.
Version 0.1.5 was not published: CI rejected an empty changelog section.
- Added source-style advanced notification controls with independent persisted event choices,
confirmation before hiding advanced controls and single-event expansion.
- Corrected server-tree painting against paired hidden captures. Remaining light-theme,
narrow-layout and composer differences are not claimed fixed in this release.
- Rebuilt Identities around the original selector, inline creation/rename, selected-identity Details,
security-level controls and related bookmarks. Fixed default-profile UID leakage into selected Details,
selector popup initialization and the final improvement level briefly reverting during a list refresh.
Export and the explicit current-server nickname action remain available.
- Replaced raw File Transfer number fields with source-style keyboard/step controls that retain focus
and drafts through serialized saves. Native folder/copy restrictions, shared limits and safe defaults remain.
- Added notification category switches with real sound-policy gating, preserved per-event states and
independent event logs; concurrent state edits are serialized.
- Added nested bookmark folders with inline creation, rename, ordering, move/duplicate menus and
confirmed subtree deletion, using validated local preferences rather than a separate bookmark store.
- Extended bookmarks with a per-connection nickname, initial channel, session-bound channel drops,
startup connection and input-only startup mute. A nickname override never changes the stored identity.
- Bookmark passwords use OS-protected encryption, bound to address and server/channel purpose. Plaintext
is never persisted; Linux basic_text/unknown storage is refused. Stale metadata writes cannot overwrite
or resurrect a password, and native key-store interactions revalidate the window, bookmark and connection.
Explicit reveal, same-address duplication, address-change cleanup, restart and forgetting a password
after storage becomes unavailable were exercised with real Windows DPAPI. No live server join was performed.
- Startup bookmark enumeration is one-shot in main, so a renderer reload cannot start a second set of
connections. Automatic microphone mute is applied before connecting and never changes speaker mute.
- Added Privacy with trusted-site management and remembered confirmations; reset and concurrent
confirmation changes are serialized so an older save cannot overwrite a later reset.
- Removed the mistakenly added Remote Apps integration to honor the owner's explicit exclusion:
no listener, authorization IPC, settings page, remote-button capture or WebSocket production dependency.
- Added account-free local UID contacts and public badge artwork display. These are not myTeamSpeak
contacts, owned-badge management, cloud presence or offline messaging.
- Added server icon management bound to the listing's connection generation. Reconnecting invalidates
mutation grants; old icon/snapshot transfers cannot cancel a new session's reused transfer ID.
- Added the four-level noise-reduction control with persisted per-input settings. Processing remains
an independent implementation, not a claim of identity with TeamSpeak's private native DSP.
- Fixed key recording in the contents-layout settings host by checking the enclosing panel's visibility.
Packaged verification covers saving the binding and retaining it across an application restart.
- Isolated Mermaid rendering from the privileged application renderer; nested renderers cannot acquire
media/presentation permissions. Local diagram/math rendering and hostile-content rejection were exercised.
- Corrected smoke polling to await asynchronous IPC/import predicates instead of accepting a Promise
as a satisfied condition. Persistence checks now wait for actual saved state.
- Fixed full Changelog and Open Source Licenses pages rendering arrays as text instead of appending
their DOM nodes. Added a real offscreen navigation smoke covering document text and back-focus restoration.
- Whispers follow the original manager: Live Preview highlights the current list's clients and channels in
the server tree (resolved from the current snapshot only), "Switch to Server and Overlay" shows the list
next to the microphone's server, and the status bar Whisper History lists received whispers with Delete.
Replies and avatars use only entries whose client id and UID are still on the same server session.
- Key Bindings follow the original page: "Require exact key match" toggle, named profiles (inline
"New Profile Name" editor, rename, choose, Activate, delete of inactive profiles) and every official
hotkey action, each running the app's real operation. Push-to-mute stops sending without touching your
mute choice; global push-to-talk survives window focus loss while local keys still release on it. Go Live
opens the broadcast source chooser instead of guessing the focused application. Bindings can be in-window,
or global; with exact matching off, global keys also register their
extra-modifier combinations. keybinds.json moves to version 2; version 1 whisper bindings migrate unchanged
into one active profile and the original file is kept as `keybinds.v1-<time>.json`.
- Reworked the interface against the actual installed TeamSpeak frontend rather than the earlier
hand-reconstructed component sheet: original non-brand SVG artwork, Noto Sans 2.013, channel and
client chat layouts, membership event rows, sidebar actions, in-pane administration, settings
dropdowns/sliders and the two-stage broadcast dialog. Independent branding and account-free
behavior remain. Artwork provenance does not grant redistribution rights.
- Corrected sidebar group geometry and moved New Connection into its own account-free action slot;
bookmark add/search/disclosure retain their real persistence/navigation behavior. Language and sidebar
icon-mode selectors use original local artwork, content-based widths and restored keyboard focus.
Audio device captions use the observed system-default alias, not an inferred physical device.
- Matched device-field, VAD selector, slider, record-test and display-preview geometry to source values.
Fixed the chat spacer to use the composer's content-box height, removing a two-pixel full-history offset.
- Preserve a bottom-pinned chat on window reflow without forcing readers of older history to the end.
The regression reproduced a 119px gap after narrowing; the packaged fix retains a zero gap and
separately preserves the history reader's position. The paired harness retains this behavioral check.
- Match chat scrollbar safe-area width and system-event wrapping to the actual original renderer;
restore the localized empty-chat prompt with real draft/send-state visibility. Narrow composer tools
now overflow into working ordered menus rather than clipping. Settings categories occupy the original
narrow-sidebar position below Servers/New Connection, with source-sized previews and server columns.
- Correct empty-chat prompt geometry with the measured 22px glyph and the secondary-pane contrast
background. The focused dark/en wide-screen chat region passes; the whole screen still fails other regions.
- Use the original Russian bookmark-help wording (`Добавьте`), preserving the same save/connect behavior.
- Run both sides of visual QA with Electron's normal acceleration policy. Earlier reference captures
forced software rendering while the product did not; those comparisons remain historical evidence,
not directly comparable pixel baselines for the corrected capture policy.
- Actual whole-screen comparison still does not meet the 1:1 acceptance criterion. The refreshed 168-pair
run has no blocked captures but no fully passing screen pairs. Viewport-only timestamp comparison and
nested native-caption exclusions now avoid earlier harness false positives; thresholds are unchanged.
See `docs/evidence/official-parity/qa-parity-harness.md` for build-specific results and remaining differences.
- Initialize custom controls explicitly at renderer startup, not when audio/notification modules
import the slider helper. The Node suite and focused packaged chat/control smoke checks pass;
this does not establish complete visual or native platform parity.
- Added local TS6 theme extensions (Settings → Appearance → User Theme): the official `package.json`
schema, `<identifier>//<variant>` selection, stock fallback and a five-minute list cache with Reload.
Files load only through the restricted `tsext:` scheme (selected variant CSS, fonts, images, previews);
`@import`, remote URLs, links and path traversal are rejected and reads are bounded. Account-free; no
store or Remote Apps. Compatibility covers the package format and `--tsv-*` tokens, not official DOM
class hooks.
- Added account-free local identity management: additive import, selected-identity export, per-identity
names/nicknames, default and bookmark selection, guarded deletion, and resumable/cancellable bounded
security-level improvement. Active connections retain their chosen identity.
- Added simultaneous connection records with one isolated native core per server, explicit viewed/input
connection routing, connection-local chat, streams, recording and administrative operations.
- Added channel/server administration, local whisper lists and held targets, general legacy file browsing
and transfers, server snapshots, recording, notifications, and OS-specific local settings. Available
functionality and unverified native protocol branches are listed separately in the compatibility matrix.
- Migrated audio preferences to per-device capture/playback profiles and the official piecewise dB fader;
existing voice choices are converted on load. Automatic/hybrid/level activation, PTT release delay,
notification routing and independent processing are implemented without claiming native-DSP identity.
- Added connection/identity-scoped disk chat history, independent drafts/unread state, local rich text,
emoji/math/diagrams and server-file links. Remote images require explicit consent; account-only Matrix
editing, reactions and read receipts are not included. Local vendor assets carry redistribution notices.
- Recording finalization preserves dropped-tail timing and counts actual published bytes. Notification
event overrides and the event log are independent. Theme loading rejects directory escapes and remote
content; Small/Medium/Large and compact/detailed appearance settings use source-backed values.
- File Transfer settings apply app-wide directional concurrency and pacing limits across server tabs,
including snapshot transfers. The remembered destination is main-approved; no renderer-provided host
path is accepted and an unavailable folder never silently changes the destination.
- Unversioned legacy sidebar widths migrate lazily to the server-pane width for the three-pane layout.
Reading preferences does not rewrite the file; the next successful save records layout version 2,
while existing new-layout choices remain unchanged.
- Added a bounded ten-second in-memory microphone record/listen test using the selected output device.
It never sends test audio to a server; Finish, device/privacy changes and closing settings clear the clip.
- Bounded microphone MessagePort backlog to 200 ms using capture-context sample timestamps; renderer
stalls no longer replay older queued speech. Capture DSP preferences and channel bitrate mapping are
unchanged. Hidden 190-second speech/silence captures and a real Opus encode/decode matrix were measured;
natural-microphone and official-client subjective quality remain unproven.
- Saved servers now use an always-visible inline heading/chevron disclosure, with persisted collapsed
state; toggling the heading never connects or navigates. Removed the old detached bookmark toggle.
- Connection information now uses vertical labelled groups instead of one column per protocol field,
with locale-aware duration, byte, rate and loss units, long-value wrapping and expandable raw records.
Member menus use measured pointer/keyboard anchors, side flipping and viewport bounds, reposition on
resize and dismiss on background scrolling rather than retaining a stale sidebar offset.
- The flat application caption follows the official 44 px palette. Windows/Linux window-controls overlay
and macOS traffic lights remain OS-owned; offscreen fixtures do not claim native Snap, fullscreen,
picture-in-picture or focus behavior.
- Application chrome no longer selects text during clicks and drags; chat, inputs and useful content remain
selectable. Removed the redundant audio-muted banner and transmission-mode/key header hint without
changing mute/deafen or push-to-talk safety. The host banner now sits behind the server header card.
- Added separate channel-member collapse chevrons with compact avatar summaries and per-server persistence,
plus a bounded sidebar divider supporting pointer and keyboard resize/reset.
- Watched screen shares now have independent tiles, controls and native picture-in-picture windows. Full
screen and PiP preserve their media sessions; stopping one view leaves its siblings running. The upper
stream stage can be resized or collapsed independently of chat, with saved layout preferences.
- Stream players now put the picture first: large resizable video above chat, a small name overlay, and
controls over the picture on hover or keyboard focus instead of a permanent footer. Live statistics move
into an accessible EN/RU details disclosure. New profiles start with a larger stage; existing saved sizes,
independent streams and the broadcaster's separate local-preview controls are preserved.
- Added target-bound member context menus with server-derived capability hints, explicit unknown/denied
states, guarded confirmations for moderation and permission/group changes, native bounded avatar
selection, and visible backend errors. Menus reject stale identities and connection generations.
- Per-participant voice volume uses -200..+10 dB and an independent Mute control. Reset restores 0 dB and
unmutes. Explicit committed modifiers persist by UID; session mute remains connection-local.
- Added explicit source selection, private preview and Start/Stop P2P publishing, with a muted local tile,
quality targets, per-viewer admission and a transmission-scoped UID allowlist. Capture remains opt-in;
native OS/portal support and live official-client interoperability require separate platform evidence.
- Added selected-application audio adapters for Windows WASAPI process trees and Linux PulseAudio /
pipewire-pulse streams, with bounded IPC and outgoing per-app/master gain. macOS application-audio capture
remains unavailable. The native combined capture-to-WebRTC path is not claimed proven by UI fixtures.
- Disposable UI checks now run hidden and offscreen by default, with separate profiles, denied physical
capture/permission prompts and native dialogs disabled unless a test supplies a fixture answer. The
shared launcher asserts invisible/unfocused/nonfocusable offscreen state and mutes webContents.
Packaged tests verify bundled main-process bytes match the current offscreen-safe source before launch.
- Channel clicks now browse the channel without moving voice; double-click or the explicit Join channel
action moves voice. The header explains when the channel chat still belongs to the current voice channel.
- Available screen shares appear above chat with explicit Watch actions, including multiple announced
streams; the old member-row Watch buttons are replaced by stream indicators. Browsing never subscribes.
Unavailable discovery and denied joins remain visible errors rather than fabricated streams.
- Allowed HTML fullscreen requests from the app origin while retaining the existing camera/screen-capture
restrictions. The player uses native full screen, an exit control and native Escape, keeps the same media
session, and exits on stop/end/disconnect. Request/exit failures are reported, and teardown only exits
fullscreen owned by the stream player.
- Added an isolated Electron stream-UI/media smoke with EN/RU and light/dark captures. Synthetic directory
events and local real WebRTC media are explicitly distinguished from TS6 server interoperability.
- Fixed memory growth during microphone restart/test cycles: capture processors acknowledge shutdown,
release their ports and track listeners, and close their own capture context without interrupting the
persistent playback context. Partial audio initialization is rolled back and can be retried.
- The active chat DOM now follows the existing 500-message history limit, preserving message headers and
the visible scroll anchor. Reconnect history retains server labels instead of entire server snapshots.
- Server image caching releases obsolete avatars, banners and icons when the snapshot no longer refers
to them, including downloads that finish after removal; current resources are not arbitrarily evicted.
- Core startup failures now release child/log/readiness resources on process close, including failures
without an exit event. Core stderr applies lossless log-stream backpressure.
- Screenshare lifecycle: duplicate/unknown per-stream stop notifications no longer remove sibling shares;
cancellation stops queued ICE/offer work, releases closed peer connections, and avoids retaining stopped
sessions through empty translated-label callbacks. Added isolated generated-media pipeline/lifecycle
evidence; no codec, bitrate or throttling policy change, and no claimed FPS-cap fix.
- Added reproducible disposable-profile Electron memory workloads with generated/fake audio, native heap
and process memory evidence, and regression coverage for capture cancellation, chat and image ownership.
- Second lifecycle audit: obsolete pending image downloads no longer expose revoked URLs when a cache
key returns (A→B→A); reused client rows reload avatars when UID changes. Stream discovery ignores old
responses after newer announcements, client/channel changes or stream restarts while preserving current
failures and completing fresh discovery. Delayed output/fullscreen failures cannot report errors for
ended or replaced viewing sessions. Added disposable real-renderer interleaving and generated-WebRTC
callback regressions; the live 20 fps report remains unexplained, with no performance-policy change.
- Audio/core failure ownership: capture-processor errors stop the microphone; failed context closure
retains ownership until an explicit recovery succeeds. Explicit playback recovery settles failed
diagnostics and preserves applied volume/output selection. Core log-destination failures report an
error without crashing main or stalling stderr; exited cores reject new commands while final replies
and events drain before close.
## 0.1.4 — 2026-10-24
Version 0.1.3 was tagged but never released: a race in the transmit-mode handshake was found before
publication (an older answer could re-enable forwarding while a newer mode change was still pending). It is
fixed here.
- Added voice activation as a third transmission mode next to push to talk and the open microphone
(Settings → Audio → Voice transmission, sensitivity High / Normal / Low). The core decides locally with
the earshot voice detector (a small embedded neural network, no cloud service, no speech recognition) on
audio that has already passed the microphone processing (noise suppression, echo cancellation, gain
control). It sends from about 100 ms before a detected onset until about 400 ms after the last detected
speech. After connecting, unmuting or changing the mode the gate cannot open for 200 ms, but every frame
since then is kept (up to 300 ms) and sent with the first spurt, so the first word is complete; that first
spurt therefore starts up to 300 ms late (later spurts carry the normal 100 ms). Muting, deafening, disconnecting, a channel or codec change and
a server talk denial discard what the detector heard. Push to talk and the open microphone are unchanged;
stored settings keep their mode, and new profiles still start with push to talk.
- The transmission mode moved from Settings → Keyboard to Settings → Audio; the push-to-talk key stays in
Keyboard. The microphone test explains that it only shows the input level and never transmits.
- The renderer forwards microphone audio only after the core has confirmed the selected mode; only the
answer to the latest request counts (older answers, also from a restarted core, are ignored), and a failed
mode change is shown and nothing is sent until it is applied. Renderer diagnostics now count frames
forwarded to the core, not "sent" frames; whether voice is sent is the core's transmitting state.
- Fixed: a preference write failure no longer changes the in-memory value the app keeps using.
- ARM64 CI runs the core unit tests (voice detector, resampler, identity, codecs) under qemu-aarch64
(emulated, not native hardware).
## 0.1.2 — 2026-10-24
- Fixed: Settings → Audio listed only the system default device. Electron reports the app origin as
`app://teamspeach/` and the permission check compared it with `app://teamspeach`, so Chromium withheld
@@ -20,6 +675,7 @@
- Replaced the application icon assets with an original peach silhouette on a transparent background,
including PNG assets and a seven-size Windows ICO. The reproducible Electron export now renders the
SVG directly to an alpha-enabled canvas instead of capturing a window, avoiding captured scrollbars.
The start, error and onboarding screens show the same icon asset instead of a separate inline drawing.
- Added an English-default interface with selectable Russian, backed by shared catalogs for the renderer
and native identity dialogs. Repository-authored documentation and technical diagnostics are English;
historical captures and server-provided content remain unchanged.
Generated
+10093
View File
File diff suppressed because it is too large. Load diff
+47
View File
@@ -0,0 +1,47 @@
[workspace]
resolver = "3"
members = ["core", "dsp", "native", "xtask"]
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"
edition = "2024"
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.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.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 }
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.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.19.1" }
[profile.release]
lto = "thin"
codegen-units = 4
+253 -53
View File
@@ -1,69 +1,269 @@
# Design
---
name: TeamsPeach
description: Native TeamsPeach's account-free visual contract, derived from TeamSpeak 6 reference evidence.
colors:
tsv-bg-dark: "#2b3346"
tsv-bg-light: "#f5f5f5"
tsv-shaded-bg-dark: "#222A3C"
tsv-shaded-bg-light: "rgb(235, 235, 235)"
tsv-header-bg-dark: "#1C2539"
ts-new-header-bg-dark: "#121A2C"
tsv-contrast-bg-dark: "#0C1326"
tsv-contrast-bg-light: "#C9D9E5"
tsv-deviant-bg-dark: "#1E2538"
tsv-deviant-bg-light: "#d3d5de"
tsv-side-bar-bg-gradient-bottom-dark: "#1D2537"
presence-separator-presence-dark: "#171C2A"
strong-bg-dark: "#0B1124"
tsv-tint-dark: "#1588FA"
tsv-tint-light: "#5DA1CB"
tsv-tint2-light: "#22658f"
tsv-font-color-dark: "#FFFFFF"
tsv-font-color-light: "#1a1a1a"
tsv-font-subtitle-color-dark: "#697A97"
tsv-font-subtitle-color-light: "#445d77"
ts-third-font-color-dark: "#bbd6f3"
tsv-error-color-dark: "#CC3838"
tsv-error-light-color-dark: "rgb(255, 130, 130)"
tsv-away-color-dark: "#FF8B04"
presence-online-dark: "#17f78d"
tsv-online-color-dark: "#13F78D"
settings-highlight-bg-dark: "#282F40"
ts-tree-channel-bg-start-dark: "#192031"
ts-tree-channel-bg-end-dark: "#1D263A"
ts-tree-badges-bg-dark: "#222A3B"
tsv-chat-remote-bg-dark: "#697a97"
tsv-chat-self-bg-dark: "#0C1326"
ts-chat-system-message-bg-dark: "#131824"
ts-chat-system-message-text-color-dark: "#acacac"
tsv-chat-link-color: "#081cbd"
tsv-preview-bg-light: "#bccbeb"
ts-menu-action-color: "#8ac5fc"
tsv-separation-border-color-dark: "#1D1F20"
tsv-scrollbar-bg-dark: "#0B111D"
tsv-slider-track-bg-dark: "#131824"
ts-checkbox-bg-color-dark: "#0c0d0f"
tsv-commander-color: "#daa520"
typography:
body:
fontFamily: '"Noto Sans"'
fontSize: "15px"
lineHeight: "19px"
fontWeight: 450
content:
fontSize: "14px"
lineHeight: "18px"
small:
fontSize: "13px"
lineHeight: "15px"
large:
fontSize: "16px"
lineHeight: "19px"
title-small:
fontSize: "24px"
lineHeight: "28px"
fontWeight: 700
rounded:
small: "2px"
base: "4px"
large: "8px"
xlarge: "10px"
xxlarge: "15px"
xxxlarge: "20px"
pill: "100px"
spacing:
v-minimal: "2px"
v-small: "4px"
h-minimal: "5px"
v: "8px"
h-small: "10px"
v-large: "16px"
h: "20px"
h-large: "40px"
components:
button-filled:
backgroundColor: "linear-gradient(60deg, #0058FF, #1365BB)"
textColor: "#FFFFFF"
rounded: "{rounded.pill}"
padding: "4px 20px"
settings-section:
backgroundColor: "{colors.tsv-header-bg-dark}"
textColor: "{colors.tsv-font-color-dark}"
rounded: "{rounded.xxlarge}"
padding: "8px 20px"
---
Documented from the shipped interface (`app/renderer/styles/app.css`, `index.html`) — this records what is
built, it is not an aspiration. Mode: **Operate**. Direction: the category standard of voice-chat clients,
an engineering choice for a familiar working tool, executed with a restrained peach accent. The only
owner-pinned visual reference is the TeamSpeak 6 settings screenshot that the settings layout follows.
# Design System: TeamsPeach
## Overview
**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 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.
Source matching, screenshot similarity and functional parity are separate evidence claims; this document
is the retained implementation contract, not proof that every native pixel or feature matches.
The product name and application icon stay TeamsPeach's own. Retained source-derived fonts and sounds,
and historical non-brand pictograms, have provenance/redistribution limitations in `LICENSES/`.
The official JavaScript application and removed browser implementation are historical references only,
not product runtime dependencies. Native cutover does not establish visual or functional acceptance.
## Colors
Dark is the default for new profiles; light follows the official light module. Native stock token data
and the supported user-theme importer preserve the dark/light contract without a browser cascade.
Supported declaration order/specificity and `!important` are handled as data; see `docs/themes.md`.
Blue `--tsv-tint` (#1588FA dark, #5DA1CB light; `--tsv-tint2` #22658f light) marks own nickname,
selection outlines, active toggles and primary actions; green (`--presence-online`) marks talking/online
and enabled toggles; red (`--tsv-error-color`) mutes and destructive actions; orange
(`--tsv-away-color`) away and warnings. Secondary text is `--tsv-font-subtitle-color`; client names
in the tree use `--ts-third-font-color` (#bbd6f3).
## Typography
Noto Sans variable files version 2.013 from the installed client are bundled under
`native/resources/fonts/`, with SIL OFL 1.1 in `LICENSES/NotoSans-OFL.txt`. Preserve normal, italic and
oblique source semantics where the native font backend supports them. Body 15/19, content 14/18,
small 13, header titles 24/28 bold. Channel labels use 14px normal; client names use 14px semibold.
Chat names use the source hash/contrast colour calculation, with 16/19 message text and 13/15 events.
## Layout
- Two columns: sidebar `clamp(280px, 27vw, 390px)` (server header, host banner, channel tree, own-status
footer) and a workspace (connect form, or channel header + optional stream viewer + chat, or settings).
- Tree rows: channels with `#`/lock glyph, server channel icon at the right, server banner as a row
background fading from the sidebar colour; members indented under channels with avatar/status dot,
nickname (never truncated before group labels), server-configured group labels, mute/away/recording
flags, group icons and country code, and a pill-shaped Watch button for streamers.
- Settings follow the owner's pinned reference: the sidebar's room area is replaced by category navigation
(Back to server, User / Application / Information groups, active item with an accent bar and tint),
the workspace shows the selected category as titled cards (`.card`, 12 px radius) with an expandable
Details area for advanced video information. The connection, voice footer and any stream keep running.
- Saved servers sit above the tree as a compact list (name, address, action: Connect / Switch /
Connected); a bookmark button in the server header shows or hides it.
- Stream viewer: black stage with the video contained, dark control bar (title, codec · resolution · fps,
mute, volume 0–100 %, fullscreen, stop). Overlay text explains every non-live state.
The desktop target is the official three-slot frame (source component names below are historical
geometry labels, not required DOM selectors):
## Colour
1. **Sidebar**, 270px default, max 420; dragging below 200 collapses it to the 62px rail.
Header gradient #121A2C → #1D2537, activity rows 44px with an always-visible 8px-radius pill inset
10px (4px gap), group captions 13px subtitle, footer 55px with a 3px separator inset 20px.
2. **Server pane**, 500px default, min 220: 44px window bar (#121A2C) carrying the toolbar
pill (26px, `--tsv-bg`, 1px `--strong-bg` separators) with microphone and speaker; separate Away action; a 10px
inverse fillet; the server tree on the 25° gradient (#252F44 → #2E374C); the 92px server header card;
channel rows 44px with a 30px pill (inset 7/10, radius 9, 1.5px outline, channel background gradient
on by default); client rows 40px with 33px avatars and 23px status plates; the 55px status bar with
40px side padding.
3. **Detail pane**, min 295, body `--tsv-shaded-bg`: 44px window bar reserving native caption
integration, 71px content header (38px icon, 24/28 bold title, segmented mode switch), 4px separator, the
stream stage, chat log and composer.
Restrained strategy: warm neutrals plus one accent; state colours only where they mean something.
Settings occupy the main and detail slots as the official settings activity does at ≥900px: category
column `clamp(30ch, 20vw, 50ch)` with 44px rows, `--settings-highlight-bg` selection and a 4px tint bar;
pages max 640px wide with section cards (`--tsv-header-bg`, radius 15, padding 8px 20px, 12px apart).
Below 900px retain category navigation without losing settings drafts/focus. Small/Large use the official
token modules (53225/68865), not browser zoom; collapsed rail widths are 52/62/72px. Compact/mobile
adaptation preserves usable targets, safe areas, IME and an independent voice strip; it is not desktop
pixel-parity evidence. Native caption integration retains the 44px design target where supported.
| Token | Light | Dark | Use |
|---|---|---|---|
| `--bg` | `#f6f3f0` | `#1b2029` | window ground, settings background |
| `--surface` | `#fffdfb` | `#242b37` | workspace, inputs, settings cards |
| `--sidebar` | `#eee9e4` | `#1e242e` | sidebar, settings navigation |
| `--sunken` | `#e6e0da` | `#171b23` | footer, UID, group labels |
| `--text` / `--text-2` / `--text-3` | `#221c18` / `#5e544d` / `#776c64` | `#e7ebf2` / `#aab3c2` / `#8e98aa` | text hierarchy |
| `--accent` | `#b24f26` | `#f09a6c` | primary buttons, selected tab, own name, focus |
| `--accent-soft` | `#fbe2d4` | `#3a3033` | current channel, active settings category |
| `--peach` | `#f3a37c` | `#f3a37c` | brand mark |
| `--talk` | `#1f8a5a` | `#4fcf8e` | talking indicator, PTT held |
| `--danger` | `#b3261e` | `#f08b82` | mute/deafen active, errors |
Resize handles are invisible 9px strips centred on each pane edge, tinted at 50% while focused or
dragged. Native window/caption colors follow the window-bar palette through real platform integration.
Theme follows the choice in Settings → Appearance (dark by default for new profiles, independent of the OS;
Light and System are selectable; implemented through Electron
`nativeTheme.themeSource`, applied before the window is created, so `prefers-color-scheme` stays the single switch). The dark palette uses the
blue-gray surfaces of the owner's reference (`--bg #1b2029`, `--surface #242b37`, `--sidebar #1e242e`).
Selection, caret, scrollbars and focus rings use the palette.
## Elevation & Depth
## Type
Depth comes from the official background ladder (contrast < header < shaded < bg), not shadows.
Context menus paint `linear-gradient(#0B1124, #222C41)` at 0.8 behind a 4px blur, radius 8, shadow
`1px 1px 2px rgba(0,0,0,.2)`. Dialogs use the modal container (contrast-bg, 1px tint2 border, radius 8)
over a 25% contrast-bg wash with 2px blur. Notifications use the 15px-radius gradient plate.
Stream tiles have a 2px `--tsv-bg` border and radius 8; their 26px control bar slides in on hover.
System UI stack (`system-ui, -apple-system, "Segoe UI", "Noto Sans", Ubuntu, Cantarell, …`), 14 px base,
line-height 1.45; headings 600–650 weight at 17–24 px; monospace only for the UID and codec lists (data).
Tabular numerals for counts, times and statistics.
## Shapes
Radii follow the official scale: 2 (toolbar buttons), 4 (fields, chips), 8 (menus, tiles, composer,
dialogs), 9 (tree pills), 10 (server card, event rows, selects), 15 (settings sections, theme tiles,
notifications), pill (toolbar, filled buttons, segmented controls).
## Components
Buttons (primary, default, ghost), 34 px icon buttons with `aria-pressed` states, fields with labels above,
radio/checkbox choices with accent colour, range sliders, chat tabs with unread counters, toasts in a polite
live region (errors 10 s, others 5 s). Icons are an inline SVG sprite drawn in one 1.8 stroke style.
- **Buttons:** filled pill gradient (#0058FF → #1365BB) for primary; gray pill on `--tsv-preview-bg`;
plain tint text for secondary; 42px subtle icon buttons whose glyph tints on hover.
- **Inputs:** 26px, `--tsv-bg`, 1.5px transparent border turning tint on focus; selects in the
multiselect look (radius 10); 20px dark checkboxes with a green check; 40×20 toggles; 10px slider
tracks; segmented 26px pills.
- **Chat:** detailed and compact styles. Remote bubbles #697a97 with a 12×14 tail on the first message,
own bubbles #0C1326; compact rows use the source 65px timestamp column and 13px bold sender. Event rows
have a #131824 → transparent gradient and radius 10; composer formatting sits above the 14/18 input
and working emoji, conditional attachment and send actions.
- **Menus:** 30px rows, 22px icons, 13px subtitle section captions, disabled #9c9c9c, destructive
rgb(255,130,130), min width 170, max 260. Client group/volume subpages replace the same popup contents;
Back or Left/Escape restores the original items and focus, not a second flyout.
- **Dynamic settings:** Audio follows Microphone, Output and Processing sections; device controls move
without being recreated. Identities use the source selector/Details/Bookmarks order; creation and rename
use the inline selector editor, and Details always represent the selected identity. Export/private-key
guidance and the separately labelled Current Server Nickname action remain functional product additions.
Whisper receive/list/editor and key binding controls use actual labelled rows, not an
unstyled vertical list. Toggle labels remain left with 40×20 switches right; numeric controls stay
compact and faders include their real live output. All fields, including inputs with implicit text
type, receive the shared source control styling. These changes address the first packaged capture
batch; confirmation screenshots are QA evidence, not assumed passes.
- **Selected values:** language flags and sidebar icon-mode pictograms come from the original local
artwork where legally available. The native value control owns selection; decorative artwork is not
a second accessibility control. Default-device captions require actual platform default metadata,
not guesses from device names; absent alias metadata leaves the caption unset.
The application icon is an original peach silhouette with a small stem and leaf on a transparent
background, without a plate, font or emoji dependency. `build/icon.svg` is the source for the 512 px
build PNG, 256 px runtime PNG and Windows ICO sizes 16, 24, 32, 48, 64, 128 and 256 px. Raster export uses
an alpha-enabled canvas in Electron, not a window screenshot. Asset-level alpha and small-size visual
checks do not establish that a particular packaged release contains or displays these assets.
Motion is limited to the official short state transitions (pill growth 150ms, toolbar 100ms, controls
120ms, toast 180ms); reduced motion removes them. Reduced transparency/increased contrast make menus and
notifications opaque; forced colours use system tokens.
## Motion
## Documented deviations from the official client
Only colour transitions (120 ms) and the toast entrance (180 ms, exponential ease-out); everything is
disabled under `prefers-reduced-motion`.
- No TeamSpeak logo in the sidebar header: the header shows the TeamsPeach name/icon. Search filters
local server connections/bookmarks only. Connecting and identity selection use a detail-pane form.
The account-bound community action slot instead exposes the real New Connection action. Bookmark
search/add/disclosure remain working; no decorative, nonfunctional folder action is introduced.
- No notification bell, cloud contacts, myTeamSpeak presence or "Setup Chat" footer state: TeamsPeach is
strictly account-free. Offline onboarding includes a real persisted System/Dark/Light choice before
local identity creation/restoration, adapting the official `first_launch.theme` stage (render@2995390)
without its account stages. Existing profiles keep their theme and do not repeat onboarding. The footer
shows the local nickname and UID instead of cloud presence: the approved account-free exception.
- A push-to-talk hold button remains in the server footer in push-to-talk mode for pointer access;
the central toolbar preserves the source Away + microphone/speaker geometry.
- Information/Chat/Files modes are in the detail header. Open private conversations and explicitly
opened server chat are sidebar activities; no extra tab row occupies the channel chat canvas.
- Stream placement reuses the same decoded media/session between chat and the 175px tree overlay.
Tile layout and native controls require the scoped capabilities/evidence in FEATURE_COMPATIBILITY.md.
- The exact 2.013 font and retained source-derived artwork preserve reference provenance; native
component placement/state and any legally unavailable pictograms remain separate acceptance questions.
- A "System" theme tile exists beside the official Dark and Light tiles.
- New server administration, identity, snapshot, whisper, recording and file surfaces use the source
control tokens around real APIs. Token conformity alone does not establish identical screen composition.
- Local UID contacts, public badge display, bookmark folders, Privacy and the
whisper manager bind real local/server operations. They do not emulate a myTeamSpeak account.
The whisper overlay shares the settings controls and list reset; its tree preview derives only from
current-session snapshots, and received-whisper history distinguishes departed identities.
- File Transfer uses source-style icon actions and keyboard-operable minus/value/plus controls, 3/3
per-channel concurrency defaults, the saved download location and shared application rate limits.
- Notification category switches suppress all sounds in that category without erasing per-event choices
or event logs. The disabled-category message and system notification subtitles use the original strings.
- Privacy, Video, Notifications and About follow the owner's explicit original-composition choice.
Unsupported controls keep their source positions but are disabled and explained; no telemetry, cloud
account, Cisco native backend or fabricated service is introduced. Real native decoder policy,
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.
- 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** 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.
- **Don't** present unavailable account or native controls as working; original-layout compatibility rows
must be disabled, explained and incapable of storing an ineffective preference.
- **Don't** claim full feature parity from visual parity; see `FEATURE_COMPATIBILITY.md`.
+683 -11
View File
@@ -1,19 +1,514 @@
# TeamsPeach ↔ TeamSpeak 6 server features
Status: **proven** = exercised against the real server 10.10.10.160 (TS6 6.0.0-beta13.1) with the real
UI, evidence path given; **implemented** = code + unit/loopback tests, no live proof yet;
**blocked** = not available, reason given. Windows x64 only unless stated.
## Current Windows account-free checkpoint (2026-11-26)
**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.
**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 join:** On private beta14 two disposable guests used a temporary password-protected channel. Selecting the row and cancelling the join prompt both 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 to the protected channel on both rosters and both Slint trees. This covers the Windows `command:join_channel` workflow, 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.
**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. Native display size, chat compactness, clients-before-channels and contact highlighting have rendering consumers. Tree style, sidebar icon mode, badge/flag/banner/background visibility and the commander lamp have stored controls but no corresponding tree rendering consumer was found in this inspection. 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 are static comparisons, 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 or clear-all control (the core has `bandelall`), no copy control in those key/password lists, no password validity dates there, 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
source-built libwebrtc. The Electron runtime, interface, consumer suites and launch/build tooling have
been removed. This owner-authorized source cutover is **not** completion of all native/mobile acceptance.
`native/compatibility.json` retains 718 pending behavioral requirements; none are promoted to passes.
Historical browser-client evidence below remains useful regression history, never native acceptance.
For historical deleted source, use the revision-pinned
[pre-cutover tree](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6).
It is reference-only, not a development/runtime dependency. Current commands are Cargo/`xtask` interfaces
in README; no historical runtime or harness is needed to build the native client.
Windows x64 WebRTC was built from pinned SDK `88705b15086ecbe2c26ee91ede6203f974a0fc62` and
WebRTC `9c3a1386f07e4348c28cd85c066821cebc3b56e4`; `native/native-deps.lock.json` records the
resolved DEPS, patches, effective GN arguments, compiler, archive gates and artifact hashes.
The native CXX bridge compiled against that source-built archive. No mutable prebuilt was used.
`native/tools/codec_probe.cpp` exercised the production software-only decoder factory with four
independently encoded synthetic 64×48 single-frame fixtures. H264 High decoded through FFmpeg,
AV1 Profile 0 through dav1d, and VP8/VP9 through libvpx. Every output matched the corresponding
independent FFmpeg I420 reference byte-for-byte. Fixtures and outputs were generated under
`target/codec-fixtures`; this proves these small decode cases, not sustained playback, hardware
acceleration, official-peer compatibility or other targets.
A separate real native PeerConnection loopback negotiated and transported generated video through
the production sender, receiver and bounded display path: 13 frames decoded by libvpx, 12 presented
with the expected red pixels, and one source-stop callback. Terminal cleanup removed the pending
frame. `target/codec-fixtures/peer-loopback.png` is the captured decoded image, not a UI mock.
This check exposed and fixed duplicate Opus linkage: WebRTC's 443 external Opus symbols and their
references are isolated from the unchanged voice-core codec, while unrelated assembly objects are
preserved byte-for-byte. No physical microphone, speaker, camera, screen capture or working server
was used for these checks.
## Approved original panel composition
Historical browser-client checkpoint: the paragraphs in this section describe that build, not a native pass.
The owner selected the original TS6 composition for Privacy, Video, Notifications and About. Root
sections now retain the source order with explicit unavailable states. Actual decoder controls are in
Video → Chromium Video Options; installation diagnostics and project links are subpages of About.
Report Issue opens the verified project issue list only through the external-link confirmation.
No telemetry, account integration, Cisco backend, content-report service or social affiliation is implied.
`approved-panels-confirmed/result.json` under `C:/Users/Admin/tmp/teamspeach-parity-complete-20261102/`
passed all four workflow groups and 32 captures with no external openings, network attempts, capture
attempts or renderer errors. Locale, notification overrides, licence/changelog navigation and real
decoder-policy restart passed separately. `approved-panel-pairs` still reports 32 strict visual failures;
that result is not converted into a pixel-parity pass by the approved composition change.
## Current local workflow corrections
Historical browser-client workflow checkpoint; these behaviors remain native requirements unless corrected below.
Identity export and Copy UID are in the identity selector's context menu (also Shift+F10).
Export still requires the private-key warning confirmation. Disconnected nickname changes use
Details; a connected own-client nickname is edited in its information header. Bookmarks have one
manager in the sidebar, not a second Settings category. Language selection is persisted for restart.
The identity migration, including warning cancellation and nickname persistence, passed the actual
isolated renderer/native-CLI scenario at
`C:/Users/Admin/tmp/teamspeach-parity-complete-20261102/identity-context-fixed/result.json`.
The comprehensive packaged matrix (`full-geometry-matrix/`) completed 192 pairs: 56 passed, 136 failed,
with no blocked navigation. All eight theme/locale/size variants of main/full/few/empty, private chat,
server bans and client lists passed. Remaining whole-screen failures are not whole-client parity.
Final verification and artifact hashes are in `docs/evidence/official-parity/qa-parity-harness.md`.
Navigation intentionally omits Account/Remote Apps; local-contact, privacy, video-backend and About
content also differ. Remaining geometry is not automatically an authorized exception.
## Expanded local panels checkpoint (2026-11-01)
Historical browser-client evidence only. “Current” in the retained table means the recorded 2026-11-01 build.
This supersedes the earlier absence of local contacts below. Remote Apps remains explicitly excluded.
The earlier tables remain historical evidence, not a declaration that all current screens match TS6.
Runtime artifacts are under `C:/Users/Admin/tmp/teamspeach-exact-design-20261101/`;
the exact build hashes and limits are in `docs/evidence/official-parity/qa-parity-harness.md`.
| Surface | Current exercised result | Boundary |
|---|---|---|
| Bookmark folders and connection options | Actual editor, nickname/channel/startup persistence, current-channel insertion, stale-session drag rejection and duplication passed; real Windows DPAPI save/reveal/restart/clear passed | Startup routing was exercised with injected enumeration and real offscreen connect rejection; live joins and Linux/macOS key stores remain unverified |
| Privacy and Markdown Help | Actual trusted-host subpage and production Markdown examples opened; concurrent confirmation/reset regression passed | No cloud typing/presence or telemetry service |
| Key bindings | Actual profile/binding persistence and process restart passed after the contents-layout visibility fix | Native global shortcut registration was not exercised |
| Four-level noise reduction | All levels persisted via the native range control for the selected input device | Independent processing; no physical microphone or native-DSP identity proof |
| Remote Apps | Excluded by the owner's explicit instruction; erroneous intermediate integration removed | Historical test artifacts describe only that removed intermediate implementation |
| Server icons and snapshot transfer ownership | Main/renderer consumer tests cover session grants, reconnect, partial failure and recycled transfer IDs | No successful live server icon mutation is claimed |
| Local contacts and public badges | Model/prefs/catalog tests and actual contact add/alias/restart passed; offline state is retained honestly | Not cloud contacts, badge ownership/redeeming or global presence |
| Rich chat | Actual history IPC/restart, scope isolation and local KaTeX/Mermaid hydration passed | Synthetic messages, no server traffic; sandbox permissions tested separately |
| Rich-text composer (post-release development) | Real packaged typing, formatting, emoji/slash completion, raw/hybrid settings, selection/undo, conversation isolation, refused sends and IME passed; hostile preview stayed inert with zero network requests | Windows hidden runtime only; the separate v0.1.6 release does not include this post-cut feature |
| Identity related bookmarks | Actual nested/default assignment display and nickname-clearing restart passed without changing UID | The original identity component exposes ordinary nickname, not a separate editable phonetic field |
| Whisper manager and history | Actual hidden UI with synthetic events passed overlay switching, preview, session/recycled-ID cleanup and received-history handling | No live whisper delivery proof; two microphone attempts were refused by the test stub |
| Changelog and licenses | Actual packaged list/detail navigation and focus restoration passed after fixing stringified DOM arrays | Displays this installation's documents, not TeamSpeak service terms |
Strict whole-screen visual parity remains open. The historical pair failures below are not converted
to passes by adding functionality or changing the test wait implementation.
## Historical interoperability baseline
The table below records earlier exercised builds, not automatic proof of the current cutover. **Proven**
means the cited earlier run exercised that feature; **implemented** means its recorded implementation
scope, not a new live-server pass. Current account-free acceptance follows the table. Windows x64 only
unless stated. No new live-server mutation or physical media capture is part of the final parity run.
| Feature | Status | Evidence / reason |
|---|---|---|
| First-run nickname, P-256 identity, public UID, restart persistence, rename keeps UID | proven | `docs/evidence/runtime/2026-10-24-identity/` |
| Connect / disconnect by address | proven | identity run `04-connected.png` |
| Saved servers (name + address, no passwords): save, edit, delete, restart persistence, one-click connect, clean switch | proven | `docs/evidence/runtime/2026-10-24-servers-settings/` (connect with same UID, mic muted) + `test/prefs.test.js` |
| Saved servers (name + address, no passwords): save, edit, delete, restart persistence, one-click connect, clean switch | proven | `docs/evidence/runtime/2026-10-24-servers-settings/` (connect with same UID, mic muted); [historical preferences tests](https://git.eeee.moe/TeamsPeach/client/src/commit/eb24965076599267687c8c4dd6f24f22953b15f6/test/prefs.test.js) |
| Sectioned settings (Identity, Servers, Appearance, Audio, Video, Keys, Information) without dropping the connection | proven | servers-settings run: all 7 panels visited while connected, keyboard Home/arrows, Escape returns |
| Theme: system / dark / light | implemented | dark captured in servers-settings screenshots |
| User themes / extensions | Current implementation; format- and `--tsv-*` token-compatible, not official DOM-class compatible | `docs/themes.md`; current consumer unit suite and guarded runtime acceptance below |
| Server password on connect | implemented, not exercised | the test server has no password |
| Channel tree, join channel, password channels (inline prompt) | proven (join), implemented (password) | probe joined `cs`; no password test performed |
| Voice TX/RX (Opus via core), talking indicators, mute, deafen RX+TX block/restore, PTT, open mic | proven between two TeamsPeach clients with synthetic capture | `docs/evidence/runtime/2026-10-24-voice-chat/`; the path after capture is real. Live microphone voice with the official TS6 client and Asahi hardware operation are not proven |
| Voice activation (local voice detector in the core, sensitivity High/Normal/Low, 100 ms preroll, 400 ms hangover) | proven between two TeamsPeach clients with a real speech recording as file-fed capture; detector unit tests on real speech and synthetic noise | `docs/evidence/runtime/2026-10-24-vad-dev/`, `docs/evidence/vad-0.1.4.md`: speech opens and silence closes the gate, mute/deafen/push-to-talk-not-held/disconnected send nothing, setting persists. A live microphone, an official TS6 receiver and native ARM64 hardware are not proven (ARM64 unit tests run under qemu) |
| Long-session capture freshness and offline Opus fidelity | measured with real Chromium fake-file capture and native encoder/receiver, not natural microphone or server interoperability | `docs/evidence/voice-timed-20261029.json`: before/after 190 s, 9500 frames each, stable 48 kHz mono EC/NS/AGC; 600 ms renderer stall previously replayed 30 frames in 10 ms, now discards 20 older-than-200-ms frames. Both codecs at quality 0/6/10 measured. Synthetic session did not reproduce progressive barrel coloration; subjective live report remains unresolved. Official UI estimator vs unknown native DSP/encoder distinction: `docs/evidence/voice-official-source-20261029.json`. |
| Private chat | proven | voice-chat run `15/16-*.png` |
| Channel chat | proven error path | server denies guests: TS 2568, permission 224, shown in UI |
| Server chat | implemented | not exercised live |
@@ -21,16 +516,17 @@ UI, evidence path given; **implemented** = code + unit/loopback tests, no live p
| TS6 screenshare viewing (P2P): discovery, join, answer, ICE buffering, stop | proven | `2026-10-24-ts6-stream-view/`: AV1 2560×1440 ~59 fps, 2298 frames, D3D11 decoder |
| Realign / reconnect offer renegotiation | implemented | unit tests + loopback (2 offers/2 answers); no realign seen live |
| Stream audio | implemented | live stream advertised `audio=0`; loopback 139 inbound audio packets |
| SFU streams | blocked | P2P only; `notifysfuaccessinfo` is reported as unsupported |
| Sending own screenshare | blocked | not implemented |
| Independent simultaneous P2P viewers, native fullscreen/Escape and picture in picture | real local WebRTC and historical native Windows fixture proof, not new live-server proof | `C:/Users/Admin/tmp/teamspeach-ui9-20261024/dev-streams/result.json`: native PiP HWND/topmost and cleanup before the desktop-test prohibition. Redesigned player: `C:/Users/Admin/tmp/teamspeach-player-refine-20261024/final-stage/result.json`, 120 offscreen assertions covering two generated receivers, identity/continuity, controls, keyboard, resize/collapse, and actual contained-image proportions. No new native PiP/fullscreen evidence; see `docs/evidence/player-refine-20261024.md` |
| SFU streams | blocked | Exact request fields are partly recovered, but token/URL/auth values and Chromium negotiation interoperability remain unproven; see current limits below |
| Sending own screenshare | generated production sender-to-viewer media verified; native/live interoperability not established | `C:/Users/Admin/tmp/teamspeach-publisher-decoded-pass/result.json`: decoded 640×360 H.264 and audio RMS 0.1063, admission/stop/cleanup. `offscreen-broadcast-final/result.json` under the UI9 evidence root covers 14 UI cases and eight locale/theme/size captures with injected capture only |
| Server/channel group labels (`name_mode`), custom group icons, country | proven | `2026-10-24-tree-metadata/`: two server-supplied group labels retained verbatim in the raw capture, 6 custom icons, RU country code |
| Built-in group icons (ids 100, 200, 300, 500, 600) | partial | server has no file (core: `not_found`, `builtin:true`); neutral badge named after the group |
| Channel icons and channel banners | proven | tree-metadata run: 11/11 channel icons and 11/11 banners from the server's file transfer |
| Host banner | proven | tree-metadata run: server GIF rendered above the tree |
| Host banner | historical server download proven; new behind-card presentation fixture verified | `C:/Users/Admin/tmp/teamspeach-ui9-20261024/offscreen-shell-confirmed/result.json`: compact artwork, theme/locale/window sizes, selectable content, absent-banner cleanup; not a new server-media download test |
| Avatars (server file) | implemented | no client on this server has `client_flag_avatar` |
| Avatars (myTeamSpeak URL) | proven | tree-metadata run: 1 avatar (public https PNG, bytes sniffed; URL allowlisted from server data) |
| Nickname colours | matches official semantics | official UI colours own client and myTS contacts locally (`docs/evidence/ts6-official-client.md`); TeamsPeach highlights own nickname, has no contacts |
| Poke | not implemented | core supports target `poke` |
| Poke, target menus, moderation confirmations, avatar selection | historical real-shell/preload/validator fixture | `C:/Users/Admin/tmp/teamspeach-ui9-20261024/offscreen-menu/result.json`; no live moderation/avatar transactions. Current whisper/menu additions are tested separately below |
| Identity export | proven | packaged Windows run `2026-10-24-windows-package/result.json`: real core CLI export through the app (only the native save dialog answered by the harness), file starts with `[Identity]`, status shows the UID |
| Identity import / restore from backup | implemented, not exercised | uses the same core CLI; import of a file produced by the official TeamSpeak client not verified |
| Hardware video decode on/off | proven (policy) | packaged run: saved off → restart → launched with `disable-accelerated-video-decode`, engine reports `disabled_software`. Separately, the live TS6 stream decoded AV1 with `D3D11VideoDecoder` while allowed; no claim for other codecs |
@@ -38,6 +534,182 @@ UI, evidence path given; **implemented** = code + unit/loopback tests, no live p
| Linux x64 / arm64 packages | released (pre-release v0.1.1), built in CI | release run #18 on `71300ff`: tests, core smoke (arm64 under qemu), every packaged arm64 ELF 16 KiB-compatible, static AppImage runtime starts in a slim container (arm64 under qemu); `docs/evidence/release-v0.1.1.md`. v0.1.0 ARM64 AppImage is broken (needs `libz.so`). Not run on Asahi hardware (target unreachable) |
| Windows x64 package | released (pre-release v0.1.1), local build | built on the developer PC from `71300ff`, static CRT core, provenance file attached; packaged smoke in `docs/evidence/runtime/2026-10-24-windows-package*/`; not tested on a pristine Windows |
| macOS, Windows ARM64 | blocked | no macOS host; Windows ARM64 needs the VS "MSVC ARM64 build tools" component (not installed) |
| Server/channel group (role) and permission management | not implemented | groups are displayed read-only; no assignment or permission editing |
| General file browser / file transfer | not implemented | file transfer is used internally only to download icons, banners and avatars |
| Other TeamSpeak 6 features not listed here | not implemented | TeamsPeach does not claim full TS6 parity |
| Server/channel group (role) and explicit client/channel permission management | implemented; controlled command/wiring coverage, not live server proof | Real verbs and target/connection-generation guards; production-shell fixture confirms group/permission payloads and cancel paths. Unknown effective rights remain server-decided |
| Per-participant local volume/mute/reset | generated native two-codec decode/mix plus real UI transport verified | Whole native suite: 66 unit tests including both codecs, gain/mute/reset and subprocess proof; max sample error 2, target mute retains other speaker exactly. Connection-scoped UID identity and recycled decode queues tested; no new live call claim |
| Channel member collapse and sidebar resize | isolated Electron UI verified | `C:/Users/Admin/tmp/teamspeach-ui9-20261024/dev-tree/result.json`; actual pointer/keyboard, per-server persistence, child headings retained; no active live-call proof |
| Selected-application broadcast audio | Windows native capture proof and synthetic bridge-to-WebRTC proof are separate; Linux runtime unverified; macOS blocked | `docs/evidence/native-app-audio-proof.json` records prior Windows 64.7 dB selection isolation, before later ancestry/lifetime fixes. `smoke-out/appaudio-synthetic/result.json` proves exact-contract PCM through production transport/worklet and decoded WebRTC. Combined native-to-WebRTC verification needs an isolated audio endpoint; prior default-output tone was potentially audible. Linux requires pactl/parec and PulseAudio or PipeWire-Pulse; macOS SDK/CoreAudio/TCC implementation is missing |
| General file browser / file transfer | Implemented in the historical browser-client cutover, not part of this baseline | Legacy TCP transfer and app-wide settings; native acceptance remains separate |
| Other features | No blanket parity claim | The current full feature matrix identifies owners, observed tests and exact remaining prerequisites |
## Earlier account-free acceptance checkpoint (2026-11-01)
Scope is strictly local/server functionality without an account; central myTeamSpeak/homebase services and
Remote Apps integration are excluded by instruction. Server-hosted `MATRIXCHAT` is not an account-only
exception: its native transport remains unimplemented (see below). No account UI is substituted for a
missing local feature. Tests use disposable state and controlled inputs; protocol fixtures do not establish
real server interoperability, and synthetic renderer IPC is never native transaction success.
Historical exercised gates: **318 Node consumer tests passed**, one deliberately skipped live release-list
test; **152 native unit tests passed**, one optional external-PCM audit ignored; **5 native stdio bridge
tests passed** after contract fixes. Full logs are in
`C:/Users/Admin/tmp/teamspeach-official-parity-20261101/qa-final/`. Actual release subprocess checks also
passed: two simultaneous core PIDs sharing the canonical identity without private-key runtime copies,
and 30 disconnected administration requests plus four malformed requests rejecting with exact errors.
Linux x64 additionally passed **154 native unit tests and 5 stdio tests** in an approved disposable
Rust 1.96 container. The same source cross-built for `aarch64-unknown-linux-gnu`; its ELF passed the
16 KiB page-alignment check (64 KiB LOAD alignment, GLIBC_2.34). It was not executed on ARM/Asahi.
Only owned temporary build files/containers were removed afterward; runner services/config were unchanged.
Actual hidden runtime passes include all twelve settings categories in EN/RU plus restart, native identity
CRUD/improvement cancellation, whisper/keybind persistence/restart, rich-chat history and safe local
math/diagram rendering, theme-resource confinement, onboarding theme-save ordering, menus, broadcast UI,
and administration/recording/file-browser controller rendering. The whole-shell batch passed 1,001 checks
over 324 cases. **224/224 class-matched visual metrics passed** at 1553×998 after correcting the independent
reference's source-observed 260 px popup modifier; this is not whole-image or whole-client identity.
| Feature family | Owner | Current observed evidence | Scope boundary |
|---|---|---|---|
| Multiple identities, additive import/export, defaults, guarded delete, hash-cash resume/cancel | AstraIdentity | Native profile/improvement and real CLI stdio tests; hidden actual create/edit/default/delete/improve-cancel passed | No official exported-key corpus claimed |
| Eight simultaneous server slots, viewed/input routing, reconnect epochs, bookmark identity | AstraConnections | Connection/media consumer units passed; actual two-core release subprocess proof passed | No new server joins; native microphone routing hardware not exercised |
| Channel CRUD/subscriptions, away/talk power, server moderation/keys/passwords/log/client database | AstraCore | Native wire/target units and 13 renderer behavioral cases passed; real disconnected-core rejections passed | Controlled protocol replies, not successful live server mutation |
| Server snapshots, typed properties, UID memberships and icons | AstraCore | Snapshot codec and main consumer suites passed | Import is non-atomic; server icon canonicalization and server feature support remain server-dependent |
| Whisper lists/groups/quick/reply, epoch gating and incoming deny | AstraAudio | Native generated Opus whisper route/block and target tests passed; local store/hold tests passed | Offline core rejection is not live whisper interoperability; contacts-only targets excluded |
| Per-device DSP, voice activation/PTT delay, dB fader, output/notification routing | AstraAudio | Native detector/mix tests and generated worklet consumer tests passed | Independent processing, not private native DSP identity; physical audio not exercised |
| Global hotkeys | AstraAudio | Windows/Linux parsing/backend tests and Linux x64/ARM compilation passed; offscreen no-helper guard passed | macOS global shortcuts unsupported; Windows/Linux OS registration/portal runtime deliberately unexercised |
| Legacy files, opaque chooser capabilities, commit/cancel/no-overwrite, global settings | AstraFiles | Real loopback TCP byte/hash/pacing/cancellation tests and main/renderer/scheduler consumer suites passed | HTTPFT/S3 explicitly unsupported; no speculative fallback; filesystem hard-link requirement fails safely |
| Recording/WAV timing, tracks, pause/finalize, notification log/matrix, OS local settings | AstraRecordThemes | Generated native PCM/WAV tests and main/renderer policy suites passed | No real microphone, OS startup/lock action, notification sound or private recording exercised |
| Local themes and appearance options | AstraRecordThemes / AstraVisual | Functional confinement suites and real selected CSS/font/image/restart/denied-remote smoke passed; actual settings pixels inspected | Package/token compatibility only, not official DOM-class compatibility |
| Local history, safe rich chat, drafts/unread, links/images, file attachments | AstraChat | Main/parser suites; actual 621-row history IPC/restart, local KaTeX/Mermaid and inert malicious-content smoke passed | Non-own-channel legacy delivery unverified; central chat excluded, server-hosted Matrix room actions missing |
| P2P stream extras, layout, internal/standalone popout and publishing controls | AstraStreams | 249 generated-media stage checks; actual sender→receiver video/Opus, admission, rate changes, pause, ban and cleanup passed | macOS selected-application audio unimplemented; standalone viewport emulation limitation below; no live SFU claim |
| Official visual system and EN/RU catalogs | AstraVisual / AstraQA | All twelve settings categories EN/RU/restart; actual full three-pane/settings/menu pixels reviewed; 224 class-matched metrics passed | Historical 22/22 source-reference probes are not whole-client identity |
The original feature inventory, owners, evidence and corrected exclusions are in
[`docs/evidence/official-parity/final-feature-matrix.json`](docs/evidence/official-parity/final-feature-matrix.json).
Consolidated results and exact package hashes: `qa-final/verification.json` and `qa-final/package-manifest.json`
under the evidence root above. The isolated package is `build/win-unpacked/TeamsPeach.exe`; no installer
was run, no version was changed and nothing was published.
## Remaining implementation gaps and external verification prerequisites
Authorized live check on 2026-11-02: `server_info` and the resulting snapshot from 10.10.10.160:9987
announced P2P=true and Matrix/SFU/HTTPFT/S3=false to core 0.1.6. Both mute flags were confirmed.
Two temporary identities disconnected cleanly and their local profiles were removed; no token,
invitation, media or server-setting mutation was attempted. This is a per-client/session advertisement,
not a claim about every server configuration. Evidence: `docs/evidence/official-parity/server-sfu-prerequisite.json`.
- **Server-hosted Matrix chat:** static frontend review on 2026-11-02 corrects the earlier blanket Matrix
exclusion. `MATRIXCHAT` selects a server-identity participation, separate from account/homebase login.
It supports channel/private rooms, invitation accept/reject and room-based edit/reply/reactions;
pinning is non-direct-room-only and other actions remain permission/event-dependent. Static native
constructors establish `chatlogintoken`, `notifychatlogintoken token=...` and
`requestchat type=private clid=<uint16>`, but well-known binding, token-to-Matrix login/renewal,
device/session lifecycle, server UUID derivation and sync/event envelopes remain unresolved.
No authenticated native/server-room exchange has been captured. Generic Matrix login is not a valid
substitute, and no inert setting or room-action controls are added. Exact source chain and scope:
`docs/evidence/official-parity/ts6spec-chat.md`, section 0.
- **SFU:** `docs/evidence/official-parity/sfu-native-inspection.json` and
`docs/evidence/official-parity/sfu-request-construction.json` recover command/envelope fields,
not authoritative token origin/renewal, exact optional/value branches or a proved mediasoup-to-Chromium
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.
- **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.
- **Non-own-channel chat:** arbitrary legacy channel-text delivery is not established by the own-channel
and UID-bound private-message fixtures. It remains specifically unverified; current results do not
establish permission semantics or delivery to a channel the client has not joined.
- **Platform/native behavior:** hidden Windows tests and Linux cross-compilation do not prove Asahi/M1 hardware, Linux portal/global
shortcuts, physical microphone/speaker/camera/application capture, native fullscreen/PiP or official
native DSP sound identity. Those are stated as verification limits, not silently emulated passes.
- **Standalone pop-out:** the actual Electron 44.9.3 offscreen guest starts with a 0×0 native viewport.
`docs/evidence/official-parity/popout-offscreen-limitation.json` records the source-supported engine
explanation. Explicitly authorized test-only CDP viewport emulation exercises the real adopted video,
MediaStream, continuing RTP, child controls and restore/cleanup. It does not verify unmodified native
offscreen painting or a normal visible child window; production flags are not weakened for the test.
## Native runtime integration and Windows offline evidence
The native host now owns a dedicated Tokio application worker and constructs the existing profile,
connection, file, audio and stream services. `native/src/app/runtime/` routes captured shell/chat/settings
intents and authoritative core/audio/platform events; settings use an ordered bounded consumer with
pending control identities and explicit completion/error state. First-run profile/import/recovery
decisions precede writable profile ownership, and private-key import and staging-discard operations
require an explicit warning confirmation.
`ui::application::bind` constructs a generation-scoped Slint attachment without entering its event
loop. It keeps Slint objects on the UI thread, applies coalesced Send-only snapshots, drains bounded
effects/prompts, and updates latest video images without re-projecting the tree for each frame.
Native theme font bytes pass the existing confined asset policy and are registered with Slint's
pinned Fontique interface; CSS Color 4 token values are converted to the sRGB UI surface.
`AppConfig::isolated` disables network and OS/device actions. Runtime snapshots expose actual
audio-start event counters and structured settings completion errors so a denied action cannot be
mistaken for a successful operation or an unrelated stale error. Mobile call capabilities and UI
generations have separate lifetimes; desktop installation state comes from validated running-package
metadata, not a caller-supplied installed flag.
Windows x64 integration now builds through `xtask build --target x86_64-pc-windows-msvc
--test-harness true`. The full release-profile workspace test command passed, including 461 native
library tests, the real atomic-document replacement regression, connection lifetime tests and updater
contracts. The captured-speech quality test remains explicitly ignored without its external PCM fixture.
Executed native smoke reports (under the local `target/evidence/` directory):
- `native-offline-ui-03/result.json`: actual Slint software rasterization, account-free onboarding,
all twelve settings categories, EN/RU and dark/light at 390/800/1280 logical pixels, actual semantic
combobox values matching persisted selections, math/Mermaid images, literal HTML, real text-input
focus blocking local PTT, microphone permission denial with zero physical endpoint starts, refused
Unicode draft retention/undo/redo, two full profile restarts and stale session rejection.
- `native-migration-01/result.json`: generated legacy profile import, unchanged hashes of five source
files, preserved UID/default identity, security offset 42424242 and history. No existing user profile
was imported or modified. This run predates the controlled-combobox correction checked above.
- `native-media-loopback-01/result.json`: production native PeerConnections decoded moving generated
video (13 decoded, 12 presented, libvpx) and 46 decoded audio blocks / 22080 samples, RMS 0.06160.
Audio was observed at the real decoded AudioSink before the closed output gate; no speaker or
microphone was opened. This is same-host RTP/ICE/DTLS evidence, not official TS6 signaling acceptance.
Smoke failures found and corrected an OS-capability page which refused navigation, stale native
combobox captions despite persisted values, missing text-focus propagation to local shortcuts and
Windows atomic overwrite failing while the old reader remained open. Windows publication now uses
`FileRenameInformationEx` with POSIX replacement semantics, preserving existing reader handles.
These results do not establish acoustic AEC, physical capture, official-peer interoperability,
Asahi/mobile execution, OS accessibility, installed updater/relaunch or complete visual parity.
Existing Electron evidence above remains historical reference only. Its production runtime/source has
been removed by the native-only cutover; outstanding acceptance gates remain outstanding, not waived.
Windows test-only packaging produced an unsigned NSIS installer (38,668,543 bytes) and ZIP
(52,858,951 bytes) in `target/evidence/native-package-03/`. Its `x86_64-pc-windows-msvc/verification.json`
passed real archive extraction, application/helper ISA and imports, asset/license hashes and the
browser/Node/WASM exclusion checks. NSIS's x86 uninstaller/plugin are classified separately from the
x64 application. The executable extracted from that ZIP passed the complete offline UI smoke from
its own package directory: `target/evidence/native-packaged-smoke-01/result.json`.
The installer was not executed, no default installation was modified, and no release manifest/update
feed was published. Both artifacts have `testOnly=true` and `release_eligible=false`; they are not a
production migration or installed update/relaunch proof.
### Ordinary desktop startup correction
The first test ZIP failed normal Windows launch with `Attach the desktop lease after the Slint
window is realized`; offscreen smoke did not cover the winit startup ordering. Desktop attachment
now awaits Slint's native-window future on its UI executor, retains/cancels that task with the UI
generation, and propagates real initialization failures. Closing onboarding also now stops the
application before profile services exist (including failed profile inspection).
`native/examples/desktop_startup_smoke.rs` exercised the real Windows window and desktop lease,
captured its 1280×800 pixels and closed it through the normal close-request callback. Evidence:
`target/evidence/native-desktop-startup-02/`. The corrected portable `teamspeach.exe` was also started
normally with a fresh test profile, observed as a visible TeamsPeach window, then sent WM_CLOSE:
exit code 0, empty stdout/stderr. No microphone/speaker or server connection was started.
The desktop delivery is `TeamsPeach-0.1.7-win-x64-startup-fix/` and the matching ZIP; the executable
SHA256 is `9d4d898b7ea723a9e0cdff2ca47cf4dbbdb2981163a6403498ab010c7bad9a95`.
+23 -5
View File
@@ -1,10 +1,28 @@
# TeamsPeach — notices
- TeamsPeach's own code carries no open-source license yet (`UNLICENSED` in package.json): all rights
reserved by its owner until the owner chooses a license.
- Electron and Chromium license texts ship at the root of the application directory
(`LICENSE`, `LICENSES.chromium.html`), as placed there by electron-builder.
- TeamsPeach's own code carries no open-source license yet: all rights reserved by its owner until the owner
chooses a license. Removing the former renderer does not grant redistribution rights.
- The application uses native Rust/Slint UI and media components; Electron, Chromium and the renderer's
WebAssembly DSP module are not bundled runtimes.
- The native core (`teamspeach-core`, built on ReSpeak tsclientlib, libopus and other Rust crates)
ships its complete third-party notices in `teamspeach-core-THIRD_PARTY_NOTICES.md` in this folder.
has its third-party notices in `core/THIRD_PARTY_NOTICES.md` in the source tree, also exposed in native About.
This includes the earshot voice detector (MIT OR Apache-2.0), whose crate embeds the small neural network
it runs (`weights.bin`) under the same license.
- The interface font Noto Sans (variable regular and italic, version 2.013, © 2022 The Noto Project Authors) is
bundled under the SIL Open Font License 1.1; see `NotoSans-OFL.txt` in this folder. The files are the exact
copies shipped in the installed official TeamSpeak 6 client bundle, unmodified.
- `teamspeak-client-icons-PROVENANCE.md` preserves the former renderer's TeamSpeak artwork source, hashes,
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 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
license texts; it is not a complete dependency inventory for the native application. Native About explicitly
reports the absence of a complete native UI/media dependency notice inventory.
- The 54 notification WAV files in `native/resources/sounds/` are copied unchanged from the installed official
TeamSpeak client at the owner's direction.
No redistribution licence has been identified; source hashes and event mapping are recorded in
`teamspeak-client-sounds-PROVENANCE.md`. They are not relicensed by TeamsPeach.
- TeamSpeak is a trademark of TeamSpeak Systems GmbH. TeamsPeach is an independent client and is not
affiliated with or endorsed by TeamSpeak Systems GmbH.
+99
View File
@@ -0,0 +1,99 @@
Noto Sans 2.013 variable, axes wght 100-900 and wdth 62.5-100 (native/resources/fonts/NotoSans-VF.ttf,
NotoSans-Italic-VF.ttf): unmodified copies of the files shipped in the installed official TeamSpeak 6 client
(html/client_ui/b1d0ab70303caea663db.ttf, name ID 3 "2.013;GOOG;NotoSans-Regular", sha256
74df1f61ab9d4bfaa961c65f8dc991deaae2885b0a6a6d6a60ed23980b3c8554; html/client_ui/628d4779d07f4e15066b.ttf, name ID 3
"2.013;GOOG;NotoSans-Italic", sha256 fe5a1fafb96618733aa4ea4c14a2e76ee65fee0d042b040e374f17575467e433).
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
File diff suppressed because it is too large. Load diff
+75
View File
@@ -0,0 +1,75 @@
TeamsPeach native capture DSP (dsp/)
===================================================================
The native microphone capture processor is linked as Rust code from TeamsPeach's
dsp/ crate. It runs Sonora's integrated AEC3, noise suppression and adaptive AGC2
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.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: 1632d47c1e77d0857f9145bd175134b348541e11 (per the published crates'
.cargo_vcs_info.json)
Registry: crates.io; package checksums (SHA-256 of the .crate files)
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, 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
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. 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):
Copyright (c) 2011, The WebRTC Project Authors. All rights reserved.
Copyright (c) 2016, Arun Raghavan and contributors. All rights reserved.
Copyright (c) 2026, dignifiedquire. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,373 @@
# Official TeamSpeak 6 client icon artwork in TeamsPeach — provenance
**Historical scope.** This document records the removed reference renderer's artwork imports and transformations.
The `app/renderer/` paths below are historical, not current native resource dependencies. The renderer SVG sprite,
mask files and country-flag files were not migrated into the native resource bundle. Their original source hashes
and redistribution restrictions are retained here; removing the renderer grants no new rights. The separate
TeamsPeach product icon was relocated unchanged to `native/resources/icon.png` (SHA-256
`87cfe10da3359eae8c000d0e5b2491524e132c4f9c34a54bfd0c94296c97c422`).
The SVG symbols in the sprite of `app/renderer/index.html` and the four mask files in `app/renderer/assets/icons/`
are artwork of the official TeamSpeak 6 client (TeamSpeak Systems GmbH), copied from the client installed on the
owner's workstation at the owner's direction (2026-11-01 brief: the installed client's design, value for value).
**Licence status.** No licence grant for redistributing this artwork has been identified. The installed client is
governed by its own licence agreement (`licenses/en/la_desktop.html` in the client installation). TeamsPeach does not
relicense this artwork and does not claim the right to publish it; it is not covered by TeamsPeach's own terms or by
any open-source licence in this folder. TeamSpeak logos, wordmarks, `teamspeak_label`, brand icons, presets and
account/myTeamSpeak-only artwork were deliberately not included; the TeamsPeach name and product icon remain the
product brand (current path `native/resources/icon.png`).
## Source
- Installation: `%LOCALAPPDATA%/Programs/TeamSpeak/html/client_ui` (TeamSpeak.exe file version 6.0.0.0; DESIGN.md
records build 6.0.0.5163 for the same bundle).
- `main.js` sha256 `9d6bea2ee5333086555c36584621c1b3462a83042ce746d3229d6766a9b82c39`; `main.css` sha256 `bc700401d04954d07f82570b060335e2278166db4f618f6cf3dcf8fde1834adf`.
- `images/icons/settings.json` sha256 `82c6a1be9a052fcbabe5b762c21c7893947703fd4db13094c92c48f89ba76f76` maps each TSIcon id to its file.
- TSIcon enum: `main.js` webpack module 58917 (`e.Settings="settings"`, … at offset ≈1959558); the `ts-icon`
renderer is at offset ≈10686241. Offsets below (`@N`) are character offsets in `main.js`.
## Transformations (render-preserving)
Each source file becomes one `<symbol id="i-<TSIcon id>">`. Applied mechanically by a one-off conversion, nothing redrawn:
1. `style` attributes converted to equivalent presentation attributes, because the renderer CSP (`style-src 'self'`)
blocks inline styles. Where a `style` declaration and an official colour class (`tsv-icon-*-fill|stroke`) set the
same property, the class (which the inline style always overrode) would be dropped; no source file needed this.
2. `enable-background` (SVG 1.1 hint, no rendering effect) dropped from `chat_poke.svg` and `chat_poke_solid.svg`.
3. Element ids prefixed with the symbol id (`i-away--label`) and their `url(#…)` references rewritten, so ids stay
unique in one document. Editor metadata (`serif:id`, Inkscape/Sodipodi attributes and `<metadata>`), XML
declarations, DOCTYPEs, comments, `version`, `xml:space`, root `width/height/x/y/id` are omitted.
4. `viewBox` is written as `0 0 <int w> <int h>`, exactly as the official `ts-icon` renderer rewrites it; every
source already had that form. Root class names (`tsv-icon-audio-input`, …) are kept on the symbol.
5. `shape-rendering="geometricPrecision"` is set on each symbol, as the official renderer sets it on every inline icon.
6. At runtime `icon()`/`setIcon()` in `app/renderer/js/dom.js` copy the symbol content inline into the `<svg>` with the
symbol's root class and attributes, as the official `ts-icon` renderer injects `innerHTML`. Ids referenced by
`url(#…)` get a per-instance suffix; other ids regain their source id so official id selectors (`#label`,
`#bar1_step0`, …) apply.
Mask files (`client_detailed_mask.svg`, `contact_mask.svg`, `server_mask.svg`, `channel_mask.svg`) are byte-identical
copies, used as CSS `-webkit-mask` images exactly as the official `ts-icon-stack` (`@3162500`) does.
## Symbols
| Symbol | Source | Source file | sha256 (source) |
|---|---|---|---|
| `i-delay-low` | DelayLow | `images/icons/delay_low.svg` | `16a2c7e08cdcf636a917b1fd3f99445869f0d0c6c24ce3cd6bf80885872a1832` |
| `i-delay-medium` | DelayMedium | `images/icons/delay_medium.svg` | `fb11aab3b06c0555ce164b1e443a40d864ca24556c8fdd0b01663e42d9270700` |
| `i-delay-high` | DelayHigh | `images/icons/delay_high.svg` | `154421a45765777aac316c3a0408e3f867bc7195d22a27c96c918cce166a72ce` |
| `i-accept` | Accept | `images/icons/item_accept.svg` | `c37087a87505a50a…` |
| `i-add` | Add | `images/icons/add.svg` | `06b8d432a7e8265e…` |
| `i-away` | Away | `images/icons/away.svg` | `1dfbb5649223e71e…` |
| `i-away-small` | AwaySmall | `images/icons/away_small.svg` | `dc1ac78a381a1621…` |
| `i-bookmark` | Bookmark | `images/icons/bookmark.svg` | `7c838e615fcdc016…` |
| `i-bookmarks` | BookmarkEdit | `images/icons/bookmarks.svg` | `eb3e1ec7f17c4ef2…` |
| `i-channel` | Channel | `images/icons/channel.svg` | `da88eccbd1bbb7ca…` |
| `i-channel-commander` | ChannelCommander | `images/icons/channel_commander.svg` | `496637e240474ef3…` |
| `i-channel-create` | ChannelCreate | `images/icons/channel_create.svg` | `450e18178dcd006f…` |
| `i-channel-default` | ChannelDefault | `images/icons/channel_default.svg` | `d5937550d3415c0e…` |
| `i-channel-mask` | ChannelMask | `images/icons/channel_mask.svg` | `69e1d3e053e77256…` |
| `i-channel-red` | ChannelRed | `images/icons/channel_restricted.svg` | `80853e27620d57f7…` |
| `i-channel-show-chat` | ChannelShowChat | `images/icons/channel_show_chat.svg` | `16d2d6354dc4b2e1…` |
| `i-channel-status-full` | ChannelStatusFull | `images/icons/channel_status_full.svg` | `6653c7e2bc19548d…` |
| `i-channel-status-restricted` | ChannelStatusRestricted | `images/icons/channel_status_restricted.svg` | `7f92a4e3be437977…` |
| `i-channel-yellow` | ChannelYellow | `images/icons/channel_locked.svg` | `c836375982c5c2bf…` |
| `i-chat-emoji` | ChatEmoji | `images/icons/chat_emoji.svg` | `c4e56048536a96d2…` |
| `i-chat-image` | ChatImage | `images/icons/chat_image.svg` | `b490111ba17ad580…` |
| `i-chat-poke` | ChatPoke | `images/icons/chat_poke.svg` | `482f8e135955e711…` |
| `i-chat-poke-solid` | ChatPokeSolid | `images/icons/chat_poke_solid.svg` | `0324599ddbc4c5e7…` |
| `i-chat-scroll-bottom` | ChatScrollBottom | `images/icons/chat_scroll_bottom.svg` | `ffc342c97703cbca…` |
| `i-chat-send` | ChatSend | `images/icons/chat_send.svg` | `cd23d5874caf4955…` |
| `i-checkbox-checked` | CheckboxChecked | `images/icons/checkbox_checked.svg` | `eec817685169e518…` |
| `i-checkbox-tick` | CheckboxTick | `images/icons/checkbox_tick.svg` | `c37b8bffa558868c…` |
| `i-checkbox-unchecked` | CheckboxUnchecked | `images/icons/checkbox_unchecked.svg` | `058673894173f0be…` |
| `i-client` | PlayerOff | `images/icons/client_normal.svg` | `c974ac95caaa1026…` |
| `i-client-detailed` | ClientDetailed | `images/icons/client_detailed_normal.svg` | `b16e10a88a032d32…` |
| `i-client-detailed-mask` | ClientDetailedMask | `images/icons/client_detailed_mask.svg` | `006e04703e627c8d…` |
| `i-client-detailed-placeholder` | ClientDetailedPlaceholder | `images/icons/client_detailed_placeholder.svg` | `7a35e3c9ba26e91b…` |
| `i-client-detailed-talking` | ClientDetailedTalking | `images/icons/client_detailed_talking.svg` | `01f65ddb3539c052…` |
| `i-client-detailed-voiceless` | ClientDetailedVoiceless | `images/icons/client_detailed_voiceless.svg` | `ee25d4ac9fb53035…` |
| `i-client-invisible` | ClientInvisible | `images/icons/client_invisible.svg` | `9b73e1a670795a58…` |
| `i-client-talking` | PlayerOn | `images/icons/client_talking.svg` | `f6e654923b5257d5…` |
| `i-client-voiceless` | ClientVoiceless | `images/icons/client_voiceless.svg` | `037849d56372402c…` |
| `i-connection-lost` | ConnectionLost | `images/icons/connection_lost.svg` | `8d6fa715ac1ffb0f…` |
| `i-connection-reconnecting` | ConnectionReconnecting | `images/icons/connection_reconnecting.svg` | `d998fa1936eb5fc9…` |
| `i-connection-status` | ConnectionStatus | `images/icons/connection_status.svg` | `6abd9fb0e4fd5829…` |
| `i-connection-status-label` | ConnectionStatusLabel | `images/icons/connection_status_label.svg` | `2015cb11cb504057…` |
| `i-contact-mask` | ContactMask | `images/icons/contact_mask.svg` | `176d68bc8c65caf6…` |
| `i-contact-normal` | ContactNormal | `images/icons/contact_normal.svg` | `110a7768034350b9…` |
| `i-contact-placeholder` | ContactPlaceholder | `images/icons/contact_placeholder.svg` | `d9b9390a77ed44e5…` |
| `i-contacts` | Contacts | `images/icons/contacts.svg` | `4eb8c29de4630f6f…` |
| `i-decline` | Decline | `images/icons/item_decline.svg` | `4eb1851b7e07e77d…` |
| `i-delete` | Delete | `images/icons/delete.svg` | `86b35526820aab24…` |
| `i-dots` | Dots | `images/icons/dots.svg` | `3b5bacf307ef1247…` |
| `i-download` | Download | `images/icons/download.svg` | `a8745797944f94c6…` |
| `i-download-flat` | DownloadFlat | `images/icons/download_flat.svg` | `be8f38d114ced5e2…` |
| `i-drag` | Drag | `images/icons/drag_indicator.svg` | `e07278d722fa784a…` |
| `i-edit` | Edit | `images/icons/item_edit.svg` | `0812e24304ab5359…` |
| `i-emoji` | Emoji | `images/icons/emoji.svg` | `357a4b8688ebc0da…` |
| `i-empty` | Empty | `images/icons/item_empty.svg` | `3141ea74fdb9d539…` |
| `i-exclamation-triangle` | Warning | `images/icons/exclamation-triangle.svg` | `2374cc1524f4d43a…` |
| `i-expand` | Expand | `images/icons/expand.svg` | `98a71fdbac31171d…` |
| `i-fa-align-center` | FaAlignCenter | `images/icons/fa_align-center.svg` | `1f6d10ae5947f152…` |
| `i-fa-align-justify` | FaAlignJustify | `images/icons/fa_align-justify.svg` | `ad8c53483fe90031…` |
| `i-fa-align-left` | FaAlignLeft | `images/icons/fa_align-left.svg` | `d10294d25252aac1…` |
| `i-fa-align-right` | FaAlignRight | `images/icons/fa_align-right.svg` | `eaecfe8bcd8dfbe1…` |
| `i-fa-asterisk` | FaAsterisk | `images/icons/fa_asterisk.svg` | `128f63761bc0c1b5…` |
| `i-fa-block-quote` | FaBlockquote | `images/icons/fa_block-quote.svg` | `c9259e07ca73a9d2…` |
| `i-fa-bold` | FaBold | `images/icons/fa_bold.svg` | `7ad7159a7b833081…` |
| `i-fa-chart-diagram` | FaChartDiagram | `images/icons/fa_chart-diagram.svg` | `80b9c1ca124af38b…` |
| `i-fa-code` | FaCode | `images/icons/fa_code.svg` | `af4f9b9679da1890…` |
| `i-fa-dash` | FaDash | `images/icons/fa_dash.svg` | `d5c7399ad747da9c…` |
| `i-fa-function` | FaFunction | `images/icons/fa_function.svg` | `9c2656ac652dd69b…` |
| `i-fa-h1` | FaHeading1 | `images/icons/fa_h1.svg` | `e979446418683043…` |
| `i-fa-h2` | FaHeading2 | `images/icons/fa_h2.svg` | `6032da9a2c7f9a8e…` |
| `i-fa-h3` | FaHeading3 | `images/icons/fa_h3.svg` | `0f872fd3d422585f…` |
| `i-fa-h4` | FaHeading4 | `images/icons/fa_h4.svg` | `7db6b3cc838e0706…` |
| `i-fa-h5` | FaHeading5 | `images/icons/fa_h5.svg` | `946825713599e02a…` |
| `i-fa-h6` | FaHeading6 | `images/icons/fa_h6.svg` | `9895825e957e8d19…` |
| `i-fa-heading` | FaHeading | `images/icons/fa_heading.svg` | `e6267b2415251c53…` |
| `i-fa-highlighter` | FaHighlighter | `images/icons/fa_highlighter.svg` | `72803253d03ca796…` |
| `i-fa-italic` | FaItalic | `images/icons/fa_italic.svg` | `0cdc36fdcedead43…` |
| `i-fa-link` | FaLink | `images/icons/fa_link.svg` | `251db02d8df47424…` |
| `i-fa-list-check` | FaListCheck | `images/icons/fa_list-check.svg` | `5458eae97afeea54…` |
| `i-fa-list-ol` | FaListOl | `images/icons/fa_list-ol.svg` | `f5a9b94c6deff472…` |
| `i-fa-list-ul` | FaListUl | `images/icons/fa_list-ul.svg` | `6828c3e8667836f5…` |
| `i-fa-strikethrough` | FaStrikethrough | `images/icons/fa_strikethrough.svg` | `06efdda10193edbf…` |
| `i-fa-subscript` | FaSubscript | `images/icons/fa_subscript.svg` | `cfad1c6f1915e180…` |
| `i-fa-superscript` | FaSuperscript | `images/icons/fa_superscript.svg` | `b37a64ef30ca863d…` |
| `i-fa-table` | FaTable | `images/icons/fa_table.svg` | `d61158d1bfae0288…` |
| `i-fa-underline` | FaUnderline | `images/icons/fa_underline.svg` | `8b546d77026607b1…` |
| `i-file-archive` | FileArchive | `images/icons/file_archive.svg` | `96de2a20f97e23a6…` |
| `i-file-executable` | FileExecutable | `images/icons/file_executable.svg` | `b1e36ea24752d657…` |
| `i-file-image` | FileImage | `images/icons/file_image.svg` | `0d427733c2d153a5…` |
| `i-file-pdf` | FilePdf | `images/icons/file_pdf.svg` | `4c5a7da87b63c74e…` |
| `i-file-text` | FileText | `images/icons/file_text.svg` | `531179c88753b796…` |
| `i-file-video` | FileVideo | `images/icons/file_video.svg` | `4637a535200bff33…` |
| `i-folder` | Folder | `images/icons/folder.svg` | `73c9d3232aae0e6e…` |
| `i-folder-add` | FolderAdd | `images/icons/folder_add.svg` | `59f4417f1026f72e…` |
| `i-folder-up` | FolderUp | `images/icons/folder_up.svg` | `bc208a31c007b4e8…` |
| `i-generic-file-attachment` | GenericFileAttachment | `images/icons/generic_file_attachment.svg` | `259e5b4e4d5bd9a2…` |
| `i-globe` | Globe | `images/icons/globe.svg` | `cd3ba6451e404325…` |
| `i-group-100` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_100.svg` | `1218b6852fe6c58e…` |
| `i-group-200` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_200.svg` | `959a58918fa66b26…` |
| `i-group-300` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_300.svg` | `a0d817ea944c0a5b…` |
| `i-group-500` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_500.svg` | `d8fc5f716a283bc6…` |
| `i-group-600` | server built-in group icon; `GetIcon` maps ids 1–999 to `group_<id>.svg` @2407426 | `images/icons/group_600.svg` | `dbb80d6687c16946…` |
| `i-groups` | Groups | `images/icons/groups.svg` | `1b69dd2d6b1dfbc5…` |
| `i-hidden` | Hidden | `images/icons/hidden.svg` | `96703f0789262f12…` |
| `i-info` | Info | `images/icons/info.svg` | `3f88c77dedf677b4…` |
| `i-input-muted-local` | InputMutedLocal | `images/icons/audio_input_muted_local.svg` | `389f1609902d564a…` |
| `i-item-close` | ItemClose | `images/icons/item_close.svg` | `72a1bc4ddac9a649…` |
| `i-item-collapse` | ItemCollapse | `images/icons/item_collapse.svg` | `7849a8feb879ceca…` |
| `i-item-copy` | ItemCopy | `images/icons/item_copy.svg` | `0aa0c0042d60ae9f…` |
| `i-item-expand` | ItemExpand | `images/icons/item_expand.svg` | `7a5b4228c34d4fca…` |
| `i-item-indent` | ItemIndent | `images/icons/item_indent.svg` | `3d54802e47ab6fd2…` |
| `i-item-leave` | ItemLeave | `images/icons/item_leave.svg` | `834b1096de82e6bd…` |
| `i-item-menu` | ItemMenu | `images/icons/item_menu.svg` | `b5b54c17b6cb8d00…` |
| `i-item-pin` | ItemPin | `images/icons/item_pin.svg` | `3d883f74a24916db…` |
| `i-item-settings` | ItemSettings | `images/icons/item_settings.svg` | `2c4027ab4f8c491f…` |
| `i-loading` | Loading | `images/icons/loading.svg` | `93f459dfb6937c5a…` |
| `i-lock` | Lock | `images/icons/lock.svg` | `940e806a10882ddf…` |
| `i-lock-opened` | LockOpened | `images/icons/lock_opened.svg` | `5fbac2e7a0b77d43…` |
| `i-microphone` | Input | `images/icons/audio_input.svg` | `c4a4bed2f5aa65fc…` |
| `i-microphone-slash` | InputMuted | `images/icons/audio_input_muted.svg` | `2f6a53252ec823f3…` |
| `i-microphone-slash-small` | InputMutedSmall | `images/icons/audio_input_muted_small.svg` | `87db7bab2852a36b…` |
| `i-microphone-small` | InputSmall | `images/icons/audio_input_small.svg` | `c6a3879869d73ef8…` |
| `i-mode-chat` | ModeChat | `images/icons/mode_chat.svg` | `61e4a63cf96bddc9…` |
| `i-mode-events` | ModeEvents | `images/icons/mode_events.svg` | `221a75257af47493…` |
| `i-mode-files` | ModeFiles | `images/icons/mode_files.svg` | `8b45d0235e5f304d…` |
| `i-mode-info` | ModeInfo | `images/icons/mode_info.svg` | `0f1441469a6afbf2…` |
| `i-mode-recording` | ModeRecording | `images/icons/mode_recording.svg` | `9942158cd6cba65d…` |
| `i-mode-server-bans` | ModeServerBans | `images/icons/mode_server_bans.svg` | `3864ce4c547d6943…` |
| `i-mode-server-compact` | ModeServerCompact | `images/icons/mode_server_compact.svg` | `ee8a00e62099cee4…` |
| `i-mode-server-detailed` | ModeServerDetailed | `images/icons/mode_server_detailed.svg` | `d2095ab12d5320a6…` |
| `i-mode-server-permissions` | ModeServerPermissions | `images/icons/mode_server_permissions.svg` | `9a42f928cb3c497f…` |
| `i-mode-stats` | ModeStats | `images/icons/mode_stats.svg` | `da6337edd873471d…` |
| `i-mode-streaming` | ModeStreaming | `images/icons/mode_streaming.svg` | `9266f6d1903d7c95…` |
| `i-navigation-back` | NavigationBack | `images/icons/navigation_back.svg` | `0840b7ff6c8238af…` |
| `i-navigation-forward` | NavigationForward | `images/icons/navigation_forward.svg` | `4c043e9c0751ab2b…` |
| `i-notifications` | Notifications | `images/icons/notifications.svg` | `8329f49d50a1bb65…` |
| `i-open-file` | OpenFile | `images/icons/open.svg` | `27b6c5a632b76ce8…` |
| `i-pause` | Pause | `images/icons/pause.svg` | `0ae327e335ecea24…` |
| `i-phonetic-available` | PhoneticAvailable | `images/icons/phonetic_available.svg` | `07a2790929d8bc50…` |
| `i-phonetic-unavailable` | PhoneticUnavailable | `images/icons/phonetic_unavailable.svg` | `76ab4d5bb87ed399…` |
| `i-play` | Play | `images/icons/play.svg` | `a156bbc7b646ac11…` |
| `i-privilege-key` | PrivilegeKey | `images/icons/privilege_key.svg` | `b1b241c52d781873…` |
| `i-refresh` | Refresh | `images/icons/refresh.svg` | `be320bc183d48268…` |
| `i-remove` | Remove | `images/icons/remove.svg` | `69bf994d573aefa4…` |
| `i-reply` | Reply | `images/icons/reply.svg` | `db14a05b7e0a01d0…` |
| `i-reset` | Reset | `images/icons/reset.svg` | `bcda4c52cc87f4cd…` |
| `i-search` | Search | `images/icons/search.svg` | `82e53700c60e5295…` |
| `i-server` | ServerGreen | `images/icons/server.svg` | `e154bfdff4b29dc6…` |
| `i-server-connect` | ServerConnect | `images/icons/server_connect.svg` | `cd01cc4a5a954b65…` |
| `i-server-info-users` | ServerInfoUsers | `images/icons/server_info_users.svg` | `831f971da2a118d0…` |
| `i-server-mask` | ServerMask | `images/icons/server_mask.svg` | `61dcf36ea4c6fa57…` |
| `i-settings` | Settings | `images/icons/settings.svg` | `6b3e4baed758cabb…` |
| `i-settings-addons` | SettingsAddons | `images/icons/settings_addons.svg` | `4f7eeea20e1a9793…` |
| `i-settings-appearances` | SettingsAppearances | `images/icons/settings_appearances.svg` | `217094ddb593bb5a…` |
| `i-settings-audio` | SettingsAudio | `images/icons/settings_audio.svg` | `1bc3fe384e4fcda6…` |
| `i-settings-behavior` | SettingsBehavior | `images/icons/settings_behavior.svg` | `743dc5de305ee52f…` |
| `i-settings-chat` | SettingsChat | `images/icons/settings_chat.svg` | `ba267177ededa7de…` |
| `i-settings-identities` | SettingsIdentities | `images/icons/settings_identities.svg` | `58ec6ac93a54d0fc…` |
| `i-settings-keybindings` | SettingsKeybindings | `images/icons/settings_keybindings.svg` | `d12aaf38122645c3…` |
| `i-settings-notifications` | SettingsNotifications | `images/icons/settings_notifications.svg` | `71671c67ca04aec4…` |
| `i-settings-privacy` | SettingsPrivacy | `images/icons/settings_privacy.svg` | `2786b5525bdfb5c7…` |
| `i-settings-whispers` | SettingsWhispers | `images/icons/settings_whispers.svg` | `abad49ce11dd6d10…` |
| `i-share` | Share | `images/icons/share.svg` | `fa64b0aea74ddc36…` |
| `i-slider-knob` | SliderKnob | `images/icons/slider_knob.svg` | `78d89c9dfa3ddbef…` |
| `i-speaker` | Output | `images/icons/audio_output.svg` | `131b918c2f78ca28…` |
| `i-speaker-slash` | OutputMuted | `images/icons/audio_output_muted.svg` | `859adad3f67a4109…` |
| `i-speaker-slash-small` | OutputMutedSmall | `images/icons/audio_output_muted_small.svg` | `bf534b06195aa96b…` |
| `i-speaker-small` | OutputSmall | `images/icons/audio_output_small.svg` | `c9100861f5fe9128…` |
| `i-status-recording` | StatusRecording | `images/icons/status_recording.svg` | `224f1f36ceb8edee…` |
| `i-stream-join` | StreamJoin | `images/icons/stream_join.svg` | `8bdbfa61c6ba5ed9…` |
| `i-stream-leave` | StreamLeave | `images/icons/stream_leave.svg` | `4945f241d5580522…` |
| `i-stream-maximize` | StreamMaximize | `images/icons/stream_maximize.svg` | `1e273e2190c591b8…` |
| `i-stream-minimize` | StreamMinimize | `images/icons/stream_minimize.svg` | `15ab09e5bb0a3496…` |
| `i-stream-playing` | StreamPlaying | `images/icons/stream_playing.svg` | `29017299d75b2a4b…` |
| `i-stream-settings` | StreamSettings | `images/icons/stream_settings.svg` | `7254dfc213ffcf41…` |
| `i-stream-shutdown` | StreamShutdown | `images/icons/stream_shutdown.svg` | `cf65796b2e5f0cf4…` |
| `i-transfer` | Transfer | `images/icons/transfer.svg` | `a7a1bd86f367978e…` |
| `i-upload` | Upload | `images/icons/upload.svg` | `318339a5c1476712…` |
| `i-upload-flat` | UploadFlat | `images/icons/upload_flat.svg` | `f78dee30d9d7ebab…` |
| `i-video-screen` | VideoScreen | `images/icons/video_screen.svg` | `fc504c589e8c3597…` |
| `i-viewer-small` | ViewerSmall | `images/icons/viewer_small.svg` | `6b70ae8be28dd5ba…` |
| `i-visible` | Visible | `images/icons/visible.svg` | `89150f6fc862ee7d…` |
| `i-waiting` | Waiting | `images/icons/waiting.svg` | `77659891ca6a57b5…` |
| `i-whisper` | Whisper | `images/icons/whisper.svg` | `83bcba03cb41abd2…` |
## Composite
`i-avatar` (viewBox 0 0 51 33) is the official default client avatar stack, composed only of official symbols: `i-client-detailed`
(ClientDetailed portrait) under `i-client-detailed-placeholder` placed at x=9 (the centred 33×33 `tsv-avatar` layer) and clipped by
`i-client-detailed-mask` as an alpha mask, matching `clientDetailedIcons`/`avatarImage` (@10693354) rendered by `ts-icon-stack`
(@3162500, `-webkit-mask: url(client_detailed_mask.svg)`). The talking ring is the separate `i-client-detailed-talking` layer.
## Mask assets
| File | sha256 |
|---|---|
| `app/renderer/assets/icons/channel_mask.svg` | `69e1d3e053e77256c83c539796ac01a3ddc4dc9b55e1d1ff6441ba19c5c4cc16` |
| `app/renderer/assets/icons/client_detailed_mask.svg` | `006e04703e627c8d2da6eb619647fcdf46cc466882c9fb3b05b45fa9a0a2e888` |
| `app/renderer/assets/icons/contact_mask.svg` | `176d68bc8c65caf6092ac615eaf3229e7b0c5612cde1ddc4706b0f75de72b0b2` |
| `app/renderer/assets/icons/server_mask.svg` | `61dcf36ea4c6fa5790b8dc513b2bebfe0d91b3879601eb2fedc0af5551eebb93` |
## Aliases
An alias symbol contains only `<use href="#i-<target>">`, so it renders the official target unchanged. Surface evidence is the
official usage that matches the TeamsPeach surface; entries marked UNAVAILABLE have no exact official counterpart and name the
nearest official glyph instead.
| Alias | Target | Evidence |
|---|---|---|
| `i-attachment` | `i-chat-image` | composer file picker ts-chat-image-button ChatImage (paperclip) @3571934 |
| `i-back` | `i-navigation-back` | menu Back NavigationBack @1615889 |
| `i-bell` | `i-notifications` | settings Notifications category; poke uses i-poke |
| `i-bold` | `i-fa-bold` | composer toolbar FaBold (markdown table @3507384 ff.) |
| `i-channel-green` | `i-channel` | official kebab channel-green maps to same file channel.svg (settings.json) |
| `i-channel-locked` | `i-channel-yellow` | official kebab channel-locked maps to same file channel_locked.svg (settings.json) |
| `i-check` | `i-checkbox-tick` | menu current-choice accessory CheckboxTick @1642454, @1738614 |
| `i-chevron-down` | `i-item-expand` | expander chevron ItemExpand @2864925, sections collapse @2854917 |
| `i-chevron-right` | `i-navigation-forward` | menu submenu accessory NavigationForward @1620314, @1627400 |
| `i-code` | `i-fa-code` | composer codeblock FaCode @3513668 |
| `i-commander` | `i-channel-commander` | tree commander ChannelCommander @4127418 |
| `i-copy` | `i-item-copy` | ItemCopy copy actions (28 uses), files @3834346 |
| `i-file` | `i-file-text` | UNAVAILABLE exact row source: official browser row icon not located; generic document FileText |
| `i-file-transfer` | `i-mode-files` | official kebab file-transfer maps to same file mode_files.svg (settings.json) |
| `i-fullscreen` | `i-stream-maximize` | stream enlargeImage (not fullscreen) @4061371 |
| `i-fullscreen-exit` | `i-stream-minimize` | stream enlargeImage (fullscreen) @4061351 |
| `i-gear` | `i-settings` | settings button Settings @2840824, settings title |
| `i-heading` | `i-fa-heading` | composer heading group FaHeading @3518397 |
| `i-headphones` | `i-speaker` | playback toggle Output @3992939 |
| `i-headphones-off` | `i-speaker-slash` | tree mutedIcon OutputMuted @2891233 |
| `i-image` | `i-chat-image` | composer file picker ChatImage (paperclip) @3571934 |
| `i-input` | `i-microphone` | enum key alias Input |
| `i-italic` | `i-fa-italic` | composer toolbar FaItalic |
| `i-keyboard` | `i-settings-keybindings` | settings category SettingsKeybindings |
| `i-link` | `i-fa-link` | composer toolbar FaLink @3510645 |
| `i-list` | `i-fa-list-ul` | composer lists group FaListUl @3518496 |
| `i-logout` | `i-item-leave` | kick channel/server/ban ItemLeave @1624216; NOTE official Disconnect uses ItemClose @1757045 |
| `i-message` | `i-mode-chat` | content mode Chat ModeChat @1343509 |
| `i-mic` | `i-microphone` | toolbar/call-bar capture toggle Input @3992501 |
| `i-mic-off` | `i-microphone-slash` | capture toggle InputMuted @3992484; tree mutedIcon @2891329 |
| `i-monitor` | `i-video-screen` | start stream / screen source VideoScreen @1896420, app-audio list @3720680 |
| `i-moon` | `i-away` | tree/presence state Away @2891233, @1745074 |
| `i-more` | `i-dots` | stream view settings Dots @4051881 |
| `i-output` | `i-speaker` | enum key alias Output |
| `i-palette` | `i-settings-appearances` | settings category SettingsAppearances |
| `i-permissions` | `i-mode-server-permissions` | client/channel permissions ModeServerPermissions @1630053 |
| `i-pip` | `i-expand` | UNAVAILABLE: official toolbar has no PiP glyph; nearest official = video.action.popout Expand @4064201 |
| `i-pip-exit` | `i-expand` | UNAVAILABLE: no official PiP-exit glyph; same Expand fallback, pressed state via --tsv-icon-base tint |
| `i-plus` | `i-add` | Add (26 uses) |
| `i-poke` | `i-chat-poke-solid` | client menu poke ChatPokeSolid @1627400 |
| `i-popout` | `i-expand` | video.action.popout Expand @4064201 |
| `i-priority-speaker` | `i-microphone` | official kebab priority-speaker maps to same file audio_input.svg (settings.json) |
| `i-quote` | `i-fa-block-quote` | composer toolbar FaBlockquote @3512197 |
| `i-record` | `i-status-recording` | recording status StatusRecording @1759184 |
| `i-self-avatar` | `i-contact-placeholder` | sidebar presence slot default avatar ts-presence avatarImage = ContactPlaceholder @2881456 (no account avatar) |
| `i-send` | `i-chat-send` | chat send button ChatSend @3572254 |
| `i-shield` | `i-mode-server-permissions` | legacy group-icon fallback; official permissions ModeServerPermissions @1614689 (official has no group fallback: icon 0 = none @2407426) |
| `i-sliders` | `i-item-settings` | no 1:1 official surface (legacy generic glyph); ItemSettings = settings resource @2954502. Use i-settings-behavior (OS settings), i-connection-status (connection info @4398096) |
| `i-speaker-off` | `i-speaker-slash` | playback toggle OutputMuted @3992939; stream hero mute @4075195 |
| `i-stats` | `i-mode-stats` | ModeStats content mode |
| `i-stream` | `i-mode-streaming` | screenshare toolbar ModeStreaming @2818131 |
| `i-strike` | `i-fa-strikethrough` | composer toolbar FaStrikethrough |
| `i-underline` | `i-fa-underline` | composer toolbar FaUnderline |
| `i-user` | `i-settings-identities` | identity surfaces SettingsIdentities @1914926, settings category @1376540 |
| `i-warning` | `i-exclamation-triangle` | enum key alias Warning |
| `i-x` | `i-item-close` | close/cancel ItemClose @1547254, @1607017 |
## Legacy ids that are official ids
`i-away`, `i-bookmark`, `i-channel`, `i-download`, `i-edit`, `i-emoji`, `i-folder`, `i-folder-add`, `i-folder-up`, `i-hidden`, `i-info`,
`i-lock`, `i-play`, `i-refresh`, `i-search`, `i-server`, `i-speaker` and `i-upload` now render the official icon of the same id.
`i-emoji` is `emoji.svg` (the composer button is `i-chat-emoji`, @3571700) and `i-info` is `info.svg` (the detail-pane Information
mode is `i-mode-info`, @1343385).
## Additional footer import
`i-connection-events` uses the installed `images/icons/connection_events.svg`, SHA-256
`1736f417cdf38002f3478e0a7e03809764738b657322a5b9d211f20c8d53257b`.
The conversion preserves geometry, changes inline styles to presentation attributes, prefixes IDs,
and omits XML/doctype declarations, as for the other sprite imports. No redistribution licence is implied.
## Country and language flags
The 258 SVG files in `app/renderer/assets/countries/` are byte-identical to the same-named files
under the installed client's `images/countries/`; all 258 were compared on 2026-11-01, with no mismatches.
They supply the optional server-tree country markers and the US/RU language-selection artwork.
`country-flags.js` accepts only its explicit local country-code allowlist, never arbitrary resource URLs.
Aggregate SHA-256: `eebd6910a9077dacaf199ff25fbdc12cf3d50ea35a0b27123e556ca8856cba0c`.
Input: filename-sorted records `filename + NUL + lowercase_file_sha256 + LF`, UTF-8 encoded.
The provenance and redistribution caveats above apply; these copies receive no new licence grant.
## Expanded bookmark and whisper controls
Additional symbols use the same transformations and redistribution caveats above. Source files are
under the installed client's `images/icons/`; hashes were read on 2026-11-01.
| Product symbol | Source file | SHA-256 |
|---|---|---|
| `i-folder-action` | `folder_action.svg` | `59df74a51ea024d214611b25568dfa53420f706b886ebdf9302e8c0011979d94` |
| `i-connection-whispers` | `connection_whispers.svg` | `50de820d13d6a4f08966448d81b94d59188a2f15fe9de9d730e43e83b34e65ad` |
| `i-chat-contact` | `chat_contact.svg` | `d11e41302a634d8e4f48a38ee8443e095c4c09b8d1fb87d4a4b95190c8d370a3` |
| `i-channel-select-default` | `channel_select_default.svg` | `690ebc95dff843e6257743c91fa752868bafdce63e788c47364fa80303b918a9` |
`i-chat-contact` represents a locally received whisper participant, not an account service.
## Analytics mode artwork
The owner-approved original Privacy composition uses two source symbols to describe unavailable
diagnostics modes, not to enable telemetry. The same redistribution restrictions above apply.
| Product symbol | Source file | SHA-256 |
|---|---|---|
| `i-analytics-limited` | `analytics_limited.svg` | `0d7af0589dd5dc76610ef324228ad07a364e8e5c6cd66dc9d52939f10119fe49` |
| `i-analytics-enhanced` | `analytics_enhanced.svg` | `18a012f09aaefd230c65286e594d0fcf09115473497da07421a692ea86bf1535` |
## Not included
TeamSpeak logo/label/mono marks, `ts_logo_qr.png`, `brands-*`, room presets and banners, content backgrounds, hex decorations,
contact-status, chat-room, homebase, two-factor and phone-call (myTeamSpeak account) artwork, and the other unused `*_old` files.
@@ -0,0 +1,97 @@
# Official TeamSpeak 6 client notification sounds in TeamsPeach — provenance
The 54 files in `native/resources/sounds/` (formerly `app/renderer/assets/sounds/`) are notification sounds of the official TeamSpeak 6 client
(TeamSpeak Systems GmbH), copied byte for byte from the client installed on the owner's workstation at the owner's
direction (2026-11-01 brief: the installed client's features and panels, value for value).
**Licence status.** No licence grant for redistributing these sounds has been identified. The installed client is
governed by its own licence agreement (`licenses/en/la_desktop.html` in the client installation). TeamsPeach does not
relicense these sounds and does not claim the right to publish them; they are not covered by TeamsPeach's own terms or
by any open-source licence in this folder.
## Source
- Installation: `%LOCALAPPDATA%/Programs/TeamSpeak/html/client_ui/sound/default/` (the only sound pack the client
ships; 61 files). `main.js` sha256 `9d6bea2ee5333086555c36584621c1b3462a83042ce746d3229d6766a9b82c39`.
- Event → file table: `NotificationSoundManager.soundFiles`, `main.js` webpack module 82164 (first file name at
character offset ≈2267292). Event types and sub types: module 69818 enums `J1` (event type), `l2`, `nA`, `x8`, `rJ`,
`eM`, `T9`, `rt`, `nZ`, `jk`, `KY`, `yc`, `ih` and `r.I3d` (stream). Playback: `playSoundForDefaultEvent` passes the
file name to native `tsclient_internal.playWaveFile(0, name)` (`main.js` ≈2120604). That the native side resolves
the name to `html/client_ui/sound/default/<name>.wav` is inferred from the adjacent `sound`, `client_ui`, `html` and
`.wav` strings in `TeamSpeak.dll` and from `default` being the only installed pack; the native code was not traced.
- Settings rows: coalesced setting table module 69818 `rg`; the row's Listen button (`playPreview`, module 186,
`main.js` ≈4964155) plays the first sub type of the row, an advanced row plays its own sub type, both ignoring the
throttle.
## Transformations
None. Each file is an unchanged copy (RIFF/WAVE PCM, including its original `LIST`/`CDif`/`cue `/`bext` chunks).
The native worker decodes PCM with `hound`, then resamples/mixes through the native notification output path;
it does not use Chromium's decoder. The former renderer resource paths were relocated without changing file bytes.
## Files
`time` is the official repeat throttle; a repeat within it is skipped.
| File | Official event sub types (`EventType.SubType`) | Format | Bytes | sha256 |
|---|---|---|---|---|
| `away_activated.wav` | ClientUpdate.YouAway (100 ms) | 1×16-bit 44100 Hz, 0.759 s | 67190 | `170fdd2f8fd07ce0b7077a45e9df6cdac8ddf9a8cdaf2e6bc5828944564d5acf` |
| `away_deactivated.wav` | ClientUpdate.YouPresent (100 ms) | 1×16-bit 44100 Hz, 0.758 s | 67034 | `6c00635fad802ebe62543e85fd402f8fcb5957b8d68c4e80a74d721fcab6306f` |
| `channel_created.wav` | ChannelEvent.YouCreated | 1×16-bit 44100 Hz, 1.065 s | 94194 | `9354320217fb8600c9b88a9ec34b19e1f5e242a13570d94ad0ec5811850f7ae2` |
| `channel_deleted.wav` | ChannelEvent.YouDeleted | 1×16-bit 44100 Hz, 1.028 s | 90882 | `25d80e7f1274caa9322bf5f1cd1846e5f4a2be1e978b5edbaf81693ccaf4c5dc` |
| `channel_edited.wav` | ChannelEvent.YouEdited | 1×16-bit 44100 Hz, 1.005 s | 88898 | `33605c5a802efa895ee043bbcc7cd43081c264a9602589355ced95a321c6c562` |
| `channel_moved.wav` | ChannelEvent.YouMoved | 1×16-bit 44100 Hz, 0.918 s | 81144 | `144bfc4a22c578872a998d518833c7b0cc1d60be0d81319506da5d84e3278ffd` |
| `channel_switched.wav` | ClientMove.YouSwitchedChannel | 1×16-bit 44100 Hz, 0.995 s | 87998 | `f38c9e67bbd861319d4eef15454893419285ba6dcdd05566dcb3b2042899f468` |
| `channelgroup_changed.wav` | ClientUpdate.YouChannelGroupChanged (1000 ms) | 1×16-bit 44100 Hz, 1.298 s | 114698 | `4ac60b4c0b4bb7a5784d6ae55412fdc198d89ac8a52c7cf3116cf6620f2a024e` |
| `chat_message_inbound.wav` | TextMessage.FromAnotherClient, TextMessage.FromChannel, TextMessage.FromServer | 1×16-bit 44100 Hz, 1.000 s | 88244 | `51e29bb0284b1c62447a720684dd9628034d0bd5b0c1fab2b1dde5986f457a3c` |
| `chat_message_outbound.wav` | TextMessage.ToAnotherClient | 1×16-bit 44100 Hz, 0.047 s | 4148 | `7fc8296f113485aa7d66b3f1e1e04ea3c7470d9efb238fb692a9504cf8c33ce2` |
| `connected.wav` | ConnectStatus.Connected | 1×16-bit 44100 Hz, 0.624 s | 55262 | `e9bc4136b91bc7d36dc9a561b2b8d4436244f42af65c1d01540f0b8a958c5a10` |
| `connection_lost.wav` | ConnectStatus.ConnectionLost | 1×16-bit 44100 Hz, 0.988 s | 87394 | `5566aa08c4e0f126a586ff50ed41ccbad3c5f942e75c9f924ad6578e8ccf6d45` |
| `disconnected.wav` | ConnectStatus.Disconnected | 1×16-bit 44100 Hz, 0.950 s | 84018 | `58ad23d848d07c37e0b521dadeecedbc268beaad657d4e12d03daf7b9ab16e53` |
| `error.wav` | ConnectStatus.FailedToConnect (1000 ms), LogEvent.LogError (1000 ms) | 1×16-bit 44100 Hz, 0.472 s | 41870 | `3b0589a6349d96198f496861b2be12c825a922b1b59b56d202195208014035e0` |
| `insufficient_permissions.wav` | ServerPermissionErrorEvent.Error (2000 ms) | 1×16-bit 44100 Hz, 1.370 s | 121066 | `4284bf1e85c53cb450b7ae9d488df417a372e0c23ad91bf24fcd2992b28cec1c` |
| `mic_activated.wav` | ClientUpdate.YouCaptureUnmuted (100 ms) | 1×16-bit 44100 Hz, 1.210 s | 106982 | `c44490c0f9ce270d0ee90c5f5fc4004ea39ebbdc8b6ebc5dab75cf175f9f6f83` |
| `mic_muted.wav` | ClientUpdate.YouCaptureMuted (100 ms) | 1×16-bit 44100 Hz, 1.017 s | 89936 | `528ea98a11951d8fa96a5396c12c9e3bceabf0a895e084826f3b1cfca0d4ed8e` |
| `neutral_banned_server_currentchannel.wav` | ClientMove.SomeoneInYourChannelWasBanned | 1×16-bit 44100 Hz, 2.478 s | 218768 | `599e671f50842cee1603a56f7e211686b985abd92a977b5f3c5532393213b67c` |
| `neutral_connection_connected_currentchannel.wav` | ClientMove.SomeoneInYourChannelConnected | 1×16-bit 44100 Hz, 1.446 s | 127760 | `6a4ad2636c93e88cd6247a3105a65d88af8ca3fff05f9debb09726df6074b9e0` |
| `neutral_connection_connectionlost_currentchannel.wav` | ClientMove.SomeoneInYourChannelConnectionLost | 1×16-bit 44100 Hz, 1.829 s | 161498 | `7c39ad53fd3d041fa711c97e6559c5af3ebf7b3b3285f9ae0edb4a42a92a5568` |
| `neutral_connection_disconnected_currentchannel.wav` | ClientMove.SomeoneInYourChannelDisconnected | 1×16-bit 44100 Hz, 1.900 s | 167834 | `cdbb181918c33842ae3572ad3752aabff8b47559e881862fe64ee6e40bddd6f8` |
| `neutral_kicked_channel_awayfromcurrentchannel.wav` | ClientMove.SomeoneInYourChannelWasKickedChannel | 1×16-bit 44100 Hz, 2.020 s | 178416 | `eafadd9b5f7cef69c106803bb0bac94d39880158330a3820995c4a1a897538e4` |
| `neutral_kicked_channel_tocurrentchannel.wav` | ClientMove.SomeoneWasKickedToYourChannel | 1×16-bit 44100 Hz, 1.856 s | 163914 | `29e2bf7ceaadb1d124a9f0ac8c4e1fe8c26697e3072f3d0b8936c4766416ff25` |
| `neutral_kicked_server_currentchannel.wav` | ClientMove.SomeoneInYourChannelWasKickedFromServer | 1×16-bit 44100 Hz, 2.534 s | 223686 | `2d53d3c8a338418e23c8803a8abb8b73349df5befc0af0096ae7a3bb0a376872` |
| `neutral_moved_awayfromcurrentchannel.wav` | ClientMove.SomeoneWasMovedAwayFromYourChannel (100 ms) | 1×16-bit 44100 Hz, 1.764 s | 155802 | `e2b1e2a4336a8af7e8cfcdd239f26138c3a11b045cd952d81aaa671ebd6c6c85` |
| `neutral_moved_tocurrentchannel.wav` | ClientMove.SomeoneWasMovedToYourChannel (100 ms) | 1×16-bit 44100 Hz, 1.741 s | 153818 | `569fd8904a2d6a70529ea36466cc590179ec7c4e40b6b5d40f2643fb0a25ed68` |
| `neutral_recording_active_currentchannel.wav` | ClientMove.YouSwitchedChannelRecording | 1×16-bit 44100 Hz, 1.815 s | 160290 | `7448f91c3ecd901500a954a42276a3459bbc93daa66e1080b3aead80f24cf92d` |
| `neutral_recording_started_currentchannel.wav` | ClientUpdate.SomeoneInYourChannelRecordingStarted | 1×16-bit 44100 Hz, 2.106 s | 185978 | `af5a29f7974591b010044d6a212f4238c4446f66ab27b2429e08b1c07c6a8670` |
| `neutral_recording_stopped_currentchannel.wav` | ClientUpdate.SomeoneInYourChannelRecordingStopped | 1×16-bit 44100 Hz, 2.096 s | 185126 | `3f0ab4f666518055fc05d8b5102bdddcde7b042aee6cd2527529b0753edf4557` |
| `neutral_switched_awayfromcurrentchannel.wav` | ClientMove.SomeoneLeftYourChannel (1000 ms) | 1×16-bit 44100 Hz, 1.326 s | 117182 | `d0c0fb1153a6b28f038c83ccc91bfecb218a0202171f3b2d14266fd290c5d622` |
| `neutral_switched_tocurrentchannel.wav` | ClientMove.SomeoneJoinedYourChannel (1000 ms) | 1×16-bit 44100 Hz, 1.343 s | 118682 | `d334e0e463472dfe389b1bfb2e24d254f99e00744d4f634c6eac76c0bcd6a19b` |
| `no_whisper_target_found.wav` | WhisperErrorEvent.NoSelection | 1×16-bit 44100 Hz, 1.514 s | 133786 | `6c6d1054a9b218f2ae1600c1567eeff9052802254ed1ed888c17a73a7095e5e0` |
| `recording_paused.wav` | LocalRecordingEvent.RecordingPaused (300 ms) | 2×16-bit 48000 Hz, 1.155 s | 221728 | `fee07ad4647998381f1c176c19c51ff88bff9be76c9bb999384cadec181d55ca` |
| `recording_resumed.wav` | LocalRecordingEvent.RecordingResumed (300 ms) | 2×16-bit 48000 Hz, 1.152 s | 221280 | `bbecb5fb7a9f1cf3f60cdb0ab690f8043dcf3fa7fbae69d8b4b93ebc99939d64` |
| `recording_started.wav` | LocalRecordingEvent.RecordingStarted (500 ms) | 2×16-bit 48000 Hz, 1.230 s | 236272 | `1fd58b214c851cd88b53fd61a38d71bc98d8cd407bb4270951360d4dc4e89b23` |
| `recording_stopped.wav` | LocalRecordingEvent.RecordingStopped (500 ms) | 2×16-bit 48000 Hz, 1.263 s | 242484 | `b9261ceccf4828680256b7edfbdd131781d815c30aef019dc624f4d55219967d` |
| `servergroup_assigned.wav` | ClientUpdate.YouServerGroupAssigned (1000 ms) | 1×16-bit 44100 Hz, 1.327 s | 117248 | `8f278ac08f259131eebc6a78ed700a76e036e627cb8a3ef78036f3f570c4501f` |
| `servergroup_revoked.wav` | ClientUpdate.YouServerGroupRevoked (1000 ms) | 1×16-bit 44100 Hz, 1.476 s | 130438 | `8befbc4a4025ed28de7d397ccb718c59417ea553065c50173693678b0e5d4211` |
| `sound_muted.wav` | ClientUpdate.YouPlaybackMuted (100 ms) | 1×16-bit 44100 Hz, 1.011 s | 89424 | `41cf6d43b7115e7e212f4cc75146291f0d847f079268b385fcd053090cd1e36c` |
| `sound_resumed.wav` | ClientUpdate.YouPlaybackUnmuted (100 ms) | 1×16-bit 44100 Hz, 1.018 s | 89978 | `28b0bfabfe904d54779979e652ae99122d1689aa64820e01a82db7d3c2f67cd8` |
| `stop_talking.wav` | TalkStatusChanged.YouTalkingWhileMuted, WhisperErrorEvent.NoInput (2000 ms) | 1×16-bit 48000 Hz, 0.467 s | 45742 | `c734b077fe252640535b7ba4ca607aadbf0884a8734c68cf17522b7f2f3a64bc` |
| `stream_started.wav` | StreamEvent.StreamStarted (100 ms) | 2×16-bit 48000 Hz, 1.300 s | 249812 | `55b922d7d457e0e9c6e86cbbb4bf7aa5edf310934ec673a39bd2f8e45629bf32` |
| `stream_stopped.wav` | StreamEvent.StreamStopped (100 ms) | 2×16-bit 48000 Hz, 1.233 s | 236924 | `8f8138de2d91ccdb0a2a1af112ea9acff58e845f30e79913697e025bf9b5cdba` |
| `talkpower_granted.wav` | ClientUpdate.YouTalkPowerGranted | 1×16-bit 44100 Hz, 1.267 s | 111962 | `3ef9564294f6673e3dbc945ee8b49bc381e674a31c93ab4c0363fa45b5eeadea` |
| `talkpower_requested.wav` | ClientUpdate.SomeoneRequestsTalkPower | 1×16-bit 44100 Hz, 1.720 s | 151946 | `57c1eac582806288b0e055110d265271bb597fd4556ccba01a59f87dd9ca48fc` |
| `talkpower_revoked.wav` | ClientUpdate.YouTalkPowerRevoked | 1×16-bit 44100 Hz, 1.503 s | 132770 | `02af63898cc739ef439afdc5c54420148d030532129f578c84d5e91ccd9e406f` |
| `whisper_received.wav` | WhisperEvent.WhisperReceived (2000 ms) | 1×16-bit 48000 Hz, 0.173 s | 16648 | `6c8e708f35a7025ed096e2c50677f2a2e677ada99d9c3db2546fe22e51d7d83b` |
| `you_edited_server.wav` | ServerEdited.YouEdited | 1×16-bit 44100 Hz, 1.229 s | 108638 | `1dc49aae0f48fd021e27ee642f345756b5c734512d3683bc15328d0f14188d67` |
| `you_kicked_channel.wav` | ClientMove.YouWereKickedFromChannel | 1×16-bit 44100 Hz, 1.431 s | 126418 | `3bf0594419ce06d87df94c8a8f068b882b3ff0b131b76088dfcc24cbbf370e3d` |
| `you_kicked_server.wav` | ClientMove.YouWereKickedFromServer | 1×16-bit 44100 Hz, 1.458 s | 128804 | `6e80de6a0dfcf2ead8163f8988cc664f8b09f046e1fe0337d8d8b4dd40f0afa7` |
| `you_were_banned.wav` | ClientMove.YouWereBanned | 1×16-bit 44100 Hz, 1.501 s | 132570 | `5e07d8d80230e9f663f0945b79180b363636d7dcc54962b82bf7bb20798ce0f7` |
| `you_were_moved.wav` | ClientMove.YouWereMoved | 1×16-bit 44100 Hz, 0.875 s | 77390 | `009f7b61dd7bfbdd3c6a4c4cda8d3d56af23c378d5e43654b69d421fc1b528e8` |
| `you_were_poked.wav` | TextMessage.PokedFromAnotherClient | 1×16-bit 44100 Hz, 0.936 s | 82766 | `ecb415cf29eccebb9d72ac745f7e5ac919cb0d1bcb62dc9c690fc1c0ed560385` |
| `your_channel_was_edited.wav` | ChannelEvent.YourChannelEdited | 1×16-bit 44100 Hz, 1.380 s | 121976 | `02363f9f2285747b78c271edb15dde0f99dffc0d08f07d0220b166dc940f8583` |
## Not included
`call_incoming.wav`, `call_outgoing.wav` (CallEvent, myTeamSpeak calls), `chat_inbound.wav` (MatrixMessageEvent
IncomingFollowupMessage, myTeamSpeak chat), and `chat_outbound.wav`, `client_joined.wav`, `client_left.wav`,
`incoming_call.wav`, which no official event table references. TeamsPeach has no local source for these events.
+36 -19
View File
@@ -7,17 +7,19 @@ session; items marked *inferred* come from the brief alone).
## Platform
web
native
(An Electron desktop application whose interface is HTML/CSS; target systems: Linux ARM64 on Apple M1 Pro
under Asahi Linux first, plus Linux x86-64 and Windows x86-64.)
(A Rust/Slint application targeting Linux ARM64 on Apple M1 Pro under Asahi Linux first,
plus Linux x86-64 and Windows x86-64. Other desktop/mobile targets are acceptance targets,
not a claim of tested platform support.)
## Stack
Delegated: Electron with plain JavaScript modules and HTML/CSS for the interface; a Rust native core
(ReSpeak tsclientlib) for the TeamSpeak protocol, spoken to over newline-JSON stdio. Chosen because the
screenshare viewer needs a real libwebrtc-compatible WebRTC stack (Chromium's) and the owner had no stack
preference.
Rust workspace: Slint UI in `native/`, ReSpeak tsclientlib protocol library in `core/`,
native DSP in `dsp/`, and source-built libwebrtc with Skia presentation. The application
uses typed in-process services and bounded media channels; the standalone core JSON adapter
remains a diagnostic interface, not the desktop transport. There is no browser or JavaScript
runtime. Cargo `xtask` owns dependency provisioning, builds, packaging and isolated smoke entry points.
## Users
@@ -40,25 +42,39 @@ a claim of complete interoperability; the evidence matrix records the demonstrat
## Operating Context
Long voice sessions with the app in the background; push-to-talk or an open microphone; occasional stream
viewing in a channel; the server is the owner's own TS6 server, administered elsewhere (no administration
from this client).
viewing and explicitly started publishing in a channel; target-bound moderation and explicit group/client
permission changes remain required, while the server remains authoritative. Historical implementation
evidence is separated from native acceptance in FEATURE_COMPATIBILITY.md.
## Capabilities and Constraints
- No myTeamSpeak account, registration or global services; identity is a local P-256 key with a public UID.
- Server-provided content (names, chat, descriptions, banners, icons) is untrusted input.
- Screenshare viewing uses the P2P path only; SFU-routed streams are reported as unsupported.
- The renderer may not choose files, paths or commands; native dialogs live in the main process.
- Later goal: broader parity with server features; out of scope: global myTeamSpeak features.
- Undecided: sending one's own screen share; global push-to-talk on Wayland; license of TeamsPeach's code.
- UI intents cannot choose arbitrary host paths or commands; native services own chooser grants and validation.
- Broader local/server parity remains required; global myTeamSpeak services are outside scope.
- Publishing, global shortcuts and platform integration require real native backends and separately scoped evidence.
- Product cutover does not establish full acceptance; no historical browser-client pass becomes a native pass.
## Brand Commitments
Name "TeamsPeach"; restrained peach accent (*inferred* from the name and brief); English as the default
interface language, with Russian selectable through the shared translation catalog.
The owner pinned a visual reference for settings (TeamSpeak 6 style: category navigation on the left,
titled card sections on the right, dark blue-gray surfaces); settings follow it.
The owner explicitly asked for a straightforward, familiar chat UI rather than a branding exercise.
Name "TeamsPeach" and its own application icon; English as the default interface language, with Russian
selectable through the shared translation catalog. The owner's latest brief (2026-11-01) requires the
installed official TeamSpeak 6 client's design, not an interpretation: the Liquid Glass world and the
peach accent are retired. Colours, typography (bundled Noto Sans, SIL OFL), spacing, row heights,
the three-slot window (sidebar, server tree, detail pane), menus, settings and chat geometry come from
the installed client's own source values, with extraction offsets in `docs/evidence/official-parity/`.
The TeamSpeak application logo and name are not shipped. Historical non-brand SVG artwork and retained
notification sounds have provenance records in `LICENSES/`; no redistribution licence is claimed.
Removing the old interface does not remove the legal obligations of retained assets.
Account-bound surfaces (notification bell, cloud contacts, myTeamSpeak presence, Setup Chat) remain omitted.
Local UID contacts use connected-server presence only and are not a substitute for cloud synchronization.
Remaining visual and functional deviations are listed in DESIGN.md and FEATURE_COMPATIBILITY.md; visual
parity is never presented as feature parity. Offline identity onboarding and the independent brand marker
are explicit exceptions, not imitations of account functionality. New module controls bind real APIs;
source-token matching is not a substitute for rendered screenshot comparison. No preference, error or
working control is removed for visual reasons. Keyboard focus, reduced motion, reduced transparency
where supported, increased contrast and forced colours remain part of the design contract.
## Evidence on Hand
@@ -76,5 +92,6 @@ benchmarks exist and none may be invented.
## Accessibility & Inclusion
Keyboard-operable controls with visible focus, screen-reader names for icon buttons and tree rows, light
and dark themes with an optional System mode, and readable system fonts. New profiles default to dark;
an existing saved theme choice is preserved.
and dark themes with an optional System mode, and the official interface font bundled locally so text
renders the same on Windows and Asahi Linux. New profiles default to dark; an existing saved theme choice
is preserved.
+352 -86
View File
@@ -2,8 +2,9 @@
A desktop client for **TeamSpeak 6** servers without a myTeamSpeak account: voice, chat, a channel tree
with server groups, icons and banners, and **TS6 screenshare viewing**.
The interface uses Electron (plain JavaScript modules and HTML/CSS); a native Rust core handles the
protocol (`core/`, ReSpeak tsclientlib) over private stdio. See the [bridge contract](docs/bridge.md).
The interface is native **Rust/Slint**, with Skia presentation and source-built libwebrtc. The Rust
protocol library (`core/`, ReSpeak tsclientlib) runs in process through typed, bounded services.
The standalone core's diagnostic JSON adapter is documented in the [bridge contract](docs/bridge.md).
See [`FEATURE_COMPATIBILITY.md`](FEATURE_COMPATIBILITY.md) for feature status and evidence. This is not a
claim of full TeamSpeak 6 parity: official-client voice interoperability and Asahi hardware operation
@@ -11,60 +12,287 @@ have not been proven.
## Development (Windows / Linux)
```
npm ci
cargo build --release --locked --manifest-path core/Cargo.toml # requires Rust ≥ 1.89, CMake and a C compiler
npm start
Use the pinned Rust toolchain in `rust-toolchain.toml`, a native C/C++ compiler, CMake, Python 3,
and the target's installed SDK/toolchain. Native dependencies are source-built from the revisions and
provenance gates in `native/native-deps.lock.json`; no browser runtime or JavaScript build tooling is required.
Run from the repository root, selecting the real target triple:
```sh
cargo run -p xtask -- deps --target x86_64-pc-windows-msvc
cargo run -p xtask -- build --target x86_64-pc-windows-msvc
```
Electron looks for the core in `core/target/release` and `core/target/debug`, choosing the newer binary.
If rustup installed Cargo without adding it to PATH on Windows, run
`%USERPROFILE%\.cargo\bin\cargo.exe` or open Developer PowerShell for VS. Use `-j 2` if linking runs out
of memory.
Linux targets include `x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`. Provisioning requires
network access and suitable installed platform tools; `xtask` does not install system SDKs. `--llvm-dir`,
`--skia-source` and `--jobs` select explicitly supplied tools/sources and build parallelism.
The normal build retains the Skia and WebRTC feature set; a reduced-feature build is not a product build.
Outputs use workspace `target/<target-triple>/release` or `CARGO_TARGET_DIR` (relative to the repository root).
Launch `teamspeach.exe` on Windows or `teamspeach` on Linux from that directory.
Use a separate profile without touching the main one: `TEAMSPEACH_PROFILE_DIR=<absolute-path> npm start`.
Set `TEAMSPEACH_PROFILE_DIR` to an absolute, separate directory before launch to avoid changing the main
profile. First-run native onboarding supports explicit read-only import of a selected historical profile;
it never silently adopts or overwrites it. See **Identity backups and profile migration** below.
## Packaging
```
npm run dist:win-x64 # NSIS + zip
npm run dist:linux-x64 # AppImage + tar.gz
npm run dist:linux-arm64 # AppImage + tar.gz (build the aarch64 core separately)
```sh
cargo run -p xtask -- package --target x86_64-pc-windows-msvc --out dist/native-local
cargo run -p xtask -- verify-package --target x86_64-pc-windows-msvc --out dist/native-local
```
`scripts/dist.mjs` **refuses** to package without a core for the target OS and architecture (checked via
its PE/ELF/Mach-O header), copies the core's `THIRD_PARTY_NOTICES.md` into `resources/licenses/`, and
checks that the package actually contains the core. For Asahi's 16 KiB pages, use
`node scripts/elf-pagesize.mjs <file-or-directory>` to check PT_LOAD alignment, glibc and dependencies.
Packaging consumes a completed native build and installed platform packaging tools. Use a fresh output
directory for a rebuild. Windows uses NSIS and ZIP; Linux uses AppImage and tar.gz. The package includes
native resources, core/WebRTC notices and asset provenance. Actual archive inspection checks architecture,
imports, assets/licenses, native build receipts and the absence of browser/JavaScript runtime payloads.
ARM64 Linux acceptance includes 16 KiB-compatible ELF segments; emulation is not Asahi hardware evidence.
CI: `.gitea/workflows/ci.yml` (Gitea Actions, Linux x64 containers) runs tests, builds the core, checks
identity invariants offline over stdio, runs Electron smoke checks under Xvfb, and cross-compiles the
aarch64 core with 16 KiB checks and execution under `qemu-aarch64` (emulation, not Apple hardware).
It runs on pushes to `main` and manual dispatch only. Pull requests do not run automatically: this is a
public repository with a runner on a private network, so a maintainer reviews external changes first.
Local packages, unsigned packages and test-harness packages are not publication or installed-update proof.
`xtask package` and `verify-package` are local-only; `publish-release` is a separate explicit command
used by the trusted-tag workflow. No command creates tags or infers signing credentials. Redistribution
rights for retained TeamSpeak artwork/sounds and platform signing/acceptance remain separate requirements.
CI/release configuration is under `.gitea/workflows/`; an unexecuted configuration is not a successful run.
Releases: `.gitea/workflows/release.yml` runs for `v*` tags. The tag must match `package.json` and
`core/Cargo.toml`. It builds Linux x64 and ARM64, checks ELF files, and publishes the release only after
uploading all files to a draft. Windows x64 is built on the developer's machine from the same commit and
attached with a `local` designation and a `*-build-info.txt` provenance file.
### Native CI and releases
The workflows require matching native runners labelled `teamspeach-native-linux-x64` and
`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
requires linuxdeploy, appimagetool, unsquashfs and archive/LLVM inspection tools. Jobs explicitly run
`xtask deps` to provision pinned WebRTC; they do not install system SDKs on the runner.
```sh
cargo run --locked -p xtask -- check-version
python -B -m unittest discover -s xtask -p test_publish_release.py
cargo run --locked -p xtask -- prepare-release --out artifacts
```
Release assembly consumes the downloaded `teamspeach-native-<target-triple>` bundles for both Linux
architectures, including their package, payload-verification and dependency receipts. It validates all
digests and merges the native manifest. Trusted `v*` tags then use `publish-release --out artifacts`
with the workflow's `GITEA_TOKEN`, `GITHUB_REF`, `GITHUB_SERVER_URL` and `GITHUB_REPOSITORY` environment.
Publication creates a new draft, uploads and reads back all assets, checks hashes, then publishes;
it refuses to overwrite an existing release. Manual dispatch builds/verifies without publication.
The Python tests mock HTTP and never publish. Native compilation, UI smoke and device acceptance
remain separate checks; removing the Electron updater harness does not establish native update E2E.
### Android development (Windows, Linux CI)
The selected Android route is **develop on Windows → manually dispatch Gitea Actions → build and
package entirely on Linux CI → download artifacts → install the test-only APK with Windows `adb`**.
WSL, Docker and a local Linux installation are **not required on the developer PC**. Windows needs
the editor/source checkout, a browser for Gitea and Android SDK Platform-Tools for device installation;
the Android SDK/NDK, Java and heavy native build tools belong on the CI runner for this route.
Pinned WebRTC's [official Android source-build documentation](https://github.com/webrtc-sdk/webrtc/blob/9c3a1386f07e4348c28cd85c066821cebc3b56e4/docs/native-code/android/README.md)
states “Android development is only supported on Linux.” This is a build-host requirement for CI,
not a requirement to run Linux locally. A Windows WebRTC Android source build is not a supported
alternative. CI keeps the full **Skia + WebRTC** feature set and pinned-source/receipt checks.
#### CI administrator prerequisites
The manual [`android-ci`](.gitea/workflows/android.yml) workflow is separate from the Linux desktop
workflows above. Before dispatch, an administrator must enable Gitea Actions and artifact support,
register a dedicated **Linux x64** runner labelled `teamspeach-android-linux-x64`, and provision its
toolchains and repository variables. Their presence is not established merely by committing the workflow.
| Repository variable | Required existing runner installation/input |
| --- | --- |
| `ANDROID_SDK_ROOT` | Android SDK with API 36, `build-tools/36.0.0` and `ndk/28.2.13676358` |
| `ANDROID_JAVA_HOME` | JDK 17+ including `keytool` (JDK 21 is acceptable) |
| `NATIVE_LLVM_HOME` | LLVM tool directory used by `xtask` |
| `NATIVE_LIBCLANG_PATH` | libclang library directory |
| `NATIVE_SKIA_SOURCE_DIR` | Dependency-synchronized Skia source checkout containing `bin/gn` |
| `ANDROID_GRADLE_DISTRIBUTION` | Local `gradle-8.14.3-bin.zip`; bootstrap verifies its committed SHA-256 |
| `ANDROID_BUNDLETOOL` | Local `bundletool.jar` for AAB inspection |
Also provision the pinned Rust toolchain and `aarch64-linux-android` target, Python 3, Git, CMake,
Ninja and required Linux native-build dependencies. The workflow does not install system SDKs or
download a Gradle distribution. It source-builds pinned WebRTC via `xtask deps`, builds the ARM64
application, packages both variants and runs `verify-package`. Its explicit `--gradle-online true`
allows Gradle dependency resolution on CI; the ordinary packaging default remains offline.
Provision runner resources for the full native build; local developer-machine limits are not a CI policy.
No production signing credentials are needed or used by this unsigned-artifact workflow.
#### Dispatch, download and install from Windows
1. Deliver the source changes through the normal authorized repository process. In the repository's
**Actions** page select **android-ci** (`android.yml`), choose the intended branch/ref and dispatch it
manually. This workflow has no automatic push/tag trigger and does not publish releases.
2. Only after an actual successful run, download and extract **`android-harness-arm64`** and
**`android-production-unsigned-arm64`**. Each bundle includes root `build-info.json` identifying
the exact revision, package manifests/hashes and `aarch64-linux-android` package-verification,
native-build and dependency JSON receipts. Match the run/ref and APK SHA-256 to that evidence
before installing; a bare APK is not provenance.
For version `0.1.7`, the harness APK is `TeamsPeach-0.1.7-android-arm64-harness-test.apk`; the
production bundle contains `TeamsPeach-0.1.7-android-arm64-unsigned.apk` and `.aab`.
Use the version actually recorded by the selected run, not a stale download.
3. Use a separate **ARM64 Android 8/API 26+ test device**, enable USB debugging and approve this
PC's debugging authorization. From the extracted harness APK directory in PowerShell, with
Platform-Tools on `PATH`, select the device explicitly and install **only the harness APK**:
```powershell
adb devices -l
$serial = 'replace-with-authorized-device-serial'
Get-FileHash .\TeamsPeach-0.1.7-android-arm64-harness-test.apk -Algorithm SHA256
adb -s $serial install -t -r .\TeamsPeach-0.1.7-android-arm64-harness-test.apk
```
Compare the displayed hash with the APK entry in `build-info.json` → `sha256`. `-t` permits the intentionally
`testOnly` APK; its debug/test signature is not production signing. Each CI package has an isolated
debug key, so a later run can have a different certificate and `-r` can fail with a signature mismatch.
Never automatically uninstall anything. Do not remove a production installation or its profile to
force an update; use a separate test device. Removing a previous disposable harness installation
requires an explicit user decision: **uninstall deletes that app's data**, including local identities
and settings. The CI job never selects, installs on or runs tests against a phone.
The **unsigned production APK is not installable** until separately authorized production signing
and signature verification are completed. **An AAB is not directly installable with `adb install`**;
it requires the separate signing/store or APK-generation process. These bundles are not a release.
The harness is for test-only/offline smoke scenarios, not production feature/device acceptance.
Neither this workflow configuration nor installing a harness proves live voice, official-client
interoperability, Bluetooth/background behavior or full mobile parity. No successful CI run, generated
APK/AAB, device install or mobile acceptance is claimed here.
**iOS still requires macOS and Xcode/Apple SDKs**, either locally or on separately provisioned macOS
CI, plus appropriate signing/provisioning for devices. Windows editing does not make iOS buildable
on Windows, and this Android workflow does not build or validate iOS. See the
[mobile assessment's current decision](docs/mobile-port-assessment.md#текущее-решение-android-all-ci-2026-11-10)
for its relationship to the preserved historical investigation.
## Usage
The following is the retained behavioral contract for the native client, not a declaration that every
native/platform acceptance case has passed. Consult FEATURE_COMPATIBILITY.md for scoped evidence and gaps.
1. On first launch, enter a nickname to create a cryptographic identity (P-256). The public UID is shown
in Settings → Identity. Changing your nickname does not change your UID.
2. Enter a server address and, if required, its password, then select Connect. Save adds the address to
saved servers above the tree; the bookmark button in the header toggles that list. Connect with one
click. If already connected elsewhere, Switch first disconnects from the current server cleanly.
Edit names and addresses or remove entries in Settings → Servers. Server passwords are not saved;
all servers use the same identity.
3. Click a channel to join it. Password-protected channels show a password field.
4. Voice uses push-to-talk (F8 by default, or the button in the channel header) or an open microphone.
The microphone and audio buttons at the bottom left update your server-visible mute state.
Right-click these buttons, or press Shift+F10 while focused, to select an input or output device using
the same selection as Settings → Audio. Left-click still mutes or deafens. The push-to-talk key works
**only while the TeamsPeach window is focused**; the hint in the channel header explains this.
5. A streaming member has a Watch button. Volume, mute, fullscreen and Stop watching are below the video.
The status line shows the negotiated codec, resolution and frame rate.
1. On first launch, enter a nickname to create a local P-256 identity without an account. Settings →
Identity manages multiple identities, their names/nicknames, default selection, additive import,
selected export and cancellable security-level improvement. Default and in-use identities cannot be
deleted. Editing a stored nickname affects future connections; it does not rename every active session.
2. Enter a server address and, if required, its password, then select Connect. Up to eight simultaneous
native connections are supported. Selecting a server tab changes the viewed server, not automatically
the microphone target; input routing has its own controls and acknowledgement. Bookmarks save a name,
address, optional local identity and folder. The sidebar editor also configures a per-connection nickname,
initial channel, startup connection and optional OS-encrypted server/channel passwords. Startup muting
affects only the microphone; it never changes output mute or unmutes a connection. The sidebar supports nested
folders, rename, duplicate, moving/reordering and confirmed subtree deletion. A security-level
rejection offers an explicit improvement action rather than starting expensive work automatically.
3. Click a channel (or focus its row and press Enter) to **browse** its heading and available streams.
This does not move your voice or change the channel-chat destination: the chat tab and composer still
name your current voice channel, and a notice explains this while browsing elsewhere. Double-click
a channel, or use **Join channel** in its header, to move voice. Password channels then show a password field.
The right-edge chevron hides or shows that channel's direct members without joining; collapsed rows show
a compact avatar summary. Collapse choices are saved per server address. Drag the sidebar divider or
focus it and use Left/Right or Home/End to resize; Enter or a double-click restores the responsive default.
4. Settings → Audio provides per-input and per-output device processing profiles. Voice activation can
use automatic speech detection, a volume gate, or a hybrid; push-to-talk can be combined with activation
and an optional release delay. Disabling both gives continuous transmission. Existing profile choices
migrate to this model. Notification output has a separate device and dB level. Processing is independent
and is not claimed bit-identical to the official client's private native DSP. Settings → Key Bindings has
named profiles (add/rename/activate/delete; only the active one is live), the official "Require exact key
match" toggle and the full official action list (push-to-talk, push-to-mute, microphone/speaker, away,
whispers, recording, disconnect, talk power, and Go Live, which opens the normal broadcast source chooser).
A binding is an in-window key or a global key (depends on the OS backend and permissions).
Older whisper-only bindings move unchanged into one active profile.
Local whisper lists/groups, quick whisper and reply use held-target epochs; failed or stale whisper
targets suppress sending rather than falling back to ordinary channel voice. Contact-only targets are
not offered without an account. The microphone test retains at most ten seconds of PCM in memory,
plays it only after an explicit Listen action through the selected output, and blocks server voice
until Finish clears the clip. Device/privacy changes and leaving settings also cancel and clear it.
The microphone and audio buttons update your server-visible mute state; muting or deafening stops transmission in every
mode. Right-click these buttons, or press Shift+F10 while focused, to select an input or output device
using the same selection as Settings → Audio. Left-click still mutes or deafens.
Deafening still blocks playback and transmission; its button state replaces the former muted banner.
5. Streaming members have a screen indicator. Select their channel to see available shares above the chat,
then choose **Watch** on a share. Several announced shares are listed separately; browsing alone never
subscribes to one. If the server flags a member as streaming but does not provide usable details, the
area shows discovery progress or the actual error instead of inventing a watchable stream.
Each watched share gets its own tile above chat and keeps playing while you browse other channels.
Volume, mute, picture in picture, full screen and Stop watching apply to that tile, not its neighbours.
The picture fills the tile: its name remains over the video while controls appear on pointer hover or
keyboard focus (always visible on coarse-pointer devices). **Stream details** opens the live statistics;
Escape closes that panel. Unavailable picture-in-picture remains disabled with an explanatory label.
Native picture in picture detaches the same video into an OS-managed floating window; full screen and
PiP do not subscribe again. Ending a share closes only its presentation; disconnecting closes all views.
Drag the divider above chat or focus it and use Up/Down or Home/End to resize the stream stage. Enter or
a double-click resets its height. Collapse hides the stage without stopping watched shares; its height
and collapsed state are saved. The chat retains usable space at the minimum window size.
6. Application chrome does not select text during interaction. Chat messages, editable fields, public
identity data and other useful content remain selectable. The server's host banner sits behind its
top card rather than in a separate panel, with a theme-aware contrast overlay.
7. Right-click a member, or focus the row and press Shift+F10 / the Menu key, for target-specific actions.
The menu uses server permission hints and distinguishes a known denial from an unknown permission that
the server must decide; group names never grant authority. Group/permission changes and moderation show
the exact target and operation before confirmation. A target that leaves, changes identity, or moves
channels closes its stale menu. Server errors are shown rather than reported as success.
Local volume uses the official -200..+10 dB taper, Mute and Reset. Reset restores 0 dB and unmutes;
explicitly committed modifiers persist by UID, while mute is session-local. Gain is applied before
voice mixing and never changes other participants.
The native avatar chooser accepts PNG/JPEG up to 128 KiB; UI intents do not supply arbitrary host paths.
Permission lists show explicit client/channel assignments, not a full effective-rights audit.
8. **Start Stream** opens the source chooser. Selecting a tile shows its thumbnail; **Next** starts
the muted private preview. Only **Go Live** publishes it. Choose an observed window/screen or
explicitly opt into a camera; camera capture does not include a microphone. Back, cancellation,
source loss and disconnect release the preview capture.
Presets and advanced controls set resolution/frame-rate and bitrate targets. Public allows viewers;
Selected participants uses a local UID allowlist (empty means nobody); Private requires a decision
per viewer. The stream can still appear in discovery. Audience settings remain locked until Stop.
Selected-application audio is opt-in: Windows uses WASAPI process-tree capture on build 20348+;
Linux uses PulseAudio/pipewire-pulse sink-input streams through `pactl` and `parec`. Pure PipeWire
without Pulse compatibility and macOS selected-application audio are not implemented.
Changing the audio source/scope/app selection never silently reopens a system picker. Changed sources
require explicit preview restart or Back and a fresh source selection, according to the native backend.
Per-app/master gains apply to the outgoing mix; clicking the percent readout resets gain to 100%.
System audio is never substituted silently, and the local tile is not another receiver subscription.
Native capture depends on OS consent and the installed desktop/portal backend; these paths are not
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.
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.
10. Chat history is local and separated by own identity, server and channel/peer identity. Drafts and
unread state are connection-local. Rich text, local math/diagrams, emoji and server-file links do not
require cloud services. Remote images require explicit consent; trusted external sites can be removed
in Settings → Privacy. Central myTeamSpeak/homebase chat and cloud contacts are outside the account-free
scope. Server-hosted Matrix rooms on `MATRIXCHAT` servers are a separate, unimplemented transport:
their frontend uses the server identity, but native endpoint discovery, authentication and invite requests
remain unresolved. They are not excluded merely because they share Matrix room controls. Local UID contacts are separate.
11. Streams support hide/show without unsubscribing, ordering, focus with a secondary strip, pages,
an internal tile overlay and moving the existing stage over the server tree. Publisher admission,
kick/ban/unblock, pause and live options keep the original tracks/sessions. Standalone pop-out must
reuse the same decoded media and ownership without a second join. Historical browser-only viewport
emulation does not prove native pop-out painting or SFU interoperability.
## Local panels and integrations
- **Privacy:** manage trusted external hosts and reset remembered confirmations. Skipping a confirmation
changes that operation's local preference; reset restores prompts. No analytics service is enabled.
- **Contacts:** save server users locally by identity UID, optionally give them aliases, and show/sort/group
offline entries. Presence comes from the client's connected server snapshots, not a global service.
Public badge display does not redeem badges or claim ownership of them.
- **Remote Apps:** excluded by the owner's explicit instruction. No Remote Apps listener, authorization
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. 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.
- **Saved bookmark passwords:** native protected storage uses platform secret APIs, never a plaintext
fallback. Historical encrypted passwords require explicit one-time re-entry; old ciphertext is not
reused. Reveal requires an explicit action, address changes invalidate saved credentials, and forgetting
a password remains possible if the key store is unavailable. Encryption is tied to the OS user/key store,
not a portable backup format. Hardware verification is platform-specific; simulated backends are not proof.
## Language
@@ -74,68 +302,86 @@ changes do not translate server names, chat messages or operating-system device
## Updates
Check for updates in Settings → Information. The first updater-capable version must be installed
manually: version 0.1.1 and older cannot update themselves. Updates come only from published releases
of the public [TeamsPeach/client repository](https://git.eeee.moe/TeamsPeach/client), without credentials.
Check for updates in Settings → Information. Updates come only from published releases of the public
[TeamsPeach/client repository](https://git.eeee.moe/TeamsPeach/client), without credentials. The native
updater requires a validated `rust-slint` release manifest, exact target artifacts and verified hashes.
Historical browser-client release feeds alone are insufficient for a native offer.
Windows x64 NSIS installations and Linux x64/ARM64 AppImages can download a verified package and install
it after confirmation. Windows zip and Linux tar.gz distributions notify you and open the release page;
replace those files manually. Development runs and unsupported platforms do not self-update. The
default Preview channel includes prereleases; choose Stable to exclude them. Installation never starts
automatically, and interrupting an active server session requires explicit confirmation.
Windows x64 NSIS installations with a valid native installation receipt and Linux x64/ARM64 AppImages
have explicit-install paths. Portable archives and custom-profile Windows runs are manual-only;
development/test builds do not self-update. Preview includes prereleases; Stable excludes them.
Nothing installs or restarts automatically, and interrupting an active session requires confirmation.
See [Updates](docs/updates.md) for platform modes and release/acceptance requirements. No successful
published native upgrade is claimed without source/destination versions and preserved-profile evidence.
For platform details, release requirements and verification scope, see [Updates](docs/updates.md).
Implementation and service-level tests do not by themselves prove a successful installed upgrade;
published-release end-to-end evidence must identify the source and destination versions.
## Identity backups and profile migration
## Identity backups
Identity export writes a TeamSpeak-format `.ini` through a native chooser after a private-key warning.
**This file contains your private key: protect it like a password.** Import is additive, preserves existing
UIDs, and never silently replaces a corrupt identity. Native onboarding also offers explicit migration
from an existing historical profile into a separate native profile; close the old client first.
Settings → Identity → Export saves a TeamSpeak-format `.ini` file through a native dialog.
**This file contains your private key: protect it like a password.** Restore it with Import after
disconnecting from the server; replacing the current identity requires confirmation. You can also use
Restore from backup on the first-run screen. The core never silently replaces a corrupt identity.
Data locations: `%APPDATA%\TeamsPeach` (Windows), `~/.config/TeamsPeach` (Linux). Files include
`core/identity.json`, `core/profile.json`, `prefs.json` and `logs/`.
Migration copies and validates identities/default selection, preferences, history, keybindings, whispers,
local volumes, file settings and extensions, leaving the source untouched. Passwords require re-entry;
legacy device identifiers require separate user-confirmed input/output/notification mapping before capture.
Interrupted staging imports need an explicit recovery decision; no silent reset or source deletion occurs.
Native data defaults to `%APPDATA%\TeamsPeachNative` on Windows,
`$XDG_CONFIG_HOME/TeamsPeachNative` (or `~/.config/TeamsPeachNative`) on Linux, and
`~/Library/Application Support/TeamsPeachNative` on macOS. These roots are separate from historical
`TeamsPeach` profiles. Mobile uses its private application container's `profile-v1` directory.
An absolute, normalized `TEAMSPEACH_PROFILE_DIR` selects a separate root; do not point it at the old profile.
## Limitations
- Screenshares use P2P only, as the official client does by default. SFU notifications are reported as
unsupported. There is no TURN relay: the viewer needs a direct network path to the streaming computer
(STUN uses `turn.teamspeak.com`, as in the official client).
- Sending your own screenshare is not implemented.
- Push-to-talk only works while the window is focused. A global hold-to-talk shortcut, such as one using
the Wayland GlobalShortcuts portal, is not implemented.
- The official client highlights your own nickname and myTeamSpeak contacts using local relationships,
not server data. Without an account there are no contacts, so TeamsPeach highlights only your own name.
- P2P screenshare publishing is implemented, but native source capture on every OS/window manager,
macOS selected-application audio and official-client interoperability are not all verified. SFU publishing
is unavailable. See the feature matrix for the precise implementation and evidence boundaries.
- In-window push-to-talk must release on focus loss. Global bindings depend on the real OS backend,
registration and permissions; hidden checks do not prove OS registration or Wayland portal operation.
No platform-wide shortcut guarantee is made.
- Local contacts are keyed by server identity UID and can be highlighted in the tree. They do not sync
with myTeamSpeak, provide global presence or enable cloud/offline chat.
- Server-stored avatars, icons and banners use TeamSpeak file transfer. myTeamSpeak avatars use public
HTTPS URLs announced by the server; downloaded image bytes are checked by signature. A myTeamSpeak
avatar was observed in the live run; server-stored avatar support is implemented but was not exercised
live because no client on the test server advertised one.
Built-in TeamSpeak group icons (IDs 100, 200, 300, 500, 600) use a neutral badge with the group name,
because the server does not supply these files.
- Chromium does not expose the official client's Cisco OpenH264 switch or per-codec hardware backend
selection. Chromium chooses the decoder; AV1 hardware decoding with D3D11 was demonstrated on Windows.
- Native decoder policy applies to the real libwebrtc factory. Historical Chromium hardware-decoder
evidence does not establish native hardware decode, per-codec selection or Cisco backend support.
- macOS and Windows ARM64 builds are not published because build hosts are unavailable. Linux ARM64 is
cross-compiled; execution on Asahi M1 Pro hardware has not been checked because the target was
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
A familiar voice-chat layout: server and channel tree on the left, channel and chat on the right.
Settings use category navigation (Identity, Servers, Appearance, Audio, Video, Keys, Information) on the
left and cards on the right, following the supplied reference. New profiles default to a dark theme,
independent of the OS. Choose Light or System in Settings → Appearance; the choice persists, and an
existing saved choice is preserved across upgrades.
The design contract reproduces the installed TeamSpeak 6 client's source values (see
DESIGN.md and `docs/evidence/official-parity/`): a three-pane window with a 270 px navigation sidebar
(collapsible to a 62 px rail) listing server connections and saved servers, a 500 px server pane with
the server header card and channel tree, and a detail pane with the channel header, stream stage, chat
and composer. Settings open in the main and detail panes with the official category column and section
cards (Identity, Servers, Appearance, Audio, Video, Keyboard, Chats, Notifications, OS Specific,
Information). Reduced-transparency, reduced-motion and forced-colors preferences have explicit fallbacks.
New profiles default to dark independently of the OS; Light and System remain selectable. Account-bound
official surfaces (notification bell, cloud contacts, myTeamSpeak presence) are intentionally absent;
local UID contacts are an independent account-free feature.
System fonts and a restrained peach accent keep the interface readable; green indicates a speaker.
Server text is rendered with `textContent`; image bytes are checked by signature. The renderer uses
context isolation, a sandbox, a strict CSP and allowlisted main-process commands. Only the main process
selects file paths through native dialogs.
The native window must retain OS minimize, maximize/restore, close, system shortcuts and caption behavior
without fake JavaScript controls. The target app-bar geometry is 44 px and its colors follow the theme;
actual caption integration and accessibility require platform-specific evidence. Fullscreen/PiP must not
create a second media subscription. Bundled Noto Sans (OFL) and the official blue tint retain the typography
and color contract; green indicates a speaker.
Server text remains data, never executable markup. Native services validate commands and media bytes,
bind delayed actions to connection/session/UI generations, and own native chooser/path capabilities.
No embedded browser, browser sandbox, DOM or renderer/main IPC is part of the runtime architecture.
## Repository language and evidence
@@ -148,10 +394,30 @@ Historical JSON captures and screenshots in `docs/evidence/runtime/` retain the
names and device names observed during each run, including Russian text. They are not translated or
rewritten to resemble the current interface. Unicode test fixtures retain their original values.
## Checks
## Checks and evidence
- `npm test` runs unit tests for contracts such as IPC validation, viewer sessions and stream discovery.
- `node scripts/core-smoke.mjs <core-binary>` checks identity invariants offline.
- `node scripts/smoke-ui.mjs`, `smoke-voice.mjs`, `probe-stream.mjs`, `loopback-stream.mjs` and
`smoke-tree.mjs` exercise the real UI. Recorded results are in `docs/evidence/runtime/`; each run's
scope and limitations apply.
Native verification uses the Cargo workspace and `xtask` entry points, not the removed browser harness:
```sh
cargo test --release --locked --workspace
cargo run -p xtask -- build --target x86_64-pc-windows-msvc --test-harness true
cargo run -p xtask -- smoke --target x86_64-pc-windows-msvc --scenario offline-ui --out target/evidence/native-ui
cargo run -p xtask -- smoke --target x86_64-pc-windows-msvc --scenario migration --out target/evidence/native-migration
cargo run -p xtask -- smoke --target x86_64-pc-windows-msvc --scenario media-loopback --out target/evidence/native-media
```
Use fresh output directories and disposable profiles. Test-harness builds disable real network/device/OS
actions and are not release eligible. Generated media proves only its exercised local transport/decoder
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.
See FEATURE_COMPATIBILITY.md for recorded native evidence and explicit remaining prerequisites.
-226
View File
@@ -1,226 +0,0 @@
'use strict';
const { spawn } = require('node:child_process');
const { EventEmitter } = require('node:events');
const readline = require('node:readline');
const fs = require('node:fs');
const READY_TIMEOUT_MS = 15000;
const STOP_TIMEOUT_MS = 6000;
const AUDIO_BACKLOG_LIMIT = 128 * 1024;
const MAX_LINE_BYTES = 256 * 1024;
const TIMEOUTS = {
connect: 60000,
disconnect: 10000,
rename: 15000,
join_channel: 15000,
send_text: 15000,
stream_list: 15000,
default: 15000,
};
/**
* Owns one `teamspeach-core` child process speaking the newline-JSON protocol of docs/bridge.md.
* Emits: 'event' (core event object), 'status' ({status, code?, message?, coreVersion?}).
*/
class CoreProcess extends EventEmitter {
constructor({ binary, dataDir, logFile, logLevel }) {
super();
this.binary = binary;
this.dataDir = dataDir;
this.logFile = logFile;
this.logLevel = logLevel || 'info';
this.child = null;
this.pending = new Map();
this.nextId = 1;
this.status = 'stopped';
this.coreVersion = null;
this.stopping = false;
this.droppedAudioFrames = 0;
}
start() {
if (this.child) throw new Error('core already running');
this.stopping = false;
this.coreVersion = null;
rotateLog(this.logFile);
const log = fs.createWriteStream(this.logFile, { flags: 'a' });
log.write(`\n=== ${new Date().toISOString()} start ${this.binary}\n`);
let child;
try {
child = spawn(this.binary, ['--data-dir', this.dataDir], {
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
env: { ...process.env, TEAMSPEACH_LOG: process.env.TEAMSPEACH_LOG || this.logLevel },
});
} catch (err) {
log.end();
this._setStatus('failed', { reason: 'spawn', message: err.message });
return;
}
this.child = child;
this._setStatus('starting');
child.stderr.on('data', (chunk) => log.write(chunk));
child.stdin.on('error', (err) => log.write(`[main] stdin error: ${err.message}\n`));
const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
rl.on('line', (line) => this._onLine(line, log));
const readyTimer = setTimeout(() => {
if (this.status === 'starting') {
log.write('[main] core did not report ready in time, terminating\n');
this._setStatus('failed', { reason: 'ready_timeout', message: 'The core did not report ready within 15 seconds' });
child.kill();
}
}, READY_TIMEOUT_MS);
child.on('error', (err) => {
clearTimeout(readyTimer);
log.write(`[main] spawn error: ${err.message}\n`);
this._setStatus('failed', { reason: 'spawn', message: err.message });
});
child.on('exit', (code, signal) => {
clearTimeout(readyTimer);
rl.close();
log.write(`[main] core exited code=${code} signal=${signal}\n`);
log.end();
this.child = null;
for (const [, entry] of this.pending) {
clearTimeout(entry.timer);
entry.resolve({ ok: false, error: { code: 'core_exited', message: 'The core exited' } });
}
this.pending.clear();
const expected = this.stopping;
this._setStatus(expected ? 'stopped' : 'exited', { code, signal, message: exitMessage(code) });
});
this.once('ready-internal', () => clearTimeout(readyTimer));
}
_onLine(line, log) {
if (!line) return;
let msg;
try {
msg = JSON.parse(line);
} catch {
log.write(`[main] unparseable stdout line (${line.length} chars)\n`);
return;
}
if (msg === null || typeof msg !== 'object') return;
if (Object.prototype.hasOwnProperty.call(msg, 'id')) {
const entry = this.pending.get(msg.id);
if (!entry) return;
this.pending.delete(msg.id);
clearTimeout(entry.timer);
entry.resolve(msg.ok ? { ok: true, result: msg.result ?? {} } : { ok: false, error: normalizeError(msg.error) });
return;
}
if (msg.event === 'ready') {
this.coreVersion = typeof msg.core_version === 'string' ? msg.core_version : null;
if (msg.protocol !== 1) {
log.write(`[main] unsupported core protocol ${msg.protocol}\n`);
this._setStatus('failed', { reason: 'protocol', protocol: msg.protocol, message: `Unsupported core protocol version: ${msg.protocol}` });
this.child?.kill();
return;
}
this.emit('ready-internal');
this._setStatus('ready', { coreVersion: this.coreVersion });
return;
}
if (typeof msg.event === 'string') this.emit('event', msg);
}
_setStatus(status, extra = {}) {
this.status = status;
this.emit('status', { status, ...extra });
}
get running() {
return this.child !== null;
}
request(cmd, args) {
if (!this.child || this.status !== 'ready') {
return Promise.resolve({ ok: false, error: { code: 'core_unavailable', message: 'The core is not running' } });
}
const id = `m${this.nextId++}`;
const payload = args === undefined ? { id, cmd } : { id, cmd, args };
const line = JSON.stringify(payload) + '\n';
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
return Promise.resolve({ ok: false, error: { code: 'bad_request', message: 'Request too large' } });
}
return new Promise((resolve) => {
const timeoutMs = TIMEOUTS[cmd] ?? TIMEOUTS.default;
const timer = setTimeout(() => {
this.pending.delete(id);
resolve({ ok: false, error: { code: 'timeout', message: `The core did not answer "${cmd}" within ${Math.round(timeoutMs / 1000)} s` } });
}, timeoutMs);
this.pending.set(id, { resolve, timer });
this.child.stdin.write(line);
});
}
/** audio_frame / audio_end: never answered. Frames are dropped instead of queueing unboundedly behind a stalled pipe. */
sendAudio(cmd, args) {
if (!this.child || this.status !== 'ready') return false;
if (cmd === 'audio_frame' && this.child.stdin.writableLength > AUDIO_BACKLOG_LIMIT) {
this.droppedAudioFrames += 1;
return false;
}
this.child.stdin.write(JSON.stringify(args === undefined ? { cmd } : { cmd, args }) + '\n');
return true;
}
async stop() {
const child = this.child;
if (!child) return;
this.stopping = true;
const exited = new Promise((resolve) => child.once('exit', resolve));
if (this.status === 'ready') {
await Promise.race([this.request('shutdown'), delay(STOP_TIMEOUT_MS)]);
} else {
child.stdin.end();
}
const done = await Promise.race([exited.then(() => true), delay(STOP_TIMEOUT_MS).then(() => false)]);
if (!done && this.child) {
this.child.kill();
await Promise.race([exited, delay(2000)]);
}
}
}
function normalizeError(error) {
if (!error || typeof error !== 'object') return { code: 'internal', message: 'Empty error response' };
const out = { code: String(error.code ?? 'internal'), message: String(error.message ?? '') };
if (error.ts_error && typeof error.ts_error === 'object') out.ts_error = error.ts_error;
if (error.detail && typeof error.detail === 'object') out.detail = error.detail;
return out;
}
function exitMessage(code) {
switch (code) {
case 0: return 'The core exited';
case 2: return 'The core rejected its start arguments';
case 3: return 'The profile is in use by another TeamsPeach instance or the data directory is unavailable';
case 1: return 'Internal core error (details in core.log)';
default: return `The core exited with code ${code}`;
}
}
function rotateLog(file) {
try {
if (fs.statSync(file).size > 5 * 1024 * 1024) fs.renameSync(file, `${file}.1`);
} catch {
// no log yet
}
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
module.exports = { CoreProcess };
-146
View File
@@ -1,146 +0,0 @@
'use strict';
/**
* Allowlist + argument-shape validation for renderer → core requests.
* The renderer may only call these bridge commands; `shutdown`, `audio_frame` and `audio_end`
* are main-owned (audio has its own binary IPC channel). Unknown keys are rejected like the core does.
*/
class ValidationError extends Error {
constructor(message) {
super(message);
this.code = 'bad_request';
}
}
const CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
const str = (min, max, { multiline = false, maxBytes } = {}) => (value, key) => {
if (typeof value !== 'string') throw new ValidationError(`${key}: expected a string`);
if (value.length < min || value.length > max) throw new ValidationError(`${key}: invalid length`);
if (maxBytes !== undefined && Buffer.byteLength(value, 'utf8') > maxBytes) throw new ValidationError(`${key}: too long`);
if (multiline ? CONTROL_CHARS.test(value) : /[\u0000-\u001f\u007f]/.test(value)) {
throw new ValidationError(`${key}: control characters are not allowed`);
}
return value;
};
const posInt = (value, key) => {
if (!Number.isSafeInteger(value) || value < 0) throw new ValidationError(`${key}: expected a non-negative integer`);
return value;
};
const bool = (value, key) => {
if (typeof value !== 'boolean') throw new ValidationError(`${key}: expected true/false`);
return value;
};
const oneOf = (...allowed) => (value, key) => {
if (!allowed.includes(value)) throw new ValidationError(`${key}: value not allowed`);
return value;
};
const optional = (check) => {
const wrapped = (value, key) => check(value, key);
wrapped.optional = true;
return wrapped;
};
function isPlainObject(value) {
return value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
}
function shape(spec) {
return (args) => {
if (args === undefined || args === null) args = {};
if (!isPlainObject(args)) throw new ValidationError('args: expected an object');
for (const key of Object.keys(args)) {
if (!Object.prototype.hasOwnProperty.call(spec, key)) throw new ValidationError(`${key}: unknown argument`);
}
const out = {};
for (const [key, check] of Object.entries(spec)) {
const value = args[key];
if (value === undefined) {
if (!check.optional) throw new ValidationError(`${key}: required argument`);
continue;
}
out[key] = check(value, key);
}
return out;
};
}
const streamId = str(1, 256);
const SIGNAL_COMMANDS = new Set(['answer', 'iceCandidate']);
function signalJson(value) {
if (!isPlainObject(value)) throw new ValidationError('json: expected an object');
const keys = Object.keys(value);
if (keys.length !== 2 || !keys.includes('cmd') || !keys.includes('args')) throw new ValidationError('json: expected exactly the fields cmd and args');
if (!SIGNAL_COMMANDS.has(value.cmd)) throw new ValidationError('json.cmd: signalling command not allowed');
const args = value.args;
if (!isPlainObject(args)) throw new ValidationError('json.args: expected an object');
if (value.cmd === 'answer') {
shape({ answer: str(1, 60000, { multiline: true }) })(args);
} else {
shape({
mLine: posInt,
mid: str(0, 64),
sdp: str(0, 2048),
})(args);
}
const serialized = JSON.stringify(value);
if (Buffer.byteLength(serialized, 'utf8') > 60 * 1024) throw new ValidationError('json: larger than 60 KiB');
return JSON.parse(serialized);
}
const COMMANDS = {
profile_get: shape({}),
profile_create: shape({ nickname: str(1, 64) }),
rename: shape({ nickname: str(1, 64) }),
connect: shape({
address: str(1, 255),
server_password: optional(str(0, 255)),
channel: optional(str(1, 512)),
channel_password: optional(str(0, 255)),
}),
disconnect: shape({ message: optional(str(0, 80)) }),
join_channel: shape({ channel_id: posInt, password: optional(str(0, 255)) }),
send_text: (args) => {
const out = shape({
target: oneOf('channel', 'server', 'client'),
client_id: optional(posInt),
message: str(1, 8192, { multiline: true, maxBytes: 8192 }),
})(args);
if ((out.target === 'client') !== (out.client_id !== undefined)) {
throw new ValidationError('client_id: required for private messages only');
}
return out;
},
set_audio: shape({ input_muted: optional(bool), output_muted: optional(bool) }),
stream_list: shape({ client_id: optional(posInt) }),
stream_join: shape({ stream_id: streamId, client_id: posInt, message: optional(str(0, 200)) }),
stream_signal: shape({ stream_id: streamId, client_id: posInt, json: signalJson }),
stream_leave: shape({ stream_id: streamId, client_id: posInt }),
fetch_icon: shape({
icon_id: (v, k) => {
if (!Number.isSafeInteger(v) || v <= 0 || v > 0xffffffff) throw new ValidationError(`${k}: expected an icon id`);
return v;
},
}),
fetch_avatar: shape({ client_id: posInt }),
fetch_banner: shape({ channel_id: posInt }),
fetch_server_banner: shape({}),
};
/** Returns sanitized args or throws ValidationError. */
function validateRequest(cmd, args) {
if (typeof cmd !== 'string' || !Object.prototype.hasOwnProperty.call(COMMANDS, cmd)) {
const err = new ValidationError('Command not allowed');
err.code = 'unknown_command';
throw err;
}
return COMMANDS[cmd](args);
}
module.exports = { validateRequest, ValidationError, RENDERER_COMMANDS: Object.keys(COMMANDS) };
-561
View File
@@ -1,561 +0,0 @@
'use strict';
const path = require('node:path');
const fs = require('node:fs');
const { execFile } = require('node:child_process');
const {
app, BrowserWindow, ipcMain, protocol, session, nativeTheme, dialog, Menu, shell, clipboard,
} = require('electron');
// A disposable profile directory for tests/second instances. Set by whoever launches the app, never by the renderer.
const profileOverride = process.env.TEAMSPEACH_PROFILE_DIR;
if (profileOverride) {
if (!path.isAbsolute(profileOverride)) {
console.error('TEAMSPEACH_PROFILE_DIR must be an absolute path');
process.exit(2);
}
app.setPath('userData', profileOverride);
}
const { RENDERER_DIR, resolveCoreBinary, dataDir, logsDir, prefsFile } = require('./paths');
const { CoreProcess } = require('./core-process');
const { validateRequest } = require('./ipc-validate');
const { permissionCheckAllowed, permissionRequestAllowed } = require('./permissions');
// Same switch the core uses for its own verbosity (see docs/bridge.md).
const RENDERER_DEBUG_LOG = /\b(debug|trace)\b/.test(process.env.TEAMSPEACH_LOG ?? '');
const { Prefs } = require('./prefs');
const { createUpdateService } = require('./updates');
const i18n = require('../renderer/shared/i18n.js');
const APP_SCHEME = 'app';
const APP_HOST = 'teamspeach';
const APP_ORIGIN = `${APP_SCHEME}://${APP_HOST}`;
const CSP = [
"default-src 'none'",
"script-src 'self'",
"style-src 'self'",
"img-src 'self' data: blob:",
"media-src 'self' blob: mediastream:",
"font-src 'self'",
"connect-src 'none'",
"worker-src 'self'",
"base-uri 'none'",
"form-action 'none'",
"frame-src 'none'",
"frame-ancestors 'none'",
"object-src 'none'",
].join('; ');
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.woff2': 'font/woff2',
'.json': 'application/json',
};
// Chromium hides host candidates behind mDNS names when the page has no capture permission.
// The TS6 streamer is native libwebrtc; plain host candidates keep LAN viewing working even while the mic is off.
app.commandLine.appendSwitch('disable-features', 'WebRtcHideLocalIpsWithMdns');
// Hardware video decoding policy is a launch-time Chromium switch, so it is read from the saved
// preferences before the app is ready and only changes after a restart.
const hardwareVideoDecodeAtLaunch = new Prefs(prefsFile()).get().hardwareVideoDecode;
if (!hardwareVideoDecodeAtLaunch) app.commandLine.appendSwitch('disable-accelerated-video-decode');
protocol.registerSchemesAsPrivileged([
{ scheme: APP_SCHEME, privileges: { standard: true, secure: true, supportFetchAPI: true, codeCache: true } },
]);
let mainWindow = null;
let core = null;
let prefs = null;
const gotInstanceLock = app.requestSingleInstanceLock();
if (!gotInstanceLock) {
app.quit();
} else {
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
let coreStatus = { status: 'starting' };
let connectionState = 'disconnected';
let updates = null;
let quitting = false;
let rendererLog = null;
let rendererLogBudget = { windowStart: 0, count: 0 };
function isAppUrl(url) {
return typeof url === 'string' && url.startsWith(`${APP_ORIGIN}/`);
}
function trustedSender(event) {
return Boolean(mainWindow && event.sender === mainWindow.webContents && event.senderFrame && isAppUrl(event.senderFrame.url));
}
function sendToRenderer(channel, payload) {
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send(channel, payload);
}
// ---------- core lifecycle ----------
function startCore() {
const binary = resolveCoreBinary();
if (!binary.path) {
coreStatus = { status: 'missing', candidates: binary.candidates };
sendToRenderer('core:status', coreStatus);
return;
}
fs.mkdirSync(logsDir(), { recursive: true });
core = new CoreProcess({
binary: binary.path,
dataDir: dataDir(),
logFile: path.join(logsDir(), 'core.log'),
});
core.on('status', (status) => {
coreStatus = { ...status, binary: binary.path };
if (status.status !== 'ready') connectionState = 'disconnected';
sendToRenderer('core:status', coreStatus);
});
core.on('event', onCoreEvent);
core.start();
}
function onCoreEvent(evt) {
if (evt.event === 'audio') {
if (typeof evt.pcm !== 'string') return;
const pcm = Buffer.from(evt.pcm, 'base64');
if (pcm.length !== 1920) return;
sendToRenderer('core:audio', { pcm, speakers: Array.isArray(evt.speakers) ? evt.speakers : [] });
return;
}
if (evt.event === 'state' && typeof evt.state === 'string') connectionState = evt.state;
if (evt.event === 'state' && evt.state === 'disconnected') externalMedia.clear();
if (evt.event === 'snapshot' && Array.isArray(evt.clients)) {
for (const c of evt.clients) {
if (Array.isArray(c.myts_avatars)) for (const v of c.myts_avatars) allowExternalMedia(v && v.url);
}
}
sendToRenderer('core:event', evt);
}
async function restartCore() {
if (core) {
const old = core;
core = null;
await old.stop();
old.removeAllListeners();
}
startCore();
}
function runCoreCli(args) {
const binary = resolveCoreBinary();
if (!binary.path) return Promise.resolve({ ok: false, error: { code: 'core_missing', message: 'Core executable not found' } });
return new Promise((resolve) => {
execFile(binary.path, args, { windowsHide: true, timeout: 30000, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
if (stderr) appendLog('core-cli.log', stderr);
const line = String(stdout || '').trim().split(/\r?\n/).filter(Boolean).pop();
let parsed = null;
try {
parsed = line ? JSON.parse(line) : null;
} catch {
parsed = null;
}
if (parsed && typeof parsed === 'object') {
resolve(parsed.ok ? { ok: true, uid: parsed.uid } : { ok: false, error: parsed.error || { code: 'internal', message: 'Unknown error' } });
return;
}
resolve({ ok: false, error: { code: 'internal', message: err ? err.message : 'The core returned no result' } });
});
});
}
function appendLog(file, text) {
try {
fs.mkdirSync(logsDir(), { recursive: true });
fs.appendFileSync(path.join(logsDir(), file), `${new Date().toISOString()} ${text}\n`);
} catch {
// logging must never break the app
}
}
// ---------- external images announced by the server (http/https only) ----------
const EXTERNAL_MEDIA_LIMIT = 4 * 1024 * 1024;
const externalMedia = new Set();
let mediaSession = null;
/** Only URLs the core reported from server data may be fetched; the renderer cannot add its own. */
function allowExternalMedia(url) {
if (typeof url !== 'string' || url.length > 2048) return;
try {
const u = new URL(url);
if (u.protocol !== 'https:' && u.protocol !== 'http:') return;
} catch {
return;
}
if (externalMedia.size >= 512) externalMedia.clear();
externalMedia.add(url);
}
function sniffImage(b) {
if (b.length >= 8 && b.readUInt32BE(0) === 0x89504e47) return 'image/png';
if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'image/jpeg';
if (b.length >= 6 && b.toString('latin1', 0, 4) === 'GIF8') return 'image/gif';
if (b.length >= 12 && b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP') return 'image/webp';
if (b.length >= 4 && b.readUInt32BE(0) === 0x00000100) return 'image/x-icon';
return null;
}
async function fetchExternalMedia(url) {
if (typeof url !== 'string' || !externalMedia.has(url)) {
return { ok: false, error: { code: 'forbidden', message: 'The server did not announce this address' } };
}
if (!mediaSession) mediaSession = session.fromPartition('teamspeach-media', { cache: true });
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
try {
const res = await mediaSession.fetch(url, { signal: controller.signal, headers: { Accept: 'image/*' } });
const finalProtocol = new URL(res.url || url).protocol;
if (finalProtocol !== 'https:' && finalProtocol !== 'http:') throw new Error('redirect to a non-http scheme');
if (!res.ok) return { ok: false, error: { code: 'http_error', message: `HTTP ${res.status}` } };
const reader = res.body.getReader();
const chunks = [];
let size = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > EXTERNAL_MEDIA_LIMIT) {
controller.abort();
return { ok: false, error: { code: 'media_too_large', message: 'Image larger than 4 MiB' } };
}
chunks.push(Buffer.from(value));
}
const bytes = Buffer.concat(chunks);
// Servers mislabel images (e.g. text/plain); trust only the bytes.
const mime = sniffImage(bytes);
if (!mime) return { ok: false, error: { code: 'media_unsupported', message: 'Not an image' } };
return { ok: true, result: { mime, bytes: bytes.length, data: bytes.toString('base64') } };
} catch (err) {
return { ok: false, error: { code: 'io', message: err.name === 'AbortError' ? 'Download timed out' : err.message } };
} finally {
clearTimeout(timer);
}
}
// ---------- identity backup (main-only, native dialogs) ----------
/** Native dialog text in the user's interface language. */
function tr(key, params) {
return i18n.t(key, params, prefs.get().language);
}
async function exportIdentity() {
const result = await dialog.showSaveDialog(mainWindow, {
title: tr('native.identityExport.title'),
defaultPath: path.join(app.getPath('documents'), 'teamspeach-identity.ini'),
filters: [{ name: tr('native.identity.filter'), extensions: ['ini'] }],
properties: ['showOverwriteConfirmation', 'createDirectory'],
});
if (result.canceled || !result.filePath) return { ok: false, canceled: true };
const outcome = await runCoreCli(['identity', 'export', '--data-dir', dataDir(), '--out', result.filePath]);
if (outcome.ok && process.platform !== 'win32') {
try {
fs.chmodSync(result.filePath, 0o600);
} catch (err) {
appendLog('core-cli.log', `chmod failed: ${err.message}`);
}
}
return outcome.ok ? { ok: true, uid: outcome.uid, file: path.basename(result.filePath) } : outcome;
}
async function importIdentity() {
if (connectionState !== 'disconnected') {
return { ok: false, error: { code: 'connected', message: 'Disconnect from the server first' } };
}
const identityExists = fs.existsSync(path.join(dataDir(), 'identity.json'));
if (identityExists) {
const confirm = await dialog.showMessageBox(mainWindow, {
type: 'warning',
title: tr('native.identityReplace.title'),
message: tr('native.identityReplace.message'),
detail: tr('native.identityReplace.detail'),
buttons: [tr('native.identityReplace.cancel'), tr('native.identityReplace.confirm')],
defaultId: 0,
cancelId: 0,
noLink: true,
});
if (confirm.response !== 1) return { ok: false, canceled: true };
}
const pick = await dialog.showOpenDialog(mainWindow, {
title: tr('native.identityImport.title'),
filters: [{ name: tr('native.identity.filter'), extensions: ['ini'] }, { name: tr('native.allFiles'), extensions: ['*'] }],
properties: ['openFile'],
});
if (pick.canceled || pick.filePaths.length !== 1) return { ok: false, canceled: true };
const old = core;
core = null;
if (old) {
await old.stop();
old.removeAllListeners();
}
const args = ['identity', 'import', '--data-dir', dataDir(), '--in', pick.filePaths[0]];
if (identityExists) args.push('--replace');
const outcome = await runCoreCli(args);
startCore();
return outcome;
}
// ---------- window ----------
function createWindow() {
mainWindow = new BrowserWindow({
width: 1220,
height: 780,
minWidth: 880,
minHeight: 560,
show: false,
title: 'TeamsPeach',
backgroundColor: nativeTheme.shouldUseDarkColors ? '#1a1817' : '#f6f3f0',
icon: path.join(__dirname, '..', 'renderer', 'assets', 'icon.png'),
webPreferences: {
preload: path.join(__dirname, '..', 'preload', 'preload.js'),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
nodeIntegrationInWorker: false,
webSecurity: true,
spellcheck: false,
autoplayPolicy: 'no-user-gesture-required',
devTools: !app.isPackaged || process.env.TEAMSPEACH_DEVTOOLS === '1',
},
});
mainWindow.once('ready-to-show', () => mainWindow.show());
mainWindow.on('closed', () => {
mainWindow = null;
});
mainWindow.loadURL(`${APP_ORIGIN}/index.html`);
}
function registerProtocol() {
protocol.handle(APP_SCHEME, async (request) => {
const url = new URL(request.url);
if (url.host !== APP_HOST) return new Response('Not found', { status: 404 });
let rel;
try {
rel = decodeURIComponent(url.pathname);
} catch {
return new Response('Bad request', { status: 400 });
}
if (rel === '/' || rel === '') rel = '/index.html';
const filePath = path.normalize(path.join(RENDERER_DIR, rel));
if (!filePath.startsWith(RENDERER_DIR + path.sep)) return new Response('Forbidden', { status: 403 });
const type = MIME[path.extname(filePath).toLowerCase()];
if (!type) return new Response('Forbidden', { status: 403 });
try {
const body = await fs.promises.readFile(filePath);
return new Response(body, {
status: 200,
headers: {
'Content-Type': type,
'Content-Security-Policy': CSP,
'X-Content-Type-Options': 'nosniff',
'Cross-Origin-Opener-Policy': 'same-origin',
'Referrer-Policy': 'no-referrer',
},
});
} catch {
return new Response('Not found', { status: 404 });
}
});
}
function hardenSession() {
const ses = session.defaultSession;
// Electron passes origins as "app://teamspeach/"; the policy normalises them (see permissions.js).
ses.setPermissionRequestHandler((_wc, permission, callback, details) => {
callback(permissionRequestAllowed(permission, details, APP_ORIGIN));
});
ses.setPermissionCheckHandler((_wc, permission, requestingOrigin, details) => {
return permissionCheckAllowed(permission, requestingOrigin, details, APP_ORIGIN);
});
ses.setDisplayMediaRequestHandler((_request, callback) => callback({}));
}
app.on('web-contents-created', (_event, contents) => {
contents.on('will-navigate', (event, url) => {
if (!isAppUrl(url)) event.preventDefault();
});
contents.on('will-redirect', (event, url) => {
if (!isAppUrl(url)) event.preventDefault();
});
contents.setWindowOpenHandler(() => ({ action: 'deny' }));
contents.on('will-attach-webview', (event) => event.preventDefault());
});
// ---------- IPC ----------
function registerIpc() {
ipcMain.handle('core:request', async (event, cmd, args) => {
if (!trustedSender(event)) return { ok: false, error: { code: 'forbidden', message: 'forbidden' } };
let clean;
try {
clean = validateRequest(cmd, args);
} catch (err) {
return { ok: false, error: { code: err.code || 'bad_request', message: err.message } };
}
if (!core) return { ok: false, error: { code: 'core_unavailable', message: 'The core is not running' } };
const hasArgs = Object.keys(clean).length > 0;
const response = await core.request(cmd, hasArgs ? clean : undefined);
if (!response.ok && response.error.code === 'external_media' && response.error.detail) {
const detail = response.error.detail;
allowExternalMedia(detail.url);
if (Array.isArray(detail.urls)) for (const v of detail.urls) allowExternalMedia(v && v.url);
}
return response;
});
ipcMain.on('core:audio-frame', (event, frame) => {
if (!core || !trustedSender(event)) return;
if (!(frame instanceof Uint8Array) || frame.byteLength !== 1920) return;
core.sendAudio('audio_frame', { pcm: Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength).toString('base64') });
});
ipcMain.on('core:audio-end', (event) => {
if (!core || !trustedSender(event)) return;
core.sendAudio('audio_end');
});
ipcMain.handle('core:status', (event) => (trustedSender(event) ? coreStatus : null));
ipcMain.handle('core:restart', async (event) => {
if (!trustedSender(event)) return false;
await restartCore();
return true;
});
ipcMain.handle('app:info', (event) => {
if (!trustedSender(event)) return null;
return {
appVersion: app.getVersion(),
electron: process.versions.electron,
chrome: process.versions.chrome,
platform: process.platform,
arch: process.arch,
packaged: app.isPackaged,
coreVersion: core ? core.coreVersion : null,
coreBinary: coreStatus.binary || null,
dataDir: dataDir(),
logsDir: logsDir(),
};
});
ipcMain.handle('prefs:get', (event) => (trustedSender(event) ? prefs.get() : null));
ipcMain.handle('prefs:set', (event, partial) => {
if (!trustedSender(event)) return { ok: false };
try {
const next = prefs.set(partial);
if (partial && Object.prototype.hasOwnProperty.call(partial, 'theme')) nativeTheme.themeSource = next.theme;
return { ok: true, prefs: next };
} catch (err) {
return { ok: false, message: err.message };
}
});
ipcMain.handle('identity:export', (event) => (trustedSender(event) ? exportIdentity() : { ok: false }));
ipcMain.handle('identity:import', (event) => (trustedSender(event) ? importIdentity() : { ok: false }));
ipcMain.handle('media:external', (event, url) => (trustedSender(event) ? fetchExternalMedia(url) : { ok: false }));
ipcMain.handle('clipboard:write', (event, text) => {
if (!trustedSender(event) || typeof text !== 'string' || text.length > 4096) return false;
clipboard.writeText(text);
return true;
});
ipcMain.handle('app:video-status', (event) => {
if (!trustedSender(event)) return null;
return { hardwareDecodeAtLaunch: hardwareVideoDecodeAtLaunch, gpu: app.getGPUFeatureStatus() };
});
ipcMain.handle('app:relaunch', (event) => {
if (!trustedSender(event)) return false;
app.relaunch();
app.quit();
return true;
});
ipcMain.handle('app:open-logs', async (event) => {
if (!trustedSender(event)) return false;
fs.mkdirSync(logsDir(), { recursive: true });
return (await shell.openPath(logsDir())) === '';
});
ipcMain.on('app:log', (event, level, message) => {
if (!trustedSender(event) || typeof message !== 'string') return;
const now = Date.now();
if (now - rendererLogBudget.windowStart > 1000) rendererLogBudget = { windowStart: now, count: 0 };
if (++rendererLogBudget.count > 40) return;
const lvl = ['debug', 'info', 'warn', 'error'].includes(level) ? level : 'info';
// Per-burst voice diagnostics are debug level: written only when started with TEAMSPEACH_LOG=debug|trace.
if (lvl === 'debug' && !RENDERER_DEBUG_LOG) return;
if (!rendererLog) {
fs.mkdirSync(logsDir(), { recursive: true });
rendererLog = fs.createWriteStream(path.join(logsDir(), 'renderer.log'), { flags: 'a' });
}
rendererLog.write(`${new Date().toISOString()} ${lvl} ${message.slice(0, 4000).replace(/[\r\n]+/g, ' ')}\n`);
});
}
// ---------- app lifecycle ----------
app.whenReady().then(() => {
if (!gotInstanceLock) return;
Menu.setApplicationMenu(null);
prefs = new Prefs(prefsFile());
// Explicit theme choice drives Chromium's prefers-color-scheme; 'system' follows the OS.
nativeTheme.themeSource = prefs.get().theme;
registerProtocol();
hardenSession();
registerIpc();
if (process.env.TEAMSPEACH_TEST_HOLD_WINDOW === '1') {
// Test harness only (scripts/lib/electron-app.mjs with --exe): Playwright cannot inject its startup loader
// into a packaged app, and attaching while the first page commits loses its utility world, so the harness
// attaches first and then creates the window through this hook.
globalThis.__teamspeachCreateWindow = () => {
delete globalThis.__teamspeachCreateWindow;
createWindow();
};
} else {
createWindow();
}
startCore();
// Updates come only from published releases of the public repo; nothing installs without a click.
updates = createUpdateService({
prefs,
isSessionActive: () => connectionState !== 'disconnected',
send: (state) => sendToRenderer('update:state', state),
});
updates.registerIpc(ipcMain, trustedSender);
updates.start();
});
app.on('window-all-closed', () => app.quit());
app.on('before-quit', (event) => {
if (quitting || !core || !core.running) return;
event.preventDefault();
quitting = true;
core.stop().finally(() => app.quit());
});
-47
View File
@@ -1,47 +0,0 @@
'use strict';
const path = require('node:path');
const fs = require('node:fs');
const { app } = require('electron');
const CORE_FILE = process.platform === 'win32' ? 'teamspeach-core.exe' : 'teamspeach-core';
const APP_ROOT = path.resolve(__dirname, '..', '..');
const RENDERER_DIR = path.join(APP_ROOT, 'app', 'renderer');
/** Candidate locations of the native core. Only main decides these; nothing comes from the renderer. */
function coreCandidates() {
if (app.isPackaged) return [path.join(process.resourcesPath, 'core', CORE_FILE)];
return [
path.join(APP_ROOT, 'core', 'target', 'release', CORE_FILE),
path.join(APP_ROOT, 'core', 'target', 'debug', CORE_FILE),
];
}
/** Newest existing candidate wins in development so a fresh debug build is not shadowed by a stale release build. */
function resolveCoreBinary() {
const candidates = coreCandidates();
let best = null;
for (const candidate of candidates) {
try {
const stat = fs.statSync(candidate);
if (stat.isFile() && (!best || stat.mtimeMs > best.mtimeMs)) best = { path: candidate, mtimeMs: stat.mtimeMs };
} catch {
// missing candidate
}
}
return { path: best ? best.path : null, candidates };
}
function dataDir() {
return path.join(app.getPath('userData'), 'core');
}
function logsDir() {
return path.join(app.getPath('userData'), 'logs');
}
function prefsFile() {
return path.join(app.getPath('userData'), 'prefs.json');
}
module.exports = { APP_ROOT, RENDERER_DIR, CORE_FILE, resolveCoreBinary, dataDir, logsDir, prefsFile };
-44
View File
@@ -1,44 +0,0 @@
'use strict';
/**
* Media permission policy for the app's own origin. Electron reports origins as a URL spec with a
* trailing slash ("app://teamspeach/"), so origins are compared after normalisation. Only audio is
* ever allowed: microphone capture on request, device enumeration and output selection on check.
* Camera, screen capture and every other permission stay denied.
*/
// WHATWG URL reports "null" as the origin of non-special schemes such as app:, so the origin is rebuilt from
// the parsed protocol and host. Inputs with credentials or backslashes (lookalikes such as
// "app://teamspeach\@evil" or "app://teamspeach@evil") never match.
function normalizeOrigin(origin) {
if (typeof origin !== 'string' || origin.includes('\\')) return '';
let url;
try {
url = new URL(origin);
} catch {
return '';
}
if (url.username || url.password || !url.host) return '';
return `${url.protocol}//${url.host}`.toLowerCase();
}
function isAppOrigin(origin, appOrigin) {
return normalizeOrigin(origin) === appOrigin;
}
/** setPermissionCheckHandler: enumerateDevices labels/ids and setSinkId depend on this. */
function permissionCheckAllowed(permission, requestingOrigin, details, appOrigin) {
if (!isAppOrigin(requestingOrigin, appOrigin)) return false;
if (permission === 'media') return Boolean(details) && details.mediaType === 'audio';
return permission === 'speaker-selection';
}
/** setPermissionRequestHandler: getUserMedia for audio only, from a page of the app. */
function permissionRequestAllowed(permission, details, appOrigin) {
if (permission !== 'media' || !details) return false;
if (!isAppOrigin(details.requestingUrl, appOrigin)) return false;
const types = Array.isArray(details.mediaTypes) ? details.mediaTypes : [];
return types.length > 0 && types.every((t) => t === 'audio');
}
module.exports = { normalizeOrigin, permissionCheckAllowed, permissionRequestAllowed };
-93
View File
@@ -1,93 +0,0 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
/**
* UI preferences owned by main (identity/nickname live in the core data dir, never here).
* Every key has a validator; unknown keys and wrong types are rejected.
*/
const SCHEMA = {
lastAddress: { default: '', check: (v) => typeof v === 'string' && v.length <= 255 && !/[\u0000-\u001f]/.test(v) },
transmitMode: { default: 'ptt', check: (v) => v === 'ptt' || v === 'open' },
pttCode: { default: 'F8', check: (v) => typeof v === 'string' && /^[A-Za-z0-9]{1,32}$/.test(v) },
inputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
outputDeviceId: { default: '', check: (v) => typeof v === 'string' && v.length <= 512 },
echoCancellation: { default: true, check: (v) => typeof v === 'boolean' },
noiseSuppression: { default: true, check: (v) => typeof v === 'boolean' },
autoGainControl: { default: true, check: (v) => typeof v === 'boolean' },
voiceVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 200 },
hardwareVideoDecode: { default: true, check: (v) => typeof v === 'boolean' },
streamVolume: { default: 100, check: (v) => Number.isInteger(v) && v >= 0 && v <= 100 },
// Dark by default for new profiles regardless of the OS (owner's request); a stored valid choice —
// including 'system' or 'light' — is always kept.
theme: { default: 'dark', check: (v) => v === 'system' || v === 'dark' || v === 'light' },
// Updater: 'preview' accepts prereleases (all TeamsPeach releases so far), 'stable' only full releases.
updateChannel: { default: 'preview', check: (v) => v === 'preview' || v === 'stable' },
// Interface language: English for new profiles (owner's request); a stored valid choice is kept.
language: { default: 'en', check: (v) => v === 'en' || v === 'ru' },
// Quick-access servers: name + address only. Passwords are never stored.
savedServers: { default: [], check: validServers },
};
const CONTROL = /[\u0000-\u001f\u007f]/;
function validServers(list) {
if (!Array.isArray(list) || list.length > 50) return false;
const ids = new Set();
for (const s of list) {
if (!s || typeof s !== 'object' || Array.isArray(s)) return false;
const keys = Object.keys(s);
if (keys.length !== 3 || !keys.includes('id') || !keys.includes('name') || !keys.includes('address')) return false;
if (typeof s.id !== 'string' || !/^[a-z0-9]{6,32}$/.test(s.id) || ids.has(s.id)) return false;
if (typeof s.name !== 'string' || s.name.trim().length < 1 || s.name.length > 64 || CONTROL.test(s.name)) return false;
if (typeof s.address !== 'string' || s.address.trim().length < 1 || s.address.length > 255 || CONTROL.test(s.address)) return false;
ids.add(s.id);
}
return true;
}
class Prefs {
constructor(file) {
this.file = file;
this.values = defaults();
try {
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
if (raw && typeof raw === 'object') {
for (const [key, spec] of Object.entries(SCHEMA)) {
if (Object.prototype.hasOwnProperty.call(raw, key) && spec.check(raw[key])) this.values[key] = raw[key];
}
}
} catch {
// first run or unreadable file: defaults
}
}
get() {
return { ...this.values };
}
/** Applies a validated partial update; returns the full prefs or throws. */
set(partial) {
if (!partial || typeof partial !== 'object' || Array.isArray(partial)) throw new Error('prefs: expected an object');
const next = { ...this.values };
for (const [key, value] of Object.entries(partial)) {
const spec = SCHEMA[key];
if (!spec) throw new Error(`prefs: unknown key ${key}`);
if (!spec.check(value)) throw new Error(`prefs: invalid value for ${key}`);
next[key] = value;
}
this.values = next;
fs.mkdirSync(path.dirname(this.file), { recursive: true });
const tmp = `${this.file}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(next, null, 2));
fs.renameSync(tmp, this.file);
return this.get();
}
}
function defaults() {
return Object.fromEntries(Object.entries(SCHEMA).map(([key, spec]) => [key, spec.default]));
}
module.exports = { Prefs };
-277
View File
@@ -1,277 +0,0 @@
'use strict';
// Where updates come from and which published release this installation may move to.
// Pure Node (no Electron): the complete Gitea release list is fetched anonymously from one fixed HTTPS host,
// releases are filtered by channel, version (semver) and platform, and only complete releases are offered.
// electron-updater then reads the feed of the chosen release and verifies size and sha512.
const path = require('node:path');
const semver = require('semver');
const FORGE_ORIGIN = 'https://git.eeee.moe';
const OWNER = 'TeamsPeach';
const REPO = 'client';
const RELEASES_API = `${FORGE_ORIGIN}/api/v1/repos/${OWNER}/${REPO}/releases`;
const PAGE_SIZE = 50;
const MAX_PAGES = 20;
const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
const PRODUCT = 'TeamsPeach';
const LINUX_EXECUTABLE = 'teamspeach';
const ASSET_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
const SHA512_BASE64 = /^[A-Za-z0-9+/]{86}==$/;
/**
* Failure with a stable machine code and parameters; the renderer shows the localized text for `code`.
* `message` is English technical text for logs only.
*/
class UpdateError extends Error {
constructor(code, params = {}, message = code) {
super(message);
this.code = code;
this.params = params;
}
}
/** Strict SemVer 2.0 without build metadata (`0.1.2`, `0.1.2-rc.1`); null otherwise (`01.1.1`, `0.1`, `1.0.0+x`). */
function cleanVersion(text) {
if (typeof text !== 'string' || text.includes('+')) return null;
return semver.valid(text) === text ? text : null;
}
/** Release tag `v<version>`; returns the version or null. */
function tagVersion(tag) {
return typeof tag === 'string' && tag.startsWith('v') ? cleanVersion(tag.slice(1)) : null;
}
/**
* What this installation is and how it can be updated.
* mode 'auto': electron-updater installs (NSIS-installed Windows x64, Linux AppImage).
* mode 'manual': user is told and replaces files himself (Windows zip, Linux tar.gz).
* mode 'none': dev run or a platform that has no published build.
*/
function detectTarget({ platform, arch, packaged, env, execPath, exists }) {
const none = (id, disabledCode) => ({ id, platform, arch, mode: 'none', kind: null, disabledCode });
if (!packaged) return none(`${platform}-${arch}-dev`, 'dev-build');
if (platform === 'win32') {
if (arch !== 'x64') return none(`win-${arch}`, 'unsupported-platform');
// The NSIS installer leaves its uninstaller next to the executable; the portable zip does not.
if (exists(path.join(path.dirname(execPath), `Uninstall ${PRODUCT}.exe`))) {
return { id: 'win-x64-nsis', platform, arch, mode: 'auto', kind: 'nsis', disabledCode: null };
}
return { id: 'win-x64-zip', platform, arch, mode: 'manual', kind: 'zip', disabledCode: null };
}
if (platform === 'linux') {
if (arch !== 'x64' && arch !== 'arm64') return none(`linux-${arch}`, 'unsupported-platform');
if (env.APPIMAGE) return { id: `linux-${arch}-appimage`, platform, arch, mode: 'auto', kind: 'appimage', disabledCode: null };
return { id: `linux-${arch}-tar.gz`, platform, arch, mode: 'manual', kind: 'tar.gz', disabledCode: null };
}
if (platform === 'darwin') return none(`mac-${arch}`, 'unsupported-platform');
return none(`${platform}-${arch}`, 'unsupported-platform');
}
/** electron-builder names the feed after the version's first prerelease identifier, else "latest". */
function feedChannel(version) {
const pre = semver.prerelease(version);
return pre && pre.length > 0 ? String(pre[0]) : 'latest';
}
/** Exact feed file electron-builder writes for this target (app-builder-lib getUpdateInfoFileName). */
function feedFileName(target, version) {
const channel = feedChannel(version);
if (target.kind === 'nsis') return `${channel}.yml`;
if (target.kind === 'appimage') return target.arch === 'x64' ? `${channel}-linux.yml` : `${channel}-linux-${target.arch}.yml`;
return null;
}
/**
* Exact installer electron-builder produces for this target (package.json build config: AppImage default
* name, nsis.artifactName "${productName}-${version}-win-${arch}-setup.${ext}").
*/
function packageFileName(target, version) {
if (target.kind === 'appimage') return target.arch === 'x64' ? `${PRODUCT}-${version}.AppImage` : `${PRODUCT}-${version}-${target.arch}.AppImage`;
if (target.kind === 'nsis') return `${PRODUCT}-${version}-win-${target.arch}-setup.exe`;
return null;
}
/** Package names a manual-mode user downloads (builder defaults, plus the historical "-local" Windows zip). */
function manualAssetNames(target, version) {
if (target.kind === 'tar.gz') return [target.arch === 'x64' ? `${LINUX_EXECUTABLE}-${version}.tar.gz` : `${LINUX_EXECUTABLE}-${version}-${target.arch}.tar.gz`];
if (target.kind === 'zip') return [`${PRODUCT}-${version}-win-x64.zip`, `${PRODUCT}-${version}-win.zip`, `${PRODUCT}-${version}-win-x64-local.zip`];
return [];
}
function releaseDownloadBase(tag) {
return `${FORGE_ORIGIN}/${OWNER}/${REPO}/releases/download/${tag}/`;
}
function releasePageUrl(tag) {
return `${FORGE_ORIGIN}/${OWNER}/${REPO}/releases/tag/${tag}`;
}
/**
* Picks the releases this installation may update to, newest first.
* Every published, non-draft release with a valid tag is considered. A release is "preview" when Gitea
* marks it prerelease or its version has a prerelease part; the stable channel never sees previews.
* Same or older versions are never offered. A release counts only when it carries this target's feed and
* installer (auto) or package (manual); newer releases without one are reported in `withoutBuild`.
*/
function selectReleases(releases, { currentVersion, channel, target }) {
const current = cleanVersion(currentVersion);
if (!current) throw new UpdateError('bad-version', { version: String(currentVersion) }, `app version ${currentVersion} is not semver`);
if (channel !== 'preview' && channel !== 'stable') throw new UpdateError('bad-channel', { channel: String(channel) }, `unknown channel ${channel}`);
if (!Array.isArray(releases)) throw new UpdateError('bad-response', { detail: 'release list is not an array' }, 'release list is not an array');
const candidates = [];
const withoutBuild = [];
const previews = [];
for (const release of releases) {
if (!release || typeof release !== 'object' || release.draft !== false) continue;
const version = tagVersion(release.tag_name);
if (!version || !semver.gt(version, current)) continue;
const preview = release.prerelease !== false || semver.prerelease(version) !== null;
if (channel === 'stable' && preview) {
previews.push(version);
continue;
}
const assets = new Map();
for (const asset of Array.isArray(release.assets) ? release.assets : []) {
if (asset && typeof asset.name === 'string' && ASSET_NAME.test(asset.name) && Number.isSafeInteger(asset.size) && asset.size > 0) {
assets.set(asset.name, asset.size);
}
}
const tag = release.tag_name;
const entry = {
tag,
version,
preview,
publishedAt: typeof release.published_at === 'string' ? release.published_at : null,
assets,
downloadBase: releaseDownloadBase(tag),
releaseUrl: releasePageUrl(tag),
feedChannel: feedChannel(version),
feedFile: null,
packageFile: null,
manualAsset: null,
};
if (target.mode === 'auto') {
const feed = feedFileName(target, version);
const pkg = packageFileName(target, version);
if (!assets.has(feed) || !assets.has(pkg)) {
const missing = assets.has(feed) ? pkg : feed;
withoutBuild.push({ version, code: assets.has(feed) ? 'no-package' : 'no-feed', params: { version, file: missing, target: target.id } });
continue;
}
entry.feedFile = feed;
entry.packageFile = pkg;
} else if (target.mode === 'manual') {
const name = manualAssetNames(target, version).find((n) => assets.has(n));
if (!name) {
withoutBuild.push({ version, code: 'no-package', params: { version, file: manualAssetNames(target, version)[0], target: target.id } });
continue;
}
entry.manualAsset = name;
} else {
continue;
}
candidates.push(entry);
}
candidates.sort((a, b) => semver.rcompare(a.version, b.version));
withoutBuild.sort((a, b) => semver.rcompare(a.version, b.version));
previews.sort(semver.rcompare);
return { candidates, withoutBuild, newestPreview: previews.length > 0 ? previews[0] : null };
}
/**
* Checks the feed electron-updater parsed against the release it was taken from: same version, and exactly
* one package — this target's installer by its exact builder name (so an arm64 feed pointing at the x64
* AppImage, or a renamed/foreign file, is refused) — present in THIS release with the declared size and a sha512.
*/
function verifyFeed(candidate, target, updateInfo) {
const mismatch = (detail) => new UpdateError('feed-mismatch', { tag: candidate.tag, detail }, `${candidate.tag}: ${detail}`);
if (!updateInfo || typeof updateInfo !== 'object') throw mismatch('feed is empty');
if (cleanVersion(updateInfo.version) !== candidate.version) throw mismatch(`feed describes version ${String(updateInfo.version)}`);
const expected = packageFileName(target, candidate.version);
const files = Array.isArray(updateInfo.files) ? updateInfo.files : [];
if (files.length !== 1 || !files[0] || files[0].url !== expected) {
const listed = files.map((f) => (f && typeof f.url === 'string' ? f.url : '?')).join(', ') || 'nothing';
throw mismatch(`feed for ${target.id} must list only ${expected}, lists: ${listed}`);
}
if (updateInfo.path !== undefined && updateInfo.path !== expected) throw mismatch(`feed path ${String(updateInfo.path)} is not ${expected}`);
const file = files[0];
if (typeof file.sha512 !== 'string' || !SHA512_BASE64.test(file.sha512)) throw mismatch(`no sha512 for ${expected}`);
if (!candidate.assets.has(expected)) {
throw new UpdateError('incomplete-release', { tag: candidate.tag, file: expected }, `${candidate.tag} has no asset ${expected}`);
}
if (file.size !== candidate.assets.get(expected)) {
throw new UpdateError('incomplete-release', { tag: candidate.tag, file: expected }, `${candidate.tag}: size of ${expected} differs from the feed`);
}
}
/**
* Anonymous GET of EVERY published release (paged; Gitea reports the total in X-Total-Count).
* `fetchImpl` is Electron's net.fetch in the app. Network failure, timeout (whole listing), HTTP errors,
* malformed bodies and a listing that cannot be completed within MAX_PAGES all throw UpdateError —
* never a partial list that could hide a newer release.
*/
async function fetchReleases({ fetchImpl, timeoutMs = 20000 }) {
const badResponse = (detail) => new UpdateError('bad-response', { detail }, `release list: ${detail}`);
const signal = AbortSignal.timeout(timeoutMs);
const all = [];
let total = null;
for (let page = 1; page <= MAX_PAGES; page += 1) {
const url = `${RELEASES_API}?draft=false&limit=${PAGE_SIZE}&page=${page}`;
let text;
let headerTotal;
try {
const res = await fetchImpl(url, { signal, redirect: 'error', cache: 'no-store', headers: { Accept: 'application/json' } });
if (!res.ok) throw new UpdateError('http', { status: res.status }, `release list: HTTP ${res.status}`);
if (Number(res.headers.get('content-length')) > MAX_RESPONSE_BYTES) throw badResponse('response too large');
headerTotal = res.headers.get('x-total-count');
text = await res.text();
} catch (err) {
if (err instanceof UpdateError) throw err;
const seconds = Math.round(timeoutMs / 1000);
if (signal.aborted) throw new UpdateError('timeout', { seconds }, `release list: no answer in ${seconds} s`);
const detail = err && err.cause && err.cause.message ? `${err.message}: ${err.cause.message}` : String(err && err.message ? err.message : err);
throw new UpdateError('network', { detail }, `release list: ${detail}`);
}
if (text.length > MAX_RESPONSE_BYTES) throw badResponse('response too large');
let items;
try {
items = JSON.parse(text);
} catch {
throw badResponse('not JSON');
}
if (!Array.isArray(items)) throw badResponse('not a release list');
if (headerTotal !== null) {
if (!/^\d+$/.test(headerTotal)) throw badResponse('invalid X-Total-Count');
total = Number(headerTotal);
}
all.push(...items);
// Done when the server's total is reached, or (no total reported) when a page comes back empty.
if (total !== null ? all.length >= total || items.length === 0 : items.length === 0) {
if (total !== null && all.length < total) {
throw new UpdateError('incomplete-list', { fetched: all.length, total }, `release list: got ${all.length} of ${total}`);
}
return all;
}
}
throw new UpdateError('incomplete-list', { fetched: all.length, total }, `release list longer than ${MAX_PAGES} pages`);
}
module.exports = {
FORGE_ORIGIN,
RELEASES_API,
PAGE_SIZE,
UpdateError,
cleanVersion,
detectTarget,
feedFileName,
packageFileName,
manualAssetNames,
releaseDownloadBase,
releasePageUrl,
selectReleases,
verifyFeed,
fetchReleases,
};
-463
View File
@@ -1,463 +0,0 @@
'use strict';
// Update service of the main process. Finds the newest eligible published release (update-source.js),
// lets electron-updater read that release's feed, download and verify the package, and installs ONLY after
// an explicit user action. It never quits or restarts the app on its own.
//
// Every check uses a NEW electron-updater instance. electron-updater keeps the last checked feed inside the
// instance and cannot cancel a running check, so a check that timed out (or a check for another channel) can
// still finish later; with one instance per check, such a late result can only touch an abandoned instance.
// Download and install always use the exact instance that checked the offered release.
const fs = require('node:fs');
const path = require('node:path');
const { app, net, shell } = require('electron');
const source = require('./update-source');
const { logsDir } = require('./paths');
const STARTUP_DELAY_MS = 15 * 1000;
const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
const DEFERRED_POLL_MS = 60 * 1000;
const FEED_TIMEOUT_MS = 60 * 1000;
const LOG_LIMIT_BYTES = 1024 * 1024;
const CHANNELS = ['preview', 'stable'];
function fileLogger(file) {
const write = (level, parts) => {
const line = `${new Date().toISOString()} ${level} ${parts.map((p) => (p instanceof Error ? p.stack || p.message : String(p))).join(' ')}`;
try {
fs.mkdirSync(path.dirname(file), { recursive: true });
try {
if (fs.statSync(file).size > LOG_LIMIT_BYTES) fs.renameSync(file, `${file}.1`);
} catch {
// no log yet
}
fs.appendFileSync(file, `${line.replace(/[\r\n]+/g, ' ')}\n`);
} catch {
// logging must never break updating
}
};
return {
info: (...p) => write('info', p),
warn: (...p) => write('warn', p),
error: (...p) => write('error', p),
debug: () => {},
};
}
/** electron-updater instance for this target, configured so that nothing happens without our call. */
function defaultCreateUpdater(target, logger, channel) {
const { NsisUpdater, AppImageUpdater } = require('electron-updater');
const instance = target.kind === 'nsis' ? new NsisUpdater() : new AppImageUpdater();
instance.logger = logger;
instance.autoDownload = false;
instance.autoInstallOnAppQuit = false;
instance.allowDowngrade = false;
// Only the GitHub providers read allowPrerelease; with the generic provider the channel policy is applied
// by update-source before a feed is chosen. Kept consistent with the selected channel anyway.
instance.allowPrerelease = channel === 'preview';
instance.disableWebInstaller = true;
return instance;
}
const CHECKSUM_FAILURE = /checksum mismatch/i;
const NETWORK_FAILURE = /net::ERR_|ENOTFOUND|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket hang up/i;
/** Maps electron-updater / network failures to stable codes; `detail` keeps the technical text. */
function classify(err, fallback, tag) {
if (err instanceof source.UpdateError) return err;
const detail = (err && err.message ? err.message : String(err)).split('\n')[0].slice(0, 300);
const code = err && err.code;
if (code === 'ERR_CHECKSUM_MISMATCH' || CHECKSUM_FAILURE.test(detail)) return new source.UpdateError('checksum', { tag, detail }, detail);
if (code === 'ERR_UPDATER_CHANNEL_FILE_NOT_FOUND' || (err && err.statusCode === 404)) {
return new source.UpdateError('incomplete-release', { tag, file: null, detail }, detail);
}
if (err && Number.isInteger(err.statusCode)) return new source.UpdateError('http', { status: err.statusCode }, detail);
if (NETWORK_FAILURE.test(detail)) {
return new source.UpdateError('network', { detail }, detail);
}
return new source.UpdateError(fallback, { tag, detail }, detail);
}
function withTimeout(promise, ms, tag) {
let timer;
const seconds = Math.round(ms / 1000);
return Promise.race([
promise,
new Promise((_, reject) => {
timer = setTimeout(() => reject(new source.UpdateError('timeout', { seconds, tag }, `feed of ${tag}: no answer in ${seconds} s`)), ms);
}),
]).finally(() => clearTimeout(timer));
}
/**
* @param {object} o
* @param {{ get(): object, set(partial: object): object }} o.prefs holds `updateChannel`
* @param {() => boolean} o.isSessionActive true while connected to a server (voice / stream viewing)
* @param {(state: object) => void} o.send pushes the state to the renderer
* Remaining options exist for the Electron behaviour harness; the release host is not configurable.
*/
function createUpdateService({
prefs,
isSessionActive,
send,
electronApp = app,
fetchImpl = (url, init) => net.fetch(url, init),
target = source.detectTarget({
platform: process.platform,
arch: process.arch,
packaged: electronApp.isPackaged,
env: process.env,
execPath: process.execPath,
exists: fs.existsSync,
}),
createUpdater = defaultCreateUpdater,
openExternal = (url) => shell.openExternal(url),
logger = fileLogger(path.join(logsDir(), 'updater.log')),
appImagePath = () => process.env.APPIMAGE,
argv = process.argv,
feedTimeoutMs = FEED_TIMEOUT_MS,
profileOverride = process.env.TEAMSPEACH_PROFILE_DIR,
}) {
const currentVersion = electronApp.getVersion();
// The NSIS installer restarts the app through Explorer (StdUtils.ExecShellAsUser), which does not pass this
// process's environment on: an app running on a TEAMSPEACH_PROFILE_DIR profile would come back on the
// default profile. Such a run is offered the release page (manual install) instead of an automatic install.
// AppImage relaunch (app.relaunch) keeps the environment and is not affected.
const installBlock = target.kind === 'nsis' && profileOverride ? 'custom-profile' : null;
const autoInstall = target.mode === 'auto' && !installBlock;
let offered = null; // { candidate, updater } — release in state.available and the instance that checked it
let downloaded = null; // { candidate, updater } — verified package ready to install
let downloading = null; // { updater, token }
let busy = null; // in-flight check/download promise
let timers = [];
let deferredTimer = null;
let lastProgressSent = 0;
const state = {
currentVersion,
channel: 'preview',
mode: installBlock ? 'manual' : target.mode,
manualReason: installBlock, // null | 'custom-profile'
target: target.id,
phase: target.mode === 'none' ? 'disabled' : 'idle',
lastCheckedAt: null,
available: null,
progress: null,
newerWithoutBuild: [],
newerPreview: null,
error: null, // { code, params } — localized by the renderer; params.detail is technical text
disabledCode: target.disabledCode,
disabledParams: target.mode === 'none' ? { platform: target.platform, arch: target.arch } : null,
};
logger.info(`updater: version ${currentVersion} pid ${process.pid} target ${target.id} mode ${state.mode}${installBlock ? ` (${installBlock})` : ''}`);
function channel() {
const value = prefs.get().updateChannel;
return CHANNELS.includes(value) ? value : 'preview';
}
function snapshot() {
return {
...state,
channel: channel(),
available: state.available ? { ...state.available } : null,
progress: state.progress ? { ...state.progress } : null,
newerWithoutBuild: state.newerWithoutBuild.map((x) => ({ ...x, params: { ...x.params } })),
error: state.error ? { code: state.error.code, params: { ...state.error.params } } : null,
disabledParams: state.disabledParams ? { ...state.disabledParams } : null,
sessionActive: Boolean(isSessionActive()),
};
}
function emit() {
try {
send(snapshot());
} catch (err) {
logger.warn('updater: state push failed', err);
}
}
function setPhase(phase, extra = {}) {
Object.assign(state, { phase }, extra);
emit();
}
function fail(err, fallback, tag) {
const e = classify(err, fallback, tag);
logger.error(`updater: ${e.code}: ${e.message}`);
setPhase('error', { error: { code: e.code, params: e.params || {} }, progress: null });
return e;
}
function newUpdater(selectedChannel) {
const u = createUpdater(target, logger, selectedChannel);
// Failures are handled where the promises reject; the listener keeps EventEmitter from throwing.
u.on('error', (err) => logger.warn('updater: electron-updater error event', err));
u.on('download-progress', (p) => {
if (!downloading || downloading.updater !== u) return;
state.progress = { percent: Math.max(0, Math.min(100, Number(p.percent) || 0)), transferred: p.transferred, total: p.total };
const now = Date.now();
if (now - lastProgressSent >= 250) {
lastProgressSent = now;
emit();
}
});
return u;
}
/** Reads the candidate's feed through electron-updater and checks it against the release assets. */
async function readFeed(u, candidate) {
u.setFeedURL({ provider: 'generic', url: candidate.downloadBase, channel: candidate.feedChannel });
const result = await withTimeout(u.checkForUpdates(), feedTimeoutMs, candidate.tag);
if (!result) throw new source.UpdateError('feed-mismatch', { tag: candidate.tag, detail: 'updater inactive' }, 'electron-updater inactive');
source.verifyFeed(candidate, target, result.updateInfo);
if (!result.isUpdateAvailable) {
const detail = 'electron-updater: not applicable to this system';
throw new source.UpdateError('feed-mismatch', { tag: candidate.tag, detail }, detail);
}
}
async function runCheck() {
const selectedChannel = channel();
setPhase('checking', { error: null });
let selection;
try {
const releases = await source.fetchReleases({ fetchImpl });
selection = source.selectReleases(releases, { currentVersion, channel: selectedChannel, target });
} catch (err) {
fail(err, 'bad-response');
return;
}
const skipped = [...selection.withoutBuild];
let chosen = null;
if (target.mode === 'manual') {
if (selection.candidates[0]) chosen = { candidate: selection.candidates[0], updater: null };
} else {
for (const candidate of selection.candidates) {
const u = newUpdater(selectedChannel);
try {
await readFeed(u, candidate);
chosen = { candidate, updater: u };
break;
} catch (err) {
const e = classify(err, 'feed-mismatch', candidate.tag);
// A broken or incomplete release is skipped in favour of an older complete one; a network failure or
// timeout ends the check with an error, so "no update" is never reported without a full answer.
if (e.code !== 'feed-mismatch' && e.code !== 'incomplete-release') {
fail(e, 'network');
return;
}
logger.warn(`updater: skip ${candidate.tag}: ${e.message}`);
skipped.push({ version: candidate.version, code: e.code, params: { version: candidate.version, ...e.params } });
}
}
}
offered = chosen;
state.lastCheckedAt = new Date().toISOString();
state.newerWithoutBuild = skipped;
state.newerPreview = selection.newestPreview;
if (!chosen) {
downloaded = null;
logger.info(`updater: up to date (${selectedChannel}), ${skipped.length} newer release(s) without a usable build`);
setPhase('up-to-date', { available: null, progress: null, error: null });
return;
}
const c = chosen.candidate;
logger.info(`updater: ${c.tag} available (${selectedChannel})`);
const available = { version: c.version, tag: c.tag, preview: c.preview, publishedAt: c.publishedAt, assetName: c.manualAsset || c.packageFile };
if (downloaded && downloaded.candidate.tag === c.tag) {
offered = downloaded;
setPhase('downloaded', { available, error: null });
return;
}
downloaded = null;
setPhase('available', { available, progress: null, error: null });
}
async function runDownload() {
const job = offered;
const { CancellationToken } = require('electron-updater');
downloading = { updater: job.updater, token: new CancellationToken() };
const { token } = downloading;
setPhase('downloading', { progress: { percent: 0, transferred: 0, total: 0 }, error: null });
try {
await job.updater.downloadUpdate(token);
if (offered !== job) {
logger.info(`updater: ${job.candidate.tag} downloaded but no longer offered`);
return;
}
downloaded = job;
logger.info(`updater: ${job.candidate.tag} downloaded and verified`);
setPhase('downloaded', { progress: null });
} catch (err) {
if (token.cancelled) {
logger.info('updater: download cancelled');
if (offered === job) setPhase('available', { progress: null });
} else {
fail(err, 'download', job.candidate.tag);
}
} finally {
downloading = null;
}
}
function exclusive(fn) {
if (busy) return busy.then(snapshot);
busy = fn().finally(() => {
busy = null;
});
return busy.then(snapshot);
}
function scheduleDeferredPoll() {
if (deferredTimer) return;
deferredTimer = setInterval(() => {
if (state.phase !== 'deferred') {
clearInterval(deferredTimer);
deferredTimer = null;
} else if (!isSessionActive()) {
download({ manual: false });
}
}, DEFERRED_POLL_MS);
}
/** Background downloads wait while the user is connected; a manual request downloads now. */
function download({ manual }) {
if (busy) return busy.then(snapshot);
if (!autoInstall || !offered || (state.phase !== 'available' && state.phase !== 'deferred')) return Promise.resolve(snapshot());
if (!manual && isSessionActive()) {
if (state.phase !== 'deferred') {
logger.info('updater: download deferred until the session ends');
setPhase('deferred');
}
scheduleDeferredPoll();
return Promise.resolve(snapshot());
}
return exclusive(runDownload);
}
function check({ manual }) {
if (target.mode === 'none' || state.phase === 'installing') return Promise.resolve(snapshot());
return exclusive(runCheck)
.then((s) => (s.phase === 'available' && autoInstall ? download({ manual: false }) : s))
.then((s) => {
if (manual) logger.info(`updater: manual check → ${s.phase}`);
return s;
});
}
/**
* Installs the downloaded, verified package after an explicit user action. Uses electron-updater's
* quitAndInstall; its install step is synchronous and reports failures through the 'error' event.
* NSIS: silent update of the existing installation, the installer starts the new version. Whether the
* installer then succeeds happens after this process quits and is not claimed here.
* AppImage: the file is replaced, then app.relaunch() starts the new AppImage only after this process
* has exited (the single-instance lock and the core's data-dir lock are free by then).
*/
function install(options) {
const confirmInterrupt = Boolean(options && options.confirmInterrupt === true);
if (installBlock) return { ok: false, code: installBlock };
if (target.mode !== 'auto' || state.phase !== 'downloaded' || !downloaded || offered !== downloaded) {
return { ok: false, code: 'not-ready' };
}
if (isSessionActive() && !confirmInterrupt) return { ok: false, code: 'session-active' };
const u = downloaded.updater;
const tag = downloaded.candidate.tag;
setPhase('installing');
let installError = null;
let destination = appImagePath();
const onError = (err) => {
installError = err;
};
const onRename = (file) => {
destination = file;
};
u.on('error', onError);
u.on('appimage-filename-updated', onRename);
try {
if (target.kind === 'appimage') u.quitAndInstall(true, false);
else u.quitAndInstall(true, true);
} catch (err) {
installError = err;
} finally {
u.removeListener('error', onError);
u.removeListener('appimage-filename-updated', onRename);
}
if (installError) {
const e = fail(installError, 'install', tag);
return { ok: false, code: 'install-failed', params: e.params };
}
if (target.kind === 'appimage') {
// quitAndInstall quits on the next tick; the relaunch is registered before that.
electronApp.relaunch({ execPath: destination, args: argv.slice(1) });
logger.info(`updater: AppImage replaced by ${tag} at ${destination}; relaunch after exit`);
} else {
logger.info(`updater: NSIS installer for ${tag} started; app quits`);
}
return { ok: true };
}
async function setChannel(value) {
if (!CHANNELS.includes(value)) return snapshot();
if (value !== channel()) {
prefs.set({ updateChannel: value });
logger.info(`updater: channel → ${value}`);
if (downloading) downloading.token.cancel();
if (busy) await busy;
offered = null;
downloaded = null;
Object.assign(state, { available: null, progress: null, newerWithoutBuild: [], newerPreview: null });
if (state.phase !== 'disabled') setPhase('idle');
}
return check({ manual: true });
}
async function openRelease() {
if (!offered) return { ok: false };
try {
await openExternal(source.releasePageUrl(offered.candidate.tag));
return { ok: true };
} catch (err) {
logger.warn('updater: cannot open release page', err);
return { ok: false };
}
}
function start() {
if (target.mode === 'none') {
logger.info(`updater: disabled: ${target.disabledCode}`);
return;
}
timers.push(setTimeout(() => check({ manual: false }), STARTUP_DELAY_MS));
timers.push(setInterval(() => check({ manual: false }), CHECK_INTERVAL_MS));
}
function stop() {
for (const t of timers) clearTimeout(t);
timers = [];
clearInterval(deferredTimer);
deferredTimer = null;
if (downloading) downloading.token.cancel();
}
function registerIpc(ipcMain, trustedSender) {
ipcMain.handle('update:get-state', (event) => (trustedSender(event) ? snapshot() : null));
ipcMain.handle('update:check', (event) => (trustedSender(event) ? check({ manual: true }) : null));
ipcMain.handle('update:download', (event) => (trustedSender(event) ? download({ manual: true }) : null));
ipcMain.handle('update:install', (event, options) => {
if (!trustedSender(event)) return { ok: false, code: 'forbidden' };
if (options !== undefined && (options === null || typeof options !== 'object' || Array.isArray(options))) {
return { ok: false, code: 'bad-request' };
}
return install(options);
});
ipcMain.handle('update:open-release', (event) => (trustedSender(event) ? openRelease() : { ok: false }));
ipcMain.handle('update:set-channel', (event, value) => (trustedSender(event) && typeof value === 'string' ? setChannel(value) : null));
}
return { start, stop, check, download, install, setChannel, openRelease, getState: snapshot, registerIpc };
}
module.exports = { createUpdateService, createElectronUpdater: defaultCreateUpdater };
-40
View File
@@ -1,40 +0,0 @@
'use strict';
// Sandboxed preload: the only surface the renderer gets. No paths, no commands, no generic IPC.
const { contextBridge, ipcRenderer } = require('electron');
function subscribe(channel, callback) {
if (typeof callback !== 'function') throw new TypeError('callback must be a function');
const handler = (_event, payload) => callback(payload);
ipcRenderer.on(channel, handler);
return () => ipcRenderer.removeListener(channel, handler);
}
contextBridge.exposeInMainWorld('teamspeach', {
request: (cmd, args) => ipcRenderer.invoke('core:request', cmd, args),
sendAudioFrame: (frame) => ipcRenderer.send('core:audio-frame', frame),
endAudio: () => ipcRenderer.send('core:audio-end'),
onEvent: (callback) => subscribe('core:event', callback),
onAudio: (callback) => subscribe('core:audio', callback),
onCoreStatus: (callback) => subscribe('core:status', callback),
getCoreStatus: () => ipcRenderer.invoke('core:status'),
restartCore: () => ipcRenderer.invoke('core:restart'),
getAppInfo: () => ipcRenderer.invoke('app:info'),
getPrefs: () => ipcRenderer.invoke('prefs:get'),
setPrefs: (partial) => ipcRenderer.invoke('prefs:set', partial),
exportIdentity: () => ipcRenderer.invoke('identity:export'),
importIdentity: () => ipcRenderer.invoke('identity:import'),
copyText: (text) => ipcRenderer.invoke('clipboard:write', text),
openLogs: () => ipcRenderer.invoke('app:open-logs'),
fetchExternalMedia: (url) => ipcRenderer.invoke('media:external', url),
getVideoStatus: () => ipcRenderer.invoke('app:video-status'),
relaunch: () => ipcRenderer.invoke('app:relaunch'),
getUpdateState: () => ipcRenderer.invoke('update:get-state'),
checkForUpdates: () => ipcRenderer.invoke('update:check'),
downloadUpdate: () => ipcRenderer.invoke('update:download'),
installUpdate: (confirmInterrupt) => ipcRenderer.invoke('update:install', { confirmInterrupt: confirmInterrupt === true }),
openUpdateRelease: () => ipcRenderer.invoke('update:open-release'),
setUpdateChannel: (channel) => ipcRenderer.invoke('update:set-channel', channel),
onUpdateState: (callback) => subscribe('update:state', callback),
log: (level, message) => ipcRenderer.send('app:log', level, String(message)),
});
-404
View File
@@ -1,404 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; media-src 'self' blob: mediastream:; font-src 'self'; connect-src 'none'; worker-src 'self'; base-uri 'none'; form-action 'none'; frame-src 'none'; object-src 'none'">
<meta name="color-scheme" content="light dark">
<title>TeamsPeach</title>
<link rel="stylesheet" href="styles/app.css">
<script type="module" src="js/app.js"></script>
</head>
<body>
<svg class="sprite" aria-hidden="true" focusable="false">
<symbol id="i-mic" viewBox="0 0 24 24"><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/></symbol>
<symbol id="i-mic-off" viewBox="0 0 24 24"><path d="M15 9.5V6a3 3 0 0 0-5.6-1.5M9 9v2a3 3 0 0 0 4.7 2.5M18.5 11a6.5 6.5 0 0 1-1 3.4M5.5 11a6.5 6.5 0 0 0 10 5.5M12 17.5V21M4 4l16 16"/></symbol>
<symbol id="i-headphones" viewBox="0 0 24 24"><path d="M4 15v-3a8 8 0 0 1 16 0v3"/><rect x="3" y="14" width="4.5" height="6.5" rx="1.6"/><rect x="16.5" y="14" width="4.5" height="6.5" rx="1.6"/></symbol>
<symbol id="i-headphones-off" viewBox="0 0 24 24"><path d="M4 15v-3a8 8 0 0 1 12.2-6.8M19.3 9A8 8 0 0 1 20 12v3"/><rect x="3" y="14" width="4.5" height="6.5" rx="1.6"/><rect x="16.5" y="14" width="4.5" height="6.5" rx="1.6"/><path d="M3.5 3.5l17 17"/></symbol>
<symbol id="i-sliders" viewBox="0 0 24 24"><path d="M4 7h9.5M18.5 7H20M4 17h3.5M12.5 17H20"/><circle cx="16" cy="7" r="2.3"/><circle cx="10" cy="17" r="2.3"/></symbol>
<symbol id="i-monitor" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8.5 20h7M12 16v4"/></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><path d="M9 7.2v9.6l7.6-4.8z"/></symbol>
<symbol id="i-x" viewBox="0 0 24 24"><path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/></symbol>
<symbol id="i-send" viewBox="0 0 24 24"><path d="M4.5 11.6L19.5 4.5l-5.2 15-2.9-6.2zM11.4 13.3l8.1-8.8"/></symbol>
<symbol id="i-copy" viewBox="0 0 24 24"><rect x="8.5" y="8.5" width="11.5" height="11.5" rx="2"/><path d="M15.5 8.5V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v7.5a2 2 0 0 0 2 2h2.5"/></symbol>
<symbol id="i-lock" viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="9.5" rx="2"/><path d="M8.5 11V8a3.5 3.5 0 0 1 7 0v3"/></symbol>
<symbol id="i-channel" viewBox="0 0 24 24"><path d="M5 9.5h14M5 14.5h14M10.5 4.5l-2 15M15.5 4.5l-2 15"/></symbol>
<symbol id="i-logout" viewBox="0 0 24 24"><path d="M14.5 4.5h3a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-3M10 16l4-4-4-4M14 12H4.5"/></symbol>
<symbol id="i-speaker" viewBox="0 0 24 24"><path d="M4.5 9.5v5h3.8l4.7 4V5.5l-4.7 4z"/><path d="M16.3 8.8a4.6 4.6 0 0 1 0 6.4M18.8 6.3a8.2 8.2 0 0 1 0 11.4"/></symbol>
<symbol id="i-speaker-off" viewBox="0 0 24 24"><path d="M4.5 9.5v5h3.8l4.7 4V5.5l-4.7 4z"/><path d="M16.5 9.5l5 5M21.5 9.5l-5 5"/></symbol>
<symbol id="i-fullscreen" viewBox="0 0 24 24"><path d="M4.5 9V4.5H9M15 4.5h4.5V9M19.5 15v4.5H15M9 19.5H4.5V15"/></symbol>
<symbol id="i-back" viewBox="0 0 24 24"><path d="M14.5 5.5L8 12l6.5 6.5"/></symbol>
<symbol id="i-moon" viewBox="0 0 24 24"><path d="M19.5 14.6A7.8 7.8 0 1 1 9.4 4.5a6.2 6.2 0 0 0 10.1 10.1z"/></symbol>
<symbol id="i-message" viewBox="0 0 24 24"><path d="M4.5 5.5h15v10.5h-9.5l-5.5 4z"/></symbol>
<symbol id="i-peach" viewBox="0 0 24 24"><path class="peach-body" d="M12 7.2c-4.6-1.6-8 1.6-8 6 0 4.6 3.6 8.3 8 8.3s8-3.7 8-8.3c0-4.4-3.4-7.6-8-6z"/><path class="peach-crease" d="M12 7.6c-1.8 2.6-2 8.6 0 13.6"/><path class="peach-leaf" d="M12.2 6.8c.2-2.6 2-4.2 5-4.3-.3 2.7-2.1 4.2-5 4.3z"/></symbol>
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 3.5l7 2.6v5.4c0 4.3-2.9 7.6-7 9-4.1-1.4-7-4.7-7-9V6.1z"/></symbol>
<symbol id="i-record" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="2.5"/></symbol>
<symbol id="i-bookmark" viewBox="0 0 24 24"><path d="M7 4.5h10v15l-5-3.6-5 3.6z"/></symbol>
<symbol id="i-user" viewBox="0 0 24 24"><circle cx="12" cy="8.5" r="3.5"/><path d="M5 19.5c1-3.6 3.8-5.5 7-5.5s6 1.9 7 5.5"/></symbol>
<symbol id="i-palette" viewBox="0 0 24 24"><path d="M12 4a8 8 0 0 0 0 16c1.2 0 1.8-.8 1.8-1.7 0-1.3-1-1.6-1-2.6 0-1 .8-1.7 1.8-1.7H17a3 3 0 0 0 3-3C20 7.3 16.4 4 12 4z"/><circle cx="8" cy="11" r="1"/><circle cx="11" cy="7.8" r="1"/><circle cx="15" cy="8.3" r="1"/></symbol>
<symbol id="i-keyboard" viewBox="0 0 24 24"><rect x="3" y="6.5" width="18" height="11" rx="2"/><path d="M7 10h.01M10.5 10h.01M14 10h.01M17 10h.01M8 14h8"/></symbol>
<symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 11v5.5M12 7.8v.01"/></symbol>
<symbol id="i-check" viewBox="0 0 24 24"><path d="M5.5 12.5l4.2 4.2 8.8-9.2"/></symbol>
</svg>
<div id="boot" class="boot" role="status">
<svg class="icon brand-mark" aria-hidden="true"><use href="#i-peach"/></svg>
<p id="boot-text" data-i18n="ui.starting.core">Starting core…</p>
</div>
<main id="view-fatal" class="fatal" hidden>
<div class="fatal-inner">
<svg class="icon brand-mark" aria-hidden="true"><use href="#i-peach"/></svg>
<h1 id="fatal-title" data-i18n="ui.core.unavailable">Core unavailable</h1>
<p id="fatal-text"></p>
<ul id="fatal-list" class="fatal-list"></ul>
<div class="fatal-actions">
<button id="fatal-retry" class="btn btn-primary" type="button" data-i18n="ui.restart.core">Restart core</button>
<button id="fatal-import" class="btn" type="button" hidden data-i18n="ui.import.backup">Import backup…</button>
<button id="fatal-logs" class="btn" type="button" data-i18n="ui.open.logs">Open logs</button>
</div>
</div>
</main>
<main id="view-onboarding" class="onboarding" hidden>
<form id="onboarding-form" class="onboarding-form" novalidate>
<svg class="icon brand-mark brand-mark-large" aria-hidden="true"><use href="#i-peach"/></svg>
<h1 data-i18n="ui.what.should.we.call.you">What should we call you?</h1>
<p class="lede" data-i18n="ui.everyone.on.the.server.sees.your.nickname">Everyone on the server sees your nickname. You can change it later without changing your permanent identifier (UID).</p>
<label class="field">
<span class="field-label" data-i18n="ui.nickname">Nickname</span>
<input id="onboarding-nick" name="nickname" type="text" autocomplete="off" spellcheck="false" maxlength="30" required aria-describedby="onboarding-hint onboarding-error">
</label>
<p id="onboarding-hint" class="hint" data-i18n="ui.3.30.characters">3–30 characters.</p>
<p id="onboarding-existing" class="hint" hidden></p>
<p id="onboarding-error" class="form-error" role="alert"></p>
<button id="onboarding-submit" class="btn btn-primary btn-wide" type="submit" data-i18n="ui.continue">Continue</button>
<p class="hint" data-i18n="ui.teamspeach.will.create.a.cryptographic.identity.on">TeamsPeach will create a cryptographic identity on this computer. No registration required.</p>
<button id="onboarding-import" class="btn btn-ghost" type="button" data-i18n="ui.restore.from.backup">Restore from backup…</button>
</form>
</main>
<div id="view-app" class="shell" hidden>
<aside class="sidebar" aria-label="Server" data-i18n-aria-label="ui.server">
<header class="server-head">
<div class="server-title">
<span id="server-name" class="server-name" data-i18n="ui.not.connected">Not connected</span>
<span id="conn-badge" class="conn-badge" data-state="disconnected" data-i18n="ui.not.connected2">not connected</span>
</div>
<button id="btn-servers" class="icon-btn" type="button" aria-expanded="false" aria-controls="servers-panel" aria-label="Saved servers" data-i18n-aria-label="ui.saved.servers" title="Saved servers" data-i18n-title="ui.saved.servers">
<svg class="icon" aria-hidden="true"><use href="#i-bookmark"/></svg>
</button>
<button id="btn-disconnect" class="icon-btn" type="button" aria-label="Disconnect from server" data-i18n-aria-label="ui.disconnect.from.server" title="Disconnect" data-i18n-title="ui.disconnect" hidden>
<svg class="icon" aria-hidden="true"><use href="#i-logout"/></svg>
</button>
</header>
<div id="room-side" class="room-side">
<section id="servers-panel" class="servers-panel" aria-labelledby="servers-title" hidden>
<div class="servers-head">
<h2 id="servers-title" class="servers-title" data-i18n="ui.saved.servers">Saved servers</h2>
<button id="servers-save-current" class="btn btn-ghost btn-small" type="button" hidden data-i18n="ui.save.current.server">Save current server</button>
</div>
<ul id="servers-list" class="servers-list"></ul>
<p id="servers-empty" class="servers-empty" data-i18n="ui.no.saved.servers.enter.an.address.in">No saved servers. Enter an address in the connection form and select Save.</p>
</section>
<p id="tree-empty" class="tree-empty" data-i18n="ui.channels.will.appear.after.you.connect.to">Channels will appear after you connect to a server.</p>
<img id="host-banner" class="host-banner" alt="" hidden>
<ul id="tree" class="tree" aria-label="Channels and members" data-i18n-aria-label="ui.channels.and.members"></ul>
</div>
<nav id="settings-nav" class="settings-nav" aria-label="Settings categories" data-i18n-aria-label="ui.settings.categories" hidden>
<button id="settings-back" class="settings-back" type="button">
<svg class="icon" aria-hidden="true"><use href="#i-back"/></svg><span data-i18n="ui.back.to.server">Back to server</span>
</button>
<div class="settings-nav-title"><svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg><span data-i18n="ui.settings">Settings</span></div>
<div class="nav-group-label" data-i18n="ui.user">User</div>
<button class="nav-item" type="button" data-panel="identity"><svg class="icon" aria-hidden="true"><use href="#i-user"/></svg><span data-i18n="ui.identity">Identity</span></button>
<button class="nav-item" type="button" data-panel="servers"><svg class="icon" aria-hidden="true"><use href="#i-bookmark"/></svg><span data-i18n="ui.servers">Servers</span></button>
<div class="nav-group-label" data-i18n="ui.application">Application</div>
<button class="nav-item" type="button" data-panel="appearance"><svg class="icon" aria-hidden="true"><use href="#i-palette"/></svg><span data-i18n="ui.appearance">Appearance</span></button>
<button class="nav-item" type="button" data-panel="audio"><svg class="icon" aria-hidden="true"><use href="#i-speaker"/></svg><span data-i18n="ui.audio">Audio</span></button>
<button class="nav-item" type="button" data-panel="video"><svg class="icon" aria-hidden="true"><use href="#i-monitor"/></svg><span data-i18n="ui.video">Video</span></button>
<button class="nav-item" type="button" data-panel="keys"><svg class="icon" aria-hidden="true"><use href="#i-keyboard"/></svg><span data-i18n="ui.keyboard">Keyboard</span></button>
<div class="nav-group-label" data-i18n="ui.information">Information</div>
<button class="nav-item" type="button" data-panel="about"><svg class="icon" aria-hidden="true"><use href="#i-info"/></svg><span data-i18n="ui.information">Information</span></button>
</nav>
<footer class="self">
<div class="self-id">
<span id="self-dot" class="status-dot" aria-hidden="true"></span>
<div class="self-text">
<div id="self-nick" class="self-nick"></div>
<div id="self-sub" class="self-sub"></div>
</div>
</div>
<div class="self-actions">
<button id="btn-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Microphone" data-i18n-aria-label="ui.microphone" title="Mute microphone" data-i18n-title="ui.mute.microphone">
<svg class="icon" aria-hidden="true"><use href="#i-mic"/></svg>
</button>
<button id="btn-deafen" class="icon-btn" type="button" aria-pressed="false" aria-label="Audio" data-i18n-aria-label="ui.audio" title="Mute audio" data-i18n-title="ui.mute.audio">
<svg class="icon" aria-hidden="true"><use href="#i-headphones"/></svg>
</button>
<button id="btn-settings" class="icon-btn" type="button" aria-label="Settings" data-i18n-aria-label="ui.settings" title="Settings" data-i18n-title="ui.settings">
<svg class="icon" aria-hidden="true"><use href="#i-sliders"/></svg>
</button>
</div>
</footer>
</aside>
<main class="workspace">
<section id="connect-view" class="connect-view" aria-labelledby="connect-title">
<form id="connect-form" class="connect-form" novalidate>
<h1 id="connect-title" data-i18n="ui.connect.to.a.server">Connect to a server</h1>
<p id="connect-identity" class="lede"></p>
<label class="field">
<span class="field-label" data-i18n="ui.server.address">Server address</span>
<input id="connect-address" name="address" type="text" autocomplete="off" spellcheck="false" placeholder="address or address:9987" data-i18n-placeholder="ui.address.or.address.9987" required>
</label>
<label class="field">
<span class="field-label"><span data-i18n="ui.server.password">Server password</span> <span class="optional" data-i18n="ui.optional">optional</span></span>
<input id="connect-password" name="password" type="password" autocomplete="off">
</label>
<p id="connect-error" class="form-error" role="alert"></p>
<div class="form-actions">
<button id="connect-submit" class="btn btn-primary" type="submit" data-i18n="ui.connect">Connect</button>
<button id="connect-save" class="btn" type="button" data-i18n="ui.save">Save</button>
<span id="connect-status" class="form-status" role="status"></span>
</div>
</form>
</section>
<section id="session-view" class="session-view" hidden>
<header class="session-head">
<div class="session-title">
<h1 id="channel-title"></h1>
<p id="channel-topic" class="channel-topic"></p>
</div>
<div class="transmit">
<span id="transmit-hint" class="transmit-hint"></span>
<button id="btn-ptt" class="btn btn-ptt" type="button" aria-pressed="false" data-i18n="ui.hold.to.talk">Hold to talk</button>
</div>
</header>
<p id="session-notice" class="notice" role="status" hidden></p>
<section id="stream-view" class="stream-view" aria-label="Stream" data-i18n-aria-label="ui.stream" hidden>
<div class="stream-stage">
<video id="stream-video" autoplay playsinline></video>
<div id="stream-overlay" class="stream-overlay" role="status"></div>
</div>
<div class="stream-bar">
<div class="stream-meta">
<strong id="stream-title" class="stream-title"></strong>
<span id="stream-stats" class="stream-stats"></span>
</div>
<div class="stream-controls">
<button id="stream-mute" class="icon-btn" type="button" aria-pressed="false" aria-label="Stream audio" data-i18n-aria-label="ui.stream.audio" title="Mute stream" data-i18n-title="ui.mute.stream">
<svg class="icon" aria-hidden="true"><use href="#i-speaker"/></svg>
</button>
<input id="stream-volume" class="range" type="range" min="0" max="100" step="1" aria-label="Stream volume" data-i18n-aria-label="ui.stream.volume">
<output id="stream-volume-value" class="range-value" for="stream-volume"></output>
<button id="stream-fullscreen" class="icon-btn" type="button" aria-label="Full screen" data-i18n-aria-label="ui.full.screen" title="Full screen" data-i18n-title="ui.full.screen">
<svg class="icon" aria-hidden="true"><use href="#i-fullscreen"/></svg>
</button>
<button id="stream-stop" class="btn" type="button" data-i18n="ui.stop.watching">Stop watching</button>
</div>
</div>
</section>
<section class="chat" aria-label="Chat" data-i18n-aria-label="ui.chat">
<div id="chat-tabs" class="chat-tabs" role="tablist" aria-label="Chats" data-i18n-aria-label="ui.chats"></div>
<ol id="chat-log" class="chat-log" role="log" aria-live="polite" aria-relevant="additions" tabindex="0"></ol>
<form id="chat-form" class="composer" novalidate>
<textarea id="chat-input" rows="1" aria-label="Message" data-i18n-aria-label="ui.message" placeholder="Message" data-i18n-placeholder="ui.message"></textarea>
<button id="chat-send" class="icon-btn icon-btn-accent" type="submit" aria-label="Send" data-i18n-aria-label="ui.send" title="Send (Enter)" data-i18n-title="ui.send.enter">
<svg class="icon" aria-hidden="true"><use href="#i-send"/></svg>
</button>
</form>
</section>
</section>
<section id="settings-view" class="settings-view" hidden aria-label="Settings" data-i18n-aria-label="ui.settings">
<div class="settings-scroll">
<div class="settings-panel" data-panel="identity" hidden>
<h1 id="settings-title" class="panel-title" data-i18n="ui.identity">Identity</h1>
<section class="card" aria-labelledby="card-identity">
<h2 id="card-identity" class="card-title" data-i18n="ui.identity">Identity</h2>
<div class="card-row">
<span class="row-name" data-i18n="ui.unique.identifier">Unique identifier</span>
<code id="uid-value" class="uid-value"></code>
<button id="uid-copy" class="btn btn-ghost btn-small" type="button"><svg class="icon" aria-hidden="true"><use href="#i-copy"/></svg><span data-i18n="ui.copy">Copy</span></button>
</div>
<p class="hint" data-i18n="ui.your.uid.is.your.public.key.fingerprint">Your UID is your public key fingerprint. TeamSpeak servers use it to recognize you and assign permissions; changing your nickname does not change it.</p>
<p id="security-level" class="hint"></p>
<div class="card-divider"></div>
<div class="form-actions">
<button id="identity-export" class="btn" type="button" data-i18n="ui.export.to.file">Export to file…</button>
<button id="identity-import" class="btn" type="button" data-i18n="ui.import.from.file">Import from file…</button>
</div>
<p class="hint" data-i18n="ui.the.file.contains.your.private.key.protect">The file contains your private key. Protect it like a password: anyone with it can impersonate you.</p>
<p id="identity-status" class="form-status" role="status"></p>
</section>
<section class="card" aria-labelledby="card-details">
<h2 id="card-details" class="card-title" data-i18n="ui.details">Details</h2>
<form id="rename-form" class="inline-form" novalidate>
<label class="inline-label" for="rename-input" data-i18n="ui.nickname2">Nickname</label>
<input id="rename-input" type="text" autocomplete="off" spellcheck="false" maxlength="30">
<button id="rename-submit" class="btn btn-primary btn-small" type="submit" data-i18n="ui.save">Save</button>
</form>
<p class="hint" data-i18n="ui.other.users.on.the.teamspeak.server.see">Other users on the TeamSpeak server see your nickname. 3–30 characters.</p>
<p id="rename-status" class="form-status" role="status"></p>
</section>
</div>
<div class="settings-panel" data-panel="servers" hidden>
<h1 class="panel-title" data-i18n="ui.servers">Servers</h1>
<section class="card" aria-labelledby="card-saved">
<h2 id="card-saved" class="card-title" data-i18n="ui.saved.servers">Saved servers</h2>
<ul id="servers-manage" class="servers-list servers-manage"></ul>
<p id="servers-manage-empty" class="hint" data-i18n="ui.no.saved.servers">No saved servers.</p>
</section>
<section class="card" aria-labelledby="card-add-server">
<h2 id="card-add-server" class="card-title" data-i18n="ui.add.server">Add server</h2>
<form id="server-add-form" class="stack-form" novalidate>
<label class="field"><span class="field-label" data-i18n="ui.name">Name</span><input id="server-add-name" type="text" maxlength="64" autocomplete="off"></label>
<label class="field"><span class="field-label" data-i18n="ui.address">Address</span><input id="server-add-address" type="text" maxlength="255" autocomplete="off" spellcheck="false" placeholder="address or address:9987" data-i18n-placeholder="ui.address.or.address.9987"></label>
<div class="form-actions"><button class="btn btn-primary btn-small" type="submit" data-i18n="ui.add">Add</button><span id="server-add-status" class="form-status" role="status"></span></div>
</form>
<p class="hint" data-i18n="ui.only.the.name.and.address.are.saved">Only the name and address are saved. Server passwords are not stored; you will be asked when connecting. The same identity is used for every server.</p>
</section>
</div>
<div class="settings-panel" data-panel="appearance" hidden>
<h1 class="panel-title" data-i18n="ui.appearance">Appearance</h1>
<section class="card" aria-labelledby="card-theme">
<h2 id="card-theme" class="card-title" data-i18n="ui.theme">Theme</h2>
<fieldset class="fieldset">
<legend class="visually-hidden" data-i18n="ui.color.theme">Color theme</legend>
<label class="choice"><input type="radio" name="theme" value="system"> <span data-i18n="ui.system">System</span></label>
<label class="choice"><input type="radio" name="theme" value="dark"> <span data-i18n="ui.dark">Dark</span></label>
<label class="choice"><input type="radio" name="theme" value="light"> <span data-i18n="ui.light">Light</span></label>
</fieldset>
</section>
<section class="card" aria-labelledby="card-language">
<h2 id="card-language" class="card-title" data-i18n="language.label">Language</h2>
<label class="field"><span class="field-label" data-i18n="language.label">Language</span>
<select id="language-select"><option value="en" lang="en">English</option><option value="ru" lang="ru" data-i18n="language.russian">Russian</option></select>
</label>
<p class="hint" data-i18n="language.note">Changes apply immediately. Your identity, connection and audio are unchanged.</p>
</section>
</div>
<div class="settings-panel" data-panel="audio" hidden>
<h1 class="panel-title" data-i18n="ui.audio">Audio</h1>
<section class="card" aria-labelledby="card-devices">
<h2 id="card-devices" class="card-title" data-i18n="ui.devices">Devices</h2>
<label class="field"><span class="field-label" data-i18n="ui.microphone">Microphone</span><select id="input-device"></select></label>
<div class="meter-row">
<div class="meter" aria-hidden="true"><div id="mic-meter" class="meter-fill"></div></div>
<button id="mic-test" class="btn btn-ghost btn-small" type="button" aria-pressed="false" data-i18n="ui.test.microphone">Test microphone</button>
</div>
<label class="field"><span class="field-label" data-i18n="ui.output.device">Output device</span><select id="output-device"></select></label>
<p id="device-status" class="hint" role="status"></p>
</section>
<section class="card" aria-labelledby="card-volume">
<h2 id="card-volume" class="card-title" data-i18n="ui.volume">Volume</h2>
<label class="field"><span class="field-label"><span data-i18n="ui.voice.volume">Voice volume</span> <output id="voice-volume-value" for="voice-volume"></output></span>
<input id="voice-volume" class="range" type="range" min="0" max="200" step="5"></label>
</section>
<section class="card" aria-labelledby="card-processing">
<h2 id="card-processing" class="card-title" data-i18n="ui.microphone.processing">Microphone processing</h2>
<fieldset class="fieldset">
<legend class="visually-hidden" data-i18n="ui.microphone.processing">Microphone processing</legend>
<label class="choice"><input id="opt-ns" type="checkbox"> <span data-i18n="ui.noise.suppression">Noise suppression</span></label>
<label class="choice"><input id="opt-ec" type="checkbox"> <span data-i18n="ui.echo.cancellation">Echo cancellation</span></label>
<label class="choice"><input id="opt-agc" type="checkbox"> <span data-i18n="ui.automatic.gain.control">Automatic gain control</span></label>
</fieldset>
</section>
</div>
<div class="settings-panel" data-panel="video" hidden>
<h1 class="panel-title" data-i18n="ui.video">Video</h1>
<section class="card" aria-labelledby="card-decode">
<h2 id="card-decode" class="card-title" data-i18n="ui.hardware.acceleration">Hardware acceleration</h2>
<label class="choice"><input id="opt-hwdec" type="checkbox"> <span data-i18n="ui.allow.hardware.video.decoding">Allow hardware video decoding</span></label>
<p class="hint" data-i18n="ui.the.engine.may.use.your.gpu.to">The engine may use your GPU to decode streams. Applies after restarting.</p>
<div id="hwdec-restart" class="form-actions" hidden>
<span class="form-status" data-i18n="ui.this.change.takes.effect.after.restarting.teamspeach">This change takes effect after restarting TeamsPeach.</span>
<button id="hwdec-relaunch" class="btn btn-small" type="button" data-i18n="ui.restart.now">Restart now</button>
</div>
<div class="card-divider"></div>
<div class="card-row">
<span class="row-name" data-i18n="ui.decoding.backend">Decoding backend</span>
<span class="row-value" data-i18n="ui.automatic.chosen.by.chromium">Automatic (chosen by Chromium)</span>
</div>
<details class="card-details">
<summary data-i18n="ui.details.status.codecs.and.backends">Details: status, codecs and backends</summary>
<dl class="diag-list">
<dt data-i18n="ui.policy">Policy</dt><dd id="hwdec-status"></dd>
<dt data-i18n="ui.current.reception">Current reception</dt><dd id="decoder-last"></dd>
</dl>
<h3 class="details-title" data-i18n="ui.receive.codecs.reported.by.the.engine">Receive codecs reported by the engine</h3>
<ul id="codec-list" class="codec-list"></ul>
<h3 class="details-title" data-i18n="ui.unavailable.settings">Unavailable settings</h3>
<p class="hint" data-i18n="ui.unlike.teamspeak.6.there.is.no.cisco">Unlike TeamSpeak 6, there is no Cisco OpenH264 toggle or manual hardware backend selection (NVENC, AMF, QSV, etc.). TeamsPeach receives video through Chromium WebRTC, which has no decoder-selection API. Chromium decodes H.264 through FFmpeg; OpenH264 is only an encoder, and sending your own screen is not implemented in TeamsPeach.</p>
</details>
</section>
</div>
<div class="settings-panel" data-panel="keys" hidden>
<h1 class="panel-title" data-i18n="ui.keyboard">Keyboard</h1>
<section class="card" aria-labelledby="card-transmit">
<h2 id="card-transmit" class="card-title" data-i18n="ui.voice.transmission">Voice transmission</h2>
<fieldset class="fieldset">
<legend class="visually-hidden" data-i18n="ui.transmission.mode">Transmission mode</legend>
<label class="choice"><input type="radio" name="transmit" value="ptt"> <span data-i18n="ui.push.to.talk">Push to talk</span></label>
<label class="choice"><input type="radio" name="transmit" value="open"> <span data-i18n="ui.open.microphone">Open microphone</span></label>
</fieldset>
<div class="card-divider"></div>
<div class="ptt-row">
<span class="row-name" data-i18n="ui.push.to.talk.key">Push-to-talk key</span>
<kbd id="ptt-key" class="kbd"></kbd>
<button id="ptt-assign" class="btn btn-ghost btn-small" type="button" data-i18n="ui.assign">Assign</button>
</div>
<p id="ptt-hint" class="hint" data-i18n="ui.the.key.works.while.teamspeach.is.focused">The key works while TeamsPeach is focused. Letter keys do not trigger while typing. Press Esc to cancel assignment.</p>
</section>
</div>
<div class="settings-panel" data-panel="about" hidden>
<h1 class="panel-title" data-i18n="ui.information">Information</h1>
<section class="card" aria-labelledby="card-about">
<h2 id="card-about" class="card-title" data-i18n="ui.about">About</h2>
<dl id="diag-list" class="diag-list"></dl>
<div class="card-divider"></div>
<div class="form-actions"><button id="open-logs" class="btn btn-small" type="button" data-i18n="ui.open.logs">Open logs</button></div>
</section>
<section class="card" aria-labelledby="card-updates">
<h2 id="card-updates" class="card-title" data-i18n="ui.updates">Updates</h2>
<label class="field"><span class="field-label" data-i18n="ui.update.channel">Update channel</span>
<select id="update-channel">
<option value="preview" data-i18n="ui.preview.releases">Preview releases</option>
<option value="stable" data-i18n="ui.stable.only">Stable only</option>
</select>
</label>
<p class="hint" data-i18n="update.channel.hint">Preview includes prereleases; Stable excludes them.</p>
<p id="update-status" class="update-status" role="status"></p>
<progress id="update-progress" class="update-progress" max="100" hidden></progress>
<div id="update-confirm" class="update-confirm" hidden>
<p class="hint" data-i18n="ui.installing.closes.teamspeach.and.interrupts.your.current">Installing closes TeamsPeach and interrupts your current call and stream.</p>
<div class="form-actions">
<button id="update-confirm-yes" class="btn btn-primary btn-small" type="button" data-i18n="ui.interrupt.and.install">Interrupt and install</button>
<button id="update-confirm-no" class="btn btn-ghost btn-small" type="button" data-i18n="ui.cancel">Cancel</button>
</div>
</div>
<div class="form-actions">
<button id="update-check" class="btn btn-small" type="button" data-i18n="ui.check.for.updates">Check for updates</button>
<button id="update-download" class="btn btn-small" type="button" hidden data-i18n="ui.download">Download</button>
<button id="update-install" class="btn btn-primary btn-small" type="button" hidden data-i18n="ui.install.and.restart">Install and restart</button>
<button id="update-open" class="btn btn-small" type="button" hidden data-i18n="ui.open.release.page">Open release page</button>
</div>
</section>
</div>
</div>
</section>
</main>
</div>
<div id="toasts" class="toasts" aria-live="polite" aria-atomic="false"></div>
</body>
</html>
-555
View File
@@ -1,555 +0,0 @@
import { t, setLanguage, onLanguageChange } from './i18n.js';
// TeamsPeach renderer entry: core lifecycle, onboarding, connection, self controls and view routing.
import { $, h, setIcon, setText } from './dom.js';
import { S, emit, isConnected, ownChannel } from './state.js';
import { tp, call, log } from './core.js';
import { errorText, shortUid, stripBBCode } from './text.js';
import { toast } from './toast.js';
import { initTree, renderTree, updateTalking } from './tree.js';
import * as chat from './chat.js';
import * as watch from './watch.js';
import * as voice from './voice.js';
import * as settings from './settings.js';
import { serverBannerUrl, clearMedia } from './media.js';
import * as servers from './servers.js';
import { initDeviceMenus } from './device-menu.js';
import { initUpdates } from './updates-ui.js';
let hostBannerKey = null;
/** The server's host banner (hostbanner_gfx_url) above the tree; hidden when the server has none. */
function renderHostBanner() {
const img = $('#host-banner');
const server = S.snap?.server;
const key = server?.hostbanner_gfx_url ?? null;
if (key === hostBannerKey) return;
hostBannerKey = key;
img.hidden = true;
img.removeAttribute('src');
if (!key) return;
serverBannerUrl(server).then((url) => {
if (!url || hostBannerKey !== key) return;
img.src = url;
img.alt = server.hostbanner_url ? t('message.server.banner.p0', { p0: server.hostbanner_url }) : t('ui.server.banner');
img.hidden = false;
});
}
const VIEWS = ['#boot', '#view-fatal', '#view-onboarding', '#view-app'];
let welcomeShown = false;
let lastOwnChannel = null;
let lastAsyncError = { code: '', at: 0 };
function showView(id) {
for (const v of VIEWS) $(v).hidden = v !== id;
}
// ---------- prefs ----------
async function savePrefs(partial) {
const r = await tp.setPrefs(partial);
if (r && r.ok) S.prefs = r.prefs;
else toast(() => t('message.setting.not.saved.p0', { p0: r?.message ?? t('ui.error') }), 'error');
if (!Object.hasOwn(partial, 'language')) {
renderSessionHead();
servers.renderServers();
}
return S.prefs;
}
// ---------- core lifecycle ----------
function onCoreStatus(status) {
S.core = status;
switch (status.status) {
case 'starting':
setText($('#boot-text'), () => t('ui.starting.core'));
showView('#boot');
break;
case 'stopped':
setText($('#boot-text'), () => t('ui.restarting.core'));
showView('#boot');
resetConnection(null);
break;
case 'ready':
loadProfile();
break;
case 'missing':
showFatal(t('ui.teamspeach.core.not.found'), t('ui.the.core.executable.is.missing.build.it'), status.candidates ?? []);
break;
default:
resetConnection(null);
showFatal(t('ui.the.core.stopped'), coreStatusText(status), []);
}
}
function coreStatusText(status) {
if (status.reason === 'ready_timeout') return t('core.status.readyTimeout');
if (status.reason === 'protocol') return t('core.status.protocol', { protocol: status.protocol });
if (status.reason === 'spawn') return `${t('ui.the.core.stopped')}: ${status.message}`;
const code = status.code ?? 'unknown';
return [0, 1, 2, 3].includes(code) ? t(`core.exit.${code}`) : t('core.exit.other', { code });
}
function showFatal(title, text, list, { allowImport = false } = {}) {
setText($('#fatal-title'), () => title);
setText($('#fatal-text'), () => text);
$('#fatal-list').replaceChildren(...list.map((item) => h('li', { text: item })));
$('#fatal-import').hidden = !allowImport;
$('#fatal-retry').hidden = S.core.status === 'missing';
showView('#view-fatal');
}
async function loadProfile() {
try {
S.profile = await call('profile_get');
} catch (err) {
if (err.code === 'identity_corrupt' || err.code === 'profile_corrupt') {
showFatal(t('ui.profile.corrupted'), t('message.p0.teamspeach.never.replaces.a.corrupted', { p0: errorText(err) }), [], { allowImport: true });
} else {
showFatal(t('ui.could.not.read.profile'), errorText(err), []);
}
return;
}
if (!S.profile.exists || !S.profile.nickname) showOnboarding();
else showApp();
}
// ---------- onboarding ----------
function showOnboarding() {
const existing = $('#onboarding-existing');
existing.hidden = !S.profile.exists;
setText(existing, () => S.profile.exists ? t('message.an.identity.already.exists.uid.p0', { p0: S.profile.uid }) : '');
showView('#view-onboarding');
$('#onboarding-nick').focus();
}
async function submitOnboarding(e) {
e.preventDefault();
const input = $('#onboarding-nick');
const error = $('#onboarding-error');
const nickname = input.value.trim();
const len = [...nickname].length;
if (len < 3 || len > 30) {
input.setAttribute('aria-invalid', 'true');
setText(error, () => t('ui.nickname.must.contain.3.30.characters'));
input.focus();
return;
}
input.removeAttribute('aria-invalid');
setText(error, () => '');
const submit = $('#onboarding-submit');
submit.disabled = true;
setText(submit, () => t('ui.creating.identity'));
try {
S.profile = S.profile.exists ? await call('rename', { nickname }) : await call('profile_create', { nickname });
showApp();
toast(() => t('message.profile.created.your.uid.p0', { p0: S.profile.uid }));
} catch (err) {
setText(error, () => errorText(err));
} finally {
submit.disabled = false;
setText(submit, () => t('ui.continue'));
}
}
// ---------- main shell ----------
function showApp() {
showView('#view-app');
voice.startAudio();
renderAll();
if (S.view === 'main' && !isConnected()) $('#connect-address').focus();
}
function renderAll() {
renderConnection();
renderTree();
renderSelf();
renderSessionHead();
chat.renderTabs();
chat.renderLog();
settings.renderProfile();
}
function renderConnection() {
const state = S.conn.state;
const badge = $('#conn-badge');
badge.dataset.state = state;
const labels = { connecting: 'ui.connecting', connected: 'ui.connected', disconnecting: 'ui.disconnecting', disconnected: 'ui.not.connected2' };
setText(badge, () => labels[state] ? t(labels[state]) : state);
setText($('#server-name'), () => isConnected() ? S.snap.server.name || S.conn.address : S.conn.address && state !== 'disconnected' ? S.conn.address : t('ui.not.connected'));
$('#btn-disconnect').hidden = state === 'disconnected';
const inSettings = S.view === 'settings';
$('#settings-view').hidden = !inSettings;
$('#settings-nav').hidden = !inSettings;
$('#room-side').hidden = inSettings;
$('#connect-view').hidden = inSettings || isConnected();
$('#session-view').hidden = inSettings || !isConnected();
servers.renderServers();
const busy = state === 'connecting' || state === 'disconnecting';
$('#connect-submit').disabled = busy;
setText($('#connect-status'), () => state === 'connecting' ? t('ui.connecting2') : '');
setText($('#connect-identity'), () => S.profile ? t('message.you.will.join.as.p0.uid', { p0: S.profile.nickname, p1: shortUid(S.profile.uid) }) : '');
if (!$('#connect-address').value && S.prefs.lastAddress) $('#connect-address').value = S.prefs.lastAddress;
}
function renderSelf() {
const p = S.profile;
if (!p) return;
setText($('#self-nick'), () => p.nickname ?? '');
const ch = ownChannel();
setText($('#self-sub'), () => isConnected() && ch ? ch.name : `UID ${shortUid(p.uid)}`);
$('#self-sub').title = `UID ${p.uid}`;
$('#self-dot').dataset.talking = String(Boolean(S.audio.transmitting));
const mute = $('#btn-mute');
mute.setAttribute('aria-pressed', String(S.audio.input_muted));
setIcon(mute.firstElementChild, S.audio.input_muted ? 'mic-off' : 'mic');
mute.title = S.audio.input_muted ? t('ui.unmute.microphone') : t('ui.mute.microphone');
mute.setAttribute('aria-label', S.audio.input_muted ? t('ui.microphone.muted') : t('ui.microphone.unmuted'));
const deafen = $('#btn-deafen');
deafen.setAttribute('aria-pressed', String(S.audio.output_muted));
setIcon(deafen.firstElementChild, S.audio.output_muted ? 'headphones-off' : 'headphones');
deafen.title = S.audio.output_muted ? t('ui.unmute.audio') : t('ui.mute.audio.and.microphone');
deafen.setAttribute('aria-label', S.audio.output_muted ? t('ui.audio.muted') : t('ui.audio.unmuted'));
}
function renderSessionHead() {
if (!S.prefs) return;
const ch = ownChannel();
setText($('#channel-title'), () => ch ? ch.name : '');
setText($('#channel-topic'), () => ch ? stripBBCode(ch.topic) : '');
const ptt = S.prefs.transmitMode === 'ptt';
$('#btn-ptt').hidden = !ptt;
setText($('#transmit-hint'), () => voice.transmitHint());
const notice = $('#session-notice');
const codec = voice.channelCodecProblem();
let text = '';
if (codec) text = t('message.this.channel.uses.a.legacy.codec', { p0: codec });
else if (S.audio.output_muted) text = t('ui.audio.is.muted.you.cannot.hear.others');
else if (S.audio.input_muted) text = t('ui.microphone.is.muted');
notice.hidden = !text;
setText(notice, () => text);
}
// ---------- connection ----------
function submitConnect(e) {
e.preventDefault();
connectTo($('#connect-address').value.trim(), { password: $('#connect-password').value });
}
function isPasswordError(err) {
const ts = err.ts_error;
return Boolean(ts && (ts.id === 1028 || /password/i.test(`${ts.name ?? ''} ${ts.message ?? ''}`)));
}
/**
* Connects to `address`. When another server is active, the user chose "Switch": the current
* session is closed cleanly first, so there is never more than one connection.
*/
async function connectTo(address, { password = '', switching = false } = {}) {
const error = $('#connect-error');
setText(error, () => '');
if (!address) {
setText(error, () => t('ui.enter.a.server.address'));
$('#connect-address').focus();
return;
}
$('#connect-address').value = address;
if (S.conn.state !== 'disconnected') {
if (!switching) return;
await disconnect();
const deadline = Date.now() + 10000;
while (S.conn.state !== 'disconnected' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
if (S.conn.state !== 'disconnected') {
toast(() => t('ui.could.not.disconnect.from.the.current.server'), 'error');
return;
}
}
const args = { address };
if (password) args.server_password = password;
S.conn = { state: 'connecting', address, reason: null };
renderConnection();
renderTree();
try {
await call('connect', args);
await savePrefs({ lastAddress: address });
$('#connect-password').value = '';
} catch (err) {
if (err.code !== 'already_connected') {
setText(error, () => isPasswordError(err) ? t('message.p0.enter.the.server.password.and', { p0: errorText(err) }) : errorText(err));
if (S.conn.state === 'connecting') S.conn = { state: 'disconnected', address, reason: null };
renderConnection();
renderTree();
if (isPasswordError(err)) $('#connect-password').focus();
}
}
}
async function disconnect() {
try {
await call('disconnect', {});
} catch (err) {
if (err.code !== 'not_connected') toast(() => t('message.disconnect.p0', { p0: errorText(err) }), 'error');
}
}
function resetConnection(reason) {
const wasConnected = S.snap !== null;
S.conn = { state: 'disconnected', address: S.conn.address, reason };
S.snap = null;
S.talking.clear();
S.audio.transmitting = false;
welcomeShown = false;
lastOwnChannel = null;
watch.onDisconnected();
clearMedia();
hostBannerKey = null;
$('#host-banner').hidden = true;
voice.setPtt(false);
voice.syncCapture();
if (wasConnected) {
chat.addSystem('channel', () => reason ? t('message.disconnected.p0', { p0: errorText(reason) }) : t('ui.disconnected.from.server'));
}
if (reason) setText($('#connect-error'), () => errorText(reason));
}
function onStateEvent(evt) {
const prev = S.conn.state;
if (evt.state === 'disconnected') {
resetConnection(evt.reason ?? null);
} else {
S.conn = { state: evt.state, address: evt.address ?? S.conn.address, reason: null };
if (evt.state === 'connecting' && prev === 'connected') chat.addSystem('channel', () => t('ui.connection.lost.reconnecting'));
if (evt.state === 'connected') {
setText($('#connect-error'), () => '');
voice.syncCapture();
}
}
log('info', `state ${prev} → ${evt.state}`);
renderAll();
}
function onSnapshot(snap) {
S.snap = snap;
if (S.conn.state !== 'connected' && S.conn.state !== 'disconnecting') S.conn.state = 'connected';
const present = new Set(snap.clients.map((c) => c.id));
for (const id of Array.from(S.talking)) if (!present.has(id)) S.talking.delete(id);
if (!welcomeShown) {
welcomeShown = true;
chat.addSystem('server', () => t('message.connected.to.p0.p1', { p0: snap.server.name, p1: snap.server.version ? ` (${snap.server.version})` : '' }));
const welcome = stripBBCode(snap.server.welcome_message).trim();
if (welcome) chat.addSystem('server', () => welcome);
}
if (snap.own_channel_id !== lastOwnChannel) {
lastOwnChannel = snap.own_channel_id;
const ch = ownChannel();
if (ch) chat.addSystem('channel', () => t('message.you.are.in.channel.p0', { p0: ch.name }));
}
watch.onSnapshot();
renderHostBanner();
renderConnection();
renderTree();
renderSelf();
renderSessionHead();
chat.renderTabs();
}
function onAsyncError(error) {
const code = error?.code;
log('warn', `core error ${code}: ${error?.message ?? ''}`);
if (code === 'audio_muted' || code === 'not_connected') return;
const now = Date.now();
if (lastAsyncError.code === code && now - lastAsyncError.at < 5000) return;
lastAsyncError = { code, at: now };
if (code === 'audio_codec_unsupported') {
renderSessionHead();
return;
}
toast(() => errorText(error), 'error');
}
function onCoreEvent(evt) {
switch (evt.event) {
case 'state':
onStateEvent(evt);
break;
case 'snapshot':
onSnapshot(evt);
break;
case 'audio_state': {
const wasDeaf = S.audio.output_muted;
const wasTransmitting = S.audio.transmitting;
S.audio = { input_muted: Boolean(evt.input_muted), output_muted: Boolean(evt.output_muted), transmitting: Boolean(evt.transmitting) };
// Core-side confirmation that voice is going out (TEAMSPEACH_LOG=debug only).
if (S.audio.transmitting !== wasTransmitting) log('debug', `voice: core transmitting=${S.audio.transmitting}`);
if (S.audio.output_muted && !wasDeaf) voice.onOutputMuted(true);
watch.applyVolume();
renderSelf();
renderSessionHead();
const self = S.snap?.own_client_id;
if (self !== undefined) updateTalking(self);
break;
}
case 'talking':
if (evt.talking) S.talking.add(evt.client_id);
else S.talking.delete(evt.client_id);
updateTalking(evt.client_id);
break;
case 'text':
chat.onText(evt);
break;
case 'stream':
watch.onStreamEvent(evt);
break;
case 'profile':
S.profile = { exists: evt.exists, uid: evt.uid, nickname: evt.nickname, security_level: evt.security_level };
renderSelf();
renderConnection();
settings.renderProfile();
break;
case 'error':
onAsyncError(evt.error);
break;
default:
break;
}
emit(evt.event, evt);
}
// ---------- self controls ----------
async function toggleAudio(key) {
try {
const result = await call('set_audio', { [key]: !S.audio[key] });
S.audio = { ...S.audio, input_muted: result.input_muted, output_muted: result.output_muted, transmitting: result.transmitting ?? S.audio.transmitting };
if (S.audio.output_muted) voice.onOutputMuted(true);
watch.applyVolume();
renderSelf();
renderSessionHead();
} catch (err) {
toast(() => errorText(err), 'error');
}
}
function openSettings(panel) {
S.view = 'settings';
renderConnection();
settings.open(panel);
}
async function closeSettings() {
await settings.close();
S.view = 'main';
renderConnection();
chat.renderLog();
(isConnected() ? $('#chat-input') : $('#connect-address')).focus();
}
// ---------- diagnostics for automated smoke runs (read-only) ----------
Object.defineProperty(window, 'teamspeachDiagnostics', {
value: Object.freeze({
snapshot: () => ({
core: S.core.status,
profile: S.profile ? { uid: S.profile.uid, nickname: S.profile.nickname } : null,
conn: S.conn.state,
server: S.snap?.server?.name ?? null,
ownClientId: S.snap?.own_client_id ?? null,
ownChannel: ownChannel()?.name ?? null,
clients: S.snap ? S.snap.clients.map((c) => ({ id: c.id, nickname: c.nickname, channel: c.channel_id, type: c.client_type, inputMuted: c.input_muted })) : [],
talking: Array.from(S.talking),
audio: { ...S.audio },
voice: { ...voice.voiceStats, sending: voice.isSending(), capturing: voice.isCapturing() },
streams: Array.from(watch.directory.streams.values()).map((s) => ({ id: s.id, clientId: s.clientId, name: s.name })),
watch: { ...watch.watchStats },
videoCodecs: settings.videoCodecs(),
}),
playback: () => voice.playbackStats(),
}),
});
// ---------- boot ----------
async function boot() {
S.prefs = await tp.getPrefs();
setLanguage(S.prefs.language);
$('#stream-volume').value = String(S.prefs.streamVolume);
initTree({
openPrivate: (id) => chat.openPrivate(id),
openSettings,
toggleWatch: (s) => watch.toggleWatch(s),
streamOf: (id) => watch.streamOf(id),
watchingId: () => watch.watchingId(),
});
chat.initChat();
servers.initServers({ savePrefs, connectTo });
initDeviceMenus({ openAudioSettings: () => openSettings('audio') });
initUpdates();
watch.initWatch({ onChange: () => renderTree(), savePrefs });
voice.initVoice({
savePrefs,
onOutputChanged: () => watch.applySink(),
onPtt: () => renderSessionHead(),
onTransmitChanged: () => {},
});
settings.initSettings({
savePrefs,
close: closeSettings,
onProfile: (p) => {
S.profile = p;
renderSelf();
renderConnection();
settings.renderProfile();
renderTree();
},
});
onLanguageChange(() => {
renderSelf();
renderSessionHead();
renderTree();
chat.renderTabs();
const chatLog = $('#chat-log');
const scrollTop = chatLog.scrollTop;
chat.renderLog();
chatLog.scrollTop = scrollTop;
const banner = $('#host-banner');
if (!banner.hidden) banner.alt = S.snap?.server?.hostbanner_url ? t('message.server.banner.p0', { p0: S.snap.server.hostbanner_url }) : t('ui.server.banner');
});
$('#onboarding-form').addEventListener('submit', submitOnboarding);
$('#onboarding-import').addEventListener('click', async () => {
const r = await tp.importIdentity();
if (r.ok) toast(() => t('message.identity.restored.uid.p0', { p0: r.uid }));
else if (!r.canceled) setText($('#onboarding-error'), () => t('message.restore.failed.p0', { p0: errorText(r.error) }));
});
$('#connect-form').addEventListener('submit', submitConnect);
$('#btn-disconnect').addEventListener('click', disconnect);
$('#btn-mute').addEventListener('click', () => toggleAudio('input_muted'));
$('#btn-deafen').addEventListener('click', () => toggleAudio('output_muted'));
$('#btn-settings').addEventListener('click', () => (S.view === 'settings' ? closeSettings() : openSettings()));
$('#fatal-retry').addEventListener('click', () => tp.restartCore());
$('#fatal-import').addEventListener('click', async () => {
const r = await tp.importIdentity();
if (!r.ok && !r.canceled) toast(() => t('message.import.failed.p0', { p0: errorText(r.error) }), 'error');
});
$('#fatal-logs').addEventListener('click', () => tp.openLogs());
tp.onEvent(onCoreEvent);
tp.onCoreStatus(onCoreStatus);
const status = await tp.getCoreStatus();
if (status) onCoreStatus(status);
}
boot().catch((err) => {
log('error', `boot failed: ${err.stack || err.message}`);
showFatal(t('ui.interface.startup.failed'), String(err.message || err), []);
});
-42
View File
@@ -1,42 +0,0 @@
// Microphone → 20 ms frames of 960 signed 16-bit mono samples at 48 kHz (bridge §4.9).
const FRAME = 960;
class CaptureProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.frame = new Int16Array(FRAME);
this.pos = 0;
this.sumSq = 0;
this.peak = 0;
if (sampleRate !== 48000) this.port.postMessage({ type: 'error', message: `sample rate ${sampleRate}` });
}
process(inputs, outputs) {
const input = inputs[0];
const out = outputs[0] && outputs[0][0];
if (out) out.fill(0);
if (!input || input.length === 0) return true;
const ch = input[0];
for (let i = 0; i < ch.length; i += 1) {
let s = ch[i];
if (s > 1) s = 1;
else if (s < -1) s = -1;
this.frame[this.pos] = s < 0 ? Math.round(s * 0x8000) : Math.round(s * 0x7fff);
this.pos += 1;
this.sumSq += s * s;
const a = s < 0 ? -s : s;
if (a > this.peak) this.peak = a;
if (this.pos === FRAME) {
const pcm = this.frame.buffer;
this.port.postMessage({ type: 'frame', pcm, rms: Math.sqrt(this.sumSq / FRAME), peak: this.peak }, [pcm]);
this.frame = new Int16Array(FRAME);
this.pos = 0;
this.sumSq = 0;
this.peak = 0;
}
}
return true;
}
}
registerProcessor('tp-capture', CaptureProcessor);
-37
View File
@@ -1,37 +0,0 @@
import { t } from '../i18n.js';
// Turns MediaDeviceInfo entries of one kind into select options. DOM-free for unit tests.
//
// Chromium adds aliases ("default", "communications") next to the physical endpoints and, without media
// permission, returns one anonymous entry per kind (empty deviceId and label). Aliases are not offered as
// separate choices; the system-default option names the device the alias currently points to.
const ALIASES = new Set(['default', 'communications']);
/** Strips Chromium's localized "<Default> - " prefix from the alias label to get the device name. */
function aliasTarget(label) {
const m = /^[^-]+ - (.+)$/.exec(label || '');
return m ? m[1] : '';
}
/**
* @param {{deviceId:string,label:string}[]} list entries of one kind
* @param {string} selected saved deviceId ('' = system default)
* @returns {{options:{value:string,label:string}[], physical:number, redacted:boolean}}
*/
export function buildDeviceOptions(list, selected) {
const defaultEntry = list.find((d) => d.deviceId === 'default');
const defaultName = aliasTarget(defaultEntry?.label);
const options = [{ value: '', label: defaultName ? t('message.system.default.p0', { p0: defaultName }) : t('ui.system.default.device') }];
let physical = 0;
for (const d of list) {
if (!d.deviceId || ALIASES.has(d.deviceId)) continue;
physical += 1;
options.push({ value: d.deviceId, label: d.label || t('message.unnamed.device.p0', { p0: d.deviceId.slice(0, 8) }) });
}
if (selected && !options.some((o) => o.value === selected)) {
options.push({ value: selected, label: t('ui.previously.selected.device.currently.unavailable') });
}
// Entries exist but none carries an id: the engine withheld the list (no media permission).
const redacted = physical === 0 && list.some((d) => !d.deviceId);
return { options, physical, redacted };
}
-201
View File
@@ -1,201 +0,0 @@
// Web Audio side of voice: one 48 kHz AudioContext, a capture worklet producing bridge-format
// frames and a playback worklet with a bounded ring buffer.
export class AudioEngine {
constructor({ onFrame, onError, log }) {
this.onFrame = onFrame;
this.onError = onError ?? (() => {});
this.log = log ?? (() => {});
this.ctx = null;
this.playback = null;
this.voiceGain = null;
this.capture = null;
this.captureGen = 0; // bumped by every start/stop; a pending start only completes if still current
this.startingGen = null;
this.ready = null;
this.stats = { framesOut: 0 };
this.statsWaiters = [];
}
init() {
if (!this.ready) this.ready = this._init();
return this.ready;
}
async _init() {
const ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
this.ctx = ctx;
await ctx.audioWorklet.addModule(new URL('./capture-worklet.js', import.meta.url));
await ctx.audioWorklet.addModule(new URL('./playback-worklet.js', import.meta.url));
this.playback = new AudioWorkletNode(ctx, 'tp-playback', {
numberOfInputs: 0,
numberOfOutputs: 1,
outputChannelCount: [1],
});
this.playback.port.onmessage = (event) => {
if (event.data && event.data.type === 'stats') {
const waiters = this.statsWaiters.splice(0);
for (const resolve of waiters) resolve(event.data);
}
};
this.voiceGain = ctx.createGain();
this.playback.connect(this.voiceGain).connect(ctx.destination);
if (ctx.state !== 'running') await ctx.resume();
this.log('info', `audio: context ${ctx.sampleRate} Hz, baseLatency ${Math.round((ctx.baseLatency || 0) * 1000)} ms`);
}
setVoiceVolume(percent) {
if (this.voiceGain) this.voiceGain.gain.setTargetAtTime(percent / 100, this.ctx.currentTime, 0.02);
}
async setOutputDevice(deviceId) {
await this.init();
if (typeof this.ctx.setSinkId !== 'function') throw new Error('Output device selection is not supported');
await this.ctx.setSinkId(deviceId || '');
}
/** Copies the 1920-byte frame into the worklet (transfer). */
pushPlayback(bytes) {
if (!this.playback) return;
const copy = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
this.playback.port.postMessage(copy, [copy]);
this.stats.framesOut += 1;
}
flushPlayback() {
if (this.playback) this.playback.port.postMessage({ type: 'flush' });
}
playbackStats() {
if (!this.playback) return Promise.resolve(null);
return new Promise((resolve) => {
this.statsWaiters.push(resolve);
this.playback.port.postMessage({ type: 'stats' });
});
}
get capturing() {
return this.capture !== null;
}
/** True while a startCapture() call is still waiting for the engine or the microphone. */
get captureStarting() {
return this.startingGen !== null;
}
/**
* Opens the microphone. Every later startCapture() or stopCapture() supersedes a pending call: when
* getUserMedia resolves for a superseded call its tracks are stopped at once and null is returned, so a
* disconnect or a closed mic test during the permission/device wait never leaves a microphone open.
*/
async startCapture({ deviceId, echoCancellation, noiseSuppression, autoGainControl }) {
const gen = ++this.captureGen;
this.startingGen = gen;
this.releaseCapture();
try {
return await this.openCapture(gen, { deviceId, echoCancellation, noiseSuppression, autoGainControl });
} catch (err) {
if (gen !== this.captureGen) return null; // superseded: the failure no longer matters
throw err;
} finally {
if (this.startingGen === gen) this.startingGen = null;
}
}
async openCapture(gen, { deviceId, echoCancellation, noiseSuppression, autoGainControl }) {
await this.init();
if (gen !== this.captureGen) return null;
const audio = {
channelCount: 1,
echoCancellation,
noiseSuppression,
autoGainControl,
};
if (deviceId) audio.deviceId = { exact: deviceId };
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
} catch (err) {
// A saved microphone that is gone is an error: never open a different microphone in its place.
if (deviceId && err && err.name === 'OverconstrainedError') {
throw Object.assign(new Error('Selected microphone is not available'), { name: 'OverconstrainedError', code: 'device_unavailable' });
}
throw err;
}
if (gen !== this.captureGen) {
for (const t of stream.getTracks()) t.stop();
return null;
}
let source = null;
let node = null;
let sink = null;
try {
const ctx = this.ctx;
source = ctx.createMediaStreamSource(stream);
node = new AudioWorkletNode(ctx, 'tp-capture', {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
});
sink = ctx.createGain();
sink.gain.value = 0;
node.port.onmessage = (event) => {
const data = event.data;
if (data.type === 'frame') this.onFrame(data.pcm, data.rms, data.peak);
else if (data.type === 'error') this.onError({ code: 'capture', message: data.message });
};
source.connect(node).connect(sink).connect(ctx.destination);
} catch (err) {
// The microphone is already open: release it and whatever was built before rethrowing.
if (node) node.port.onmessage = null;
for (const part of [source, node, sink]) {
try {
part?.disconnect();
} catch {
// never connected
}
}
for (const t of stream.getTracks()) t.stop();
throw err;
}
const track = stream.getAudioTracks()[0];
track.addEventListener('ended', () => {
if (this.capture && this.capture.stream === stream) {
this.stopCapture();
this.onError({ code: 'device_lost', message: 'Microphone disconnected' });
}
});
this.capture = { stream, source, node, sink, label: track ? track.label : '' };
// The OS can mute a capture track (privacy switch, exclusive mode); record it for diagnosis.
track.addEventListener('mute', () => this.log('warn', 'audio: capture track muted by the system'));
track.addEventListener('unmute', () => this.log('info', 'audio: capture track unmuted'));
const settings = track ? track.getSettings() : {};
this.log('info', `audio: capture started "${track ? track.label : '?'}" ${settings.sampleRate ?? '?'} Hz, ${settings.channelCount ?? '?'} ch, muted=${track ? track.muted : '?'}, ec=${settings.echoCancellation} ns=${settings.noiseSuppression} agc=${settings.autoGainControl}`);
return this.capture.label;
}
/** Stops the microphone and cancels a pending startCapture(). */
stopCapture() {
this.captureGen += 1;
this.startingGen = null;
this.releaseCapture();
}
releaseCapture() {
const c = this.capture;
if (!c) return;
this.capture = null;
c.node.port.onmessage = null;
try {
c.source.disconnect();
c.node.disconnect();
c.sink.disconnect();
} catch {
// already disconnected
}
for (const t of c.stream.getTracks()) t.stop();
}
}
-78
View File
@@ -1,78 +0,0 @@
// Mixed voice from the core → speakers. Bounded ring: 200 ms capacity (oldest dropped),
// 40 ms prebuffer after every underrun, silence while empty (bridge §5 `audio`).
const CAPACITY = 9600;
const PREBUFFER = 1920;
class PlaybackProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.ring = new Float32Array(CAPACITY);
this.read = 0;
this.write = 0;
this.size = 0;
this.playing = false;
this.framesIn = 0;
this.dropped = 0;
this.underruns = 0;
this.port.onmessage = (event) => {
const data = event.data;
if (data instanceof ArrayBuffer) {
this.push(new Int16Array(data));
} else if (data && data.type === 'flush') {
this.read = 0;
this.write = 0;
this.size = 0;
this.playing = false;
} else if (data && data.type === 'stats') {
this.port.postMessage({
type: 'stats',
framesIn: this.framesIn,
dropped: this.dropped,
underruns: this.underruns,
bufferedMs: Math.round((this.size / 48000) * 1000),
});
}
};
}
push(pcm) {
this.framesIn += 1;
for (let i = 0; i < pcm.length; i += 1) {
if (this.size === CAPACITY) {
this.read = (this.read + 1) % CAPACITY;
this.size -= 1;
this.dropped += 1;
}
this.ring[this.write] = pcm[i] / 32768;
this.write = (this.write + 1) % CAPACITY;
this.size += 1;
}
}
process(_inputs, outputs) {
const out = outputs[0][0];
if (!this.playing) {
if (this.size < PREBUFFER) {
out.fill(0);
return true;
}
this.playing = true;
}
for (let i = 0; i < out.length; i += 1) {
if (this.size > 0) {
out[i] = this.ring[this.read];
this.read = (this.read + 1) % CAPACITY;
this.size -= 1;
} else {
out[i] = 0;
if (this.playing) {
this.playing = false;
this.underruns += 1;
}
}
}
return true;
}
}
registerProcessor('tp-playback', PlaybackProcessor);
-260
View File
@@ -1,260 +0,0 @@
import { t } from './i18n.js';
// Channel, server and private text chat. Message text is rendered as plain text only.
import { $, h, icon, reconcile, setText, formatTime } from './dom.js';
import { S, isConnected, ownChannel, clientById } from './state.js';
import { call } from './core.js';
import { errorText, stripBBCode } from './text.js';
import { toast } from './toast.js';
const MAX_MESSAGES = 500;
const chats = new Map();
let active = 'channel';
function ensureChat(key, init) {
let chat = chats.get(key);
if (!chat) {
chat = { key, messages: [], unread: 0, ...init };
chats.set(key, chat);
}
return chat;
}
ensureChat('channel', { kind: 'channel' });
ensureChat('server', { kind: 'server' });
export function initChat() {
const form = $('#chat-form');
const input = $('#chat-input');
form.addEventListener('submit', (e) => {
e.preventDefault();
send();
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
e.preventDefault();
send();
}
});
input.addEventListener('input', autosize);
$('#chat-tabs').addEventListener('keydown', onTabKey);
}
function autosize() {
const input = $('#chat-input');
input.style.height = 'auto';
input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
}
function tabTitle(chat) {
if (chat.kind === 'channel') return ownChannel()?.name ?? t('ui.channel');
if (chat.kind === 'server') return t('ui.server');
const cl = clientById(chat.clientId);
return cl ? cl.nickname : t('message.p0.left', { p0: chat.nickname });
}
function targetOf(chat) {
if (chat.kind === 'client') return { target: 'client', client_id: chat.clientId };
return { target: chat.kind };
}
async function send() {
const input = $('#chat-input');
const text = input.value.replace(/\s+$/u, '');
if (!text.trim() || !isConnected()) return;
const chat = chats.get(active);
if (!chat) return;
if (chat.kind === 'client' && !clientById(chat.clientId)) {
toast(() => t('ui.this.person.left.the.server'), 'error');
return;
}
if (new TextEncoder().encode(text).length > 8192) {
toast(() => t('ui.message.exceeds.8.kib'), 'error');
return;
}
input.disabled = true;
try {
await call('send_text', { ...targetOf(chat), message: text });
input.value = '';
autosize();
} catch (err) {
toast(() => t('message.message.not.sent.p0', { p0: errorText(err) }), 'error');
} finally {
input.disabled = false;
input.focus();
}
}
/** Incoming `text` event (bridge §5). Our own messages arrive here too, exactly once. */
export function onText(evt) {
const own = S.snap?.own_client_id;
let key;
if (evt.target === 'channel') key = 'channel';
else if (evt.target === 'server') key = 'server';
else {
const other = evt.from_client_id === own ? evt.to_client_id : evt.from_client_id;
if (!Number.isInteger(other)) return;
key = openPrivate(other, { focus: false, nickname: evt.from_client_id === own ? undefined : evt.from_nickname });
}
addMessage(key, {
author: evt.from_nickname ?? '?',
own: evt.from_client_id === own,
authorId: evt.from_client_id,
text: stripBBCode(evt.message),
});
}
export function addSystem(key, text) {
addMessage(key, { system: true, text });
}
function addMessage(key, msg) {
const chat = chats.get(key);
if (!chat) return;
msg.time = new Date();
msg.id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
chat.messages.push(msg);
if (chat.messages.length > MAX_MESSAGES) chat.messages.splice(0, chat.messages.length - MAX_MESSAGES);
if (key === active && S.view === 'main') {
appendRow(chat, msg);
} else if (!msg.system && !msg.own) {
chat.unread += 1;
}
renderTabs();
}
/** Opens (or creates) a private conversation; returns its key. */
export function openPrivate(clientId, { focus = true, nickname } = {}) {
const key = `client:${clientId}`;
const cl = clientById(clientId);
const chat = ensureChat(key, { kind: 'client', clientId, nickname: nickname ?? cl?.nickname ?? '?' });
if (cl) chat.nickname = cl.nickname;
if (focus) {
select(key);
$('#chat-input').focus();
} else {
renderTabs();
}
return key;
}
function select(key) {
if (!chats.has(key)) return;
active = key;
chats.get(key).unread = 0;
renderTabs();
renderLog();
}
function closePrivate(key) {
chats.delete(key);
if (active === key) active = 'channel';
renderTabs();
renderLog();
}
export function renderTabs() {
const host = $('#chat-tabs');
const list = Array.from(chats.values());
reconcile(host, list, (c) => c.key, createTab, updateTab);
updateComposer();
}
function createTab(chat) {
const tab = h('button', { class: 'chat-tab', type: 'button', role: 'tab' }, h('span', { class: 'tab-label' }), h('span', { class: 'unread', hidden: true }));
tab.addEventListener('click', () => select(chat.key));
const wrap = h('div', { class: 'tab-wrap', role: 'presentation' }, tab);
if (chat.kind === 'client') {
const close = h('button', { class: 'tab-close icon-btn', type: 'button', 'aria-label': t('ui.close.private.chat'), 'data-i18n-aria-label': 'ui.close.private.chat' }, icon('x'));
close.addEventListener('click', () => closePrivate(chat.key));
wrap.appendChild(close);
}
return wrap;
}
function updateTab(wrap, chat) {
const tab = wrap.firstElementChild;
const [label, unread] = tab.children;
const title = tabTitle(chat);
setText(label, () => chat.kind === 'client' ? `@ ${title}` : title);
const selected = chat.key === active;
tab.setAttribute('aria-selected', String(selected));
tab.tabIndex = selected ? 0 : -1;
tab.title = chat.kind === 'channel' ? t('ui.current.channel.chat') : chat.kind === 'server' ? t('ui.server.wide.chat') : t('message.private.messages.p0', { p0: title });
unread.hidden = chat.unread === 0;
setText(unread, () => chat.unread > 99 ? '99+' : String(chat.unread));
tab.setAttribute('aria-label', `${tab.title}${chat.unread ? t('message.unread.p0', { p0: chat.unread }) : ''}`);
}
function onTabKey(e) {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
const tabs = Array.from(document.querySelectorAll('#chat-tabs [role="tab"]'));
const idx = tabs.indexOf(document.activeElement);
if (idx < 0) return;
const next = tabs[(idx + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
next.focus();
next.click();
e.preventDefault();
}
export function renderLog() {
const log = $('#chat-log');
const chat = chats.get(active);
log.replaceChildren();
if (!chat || chat.messages.length === 0) {
log.appendChild(h('li', { class: 'chat-empty', text: emptyText(chat) }));
updateComposer();
return;
}
let prev = null;
for (const msg of chat.messages) {
log.appendChild(rowFor(msg, prev));
prev = msg;
}
log.scrollTop = log.scrollHeight;
updateComposer();
}
function emptyText(chat) {
if (!chat) return '';
if (chat.kind === 'channel') return t('ui.everyone.in.this.channel.can.see.its');
if (chat.kind === 'server') return t('ui.everyone.connected.to.the.server.can.see');
return t('ui.private.conversation.only.the.recipient.can.see');
}
function rowFor(msg, prev) {
if (msg.system) return h('li', { class: 'msg-system', text: msg.text });
const head = !prev || prev.system || prev.authorId !== msg.authorId || msg.time - prev.time > 5 * 60 * 1000;
const li = h('li', { class: 'msg', dataset: { head: String(head), own: String(Boolean(msg.own)) } });
if (head) {
li.appendChild(h('div', { class: 'msg-head' }, h('span', { class: 'msg-author', text: msg.author }), h('time', { class: 'msg-time', datetime: msg.time.toISOString(), text: formatTime(msg.time) })));
}
li.appendChild(h('div', { class: 'msg-body', text: msg.text }));
return li;
}
function appendRow(chat, msg) {
const log = $('#chat-log');
const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;
const empty = log.querySelector('.chat-empty');
if (empty) empty.remove();
const prev = chat.messages[chat.messages.length - 2] ?? null;
log.appendChild(rowFor(msg, prev));
if (nearBottom || msg.own) log.scrollTop = log.scrollHeight;
}
export function updateComposer() {
const input = $('#chat-input');
const sendBtn = $('#chat-send');
const chat = chats.get(active);
const partnerGone = chat && chat.kind === 'client' && !clientById(chat.clientId);
const enabled = isConnected() && !partnerGone;
input.disabled = !enabled;
sendBtn.disabled = !enabled;
const title = chat ? tabTitle(chat) : '';
input.placeholder = !isConnected() ? t('ui.not.connected') : partnerGone ? t('ui.this.person.left.the.server') : chat?.kind === 'client' ? t('message.message.p0', { p0: title }) : chat?.kind === 'server' ? t('ui.message.the.whole.server') : t('message.message.in.p0', { p0: title });
}
/** Called when the connection ends: private chats keep their history but cannot be answered. */
export function onConnectionChanged() {
renderTabs();
}
-22
View File
@@ -1,22 +0,0 @@
// Thin wrapper over the preload API (window.teamspeach). Requests resolve to `result` or throw BridgeError.
export const tp = window.teamspeach;
export class BridgeError extends Error {
constructor(error) {
super(error?.message || error?.code || 'error');
this.code = error?.code ?? 'internal';
this.ts_error = error?.ts_error;
this.detail = error?.detail;
}
}
export async function call(cmd, args) {
const response = await tp.request(cmd, args);
if (!response || !response.ok) throw new BridgeError(response?.error);
return response.result;
}
export function log(level, message) {
tp.log(level, message);
}
-156
View File
@@ -1,156 +0,0 @@
import { t, onLanguageChange } from './i18n.js';
// Context menus on the footer microphone/headphones buttons: pick the input or output device.
// Uses the same discovery and selection path as Settings → Audio (voice.deviceChoices / choose*Device).
// Opening never toggles mute or deafen; left click on the buttons keeps its own behaviour.
import { $, h, icon } from './dom.js';
import { S } from './state.js';
import * as voice from './voice.js';
let open = null; // { menu, anchor, cleanup }
let hooks = { openAudioSettings: () => {} };
export function initDeviceMenus(h0) {
hooks = { ...hooks, ...h0 };
bind($('#btn-mute'), 'input');
bind($('#btn-deafen'), 'output');
onLanguageChange(() => {
if (open) show(open.anchor, open.kind, open.point);
});
}
function bind(button, kind) {
button.setAttribute('aria-haspopup', 'menu');
button.addEventListener('contextmenu', (e) => {
e.preventDefault();
show(button, kind, { x: e.clientX, y: e.clientY });
});
button.addEventListener('keydown', (e) => {
if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) {
e.preventDefault();
show(button, kind, null);
}
});
}
function close({ restoreFocus = true } = {}) {
if (!open) return;
const { menu, anchor, cleanup } = open;
open = null;
cleanup();
menu.remove();
anchor.setAttribute('aria-expanded', 'false');
if (restoreFocus) anchor.focus();
}
let generation = 0;
/**
* The menu element exists from the first moment (with a loading line), so every close path — Escape,
* outside click, window blur, another menu — applies while device enumeration is still pending. The
* enumeration result only fills the menu that is still open for this request; a stale result is dropped.
*/
function show(anchor, kind, point) {
close({ restoreFocus: false });
const gen = ++generation;
const title = kind === 'input' ? t('ui.microphone') : t('ui.output.device');
const body = h('div', { class: 'menu-body' }, h('p', { class: 'menu-note', text: t('ui.loading.devices') }));
const menu = h('div', { class: 'device-menu', role: 'menu', 'aria-label': title, 'aria-busy': 'true', tabindex: '-1' },
h('div', { class: 'menu-title', text: title }),
body);
document.body.appendChild(menu);
anchor.setAttribute('aria-expanded', 'true');
position(menu, anchor, point);
let focusables = [];
const focusAt = (i) => focusables.length && focusables[(i + focusables.length) % focusables.length].focus();
const onKey = (e) => {
const i = focusables.indexOf(document.activeElement);
if (e.key === 'ArrowDown') { e.preventDefault(); focusAt(i + 1); }
else if (e.key === 'ArrowUp') { e.preventDefault(); focusAt(i - 1); }
else if (e.key === 'Home') { e.preventDefault(); focusAt(0); }
else if (e.key === 'End') { e.preventDefault(); focusAt(focusables.length - 1); }
else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
else if (e.key === 'Tab') { close({ restoreFocus: false }); }
};
const onPointer = (e) => {
if (!menu.contains(e.target) && e.target !== anchor) close({ restoreFocus: false });
};
const onDismiss = () => close({ restoreFocus: false });
menu.addEventListener('keydown', onKey);
document.addEventListener('pointerdown', onPointer, true);
window.addEventListener('resize', onDismiss);
window.addEventListener('blur', onDismiss);
open = {
gen,
menu,
anchor,
kind,
point,
cleanup: () => {
document.removeEventListener('pointerdown', onPointer, true);
window.removeEventListener('resize', onDismiss);
window.removeEventListener('blur', onDismiss);
},
};
menu.focus();
voice.deviceChoices().then((choices) => {
if (!open || open.gen !== gen || !choices) return; // closed or replaced meanwhile
const settingsItem = h('button', { class: 'menu-item menu-item-secondary', type: 'button', role: 'menuitem', tabindex: '-1' }, h('span', { class: 'menu-check', 'aria-hidden': 'true' }), h('span', { class: 'menu-label', text: t('ui.audio.settings') }));
settingsItem.addEventListener('click', () => {
close({ restoreFocus: false });
hooks.openAudioSettings();
});
if (choices.error) {
// Enumeration failed now: show that instead of any earlier list.
body.replaceChildren(h('p', { class: 'menu-note', role: 'alert', text: t('message.could.not.list.devices.p0.p1', { p0: choices.error.name, p1: choices.error.message }) }), h('div', { class: 'menu-sep', role: 'separator' }), settingsItem);
menu.removeAttribute('aria-busy');
position(menu, anchor, point);
focusables = [settingsItem];
if (menu.contains(document.activeElement)) focusAt(0);
return;
}
const data = kind === 'input' ? choices.input : choices.output;
const selected = (kind === 'input' ? S.prefs.inputDeviceId : S.prefs.outputDeviceId) || '';
const items = data.options.map((o) => {
const item = h('button', {
class: 'menu-item',
type: 'button',
role: 'menuitemradio',
'aria-checked': String(o.value === selected),
tabindex: '-1',
}, h('span', { class: 'menu-check', 'aria-hidden': 'true' }, o.value === selected ? icon('check') : null), h('span', { class: 'menu-label', text: o.label }));
item.addEventListener('click', async () => {
close();
if (o.value === selected) return;
if (kind === 'input') await voice.chooseInputDevice(o.value);
else await voice.chooseOutputDevice(o.value);
});
return item;
});
const note = data.redacted || data.physical === 0
? h('p', { class: 'menu-note', text: data.redacted ? t('ui.the.engine.hid.the.device.list.only') : kind === 'input' ? t('ui.no.microphones.found') : t('ui.no.output.devices.found') })
: null;
body.replaceChildren(...items, ...(note ? [note] : []), h('div', { class: 'menu-sep', role: 'separator' }), settingsItem);
menu.removeAttribute('aria-busy');
position(menu, anchor, point);
focusables = [...items, settingsItem];
// Move focus into the list only if it is still inside the menu (the user may have clicked elsewhere).
if (menu.contains(document.activeElement)) focusAt(Math.max(0, items.findIndex((i) => i.getAttribute('aria-checked') === 'true')));
});
}
/** Above the button (the footer sits at the bottom), clamped inside the viewport. */
function position(menu, anchor, point) {
const rect = anchor.getBoundingClientRect();
const mw = menu.offsetWidth;
const mh = menu.offsetHeight;
const margin = 8;
let left = point ? point.x : rect.left;
let top = (point ? point.y : rect.top) - mh - 6;
if (top < margin) top = Math.min(rect.bottom + 6, window.innerHeight - mh - margin);
left = Math.max(margin, Math.min(left, window.innerWidth - mw - margin));
top = Math.max(margin, top);
menu.style.left = `${Math.round(left)}px`;
menu.style.top = `${Math.round(top)}px`;
}
-108
View File
@@ -1,108 +0,0 @@
import { getLanguage, onLanguageChange } from './i18n.js';
// DOM helpers. Server-provided text only ever reaches the page through textContent / attributes.
export function $(selector, root = document) {
const el = root.querySelector(selector);
if (!el) throw new Error(`missing element ${selector}`);
return el;
}
/**
* h('button', {class: 'x', onclick, 'aria-label': 'y', dataset: {cid: 1}}, 'text', child)
* Strings become text nodes; there is no innerHTML path.
*/
export function h(tag, props = {}, ...children) {
const el = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value === undefined || value === null || value === false) continue;
if (key === 'class') el.className = value;
else if (key === 'dataset') Object.assign(el.dataset, value);
else if (key === 'text') setText(el, value);
else if (key.startsWith('on') && typeof value === 'function') el.addEventListener(key.slice(2), value);
else if (key in el && typeof value !== 'string') el[key] = value;
else el.setAttribute(key, value === true ? '' : String(value));
}
append(el, children);
return el;
}
function append(el, children) {
for (const child of children) {
if (child === undefined || child === null || child === false) continue;
if (Array.isArray(child)) append(el, child);
else if (child instanceof Node) el.appendChild(child);
else el.appendChild(document.createTextNode(String(child)));
}
}
const SVG_NS = 'http://www.w3.org/2000/svg';
/** Reference to a symbol of the inline sprite in index.html. */
export function icon(name, extraClass = '') {
const svg = document.createElementNS(SVG_NS, 'svg');
svg.setAttribute('class', `icon ${extraClass}`.trim());
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
const use = document.createElementNS(SVG_NS, 'use');
use.setAttribute('href', `#i-${name}`);
svg.appendChild(use);
return svg;
}
export function setIcon(svg, name) {
svg.firstElementChild.setAttribute('href', `#i-${name}`);
}
/**
* Keyed list reconciliation: reuses nodes by key so focus and hover survive frequent snapshots.
* create(item) → Element; update(el, item) mutates in place.
*/
export function reconcile(container, items, keyOf, create, update) {
const existing = new Map();
for (const child of Array.from(container.children)) {
if (child.dataset.key) existing.set(child.dataset.key, child);
}
let cursor = container.firstElementChild;
for (const item of items) {
const key = keyOf(item);
let el = existing.get(key);
if (el) {
existing.delete(key);
update(el, item);
} else {
el = create(item);
el.dataset.key = key;
update(el, item);
}
if (el !== cursor) container.insertBefore(el, cursor);
else cursor = cursor.nextElementSibling;
}
for (const el of existing.values()) el.remove();
}
const liveText = new WeakMap();
export function setText(el, text) {
if (typeof text === 'function') {
liveText.set(el, text);
el.dataset.liveText = '';
} else {
liveText.delete(el);
delete el.dataset.liveText;
}
// A dynamic binding supersedes an initial HTML label.
el.removeAttribute('data-i18n');
const value = (typeof text === 'function' ? text() : text) ?? '';
if (el.textContent !== value) el.textContent = value;
}
onLanguageChange(() => {
for (const el of document.querySelectorAll('[data-live-text]')) {
const render = liveText.get(el);
if (render) setText(el, render);
}
});
export function formatTime(date) {
return date.toLocaleTimeString(getLanguage(), { hour: '2-digit', minute: '2-digit' });
}
-33
View File
@@ -1,33 +0,0 @@
import '../shared/en.js';
import '../shared/ru.js';
import '../shared/i18n.js';
const shared = globalThis.TeamsPeachI18n;
let language = 'en';
const listeners = new Set();
export const getLanguage = () => language;
export const t = (key, params = {}) => shared.t(key, params, language);
export const hasTranslation = (key) => Object.hasOwn(shared.catalogs.en, key);
export function onLanguageChange(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function translatePage(root = document) {
for (const element of root.querySelectorAll('[data-i18n]')) element.textContent = t(element.dataset.i18n);
for (const attribute of ['title', 'aria-label', 'placeholder']) {
for (const element of root.querySelectorAll(`[data-i18n-${attribute}]`)) {
element.setAttribute(attribute, t(element.getAttribute(`data-i18n-${attribute}`)));
}
}
}
export function setLanguage(value) {
const next = shared.normalizeLanguage(value);
const changed = next !== language;
language = next;
if (typeof document !== 'undefined') {
document.documentElement.lang = language;
translatePage();
}
if (changed) for (const listener of listeners) listener(language);
return language;
}
-91
View File
@@ -1,91 +0,0 @@
// Server images (group/channel icons, channel banners, host banner, avatars) as blob: URLs.
// Bytes come from the core's file transfer (or main's allowlisted http(s) fetch); MIME is sniffed
// upstream and re-checked here. Failures are cached as null so a missing file is not refetched.
import { tp, call, log } from './core.js';
const ALLOWED = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/x-icon', 'image/svg+xml']);
const cache = new Map();
function toUrl(result) {
if (!result || !ALLOWED.has(result.mime) || typeof result.data !== 'string') return null;
const bin = atob(result.data);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i += 1) bytes[i] = bin.charCodeAt(i);
return URL.createObjectURL(new Blob([bytes], { type: result.mime }));
}
function cached(key, load) {
if (!cache.has(key)) {
cache.set(key, load().then(toUrl).catch((err) => {
if (err.code !== 'not_found') log('info', `media ${key.split(':')[0]} unavailable: ${err.code ?? err.message}`);
return null;
}));
}
return cache.get(key);
}
async function viaCore(cmd, args) {
try {
return await call(cmd, args);
} catch (err) {
if (err.code === 'external_media' && err.detail && typeof err.detail.url === 'string') {
const r = await tp.fetchExternalMedia(err.detail.url);
if (r && r.ok) return r.result;
const e = new Error(r?.error?.message ?? 'external fetch failed');
e.code = r?.error?.code ?? 'io';
throw e;
}
throw err;
}
}
/** TeamSpeak's built-in group icon ids (bridge §4.16): the server has no file for them. */
const BUILTIN_ICONS = new Set([100, 200, 300, 500, 600]);
export function isBuiltinIcon(id) {
return BUILTIN_ICONS.has(id);
}
export function iconUrl(iconId) {
if (!iconId || isBuiltinIcon(iconId)) return Promise.resolve(null);
return cached(`icon:${iconId}`, () => call('fetch_icon', { icon_id: iconId }));
}
export function channelBannerUrl(channel) {
if (!channel.banner_url) return Promise.resolve(null);
return cached(`banner:${channel.id}:${channel.banner_url}`, () => viaCore('fetch_banner', { channel_id: channel.id }));
}
export function serverBannerUrl(server) {
if (!server?.hostbanner_gfx_url) return Promise.resolve(null);
return cached(`hostbanner:${server.hostbanner_gfx_url}`, () => viaCore('fetch_server_banner'));
}
export function avatarUrl(client) {
if (client.avatar_hash) return cached(`avatar:${client.uid}:${client.avatar_hash}`, () => call('fetch_avatar', { client_id: client.id }));
const myts = mytsAvatar(client);
if (myts) {
return cached(`myts:${myts}`, async () => {
const r = await tp.fetchExternalMedia(myts);
if (r && r.ok) return r.result;
const e = new Error(r?.error?.message ?? 'external fetch failed');
e.code = r?.error?.code ?? 'io';
throw e;
});
}
return Promise.resolve(null);
}
/** myTeamSpeak avatar URL (bridge: myts_avatars[{variant,url}]); the highest variant observed is used. */
function mytsAvatar(client) {
if (!Array.isArray(client.myts_avatars)) return null;
const list = client.myts_avatars.filter((v) => v && typeof v.url === 'string' && v.url.startsWith('https://'));
list.sort((a, b) => (b.variant ?? 0) - (a.variant ?? 0));
return list[0]?.url ?? null;
}
/** Forget everything (new server or disconnect) and release blob URLs. */
export function clearMedia() {
for (const p of cache.values()) p.then((url) => url && URL.revokeObjectURL(url));
cache.clear();
}
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
-185
View File
@@ -1,185 +0,0 @@
import { t, onLanguageChange } from './i18n.js';
// Saved servers (name + address only; never passwords): quick access in the sidebar and management
// in Settings → Servers. Persisted through main's validated preferences.
import { $, h, icon, setText } from './dom.js';
import { S, isConnected } from './state.js';
import { toast } from './toast.js';
let hooks = { savePrefs: async () => S.prefs, connectTo: async () => {} };
let panelOpen = null; // null = automatic (open while disconnected)
let editingId = null;
let confirmDeleteId = null;
let confirmTimer = null;
export function initServers(h0) {
hooks = { ...hooks, ...h0 };
onLanguageChange(() => {
// Refresh quick actions only; never rebuild a bookmark form with an unsaved draft.
$('#servers-list').replaceChildren(...servers().map(quickRow));
});
$('#btn-servers').addEventListener('click', () => {
panelOpen = !isPanelOpen();
renderServers();
if (panelOpen) $('#servers-list button')?.focus();
});
$('#servers-save-current').addEventListener('click', () => saveAddress(S.snap?.server?.name || S.conn.address, S.conn.address));
$('#connect-save').addEventListener('click', () => {
const address = $('#connect-address').value.trim();
if (!address) {
setText($('#connect-error'), () => t('ui.enter.a.server.address.to.save.it'));
return;
}
saveAddress(address, address);
});
$('#server-add-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = $('#server-add-name').value.trim();
const address = $('#server-add-address').value.trim();
if (!address) {
setText($('#server-add-status'), () => t('ui.enter.an.address'));
return;
}
if (await saveAddress(name || address, address)) {
$('#server-add-name').value = '';
$('#server-add-address').value = '';
setText($('#server-add-status'), () => t('ui.server.added'));
}
});
}
function servers() {
return S.prefs?.savedServers ?? [];
}
function newId() {
const bytes = crypto.getRandomValues(new Uint8Array(8));
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
function sameAddress(a, b) {
const norm = (x) => x.trim().toLowerCase().replace(/:9987$/, '');
return norm(a) === norm(b);
}
async function persist(list) {
const before = servers();
const prefs = await hooks.savePrefs({ savedServers: list });
renderServers();
return prefs.savedServers !== before;
}
async function saveAddress(name, address) {
const trimmed = address.trim();
if (servers().some((s) => sameAddress(s.address, trimmed))) {
toast(() => t('ui.this.address.is.already.saved'));
return false;
}
if (servers().length >= 50) {
toast(() => t('ui.you.can.save.up.to.50.servers'), 'error');
return false;
}
const ok = await persist([...servers(), { id: newId(), name: name.trim().slice(0, 64) || trimmed, address: trimmed }]);
if (ok) toast(() => t('message.server.p0.saved', { p0: name.trim() || trimmed }));
return ok;
}
function isPanelOpen() {
return panelOpen ?? !isConnected();
}
function connectedTo(server) {
return S.conn.state !== 'disconnected' && sameAddress(server.address, S.conn.address || '');
}
export function renderServers() {
const open = isPanelOpen();
$('#servers-panel').hidden = !open;
$('#btn-servers').setAttribute('aria-expanded', String(open));
const list = servers();
const canSaveCurrent = isConnected() && S.conn.address && !list.some((s) => sameAddress(s.address, S.conn.address));
$('#servers-save-current').hidden = !canSaveCurrent;
$('#servers-empty').hidden = list.length > 0;
$('#servers-list').replaceChildren(...list.map(quickRow));
$('#servers-manage-empty').hidden = list.length > 0;
$('#servers-manage').replaceChildren(...list.map(manageRow));
}
function quickRow(server) {
const current = connectedTo(server);
const busy = S.conn.state === 'connecting' || S.conn.state === 'disconnecting';
const label = current ? t('ui.connected2') : S.conn.state === 'disconnected' ? t('ui.connect') : t('ui.switch');
const btn = h('button', {
class: 'server-item',
type: 'button',
disabled: current || busy,
'aria-label': `${server.name}, ${server.address}. ${label}`,
title: current ? t('ui.you.are.connected.to.this.server') : S.conn.state === 'disconnected' ? t('ui.connect') : t('ui.disconnect.from.the.current.server.and.connect'),
}, icon('bookmark'), h('span', { class: 'server-text' }, h('span', { class: 'server-item-name', text: server.name }), h('span', { class: 'server-item-address', text: server.address })), h('span', { class: 'server-item-action', text: label }));
btn.addEventListener('click', () => hooks.connectTo(server.address, { switching: S.conn.state !== 'disconnected' }));
return h('li', {}, btn);
}
function manageRow(server) {
if (editingId === server.id) return editRow(server);
const edit = h('button', { class: 'btn btn-ghost btn-small', type: 'button', 'data-action': 'edit', 'data-i18n': 'ui.edit' }, t('ui.edit'));
const confirming = confirmDeleteId === server.id;
const del = h('button', { class: `btn btn-ghost btn-small${confirming ? ' btn-danger' : ''}`, type: 'button', 'data-action': confirming ? 'confirm-delete' : 'delete', 'data-i18n': confirming ? 'ui.confirm.deletion' : 'ui.delete' }, confirming ? t('ui.confirm.deletion') : t('ui.delete'));
edit.addEventListener('click', () => {
editingId = server.id;
renderServers();
document.querySelector(`#servers-manage [data-edit="${server.id}"] input`)?.focus();
});
del.addEventListener('click', async () => {
if (confirmDeleteId !== server.id) {
confirmDeleteId = server.id;
clearTimeout(confirmTimer);
confirmTimer = setTimeout(() => {
confirmDeleteId = null;
renderServers();
}, 4000);
renderServers();
document.querySelector(`#servers-manage [data-row="${server.id}"] .btn-danger`)?.focus();
return;
}
confirmDeleteId = null;
await persist(servers().filter((s) => s.id !== server.id));
toast(() => t('message.server.p0.deleted', { p0: server.name }));
});
return h('li', { class: 'manage-row', dataset: { row: server.id } },
h('span', { class: 'server-text' }, h('span', { class: 'server-item-name', text: server.name }), h('span', { class: 'server-item-address', text: server.address })),
edit, del);
}
function editRow(server) {
const name = h('input', { type: 'text', maxlength: '64', value: server.name, 'data-field': 'name', 'aria-label': t('ui.server.name'), 'data-i18n-aria-label': 'ui.server.name' });
const address = h('input', { type: 'text', maxlength: '255', value: server.address, spellcheck: 'false', 'aria-label': t('ui.server.address'), 'data-i18n-aria-label': 'ui.server.address' });
const cancel = h('button', { class: 'btn btn-ghost btn-small', type: 'button', 'data-i18n': 'ui.cancel' }, t('ui.cancel'));
const form = h('form', { class: 'edit-row', novalidate: true, dataset: { edit: server.id } }, name, address, h('button', { class: 'btn btn-primary btn-small', type: 'submit', 'data-action': 'save', 'data-i18n': 'ui.save' }, t('ui.save')), cancel);
cancel.addEventListener('click', () => {
editingId = null;
renderServers();
});
form.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
e.preventDefault();
editingId = null;
renderServers();
}
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const n = name.value.trim();
const a = address.value.trim();
if (!n || !a) {
toast(() => t('ui.name.and.address.cannot.be.empty'), 'error');
return;
}
if (servers().some((s) => s.id !== server.id && sameAddress(s.address, a))) {
toast(() => t('ui.this.address.is.already.saved.under.another'), 'error');
return;
}
editingId = null;
await persist(servers().map((s) => (s.id === server.id ? { id: s.id, name: n, address: a } : s)));
});
return h('li', { class: 'manage-row editing' }, form);
}
-290
View File
@@ -1,290 +0,0 @@
import { t, setLanguage, onLanguageChange } from './i18n.js';
// Settings: profile (rename, UID, identity backup), audio devices/transmit mode, diagnostics.
import { $, h, setText } from './dom.js';
import { S, isConnected } from './state.js';
import { tp, call } from './core.js';
import { errorText, keyLabel } from './text.js';
import { toast } from './toast.js';
import * as voice from './voice.js';
import { watchStats } from './watch.js';
let hooks = { savePrefs: async () => {}, close: () => {}, onProfile: () => {} };
export function initSettings(h0) {
hooks = { ...hooks, ...h0 };
$('#language-select').value = S.prefs.language;
$('#language-select').addEventListener('change', async (event) => {
const select = event.target;
select.disabled = true;
try {
const prefs = await hooks.savePrefs({ language: select.value });
select.value = setLanguage(prefs.language);
} finally {
select.disabled = false;
}
});
onLanguageChange(() => {
renderDiagnostics();
renderVideo();
voice.refreshDevices();
});
$('#settings-back').addEventListener('click', () => hooks.close());
for (const host of [$('#settings-view'), $('#settings-nav')]) {
host.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !e.defaultPrevented) hooks.close();
});
}
const nav = $('#settings-nav');
nav.addEventListener('click', (e) => {
const item = e.target.closest('.nav-item');
if (item) showPanel(item.dataset.panel);
});
nav.addEventListener('keydown', (e) => {
const items = Array.from(nav.querySelectorAll('.nav-item'));
const i = items.indexOf(document.activeElement);
if (i < 0) return;
let next = null;
if (e.key === 'ArrowDown') next = items[(i + 1) % items.length];
else if (e.key === 'ArrowUp') next = items[(i - 1 + items.length) % items.length];
else if (e.key === 'Home') next = items[0];
else if (e.key === 'End') next = items[items.length - 1];
if (next) {
e.preventDefault();
next.focus();
showPanel(next.dataset.panel);
}
});
for (const radio of document.querySelectorAll('input[name="theme"]')) {
radio.addEventListener('change', () => {
if (radio.checked) hooks.savePrefs({ theme: radio.value });
});
}
$('#rename-form').addEventListener('submit', async (e) => {
e.preventDefault();
const input = $('#rename-input');
const status = $('#rename-status');
const nickname = input.value.trim();
const len = [...nickname].length;
if (len < 3 || len > 30) {
input.setAttribute('aria-invalid', 'true');
setText(status, () => t('ui.nickname.must.contain.3.30.characters'));
return;
}
if (nickname === S.profile?.nickname) {
setText(status, () => t('ui.this.is.already.your.nickname'));
return;
}
input.removeAttribute('aria-invalid');
$('#rename-submit').disabled = true;
setText(status, () => t('ui.saving'));
const uidBefore = S.profile?.uid;
try {
const profile = await call('rename', { nickname });
hooks.onProfile(profile);
setText(status, () => profile.uid === uidBefore ? t('message.saved.p0.uid.unchanged', { p0: isConnected() ? t('ui.and.applied.on.the.server') : '' }) : t('ui.saved'));
} catch (err) {
if (err.code === 'rename_not_persisted' && err.detail) {
setText(status, () => t('message.the.server.showed.p0.but.p1', { p0: err.detail.server_nickname, p1: err.detail.saved_nickname, p2: err.detail.reverted ? t('ui.the.server.nickname.was.restored') : '' }));
} else {
setText(status, () => errorText(err));
}
} finally {
$('#rename-submit').disabled = false;
}
});
$('#uid-copy').addEventListener('click', async () => {
if (S.profile?.uid && (await tp.copyText(S.profile.uid))) toast(() => t('ui.uid.copied'));
});
$('#identity-export').addEventListener('click', async () => {
const status = $('#identity-status');
const r = await tp.exportIdentity();
if (r.canceled) return;
status.dataset.state = r.ok ? 'ok' : 'error';
setText(status, () => r.ok ? t('message.saved.to.p0.uid.p1', { p0: r.file, p1: r.uid }) : t('message.export.failed.p0', { p0: errorText(r.error) }));
});
$('#identity-import').addEventListener('click', async () => {
const status = $('#identity-status');
if (S.conn.state !== 'disconnected') {
setText(status, () => t('ui.disconnect.from.the.server.first'));
return;
}
const r = await tp.importIdentity();
if (r.canceled) return;
status.dataset.state = r.ok ? 'ok' : 'error';
if (r.ok) toast(() => t('message.identity.imported.uid.p0', { p0: r.uid }));
else setText(status, () => t('message.import.failed.p0', { p0: errorText(r.error) }));
});
// Same selection path as the microphone/headphones context menus (voice.js).
$('#input-device').addEventListener('change', (e) => voice.chooseInputDevice(e.target.value));
$('#output-device').addEventListener('change', (e) => voice.chooseOutputDevice(e.target.value));
$('#voice-volume').addEventListener('input', (e) => {
const v = Number(e.target.value);
voice.setVoiceVolume(v);
setText($('#voice-volume-value'), () => `${v}%`);
});
$('#voice-volume').addEventListener('change', (e) => hooks.savePrefs({ voiceVolume: Number(e.target.value) }));
for (const radio of document.querySelectorAll('input[name="transmit"]')) {
radio.addEventListener('change', async () => {
if (radio.checked) {
await hooks.savePrefs({ transmitMode: radio.value });
renderAudio();
}
});
}
$('#ptt-assign').addEventListener('click', async () => {
const btn = $('#ptt-assign');
btn.disabled = true;
setText($('#ptt-key'), () => t('ui.press.a.key'));
const code = await voice.capturePttKey();
btn.disabled = false;
if (code) await hooks.savePrefs({ pttCode: code });
renderAudio();
btn.focus();
});
const processing = [['#opt-ns', 'noiseSuppression'], ['#opt-ec', 'echoCancellation'], ['#opt-agc', 'autoGainControl']];
for (const [sel, key] of processing) {
$(sel).addEventListener('change', async (e) => {
await hooks.savePrefs({ [key]: e.target.checked });
await voice.restartCapture();
});
}
$('#mic-test').addEventListener('click', async () => {
const btn = $('#mic-test');
const on = btn.getAttribute('aria-pressed') !== 'true';
btn.setAttribute('aria-pressed', String(on));
setText(btn, () => on ? t('ui.stop.test') : t('ui.test.microphone'));
await voice.setMicTest(on);
});
$('#open-logs').addEventListener('click', () => tp.openLogs());
$('#opt-hwdec').addEventListener('change', async (e) => {
await hooks.savePrefs({ hardwareVideoDecode: e.target.checked });
renderVideo();
});
$('#hwdec-relaunch').addEventListener('click', () => tp.relaunch());
}
export function renderProfile() {
const p = S.profile;
if (!p) return;
const input = $('#rename-input');
if (document.activeElement !== input) input.value = p.nickname ?? '';
setText($('#uid-value'), () => p.uid ?? '');
setText($('#security-level'), () => p.security_level !== null && p.security_level !== undefined ? t('message.identity.security.level.p0', { p0: p.security_level }) : '');
$('#identity-import').disabled = S.conn.state !== 'disconnected';
$('#identity-import').title = S.conn.state !== 'disconnected' ? t('ui.available.after.disconnecting.from.the.server') : '';
}
export function renderAudio() {
const prefs = S.prefs;
for (const radio of document.querySelectorAll('input[name="transmit"]')) radio.checked = radio.value === prefs.transmitMode;
setText($('#ptt-key'), () => keyLabel(prefs.pttCode));
$('#ptt-assign').disabled = false;
$('#opt-ns').checked = prefs.noiseSuppression;
$('#opt-ec').checked = prefs.echoCancellation;
$('#opt-agc').checked = prefs.autoGainControl;
$('#voice-volume').value = String(prefs.voiceVolume);
setText($('#voice-volume-value'), () => `${prefs.voiceVolume}%`);
}
export async function renderDiagnostics() {
const info = await tp.getAppInfo();
const rows = [
['TeamsPeach', info.appVersion],
[t('ui.core'), info.coreVersion ?? t('ui.not.running')],
['Electron', info.electron],
['Chromium', info.chrome],
[t('ui.platform'), `${info.platform} ${info.arch}`],
[t('ui.core.executable'), info.coreBinary ?? '—'],
[t('ui.data.folder'), info.dataDir],
];
$('#diag-list').replaceChildren(...rows.flatMap(([k, v]) => [h('dt', { text: k }), h('dd', { text: v })]));
$('#codec-list').replaceChildren(...videoCodecs().map((line) => h('li', { text: line })));
}
const IGNORED = new Set(['video/rtx', 'video/red', 'video/ulpfec', 'video/flexfec-03']);
export function videoCodecs() {
const caps = typeof RTCRtpReceiver.getCapabilities === 'function' ? RTCRtpReceiver.getCapabilities('video') : null;
if (!caps) return [t('ui.receive.capabilities.unavailable')];
return caps.codecs.filter((c) => !IGNORED.has(c.mimeType.toLowerCase())).map((c) => `${c.mimeType.replace('video/', '')}${c.sdpFmtpLine ? ` ${c.sdpFmtpLine}` : ''}`);
}
let currentPanel = 'identity';
/** Shows one settings category; the active navigation item carries aria-current="page". */
export function showPanel(name) {
currentPanel = name;
for (const panel of document.querySelectorAll('.settings-panel')) panel.hidden = panel.dataset.panel !== name;
for (const item of document.querySelectorAll('#settings-nav .nav-item')) {
if (item.dataset.panel === name) item.setAttribute('aria-current', 'page');
else item.removeAttribute('aria-current');
}
$('#settings-view .settings-scroll').scrollTop = 0;
if (name === 'video') renderVideo();
if (name === 'audio') voice.refreshDevices();
}
export function open(panel) {
renderProfile();
renderAudio();
voice.refreshDevices();
renderDiagnostics();
renderVideo();
for (const radio of document.querySelectorAll('input[name="theme"]')) radio.checked = radio.value === S.prefs.theme;
showPanel(panel ?? currentPanel);
document.querySelector(`#settings-nav .nav-item[data-panel="${currentPanel}"]`)?.focus();
}
export async function close() {
const btn = $('#mic-test');
if (btn.getAttribute('aria-pressed') === 'true') {
btn.setAttribute('aria-pressed', 'false');
setText(btn, () => t('ui.test.microphone'));
await voice.setMicTest(false);
}
}
// app.getGPUFeatureStatus().video_decode describes what the engine is allowed/able to use,
// not which decoder is decoding right now; that comes only from a live RTCPeerConnection.
const GPU_STATE = {
get enabled() { return t('ui.hardware.decoding.is.allowed.and.available.to'); },
get enabled_on() { return t('ui.hardware.decoding.is.allowed.and.available.to'); },
get enabled_force() { return t('ui.hardware.decoding.is.force.enabled'); },
get disabled_software() { return t('ui.hardware.decoding.is.disabled.the.engine.will'); },
get disabled_off() { return t('ui.hardware.decoding.is.disabled'); },
get disabled_off_ok() { return t('ui.hardware.decoding.is.disabled'); },
get unavailable_software() { return t('ui.hardware.decoding.is.unavailable.on.this.device'); },
get unavailable_off() { return t('ui.hardware.decoding.is.unavailable'); },
get unavailable_off_ok() { return t('ui.hardware.decoding.is.unavailable'); },
};
/** Saved preference vs what this run was started with vs what the engine reports vs the live decoder. */
export async function renderVideo() {
const status = await tp.getVideoStatus();
const saved = S.prefs.hardwareVideoDecode;
$('#opt-hwdec').checked = saved;
$('#hwdec-restart').hidden = !status || saved === status.hardwareDecodeAtLaunch;
if (status) {
$('#hwdec-status').dataset.policy = status.hardwareDecodeAtLaunch ? 'allowed' : 'forbidden';
const gpu = status.gpu?.video_decode ?? t('ui.unknown');
setText($('#hwdec-status'), () => t('message.this.run.p0.chromium.engine.p1', { p0: status.hardwareDecodeAtLaunch ? t('ui.allowed') : t('ui.disabled.disable.accelerated.video.decode.flag'), p1: GPU_STATE[gpu] ?? gpu }));
}
const d = watchStats.decoder;
const live = watchStats.state === 'live' || watchStats.state === 'unstable';
const efficiency = watchStats.powerEfficientDecoder === true ? t('ui.power.efficient') : watchStats.powerEfficientDecoder === false ? t('ui.not.power.efficient') : '';
setText($('#decoder-last'), () => d
? t('message.p0.p1.decoder.p2.p3', { p0: live ? t('ui.current.stream') : t('ui.last.stream'), p1: watchStats.codec || '—', p2: d, p3: efficiency })
: t('ui.the.actual.decoder.is.reported.only.while'));
}
-47
View File
@@ -1,47 +0,0 @@
// Single renderer state object plus a tiny topic bus. The core snapshot is replaced wholesale (bridge §5).
export const S = {
core: { status: 'starting' },
profile: null,
prefs: null,
conn: { state: 'disconnected', address: '', reason: null },
snap: null,
audio: { input_muted: false, output_muted: false, transmitting: false },
talking: new Set(),
view: 'main',
ptt: false,
codecBlocked: null,
};
const listeners = new Map();
export function on(topic, fn) {
if (!listeners.has(topic)) listeners.set(topic, new Set());
listeners.get(topic).add(fn);
}
export function emit(topic, payload) {
const set = listeners.get(topic);
if (!set) return;
for (const fn of set) fn(payload);
}
export function ownClient() {
const snap = S.snap;
if (!snap) return null;
return snap.clients.find((c) => c.id === snap.own_client_id) ?? null;
}
export function ownChannel() {
const snap = S.snap;
if (!snap) return null;
return snap.channels.find((c) => c.id === snap.own_channel_id) ?? null;
}
export function clientById(id) {
return S.snap ? S.snap.clients.find((c) => c.id === id) ?? null : null;
}
export function isConnected() {
return S.conn.state === 'connected' && S.snap !== null;
}
-91
View File
@@ -1,91 +0,0 @@
// Which clients are currently streaming, built only from server notifications
// (notifystreamstarted / notifystreaminfo / notifystreamupdated / notifystreamstopped).
export class StreamDirectory {
constructor() {
/** @type {Map<string, {id:string, clientId:number, name:string, fields:Record<string,string>}>} */
this.streams = new Map();
this.sfuSeen = false;
}
/** Returns true when the visible set changed. */
handle(name, items) {
let changed = false;
for (const item of items) {
switch (name) {
case 'notifystreamstarted':
case 'notifystreaminfo':
case 'notifystreamupdated':
changed = this._upsert(item, name !== 'notifystreamupdated') || changed;
break;
case 'notifystreamstopped':
changed = this._remove(item) || changed;
break;
case 'notifysfuaccessinfo':
if (!this.sfuSeen) changed = true;
this.sfuSeen = true;
break;
default:
break;
}
}
return changed;
}
_upsert(item, mayCreate) {
if (!item || !item.id) return false;
const id = String(item.id);
const existing = this.streams.get(id);
const clientId = item.clid !== undefined && item.clid !== '' ? Number(item.clid) : existing?.clientId;
if (!existing && (!mayCreate || !Number.isInteger(clientId))) return false;
const fields = { ...(existing?.fields ?? {}), ...item };
this.streams.set(id, {
id,
clientId,
name: typeof fields.name === 'string' ? fields.name : '',
fields,
});
return true;
}
_remove(item) {
if (item && item.id && this.streams.delete(String(item.id))) return true;
if (item && item.clid !== undefined) {
let removed = false;
for (const [id, s] of this.streams) {
if (s.clientId === Number(item.clid)) {
this.streams.delete(id);
removed = true;
}
}
return removed;
}
return false;
}
/** Drop streams of clients that are no longer on the server. */
prune(presentClientIds) {
let changed = false;
for (const [id, s] of this.streams) {
if (!presentClientIds.has(s.clientId)) {
this.streams.delete(id);
changed = true;
}
}
return changed;
}
byClient(clientId) {
for (const s of this.streams.values()) if (s.clientId === clientId) return s;
return null;
}
get(id) {
return this.streams.get(String(id)) ?? null;
}
clear() {
this.streams.clear();
this.sfuSeen = false;
}
}
-336
View File
@@ -1,336 +0,0 @@
// One viewing session of a TS6 screenshare (P2P path). DOM-free: the RTCPeerConnection factory is injected.
//
// Wire (server text channel, via core `stream_*` commands / `stream` events):
// join → joinstreamrequest id clid msg is_remove=0
// offer ← notifyrespondjoinstreamrequest decision=1 offer=<sdp>
// answer → streamsignaling json={"cmd":"answer","args":{"answer":<sdp>}}
// ICE ↔ {"cmd":"iceCandidate","args":{"mLine","mid","sdp"}}
// realign← {"cmd":"offer"|"reconnectOffer","args":{"offer":<sdp>}} must be answered or media never starts
// leave → joinstreamrequest … is_remove=1
export const JOIN_TIMEOUT_MS = 90_000;
/** Terminal states: no further signaling is accepted once one is reached. */
const TERMINAL = new Set(['declined', 'ended', 'removed', 'failed', 'stopped', 'unsupported']);
export class StreamViewerSession {
/**
* @param {object} o
* @param {string} o.streamId
* @param {number} o.clientId streamer clid
* @param {number} o.ownClientId
* @param {string} o.message join message (our nickname)
* @param {{join:Function, send:Function, leave:Function}} o.signal async core calls
* @param {(config:object)=>RTCPeerConnection} o.createPeerConnection
* @param {RTCIceServer[]} [o.iceServers]
* @param {(state:string, detail?:string)=>void} [o.onState]
* @param {(track:MediaStreamTrack)=>void} [o.onTrack]
* @param {(level:string, msg:string)=>void} [o.log]
* @param {(fn:Function, ms:number)=>any} [o.setTimer]
* @param {(id:any)=>void} [o.clearTimer]
*/
constructor(o) {
this.streamId = String(o.streamId);
this.clientId = Number(o.clientId);
this.ownClientId = Number(o.ownClientId);
this.message = o.message ?? '';
this.signal = o.signal;
this.createPeerConnection = o.createPeerConnection;
this.iceServers = o.iceServers ?? [];
this.onState = o.onState ?? (() => {});
this.onTrack = o.onTrack ?? (() => {});
this.log = o.log ?? (() => {});
this.setTimer = o.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
this.clearTimer = o.clearTimer ?? ((id) => clearTimeout(id));
this.state = 'idle';
this.detail = '';
this.pc = null;
this.queue = Promise.resolve();
this.pendingRemote = [];
this.pendingLocal = [];
this.answersSent = 0;
this.offersApplied = 0;
this.remoteCandidatesAdded = 0;
this.staleCandidates = 0;
this.candidateErrors = 0;
this.joinTimer = null;
}
get closed() {
return TERMINAL.has(this.state);
}
async start() {
this._setState('requesting');
this.joinTimer = this.setTimer(() => {
if (this.state === 'requesting') this._finish('failed', 'no_response', true);
}, JOIN_TIMEOUT_MS);
try {
await this.signal.join(this.streamId, this.clientId, this.message);
this.log('info', `watch: join sent id=${this.streamId} clid=${this.clientId}`);
} catch (err) {
if (!this.closed) this._finish('failed', describe(err), false);
}
}
/** User stopped or cancelled. Sends is_remove=1 unless the stream is already gone. */
stop() {
if (this.closed) return;
this._finish('stopped', '', true);
}
/** The stream or the connection went away underneath us: no leave command. */
terminate(reason) {
if (this.closed) return;
this._finish('ended', reason, false);
}
/** True when the notification belongs to this session (stream id + streamer/our clid). */
matches(item) {
if (!item || String(item.id) !== this.streamId) return false;
if (item.clid === undefined || item.clid === '') return true;
const clid = Number(item.clid);
return clid === this.clientId || clid === this.ownClientId;
}
/** Feeds one `stream` event item. Returns true when consumed. */
handle(name, item) {
if (this.closed) return false;
switch (name) {
case 'notifyrespondjoinstreamrequest': {
if (!this.matches(item)) return false;
this._clearJoinTimer();
const offer = typeof item.offer === 'string' ? item.offer : '';
if (item.decision === '1' && offer) {
this.log('info', `watch: join accepted, offer ${offer.length} chars (clid field=${item.clid ?? '-'})`);
this._enqueue(() => this._applyOffer(offer, 'join'));
} else {
this.log('info', `watch: join declined decision=${item.decision ?? '-'}`);
this._finish('declined', item.msg || '', false);
}
return true;
}
case 'notifystreamsignaling': {
if (!this.matches(item)) return false;
let message;
try {
message = JSON.parse(item.json ?? '');
} catch {
this.log('warn', 'watch: unparseable signaling json');
return true;
}
this._onSignal(message);
return true;
}
case 'notifystreamstopped': {
if (String(item.id) !== this.streamId) return false;
this._finish('ended', 'stream_stopped', false);
return true;
}
case 'notifystreamclientleft': {
if (String(item.id) !== this.streamId) return false;
if (Number(item.clid) === this.ownClientId) {
this._finish('removed', '', false);
return true;
}
return false;
}
case 'notifysfuaccessinfo': {
// The server routes this stream through its SFU (mediasoup); TeamsPeach only speaks the P2P path.
if (this.state === 'requesting' || this.matches(item)) {
this._finish('unsupported', 'sfu', true);
return true;
}
return false;
}
default:
return false;
}
}
_onSignal(message) {
const cmd = message && message.cmd;
const args = (message && message.args) || {};
switch (cmd) {
case 'offer':
case 'reconnectOffer': {
const sdp = typeof args.offer === 'string' ? args.offer : typeof args.sdp === 'string' ? args.sdp : '';
if (!sdp) {
this.log('warn', `watch: ${cmd} without sdp`);
return;
}
this.log('info', `watch: ${cmd} received (${sdp.length} chars)`);
this._enqueue(() => this._applyOffer(sdp, cmd));
return;
}
case 'iceCandidate':
this._enqueue(() => this._addRemoteCandidate(args));
return;
default:
this.log('info', `watch: ignored signaling cmd=${String(cmd)}`);
}
}
_ensurePc() {
if (this.pc) return this.pc;
const pc = this.createPeerConnection({ iceServers: this.iceServers });
this.pc = pc;
pc.onicecandidate = (event) => {
const c = event.candidate;
if (!c || !c.candidate || this.closed) return;
const msg = {
cmd: 'iceCandidate',
args: { mLine: c.sdpMLineIndex ?? 0, mid: c.sdpMid ?? String(c.sdpMLineIndex ?? 0), sdp: c.candidate },
};
if (this.answersSent === 0) this.pendingLocal.push(msg);
else this._send(msg).catch(() => {});
};
pc.ontrack = (event) => {
if (!this.closed) this.onTrack(event.track);
};
pc.onconnectionstatechange = () => {
if (this.closed) return;
const s = pc.connectionState;
this.log('info', `watch: connectionState=${s}`);
if (s === 'connected') this._setState('live');
else if (s === 'disconnected') this._setState('unstable');
else if (s === 'failed') this._finish('failed', 'ice_failed', true);
};
return pc;
}
async _applyOffer(sdp, reason) {
if (this.closed) return;
const pc = this._ensurePc();
if (this.state === 'requesting') this._setState('connecting');
if (pc.signalingState === 'have-remote-offer') {
// A newer offer superseded one we never answered: discard the stale one.
await pc.setRemoteDescription({ type: 'rollback' });
}
await pc.setRemoteDescription({ type: 'offer', sdp });
if (this.closed) return;
this.offersApplied += 1;
await this._flushRemoteCandidates();
const answer = await pc.createAnswer();
if (this.closed) return;
await pc.setLocalDescription(answer);
if (this.closed) return;
await this._send({ cmd: 'answer', args: { answer: pc.localDescription.sdp } });
if (this.closed) return;
this.answersSent += 1;
this.log('info', `watch: answer sent for ${reason} (#${this.answersSent})`);
const local = this.pendingLocal.splice(0);
for (const msg of local) this._send(msg).catch(() => {});
}
async _addRemoteCandidate(args) {
if (this.closed) return;
const sdp = typeof args.sdp === 'string' ? args.sdp : typeof args.candidate === 'string' ? args.candidate : '';
if (!sdp) return; // end-of-candidates marker
const mLine = Number(args.mLine);
const init = {
candidate: sdp,
sdpMid: args.mid === undefined || args.mid === null ? null : String(args.mid),
sdpMLineIndex: Number.isInteger(mLine) ? mLine : null,
};
if (init.sdpMid === null && init.sdpMLineIndex === null) init.sdpMLineIndex = 0;
if (!this.pc || !this.pc.remoteDescription) {
this.pendingRemote.push(init);
return;
}
await this._addCandidate(init);
}
async _flushRemoteCandidates() {
const list = this.pendingRemote.splice(0);
for (const init of list) await this._addCandidate(init);
}
async _addCandidate(init) {
const ufrag = candidateUfrag(init.candidate);
const current = remoteUfrags(this.pc.remoteDescription?.sdp ?? '');
if (ufrag && current.size > 0 && !current.has(ufrag)) {
// Belongs to an ICE generation replaced by a newer (reconnect) offer: skip deliberately.
this.staleCandidates += 1;
this.log('info', `watch: skipped candidate of previous ICE generation (${this.staleCandidates})`);
return;
}
try {
await this.pc.addIceCandidate(init);
this.remoteCandidatesAdded += 1;
} catch (err) {
this.candidateErrors += 1;
this.log('warn', `watch: current-generation candidate rejected (mid=${init.sdpMid} mLine=${init.sdpMLineIndex}): ${describe(err)}`);
}
}
/** No signaling leaves a closed session, so nothing can follow our is_remove=1. */
_send(json) {
if (this.closed) return Promise.resolve();
return this.signal.send(this.streamId, this.clientId, json).catch((err) => {
this.log('warn', `watch: signaling send failed: ${describe(err)}`);
throw err;
});
}
_enqueue(task) {
this.queue = this.queue.then(task).catch((err) => {
if (!this.closed) this._finish('failed', describe(err), true);
});
return this.queue;
}
_clearJoinTimer() {
if (this.joinTimer !== null) {
this.clearTimer(this.joinTimer);
this.joinTimer = null;
}
}
_finish(state, detail, sendLeave) {
if (this.closed) return;
this._clearJoinTimer();
this.pendingRemote = [];
this.pendingLocal = [];
if (this.pc) {
this.pc.onicecandidate = null;
this.pc.ontrack = null;
this.pc.onconnectionstatechange = null;
try {
this.pc.close();
} catch {
// already closed
}
}
this._setState(state, detail);
if (sendLeave) {
this.signal.leave(this.streamId, this.clientId).catch((err) => this.log('info', `watch: leave failed: ${describe(err)}`));
}
}
_setState(state, detail = '') {
this.state = state;
this.detail = detail;
this.onState(state, detail);
}
}
/** `ufrag` attribute of an ICE candidate line, if present. */
export function candidateUfrag(candidate) {
const m = / ufrag (\S+)/.exec(candidate);
return m ? m[1] : null;
}
/** All `a=ice-ufrag` values of the applied remote description. */
export function remoteUfrags(sdp) {
const set = new Set();
for (const m of sdp.matchAll(/^a=ice-ufrag:(\S+)/gm)) set.add(m[1]);
return set;
}
function describe(err) {
if (!err) return 'unknown';
if (typeof err === 'string') return err;
return err.code ? `${err.code}: ${err.message ?? ''}` : String(err.message ?? err);
}
-97
View File
@@ -1,97 +0,0 @@
import { t } from './i18n.js';
// User-facing wording for bridge errors and plain-text rendering of TeamSpeak BBCode.
const ERROR_TEXT = {
get bad_request() { return t('ui.invalid.request'); },
get unknown_command() { return t('ui.command.not.supported'); },
get profile_missing() { return t('ui.profile.not.created.yet'); },
get profile_exists() { return t('ui.profile.already.exists'); },
get identity_corrupt() { return t('ui.the.identity.file.is.corrupted.restore.a'); },
get profile_corrupt() { return t('ui.profile.file.corrupted'); },
get invalid_nickname() { return t('ui.nickname.must.contain.3.30.characters.with'); },
get nickname_required() { return t('ui.set.a.nickname.first'); },
get not_connected() { return t('ui.not.connected.to.a.server'); },
get already_connected() { return t('ui.already.connected'); },
get connect_failed() { return t('ui.could.not.connect'); },
get server_error() { return t('ui.the.server.rejected.the.action'); },
get audio_overflow() { return t('ui.microphone.queue.overflow.some.audio.was.dropped'); },
get audio_muted() { return t('ui.microphone.or.audio.is.muted.voice.is'); },
get audio_codec() { return t('ui.opus.codec.error'); },
get audio_codec_unsupported() { return t('ui.this.channel.uses.a.legacy.codec.speex'); },
get rename_not_persisted() { return t('ui.the.server.accepted.the.nickname.but.saving'); },
get io() { return t('ui.could.not.access.the.data.folder'); },
get internal() { return t('ui.internal.core.error'); },
get timeout() { return t('ui.the.core.did.not.respond.in.time'); },
get core_unavailable() { return t('ui.the.core.is.not.running'); },
get core_exited() { return t('ui.the.core.stopped2'); },
get core_missing() { return t('ui.core.executable.not.found'); },
get connected() { return t('ui.disconnect.from.the.server.first2'); },
get forbidden() { return t('ui.action.forbidden'); },
get device_unavailable() { return t('error.device_unavailable'); },
get device_lost() { return t('error.device_lost'); },
get capture() { return t('error.capture'); },
};
/** Localized code explanation with untouched server/OS diagnostic detail. */
export function errorText(error) {
if (!error) return t('ui.no.error.details.were.provided');
const base = ERROR_TEXT[error.code] ?? t('ui.error2');
const ts = error.ts_error;
if (ts && (ts.message || ts.name)) {
const perm = ts.missing_permission !== undefined && ts.missing_permission !== null ? t('message.missing.permission.p0', { p0: ts.missing_permission }) : '';
return `${base}: ${ts.message || ts.name} (TS ${ts.id}${perm})`;
}
if (error.message && error.message !== base) return `${base}: ${error.message}`;
return ERROR_TEXT[error.code] ?? t('error.detail', { code: error.code ?? 'no_code', detail: error.detail ?? error.message ?? t('ui.no.error.details.were.provided') });
}
const BB_TAGS = /\[\/?(?:b|i|u|s|url(?:=[^\]]*)?|color(?:=[^\]]*)?|size(?:=[^\]]*)?|center|left|right|img|quote|code|list|\*|hr|table|tr|td|th)\]/gi;
/** TeamSpeak clients send BBCode; TeamsPeach shows the plain text and never interprets markup. */
export function stripBBCode(text) {
return String(text ?? '').replace(/\[url=([^\]]*)\]([\s\S]*?)\[\/url\]/gi, (_m, href, label) => {
const l = label.trim();
return l && l !== href ? `${l} (${href})` : href;
}).replace(BB_TAGS, '');
}
/** TeamSpeak spacer channels: "[cspacer]Title", "[*spacer]-", "[spacer0]…" (top level only). */
export function parseSpacer(name) {
const m = /^\[(c|r|\*)?spacer[^\]]*\](.*)$/i.exec(name);
if (!m) return null;
const kind = m[1] === 'c' ? 'center' : m[1] === 'r' ? 'right' : m[1] === '*' ? 'repeat' : 'left';
return { kind, text: m[2] };
}
export function shortUid(uid) {
if (!uid) return '';
return uid.length > 14 ? `${uid.slice(0, 8)}…${uid.slice(-4)}` : uid;
}
const KEY_NAMES = {
get Space() { return t('ui.space'); },
Backquote: '`',
get ControlLeft() { return t('ui.left.ctrl'); },
get ControlRight() { return t('ui.right.ctrl'); },
get AltLeft() { return t('ui.left.alt'); },
get AltRight() { return t('ui.right.alt'); },
get ShiftLeft() { return t('ui.left.shift'); },
get ShiftRight() { return t('ui.right.shift'); },
get MetaLeft() { return t('ui.left.super'); },
get MetaRight() { return t('ui.right.super'); },
CapsLock: 'Caps Lock',
Tab: 'Tab',
};
export function keyLabel(code) {
if (!code) return t('ui.not.assigned');
if (KEY_NAMES[code]) return KEY_NAMES[code];
if (code.startsWith('Key')) return code.slice(3);
if (code.startsWith('Digit')) return code.slice(5);
if (code.startsWith('Numpad')) return `Num ${code.slice(6)}`;
return code;
}
export function pluralMembers(n) {
return t('members.count', { count: n });
}
-16
View File
@@ -1,16 +0,0 @@
import { t } from './i18n.js';
import { $, h, icon } from './dom.js';
const MAX_TOASTS = 4;
/** Non-blocking notice in the polite live region. Errors stay longer. */
export function toast(text, kind = 'info') {
const host = $('#toasts');
const close = h('button', { class: 'icon-btn', type: 'button', 'aria-label': t('ui.dismiss.notification'), 'data-i18n-aria-label': 'ui.dismiss.notification' }, icon('x'));
const el = h('div', { class: 'toast', role: kind === 'error' ? 'alert' : 'status', dataset: { kind } }, h('span', { class: 'toast-text', text }), close);
const remove = () => el.remove();
close.addEventListener('click', remove);
host.appendChild(el);
while (host.children.length > MAX_TOASTS) host.firstElementChild.remove();
setTimeout(remove, kind === 'error' ? 10000 : 5000);
}
-347
View File
@@ -1,347 +0,0 @@
import { t, getLanguage } from './i18n.js';
// Channel tree with members (TeamSpeak order): talking state, mute flags, server-configured group
// labels and icons, channel icons/banners, avatars and stream badges — all from real server data.
import { $, h, icon, reconcile, setText } from './dom.js';
import { S, isConnected } from './state.js';
import { call } from './core.js';
import { errorText, parseSpacer, pluralMembers } from './text.js';
import { toast } from './toast.js';
import { iconUrl, isBuiltinIcon, channelBannerUrl, avatarUrl } from './media.js';
let hooks = { openPrivate: () => {}, openSettings: () => {}, toggleWatch: () => {}, streamOf: () => null, watchingId: () => null };
let pendingPasswordCid = null;
export function initTree(h0) {
hooks = { ...hooks, ...h0 };
}
function sortClients(a, b) {
if (b.talk_power !== a.talk_power) return b.talk_power - a.talk_power;
return a.nickname.localeCompare(b.nickname, getLanguage(), { sensitivity: 'base' });
}
export function renderTree() {
const list = $('#tree');
const empty = $('#tree-empty');
if (!isConnected()) {
list.replaceChildren();
empty.hidden = false;
setText(empty, () => S.conn.state === 'connecting' ? t('ui.connecting2') : t('ui.channels.will.appear.after.you.connect.to'));
pendingPasswordCid = null;
return;
}
empty.hidden = true;
const snap = S.snap;
const byChannel = new Map();
for (const c of snap.clients) {
if (c.client_type === 'query') continue;
if (!byChannel.has(c.channel_id)) byChannel.set(c.channel_id, []);
byChannel.get(c.channel_id).push(c);
}
const items = [];
for (const ch of snap.channels) {
const members = (byChannel.get(ch.id) ?? []).sort(sortClients);
const spacer = ch.parent_id === 0 ? parseSpacer(ch.name) : null;
if (spacer) items.push({ type: 'spacer', ch, spacer });
else items.push({ type: 'channel', ch, count: members.length });
if (pendingPasswordCid === ch.id) items.push({ type: 'password', ch });
for (const cl of members) items.push({ type: 'member', cl, depth: ch.depth + 1 });
}
reconcile(list, items, keyOf, createRow, updateRow);
}
function keyOf(item) {
switch (item.type) {
case 'member': return `u:${item.cl.id}`;
case 'password': return `p:${item.ch.id}`;
case 'spacer': return `s:${item.ch.id}`;
default: return `c:${item.ch.id}`;
}
}
function createRow(item) {
switch (item.type) {
case 'spacer':
return h('li', { class: 'tree-row spacer-row', role: 'presentation' });
case 'password':
return createPasswordRow(item.ch);
case 'member':
return createMemberRow();
default:
return createChannelRow();
}
}
function updateRow(el, item) {
switch (item.type) {
case 'spacer': {
el.style.setProperty('--depth', String(item.ch.depth));
el.dataset.kind = item.spacer.kind;
const text = item.spacer.kind === 'repeat' ? item.spacer.text.repeat(Math.max(1, Math.ceil(60 / Math.max(1, item.spacer.text.length)))) : item.spacer.text;
setText(el, () => text);
break;
}
case 'password':
el.style.setProperty('--depth', String(item.ch.depth));
el.querySelector('input').setAttribute('aria-label', t('message.password.for.channel.p0', { p0: item.ch.name }));
break;
case 'member':
updateMemberRow(el, item.cl, item.depth);
break;
default:
updateChannelRow(el, item.ch, item.count);
}
}
// ---------- channels ----------
function createChannelRow() {
const btn = h(
'button',
{ class: 'row-btn', type: 'button' },
icon('channel'),
h('span', { class: 'row-label' }),
h('span', { class: 'channel-icon', 'aria-hidden': 'true' }),
h('span', { class: 'channel-meta' }),
);
const li = h('li', { class: 'tree-row channel-row' }, btn);
btn.addEventListener('click', () => joinChannel(Number(li.dataset.cid)));
return li;
}
function updateChannelRow(li, ch, count) {
li.dataset.cid = String(ch.id);
li.style.setProperty('--depth', String(ch.depth));
const current = ch.id === S.snap.own_channel_id;
li.dataset.current = String(current);
const btn = li.firstElementChild;
const [ic, label, chIcon, meta] = btn.children;
ic.firstElementChild.setAttribute('href', ch.has_password ? '#i-lock' : '#i-channel');
setText(label, () => ch.name);
const max = ch.max_clients;
setText(meta, () => max !== null && max !== undefined && max >= 0 && count > 0 ? `${count}/${max}` : max === 0 ? t('ui.closed') : '');
const parts = [ch.name];
if (ch.has_password) parts.push(t('ui.password.protected'));
parts.push(pluralMembers(count));
if (current) parts.push(t('ui.you.are.here'));
btn.setAttribute('aria-label', parts.join(', '));
btn.title = ch.topic ? ch.topic : current ? t('ui.you.are.in.this.channel') : t('ui.join.channel');
if (current) btn.setAttribute('aria-current', 'location');
else btn.removeAttribute('aria-current');
// Channel icon and banner are the server's own files; nothing is drawn when the server has none.
const iconKey = String(ch.icon_id ?? '');
if (chIcon.dataset.sig !== iconKey) {
chIcon.dataset.sig = iconKey;
chIcon.replaceChildren();
iconUrl(ch.icon_id).then((url) => {
if (url && chIcon.dataset.sig === iconKey) chIcon.appendChild(h('img', { src: url, alt: '', draggable: 'false' }));
});
}
const bannerKey = ch.banner_url ?? '';
if (btn.dataset.banner !== bannerKey) {
btn.dataset.banner = bannerKey;
li.classList.remove('has-banner');
btn.style.removeProperty('--banner');
channelBannerUrl(ch).then((url) => {
if (!url || btn.dataset.banner !== bannerKey) return;
btn.style.setProperty('--banner', `url("${url}")`);
li.classList.add('has-banner');
});
}
}
async function joinChannel(cid) {
if (!isConnected() || cid === S.snap.own_channel_id) return;
const ch = S.snap.channels.find((c) => c.id === cid);
if (!ch) return;
if (ch.has_password) {
pendingPasswordCid = pendingPasswordCid === cid ? null : cid;
renderTree();
const input = document.querySelector(`[data-key="p:${cid}"] input`);
if (input) input.focus();
return;
}
try {
await call('join_channel', { channel_id: cid });
} catch (err) {
toast(() => t('message.could.not.join.p0.p1', { p0: ch.name, p1: errorText(err) }), 'error');
}
}
function createPasswordRow(ch) {
const input = h('input', { type: 'password', autocomplete: 'off', 'aria-label': t('message.password.for.channel.p0', { p0: ch.name }), placeholder: t('ui.channel.password'), 'data-i18n-placeholder': 'ui.channel.password' });
const cancel = h('button', { class: 'btn btn-ghost', type: 'button', 'data-i18n': 'ui.cancel' }, t('ui.cancel'));
const form = h('form', { novalidate: true }, input, h('button', { class: 'btn btn-primary', type: 'submit', 'data-i18n': 'ui.join' }, t('ui.join')), cancel);
const li = h('li', { class: 'tree-row password-row' }, form);
const close = () => {
pendingPasswordCid = null;
renderTree();
};
cancel.addEventListener('click', close);
input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') close();
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
try {
await call('join_channel', { channel_id: ch.id, password: input.value });
close();
} catch (err) {
input.setAttribute('aria-invalid', 'true');
toast(() => t('message.could.not.enter.p0.p1', { p0: ch.name, p1: errorText(err) }), 'error');
input.select();
}
});
return li;
}
// ---------- members ----------
function createMemberRow() {
const btn = h(
'button',
{ class: 'row-btn', type: 'button' },
h('span', { class: 'avatar', 'aria-hidden': 'true' }, h('span', { class: 'status-dot' })),
h('span', { class: 'group-label', hidden: true }),
h('span', { class: 'row-label' }),
h('span', { class: 'group-label', hidden: true }),
h('span', { class: 'member-tag' }),
h('span', { class: 'member-flags' }),
h('span', { class: 'member-badges' }),
);
const li = h('li', { class: 'tree-row member-row' }, btn);
btn.addEventListener('click', () => {
const id = Number(li.dataset.clid);
if (li.dataset.self === 'true') hooks.openSettings();
else hooks.openPrivate(id);
});
return li;
}
/** A client's server groups (catalog order) plus its channel group, resolved from the snapshot. */
function groupsOf(cl) {
const ids = new Set(cl.server_groups ?? []);
const server = (S.snap.server_groups ?? []).filter((g) => ids.has(g.id));
const channel = (S.snap.channel_groups ?? []).find((g) => g.id === cl.channel_group_id) ?? null;
return { server, channel };
}
function updateMemberRow(li, cl, depth) {
li.dataset.clid = String(cl.id);
li.style.setProperty('--depth', String(depth));
li.dataset.self = String(cl.is_self);
const talking = cl.is_self ? S.audio.transmitting : S.talking.has(cl.id);
li.dataset.talking = String(talking);
const btn = li.firstElementChild;
const [avatar, before, label, after, tag, flags, badges] = btn.children;
setText(label, () => cl.nickname);
setText(tag, () => cl.is_self ? t('ui.you') : '');
// Group names appear next to the nickname exactly where each group's name_mode puts them.
const { server: groups, channel: cgroup } = groupsOf(cl);
const named = cgroup ? [...groups, cgroup] : groups;
const beforeText = named.filter((g) => g.name_mode === 'before').map((g) => g.name).join(' · ');
const afterText = named.filter((g) => g.name_mode === 'after').map((g) => g.name).join(' · ');
setText(before, () => beforeText);
before.title = beforeText;
before.hidden = !beforeText;
setText(after, () => afterText);
after.title = afterText;
after.hidden = !afterText;
const flagIcons = [];
const states = [];
if (cl.output_muted) {
flagIcons.push(['headphones-off', 'flag-muted', t('ui.audio.muted')]);
states.push(t('ui.audio.muted2'));
} else if (cl.input_muted) {
flagIcons.push(['mic-off', 'flag-muted', t('ui.microphone.muted')]);
states.push(t('ui.microphone.muted2'));
}
if (!cl.input_hardware && !cl.input_muted) {
flagIcons.push(['mic-off', '', t('ui.no.microphone')]);
states.push(t('ui.no.microphone2'));
}
if (cl.away) {
flagIcons.push(['moon', '', cl.away_message ? t('message.away.p0', { p0: cl.away_message }) : t('ui.away')]);
states.push(cl.away_message ? t('message.away.p02', { p0: cl.away_message }) : t('ui.away2'));
}
if (cl.is_recording) {
flagIcons.push(['record', 'flag-rec', t('ui.recording.the.conversation')]);
states.push(t('ui.recording'));
}
const flagKey = flagIcons.map((f) => f.join(':')).join('|');
if (flags.dataset.sig !== flagKey) {
flags.dataset.sig = flagKey;
flags.replaceChildren(...flagIcons.map(([name, cls, title]) => h('span', { title }, icon(name, cls))));
}
// Group icons: custom files from the server; built-in ids have no file, shown as a neutral named badge.
const iconGroups = named.filter((g) => g.icon_id);
const badgeKey = `${getLanguage()}|${iconGroups.map((g) => `${g.id}:${g.icon_id}`).join(',')}|${cl.country ?? ''}`;
if (badges.dataset.sig !== badgeKey) {
badges.dataset.sig = badgeKey;
badges.replaceChildren(
...iconGroups.map((g) => groupBadge(g)),
...(cl.country ? [h('span', { class: 'country', title: t('message.country.p0', { p0: cl.country }), text: cl.country })] : []),
);
}
const avatarKey = `${cl.avatar_hash ?? ''}|${JSON.stringify(cl.myts_avatars ?? null)}`;
if (avatar.dataset.sig !== avatarKey) {
avatar.dataset.sig = avatarKey;
avatar.querySelector('img')?.remove();
avatar.classList.remove('has-image');
avatarUrl(cl).then((url) => {
if (!url || avatar.dataset.sig !== avatarKey) return;
avatar.prepend(h('img', { src: url, alt: '', draggable: 'false' }));
avatar.classList.add('has-image');
});
}
if (talking) states.unshift(t('ui.talking'));
const groupNames = groups.map((g) => g.name);
btn.setAttribute('aria-label', `${cl.nickname}${cl.is_self ? t('ui.you2') : ''}${groupNames.length ? t('message.groups.p0', { p0: groupNames.join(', ') }) : ''}${states.length ? `, ${states.join(', ')}` : ''}${cl.is_self ? t('ui.open.profile.settings') : t('ui.send.a.private.message')}`);
btn.title = [cl.description ? t('message.description.p0', { p0: cl.description }) : '', groupNames.length ? t('message.groups.p02', { p0: groupNames.join(', ') }) : '', cl.is_self ? t('ui.profile.settings') : t('ui.send.a.private.message2')].filter(Boolean).join('\n');
const stream = hooks.streamOf(cl.id);
let watch = li.querySelector('.watch-btn');
if (stream && !cl.is_self) {
if (!watch) {
watch = h('button', { class: 'watch-btn', type: 'button' }, icon('monitor'), h('span', { text: t('ui.watch') }));
watch.addEventListener('click', () => {
const s = hooks.streamOf(Number(li.dataset.clid));
if (s) hooks.toggleWatch(s);
});
li.appendChild(watch);
}
const watching = hooks.watchingId() === stream.id;
watch.setAttribute('aria-pressed', String(watching));
setText(watch.lastElementChild, () => watching ? t('ui.watching') : t('ui.watch'));
watch.setAttribute('aria-label', t('message.p0.p1.p2', { p0: watching ? t('ui.stop.watching') : t('ui.watch'), p1: cl.nickname, p2: stream.name ? `: ${stream.name}` : '' }));
watch.title = stream.name || t('ui.screen.share');
} else if (watch) {
watch.remove();
}
}
function groupBadge(group) {
const el = h('span', { class: 'group-icon', title: group.name, role: 'img', 'aria-label': group.name });
if (isBuiltinIcon(group.icon_id)) {
el.appendChild(icon('shield'));
return el;
}
iconUrl(group.icon_id).then((url) => {
el.appendChild(url ? h('img', { src: url, alt: '', draggable: 'false' }) : icon('shield'));
});
return el;
}
/** Cheap talking update without a full reconcile. */
export function updateTalking(clientId) {
const li = document.querySelector(`#tree [data-key="u:${clientId}"]`);
if (!li || !S.snap) return;
const cl = S.snap.clients.find((c) => c.id === clientId);
if (cl) updateMemberRow(li, cl, Number(li.style.getPropertyValue('--depth')) || 0);
}
-134
View File
@@ -1,134 +0,0 @@
// Settings → Information → Updates. The main-process update service owns every decision (source, channel,
// platform, verification) and sends codes, never user text; this module only renders that state in the
// current language and forwards explicit user actions.
import { $, setText } from './dom.js';
import { tp } from './core.js';
import { toast } from './toast.js';
import { t, getLanguage, hasTranslation, onLanguageChange } from './i18n.js';
let state = null;
let announced = null; // version already announced by a toast in this run
let initialized = false;
/** Localized text for an updater code (`update.<group>.<code>`); optional params default to empty. */
function codeText(group, code, params) {
const key = `update.${group}.${code}`;
if (!code || !hasTranslation(key)) return String(code ?? '');
try {
return t(key, { tag: '', file: null, detail: '', target: '', ...params });
} catch {
return String(code);
}
}
const when = (iso) => new Date(iso).toLocaleString(getLanguage(), { dateStyle: 'short', timeStyle: 'short' });
function statusText(s) {
const version = s.available?.version;
switch (s.phase) {
case 'disabled':
return t('update.ui.status.disabled', { reason: codeText('disabled', s.disabledCode, s.disabledParams ?? {}) });
case 'idle':
return t('update.ui.status.idle');
case 'checking':
return t('update.ui.status.checking');
case 'up-to-date': {
const base = s.lastCheckedAt ? t('update.ui.status.upToDateChecked', { time: when(s.lastCheckedAt) }) : t('update.ui.status.upToDate');
return s.newerPreview ? `${base} ${t('update.ui.status.newerPreview', { version: s.newerPreview })}` : base;
}
case 'available': {
const base = t(s.available?.preview ? 'update.ui.status.availablePreview' : 'update.ui.status.available', { version });
if (s.mode !== 'manual') return base;
return `${base} ${s.manualReason ? codeText('manual', s.manualReason, {}) : t('update.ui.status.manual')}`;
}
case 'deferred':
return t('update.ui.status.deferred', { version });
case 'downloading':
return t('update.ui.status.downloading', { version, percent: Math.round(s.progress?.percent ?? 0) });
case 'downloaded':
return t('update.ui.status.downloaded', { version });
case 'installing':
return t('update.ui.status.installing');
case 'error':
return t('update.ui.status.error', { message: codeText('error', s.error?.code, s.error?.params ?? {}) });
default:
return '';
}
}
function render() {
if (!state) return;
const s = state;
$('#update-channel').value = s.channel;
$('#update-channel').disabled = s.phase === 'disabled';
let text = statusText(s);
const skipped = s.newerWithoutBuild?.[0];
if (skipped && s.phase !== 'disabled') {
text += ` ${t('update.ui.status.skipped', { version: skipped.version, reason: codeText('skip', skipped.code, { version: skipped.version, ...skipped.params }) })}`;
}
setText($('#update-status'), text);
const progress = $('#update-progress');
progress.hidden = s.phase !== 'downloading';
progress.value = Math.round(s.progress?.percent ?? 0);
const busy = s.phase === 'checking' || s.phase === 'downloading' || s.phase === 'installing';
const check = $('#update-check');
check.hidden = s.phase === 'disabled';
check.disabled = busy;
setText(check, t(s.phase === 'error' ? 'update.ui.retry' : 'update.ui.check'));
const download = $('#update-download');
download.hidden = !(s.mode === 'auto' && (s.phase === 'available' || s.phase === 'deferred'));
setText(download, t(s.phase === 'deferred' ? 'update.ui.downloadNow' : 'update.ui.download'));
$('#update-install').hidden = !(s.mode === 'auto' && s.phase === 'downloaded');
$('#update-open').hidden = !s.available;
if (s.phase !== 'downloaded') $('#update-confirm').hidden = true;
if (s.available && s.available.version !== announced && (s.phase === 'available' || s.phase === 'deferred' || s.phase === 'downloaded')) {
const version = s.available.version;
announced = version;
toast(() => t('update.ui.toast.available', { version }));
}
}
function askToInterrupt() {
$('#update-confirm').hidden = false;
$('#update-confirm-yes').focus();
}
async function install(confirmInterrupt) {
const r = await tp.installUpdate(confirmInterrupt);
if (!r || r.ok) return;
if (r.code === 'session-active') askToInterrupt();
else toast(() => (r.code ? codeText('install', r.code, r.params ?? {}) : t('update.ui.installFailed')), 'error');
}
export async function initUpdates() {
if (initialized) return;
initialized = true;
tp.onUpdateState((next) => {
state = next;
render();
});
onLanguageChange(render);
$('#update-check').addEventListener('click', () => tp.checkForUpdates());
$('#update-download').addEventListener('click', () => tp.downloadUpdate());
$('#update-open').addEventListener('click', () => tp.openUpdateRelease());
$('#update-install').addEventListener('click', () => (state?.sessionActive ? askToInterrupt() : install(false)));
$('#update-confirm-yes').addEventListener('click', () => install(true));
$('#update-confirm-no').addEventListener('click', () => {
$('#update-confirm').hidden = true;
$('#update-install').focus();
});
$('#update-channel').addEventListener('change', async (e) => {
const next = await tp.setUpdateChannel(e.target.value);
if (next) {
state = next;
render();
}
});
const initial = await tp.getUpdateState();
if (initial && !state) {
state = initial;
render();
}
}
-310
View File
@@ -1,310 +0,0 @@
// Voice: microphone capture → core (gated by mute/deafen/PTT/open mic), core mix → speakers,
// device selection and push-to-talk keys.
import { $, setText } from './dom.js';
import { S, isConnected, ownChannel } from './state.js';
import { tp, log } from './core.js';
import { AudioEngine } from './audio/engine.js';
import { buildDeviceOptions } from './audio/devices.js';
import { toast } from './toast.js';
import { errorText, keyLabel } from './text.js';
import { t } from './i18n.js';
export const voiceStats = { framesSent: 0, bursts: 0, framesPlayed: 0, level: 0 };
let engine = null;
let sending = false;
let burst = null;
let micTest = false;
let meterRaf = 0;
let assigningPtt = null;
let hooks = { onPtt: () => {}, onPttAssigned: () => {}, onTransmitChanged: () => {}, savePrefs: async () => S.prefs, onOutputChanged: () => {} };
export function initVoice(h0) {
hooks = { ...hooks, ...h0 };
engine = new AudioEngine({
onFrame,
onError: (e) => toast(() => errorText(e), 'error'),
log,
});
tp.onAudio(({ pcm }) => {
voiceStats.framesPlayed += 1;
engine.pushPlayback(pcm);
});
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
window.addEventListener('blur', () => {
setPtt(false, 'window-blur');
hooks.onPtt(false);
});
window.addEventListener('focus', () => hooks.onPtt(S.ptt));
navigator.mediaDevices.addEventListener('devicechange', () => refreshDevices());
const btn = $('#btn-ptt');
btn.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return;
btn.setPointerCapture(e.pointerId);
setPtt(true, 'button');
});
const release = () => setPtt(false, 'button');
btn.addEventListener('pointerup', release);
btn.addEventListener('pointercancel', release);
btn.addEventListener('lostpointercapture', release);
btn.addEventListener('keydown', (e) => {
if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) {
e.preventDefault();
setPtt(true, 'button');
}
});
btn.addEventListener('keyup', (e) => {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
setPtt(false);
}
});
}
/** Creates the AudioContext and applies output prefs; safe to call repeatedly. */
export async function startAudio() {
try {
await engine.init();
engine.setVoiceVolume(S.prefs.voiceVolume);
if (S.prefs.outputDeviceId) await engine.setOutputDevice(S.prefs.outputDeviceId).catch((err) => toast(() => t('message.output.device.unavailable.p0', { p0: err.message }), 'error'));
} catch (err) {
toast(() => t('message.audio.unavailable.p0', { p0: err.message }), 'error');
log('error', `audio init failed: ${err.message}`);
}
}
function channelCanTransmit() {
const ch = ownChannel();
return !ch || ch.codec === null || ch.codec === undefined || ch.codec === 'opus_voice' || ch.codec === 'opus_music';
}
export function shouldTransmit() {
return isConnected()
&& !S.audio.input_muted
&& !S.audio.output_muted
&& (S.prefs.transmitMode === 'open' || S.ptt)
&& channelCanTransmit();
}
function onFrame(pcm, rms, peak) {
voiceStats.level = peak;
if (micTest && !meterRaf) meterRaf = requestAnimationFrame(drawMeter);
if (shouldTransmit()) {
tp.sendAudioFrame(new Uint8Array(pcm));
voiceStats.framesSent += 1;
if (!sending) {
sending = true;
voiceStats.bursts += 1;
burst = { frames: 0, peakMax: 0, mode: S.prefs.transmitMode };
log('debug', `voice: burst start mode=${burst.mode} focused=${document.hasFocus()} capture=${engine.capturing}`);
hooks.onTransmitChanged();
}
burst.frames += 1;
if (peak > burst.peakMax) burst.peakMax = peak;
} else if (sending) {
tp.endAudio();
sending = false;
log('debug', `voice: burst end frames=${burst.frames} peak=${burst.peakMax > 0 ? (20 * Math.log10(burst.peakMax)).toFixed(1) : '-inf'} dBFS`);
burst = null;
hooks.onTransmitChanged();
}
}
function drawMeter() {
meterRaf = 0;
const db = voiceStats.level > 0 ? 20 * Math.log10(voiceStats.level) : -100;
const pct = Math.max(0, Math.min(100, ((db + 60) / 60) * 100));
$('#mic-meter').style.width = `${pct.toFixed(0)}%`;
}
/**
* Capture runs while connected (or during the settings mic test). Stopping also cancels a start that is
* still waiting for the microphone, and a second call while one start is pending does not open another.
*/
export async function syncCapture() {
const want = isConnected() || micTest;
if (!want) {
engine.stopCapture();
if (sending) {
tp.endAudio();
sending = false;
}
return;
}
if (engine.capturing || engine.captureStarting) return;
try {
const label = await engine.startCapture({
deviceId: S.prefs.inputDeviceId,
echoCancellation: S.prefs.echoCancellation,
noiseSuppression: S.prefs.noiseSuppression,
autoGainControl: S.prefs.autoGainControl,
});
if (label !== null) refreshDevices();
} catch (err) {
if (err.code === 'device_unavailable') toast(() => errorText(err), 'error');
else toast(() => t('message.microphone.access.unavailable.p0', { p0: err.message || err.name }), 'error');
log('error', `capture failed: ${err.name} ${err.message}`);
}
}
/**
* Re-opens the microphone with the current preferences. Also used after a failed start, so a newly chosen
* device recovers capture whenever capture is wanted (connected or mic test); otherwise nothing opens.
*/
export async function restartCapture() {
engine.stopCapture();
await syncCapture();
}
export function setMicTest(on) {
micTest = on;
if (!on) $('#mic-meter').style.width = '0%';
return syncCapture();
}
export function onOutputMuted(muted) {
if (muted) engine.flushPlayback();
}
export function setVoiceVolume(pct) {
engine.setVoiceVolume(pct);
}
/** Saved input device for capture; used by Settings and by the microphone context menu. */
export async function chooseInputDevice(deviceId) {
const saved = await hooks.savePrefs({ inputDeviceId: deviceId });
if (saved?.inputDeviceId === deviceId) await restartCapture(); // not saved: keep capturing from the stored device
await refreshDevices();
}
/** Saved output device for voice and stream audio; used by Settings and by the headphones menu. */
export async function chooseOutputDevice(deviceId) {
const saved = await hooks.savePrefs({ outputDeviceId: deviceId });
if (saved?.outputDeviceId !== deviceId) {
await refreshDevices(); // not saved: audio stays on the stored device the UI shows
return;
}
try {
await engine.setOutputDevice(deviceId);
} catch (err) {
toast(() => t('message.could.not.select.output.device.p0', { p0: err.message }), 'error');
}
hooks.onOutputChanged();
await refreshDevices();
}
export function playbackStats() {
return engine.playbackStats();
}
// ---------- devices ----------
let lastChoices = null;
/** Last enumerated choices ({input, output} from buildDeviceOptions), shared by Settings and the menus. */
export async function deviceChoices() {
await refreshDevices();
return lastChoices;
}
export async function refreshDevices() {
const status = $('#device-status');
let devices;
try {
devices = await navigator.mediaDevices.enumerateDevices();
} catch (err) {
// The menus must show this failure, not an earlier successful list.
lastChoices = { error: { name: err.name, message: err.message } };
setText(status, () => t('message.could.not.list.devices.p0.p1', { p0: err.name, p1: err.message }));
log('warn', `enumerateDevices failed: ${err.name}`);
return;
}
const input = buildDeviceOptions(devices.filter((d) => d.kind === 'audioinput'), S.prefs.inputDeviceId);
const output = buildDeviceOptions(devices.filter((d) => d.kind === 'audiooutput'), S.prefs.outputDeviceId);
fillSelect($('#input-device'), input.options, S.prefs.inputDeviceId);
fillSelect($('#output-device'), output.options, S.prefs.outputDeviceId);
let text;
if (input.redacted || output.redacted) text = t('ui.the.engine.hid.the.device.list.audio');
else if (input.physical === 0 && output.physical === 0) text = t('ui.no.audio.devices.found');
else if (input.physical === 0) text = t('message.no.microphones.found.output.devices.p0', { p0: output.physical });
else if (output.physical === 0) text = t('message.microphones.p0.no.output.devices.found', { p0: input.physical });
else text = t('message.microphones.found.p0.output.devices.p1', { p0: input.physical, p1: output.physical });
setText(status, () => text);
lastChoices = { input, output, status: text };
log('info', `devices: inputs=${input.physical} outputs=${output.physical} redacted=${input.redacted || output.redacted}`);
}
function fillSelect(select, options, selected) {
select.replaceChildren(...options.map((o) => {
const opt = document.createElement('option');
opt.value = o.value;
opt.textContent = o.label;
return opt;
}));
select.value = selected || '';
}
// ---------- push-to-talk ----------
function isTextField(el) {
return el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && !['checkbox', 'radio', 'range', 'button', 'submit'].includes(el.type)) || el?.isContentEditable;
}
function onKeyDown(e) {
if (assigningPtt) {
e.preventDefault();
e.stopPropagation();
const done = assigningPtt;
assigningPtt = null;
done(e.key === 'Escape' ? null : e.code);
return;
}
if (e.code !== S.prefs?.pttCode || e.repeat) return;
if (S.prefs.transmitMode !== 'ptt') return;
if (isTextField(e.target) && e.key.length === 1) return;
setPtt(true);
}
function onKeyUp(e) {
if (e.code === S.prefs?.pttCode) setPtt(false);
}
export function setPtt(down, source = 'key') {
if (S.ptt === down) return;
S.ptt = down;
const btn = $('#btn-ptt');
btn.setAttribute('aria-pressed', String(down));
setText(btn, () => down ? t('ui.talk.now') : t('ui.hold.to.talk'));
if (S.prefs?.transmitMode === 'ptt') log('debug', `voice: ptt ${down ? 'down' : 'up'} source=${source} focused=${document.hasFocus()}`);
hooks.onPtt(down);
}
/** Resolves with a KeyboardEvent.code, or null when cancelled with Escape. */
export function capturePttKey() {
return new Promise((resolve) => {
assigningPtt = resolve;
});
}
export function transmitHint() {
if (!S.prefs) return '';
if (S.prefs.transmitMode === 'open') return t('ui.open.microphone');
// The key is read only from this window: say so whenever another window has the focus.
if (!document.hasFocus()) return t('message.window.unfocused.p0.will.not.work', { p0: keyLabel(S.prefs.pttCode) });
return t('message.key.p0', { p0: keyLabel(S.prefs.pttCode) });
}
export function isCapturing() {
return Boolean(engine && engine.capturing);
}
export function isSending() {
return sending;
}
export function channelCodecProblem() {
const ch = ownChannel();
if (!ch || channelCanTransmit()) return null;
return ch.codec;
}
-412
View File
@@ -1,412 +0,0 @@
import { t, onLanguageChange } from './i18n.js';
// TS6 screenshare: discovery (stream_list + notifications), one viewing session, the viewer panel.
import { $, setIcon, setText } from './dom.js';
import { S, isConnected, clientById } from './state.js';
import { call, log } from './core.js';
import { StreamDirectory } from './stream/directory.js';
import { StreamViewerSession } from './stream/session.js';
import { toast } from './toast.js';
import { errorText } from './text.js';
// Same public STUN endpoints the official TS6 client ships with (see docs/evidence/ts6-official-client.md).
const ICE_SERVERS = [{ urls: ['stun:turn.teamspeak.com:3478', 'stun:turn2.teamspeak.com:3478'] }];
export const directory = new StreamDirectory();
let session = null;
let current = null; // { id, clientId, name, nickname }
let media = null;
let statsTimer = null;
let attachTimer = null;
let lastCodecLogged = '';
let sfuToastShown = false;
let hooks = { onChange: () => {}, savePrefs: () => {} };
let listTimer = null;
let listFull = false;
const listClients = new Set();
let knownChannelPeers = new Set();
let knownOwnChannel = null;
function emptyStats() {
return {
codec: '', fmtp: '', decoder: '', powerEfficientDecoder: null, width: 0, height: 0, fps: 0,
framesDecoded: 0, videoPackets: 0, videoBytes: 0, packetsLost: 0, keyFrames: 0,
audioTrackPresent: false, streamAdvertisesAudio: null, audioCodec: '', inboundAudioPackets: 0, inboundAudioBytes: 0,
remoteCandidatesAdded: 0, staleCandidates: 0, candidateErrors: 0, offersApplied: 0, answersSent: 0, pair: '',
sinkId: '', sinkError: '',
};
}
export const watchStats = { state: 'idle', ...emptyStats() };
export function initWatch(h0) {
hooks = { ...hooks, ...h0 };
onLanguageChange(() => {
applyVolume();
updateStatsLine();
});
const video = $('#stream-video');
const volume = $('#stream-volume');
volume.addEventListener('input', () => applyVolume());
volume.addEventListener('change', () => hooks.savePrefs({ streamVolume: Number(volume.value) }));
$('#stream-mute').addEventListener('click', () => {
const btn = $('#stream-mute');
btn.setAttribute('aria-pressed', String(btn.getAttribute('aria-pressed') !== 'true'));
applyVolume();
});
$('#stream-fullscreen').addEventListener('click', () => {
const view = $('#stream-view');
if (document.fullscreenElement) document.exitFullscreen();
else view.requestFullscreen().catch((err) => toast(() => t('message.full.screen.unavailable.p0', { p0: err.message }), 'error'));
});
$('#stream-stop').addEventListener('click', () => stopWatching());
video.addEventListener('resize', () => updateStatsLine());
// The output device is applied to a running player only; an element without media has nothing to route.
video.addEventListener('playing', () => applySink());
}
export function streamOf(clientId) {
return directory.byClient(clientId);
}
export function watchingId() {
return session && !session.closed ? current.id : null;
}
export function toggleWatch(stream) {
if (session && !session.closed && current && current.id === stream.id) {
stopWatching();
return;
}
startWatching(stream);
}
// ---------- discovery ----------
/** Called for every snapshot: asks newly seen channel members whether they stream. */
export function onSnapshot() {
const snap = S.snap;
const present = new Set(snap.clients.map((c) => c.id));
let changed = directory.prune(present);
const peers = new Set(snap.clients.filter((c) => c.channel_id === snap.own_channel_id && !c.is_self && c.client_type !== 'query').map((c) => c.id));
if (knownOwnChannel !== snap.own_channel_id) {
knownOwnChannel = snap.own_channel_id;
scheduleList(null);
} else {
for (const id of peers) if (!knownChannelPeers.has(id)) scheduleList(id);
}
knownChannelPeers = peers;
if (session && !session.closed && current && !present.has(current.clientId)) {
session.terminate('streamer_left');
changed = true;
}
if (changed) hooks.onChange();
}
function scheduleList(clientId) {
if (clientId === null) listFull = true;
else listClients.add(clientId);
if (listTimer) return;
listTimer = setTimeout(runList, 300);
}
async function runList() {
listTimer = null;
if (!isConnected()) return;
const full = listFull;
const ids = Array.from(listClients);
listFull = false;
listClients.clear();
const requests = full ? [undefined] : ids.map((id) => ({ client_id: id }));
for (const args of requests) {
try {
const result = await call('stream_list', args);
let changed = false;
for (const r of result.results ?? []) {
// A client that is not streaming answers requeststreaminfo with an error only.
if (!r.ok && directory.byClient(r.client_id)) {
changed = directory.handle('notifystreamstopped', [{ clid: String(r.client_id) }]) || changed;
}
}
if (changed) hooks.onChange();
} catch (err) {
log('warn', `stream_list failed: ${err.code}`);
}
}
}
/** `stream` event from the core (bridge §5). */
export function onStreamEvent(evt) {
const name = evt.name;
const items = Array.isArray(evt.items) ? evt.items : [];
log('info', `stream event ${name} items=${items.length} keys=${items[0] ? Object.keys(items[0]).sort().join(',') : '-'}`);
if (session && !session.closed) {
for (const item of items) session.handle(name, item);
}
if (name === 'notifysfuaccessinfo' && !sfuToastShown) {
sfuToastShown = true;
toast(() => t('ui.the.server.routes.streams.through.an.sfu'), 'error');
}
if (directory.handle(name, items)) hooks.onChange();
}
export function onDisconnected() {
if (session && !session.closed) session.terminate('disconnected');
directory.clear();
knownChannelPeers = new Set();
knownOwnChannel = null;
sfuToastShown = false;
}
// ---------- viewing ----------
/** Core-backed signaling for a session (bridge §4.12–4.14). */
const coreTransport = {
join: (id, clid, msg) => call('stream_join', { stream_id: id, client_id: clid, message: msg }),
send: (id, clid, json) => call('stream_signal', { stream_id: id, client_id: clid, json }),
leave: (id, clid) => call('stream_leave', { stream_id: id, client_id: clid }),
};
/**
* Starts viewing `stream`. `transport` is the signaling path; production always uses the core.
* Every async continuation below checks that its session is still the current one.
*/
export function startWatching(stream, transport = coreTransport) {
stopWatching();
const streamer = clientById(stream.clientId);
current = { id: stream.id, clientId: stream.clientId, name: stream.name, nickname: streamer?.nickname ?? stream.nickname ?? '?' };
const sessionMedia = new MediaStream();
media = sessionMedia;
const video = $('#stream-video');
applyVolume();
lastCodecLogged = '';
Object.assign(watchStats, emptyStats());
watchStats.streamAdvertisesAudio = stream.fields?.audio === '1' ? true : stream.fields?.audio === '0' ? false : null;
$('#stream-view').hidden = false;
const streamTitle = { ...current };
setText($('#stream-title'), () => streamTitle.name ? `${streamTitle.nickname} — ${streamTitle.name}` : t('message.stream.from.p0', { p0: streamTitle.nickname }));
setText($('#stream-stats'), () => '');
const own = new StreamViewerSession({
streamId: stream.id,
clientId: stream.clientId,
ownClientId: S.snap?.own_client_id ?? 0,
message: S.profile?.nickname ?? '',
signal: transport,
createPeerConnection: (config) => new RTCPeerConnection(config),
iceServers: ICE_SERVERS,
onState: (state, detail) => {
if (session === own) onSessionState(state, detail);
},
onTrack: (track) => {
if (session !== own) return;
sessionMedia.addTrack(track);
if (track.kind === 'audio') watchStats.audioTrackPresent = true;
track.addEventListener('ended', () => sessionMedia.removeTrack(track));
// Both tracks of an offer arrive in one setRemoteDescription; attach the stream once after them.
// Later tracks are picked up by the element from the same MediaStream.
if (attachTimer === null && video.srcObject !== sessionMedia) {
attachTimer = setTimeout(() => {
attachTimer = null;
if (session !== own || own.closed || media !== sessionMedia) return;
video.srcObject = sessionMedia;
video.play().catch((err) => log('warn', `watch: play() rejected: ${err.name}`));
}, 0);
}
},
log,
});
session = own;
hooks.onChange();
own.start();
statsTimer = setInterval(pollStats, 1500);
}
export function stopWatching() {
if (session && !session.closed) session.stop();
session = null;
current = null;
teardownMedia();
$('#stream-view').hidden = true;
watchStats.state = 'idle';
hooks.onChange();
}
function teardownMedia() {
clearInterval(statsTimer);
statsTimer = null;
clearTimeout(attachTimer);
attachTimer = null;
const video = $('#stream-video');
video.srcObject = null;
if (media) for (const t of media.getTracks()) t.stop();
media = null;
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
}
const STATE_TEXT = {
get requesting() { return t('ui.request.sent.waiting.for.the.streamer'); },
get connecting() { return t('ui.connecting.to.the.streamer'); },
live: '',
get unstable() { return t('ui.the.stream.connection.was.interrupted.waiting.to'); },
get declined() { return t('ui.the.streamer.declined.your.request.to.watch'); },
get removed() { return t('ui.the.streamer.removed.you.from.the.viewers'); },
stopped: '',
};
function failureText(detail) {
switch (detail) {
case 'no_response': return t('ui.the.streamer.did.not.respond.within.90');
case 'ice_failed': return t('ui.could.not.connect.directly.to.the.streamer');
default: return t('message.stream.error.p0', { p0: detail });
}
}
function endedText(detail) {
switch (detail) {
case 'stream_stopped': return t('ui.the.stream.ended');
case 'streamer_left': return t('ui.the.streamer.left.the.server');
case 'disconnected': return t('ui.connection.to.the.server.was.lost');
default: return t('ui.the.stream.ended');
}
}
function onSessionState(state, detail) {
watchStats.state = state;
log('info', `watch: state ${state}${detail ? ` (${detail})` : ''}`);
if (state === 'stopped') return;
const text = () => {
if (state === 'failed') return failureText(detail);
if (state === 'ended') return endedText(detail);
if (state === 'unsupported') return t('ui.this.stream.uses.a.teamspeak.sfu.server');
if (state === 'declined' && detail) return `${STATE_TEXT.declined} ${detail}`;
if (state === 'live' && watchStats.framesDecoded === 0) return t('ui.connected.waiting.for.the.first.frame');
return STATE_TEXT[state] ?? '';
};
setText($('#stream-overlay'), text);
const terminal = ['declined', 'ended', 'removed', 'failed', 'unsupported'].includes(state);
setText($('#stream-stop'), () => terminal ? t('ui.close') : state === 'requesting' ? t('ui.cancel2') : t('ui.stop.watching'));
if (terminal) {
teardownMedia();
if (state !== 'ended' || detail !== 'disconnected') toast(text, state === 'ended' ? 'info' : 'error');
}
hooks.onChange();
}
async function pollStats() {
const own = session;
const pc = own?.pc;
if (!own || !pc || own.closed) return;
let report;
try {
report = await pc.getStats();
} catch {
return;
}
// The user may have stopped or switched streams while getStats() was pending.
if (session !== own || own.closed) return;
let inbound = null;
let audioIn = null;
let pair = null;
const codecs = new Map();
report.forEach((s) => {
if (s.type === 'inbound-rtp' && s.kind === 'video') inbound = s;
if (s.type === 'inbound-rtp' && s.kind === 'audio') audioIn = s;
if (s.type === 'candidate-pair' && s.nominated && s.state === 'succeeded') pair = s;
if (s.type === 'codec') codecs.set(s.id, s);
});
watchStats.remoteCandidatesAdded = own.remoteCandidatesAdded;
watchStats.staleCandidates = own.staleCandidates;
watchStats.candidateErrors = own.candidateErrors;
watchStats.offersApplied = own.offersApplied;
watchStats.answersSent = own.answersSent;
if (pair) {
const local = report.get(pair.localCandidateId);
const remote = report.get(pair.remoteCandidateId);
watchStats.pair = `${local?.candidateType ?? '?'}/${local?.protocol ?? '?'} → ${remote?.candidateType ?? '?'}`;
}
if (audioIn) {
const ac = codecs.get(audioIn.codecId);
watchStats.audioCodec = ac ? ac.mimeType : '';
watchStats.inboundAudioPackets = audioIn.packetsReceived ?? 0;
watchStats.inboundAudioBytes = audioIn.bytesReceived ?? 0;
}
if (!inbound) return;
watchStats.videoPackets = inbound.packetsReceived ?? 0;
watchStats.videoBytes = inbound.bytesReceived ?? 0;
watchStats.packetsLost = inbound.packetsLost ?? 0;
watchStats.keyFrames = inbound.keyFramesDecoded ?? 0;
const codec = codecs.get(inbound.codecId);
watchStats.codec = codec ? codec.mimeType.replace(/^video\//, '') : '';
watchStats.fmtp = codec?.sdpFmtpLine ?? '';
watchStats.width = inbound.frameWidth ?? 0;
watchStats.height = inbound.frameHeight ?? 0;
watchStats.fps = Math.round(inbound.framesPerSecond ?? 0);
const firstFrame = watchStats.framesDecoded === 0 && (inbound.framesDecoded ?? 0) > 0;
watchStats.framesDecoded = inbound.framesDecoded ?? 0;
watchStats.decoder = inbound.decoderImplementation ?? '';
watchStats.powerEfficientDecoder = typeof inbound.powerEfficientDecoder === 'boolean' ? inbound.powerEfficientDecoder : null;
if (firstFrame && own.state === 'live') setText($('#stream-overlay'), () => '');
const sig = `${watchStats.codec} ${watchStats.fmtp}`;
if (codec && sig !== lastCodecLogged) {
lastCodecLogged = sig;
log('info', `watch: negotiated ${codec.mimeType} fmtp="${codec.sdpFmtpLine ?? ''}" decoder=${watchStats.decoder}`);
}
updateStatsLine();
}
function updateStatsLine() {
if (!session) return;
const parts = [];
if (watchStats.codec) parts.push(watchStats.codec);
if (watchStats.width) parts.push(`${watchStats.width}×${watchStats.height}`);
if (watchStats.fps) parts.push(t('message.p0.fps', { p0: watchStats.fps }));
if (session.state === 'live') {
if (watchStats.streamAdvertisesAudio === false) parts.push(t('ui.streamer.is.not.sending.audio'));
else if (watchStats.inboundAudioPackets > 0) parts.push(t('ui.with.audio'));
}
setText($('#stream-stats'), () => parts.join(' · '));
}
export function applyVolume() {
const video = $('#stream-video');
const volume = $('#stream-volume');
const muted = $('#stream-mute').getAttribute('aria-pressed') === 'true';
video.volume = Number(volume.value) / 100;
video.muted = muted || S.audio.output_muted;
setText($('#stream-volume-value'), () => `${volume.value}%`);
setIcon($('#stream-mute').firstElementChild, muted ? 'speaker-off' : 'speaker');
$('#stream-mute').title = muted ? t('ui.unmute.stream') : t('ui.mute.stream');
}
let sinkChain = Promise.resolve();
/**
* Routes stream audio to the selected output device. Calls are serialized and only issued for a
* playing element whose current sink differs; a failure is reported with the device name and the
* element keeps playing on its current device.
*/
export function applySink() {
const video = $('#stream-video');
if (typeof video.setSinkId !== 'function' || !S.prefs) return;
sinkChain = sinkChain.then(async () => {
const own = session;
const target = S.prefs.outputDeviceId || '';
if (!own || !video.srcObject || video.sinkId === target) {
watchStats.sinkId = video.sinkId;
return;
}
try {
await video.setSinkId(target);
if (session !== own) return;
watchStats.sinkId = video.sinkId;
watchStats.sinkError = '';
log('info', `watch: audio output set (${target ? 'selected device' : 'system default'})`);
} catch (err) {
log('warn', `watch: setSinkId failed ${err.name}: ${err.message}`);
if (session !== own) return;
watchStats.sinkError = `${err.name}: ${err.message}`;
const label = Array.from($('#output-device').options).find((o) => o.value === target)?.textContent || t('ui.selected.device');
toast(() => t('message.could.not.route.stream.audio.to', { p0: label, p1: err.name }), 'error');
}
});
}
-456
View File
@@ -1,456 +0,0 @@
// TeamsPeach en message catalog. Keep keys and placeholders aligned across languages.
(function (root) {
'use strict';
const messages = Object.freeze({
"ui.starting.core": "Starting core…",
"ui.restarting.core": "Restarting core…",
"ui.core.unavailable": "Core unavailable",
"ui.restart.core": "Restart core",
"ui.import.backup": "Import backup…",
"ui.open.logs": "Open logs",
"ui.what.should.we.call.you": "What should we call you?",
"ui.everyone.on.the.server.sees.your.nickname": "Everyone on the server sees your nickname. You can change it later without changing your permanent identifier (UID).",
"ui.nickname": "Nickname",
"ui.3.30.characters": "3–30 characters.",
"ui.continue": "Continue",
"ui.teamspeach.will.create.a.cryptographic.identity.on": "TeamsPeach will create a cryptographic identity on this computer. No registration required.",
"ui.restore.from.backup": "Restore from backup…",
"ui.server": "Server",
"ui.not.connected": "Not connected",
"ui.not.connected2": "not connected",
"ui.connecting": "connecting…",
"ui.connected": "connected",
"ui.disconnecting": "disconnecting…",
"ui.saved.servers": "Saved servers",
"ui.disconnect.from.server": "Disconnect from server",
"ui.disconnect": "Disconnect",
"ui.save.current.server": "Save current server",
"ui.no.saved.servers.enter.an.address.in": "No saved servers. Enter an address in the connection form and select Save.",
"ui.channels.will.appear.after.you.connect.to": "Channels will appear after you connect to a server.",
"ui.channels.and.members": "Channels and members",
"ui.settings.categories": "Settings categories",
"ui.back.to.server": "Back to server",
"ui.settings": "Settings",
"ui.user": "User",
"ui.identity": "Identity",
"ui.servers": "Servers",
"ui.application": "Application",
"ui.appearance": "Appearance",
"ui.audio": "Audio",
"ui.video": "Video",
"ui.keyboard": "Keyboard",
"ui.information": "Information",
"ui.microphone": "Microphone",
"ui.mute.microphone": "Mute microphone",
"ui.mute.audio": "Mute audio",
"ui.connect.to.a.server": "Connect to a server",
"ui.server.address": "Server address",
"ui.address.or.address.9987": "address or address:9987",
"ui.server.password": "Server password",
"ui.optional": "optional",
"ui.connect": "Connect",
"ui.save": "Save",
"ui.hold.to.talk": "Hold to talk",
"ui.stream": "Stream",
"ui.stream.audio": "Stream audio",
"ui.mute.stream": "Mute stream",
"ui.stream.volume": "Stream volume",
"ui.full.screen": "Full screen",
"ui.stop.watching": "Stop watching",
"ui.chat": "Chat",
"ui.chats": "Chats",
"ui.message": "Message",
"ui.send": "Send",
"ui.send.enter": "Send (Enter)",
"ui.unique.identifier": "Unique identifier",
"ui.copy": "Copy",
"ui.your.uid.is.your.public.key.fingerprint": "Your UID is your public key fingerprint. TeamSpeak servers use it to recognize you and assign permissions; changing your nickname does not change it.",
"ui.export.to.file": "Export to file…",
"ui.import.from.file": "Import from file…",
"ui.the.file.contains.your.private.key.protect": "The file contains your private key. Protect it like a password: anyone with it can impersonate you.",
"ui.details": "Details",
"ui.nickname2": "Nickname",
"ui.other.users.on.the.teamspeak.server.see": "Other users on the TeamSpeak server see your nickname. 3–30 characters.",
"ui.no.saved.servers": "No saved servers.",
"ui.add.server": "Add server",
"ui.name": "Name",
"ui.address": "Address",
"ui.add": "Add",
"ui.only.the.name.and.address.are.saved": "Only the name and address are saved. Server passwords are not stored; you will be asked when connecting. The same identity is used for every server.",
"ui.theme": "Theme",
"ui.color.theme": "Color theme",
"ui.system": "System",
"ui.dark": "Dark",
"ui.light": "Light",
"ui.devices": "Devices",
"ui.test.microphone": "Test microphone",
"ui.output.device": "Output device",
"ui.volume": "Volume",
"ui.voice.volume": "Voice volume",
"ui.microphone.processing": "Microphone processing",
"ui.noise.suppression": "Noise suppression",
"ui.echo.cancellation": "Echo cancellation",
"ui.automatic.gain.control": "Automatic gain control",
"ui.hardware.acceleration": "Hardware acceleration",
"ui.allow.hardware.video.decoding": "Allow hardware video decoding",
"ui.the.engine.may.use.your.gpu.to": "The engine may use your GPU to decode streams. Applies after restarting.",
"ui.this.change.takes.effect.after.restarting.teamspeach": "This change takes effect after restarting TeamsPeach.",
"ui.restart.now": "Restart now",
"ui.decoding.backend": "Decoding backend",
"ui.automatic.chosen.by.chromium": "Automatic (chosen by Chromium)",
"ui.details.status.codecs.and.backends": "Details: status, codecs and backends",
"ui.policy": "Policy",
"ui.current.reception": "Current reception",
"ui.receive.codecs.reported.by.the.engine": "Receive codecs reported by the engine",
"ui.unavailable.settings": "Unavailable settings",
"ui.unlike.teamspeak.6.there.is.no.cisco": "Unlike TeamSpeak 6, there is no Cisco OpenH264 toggle or manual hardware backend selection (NVENC, AMF, QSV, etc.). TeamsPeach receives video through Chromium WebRTC, which has no decoder-selection API. Chromium decodes H.264 through FFmpeg; OpenH264 is only an encoder, and sending your own screen is not implemented in TeamsPeach.",
"ui.voice.transmission": "Voice transmission",
"ui.transmission.mode": "Transmission mode",
"ui.push.to.talk": "Push to talk",
"ui.open.microphone": "Open microphone",
"ui.push.to.talk.key": "Push-to-talk key",
"ui.assign": "Assign",
"ui.the.key.works.while.teamspeach.is.focused": "The key works while TeamsPeach is focused. Letter keys do not trigger while typing. Press Esc to cancel assignment.",
"ui.about": "About",
"ui.updates": "Updates",
"ui.update.channel": "Update channel",
"ui.preview.releases": "Preview releases",
"ui.stable.only": "Stable only",
"ui.installing.closes.teamspeach.and.interrupts.your.current": "Installing closes TeamsPeach and interrupts your current call and stream.",
"ui.interrupt.and.install": "Interrupt and install",
"ui.cancel": "Cancel",
"ui.check.for.updates": "Check for updates",
"ui.download": "Download",
"ui.install.and.restart": "Install and restart",
"ui.open.release.page": "Open release page",
"ui.server.banner": "Server banner",
"ui.error": "error",
"ui.teamspeach.core.not.found": "TeamsPeach core not found",
"ui.the.core.executable.is.missing.build.it": "The core executable is missing. Build it (see README) or reinstall the app. Searched paths:",
"ui.the.core.stopped": "The core stopped",
"ui.profile.corrupted": "Profile corrupted",
"ui.could.not.read.profile": "Could not read profile",
"ui.nickname.must.contain.3.30.characters": "Nickname must contain 3–30 characters.",
"ui.creating.identity": "Creating identity…",
"ui.connecting2": "Connecting…",
"ui.unmute.microphone": "Unmute microphone",
"ui.microphone.muted": "Microphone muted",
"ui.microphone.unmuted": "Microphone unmuted",
"ui.unmute.audio": "Unmute audio",
"ui.mute.audio.and.microphone": "Mute audio (and microphone)",
"ui.audio.muted": "Audio muted",
"ui.audio.unmuted": "Audio unmuted",
"ui.audio.is.muted.you.cannot.hear.others": "Audio is muted: you cannot hear others or transmit voice.",
"ui.microphone.is.muted": "Microphone is muted.",
"ui.enter.a.server.address": "Enter a server address.",
"ui.could.not.disconnect.from.the.current.server": "Could not disconnect from the current server",
"ui.disconnected.from.server": "Disconnected from server",
"ui.connection.lost.reconnecting": "Connection lost, reconnecting…",
"ui.interface.startup.failed": "Interface startup failed",
"ui.channel": "Channel",
"ui.this.person.left.the.server": "This person left the server",
"ui.message.exceeds.8.kib": "Message exceeds 8 KiB",
"ui.close.private.chat": "Close private chat",
"ui.current.channel.chat": "Current channel chat",
"ui.server.wide.chat": "Server-wide chat",
"ui.everyone.in.this.channel.can.see.its": "Everyone in this channel can see its messages.",
"ui.everyone.connected.to.the.server.can.see": "Everyone connected to the server can see server messages.",
"ui.private.conversation.only.the.recipient.can.see": "Private conversation. Only the recipient can see your messages.",
"ui.message.the.whole.server": "Message the whole server",
"ui.loading.devices": "Loading devices…",
"ui.audio.settings": "Audio settings…",
"ui.the.engine.hid.the.device.list.only": "The engine hid the device list: only the system device is available.",
"ui.no.microphones.found": "No microphones found.",
"ui.no.output.devices.found": "No output devices found.",
"ui.enter.a.server.address.to.save.it": "Enter a server address to save it.",
"ui.enter.an.address": "Enter an address.",
"ui.server.added": "Server added.",
"ui.this.address.is.already.saved": "This address is already saved",
"ui.you.can.save.up.to.50.servers": "You can save up to 50 servers",
"ui.connected2": "Connected",
"ui.switch": "Switch",
"ui.you.are.connected.to.this.server": "You are connected to this server",
"ui.disconnect.from.the.current.server.and.connect": "Disconnect from the current server and connect to this one",
"ui.edit": "Edit",
"ui.confirm.deletion": "Confirm deletion?",
"ui.delete": "Delete",
"ui.server.name": "Server name",
"ui.name.and.address.cannot.be.empty": "Name and address cannot be empty",
"ui.this.address.is.already.saved.under.another": "This address is already saved under another name",
"ui.this.is.already.your.nickname": "This is already your nickname.",
"ui.saving": "Saving…",
"ui.and.applied.on.the.server": " and applied on the server",
"ui.saved": "Saved.",
"ui.the.server.nickname.was.restored": "; the server nickname was restored",
"ui.uid.copied": "UID copied",
"ui.disconnect.from.the.server.first": "Disconnect from the server first.",
"ui.press.a.key": "press a key…",
"ui.stop.test": "Stop test",
"ui.available.after.disconnecting.from.the.server": "Available after disconnecting from the server",
"ui.core": "Core",
"ui.not.running": "not running",
"ui.platform": "Platform",
"ui.core.executable": "Core executable",
"ui.data.folder": "Data folder",
"ui.receive.capabilities.unavailable": "Receive capabilities unavailable",
"ui.hardware.decoding.is.allowed.and.available.to": "hardware decoding is allowed and available to the engine",
"ui.hardware.decoding.is.force.enabled": "hardware decoding is force-enabled",
"ui.hardware.decoding.is.disabled.the.engine.will": "hardware decoding is disabled; the engine will use software decoding",
"ui.hardware.decoding.is.disabled": "hardware decoding is disabled",
"ui.hardware.decoding.is.unavailable.on.this.device": "hardware decoding is unavailable on this device; software decoding will be used",
"ui.hardware.decoding.is.unavailable": "hardware decoding is unavailable",
"ui.unknown": "unknown",
"ui.allowed": "allowed",
"ui.disabled.disable.accelerated.video.decode.flag": "disabled (disable-accelerated-video-decode flag)",
"ui.power.efficient": " (power-efficient)",
"ui.not.power.efficient": " (not power-efficient)",
"ui.current.stream": "Current stream",
"ui.last.stream": "Last stream",
"ui.the.actual.decoder.is.reported.only.while": "The actual decoder is reported only while watching a stream.",
"ui.dismiss.notification": "Dismiss notification",
"ui.closed": "closed",
"ui.password.protected": "password protected",
"ui.you.are.here": "you are here",
"ui.you.are.in.this.channel": "You are in this channel",
"ui.join.channel": "Join channel",
"ui.channel.password": "Channel password",
"ui.join": "Join",
"ui.you": "you",
"ui.audio.muted2": "audio muted",
"ui.microphone.muted2": "microphone muted",
"ui.no.microphone": "No microphone",
"ui.no.microphone2": "no microphone",
"ui.away": "Away",
"ui.away2": "away",
"ui.recording.the.conversation": "Recording the conversation",
"ui.recording": "recording",
"ui.talking": "talking",
"ui.you2": " (you)",
"ui.open.profile.settings": ". Open profile settings",
"ui.send.a.private.message": ". Send a private message",
"ui.profile.settings": "Profile settings",
"ui.send.a.private.message2": "Send a private message",
"ui.watch": "Watch",
"ui.watching": "Watching",
"ui.screen.share": "Screen share",
"ui.the.engine.hid.the.device.list.audio": "The engine hid the device list (audio device permission is unavailable). Only the system default device is available.",
"ui.no.audio.devices.found": "No audio devices found.",
"ui.talk.now": "Talk now…",
"ui.the.server.routes.streams.through.an.sfu": "The server routes streams through an SFU. TeamsPeach supports only direct (P2P) TeamSpeak 6 streams.",
"ui.request.sent.waiting.for.the.streamer": "Request sent. Waiting for the streamer…",
"ui.connecting.to.the.streamer": "Connecting to the streamer…",
"ui.the.stream.connection.was.interrupted.waiting.to": "The stream connection was interrupted. Waiting to reconnect…",
"ui.the.streamer.declined.your.request.to.watch": "The streamer declined your request to watch.",
"ui.the.streamer.removed.you.from.the.viewers": "The streamer removed you from the viewers.",
"ui.the.streamer.did.not.respond.within.90": "The streamer did not respond within 90 seconds.",
"ui.could.not.connect.directly.to.the.streamer": "Could not connect directly to the streamer. Watching requires direct network access to their computer (via STUN, without TURN).",
"ui.the.stream.ended": "The stream ended.",
"ui.the.streamer.left.the.server": "The streamer left the server.",
"ui.connection.to.the.server.was.lost": "Connection to the server was lost.",
"ui.this.stream.uses.a.teamspeak.sfu.server": "This stream uses a TeamSpeak SFU server. TeamsPeach supports only direct (P2P) streams.",
"ui.connected.waiting.for.the.first.frame": "Connected. Waiting for the first frame…",
"ui.close": "Close",
"ui.cancel2": "Cancel",
"ui.streamer.is.not.sending.audio": "streamer is not sending audio",
"ui.with.audio": "with audio",
"ui.unmute.stream": "Unmute stream",
"ui.selected.device": "selected device",
"ui.system.default.device": "System default device",
"ui.previously.selected.device.currently.unavailable": "Previously selected device (currently unavailable)",
"ui.output.device.selection.is.not.supported": "Output device selection is not supported",
"ui.selected.microphone.unavailable.using.the.default.microphone": "Selected microphone unavailable; using the default microphone",
"ui.microphone.disconnected": "Microphone disconnected",
"ui.invalid.request": "Invalid request",
"ui.command.not.supported": "Command not supported",
"ui.profile.not.created.yet": "Profile not created yet",
"ui.profile.already.exists": "Profile already exists",
"ui.the.identity.file.is.corrupted.restore.a": "The identity file is corrupted. Restore a backup in Settings → Identity → Import.",
"ui.profile.file.corrupted": "Profile file corrupted",
"ui.nickname.must.contain.3.30.characters.with": "Nickname must contain 3–30 characters with no control characters",
"ui.set.a.nickname.first": "Set a nickname first",
"ui.not.connected.to.a.server": "Not connected to a server",
"ui.already.connected": "Already connected",
"ui.could.not.connect": "Could not connect",
"ui.the.server.rejected.the.action": "The server rejected the action",
"ui.microphone.queue.overflow.some.audio.was.dropped": "Microphone queue overflow; some audio was dropped",
"ui.microphone.or.audio.is.muted.voice.is": "Microphone or audio is muted; voice is not transmitted",
"ui.opus.codec.error": "Opus codec error",
"ui.this.channel.uses.a.legacy.codec.speex": "This channel uses a legacy codec (Speex/CELT); voice transmission is unavailable",
"ui.the.server.accepted.the.nickname.but.saving": "The server accepted the nickname, but saving it to disk failed",
"ui.could.not.access.the.data.folder": "Could not access the data folder",
"ui.internal.core.error": "Internal core error",
"ui.the.core.did.not.respond.in.time": "The core did not respond in time",
"ui.the.core.is.not.running": "The core is not running",
"ui.the.core.stopped2": "The core stopped",
"ui.core.executable.not.found": "Core executable not found",
"ui.disconnect.from.the.server.first2": "Disconnect from the server first",
"ui.action.forbidden": "Action forbidden",
"ui.no.error.details.were.provided": "No error details were provided",
"ui.error2": "Error",
"ui.space": "Space",
"ui.left.ctrl": "Left Ctrl",
"ui.right.ctrl": "Right Ctrl",
"ui.left.alt": "Left Alt",
"ui.right.alt": "Right Alt",
"ui.left.shift": "Left Shift",
"ui.right.shift": "Right Shift",
"ui.left.super": "Left Super",
"ui.right.super": "Right Super",
"ui.not.assigned": "not assigned",
"message.server.banner.p0": "Server banner ({p0})",
"message.setting.not.saved.p0": "Setting not saved: {p0}",
"message.exit.code.p0": "Exit code {p0}",
"message.p0.teamspeach.never.replaces.a.corrupted": "{p0} TeamsPeach never replaces a corrupted identity with a new one.",
"message.an.identity.already.exists.uid.p0": "An identity already exists (UID {p0}). Choose a nickname to continue.",
"message.profile.created.your.uid.p0": "Profile created. Your UID: {p0}",
"message.you.will.join.as.p0.uid": "You will join as {p0} · UID {p1}",
"message.this.channel.uses.a.legacy.codec": "This channel uses a legacy codec ({p0}). TeamsPeach only sends and receives Opus; voice is unavailable here.",
"message.p0.enter.the.server.password.and": "{p0}. Enter the server password and reconnect.",
"message.disconnect.p0": "Disconnect: {p0}",
"message.disconnected.p0": "Disconnected: {p0}",
"message.connected.to.p0.p1": "Connected to “{p0}”{p1}",
"message.you.are.in.channel.p0": "You are in channel “{p0}”",
"message.identity.restored.uid.p0": "Identity restored. UID {p0}",
"message.restore.failed.p0": "Restore failed: {p0}",
"message.import.failed.p0": "Import failed: {p0}",
"message.p0.left": "{p0} (left)",
"message.message.not.sent.p0": "Message not sent: {p0}",
"message.private.messages.p0": "Private messages: {p0}",
"message.unread.p0": ", unread: {p0}",
"message.message.p0": "Message {p0}",
"message.message.in.p0": "Message in “{p0}”",
"message.server.p0.saved": "Server “{p0}” saved",
"message.server.p0.deleted": "Server “{p0}” deleted",
"message.saved.p0.uid.unchanged": "Saved{p0}. UID unchanged.",
"message.the.server.showed.p0.but.p1": "The server showed “{p0}”, but “{p1}” remains on disk{p2}.",
"message.saved.to.p0.uid.p1": "Saved to “{p0}”. UID {p1}.",
"message.export.failed.p0": "Export failed: {p0}",
"message.identity.imported.uid.p0": "Identity imported. UID {p0}",
"message.identity.security.level.p0": "Identity security level: {p0}",
"message.this.run.p0.chromium.engine.p1": "This run: {p0}. Chromium engine: {p1}.",
"message.p0.p1.decoder.p2.p3": "{p0}: {p1}, decoder “{p2}”{p3}.",
"message.missing.permission.p0": ", missing permission {p0}",
"message.could.not.join.p0.p1": "Could not join “{p0}”: {p1}",
"message.password.for.channel.p0": "Password for channel {p0}",
"message.could.not.enter.p0.p1": "Could not enter “{p0}”: {p1}",
"message.away.p0": "Away: {p0}",
"message.away.p02": "away: {p0}",
"message.country.p0": "Country: {p0}",
"message.groups.p0": ", groups: {p0}",
"message.description.p0": "Description: {p0}",
"message.groups.p02": "Groups: {p0}",
"message.p0.p1.p2": "{p0}: {p1}{p2}",
"message.output.device.unavailable.p0": "Output device unavailable: {p0}",
"message.audio.unavailable.p0": "Audio unavailable: {p0}",
"message.microphone.access.unavailable.p0": "Microphone access unavailable: {p0}",
"message.could.not.select.output.device.p0": "Could not select output device: {p0}",
"message.could.not.list.devices.p0.p1": "Could not list devices: {p0}: {p1}",
"message.no.microphones.found.output.devices.p0": "No microphones found. Output devices: {p0}.",
"message.microphones.p0.no.output.devices.found": "Microphones: {p0}. No output devices found.",
"message.microphones.found.p0.output.devices.p1": "Microphones found: {p0}; output devices: {p1}.",
"message.window.unfocused.p0.will.not.work": "Window unfocused — {p0} will not work",
"message.key.p0": "Key: {p0}",
"message.full.screen.unavailable.p0": "Full screen unavailable: {p0}",
"message.stream.from.p0": "Stream from {p0}",
"message.stream.error.p0": "Stream error: {p0}",
"message.p0.fps": "{p0} fps",
"message.could.not.route.stream.audio.to": "Could not route stream audio to “{p0}” ({p1}). It continues playing through the current device; choose another in Settings → Audio.",
"message.system.default.p0": "System default ({p0})",
"message.unnamed.device.p0": "Unnamed device ({p0})",
"native.identityExport.title": "Export TeamsPeach identity",
"native.identity.filter": "TeamSpeak identity",
"native.allFiles": "All files",
"native.identityImport.title": "Import identity",
"native.identityReplace.title": "Replace identity?",
"native.identityReplace.message": "Importing replaces the current identity.",
"native.identityReplace.detail": "The current UID is lost unless you have a backup of it. Server permissions and groups are bound to the UID.",
"native.identityReplace.cancel": "Cancel",
"native.identityReplace.confirm": "Choose file and replace",
"native.error.connected": "Disconnect from the server first",
"native.error.coreMissing": "Core executable not found",
"native.error.coreNoResult": "The core returned no result",
"native.error.unknown": "Unknown error",
"native.error.coreUnavailable": "The core is not running",
"native.error.mediaNotAnnounced": "The server did not announce this address",
"native.error.mediaTooLarge": "Image larger than 4 MiB",
"native.error.mediaUnsupported": "Not an image",
"native.error.mediaTimeout": "Download timed out",
"core.status.readyTimeout": "The core did not respond within 15 seconds",
"core.status.protocol": "Unsupported core protocol version: {protocol}",
"core.error.exited": "The core has stopped",
"core.error.requestTooLarge": "Request too large",
"core.error.timeout": "The core did not answer “{cmd}” within {seconds} s",
"core.error.emptyError": "Empty error response",
"core.exit.0": "The core has stopped",
"core.exit.2": "The core rejected its start arguments",
"core.exit.3": "The profile is in use by another TeamsPeach instance or the data folder is unavailable",
"core.exit.1": "Internal core error (details in core.log)",
"core.exit.other": "The core exited with code {code}",
"update.ui.title": "Updates",
"update.ui.channel.label": "Update channel",
"update.ui.channel.preview": "Preview releases",
"update.ui.channel.stable": "Stable only",
"update.ui.confirm.text": "Installing closes TeamsPeach: the current call and stream viewing will be interrupted.",
"update.ui.confirm.yes": "Interrupt and install",
"update.ui.confirm.no": "Cancel",
"update.ui.check": "Check for updates",
"update.ui.retry": "Retry",
"update.ui.download": "Download",
"update.ui.downloadNow": "Download now",
"update.ui.install": "Install and restart",
"update.ui.openRelease": "Open release page",
"update.ui.status.disabled": "Automatic updates are unavailable: {reason}.",
"update.ui.status.idle": "Not checked yet.",
"update.ui.status.checking": "Checking for updates…",
"update.ui.status.upToDate": "You have the latest version.",
"update.ui.status.upToDateChecked": "You have the latest version (checked {time}).",
"update.ui.status.newerPreview": "Preview version {version} is available in the “Preview releases” channel.",
"update.ui.status.available": "Version {version} is available.",
"update.ui.status.availablePreview": "Preview version {version} is available.",
"update.ui.status.manual": "This build is updated manually: download the archive from the release page and replace the files.",
"update.ui.status.deferred": "Version {version} found. The download starts after the call ends.",
"update.ui.status.downloading": "Downloading version {version}: {percent}%.",
"update.ui.status.downloaded": "Version {version} is downloaded and verified. Installing restarts TeamsPeach.",
"update.ui.status.installing": "Installing the update, TeamsPeach will restart…",
"update.ui.status.error": "Update failed: {message}",
"update.ui.status.skipped": "Version {version} skipped: {reason}.",
"update.ui.toast.available": "TeamsPeach {version} is available — Settings → Information.",
"update.ui.installFailed": "Could not install the update",
"language.label": "Language",
"language.note": "Changes apply immediately. Your identity, connection and audio are unchanged.",
"members.count": {
"one": "{count} member",
"other": "{count} members"
},
"error.detail": "Error ({code}): {detail}",
"error.device_unavailable": "The selected microphone is not available. Choose another device in Settings → Audio or by right-clicking the microphone button.",
"error.device_lost": "The microphone was disconnected. Choose an available device in Settings → Audio.",
"update.disabled.dev-build": "This development build does not install updates",
"update.disabled.unsupported-platform": "Updates are not supported on {platform} {arch}",
"update.error.network": "Network request failed: {detail}",
"update.error.timeout": "The request timed out after {seconds} seconds",
"update.error.http": "Update server returned HTTP {status}",
"update.error.bad-response": "Invalid update response: {detail}",
"update.error.incomplete-list": "Incomplete release list: received {fetched} of {total}",
"update.error.incomplete-release": "Release {tag} is incomplete. File: {file}. {detail}",
"update.error.checksum": "Release {tag} failed integrity verification: {detail}",
"update.error.download": "Could not download release {tag}: {detail}",
"update.error.install": "Could not install release {tag}: {detail}",
"update.error.bad-version": "Invalid release version: {version}",
"update.skip.no-feed": "No update feed {file} for {target}",
"update.skip.no-package": "No installation package {file} for {target}",
"update.skip.feed-mismatch": "Update feed does not match release {tag}: {detail}",
"update.skip.incomplete-release": "Release {tag} is incomplete. File: {file}. {detail}",
"update.install.session-active": "End the current call or confirm interrupting it to install.",
"update.install.not-ready": "No verified update is ready to install.",
"update.install.custom-profile": "Automatic install is off for a custom profile: the installer would restart TeamsPeach on the default profile. Install the update manually from the release page.",
"update.manual.custom-profile": "Automatic install is off for a custom profile: the installer would restart TeamsPeach on the default profile. Install the update manually from the release page.",
"update.install.install-failed": "Could not install release {tag}: {detail}",
"language.russian": "Russian",
"update.channel.hint": "Preview includes prereleases; Stable excludes them.",
"error.capture": "Microphone processing failed."
});
if (typeof module === 'object' && module.exports) module.exports = messages;
root.TeamsPeachCatalogs = root.TeamsPeachCatalogs || {};
root.TeamsPeachCatalogs.en = messages;
})(globalThis);
-26
View File
@@ -1,26 +0,0 @@
// Shared browser/CommonJS translator. Language is explicit, never inferred from the OS.
(function (root) {
'use strict';
const catalogs = typeof module === 'object' && module.exports
? { en: require('./en.js'), ru: require('./ru.js') }
: root.TeamsPeachCatalogs;
const languages = Object.freeze(['en', 'ru']);
const normalizeLanguage = (language) => languages.includes(language) ? language : 'en';
const plurals = { en: new Intl.PluralRules('en'), ru: new Intl.PluralRules('ru') };
const numbers = { en: new Intl.NumberFormat('en'), ru: new Intl.NumberFormat('ru') };
function t(key, params = {}, language = 'en') {
const locale = normalizeLanguage(language);
if (!Object.hasOwn(catalogs[locale], key)) throw new Error(`Missing translation key: ${key}`);
let message = catalogs[locale][key];
if (typeof message === 'object') message = message[plurals[locale].select(Number(params.count))] ?? message.other;
return message.replace(/\{([A-Za-z][A-Za-z0-9]*)\}/g, (_, name) => {
const value = params[name];
// Optional technical fields may be null, but missing required parameters are a programming error.
if (!Object.hasOwn(params, name)) throw new Error(`Missing translation parameter ${name} for ${key}`);
return value == null ? '' : typeof value === 'number' ? numbers[locale].format(value) : String(value);
});
}
const api = Object.freeze({ t, normalizeLanguage, languages, catalogs });
if (typeof module === 'object' && module.exports) module.exports = api;
root.TeamsPeachI18n = api;
})(globalThis);
-458
View File
@@ -1,458 +0,0 @@
// TeamsPeach ru message catalog. Keep keys and placeholders aligned across languages.
(function (root) {
'use strict';
const messages = Object.freeze({
"ui.starting.core": "Запуск ядра…",
"ui.restarting.core": "Перезапуск ядра…",
"ui.core.unavailable": "Ядро недоступно",
"ui.restart.core": "Перезапустить ядро",
"ui.import.backup": "Импортировать резервную копию…",
"ui.open.logs": "Открыть журналы",
"ui.what.should.we.call.you": "Как вас называть?",
"ui.everyone.on.the.server.sees.your.nickname": "Никнейм видят все на сервере. Его можно сменить позже — ваш постоянный идентификатор (UID) при этом не меняется.",
"ui.nickname": "Никнейм",
"ui.3.30.characters": "От 3 до 30 символов.",
"ui.continue": "Продолжить",
"ui.teamspeach.will.create.a.cryptographic.identity.on": "TeamsPeach создаст на этом компьютере криптографическую идентичность. Регистрация не нужна.",
"ui.restore.from.backup": "Восстановить из резервной копии…",
"ui.server": "Сервер",
"ui.not.connected": "Нет подключения",
"ui.not.connected2": "не подключено",
"ui.connecting": "подключение…",
"ui.connected": "подключено",
"ui.disconnecting": "отключение…",
"ui.saved.servers": "Сохранённые серверы",
"ui.disconnect.from.server": "Отключиться от сервера",
"ui.disconnect": "Отключиться",
"ui.save.current.server": "Сохранить текущий",
"ui.no.saved.servers.enter.an.address.in": "Сохранённых серверов нет. Введите адрес в форме подключения и нажмите «Сохранить».",
"ui.channels.will.appear.after.you.connect.to": "Каналы появятся после подключения к серверу.",
"ui.channels.and.members": "Каналы и участники",
"ui.settings.categories": "Разделы настроек",
"ui.back.to.server": "Назад к серверу",
"ui.settings": "Настройки",
"ui.user": "Пользователь",
"ui.identity": "Идентичность",
"ui.servers": "Серверы",
"ui.application": "Приложение",
"ui.appearance": "Внешний вид",
"ui.audio": "Звук",
"ui.video": "Видео",
"ui.keyboard": "Клавиши",
"ui.information": "Информация",
"ui.microphone": "Микрофон",
"ui.mute.microphone": "Выключить микрофон",
"ui.mute.audio": "Выключить звук",
"ui.connect.to.a.server": "Подключение к серверу",
"ui.server.address": "Адрес сервера",
"ui.address.or.address.9987": "адрес или адрес:9987",
"ui.server.password": "Пароль сервера",
"ui.optional": "необязательно",
"ui.connect": "Подключиться",
"ui.save": "Сохранить",
"ui.hold.to.talk": "Удерживайте, чтобы говорить",
"ui.stream": "Трансляция",
"ui.stream.audio": "Звук трансляции",
"ui.mute.stream": "Выключить звук трансляции",
"ui.stream.volume": "Громкость трансляции",
"ui.full.screen": "Во весь экран",
"ui.stop.watching": "Прекратить просмотр",
"ui.chat": "Чат",
"ui.chats": "Чаты",
"ui.message": "Сообщение",
"ui.send": "Отправить",
"ui.send.enter": "Отправить (Enter)",
"ui.unique.identifier": "Уникальный идентификатор",
"ui.copy": "Копировать",
"ui.your.uid.is.your.public.key.fingerprint": "UID — отпечаток вашего открытого ключа. Серверы TeamSpeak по нему узнают вас и выдают права; смена ника его не меняет.",
"ui.export.to.file": "Экспортировать в файл…",
"ui.import.from.file": "Импортировать из файла…",
"ui.the.file.contains.your.private.key.protect": "Файл содержит закрытый ключ. Храните его как пароль: тот, у кого он есть, может выдавать себя за вас.",
"ui.details": "Подробнее",
"ui.nickname2": "Ник",
"ui.other.users.on.the.teamspeak.server.see": "Ваш ник видят другие пользователи на сервере TeamSpeak. От 3 до 30 символов.",
"ui.no.saved.servers": "Сохранённых серверов нет.",
"ui.add.server": "Добавить сервер",
"ui.name": "Название",
"ui.address": "Адрес",
"ui.add": "Добавить",
"ui.only.the.name.and.address.are.saved": "Сохраняются только название и адрес. Пароль сервера не сохраняется — его спросят при подключении. Для всех серверов используется одна и та же ваша идентичность.",
"ui.theme": "Тема",
"ui.color.theme": "Тема оформления",
"ui.system": "Как в системе",
"ui.dark": "Тёмная",
"ui.light": "Светлая",
"ui.devices": "Устройства",
"ui.test.microphone": "Проверить микрофон",
"ui.output.device": "Устройство вывода",
"ui.volume": "Громкость",
"ui.voice.volume": "Громкость голосов",
"ui.microphone.processing": "Обработка микрофона",
"ui.noise.suppression": "Шумоподавление",
"ui.echo.cancellation": "Эхоподавление",
"ui.automatic.gain.control": "Автоматическая громкость",
"ui.hardware.acceleration": "Аппаратное ускорение",
"ui.allow.hardware.video.decoding": "Разрешить аппаратное декодирование видео",
"ui.the.engine.may.use.your.gpu.to": "Движок может использовать видеокарту для декодирования трансляций. Применяется после перезапуска.",
"ui.this.change.takes.effect.after.restarting.teamspeach": "Изменение вступит в силу после перезапуска TeamsPeach.",
"ui.restart.now": "Перезапустить сейчас",
"ui.decoding.backend": "Бэкенд декодирования",
"ui.automatic.chosen.by.chromium": "Автоматически (выбирает Chromium)",
"ui.details.status.codecs.and.backends": "Подробности: состояние, кодеки и бэкенды",
"ui.policy": "Политика",
"ui.current.reception": "Текущий приём",
"ui.receive.codecs.reported.by.the.engine": "Кодеки приёма, объявленные движком",
"ui.unavailable.settings": "Недоступные настройки",
"ui.unlike.teamspeak.6.there.is.no.cisco": "Переключателя Cisco OpenH264 и ручного выбора аппаратных бэкендов (NVENC, AMF, QSV и др.), как в TeamSpeak 6, здесь нет: TeamsPeach принимает видео через WebRTC движка Chromium, у которого нет API выбора декодера. H.264 Chromium декодирует через FFmpeg — OpenH264 в нём служит только кодировщиком, а кодирование (отправка своего экрана) в TeamsPeach не реализовано.",
"ui.voice.transmission": "Передача голоса",
"ui.transmission.mode": "Режим передачи",
"ui.push.to.talk": "Нажми и говори",
"ui.open.microphone": "Открытый микрофон",
"ui.push.to.talk.key": "Клавиша «нажми и говори»",
"ui.assign": "Назначить",
"ui.the.key.works.while.teamspeach.is.focused": "Клавиша работает, пока окно TeamsPeach активно. Буквенные клавиши не срабатывают во время набора текста. Esc отменяет назначение.",
"ui.about": "О программе",
"ui.updates": "Обновления",
"ui.update.channel": "Канал обновлений",
"ui.preview.releases": "Предварительные версии (preview)",
"ui.stable.only": "Только стабильные",
"ui.installing.closes.teamspeach.and.interrupts.your.current": "Установка закроет TeamsPeach: текущий разговор и просмотр трансляции прервутся.",
"ui.interrupt.and.install": "Прервать и установить",
"ui.cancel": "Отмена",
"ui.check.for.updates": "Проверить обновления",
"ui.download": "Скачать",
"ui.install.and.restart": "Установить и перезапустить",
"ui.open.release.page": "Открыть страницу релиза",
"ui.server.banner": "Баннер сервера",
"ui.error": "ошибка",
"ui.teamspeach.core.not.found": "Ядро TeamsPeach не найдено",
"ui.the.core.executable.is.missing.build.it": "Исполняемый файл ядра отсутствует. Соберите его (см. README) или переустановите приложение. Проверенные пути:",
"ui.the.core.stopped": "Ядро остановилось",
"ui.profile.corrupted": "Профиль повреждён",
"ui.could.not.read.profile": "Не удалось прочитать профиль",
"ui.nickname.must.contain.3.30.characters": "Никнейм должен содержать от 3 до 30 символов.",
"ui.creating.identity": "Создаём идентичность…",
"ui.connecting2": "Подключение…",
"ui.unmute.microphone": "Включить микрофон",
"ui.microphone.muted": "Микрофон выключен",
"ui.microphone.unmuted": "Микрофон включён",
"ui.unmute.audio": "Включить звук",
"ui.mute.audio.and.microphone": "Выключить звук (и микрофон)",
"ui.audio.muted": "Звук выключен",
"ui.audio.unmuted": "Звук включён",
"ui.audio.is.muted.you.cannot.hear.others": "Звук выключен: вы не слышите других и не передаёте голос.",
"ui.microphone.is.muted": "Микрофон выключен.",
"ui.enter.a.server.address": "Укажите адрес сервера.",
"ui.could.not.disconnect.from.the.current.server": "Не удалось отключиться от текущего сервера",
"ui.disconnected.from.server": "Отключено от сервера",
"ui.connection.lost.reconnecting": "Связь потеряна, переподключение…",
"ui.interface.startup.failed": "Ошибка запуска интерфейса",
"ui.channel": "Канал",
"ui.this.person.left.the.server": "Собеседник покинул сервер",
"ui.message.exceeds.8.kib": "Сообщение длиннее 8 КиБ",
"ui.close.private.chat": "Закрыть личный чат",
"ui.current.channel.chat": "Чат текущего канала",
"ui.server.wide.chat": "Чат всего сервера",
"ui.everyone.in.this.channel.can.see.its": "Сообщения в этом канале видят все, кто в нём находится.",
"ui.everyone.connected.to.the.server.can.see": "Сообщения сервера видят все подключённые.",
"ui.private.conversation.only.the.recipient.can.see": "Личная переписка. Сообщения видит только собеседник.",
"ui.message.the.whole.server": "Сообщение всему серверу",
"ui.loading.devices": "Получаем список устройств…",
"ui.audio.settings": "Настройки звука…",
"ui.the.engine.hid.the.device.list.only": "Движок скрыл список устройств: доступно только системное устройство.",
"ui.no.microphones.found": "Микрофоны не найдены.",
"ui.no.output.devices.found": "Устройства вывода не найдены.",
"ui.enter.a.server.address.to.save.it": "Укажите адрес сервера, чтобы сохранить его.",
"ui.enter.an.address": "Укажите адрес.",
"ui.server.added": "Сервер добавлен.",
"ui.this.address.is.already.saved": "Этот адрес уже сохранён",
"ui.you.can.save.up.to.50.servers": "Можно сохранить не больше 50 серверов",
"ui.connected2": "Подключено",
"ui.switch": "Переключиться",
"ui.you.are.connected.to.this.server": "Вы подключены к этому серверу",
"ui.disconnect.from.the.current.server.and.connect": "Отключиться от текущего сервера и подключиться к этому",
"ui.edit": "Изменить",
"ui.confirm.deletion": "Точно удалить?",
"ui.delete": "Удалить",
"ui.server.name": "Название сервера",
"ui.name.and.address.cannot.be.empty": "Название и адрес не могут быть пустыми",
"ui.this.address.is.already.saved.under.another": "Этот адрес уже сохранён под другим названием",
"ui.this.is.already.your.nickname": "Это уже ваш никнейм.",
"ui.saving": "Сохраняем…",
"ui.and.applied.on.the.server": " и применено на сервере",
"ui.saved": "Сохранено.",
"ui.the.server.nickname.was.restored": "; имя на сервере возвращено",
"ui.uid.copied": "UID скопирован",
"ui.disconnect.from.the.server.first": "Сначала отключитесь от сервера.",
"ui.press.a.key": "нажмите клавишу…",
"ui.stop.test": "Остановить проверку",
"ui.available.after.disconnecting.from.the.server": "Доступно после отключения от сервера",
"ui.core": "Ядро",
"ui.not.running": "не запущено",
"ui.platform": "Платформа",
"ui.core.executable": "Исполняемый файл ядра",
"ui.data.folder": "Каталог данных",
"ui.receive.capabilities.unavailable": "Возможности приёма недоступны",
"ui.hardware.decoding.is.allowed.and.available.to": "аппаратное декодирование разрешено и доступно движку",
"ui.hardware.decoding.is.force.enabled": "аппаратное декодирование принудительно разрешено",
"ui.hardware.decoding.is.disabled.the.engine.will": "аппаратное декодирование отключено, движок будет декодировать программно",
"ui.hardware.decoding.is.disabled": "аппаратное декодирование отключено",
"ui.hardware.decoding.is.unavailable.on.this.device": "аппаратное декодирование недоступно на этом устройстве, будет программное",
"ui.hardware.decoding.is.unavailable": "аппаратное декодирование недоступно",
"ui.unknown": "неизвестно",
"ui.allowed": "разрешено",
"ui.disabled.disable.accelerated.video.decode.flag": "запрещено (флаг disable-accelerated-video-decode)",
"ui.power.efficient": " (энергоэффективный)",
"ui.not.power.efficient": " (не энергоэффективный)",
"ui.current.stream": "Текущая трансляция",
"ui.last.stream": "При последнем просмотре",
"ui.the.actual.decoder.is.reported.only.while": "Какой декодер реально работает, видно только во время просмотра трансляции.",
"ui.dismiss.notification": "Закрыть уведомление",
"ui.closed": "закрыт",
"ui.password.protected": "с паролем",
"ui.you.are.here": "вы здесь",
"ui.you.are.in.this.channel": "Вы в этом канале",
"ui.join.channel": "Перейти в канал",
"ui.channel.password": "Пароль канала",
"ui.join": "Войти",
"ui.you": "вы",
"ui.audio.muted2": "звук выключен",
"ui.microphone.muted2": "микрофон выключен",
"ui.no.microphone": "Нет микрофона",
"ui.no.microphone2": "нет микрофона",
"ui.away": "Отошёл",
"ui.away2": "отошёл",
"ui.recording.the.conversation": "Записывает разговор",
"ui.recording": "записывает",
"ui.talking": "говорит",
"ui.you2": " (вы)",
"ui.open.profile.settings": ". Открыть настройки профиля",
"ui.send.a.private.message": ". Написать личное сообщение",
"ui.profile.settings": "Настройки профиля",
"ui.send.a.private.message2": "Написать личное сообщение",
"ui.watch": "Смотреть",
"ui.watching": "Смотрите",
"ui.screen.share": "Трансляция экрана",
"ui.the.engine.hid.the.device.list.audio": "Движок скрыл список устройств (нет разрешения на доступ к звуковым устройствам). Доступно только системное устройство по умолчанию.",
"ui.no.audio.devices.found": "Звуковые устройства не найдены.",
"ui.talk.now": "Говорите…",
"ui.the.server.routes.streams.through.an.sfu": "Сервер передаёт трансляции через SFU. TeamsPeach поддерживает только прямые (P2P) трансляции TeamSpeak 6.",
"ui.request.sent.waiting.for.the.streamer": "Запрос отправлен. Ждём ответа стримера…",
"ui.connecting.to.the.streamer": "Соединение со стримером…",
"ui.the.stream.connection.was.interrupted.waiting.to": "Связь со стримером прервалась, ждём восстановления…",
"ui.the.streamer.declined.your.request.to.watch": "Стример отклонил запрос на просмотр.",
"ui.the.streamer.removed.you.from.the.viewers": "Стример убрал вас из зрителей.",
"ui.the.streamer.did.not.respond.within.90": "Стример не ответил на запрос за 90 секунд.",
"ui.could.not.connect.directly.to.the.streamer": "Не удалось установить прямое соединение со стримером. Для просмотра нужен прямой сетевой доступ к его компьютеру (через STUN, без TURN).",
"ui.the.stream.ended": "Трансляция завершена.",
"ui.the.streamer.left.the.server": "Стример покинул сервер.",
"ui.connection.to.the.server.was.lost": "Соединение с сервером потеряно.",
"ui.this.stream.uses.a.teamspeak.sfu.server": "Эта трансляция идёт через SFU-сервер TeamSpeak. TeamsPeach поддерживает только прямые (P2P) трансляции.",
"ui.connected.waiting.for.the.first.frame": "Соединение установлено, ждём первый кадр…",
"ui.close": "Закрыть",
"ui.cancel2": "Отменить",
"ui.streamer.is.not.sending.audio": "стример не передаёт звук",
"ui.with.audio": "со звуком",
"ui.unmute.stream": "Включить звук трансляции",
"ui.selected.device": "выбранное устройство",
"ui.system.default.device": "Системное устройство по умолчанию",
"ui.previously.selected.device.currently.unavailable": "Выбранное ранее устройство (сейчас не найдено)",
"ui.output.device.selection.is.not.supported": "Выбор устройства вывода не поддерживается",
"ui.selected.microphone.unavailable.using.the.default.microphone": "Выбранный микрофон недоступен, используется микрофон по умолчанию",
"ui.microphone.disconnected": "Микрофон отключён",
"ui.invalid.request": "Некорректный запрос",
"ui.command.not.supported": "Команда не поддерживается",
"ui.profile.not.created.yet": "Профиль ещё не создан",
"ui.profile.already.exists": "Профиль уже существует",
"ui.the.identity.file.is.corrupted.restore.a": "Файл идентичности повреждён. Восстановите его из резервной копии (Настройки → Импорт).",
"ui.profile.file.corrupted": "Файл профиля повреждён",
"ui.nickname.must.contain.3.30.characters.with": "Никнейм должен содержать от 3 до 30 символов без управляющих символов",
"ui.set.a.nickname.first": "Сначала задайте никнейм",
"ui.not.connected.to.a.server": "Нет подключения к серверу",
"ui.already.connected": "Уже подключено",
"ui.could.not.connect": "Не удалось подключиться",
"ui.the.server.rejected.the.action": "Сервер отклонил действие",
"ui.microphone.queue.overflow.some.audio.was.dropped": "Очередь микрофона переполнена, часть звука пропущена",
"ui.microphone.or.audio.is.muted.voice.is": "Микрофон или звук выключены — передача не идёт",
"ui.opus.codec.error": "Ошибка кодека Opus",
"ui.this.channel.uses.a.legacy.codec.speex": "Канал использует устаревший кодек (Speex/CELT): передача голоса невозможна",
"ui.the.server.accepted.the.nickname.but.saving": "Сервер принял никнейм, но сохранить его на диск не удалось",
"ui.could.not.access.the.data.folder": "Ошибка доступа к каталогу данных",
"ui.internal.core.error": "Внутренняя ошибка ядра",
"ui.the.core.did.not.respond.in.time": "Ядро не ответило вовремя",
"ui.the.core.is.not.running": "Ядро не запущено",
"ui.the.core.stopped2": "Ядро завершило работу",
"ui.core.executable.not.found": "Исполняемый файл ядра не найден",
"ui.disconnect.from.the.server.first2": "Сначала отключитесь от сервера",
"ui.action.forbidden": "Действие запрещено",
"ui.no.error.details.were.provided": "Неизвестная ошибка",
"ui.error2": "Ошибка",
"ui.space": "Пробел",
"ui.left.ctrl": "Левый Ctrl",
"ui.right.ctrl": "Правый Ctrl",
"ui.left.alt": "Левый Alt",
"ui.right.alt": "Правый Alt",
"ui.left.shift": "Левый Shift",
"ui.right.shift": "Правый Shift",
"ui.left.super": "Левый Super",
"ui.right.super": "Правый Super",
"ui.not.assigned": "не назначена",
"message.server.banner.p0": "Баннер сервера ({p0})",
"message.setting.not.saved.p0": "Настройка не сохранена: {p0}",
"message.exit.code.p0": "Код завершения {p0}",
"message.p0.teamspeach.never.replaces.a.corrupted": "{p0} TeamsPeach никогда не создаёт новую идентичность поверх повреждённой.",
"message.an.identity.already.exists.uid.p0": "Идентичность уже есть (UID {p0}). Осталось выбрать никнейм.",
"message.profile.created.your.uid.p0": "Профиль создан. Ваш UID: {p0}",
"message.you.will.join.as.p0.uid": "Вы войдёте как {p0} · UID {p1}",
"message.this.channel.uses.a.legacy.codec": "Канал использует устаревший кодек ({p0}). TeamsPeach передаёт и принимает только Opus — говорить здесь не получится.",
"message.p0.enter.the.server.password.and": "{p0}. Введите пароль сервера и подключитесь снова.",
"message.disconnect.p0": "Отключение: {p0}",
"message.disconnected.p0": "Отключено: {p0}",
"message.connected.to.p0.p1": "Подключено к «{p0}»{p1}",
"message.you.are.in.channel.p0": "Вы в канале «{p0}»",
"message.identity.restored.uid.p0": "Идентичность восстановлена. UID {p0}",
"message.restore.failed.p0": "Восстановление не удалось: {p0}",
"message.import.failed.p0": "Импорт не удался: {p0}",
"message.p0.left": "{p0} (вышел)",
"message.message.not.sent.p0": "Сообщение не отправлено: {p0}",
"message.private.messages.p0": "Личные сообщения: {p0}",
"message.unread.p0": ", непрочитанных: {p0}",
"message.message.p0": "Сообщение для {p0}",
"message.message.in.p0": "Сообщение в «{p0}»",
"message.server.p0.saved": "Сервер «{p0}» сохранён",
"message.server.p0.deleted": "Сервер «{p0}» удалён",
"message.saved.p0.uid.unchanged": "Сохранено{p0}. UID не изменился.",
"message.the.server.showed.p0.but.p1": "Сервер показал «{p0}», но на диске остался «{p1}»{p2}.",
"message.saved.to.p0.uid.p1": "Сохранено в «{p0}». UID {p1}.",
"message.export.failed.p0": "Экспорт не удался: {p0}",
"message.identity.imported.uid.p0": "Идентичность импортирована. UID {p0}",
"message.identity.security.level.p0": "Уровень безопасности идентичности: {p0}",
"message.this.run.p0.chromium.engine.p1": "В этом запуске: {p0}. Движок Chromium: {p1}.",
"message.p0.p1.decoder.p2.p3": "{p0}: {p1}, декодер «{p2}»{p3}.",
"message.missing.permission.p0": ", не хватает права {p0}",
"message.could.not.join.p0.p1": "Не удалось перейти в «{p0}»: {p1}",
"message.password.for.channel.p0": "Пароль канала {p0}",
"message.could.not.enter.p0.p1": "Не удалось войти в «{p0}»: {p1}",
"message.away.p0": "Отошёл: {p0}",
"message.away.p02": "отошёл: {p0}",
"message.country.p0": "Страна: {p0}",
"message.groups.p0": ", группы: {p0}",
"message.description.p0": "Описание: {p0}",
"message.groups.p02": "Группы: {p0}",
"message.p0.p1.p2": "{p0} трансляцию {p1}{p2}",
"message.output.device.unavailable.p0": "Устройство вывода недоступно: {p0}",
"message.audio.unavailable.p0": "Звук недоступен: {p0}",
"message.microphone.access.unavailable.p0": "Нет доступа к микрофону: {p0}",
"message.could.not.select.output.device.p0": "Не удалось выбрать устройство вывода: {p0}",
"message.could.not.list.devices.p0.p1": "Не удалось получить список устройств: {p0}: {p1}",
"message.no.microphones.found.output.devices.p0": "Микрофоны не найдены. Устройств вывода: {p0}.",
"message.microphones.p0.no.output.devices.found": "Микрофонов: {p0}. Устройства вывода не найдены.",
"message.microphones.found.p0.output.devices.p1": "Найдено микрофонов: {p0}, устройств вывода: {p1}.",
"message.window.unfocused.p0.will.not.work": "Окно неактивно — {p0} не сработает",
"message.key.p0": "Клавиша: {p0}",
"message.full.screen.unavailable.p0": "Полноэкранный режим недоступен: {p0}",
"message.stream.from.p0": "Трансляция {p0}",
"message.stream.error.p0": "Ошибка трансляции: {p0}",
"message.p0.fps": "{p0} к/с",
"message.could.not.route.stream.audio.to": "Звук трансляции не удалось направить на «{p0}» ({p1}). Он продолжает играть через текущее устройство; выберите другое в Настройки → Звук.",
"message.system.default.p0": "Системное по умолчанию ({p0})",
"message.unnamed.device.p0": "Устройство без названия ({p0})",
"native.identityExport.title": "Экспорт идентичности TeamsPeach",
"native.identity.filter": "Идентичность TeamSpeak",
"native.allFiles": "Все файлы",
"native.identityImport.title": "Импорт идентичности",
"native.identityReplace.title": "Заменить идентичность?",
"native.identityReplace.message": "Импорт заменит текущую идентичность.",
"native.identityReplace.detail": "Текущий UID будет потерян, если у вас нет его резервной копии. Серверные права и группы привязаны к UID.",
"native.identityReplace.cancel": "Отмена",
"native.identityReplace.confirm": "Выбрать файл и заменить",
"native.error.connected": "Сначала отключитесь от сервера",
"native.error.coreMissing": "Исполняемый файл ядра не найден",
"native.error.coreNoResult": "Ядро не вернуло результат",
"native.error.unknown": "Неизвестная ошибка",
"native.error.coreUnavailable": "Ядро не запущено",
"native.error.mediaNotAnnounced": "Адрес не был объявлен сервером",
"native.error.mediaTooLarge": "Изображение больше 4 МиБ",
"native.error.mediaUnsupported": "Не изображение",
"native.error.mediaTimeout": "Истекло время загрузки",
"core.status.readyTimeout": "Ядро не ответило за 15 секунд",
"core.status.protocol": "Неподдерживаемая версия протокола ядра: {protocol}",
"core.error.exited": "Ядро завершило работу",
"core.error.requestTooLarge": "Запрос слишком большой",
"core.error.timeout": "Ядро не ответило на «{cmd}» за {seconds} с",
"core.error.emptyError": "Пустой ответ об ошибке",
"core.exit.0": "Ядро завершило работу",
"core.exit.2": "Ядро отклонило аргументы запуска",
"core.exit.3": "Профиль уже используется другим экземпляром TeamsPeach или каталог данных недоступен",
"core.exit.1": "Внутренняя ошибка ядра (подробности в журнале core.log)",
"core.exit.other": "Ядро завершилось с кодом {code}",
"update.ui.title": "Обновления",
"update.ui.channel.label": "Канал обновлений",
"update.ui.channel.preview": "Предварительные версии (preview)",
"update.ui.channel.stable": "Только стабильные",
"update.ui.confirm.text": "Установка закроет TeamsPeach: текущий разговор и просмотр трансляции прервутся.",
"update.ui.confirm.yes": "Прервать и установить",
"update.ui.confirm.no": "Отмена",
"update.ui.check": "Проверить обновления",
"update.ui.retry": "Повторить",
"update.ui.download": "Скачать",
"update.ui.downloadNow": "Скачать сейчас",
"update.ui.install": "Установить и перезапустить",
"update.ui.openRelease": "Открыть страницу релиза",
"update.ui.status.disabled": "Автообновление недоступно: {reason}.",
"update.ui.status.idle": "Проверка ещё не выполнялась.",
"update.ui.status.checking": "Проверяем обновления…",
"update.ui.status.upToDate": "Установлена последняя версия.",
"update.ui.status.upToDateChecked": "Установлена последняя версия (проверено {time}).",
"update.ui.status.newerPreview": "Есть предварительная версия {version} — она доступна в канале «Предварительные версии».",
"update.ui.status.available": "Доступна версия {version}.",
"update.ui.status.availablePreview": "Доступна предварительная версия {version}.",
"update.ui.status.manual": "Эта сборка обновляется вручную: скачайте архив на странице релиза и замените файлы.",
"update.ui.status.deferred": "Найдена версия {version}. Скачивание начнётся после окончания разговора.",
"update.ui.status.downloading": "Скачивается версия {version}: {percent}%.",
"update.ui.status.downloaded": "Версия {version} скачана и проверена. Установка перезапустит TeamsPeach.",
"update.ui.status.installing": "Устанавливаем обновление, TeamsPeach перезапустится…",
"update.ui.status.error": "Не удалось обновить: {message}",
"update.ui.status.skipped": "Версия {version} пропущена: {reason}.",
"update.ui.toast.available": "Доступна версия TeamsPeach {version} — «Настройки → Информация».",
"update.ui.installFailed": "Не удалось установить обновление",
"language.label": "Язык",
"language.note": "Изменения применяются сразу. Идентичность, подключение и звук сохраняются.",
"members.count": {
"one": "{count} участник",
"few": "{count} участника",
"many": "{count} участников",
"other": "{count} участника"
},
"error.detail": "Ошибка ({code}): {detail}",
"error.device_unavailable": "Выбранный микрофон недоступен. Выберите другое устройство в Настройки → Звук или правым кликом по кнопке микрофона.",
"error.device_lost": "Микрофон отключён. Выберите доступное устройство в Настройки → Звук.",
"update.disabled.dev-build": "Эта сборка для разработки не устанавливает обновления",
"update.disabled.unsupported-platform": "Обновления не поддерживаются на {platform} {arch}",
"update.error.network": "Ошибка сетевого запроса: {detail}",
"update.error.timeout": "Время ожидания запроса истекло через {seconds} с",
"update.error.http": "Сервер обновлений вернул HTTP {status}",
"update.error.bad-response": "Некорректный ответ обновления: {detail}",
"update.error.incomplete-list": "Неполный список релизов: получено {fetched} из {total}",
"update.error.incomplete-release": "Релиз {tag} неполный. Файл: {file}. {detail}",
"update.error.checksum": "Релиз {tag} не прошёл проверку целостности: {detail}",
"update.error.download": "Не удалось скачать релиз {tag}: {detail}",
"update.error.install": "Не удалось установить релиз {tag}: {detail}",
"update.error.bad-version": "Некорректная версия релиза: {version}",
"update.skip.no-feed": "Нет файла обновлений {file} для {target}",
"update.skip.no-package": "Нет установочного пакета {file} для {target}",
"update.skip.feed-mismatch": "Файл обновлений не соответствует релизу {tag}: {detail}",
"update.skip.incomplete-release": "Релиз {tag} неполный. Файл: {file}. {detail}",
"update.install.session-active": "Завершите разговор или подтвердите его прерывание для установки.",
"update.install.not-ready": "Проверенное обновление ещё не готово к установке.",
"update.install.custom-profile": "Автоматическая установка отключена для отдельного профиля: установщик перезапустил бы TeamsPeach с профилем по умолчанию. Установите обновление вручную со страницы релиза.",
"update.manual.custom-profile": "Автоматическая установка отключена для отдельного профиля: установщик перезапустил бы TeamsPeach с профилем по умолчанию. Установите обновление вручную со страницы релиза.",
"update.install.install-failed": "Не удалось установить релиз {tag}: {detail}",
"language.russian": "Русский",
"update.channel.hint": "Предварительный канал включает предварительные версии; стабильный исключает их.",
"error.capture": "Ошибка обработки микрофона."
});
if (typeof module === 'object' && module.exports) module.exports = messages;
root.TeamsPeachCatalogs = root.TeamsPeachCatalogs || {};
root.TeamsPeachCatalogs.ru = messages;
})(globalThis);
-724
View File
@@ -1,724 +0,0 @@
/* TeamsPeach — restrained working UI: warm neutrals, one peach accent, state colours that mean something. */
:root {
color-scheme: light dark;
--font: system-ui, -apple-system, "Segoe UI", "Noto Sans", Ubuntu, Cantarell, "Helvetica Neue", Arial, sans-serif;
--mono: ui-monospace, "Cascadia Mono", "SFMono-Regular", "DejaVu Sans Mono", Consolas, monospace;
--bg: #f6f3f0;
--surface: #fffdfb;
--sidebar: #eee9e4;
--sunken: #e6e0da;
--hover: rgba(70, 45, 30, 0.07);
--border: #dcd3cb;
--border-strong: #c3b7ad;
--text: #221c18;
--text-2: #5e544d;
--text-3: #776c64;
--accent: #b24f26;
--accent-hover: #9c431e;
--accent-ink: #ffffff;
--accent-soft: #fbe2d4;
--accent-soft-ink: #7c3112;
--peach: #f3a37c;
--talk: #1f8a5a;
--talk-soft: rgba(31, 138, 90, 0.16);
--danger: #b3261e;
--danger-soft: #f9dedc;
--warn-soft: #fbedd0;
--warn-ink: #6b4a00;
--focus: #b24f26;
--shadow: 0 6px 20px rgba(40, 24, 12, 0.14), 0 1px 3px rgba(40, 24, 12, 0.1);
--radius: 8px;
--radius-sm: 6px;
}
@media (prefers-color-scheme: dark) {
:root {
/* Blue-gray surfaces from the owner's settings reference; the peach accent stays the brand colour. */
--bg: #1b2029;
--surface: #242b37;
--sidebar: #1e242e;
--sunken: #171b23;
--hover: rgba(205, 220, 245, 0.07);
--border: #2f3746;
--border-strong: #414b5c;
--text: #e7ebf2;
--text-2: #aab3c2;
--text-3: #8e98aa;
--accent: #f09a6c;
--accent-hover: #f6ae86;
--accent-ink: #2a140a;
--accent-soft: #3a3033;
--accent-soft-ink: #f6c0a2;
--peach: #f3a37c;
--talk: #4fcf8e;
--talk-soft: rgba(79, 207, 142, 0.18);
--danger: #f08b82;
--danger-soft: #42221f;
--warn-soft: #3a2f17;
--warn-ink: #f0d18a;
--focus: #f09a6c;
--shadow: 0 8px 24px rgba(0, 0, 0, 0.45), 0 1px 3px rgba(0, 0, 0, 0.4);
}
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font: 14px/1.45 var(--font);
-webkit-font-smoothing: antialiased;
}
body { overflow: hidden; }
[hidden] { display: none !important; }
::selection { background: var(--accent-soft); color: var(--accent-soft-ink); }
:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 2px;
}
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
::-webkit-scrollbar-thumb:hover { background-color: var(--text-3); }
h1, h2, h3 { margin: 0; font-weight: 650; text-wrap: balance; }
h1 { font-size: 20px; line-height: 1.25; }
h2 { font-size: 16px; }
h3 { font-size: 14px; }
p { margin: 0; }
.sprite { position: absolute; width: 0; height: 0; overflow: hidden; }
.icon {
width: 20px;
height: 20px;
flex: none;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.brand-mark { width: 40px; height: 40px; stroke: none; }
.brand-mark-large { width: 56px; height: 56px; }
.brand-mark .peach-body, .peach-body { fill: var(--peach); stroke: none; }
.peach-crease { fill: none; stroke: rgba(120, 50, 20, 0.35); stroke-width: 1.2; }
.peach-leaf { fill: #5f9e5a; stroke: none; }
/* ---------- controls ---------- */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 34px;
padding: 6px 14px;
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--surface);
color: var(--text);
font: inherit;
font-weight: 550;
cursor: pointer;
transition: background-color 120ms ease-out, border-color 120ms ease-out;
}
.btn:hover { background: var(--hover); }
.btn:disabled { opacity: 0.55; cursor: not-allowed; }
.btn .icon { width: 18px; height: 18px; }
.btn-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); padding-inline: 8px; }
.btn-ghost:hover { background: var(--hover); color: var(--text); }
.btn-ghost[aria-pressed="true"] { color: var(--accent-soft-ink); background: var(--accent-soft); }
.btn-wide { width: 100%; }
.btn-danger { color: var(--danger); }
.icon-btn {
display: inline-grid;
place-items: center;
width: 34px;
height: 34px;
padding: 0;
border: 0;
border-radius: var(--radius-sm);
background: transparent;
color: var(--text-2);
cursor: pointer;
transition: background-color 120ms ease-out, color 120ms ease-out;
}
.icon-btn:hover { background: var(--hover); color: var(--text); }
.icon-btn:disabled { opacity: 0.45; cursor: not-allowed; }
.icon-btn[aria-pressed="true"] { color: var(--danger); background: var(--danger-soft); }
.icon-btn-accent { color: var(--accent); }
.field { display: flex; flex-direction: column; gap: 6px; }
.field-grow { flex: 1; }
.field-label { font-size: 13px; font-weight: 600; color: var(--text-2); }
.optional { font-weight: 400; color: var(--text-3); }
input[type="text"], input[type="password"], select, textarea {
width: 100%;
min-height: 36px;
padding: 7px 10px;
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--surface);
color: var(--text);
font: inherit;
caret-color: var(--accent);
}
input::placeholder, textarea::placeholder { color: var(--text-3); }
input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid var(--focus); outline-offset: 0; border-color: transparent; }
input[aria-invalid="true"] { border-color: var(--danger); }
input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); width: 16px; height: 16px; margin: 0; }
.range { accent-color: var(--accent); width: 100%; }
.range-value { min-width: 3.5ch; font-variant-numeric: tabular-nums; color: var(--text-2); font-size: 12px; }
.fieldset { border: 0; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; }
.fieldset legend { margin-bottom: 8px; padding: 0; }
.choice { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.hint { font-size: 12.5px; color: var(--text-3); max-width: 68ch; }
.lede { color: var(--text-2); max-width: 60ch; }
.form-error { min-height: 1em; color: var(--danger); font-size: 13px; }
.form-error:empty { display: none; }
.form-status { color: var(--text-2); font-size: 13px; }
.form-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.kbd {
display: inline-block;
min-width: 2.4em;
padding: 2px 8px;
border: 1px solid var(--border-strong);
border-bottom-width: 2px;
border-radius: 5px;
background: var(--surface);
font: 12.5px var(--mono);
text-align: center;
}
/* ---------- boot / fatal / onboarding ---------- */
.boot, .fatal, .onboarding {
height: 100%;
display: grid;
place-items: center;
padding: 32px;
}
.boot { gap: 12px; align-content: center; color: var(--text-2); }
.fatal-inner { max-width: 620px; display: flex; flex-direction: column; gap: 14px; }
.fatal-list { margin: 0; padding-left: 18px; font: 12.5px var(--mono); color: var(--text-2); word-break: break-all; }
.fatal-list:empty { display: none; }
.fatal-actions { display: flex; gap: 10px; flex-wrap: wrap; }
.onboarding-form {
width: min(420px, 100%);
display: flex;
flex-direction: column;
gap: 12px;
}
.onboarding-form h1 { font-size: 24px; margin-top: 6px; }
/* ---------- shell ---------- */
.shell {
height: 100%;
display: grid;
grid-template-columns: clamp(280px, 27vw, 390px) 1fr;
}
.sidebar {
display: flex;
flex-direction: column;
min-height: 0;
background: var(--sidebar);
border-right: 1px solid var(--border);
}
.server-head {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 10px 12px 14px;
border-bottom: 1px solid var(--border);
}
.server-title { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.server-name { font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.conn-badge { font-size: 12px; color: var(--text-3); display: inline-flex; align-items: center; gap: 6px; }
.conn-badge::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--text-3); }
.conn-badge[data-state="connected"] { color: var(--talk); }
.conn-badge[data-state="connected"]::before { background: var(--talk); }
.conn-badge[data-state="connecting"]::before, .conn-badge[data-state="disconnecting"]::before { background: var(--peach); }
.tree-empty { padding: 16px 14px; color: var(--text-3); font-size: 13px; }
.tree {
list-style: none;
margin: 0;
padding: 6px 6px 12px;
flex: 1;
min-height: 0;
overflow-y: auto;
}
.tree-row { --indent: calc(var(--depth, 0) * 14px); }
.row-btn {
width: 100%;
display: flex;
align-items: center;
gap: 7px;
min-height: 30px;
padding: 4px 8px 4px calc(8px + var(--indent));
border: 0;
border-radius: var(--radius-sm);
background: transparent;
color: var(--text);
font: inherit;
text-align: left;
cursor: pointer;
}
.row-btn:hover { background: var(--hover); }
.row-btn .icon { width: 17px; height: 17px; color: var(--text-3); }
.row-label { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.channel-row .row-btn { font-weight: 600; color: var(--text-2); }
.channel-row[data-current="true"] .row-btn { color: var(--text); background: var(--accent-soft); }
.channel-row[data-current="true"] .row-btn .icon { color: var(--accent-soft-ink); }
.channel-meta { font-size: 12px; font-weight: 400; color: var(--text-3); font-variant-numeric: tabular-nums; }
.spacer-row { padding: 8px 8px 4px calc(8px + var(--indent)); font-size: 12px; font-weight: 600; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: clip; }
.spacer-row[data-kind="center"] { text-align: center; }
.spacer-row[data-kind="right"] { text-align: right; }
.member-row { display: flex; align-items: center; gap: 2px; padding-right: 2px; }
.member-row .row-btn { padding-left: calc(24px + var(--indent)); min-height: 28px; font-weight: 450; }
.member-row[data-self="true"] .row-label { font-weight: 650; }
.member-tag { font-size: 12px; color: var(--text-3); }
.member-flags { display: inline-flex; gap: 2px; color: var(--text-3); }
.member-flags .icon { width: 15px; height: 15px; }
.member-flags .flag-muted { color: var(--danger); }
.status-dot {
width: 10px;
height: 10px;
flex: none;
border-radius: 50%;
border: 2px solid var(--border-strong);
transition: background-color 90ms ease-out, border-color 90ms ease-out, box-shadow 90ms ease-out;
}
[data-talking="true"] > .row-btn .status-dot,
.status-dot[data-talking="true"] {
background: var(--talk);
border-color: var(--talk);
box-shadow: 0 0 0 3px var(--talk-soft);
}
.watch-btn {
display: inline-flex;
align-items: center;
gap: 4px;
flex: none;
height: 24px;
padding: 0 8px 0 6px;
border: 1px solid var(--accent);
border-radius: 12px;
background: transparent;
color: var(--accent);
font: 600 12px var(--font);
cursor: pointer;
}
.watch-btn .icon { width: 14px; height: 14px; }
.watch-btn:hover { background: var(--accent-soft); }
.watch-btn[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); }
.password-row { padding: 4px 6px 8px calc(30px + var(--indent)); }
.password-row form { display: flex; gap: 6px; }
.password-row input { min-height: 30px; padding: 4px 8px; }
.password-row .btn { min-height: 30px; padding: 4px 10px; }
.self {
display: flex;
align-items: center;
gap: 6px;
padding: 10px 8px 10px 14px;
border-top: 1px solid var(--border);
background: var(--sunken);
}
.self-id { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; }
.self-text { min-width: 0; }
.self-nick { font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.self-sub { font-size: 12px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }
.self-actions { display: flex; gap: 2px; }
/* ---------- workspace ---------- */
.workspace { min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--surface); }
.connect-view { flex: 1; overflow-y: auto; display: grid; place-items: center; padding: 32px; }
.connect-form { width: min(440px, 100%); display: flex; flex-direction: column; gap: 14px; }
.session-view { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.session-head {
display: flex;
align-items: center;
gap: 16px;
padding: 12px 18px;
border-bottom: 1px solid var(--border);
}
.session-title { flex: 1; min-width: 0; }
.session-title h1 { font-size: 17px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.channel-topic { font-size: 12.5px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.channel-topic:empty { display: none; }
.transmit { display: flex; align-items: center; gap: 10px; flex: none; }
.transmit-hint { font-size: 12.5px; color: var(--text-3); }
.btn-ptt { user-select: none; touch-action: none; }
.btn-ptt[aria-pressed="true"] { background: var(--talk); border-color: var(--talk); color: #fff; }
.notice {
margin: 10px 18px 0;
padding: 8px 12px;
border-radius: var(--radius-sm);
background: var(--warn-soft);
color: var(--warn-ink);
font-size: 13px;
}
/* stream */
.stream-view {
flex: 0 0 58%;
min-height: 220px;
display: flex;
flex-direction: column;
background: #0d0c0b;
border-bottom: 1px solid var(--border);
}
.stream-stage { position: relative; flex: 1; min-height: 0; }
.stream-stage video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; background: #0d0c0b; }
.stream-overlay {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 24px;
color: #e9e2dc;
text-align: center;
font-size: 14px;
pointer-events: none;
}
.stream-overlay:empty { display: none; }
.stream-bar {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
background: #171514;
color: #ede6e0;
}
.stream-bar .icon-btn { color: #c9bfb7; }
.stream-bar .icon-btn:hover { background: rgba(255, 255, 255, 0.08); color: #fff; }
.stream-bar .icon-btn[aria-pressed="true"] { background: rgba(240, 139, 130, 0.18); color: #f4a39b; }
.stream-bar .btn { background: transparent; color: #ede6e0; border-color: #4a433e; }
.stream-bar .btn:hover { background: rgba(255, 255, 255, 0.08); }
.stream-bar .range { width: 120px; accent-color: #f09a6c; }
.stream-bar .range-value { color: #b2a79f; }
.stream-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.stream-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.stream-stats { font-size: 12px; color: #b2a79f; font-variant-numeric: tabular-nums; }
.stream-controls { display: flex; align-items: center; gap: 6px; }
.stream-view:fullscreen .stream-stage video { object-fit: contain; }
/* chat */
.chat { flex: 1; min-height: 160px; display: flex; flex-direction: column; }
.chat-tabs {
display: flex;
gap: 2px;
padding: 8px 12px 0;
border-bottom: 1px solid var(--border);
overflow-x: auto;
flex: none;
}
.tab-wrap { display: inline-flex; align-items: center; flex: none; }
.chat-tab {
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 220px;
padding: 7px 10px 8px;
border: 0;
border-bottom: 2px solid transparent;
background: transparent;
color: var(--text-2);
font: inherit;
font-weight: 550;
cursor: pointer;
white-space: nowrap;
}
.chat-tab:hover { color: var(--text); }
.chat-tab[aria-selected="true"] { color: var(--text); border-bottom-color: var(--accent); }
.chat-tab .tab-label { overflow: hidden; text-overflow: ellipsis; }
.chat-tab .unread {
min-width: 18px;
padding: 0 5px;
border-radius: 9px;
background: var(--accent);
color: var(--accent-ink);
font-size: 11px;
line-height: 18px;
text-align: center;
font-variant-numeric: tabular-nums;
}
.tab-close {
display: inline-grid;
place-items: center;
width: 18px;
height: 18px;
border-radius: 4px;
color: var(--text-3);
}
.tab-close:hover { background: var(--hover); color: var(--text); }
.tab-close .icon { width: 14px; height: 14px; }
.chat-log {
flex: 1;
min-height: 0;
margin: 0;
padding: 12px 18px;
list-style: none;
overflow-y: auto;
}
.chat-log:focus-visible { outline-offset: -2px; }
.chat-empty { color: var(--text-3); font-size: 13px; padding: 8px 0; }
.msg { padding: 2px 0; max-width: 80ch; }
.msg + .msg[data-head="true"] { margin-top: 10px; }
.msg-head { display: flex; align-items: baseline; gap: 8px; }
.msg-author { font-weight: 650; }
.msg[data-own="true"] .msg-author { color: var(--accent); }
.msg-time { font-size: 11.5px; color: var(--text-3); font-variant-numeric: tabular-nums; }
.msg-body { white-space: pre-wrap; overflow-wrap: anywhere; }
.msg-system { color: var(--text-3); font-size: 13px; padding: 4px 0; }
.msg-system + .msg[data-head="true"], .msg + .msg-system { margin-top: 8px; }
.composer {
display: flex;
align-items: flex-end;
gap: 8px;
margin: 0 18px 14px;
padding: 6px 6px 6px 12px;
border: 1px solid var(--border-strong);
border-radius: var(--radius);
background: var(--surface);
}
.composer:focus-within { border-color: var(--focus); box-shadow: 0 0 0 1px var(--focus); }
.composer textarea {
min-height: 24px;
max-height: 160px;
padding: 5px 0;
border: 0;
background: transparent;
resize: none;
line-height: 1.45;
}
.composer textarea:focus-visible { outline: none; }
/* settings */
.settings-view { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.uid-value {
padding: 6px 10px;
border-radius: var(--radius-sm);
background: var(--sunken);
font: 13px var(--mono);
user-select: all;
overflow-wrap: anywhere;
}
.meter-row { display: flex; align-items: center; gap: 12px; }
.meter { flex: 1; height: 8px; border-radius: 4px; background: var(--sunken); overflow: hidden; }
.meter-fill { height: 100%; width: 0%; background: var(--talk); transition: width 60ms linear; }
.ptt-row { display: flex; align-items: center; gap: 10px; }
.ptt-row .field-label { margin-right: 4px; }
.diag-list { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; margin: 0; font-size: 13px; }
.diag-list dt { color: var(--text-3); }
.diag-list dd { margin: 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.codec-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 4px; font: 12.5px var(--mono); color: var(--text-2); }
/* toasts */
.toasts {
position: fixed;
right: 16px;
bottom: 16px;
display: flex;
flex-direction: column;
gap: 8px;
max-width: min(420px, calc(100vw - 32px));
z-index: 10;
}
.toast {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 10px 8px 10px 14px;
border-radius: var(--radius);
background: var(--surface);
border: 1px solid var(--border);
box-shadow: var(--shadow);
font-size: 13px;
animation: toast-in 180ms cubic-bezier(0.16, 1, 0.3, 1);
}
.toast[data-kind="error"] { border-color: var(--danger); }
.toast-text { flex: 1; padding-top: 2px; }
.toast .icon-btn { width: 26px; height: 26px; }
.toast .icon { width: 16px; height: 16px; }
@keyframes toast-in {
from { transform: translateY(8px); opacity: 0; }
to { transform: none; opacity: 1; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { transition: none !important; animation: none !important; }
}
@media (max-width: 1000px) {
.transmit-hint { display: none; }
}
/* ---------- server-provided tree media ---------- */
.avatar { position: relative; width: 22px; height: 22px; flex: none; display: grid; place-items: center; border-radius: 50%; }
.avatar img { width: 22px; height: 22px; border-radius: 50%; object-fit: cover; }
.avatar.has-image .status-dot { position: absolute; right: -2px; bottom: -2px; width: 9px; height: 9px; background: var(--sidebar); }
[data-talking="true"] > .row-btn .avatar.has-image img { box-shadow: 0 0 0 2px var(--talk); }
.member-row .row-btn { padding-left: calc(18px + var(--indent)); }
/* The nickname keeps its width first; group labels and badges shrink and truncate before it. */
.member-row .row-label { flex: 0 0 auto; max-width: 70%; }
.group-label { flex: 0 1 auto; min-width: 2.5em; max-width: 14ch; padding: 0 6px; border-radius: 4px; background: var(--sunken); color: var(--text-2); font-size: 11.5px; line-height: 18px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.member-tag { margin-right: auto; }
.member-badges { display: inline-flex; align-items: center; gap: 3px; flex: 0 1 auto; min-width: 0; overflow: hidden; }
.group-icon { display: inline-grid; place-items: center; width: 16px; height: 16px; color: var(--text-3); }
.group-icon img { width: 16px; height: 16px; object-fit: contain; }
.group-icon .icon { width: 14px; height: 14px; }
.country { padding: 0 4px; border: 1px solid var(--border-strong); border-radius: 3px; font-size: 10.5px; line-height: 14px; color: var(--text-2); font-variant-numeric: tabular-nums; }
.member-flags .flag-rec { color: var(--danger); }
.channel-icon { display: inline-grid; place-items: center; flex: none; }
.channel-icon img { width: 16px; height: 16px; object-fit: contain; }
.channel-row.has-banner .row-btn {
min-height: 36px;
background-image: linear-gradient(90deg, var(--sidebar) 30%, color-mix(in srgb, var(--sidebar) 55%, transparent) 100%), var(--banner);
background-size: cover;
background-position: center;
}
.channel-row.has-banner[data-current="true"] .row-btn {
background-image: linear-gradient(90deg, var(--accent-soft) 30%, color-mix(in srgb, var(--accent-soft) 55%, transparent) 100%), var(--banner);
}
.host-banner { display: block; width: calc(100% - 20px); max-height: 96px; margin: 10px 10px 0; object-fit: contain; border-radius: var(--radius-sm); }
/* The official client highlights only relationships it knows: the own client (and myTS contacts, which need an account). */
.member-row[data-self="true"] .row-label { color: var(--accent); }
/* ---------- settings: category navigation + titled cards (owner's reference) ---------- */
.visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
.room-side { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.room-side[hidden] { display: none; }
.settings-nav { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; padding: 10px 10px 14px; }
.settings-back { display: inline-flex; align-items: center; gap: 6px; align-self: flex-start; margin-bottom: 6px; padding: 6px 8px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-2); font: inherit; cursor: pointer; }
.settings-back:hover { background: var(--hover); color: var(--text); }
.settings-back .icon { width: 18px; height: 18px; }
.settings-nav-title { display: flex; align-items: center; gap: 8px; padding: 4px 8px 8px; color: var(--text-2); font-size: 15px; font-weight: 600; }
.nav-group-label { padding: 10px 10px 4px; color: var(--text-3); font-size: 12px; }
.nav-item { position: relative; display: flex; align-items: center; gap: 12px; min-height: 40px; padding: 6px 12px; border: 0; border-radius: var(--radius); background: transparent; color: var(--text); font: inherit; font-weight: 550; text-align: left; cursor: pointer; }
.nav-item .icon { width: 22px; height: 22px; color: var(--text-2); }
.nav-item:hover { background: var(--hover); }
.nav-item[aria-current="page"] { background: var(--accent-soft); }
.nav-item[aria-current="page"] .icon { color: var(--accent); }
.nav-item[aria-current="page"]::before { content: ""; position: absolute; left: -10px; top: 8px; bottom: 8px; width: 3px; border-radius: 0 3px 3px 0; background: var(--accent); }
.settings-view { background: var(--bg); }
.settings-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 22px 26px 40px; }
.settings-panel { max-width: 880px; display: flex; flex-direction: column; gap: 14px; }
.panel-title { font-size: 20px; margin: 2px 2px 4px; }
.card { display: flex; flex-direction: column; gap: 12px; padding: 18px 20px; border-radius: 12px; background: var(--surface); border: 1px solid var(--border); }
.card-title { font-size: 15px; font-weight: 650; }
.card-divider { height: 1px; background: var(--border); margin: 2px 0; }
.card-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.row-name { font-weight: 600; margin-right: auto; }
.card .uid-value { font-size: 12.5px; color: var(--text-2); background: var(--sunken); }
.inline-form { display: flex; align-items: center; gap: 12px; }
.inline-label { font-weight: 600; }
.inline-form input { flex: 1; min-height: 34px; border-radius: 17px; padding: 5px 14px; background: var(--sunken); border-color: transparent; }
.stack-form { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; align-items: end; }
.stack-form .form-actions { grid-column: 1 / -1; }
.btn-small { min-height: 30px; padding: 4px 12px; font-size: 13px; }
/* ---------- saved servers ---------- */
.servers-panel { padding: 8px 8px 6px; border-bottom: 1px solid var(--border); }
.servers-head { display: flex; align-items: center; gap: 8px; padding: 2px 6px 6px; }
.servers-title { flex: 1; font-size: 12px; font-weight: 600; color: var(--text-3); }
.servers-empty { padding: 2px 6px 6px; font-size: 12.5px; color: var(--text-3); }
.servers-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
.server-item { width: 100%; display: flex; align-items: center; gap: 10px; padding: 6px 8px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text); font: inherit; text-align: left; cursor: pointer; }
.server-item:hover:not(:disabled) { background: var(--hover); }
.server-item:disabled { cursor: default; }
.server-item .icon { width: 16px; height: 16px; color: var(--text-3); }
.server-text { flex: 1; min-width: 0; display: flex; flex-direction: column; }
.server-item-name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.server-item-address { font-size: 12px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.server-item-action { flex: none; font-size: 12px; font-weight: 600; color: var(--accent); }
.server-item:disabled .server-item-action { color: var(--talk); }
.servers-manage { gap: 0; }
.manage-row { display: flex; align-items: center; gap: 8px; padding: 10px 0; border-top: 1px solid var(--border); }
.manage-row:first-child { border-top: 0; }
.edit-row { flex: 1; display: grid; grid-template-columns: 1fr 1fr auto auto; gap: 8px; }
.row-value { color: var(--text-2); font-size: 13px; }
.card-details { border-top: 1px solid var(--border); padding-top: 10px; }
.card-details > summary { cursor: pointer; font-weight: 600; color: var(--text-2); padding: 4px 0; }
.card-details > summary:hover { color: var(--text); }
.card-details[open] > summary { margin-bottom: 10px; }
.card-details .diag-list { margin-bottom: 12px; }
.details-title { font-size: 13px; font-weight: 600; color: var(--text-2); margin: 10px 0 6px; }
/* ---------- device context menus (footer microphone / headphones) ---------- */
.device-menu {
position: fixed;
z-index: 20;
min-width: 240px;
max-width: min(420px, calc(100vw - 16px));
max-height: calc(100vh - 16px);
overflow-y: auto;
padding: 6px;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--surface);
box-shadow: var(--shadow);
}
.menu-title { padding: 6px 10px 6px; font-size: 12px; font-weight: 600; color: var(--text-3); }
.menu-item { width: 100%; display: flex; align-items: center; gap: 8px; min-height: 32px; padding: 5px 10px 5px 6px; border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text); font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
.menu-item:hover, .menu-item:focus-visible { background: var(--hover); outline: none; }
.menu-item:focus-visible { box-shadow: inset 0 0 0 2px var(--focus); }
.menu-item[aria-checked="true"] { font-weight: 600; }
.menu-item-secondary { color: var(--text-2); }
.menu-check { width: 18px; flex: none; display: inline-grid; place-items: center; color: var(--accent); }
.menu-check .icon { width: 16px; height: 16px; }
.menu-label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.menu-note { margin: 4px 10px; font-size: 12px; color: var(--text-3); }
.menu-sep { height: 1px; margin: 5px 4px; background: var(--border); }
/* ---------- updates card (Settings → Information) ---------- */
.update-status { margin: 10px 0 0; font-size: 13px; color: var(--text); overflow-wrap: anywhere; }
.update-progress { display: block; width: 100%; height: 6px; margin-top: 8px; accent-color: var(--accent); }
.update-confirm { margin-top: 10px; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface-2, var(--surface)); }
.update-confirm .hint { margin-top: 0; }
+31 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "teamspeach-core"
version = "0.1.2"
version.workspace = true
edition = "2021"
rust-version = "1.89"
description = "TeamsPeach native TeamSpeak protocol core (stdio JSON bridge)"
@@ -16,27 +16,52 @@ 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"
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.
earshot = "=1.2.2"
thiserror = "2"
tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] }
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",
"Win32_Media_Audio",
"Win32_Security",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_SystemInformation",
"Win32_System_Threading",
"Win32_System_Variant",
] }
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_Security_Authorization",
"Win32_System_Threading",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_WindowsAndMessaging",
] }
[profile.release]
lto = "thin"
codegen-units = 4
[target.'cfg(target_os = "linux")'.dependencies]
dbus = { version = "0.9", features = ["vendored"] }
x11rb = "0.14.0"
+3944 -193
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
+1396
View File
File diff suppressed because it is too large. Load diff
+174
View File
@@ -0,0 +1,174 @@
//! Additional ordinary client administration primitives used by JSON snapshots and admin views.
//! Wire declarations: pinned ReSpeak Messages.toml (ClientDb*, LogView, *Group*, ChannelAddPerm, ServerGroupDel /
//! ChannelGroupDel `[sgid|cgid, force]`, ServerGroupDelPerm / ChannelGroupDelPerm / ChannelDelPerm
//! `[sgid|cgid|cid, permid?, permsid?]`). The installed TeamSpeak.dll 6.0.0.5163 carries the same five verbs in its
//! client command string table; official main.js@2408925 `RemovePermissionGroup` → `requestGroupDel(..., force)`
//! (the permission page always passes force=true after a confirmation checkbox, main.js@4606337) and
//! main.js@2410218 `RemovePermissions` → `requestPermissionsDel` (inspector `removePermission`, main.js@4575316).
use serde::Deserialize;
use serde_json::Value;
use tsproto_packets::packets::OutCommand;
use crate::{admin::{Live, Reply}, menu, protocol::{ErrorObj, ErrorCode}};
#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
#[serde(rename_all="snake_case")]
pub enum GroupKind { Server, Channel }
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Permission { pub id: String, pub value: i32, #[serde(default)] pub negate: bool, #[serde(default)] pub skip: bool }
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag="command", rename_all="snake_case", deny_unknown_fields)]
pub enum Command {
ServerLog { lines: u16, reverse: bool, instance: bool, begin_pos: u64 },
ClientDatabaseList { start: u32, duration: u16 },
ClientDatabaseFind { pattern: String, uid: bool },
ClientDatabaseDelete { generation: u64, client_database_id: u64, confirm: String },
ClientDatabaseId { uid: String },
ServerGroupList {}, ChannelGroupList {}, ChannelList {}, ChannelInfo { channel_id: u64 },
ClientInfo { client_id: u16, uid: String },
GroupAdd { generation: u64, kind: GroupKind, name: String, #[serde(rename="type")] group_type: u8 },
GroupRename { generation: u64, kind: GroupKind, group_id: u64, name: String },
GroupSetPermissions { generation: u64, kind: GroupKind, group_id: u64, permissions: Vec<Permission> },
ChannelSetPermissions { generation: u64, channel_id: u64, permissions: Vec<Permission> },
/// Destructive: `confirm` must be the decimal group ID being deleted.
GroupDelete { generation: u64, kind: GroupKind, group_id: u64, force: bool, confirm: String },
GroupDeletePermissions { generation: u64, kind: GroupKind, group_id: u64, permissions: Vec<String> },
ChannelDeletePermissions { generation: u64, channel_id: u64, permissions: Vec<String> },
ServerGroupAddClient { generation: u64, group_id: u64, client_database_id: u64 },
ServerGroupMemberAddUid { generation: u64, group_id: u64, uid: String },
}
impl Command {
pub fn name(&self) -> &'static str { match self {
Self::ServerLog{..}=>"server_log", Self::ClientDatabaseList{..}=>"client_database_list",
Self::ClientDatabaseFind{..}=>"client_database_find", Self::ClientDatabaseDelete{..}=>"client_database_delete",
Self::ClientDatabaseId{..}=>"client_database_id", Self::ServerGroupList{}=>"server_group_list",
Self::ChannelGroupList{}=>"channel_group_list", Self::ChannelList{}=>"channel_list", Self::ChannelInfo{..}=>"channel_info",
Self::ClientInfo{..}=>"client_info",
Self::GroupAdd{..}=>"group_add", Self::GroupRename{..}=>"group_rename", Self::GroupSetPermissions{..}=>"group_set_permissions",
Self::ChannelSetPermissions{..}=>"channel_set_permissions", Self::ServerGroupAddClient{..}=>"server_group_add_client",
Self::ServerGroupMemberAddUid{..}=>"server_group_member_add_uid", Self::GroupDelete{..}=>"group_delete",
Self::GroupDeletePermissions{..}=>"group_delete_permissions", Self::ChannelDeletePermissions{..}=>"channel_delete_permissions",
}}
pub fn generation(&self) -> Option<u64> { match self {
Self::ServerGroupMemberAddUid{generation,..}=>Some(*generation),
Self::ClientDatabaseDelete{generation,..}|Self::GroupAdd{generation,..}|Self::GroupRename{generation,..}
|Self::GroupSetPermissions{generation,..}|Self::ChannelSetPermissions{generation,..}|Self::ServerGroupAddClient{generation,..}
|Self::GroupDelete{generation,..}|Self::GroupDeletePermissions{generation,..}|Self::ChannelDeletePermissions{generation,..}=>Some(*generation), _=>None,
}}
pub(super) fn validate(&self) -> Result<(),ErrorObj> {
let positive=|id:u64| super::positive("target ID",id);
if let Some(g)=self.generation(){super::generation(g)?;}
match self {
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,..}=>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,..}=>{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))?;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)?;super::check_str("uid",uid,128,false)?;},
_=>{},
} Ok(())
}
pub fn build(&self, live:&Live) -> Result<(OutCommand,Reply),ErrorObj> {
let s=|v:u64|v.to_string(); let flag=|v:bool|u8::from(v).to_string();
Ok(match self {
Self::ServerLog{lines,reverse,instance,begin_pos}=>(menu::command("logview",&[("lines",lines.to_string()),("reverse",flag(*reverse)),("instance",flag(*instance)),("begin_pos",s(*begin_pos))]),Reply::rows("notifyserverlog",None)),
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::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_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)},
Self::ChannelSetPermissions{channel_id,permissions,..}=>{
if (live.channel)(*channel_id).is_none(){return Err(ErrorObj::new(ErrorCode::NotFound,"channel is no longer visible"));}
(permission_command("channeladdperm","cid",*channel_id,permissions,false),Reply::Ack)
},
Self::GroupDelete{kind,group_id,force,..}=>{
let key=group_names(*kind,"del").2;
let verb=if *kind==GroupKind::Server {"servergroupdel"}else{"channelgroupdel"};
(menu::command(verb,&[(key,s(*group_id)),("force",flag(*force))]),Reply::Ack)
},
Self::GroupDeletePermissions{kind,group_id,permissions,..}=>{
let (verb,key)=if *kind==GroupKind::Server {("servergroupdelperm","sgid")}else{("channelgroupdelperm","cgid")};
(delete_permission_command(verb,key,*group_id,permissions),Reply::Ack)
},
Self::ChannelDeletePermissions{channel_id,permissions,..}=>{
if (live.channel)(*channel_id).is_none(){return Err(ErrorObj::new(ErrorCode::NotFound,"channel is no longer visible"));}
(delete_permission_command("channeldelperm","cid",*channel_id,permissions),Reply::Ack)
},
Self::ServerGroupAddClient{group_id,client_database_id,..}=>(menu::command("servergroupaddclient",&[("sgid",s(*group_id)),("cldbid",s(*client_database_id))]),Reply::Ack),
Self::ServerGroupMemberAddUid{group_id,uid,..}=>{
// Official TS6 main.js assignServerGroupMembers + TeamSpeak.dll
// constructor 0x1814b8e7d: vsgroupassignbyids json=<versioned JSON>.
let member=if uid.len()>32 {serde_json::json!({"client_uid":uid,"vs_group_id":group_id.to_string()})}else{serde_json::json!({"migration":uid,"vs_group_id":group_id.to_string()})};
let payload=serde_json::json!({"version":1,"add":[member]}).to_string();
(menu::command("vsgroupassignbyids",&[("json",payload)]),Reply::Ack)
},
Self::ChannelInfo{..}|Self::ChannelList{}|Self::ClientInfo{..}=>return Err(ErrorObj::new(ErrorCode::Internal,"object reads are handled by the session")),
})
}
}
fn group_names(kind:GroupKind,op:&str)->(&'static str,&'static str,&'static str){match(kind,op){
(GroupKind::Server,"add")=>("servergroupadd","notifyservergrouplist","sgid"),
(GroupKind::Server,"rename")=>("servergrouprename","notifyservergrouplist","sgid"),
(GroupKind::Server,_)=>("servergroupaddperm","notifyservergrouplist","sgid"),
(GroupKind::Channel,"add")=>("channelgroupadd","notifychannelgrouplist","cgid"),
(GroupKind::Channel,"rename")=>("channelgrouprename","notifychannelgrouplist","cgid"),
(GroupKind::Channel,_)=>("channelgroupaddperm","notifychannelgrouplist","cgid"),
}}
fn validate_permission_id(id:&str)->Result<(),ErrorObj>{
if id.is_empty()||id.len()>128||!id.bytes().all(|b|b.is_ascii_alphanumeric()||b==b'_'){return Err(menu::bad("invalid permission identifier"));}
if id.bytes().all(|b|b.is_ascii_digit())&&id.parse::<u32>().ok().is_none_or(|v|v==0){return Err(menu::bad("invalid numeric permission identifier"));}
Ok(())
}
fn validate_permissions(rows:&[Permission],server:bool)->Result<(),ErrorObj>{
if rows.is_empty()||rows.len()>512{return Err(menu::bad("permissions must contain 1..512 entries"));}
for p in rows {
validate_permission_id(&p.id)?;
if !server&&(p.negate||p.skip){return Err(menu::bad("negate and skip are only available for server groups"));}
} Ok(())
}
fn validate_permission_ids(ids:&[String])->Result<(),ErrorObj>{
if ids.is_empty()||ids.len()>512{return Err(menu::bad("permissions must contain 1..512 entries"));}
ids.iter().map(String::as_str).try_for_each(validate_permission_id)
}
/// `*delperm` (declared `[key, permid?, permsid?]`): one part per explicit permission being removed.
fn delete_permission_command(verb:&'static str,key:&'static str,id:u64,ids:&[String])->OutCommand{
let mut c=menu::command(verb,&[]);
for(i,p)in ids.iter().enumerate(){if i>0{c.start_new_part();}c.write_arg(key,&id);
c.write_arg(if p.bytes().all(|b|b.is_ascii_digit()){"permid"}else{"permsid"},p);}
c
}
fn permission_command(verb:&'static str,key:&'static str,id:u64,rows:&[Permission],server:bool)->OutCommand{
let mut c=menu::command(verb,&[]);
for(i,p)in rows.iter().enumerate(){if i>0{c.start_new_part();}c.write_arg(key,&id);
c.write_arg(if p.id.bytes().all(|b|b.is_ascii_digit()){"permid"}else{"permsid"},&p.id);c.write_arg("permvalue",&p.value);
if server{c.write_arg("permnegated",&u8::from(p.negate));c.write_arg("permskip",&u8::from(p.skip));}
} c
}
pub fn recognizes(name:&str)->bool{matches!(name,"server_log"|"client_database_list"|"client_database_find"|"client_database_delete"|"client_database_id"|"server_group_list"|"channel_group_list"|"channel_list"|"channel_info"|"client_info"|"group_add"|"group_rename"|"group_set_permissions"|"channel_set_permissions"|"server_group_add_client"|"server_group_member_add_uid"|"group_delete"|"group_delete_permissions"|"channel_delete_permissions")}
pub fn parse(name:&str,raw:Option<&serde_json::value::RawValue>)->Result<Command,ErrorObj>{
let mut v:Value=serde_json::from_str(raw.map_or("{}",|r|r.get())).map_err(|e|menu::bad(e.to_string()))?;
let obj=v.as_object_mut().ok_or_else(||menu::bad("args must be an object"))?;
if obj.contains_key("command"){return Err(menu::bad("unexpected command argument"));}
obj.insert("command".into(),Value::String(name.into()));
serde_json::from_value(v).map_err(|e|menu::bad(e.to_string()))
}
+232
View File
@@ -0,0 +1,232 @@
//! 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()?;
if let Some(generation) = cmd.generation() {
if generation != c.generation {
return Err(ErrorObj::new(ErrorCode::BadRequest, "connection changed; reload and confirm again")
.with_detail(json!({ "generation": c.generation })));
}
}
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, _)| {
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(Value::from_iter([("rows", Value::Array(rows))])));
}
admin::AdminCommand::Extra(admin::extra::Command::ChannelInfo { channel_id }) => {
if !book.channels.contains_key(&ChannelId(*channel_id)) {
return Err(ErrorObj::new(ErrorCode::NotFound, "channel is no longer visible"));
}
(menu::command("channelgetdescription", &[("cid", channel_id.to_string())]), admin::Reply::ChannelInfo { channel_id: *channel_id })
}
admin::AdminCommand::Extra(admin::extra::Command::ClientInfo { client_id, uid }) => {
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::ClientInfo(admin::ClientInfoReply::new(*client_id, uid.clone())))
}
admin::AdminCommand::TalkPower { target, grant, .. } => {
let client = book
.clients
.get(&ClientId(target.client_id))
.ok_or_else(|| ErrorObj::new(ErrorCode::NotFound, "client is no longer visible"))?;
if client.uid.as_ref().is_none_or(|uid| uid.to_string() != target.uid) {
return Err(menu::bad("client identity changed; reopen the menu"));
}
(admin::talk_power(target.client_id, *grant), admin::Reply::Ack)
}
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 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)?
}
};
// Rows are matched by notification name, so only one reader per name may be in flight.
if let Some(name) = reply.notification() {
let busy = c.pending.values().any(|p| matches!(p, Pending::Admin { reply, .. } if reply.notification() == Some(name)));
if busy {
return Err(ErrorObj::new(ErrorCode::BadRequest, format!("another request reading {name} is still pending")));
}
}
let handle = c.send(command).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.pending.insert(handle, Pending::Admin { req: id.to_owned(), reply });
Ok(None)
}
pub(super) async fn admin_result(&mut self, req: String, reply: admin::Reply, res: Result<(), CommandError>) {
let empty = |e: &CommandError| {
matches!(e.error.to_u32(), Some(admin::DATABASE_EMPTY_RESULT | admin::PERMISSION_EMPTY_RESULT))
};
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| {
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),
};
match answer {
Ok(v) => self.out.ok(&req, v).await,
Err(e) => self.out.err(&req, e).await,
}
}
/// Generation, server UID and the own permission values the official client checks.
fn admin_context(&self, res: Result<(), CommandError>) -> Result<Value, ErrorObj> {
let c = self.conn.as_ref().filter(|c| c.connected()).ok_or_else(not_connected)?;
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
let mut permissions = serde_json::Map::new();
for name in admin::HINT_PERMISSIONS {
permissions.insert((*name).to_owned(), json!(c.permissions.named(name)));
}
let mut v = json!({
"generation": c.generation,
"server_uid": book.server.public_key.get_uid(),
"own_client_id": book.own_client.0,
"catalog_received": c.permissions.has_catalog(),
"permissions": permissions,
"permissions_catalog": c.permissions.catalog,
});
if let Err(e) = res {
v["permission_error"] = serde_json::to_value(command_error(&e)).expect("error serializes");
}
Ok(v)
}
}
+249
View File
@@ -0,0 +1,249 @@
//! Profileless selected-application audio. Never substitutes endpoint/system loopback.
//! Native consumers receive bounded PCM directly; only `run` uses the CLI transport.
use std::io::{Read, Write};
use std::process::ExitCode;
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
use std::thread::JoinHandle;
use std::time::Duration;
use base64::{Engine, engine::general_purpose::STANDARD};
use serde_json::{json, Value};
#[cfg(windows)]
#[path = "app_audio_windows.rs"]
mod platform;
#[cfg(target_os = "linux")]
#[path = "app_audio_linux.rs"]
mod platform;
#[cfg(all(test, not(target_os = "linux")))]
#[path = "app_audio_linux.rs"]
#[allow(dead_code)]
mod linux_contract_tests;
pub const PCM_BYTES: usize = 960 * 2 * 2;
const EVENT_CAPACITY: usize = 4;
/// Explicit, clonable cancellation shared by enumeration and capture operations.
#[derive(Clone, Default)]
pub struct Cancellation(Arc<AtomicBool>);
impl Cancellation {
pub fn cancel(&self) { self.0.store(true, Ordering::Release); }
pub fn is_cancelled(&self) -> bool { self.0.load(Ordering::Acquire) }
pub(super) fn check(&self) -> Result<(), String> {
if self.is_cancelled() { Err("Application audio cancelled".into()) } else { Ok(()) }
}
}
/// Fixed 20 ms, 48 kHz stereo signed little-endian PCM. Sequence gaps denote drops.
#[derive(Debug)]
pub enum CaptureEvent {
Format,
Pcm { sequence: u64, bytes: [u8; PCM_BYTES] },
}
#[derive(Clone)]
pub(super) struct Sink(mpsc::SyncSender<CaptureEvent>);
impl Sink {
pub(super) fn format(&self) -> Result<(), String> {
self.0.try_send(CaptureEvent::Format).map_err(|_| "Application audio consumer stopped".into())
}
pub(super) fn pcm(&self, sequence: u64, bytes: [u8; PCM_BYTES]) -> Result<(), String> {
match self.0.try_send(CaptureEvent::Pcm { sequence, bytes }) {
Ok(()) | Err(mpsc::TrySendError::Full(_)) => Ok(()),
Err(mpsc::TrySendError::Disconnected(_)) => Err("Application audio consumer stopped".into()),
}
}
}
/// Owns the capture worker and its bounded output. Drop cancels and joins it.
/// Host callbacks run on the caller, never on a capture or helper-reader thread.
/// Drain continuously; a slow consumer drops new PCM, never blocks capture.
/// The terminal success/error is returned by `join`/`stop`, not a droppable event.
/// `stop`, `join`, and Drop block: use an owner/shutdown worker, never the UI thread.
pub struct Capture {
cancel: Cancellation,
events: mpsc::Receiver<CaptureEvent>,
worker: Option<JoinHandle<Result<(), String>>>,
}
impl Capture {
pub fn cancel(&self) { self.cancel.cancel(); }
pub fn is_finished(&self) -> bool { self.worker.as_ref().is_none_or(JoinHandle::is_finished) }
pub fn recv_timeout(&self, timeout: Duration) -> Result<CaptureEvent, mpsc::RecvTimeoutError> {
if self.cancel.is_cancelled() { return Err(mpsc::RecvTimeoutError::Disconnected); }
let event = self.events.recv_timeout(timeout)?;
if self.cancel.is_cancelled() { return Err(mpsc::RecvTimeoutError::Disconnected); }
Ok(event)
}
/// Dispatch no more than the queue capacity, even while capture produces more.
pub fn dispatch_pending(&self, mut callback: impl FnMut(CaptureEvent)) -> usize {
let mut count = 0;
while count < EVENT_CAPACITY && !self.cancel.is_cancelled() {
let Ok(event) = self.events.try_recv() else { break };
callback(event);
count += 1;
}
count
}
pub fn join(mut self) -> Result<(), String> { self.join_worker() }
pub fn stop(mut self) -> Result<(), String> { self.cancel(); self.join_worker() }
fn join_worker(&mut self) -> Result<(), String> {
self.worker.take().map_or(Ok(()), |worker| worker.join().unwrap_or_else(|_| Err("Application audio worker panicked".into())))
}
}
impl Drop for Capture {
fn drop(&mut self) { self.cancel(); let _ = self.join_worker(); }
}
/// Enumerate without recording. Retains platform capability and isolation metadata.
pub fn list(cancel: &Cancellation) -> Result<Value, String> {
cancel.check()?;
#[cfg(any(windows, target_os = "linux"))]
{ platform::list(cancel) }
#[cfg(not(any(windows, target_os = "linux")))]
{ Ok(json!({"supported":false,"platform":std::env::consts::OS,"reason":unsupported_reason(),"applications":[]})) }
}
#[cfg(not(any(windows, target_os = "linux")))]
fn unsupported_reason() -> &'static str {
if cfg!(target_os = "macos") {
"Selected-application audio requires an implemented Core Audio process-tap or ScreenCaptureKit helper, macOS SDK build, app signing and user audio-recording consent; this build has no macOS application-audio backend."
} else { "This platform has no selected-application audio capture backend." }
}
/// Start only an exact identity returned by `list`; initialization failures are joined.
pub fn capture(id: &str, cancel: Cancellation) -> Result<Capture, String> {
cancel.check()?;
#[cfg(any(windows, target_os = "linux"))]
{
let id = id.to_owned();
spawn_capture(cancel, move |cancel, sink| platform::capture(&id, cancel, sink))
}
#[cfg(not(any(windows, target_os = "linux")))]
{ let _ = id; Err(unsupported_reason().into()) }
}
fn spawn_capture(cancel: Cancellation, run: impl FnOnce(&Cancellation, &Sink) -> Result<(), String> + Send + 'static) -> Result<Capture, String> {
let (tx, events) = mpsc::sync_channel(EVENT_CAPACITY);
let requested = cancel.clone();
let worker = std::thread::Builder::new().name("app-audio-capture".into()).spawn(move || run(&requested, &Sink(tx))).map_err(|e| e.to_string())?;
Ok(Capture { cancel, events, worker: Some(worker) })
}
pub fn run(args: &[String]) -> ExitCode {
match dispatch(args) {
Ok(()) => ExitCode::SUCCESS,
Err(message) => {
eprintln!("{}", json!({"event":"error","code":"application_audio","message":message}));
ExitCode::from(1)
}
}
}
fn dispatch(args: &[String]) -> Result<(), String> {
let cancel = Cancellation::default();
match args {
[command] if command == "list" => {
println!("{}", list(&cancel)?);
Ok(())
},
[command, id] if command == "capture" => {
let capture = capture(id, cancel.clone())?;
// Only the standalone CLI owns this blocking stdin thread; library workers do not.
std::thread::Builder::new().name("app-audio-stop".into()).spawn(move || {
let _ = std::io::stdin().read(&mut [0u8; 1]);
cancel.cancel();
}).map_err(|e| e.to_string())?;
let mut stdout = std::io::stdout().lock();
let mut encoded = String::with_capacity(PCM_BYTES * 4 / 3);
loop {
match capture.recv_timeout(Duration::from_millis(50)) {
Ok(CaptureEvent::Format) => writeln!(stdout, "{{\"event\":\"format\",\"sampleRate\":48000,\"channels\":2,\"format\":\"s16le\",\"frames\":960}}"),
Ok(CaptureEvent::Pcm { sequence, bytes }) => {
encoded.clear(); STANDARD.encode_string(bytes, &mut encoded);
writeln!(stdout, "{{\"event\":\"pcm\",\"sequence\":{sequence},\"pcm\":\"{encoded}\"}}")
},
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}.and_then(|_| stdout.flush()).map_err(|e| e.to_string())?;
}
capture.join()
},
_ => Err("usage: teamspeach-core app-audio list | app-audio capture <observed-id>".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bounded_consumer_preserves_format_and_drops_without_blocking() {
let capture = spawn_capture(Cancellation::default(), |_, sink| {
sink.format()?;
for sequence in 0..100 { sink.pcm(sequence, [7; PCM_BYTES])?; }
Ok(())
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
let mut events = Vec::new();
assert_eq!(capture.dispatch_pending(|event| events.push(event)), EVENT_CAPACITY);
assert!(matches!(events[0], CaptureEvent::Format));
assert!(matches!(events[1], CaptureEvent::Pcm { sequence: 0, .. }));
assert_eq!(capture.dispatch_pending(|_| panic!("queue should be empty")), 0);
capture.join().unwrap();
}
#[test]
fn cancellation_discards_queued_pcm_before_host_callback() {
let capture = spawn_capture(Cancellation::default(), |_, sink| {
sink.format()?;
sink.pcm(0, [9; PCM_BYTES])
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
capture.cancel();
assert_eq!(capture.dispatch_pending(|_| panic!("cancelled capture forwarded data")), 0);
assert!(matches!(capture.recv_timeout(Duration::ZERO), Err(mpsc::RecvTimeoutError::Disconnected)));
capture.stop().unwrap();
}
#[test]
fn callback_cancellation_stops_current_dispatch_batch() {
let cancel = Cancellation::default();
let capture = spawn_capture(cancel.clone(), |_, sink| {
sink.format()?;
sink.pcm(0, [9; PCM_BYTES])
}).unwrap();
while !capture.is_finished() { std::thread::yield_now(); }
assert_eq!(capture.dispatch_pending(|_| cancel.cancel()), 1);
capture.join().unwrap();
}
#[test]
fn missing_consumer_fails_without_blocking() {
let (tx, rx) = mpsc::sync_channel(EVENT_CAPACITY);
drop(rx);
let sink = Sink(tx);
assert!(sink.format().is_err());
assert!(sink.pcm(0, [0; PCM_BYTES]).is_err());
}
#[test]
fn drop_cancels_and_joins_worker() {
let finished = Arc::new(AtomicBool::new(false));
let completed = finished.clone();
let capture = spawn_capture(Cancellation::default(), move |cancel, _| {
while !cancel.is_cancelled() { std::thread::sleep(Duration::from_millis(1)); }
completed.store(true, Ordering::Release);
Ok(())
}).unwrap();
drop(capture);
assert!(finished.load(Ordering::Acquire));
}
#[test]
fn worker_errors_and_panics_are_joined() {
let capture = spawn_capture(Cancellation::default(), |_, _| Err("source ended".into())).unwrap();
assert_eq!(capture.join().unwrap_err(), "source ended");
let capture = spawn_capture(Cancellation::default(), |_, _| panic!("fixture")).unwrap();
assert_eq!(capture.join().unwrap_err(), "Application audio worker panicked");
}
#[test]
fn cancelled_enumeration_does_not_access_platform() {
let cancel = Cancellation::default();
cancel.cancel();
assert!(list(&cancel).is_err());
assert!(capture("not-observed", cancel).is_err());
}
}
+321
View File
@@ -0,0 +1,321 @@
//! Linux selected playback-stream capture through PulseAudio / PipeWire-Pulse.
//! Runtime prerequisites: pactl with JSON output and parec with --monitor-stream.
//! No sink moves, volume changes, defaults, modules or persistent graph edits.
use std::io::Read;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, atomic::{AtomicBool, Ordering}, mpsc};
use std::time::{Duration, Instant};
use super::{Cancellation, Sink};
use serde::Serialize;
use serde_json::{json, Value};
const BYTES: usize = 3840;
const MAX_JSON: u64 = 4 * 1024 * 1024;
const TIMEOUT: Duration = Duration::from_secs(3);
const PREREQUISITE: &str = "Linux application audio requires pactl JSON support, parec --monitor-stream, and an accessible PulseAudio or PipeWire-Pulse user audio server with recording permission; native PipeWire without pipewire-pulse is not supported by this backend";
struct OwnedChild {
child: Child,
readers: Vec<std::thread::JoinHandle<()>>,
}
impl OwnedChild {
fn new(child: Child) -> Self { Self { child, readers: Vec::new() } }
}
impl Drop for OwnedChild {
fn drop(&mut self) {
// Only these exact helper children are terminated. Killing before joining
// releases blocking pipe reads, including early-return and panic paths.
let _ = self.child.kill();
let _ = self.child.wait();
for reader in self.readers.drain(..) { let _ = reader.join(); }
}
}
struct EndForwarding(Arc<AtomicBool>);
impl Drop for EndForwarding {
fn drop(&mut self) { self.0.store(true, Ordering::Release); }
}
fn command(program: &str) -> Command {
let mut command = Command::new(program);
command.stdin(Stdio::null()).stderr(Stdio::null()).stdout(Stdio::piped()).env("LC_ALL", "C");
#[cfg(target_os = "linux")]
{
use std::os::unix::process::CommandExt;
unsafe extern "C" { fn prctl(option: i32, ...) -> i32; fn getppid() -> i32; }
let parent = std::process::id() as i32;
unsafe { command.pre_exec(move || {
// Kill this owned subprocess if its native/CLI host is forcibly terminated.
if prctl(1, 15, 0, 0, 0) != 0 || getppid() != parent { return Err(std::io::Error::last_os_error()); }
Ok(())
}); }
}
command
}
fn output(program: &str, args: &[&str], cancel: &Cancellation) -> Result<Vec<u8>, String> {
cancel.check()?;
let child = OwnedChild::new(command(program).args(args).spawn().map_err(|e| format!("{PREREQUISITE}: {program}: {e}"))?);
collect_output(child, program, cancel)
}
fn collect_output(mut child: OwnedChild, program: &str, cancel: &Cancellation) -> Result<Vec<u8>, String> {
let stdout = child.child.stdout.take().ok_or("Missing command stdout")?;
let (tx, rx) = mpsc::sync_channel(1);
child.readers.push(std::thread::Builder::new().name("app-audio-query".into()).spawn(move || {
let mut bytes = Vec::new();
let result = stdout.take(MAX_JSON + 1).read_to_end(&mut bytes).map(|_| bytes);
let _ = tx.send(result);
}).map_err(|e| e.to_string())?);
let start = Instant::now();
let mut result = None;
loop {
cancel.check()?;
if result.is_none() {
match rx.try_recv() {
Ok(bytes) => {
let bytes = bytes.map_err(|e| e.to_string())?;
if bytes.len() as u64 > MAX_JSON { return Err("Audio server response exceeds limit".into()); }
result = Some(bytes);
},
Err(mpsc::TryRecvError::Empty) => {},
Err(mpsc::TryRecvError::Disconnected) => return Err("Audio server output reader stopped".into()),
}
}
if let Some(status) = child.child.try_wait().map_err(|e| e.to_string())? {
if !status.success() { return Err(format!("{PREREQUISITE}: {program} exited with {status}")); }
if let Some(bytes) = result { return Ok(bytes); }
}
if start.elapsed() >= TIMEOUT { return Err(format!("{program}: audio server timeout")); }
std::thread::sleep(Duration::from_millis(10));
}
}
fn rows(kind: &str, cancel: &Cancellation) -> Result<Vec<Value>, String> {
serde_json::from_slice(&output("pactl", &["--format=json", "list", kind], cancel)?).map_err(|e| format!("pactl JSON: {e}"))
}
fn number(value: &Value) -> Option<u64> { value.as_u64().or_else(|| value.as_str()?.parse().ok()) }
fn process_stat(text: &str) -> Option<(u32, u64)> {
// comm may contain spaces and parentheses; field 3 starts after the final ')'.
let fields: Vec<_> = text.rsplit_once(')')?.1.split_whitespace().collect();
Some((fields.get(1)?.parse().ok()?, fields.get(19)?.parse().ok()?))
}
fn process(pid: u32) -> Result<(u32, u64), String> {
process_stat(&std::fs::read_to_string(format!("/proc/{pid}/stat")).map_err(|e| e.to_string())?).ok_or_else(|| "Malformed process identity".into())
}
#[derive(Serialize)]
struct Application {
id: String,
label: String,
pid: u32,
ancestors: Vec<u32>,
#[serde(skip)] index: u64,
#[serde(skip)] monitor: String,
}
fn application(row: &Value, sinks: &[Value], start_time: u64, ancestors: Vec<u32>) -> Option<Application> {
let index = number(&row["index"])?;
let client = number(&row["client"])?;
let sink = number(&row["sink"])?;
let props = &row["properties"];
let pid = u32::try_from(number(&props["application.process.id"])?).ok()?;
if pid == 0 { return None; }
let serial = number(&props["object.serial"]).unwrap_or(index);
let sink = sinks.iter().find(|s| number(&s["index"]) == Some(sink))?;
let monitor = sink["monitor_source_name"].as_str()?.to_owned();
if monitor.is_empty() || monitor.len() > 1024 || monitor.chars().any(char::is_control) { return None; }
let label = props["application.name"].as_str().or_else(|| props["application.process.binary"].as_str()).unwrap_or("Audio application");
let media = props["media.name"].as_str().unwrap_or("Playback");
Some(Application {
id: format!("pulse:{index}:{client}:{}:{serial}:{pid}:{start_time}", number(&sink["index"])?),
label: format!("{label} — {media}"), pid, ancestors, index, monitor,
})
}
fn applications(cancel: &Cancellation) -> Result<Vec<Application>, String> {
let sinks = rows("sinks", cancel)?;
let streams = rows("sink-inputs", cancel)?;
let mut result = Vec::new();
for row in streams {
let Some(pid) = number(&row["properties"]["application.process.id"]).and_then(|p| u32::try_from(p).ok()) else { continue };
let Ok((mut parent, start_time)) = process(pid) else { continue };
let mut ancestors = Vec::new();
while parent != 0 && parent != pid && !ancestors.contains(&parent) {
ancestors.push(parent);
let Ok((next, _)) = process(parent) else { break };
parent = next;
}
if let Some(app) = application(&row, &sinks, start_time, ancestors) { result.push(app); }
}
Ok(result)
}
fn prerequisites(cancel: &Cancellation) -> Result<(), String> {
let help = output("parec", &["--help"], cancel)?;
if !String::from_utf8_lossy(&help).contains("--monitor-stream") { return Err(PREREQUISITE.into()); }
Ok(())
}
pub fn list(cancel: &Cancellation) -> Result<Value, String> {
let result = prerequisites(cancel).and_then(|_| applications(cancel));
cancel.check()?;
Ok(match result {
Ok(apps) => json!({"supported":true,"platform":"linux","scope":"audio-stream","backend":"pulseaudio-monitor-stream","applications":apps}),
Err(reason) => json!({"supported":false,"platform":"linux","reason":reason,"applications":[]}),
})
}
pub fn capture(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
match capture_inner(id, cancel, sink) {
Err(_) if cancel.is_cancelled() => Ok(()),
result => result,
}
}
fn capture_inner(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
prerequisites(cancel)?;
let app = applications(cancel)?.into_iter().find(|a| a.id == id).ok_or("Selected audio-stream identity is stale; refresh the application list")?;
// Monitor removal/change before starting capture. Any selected-stream change fails closed.
let mut subscription = OwnedChild::new(command("pactl").arg("subscribe").spawn().map_err(|e| e.to_string())?);
let subscription_out = subscription.child.stdout.take().ok_or("Missing subscription stdout")?;
let changed = Arc::new(AtomicBool::new(false));
let changed_reader = changed.clone();
let target = format!("on sink-input #{}", app.index);
subscription.readers.push(std::thread::Builder::new().name("app-audio-subscribe".into()).spawn(move || {
use std::io::BufRead;
let mut reader = std::io::BufReader::new(subscription_out);
loop {
let mut line = String::new();
match reader.by_ref().take(4097).read_line(&mut line) {
Ok(n) if n > 0 && n <= 4096 => {
if line.trim_end().ends_with(&target) { break; }
},
_ => break,
}
}
changed_reader.store(true, Ordering::Release);
}).map_err(|e| e.to_string())?);
let monitor_arg = format!("--device={}", app.monitor);
let index_arg = format!("--monitor-stream={}", app.index);
cancel.check()?;
let mut recorder = OwnedChild::new(command("parec").args(["--raw", "--format=s16le", "--rate=48000", "--channels=2", "--latency-msec=20", &monitor_arg, &index_arg]).spawn().map_err(|e| e.to_string())?);
// Re-enumerate before forwarding anything: never use a recycled or moved stream index.
if !applications(cancel)?.iter().any(|a| a.id == id && a.monitor == app.monitor) || changed.load(Ordering::Acquire) {
return Err("Selected audio stream changed during activation".into());
}
let mut pcm = recorder.child.stdout.take().ok_or("Missing recorder stdout")?;
sink.format()?;
let pcm_sink = sink.clone();
let pcm_changed = changed.clone();
let requested = cancel.clone();
recorder.readers.push(std::thread::Builder::new().name("app-audio-read".into()).spawn(move || {
let mut sequence = 0;
while !requested.is_cancelled() && !pcm_changed.load(Ordering::Acquire) {
let mut block = [0; BYTES];
if pcm.read_exact(&mut block).is_err() { break; }
if requested.is_cancelled() || pcm_changed.load(Ordering::Acquire) { break; }
if pcm_sink.pcm(sequence, block).is_err() { break; }
sequence += 1;
}
}).map_err(|e| e.to_string())?);
let _end_forwarding = EndForwarding(changed.clone());
let mut checked = Instant::now();
while !cancel.is_cancelled() {
if changed.load(Ordering::Acquire) || subscription.readers.iter().any(|reader| reader.is_finished()) { return Err("Selected audio stream changed or disappeared".into()); }
if recorder.child.try_wait().map_err(|e| e.to_string())?.is_some() { return Err("Selected application recorder stopped".into()); }
if checked.elapsed() >= Duration::from_millis(250) {
if !applications(cancel)?.iter().any(|a| a.id == id && a.monitor == app.monitor) { return Err("Selected audio-stream identity changed or disappeared".into()); }
checked = Instant::now();
}
if recorder.readers.iter().any(|reader| reader.is_finished()) { return Err("Selected application PCM transport stopped".into()); }
std::thread::sleep(Duration::from_millis(10));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn blocking_child() -> OwnedChild {
let (program, prefix) = crate::test_exec::self_invocation();
OwnedChild::new(command(&program).args(prefix)
.args(["app_audio_blocking_child_fixture", "--nocapture", "--test-threads=1"])
.env("TEAMSPEACH_APP_AUDIO_CHILD_FIXTURE", "1").spawn().unwrap())
}
#[test]
fn app_audio_blocking_child_fixture() {
if std::env::var_os("TEAMSPEACH_APP_AUDIO_CHILD_FIXTURE").is_none() { return; }
use std::io::Write;
println!("APP_AUDIO_CHILD_READY");
std::io::stdout().flush().unwrap();
std::thread::sleep(Duration::from_secs(30));
}
#[test]
fn dropping_child_unblocks_and_joins_pipe_reader() {
use std::io::BufRead;
let mut child = blocking_child();
let stdout = child.child.stdout.take().unwrap();
let finished = Arc::new(AtomicBool::new(false));
let completed = finished.clone();
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
child.readers.push(std::thread::spawn(move || {
let mut reader = std::io::BufReader::new(stdout);
let mut line = String::new();
while reader.read_line(&mut line).unwrap_or(0) != 0 {
if line.contains("APP_AUDIO_CHILD_READY") { let _ = ready_tx.try_send(()); }
line.clear();
}
completed.store(true, Ordering::Release);
}));
ready_rx.recv_timeout(Duration::from_secs(5)).unwrap();
let start = Instant::now();
drop(child);
assert!(finished.load(Ordering::Acquire));
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn cancellation_interrupts_blocked_helper_output() {
let child = blocking_child();
let cancel = Cancellation::default();
let requested = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
requested.cancel();
});
let start = Instant::now();
let result = collect_output(child, "fixture", &cancel);
canceller.join().unwrap();
assert_eq!(result.unwrap_err(), "Application audio cancelled");
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn controlled_executable_output_and_failure() {
let (program, prefix) = crate::test_exec::self_invocation();
let run = |option: &'static str| {
let mut args: Vec<&str> = prefix.iter().map(String::as_str).collect();
args.push(option);
output(&program, &args, &Cancellation::default())
};
let data = run("--list").unwrap();
assert!(String::from_utf8(data).unwrap().contains("identity_uses_start_time_serial_and_exact_monitor"));
assert!(run("--not-a-real-test-option").is_err());
}
#[test]
fn identity_uses_start_time_serial_and_exact_monitor() {
let row = json!({"index":7,"client":4,"sink":2,"properties":{"application.process.id":"99","object.serial":"12345","application.name":"Fixture","media.name":"Generated"}});
let sinks = vec![json!({"index":2,"monitor_source_name":"fixture.monitor"})];
let app = application(&row, &sinks, 987, vec![1]).unwrap();
assert_eq!(app.id, "pulse:7:4:2:12345:99:987");
assert_eq!(app.monitor, "fixture.monitor");
assert_ne!(app.id, application(&row, &sinks, 988, vec![]).unwrap().id);
assert!(application(&row, &[], 987, vec![]).is_none());
}
#[test]
fn proc_stat_handles_parenthesized_names() {
let text = "99 (test (tone)) S 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 987 0";
assert_eq!(process_stat(text), Some((42, 987)));
assert_eq!(process_stat("broken"), None);
}
}
+264
View File
@@ -0,0 +1,264 @@
//! WASAPI process-tree loopback (Windows build 20348+), without audio routing changes.
//! Activation follows Microsoft's ApplicationLoopback sample; COM bindings are windows-rs.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::mpsc;
use super::{Cancellation, Sink};
use std::time::{Duration, Instant};
use serde::Serialize;
use serde_json::json;
use windows::core::{implement, Interface, HRESULT, PCWSTR, PWSTR};
use windows::Win32::Foundation::{CloseHandle, FILETIME, HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows::Win32::Media::Audio::*;
use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED, BLOB};
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
use windows::Win32::System::Diagnostics::ToolHelp::*;
use windows::Win32::System::SystemInformation::OSVERSIONINFOW;
use windows::Win32::System::Threading::*;
use windows::Win32::System::Variant::VT_BLOB;
const FRAMES: usize = 960;
const BYTES: usize = FRAMES * 2 * 2;
#[link(name = "ntdll")]
extern "system" { fn RtlGetVersion(version: *mut OSVERSIONINFOW) -> i32; }
struct Com;
impl Com {
fn new() -> Result<Self, String> {
unsafe { CoInitializeEx(None, COINIT_MULTITHREADED).ok() }.map_err(error)?;
Ok(Self)
}
}
impl Drop for Com { fn drop(&mut self) { unsafe { CoUninitialize() }; } }
struct Handle(HANDLE);
impl Drop for Handle { fn drop(&mut self) { unsafe { let _ = CloseHandle(self.0); } } }
struct Started(IAudioClient);
impl Drop for Started { fn drop(&mut self) { unsafe { let _ = self.0.Stop(); } } }
fn error(e: windows::core::Error) -> String { format!("{e}") }
fn supported() -> bool {
let mut v = OSVERSIONINFOW { dwOSVersionInfoSize: std::mem::size_of::<OSVERSIONINFOW>() as u32, ..Default::default() };
unsafe { RtlGetVersion(&mut v) >= 0 && v.dwBuildNumber >= 20348 }
}
#[derive(Serialize)]
struct Application {
id: String,
label: String,
pid: u32,
ancestors: Vec<u32>,
}
fn process(pid: u32) -> Result<(Handle, String, String), String> {
let h = Handle(unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE, false, pid) }.map_err(error)?);
let mut creation = FILETIME::default();
let mut exit = FILETIME::default();
let mut kernel = FILETIME::default();
let mut user = FILETIME::default();
unsafe { GetProcessTimes(h.0, &mut creation, &mut exit, &mut kernel, &mut user) }.map_err(error)?;
if unsafe { WaitForSingleObject(h.0, 0) } != WAIT_TIMEOUT { return Err("Selected application has exited".into()); }
let mut path = [0u16; 32768];
let mut length = path.len() as u32;
unsafe { QueryFullProcessImageNameW(h.0, PROCESS_NAME_WIN32, PWSTR(path.as_mut_ptr()), &mut length) }.map_err(error)?;
let path = String::from_utf16_lossy(&path[..length as usize]);
let label = path.rsplit(['\\', '/']).next().unwrap_or(&path).to_owned();
let time = (u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime);
Ok((h, format!("{pid}:{time:016x}"), label))
}
fn parents(cancel: &Cancellation) -> Result<BTreeMap<u32, u32>, String> {
let snapshot = Handle(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }.map_err(error)?);
let mut entry = PROCESSENTRY32W { dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32, ..Default::default() };
let mut result = BTreeMap::new();
unsafe {
Process32FirstW(snapshot.0, &mut entry).map_err(error)?;
loop {
cancel.check()?;
result.insert(entry.th32ProcessID, entry.th32ParentProcessID);
if Process32NextW(snapshot.0, &mut entry).is_err() { break; }
}
}
Ok(result)
}
fn applications(cancel: &Cancellation) -> Result<Vec<Application>, String> {
let tree = parents(cancel)?;
let mut ids = BTreeSet::new();
unsafe {
let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(error)?;
let devices = enumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE).map_err(error)?;
for index in 0..devices.GetCount().map_err(error)? {
cancel.check()?;
let device = devices.Item(index).map_err(error)?;
// A disappearing endpoint must not silently turn enumeration into an all-system selection.
let manager: IAudioSessionManager2 = device.Activate(CLSCTX_ALL, None).map_err(error)?;
let sessions = manager.GetSessionEnumerator().map_err(error)?;
for index in 0..sessions.GetCount().map_err(error)? {
cancel.check()?;
let session = sessions.GetSession(index).map_err(error)?;
if session.GetState().map_err(error)? == AudioSessionStateExpired { continue; }
let session: IAudioSessionControl2 = session.cast().map_err(error)?;
let pid = session.GetProcessId().map_err(error)?;
if pid != 0 && pid != std::process::id() { ids.insert(pid); }
}
}
}
let mut result = Vec::new();
for pid in ids {
cancel.check()?;
// Inaccessible/protected/exited processes are not selectable.
let Ok((_handle, id, label)) = process(pid) else { continue };
let mut ancestors = Vec::new();
let mut current = pid;
while let Some(&parent) = tree.get(&current) {
if parent == 0 || parent == pid || ancestors.contains(&parent) { break; }
ancestors.push(parent);
current = parent;
}
result.push(Application { id, label, pid, ancestors });
}
Ok(result)
}
pub fn list(cancel: &Cancellation) -> Result<serde_json::Value, String> {
cancel.check()?;
if !supported() {
return Ok(json!({"supported":false,"platform":"win32","reason":"WASAPI process-loopback requires Windows build 20348 or later","applications":[]}));
}
let _com = Com::new()?;
let tree = parents(cancel)?;
let mut host_ancestors = Vec::new();
let mut current = std::process::id();
while let Some(&parent) = tree.get(&current) {
if parent == 0 || host_ancestors.contains(&parent) { break; }
host_ancestors.push(parent);
current = parent;
}
let apps = applications(cancel)?;
cancel.check()?;
Ok(json!({"supported":true,"platform":"win32","scope":"process-tree","hostAncestors":host_ancestors,"applications":apps}))
}
#[implement(IActivateAudioInterfaceCompletionHandler)]
struct Completion {
tx: mpsc::SyncSender<()>,
// The callback retains activation input even if the caller's bounded wait times out.
_params: Box<AUDIOCLIENT_ACTIVATION_PARAMS>,
}
impl IActivateAudioInterfaceCompletionHandler_Impl for Completion_Impl {
fn ActivateCompleted(&self, _operation: windows::core::Ref<IActivateAudioInterfaceAsyncOperation>) -> windows::core::Result<()> {
let _ = self.tx.try_send(());
Ok(())
}
}
fn activate(pid: u32, cancel: &Cancellation) -> Result<IAudioClient, String> {
let mut params = Box::new(AUDIOCLIENT_ACTIVATION_PARAMS {
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 { ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
TargetProcessId: pid, ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
} },
});
// VT_BLOB borrows callback-owned storage; normal Drop would incorrectly CoTaskMemFree it.
let mut variant = std::mem::ManuallyDrop::new(PROPVARIANT::default());
unsafe {
(*variant.Anonymous.Anonymous).vt = VT_BLOB;
(*variant.Anonymous.Anonymous).Anonymous.blob = BLOB {
cbSize: std::mem::size_of::<AUDIOCLIENT_ACTIVATION_PARAMS>() as u32, pBlobData: (&mut *params as *mut AUDIOCLIENT_ACTIVATION_PARAMS).cast(),
};
}
let (tx, rx) = mpsc::sync_channel(1);
let completion: IActivateAudioInterfaceCompletionHandler = Completion { tx, _params: params }.into();
let operation = unsafe { ActivateAudioInterfaceAsync(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, &IAudioClient::IID, Some(&*variant), &completion) }.map_err(error)?;
let start = Instant::now();
loop {
cancel.check()?;
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(()) => break,
Err(mpsc::RecvTimeoutError::Timeout) if start.elapsed() < Duration::from_secs(10) => {},
_ => return Err("Application audio activation timed out".into()),
}
}
let mut status = HRESULT(0);
let mut object = None;
unsafe { operation.GetActivateResult(&mut status, &mut object) }.map_err(error)?;
status.ok().map_err(error)?;
object.ok_or("Application audio activation returned no interface")?.cast().map_err(error)
}
pub fn capture(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
match capture_inner(id, cancel, sink) {
Err(_) if cancel.is_cancelled() => Ok(()),
result => result,
}
}
fn capture_inner(id: &str, cancel: &Cancellation, sink: &Sink) -> Result<(), String> {
if cancel.is_cancelled() { return Ok(()); }
if !supported() { return Err("WASAPI process-loopback requires Windows build 20348 or later".into()); }
let _com = Com::new()?;
let app = applications(cancel)?.into_iter().find(|app| app.id == id).ok_or("Selected application identity is stale or no longer has an audio session; refresh the list")?;
let (target, current_id, _) = process(app.pid)?;
if current_id != id { return Err("Selected application identity changed before capture".into()); }
let client = match activate(app.pid, cancel) {
Err(_) if cancel.is_cancelled() => return Ok(()),
result => result?,
};
// Recheck after asynchronous activation; never start an audio client for a recycled PID.
let (_recheck, current_id, _) = process(app.pid)?;
if current_id != id || unsafe { WaitForSingleObject(target.0, 0) } != WAIT_TIMEOUT {
return Err("Selected application exited during activation".into());
}
let format = WAVEFORMATEX { wFormatTag: 1, nChannels: 2, nSamplesPerSec: 48000, nAvgBytesPerSec: 192000, nBlockAlign: 4, wBitsPerSample: 16, cbSize: 0 };
unsafe { client.Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, 0, 0, &format, None) }.map_err(error)?;
let event = Handle(unsafe { CreateEventW(None, false, false, PCWSTR::null()) }.map_err(error)?);
unsafe { client.SetEventHandle(event.0) }.map_err(error)?;
let reader: IAudioCaptureClient = unsafe { client.GetService() }.map_err(error)?;
if cancel.is_cancelled() { return Ok(()); }
unsafe { client.Start() }.map_err(error)?;
let _started = Started(client);
sink.format()?;
let mut block = [0u8; BYTES];
let mut used = 0;
let mut sequence = 0;
while !cancel.is_cancelled() {
if unsafe { WaitForSingleObject(target.0, 0) } != WAIT_TIMEOUT { return Err("Selected application exited".into()); }
let wait = unsafe { WaitForSingleObject(event.0, 50) };
if wait == WAIT_TIMEOUT { continue; }
if wait != WAIT_OBJECT_0 { return Err("Application audio capture event failed".into()); }
while !cancel.is_cancelled() && unsafe { reader.GetNextPacketSize() }.map_err(error)? > 0 {
let mut data = std::ptr::null_mut();
let mut frames = 0;
let mut flags = 0;
unsafe { reader.GetBuffer(&mut data, &mut frames, &mut flags, None, None) }.map_err(error)?;
let length = frames as usize * 4;
let silent = flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0;
if !silent && data.is_null() {
unsafe { reader.ReleaseBuffer(frames) }.map_err(error)?;
return Err("Application audio returned a null PCM buffer".into());
}
if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 { used = 0; sequence += 1; }
let mut offset = 0;
while offset < length {
let count = (BYTES - used).min(length - offset);
if silent { block[used..used + count].fill(0); }
else { block[used..used + count].copy_from_slice(unsafe { std::slice::from_raw_parts(data.add(offset), count) }); }
used += count;
offset += count;
if used == BYTES {
if !cancel.is_cancelled() {
if let Err(message) = sink.pcm(sequence, block) {
unsafe { reader.ReleaseBuffer(frames) }.map_err(error)?;
return Err(message);
}
}
used = 0;
sequence += 1;
}
}
unsafe { reader.ReleaseBuffer(frames) }.map_err(error)?;
}
}
Ok(())
}
+670 -46
View File
@@ -4,6 +4,7 @@
use std::collections::{HashSet, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use audiopus::coder::Encoder;
use audiopus::{Application, Bitrate, Channels, SampleRate};
@@ -23,17 +24,38 @@ const MAX_OPUS_PACKET: usize = 1275;
// ---------------------------------------------------------------- input queue
/// A capture-clock-stamped frame. Producers retain these tags through DSP and VAD;
/// a device callback must hand PCM to a worker rather than lock this queue itself.
#[derive(Clone, Debug)]
pub struct CapturedFrame {
pub pcm: Frame,
pub captured_at: Instant,
pub connection_generation: u64,
pub capture_epoch: u64,
/// A whisper frame may only use this registered whisper route, never normal voice.
pub whisper: Option<u32>,
}
pub enum AudioIn {
Frame(Box<Frame>),
Frame(CapturedFrame),
End,
}
/// Bounded single-consumer queue between the stdin reader and the session; drops the oldest
/// frame when full.
impl AudioIn {
fn is_frame(&self) -> bool { matches!(self, AudioIn::Frame(_)) }
}
/// Capture age is checked both on ingress and immediately before encoding/sending.
pub const MAX_CAPTURE_AGE: Duration = Duration::from_millis(200);
/// Bounded single-consumer queue between capture/DSP workers and the session.
/// The mutex also serializes synchronous network enqueue against invalidation.
pub struct AudioInQueue {
items: Mutex<VecDeque<AudioIn>>,
notify: Notify,
dropped: AtomicU64,
capture_epoch: AtomicU64,
connection_generation: AtomicU64,
}
/// Upper bound of queued entries: at most [`TX_QUEUE_FRAMES`] frames, and End markers are never
@@ -46,23 +68,76 @@ impl AudioInQueue {
items: Mutex::new(VecDeque::with_capacity(TX_QUEUE_ENTRIES)),
notify: Notify::new(),
dropped: AtomicU64::new(0),
capture_epoch: AtomicU64::new(1),
connection_generation: AtomicU64::new(0),
}
}
pub fn push(&self, item: AudioIn) {
pub fn epoch(&self) -> u64 { self.capture_epoch.load(Ordering::Acquire) }
pub fn generation(&self) -> u64 { self.connection_generation.load(Ordering::Acquire) }
/// A preliminary check, not a send permit. Use `with_valid_frame` for network enqueue.
pub fn validate(&self, frame: &CapturedFrame) -> bool {
self.validate_at(frame, Instant::now())
}
fn validate_at(&self, frame: &CapturedFrame, now: Instant) -> bool {
frame.capture_epoch == self.epoch()
&& frame.connection_generation == self.generation()
&& now.checked_duration_since(frame.captured_at).is_some_and(|age| age <= MAX_CAPTURE_AGE)
}
/// Execute encoding and synchronous network enqueue while invalidation is excluded.
/// Never await, block on network, or call queue-mutating methods in `send`.
/// Recheck `validate(frame)` after encoding, immediately before network enqueue:
/// encoding can itself exhaust the capture-age limit. Release this guard before
/// asynchronous error reporting. Once invalidation returns no old send can start.
pub fn with_valid_frame<R>(&self, frame: &CapturedFrame, send: impl FnOnce() -> R) -> Option<R> {
let _guard = self.items.lock().expect("audio queue poisoned");
self.validate(frame).then(send)
}
fn invalidate_locked(&self, q: &mut VecDeque<AudioIn>) -> u64 {
let epoch = self.epoch().checked_add(1).expect("capture epoch exhausted");
self.capture_epoch.store(epoch, Ordering::Release);
q.clear();
// The consumer must also stop its encoder/VAD burst, even if no PCM remains.
q.push_back(AudioIn::End);
epoch
}
/// Revoke queued, dequeued and VAD-held frames and ask the consumer to end its burst.
pub fn invalidate(&self) -> u64 {
let epoch = {
let mut q = self.items.lock().expect("audio queue poisoned");
self.invalidate_locked(&mut q)
};
self.notify.notify_one();
epoch
}
/// Every connection boundary revokes capture, including reapplying a generation.
pub fn set_generation(&self, generation: u64) {
{
let mut q = self.items.lock().expect("audio queue poisoned");
match item {
// Consecutive ends carry no extra information.
AudioIn::End if matches!(q.back(), Some(AudioIn::End)) => {}
AudioIn::End => q.push_back(item),
AudioIn::Frame(_) => {
let frames = q.iter().filter(|i| matches!(i, AudioIn::Frame(_))).count();
self.connection_generation.store(generation, Ordering::Release);
self.invalidate_locked(&mut q);
}
self.notify.notify_one();
}
/// Reject expired or wrong-boundary frames without ever allocating per frame.
pub fn try_push(&self, frame: CapturedFrame) -> bool {
{
let mut q = self.items.lock().expect("audio queue poisoned");
if !self.validate(&frame) { return false; }
let frames = q.iter().filter(|i| i.is_frame()).count();
if frames >= TX_QUEUE_FRAMES {
if let Some(pos) = q.iter().position(|i| matches!(i, AudioIn::Frame(_))) {
if let Some(pos) = q.iter().position(AudioIn::is_frame) {
q.remove(pos);
self.dropped.fetch_add(1, Ordering::Relaxed);
// Dropping a burst's only frame can leave two ends side by side.
// Removing a burst's only frame can leave adjacent ends.
if pos > 0
&& matches!(q.get(pos - 1), Some(AudioIn::End))
&& matches!(q.get(pos), Some(AudioIn::End))
@@ -71,12 +146,25 @@ impl AudioInQueue {
}
}
}
q.push_back(item);
}
}
q.push_back(AudioIn::Frame(frame));
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
}
self.notify.notify_one();
true
}
pub fn push(&self, item: AudioIn) {
match item {
AudioIn::Frame(frame) => { self.try_push(frame); }
AudioIn::End => {
{
let mut q = self.items.lock().expect("audio queue poisoned");
if !matches!(q.back(), Some(AudioIn::End)) { q.push_back(AudioIn::End); }
debug_assert!(q.len() <= TX_QUEUE_ENTRIES);
}
self.notify.notify_one();
}
}
}
#[cfg(test)]
@@ -84,12 +172,33 @@ impl AudioInQueue {
pub fn pop(&self) -> Option<AudioIn> { self.items.lock().expect("audio queue poisoned").pop_front() }
/// Discard queued entries without revoking dequeued frames. Privacy/routing
/// boundaries must use `invalidate` instead. Overflow statistics are unchanged.
pub fn clear(&self) -> usize {
let mut q = self.items.lock().expect("audio queue poisoned");
let frames = q.iter().filter(|i| i.is_frame()).count();
q.clear();
frames
}
pub async fn notified(&self) { self.notify.notified().await }
/// Number of frames dropped since the last call.
pub fn take_dropped(&self) -> u64 { self.dropped.swap(0, Ordering::Relaxed) }
}
impl tsclientlib::AudioSendGuard for AudioInQueue {
fn with_valid_audio(&self, metadata: &tsclientlib::AudioSendMetadata, send: &mut dyn FnMut()) {
let _guard = self.items.lock().expect("audio queue poisoned");
if metadata.capture_epoch == self.epoch()
&& metadata.connection_generation == self.generation()
&& Instant::now().checked_duration_since(metadata.captured_at).is_some_and(|age| age <= MAX_CAPTURE_AGE)
{
send();
}
}
}
// ---------------------------------------------------------------- transmit
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -166,7 +275,13 @@ impl TxEncoder {
pub fn codec(&self) -> TxCodec { self.codec }
/// Encode one mono frame into a voice packet for the current channel.
pub fn encode(&mut self, frame: &Frame) -> Result<OutPacket, audiopus::Error> {
pub fn encode(&mut self, frame: &Frame) -> Result<OutPacket, audiopus::Error> { self.encode_to(frame, None) }
/// Encode one mono frame: ordinary voice (`C2S`) when `whisper` is `None`, otherwise a whisper
/// packet to that route only (`C2SWhisper`/`C2SWhisperNew`, see [`crate::whisper::packet`]).
pub fn encode_to(
&mut self, frame: &Frame, whisper: Option<&mut crate::whisper::Route>,
) -> Result<OutPacket, audiopus::Error> {
let len = match self.codec {
TxCodec::OpusVoice => self.encoder.encode(&frame[..], &mut self.out[..])?,
TxCodec::OpusMusic => {
@@ -177,7 +292,11 @@ impl TxEncoder {
self.encoder.encode(&self.stereo[..], &mut self.out[..])?
}
};
Ok(OutAudio::new(&AudioData::C2S { id: 0, codec: self.codec.codec_type(), data: &self.out[..len] }))
let codec = self.codec.codec_type();
Ok(match whisper {
None => OutAudio::new(&AudioData::C2S { id: 0, codec, data: &self.out[..len] }),
Some(route) => crate::whisper::packet(route, codec, &self.out[..len]),
})
}
}
@@ -186,6 +305,11 @@ pub fn end_of_voice(codec: TxCodec) -> OutPacket {
OutAudio::new(&AudioData::C2S { id: 0, codec: codec.codec_type(), data: &[] })
}
/// The empty whisper packet that ends a whisper transmission, addressed to the same route as its audio.
pub fn end_of_whisper(codec: TxCodec, route: &mut crate::whisper::Route) -> OutPacket {
crate::whisper::packet(route, codec.codec_type(), &[])
}
// ---------------------------------------------------------------- receive
pub enum RxEvent {
@@ -201,6 +325,16 @@ pub struct Receiver {
mix: Vec<f32>,
speakers: Vec<u16>,
unsupported_reported: HashSet<u16>,
/// Clients whose current talk spurt reaches us as whisper (`S2CWhisper`).
whisperers: HashSet<u16>,
/// Whisper spurts started since the last [`Receiver::take_whisper_starts`] (official `onWhisperStart`).
whisper_starts: Vec<u16>,
/// Official receive mode "Deny All": incoming whisper audio is dropped locally.
deny_whispers: bool,
/// Scratch for [`Receiver::mix_tapped`]: speakers whose queue last decoded a whisper packet.
whispering_now: Vec<u16>,
/// Per-speaker playback AGC (`voice_dsp.rs`).
dsp: crate::voice_dsp::PlaybackDsp,
}
pub struct Mixed<'a> {
@@ -215,23 +349,73 @@ impl Receiver {
mix: vec![0.0; FRAME_SAMPLES * 2],
speakers: Vec::new(),
unsupported_reported: HashSet::new(),
whisperers: HashSet::new(),
whisper_starts: Vec::new(),
deny_whispers: false,
whispering_now: Vec::new(),
dsp: Default::default(),
}
}
/// Per-speaker playback AGC ("Automatically level the volume of other users", voice_dsp.rs).
pub fn set_playback_agc(&mut self, enabled: bool) { self.dsp.set_agc(enabled); }
/// Drop all speaker state (connection or channel context changed). Returns who was talking.
pub fn reset(&mut self) -> Vec<u16> {
let talking: Vec<u16> = self.handler.get_queues().keys().map(|c| c.0).collect();
self.handler.reset();
// Client ids are recycled by the server; report codec problems afresh.
self.unsupported_reported.clear();
self.whisperers.clear();
self.whisper_starts.clear();
self.dsp.reset();
talking
}
/// Discard queued audio before the server can recycle a departed client's numeric ID.
pub fn remove_client(&mut self, client_id: u16) {
self.handler.get_mut_queues().remove(&ClientId(client_id));
self.unsupported_reported.remove(&client_id);
self.whisperers.remove(&client_id);
self.dsp.remove(client_id);
}
/// Applies the incoming whisper policy. Switching to deny also drops whisper audio already queued;
/// returns the speakers whose queue was removed (they stopped talking).
pub fn set_deny_whispers(&mut self, deny: bool) -> Vec<u16> {
if self.deny_whispers == deny {
return Vec::new();
}
self.deny_whispers = deny;
if !deny {
return Vec::new();
}
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
}
/// Clients who started whispering to us since the last call (deduplicated per talk spurt).
pub fn take_whisper_starts(&mut self) -> std::vec::Drain<'_, u16> { self.whisper_starts.drain(..) }
pub fn handle_packet(&mut self, packet: InAudioBuf) -> RxEvent {
let (from, codec) = match packet.data().data() {
AudioData::S2C { from, codec, .. } | AudioData::S2CWhisper { from, codec, .. } => (*from, *codec),
// tsclientlib's jitter buffer treats a payload of at most one byte as end of stream.
let (from, codec, whisper, end) = match packet.data().data() {
AudioData::S2C { from, codec, data, .. } => (*from, *codec, false, data.len() <= 1),
AudioData::S2CWhisper { from, codec, data, .. } => (*from, *codec, true, data.len() <= 1),
_ => return RxEvent::None,
};
if whisper && self.deny_whispers {
debug!(client = from, "incoming whisper ignored (receive mode: deny all)");
return RxEvent::None;
}
if codec != CodecType::OpusVoice && codec != CodecType::OpusMusic {
return if self.unsupported_reported.insert(from) {
RxEvent::Unsupported { client_id: from, codec }
@@ -239,31 +423,69 @@ impl Receiver {
RxEvent::None
};
}
match self.handler.handle_packet(ClientId(from), packet) {
Ok(Some(id)) => RxEvent::Started(id.0),
Ok(None) => RxEvent::None,
let started = match self.handler.handle_packet(ClientId(from), packet) {
Ok(started) => started,
Err(error) => {
// Late, duplicate or overflowing packets are normal jitter-buffer outcomes.
debug!(%error, client = from, "audio packet not queued");
RxEvent::None
return RxEvent::None;
}
};
if whisper && !end {
if self.whisperers.insert(from) {
self.whisper_starts.push(from);
}
} else if whisper || !end {
// An empty whisper packet ends the whisper spurt; ordinary voice ends whispering.
self.whisperers.remove(&from);
}
started.map_or(RxEvent::None, |id| RxEvent::Started(id.0))
}
/// Pull 20 ms from every speaker's jitter buffer, mix, and downmix stereo to mono into `out`.
pub fn mix(&mut self, out: &mut [i16; FRAME_SAMPLES]) -> Mixed<'_> {
/// Pull 20 ms from every speaker's jitter buffer, apply local gains, and mix to mono.
/// Resolve the current client UID in `gain` each tick: recycled client IDs must never
/// inherit a previous occupant's volume. The resolver returns a linear 0..=MAX_USER_GAIN factor
/// (10^(10/20), from the user's dB modifier).
pub fn mix(&mut self, out: &mut [i16; FRAME_SAMPLES], gain: impl FnMut(u16) -> f32) -> Mixed<'_> {
self.mix_tapped(out, gain, |_, _, _| {})
}
/// [`Receiver::mix`] that also hands every speaker's decoded 20 ms to `tap` before local volume is
/// applied: `(client_id, whisper, interleaved stereo f32)`. `whisper` is whether the speaker's queue
/// last decoded a whisper packet (sampled before this tick's decode).
pub fn mix_tapped(
&mut self, out: &mut [i16; FRAME_SAMPLES], mut gain: impl FnMut(u16) -> f32,
mut tap: impl FnMut(u16, bool, &[f32]),
) -> Mixed<'_> {
self.whispering_now.clear();
for (id, queue) in self.handler.get_mut_queues() {
let value = gain(id.0);
// Keep invalid values out of the float sum, even if a caller bypasses IPC validation.
queue.volume = (if value.is_finite() { value.clamp(0.0, crate::voice_dsp::MAX_USER_GAIN) } else { 1.0 })
* self.dsp.speaker_gain(id.0);
if queue.is_whispering() {
self.whispering_now.push(id.0);
}
}
self.mix.iter_mut().for_each(|s| *s = 0.0);
self.speakers.clear();
let speakers = &mut self.speakers;
let whispering = &self.whispering_now;
let dsp = &mut self.dsp;
let stopped = self.handler.fill_buffer_with_proc(&mut self.mix, |id, data| {
if !data.is_empty() {
speakers.push(id.0);
}
dsp.observe(id.0, data);
tap(id.0, whispering.contains(&id.0), data);
});
for (o, lr) in out.iter_mut().zip(self.mix.chunks_exact(2)) {
let m = (lr[0] + lr[1]) * 0.5;
*o = (m.clamp(-1.0, 1.0) * f32::from(i16::MAX)) as i16;
}
for id in &stopped {
self.whisperers.remove(&id.0);
self.dsp.remove(id.0);
}
Mixed { speakers: &self.speakers, stopped: stopped.into_iter().map(|c| c.0).collect() }
}
}
@@ -316,6 +538,161 @@ 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};
use tsproto_packets::packets::{InPacket, PacketType};
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
for group in [false, true] {
let route = if group { Route::Group { whisper_type: 3, target: 6, target_id: 0 } }
else { Route::Ids { channels: vec![12], clients: vec![7], uids: vec![None] } };
let mut state = Whisper::default();
state.start(4, 9, route);
let mut encoder = TxEncoder::new(codec, 6).unwrap();
let mut rx = Receiver::new();
let mut phase = 0.0;
let mut energy = 0u64;
for id in 0..40u16 {
let packet = encoder.encode_to(&sine(&mut phase, 220.0), state.route_mut(4, 9)).unwrap();
let parsed = InPacket::try_new(Direction::C2S, packet.data()).unwrap();
assert_eq!(parsed.header().packet_type(), PacketType::VoiceWhisper);
let audio = parsed.into_audio().unwrap();
let (format, payload) = match audio.data() {
AudioData::C2SWhisper { codec, channels, clients, data, .. } => {
assert!(!group); assert_eq!(channels, &[12]); assert_eq!(clients, &[7]); (*codec, *data)
},
AudioData::C2SWhisperNew { codec, whisper_type, target, data, .. } => {
assert!(group); assert_eq!((*whisper_type, *target), (3, 6)); (*codec, *data)
},
_ => panic!("whisper must never produce ordinary voice"),
};
let incoming = OutAudio::new(&AudioData::S2CWhisper { id, from: 7, codec: format, data: payload });
rx.handle_packet(InAudioBuf::try_new(Direction::S2C, incoming.into_vec()).unwrap());
let mut out = [0; FRAME_SAMPLES];
rx.mix(&mut out, |_| crate::voice_dsp::MAX_USER_GAIN);
energy += out.iter().map(|s| i64::from(*s).pow(2) as u64).sum::<u64>();
}
assert!(energy > 1_000_000, "real Opus whisper decoded no signal");
assert!(state.stop(4));
assert!(state.route_mut(4, 9).is_none(), "released frames have no route");
rx.set_deny_whispers(true);
let mut out = [1; FRAME_SAMPLES];
rx.mix(&mut out, |_| 1.0);
assert_eq!(out, [0; FRAME_SAMPLES], "deny all clears queued whisper samples");
}
}
}
#[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]
#[ignore = "requires TEAMSPEACH_AUDIT_PCM and TEAMSPEACH_AUDIT_OUT"]
fn captured_speech_quality_matrix() {
use std::io::Write;
let input = std::fs::read(std::env::var("TEAMSPEACH_AUDIT_PCM").unwrap()).unwrap();
assert_eq!(input.len() % FRAME_BYTES, 0);
let dir = std::path::PathBuf::from(std::env::var("TEAMSPEACH_AUDIT_OUT").unwrap());
std::fs::create_dir_all(&dir).unwrap();
let mut reports = Vec::new();
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
for quality in [0, 6, 10] {
let mut enc = TxEncoder::new(codec, quality).unwrap();
let config = serde_json::json!({ "codec": format!("{codec:?}"), "quality": quality,
"bitrate": format!("{:?}", enc.encoder.bitrate().unwrap()), "application": format!("{:?}", enc.encoder.application().unwrap()),
"complexity": enc.encoder.complexity().unwrap(), "lookahead": enc.encoder.lookahead().unwrap(),
"maxBandwidth": format!("{:?}", enc.encoder.max_bandwidth().unwrap()), "signal": format!("{:?}", enc.encoder.signal().unwrap()),
"vbr": enc.encoder.vbr().unwrap(), "constrainedVbr": enc.encoder.vbr_constraint().unwrap(),
"fec": enc.encoder.inband_fec().unwrap(), "dtx": enc.encoder.dtx().unwrap() });
let mut rx = Receiver::new();
let mut file = std::io::BufWriter::new(std::fs::File::create(dir.join(format!("{codec:?}-q{quality}.pcm"))).unwrap());
let mut frame = [0; FRAME_SAMPLES];
let mut decoded = [0; FRAME_SAMPLES];
let mut packets = 0usize;
let mut gate = crate::vad::VoiceGate::new(crate::vad::Sensitivity::Normal);
let mut gate_starts = Vec::new();
let mut gate_sent = 0usize;
for (index, bytes) in input.chunks_exact(FRAME_BYTES).enumerate() {
for (s, b) in frame.iter_mut().zip(bytes.chunks_exact(2)) { *s = i16::from_le_bytes([b[0], b[1]]); }
// Same lifecycle as a channel-context boundary: no preceding speech survives.
if index == 4500 { enc = TxEncoder::new(codec, quality).unwrap(); rx.reset(); gate.reset(); }
match gate.push(&frame) {
crate::vad::Decision::Start => { gate_starts.push(index); gate_sent += 1; }
crate::vad::Decision::Send | crate::vad::Decision::SendAndEnd => gate_sent += 1,
crate::vad::Decision::Hold => {}
}
let packet = enc.encode(&frame).unwrap(); packets += packet.content().len() - 3;
rx.handle_packet(as_s2c(packet, index as u16, 7));
rx.mix(&mut decoded, |_| 1.0);
for sample in decoded { file.write_all(&sample.to_le_bytes()).unwrap(); }
}
file.flush().unwrap();
reports.push(serde_json::json!({ "config": config, "payloadBytes": packets, "frames": input.len()/FRAME_BYTES,
"gateStarts": gate_starts, "gateSentFramesExcludingPreroll": gate_sent, "contextResetFrame": 4500 }));
}
}
std::fs::write(dir.join("codec-matrix.json"), serde_json::to_vec_pretty(&reports).unwrap()).unwrap();
}
#[test]
fn clear_discards_queued_frames_without_counting_drops() {
let q = AudioInQueue::new();
for _ in 0..3 {
q.push(AudioIn::Frame(captured(&q, 1)));
}
q.push(AudioIn::End);
assert_eq!(q.clear(), 3);
assert!(q.pop().is_none());
assert_eq!(q.take_dropped(), 0);
}
#[test]
fn encode_decode_mix_roundtrip_both_codecs() {
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
@@ -331,7 +708,7 @@ mod tests {
assert_eq!(id, 7);
started = true;
}
let mixed = rx.mix(&mut out);
let mixed = rx.mix(&mut out, |_| 1.0);
if !mixed.speakers.is_empty() {
assert_eq!(mixed.speakers, &[7]);
energy += out.iter().map(|s| f64::from(*s).powi(2)).sum::<f64>();
@@ -343,7 +720,7 @@ mod tests {
rx.handle_packet(as_s2c(end_of_voice(codec), 40, 7));
let mut stopped = false;
for _ in 0..20 {
if rx.mix(&mut out).stopped.contains(&7) {
if rx.mix(&mut out, |_| 1.0).stopped.contains(&7) {
stopped = true;
break;
}
@@ -352,10 +729,138 @@ mod tests {
}
}
fn frame(tag: i16) -> AudioIn {
let mut f = Box::new([0i16; FRAME_SAMPLES]);
f[0] = tag;
AudioIn::Frame(f)
/// Real Opus encoders, S2C packet parsing, jitter buffers and decoders; no PCM echo mock.
#[test]
fn controlled_two_speaker_local_volume() {
for codec in [TxCodec::OpusVoice, TxCodec::OpusMusic] {
let mut enc_a = TxEncoder::new(codec, 6).unwrap();
let mut enc_b = TxEncoder::new(codec, 6).unwrap();
let mut phase_a = 0.0;
let mut phase_b = 0.0;
// Identical packets enter each independent real decoder. Solo references retain
// both queues, so startup buffering and packet-loss concealment match exactly.
let mut receivers: [Receiver; 8] = std::array::from_fn(|_| Receiver::new());
let mut frames = [[0i16; FRAME_SAMPLES]; 8];
let mut energy = [0u64; 8];
let mut saturated = 0usize;
let mut max_error = 0i32;
let mut proof_samples = Vec::new();
for sequence in 0..80u16 {
if sequence == 48 {
for receiver in &mut receivers { receiver.reset(); }
}
for (from, encoder, phase, frequency) in [
(7, &mut enc_a, &mut phase_a, 440.0),
(9, &mut enc_b, &mut phase_b, 730.0),
] {
let mut input = sine(phase, frequency);
if sequence >= 64 { for sample in input.iter_mut() { *sample *= 3; } }
let packet = encoder.encode(&input).unwrap();
let bytes = OutAudio::new(&AudioData::S2C {
id: sequence, from, codec: codec.codec_type(), data: &packet.content()[3..],
}).into_vec();
for receiver in &mut receivers {
receiver.handle_packet(InAudioBuf::try_new(Direction::S2C, bytes.clone()).unwrap());
}
}
let changing_gain = match sequence { 0..=15 => 1.0, 16..=31 => 0.0, 32..=47 => 0.5, _ => 1.0 };
let gains = [(1.0, 1.0), (1.0, 0.0), (0.0, 1.0), (0.5, 1.0),
(2.0, 1.0), (f32::NAN, 1.0), (changing_gain, 1.0), (0.0, 0.0)];
for (index, receiver) in receivers.iter_mut().enumerate() {
let (a, b) = gains[index];
receiver.mix(&mut frames[index], |id| if id == 7 { a } else { b });
energy[index] += frames[index].iter().map(|s| i64::from(*s).pow(2) as u64).sum::<u64>();
}
assert_eq!(frames[5], frames[0], "invalid gain cannot poison the mix");
if changing_gain == 0.0 {
assert_eq!(frames[6], frames[2], "muting target must leave the other peer bit-identical");
} else if changing_gain == 1.0 {
assert_eq!(frames[6], frames[0], "100% and restored volume must be bit-identical");
}
for sample in 0..FRAME_SAMPLES {
let a = f32::from(frames[1][sample]);
let b = f32::from(frames[2][sample]);
for (index, gain) in [(0, 1.0), (3, 0.5), (4, 2.0), (5, 1.0), (6, changing_gain)] {
let expected = (a * gain + b).clamp(-32767.0, 32767.0) as i32;
let error = (i32::from(frames[index][sample]) - expected).abs();
max_error = max_error.max(error);
assert!(error <= 3, "{codec:?} frame={sequence} mix={index} sample={sample}: error={error}");
}
assert_eq!(frames[7][sample], 0, "both peers muted must be digital silence");
if frames[4][sample].abs() == i16::MAX { saturated += 1; }
}
if [12, 24, 40, 56, 72].contains(&sequence) {
proof_samples.push(serde_json::json!({
"frame": sequence, "target_gain": changing_gain,
"target_only": &frames[1][200..208], "other_only": &frames[2][200..208],
"actual_mix": &frames[6][200..208], "both_unity": &frames[0][200..208],
}));
}
}
assert!(energy[1] > 1_000_000_000 && energy[2] > 1_000_000_000);
assert_eq!(energy[7], 0);
assert!(saturated > 0, "high-level sum must saturate, not wrap");
println!("LOCAL_VOLUME_PROOF {}", serde_json::json!({
"codec": format!("{codec:?}"), "frames": 80, "max_sample_error": max_error,
"saturated_samples": saturated, "energy": energy, "samples": proof_samples,
}));
}
}
#[test]
fn local_volume_decode_mix_subprocess_smoke() {
// Exercise the real encode/decode/mix proof in an isolated OS subprocess, not a
// server, live microphone, user profile or running desktop application's core.
let (program, prefix) = crate::test_exec::self_invocation();
let output = std::process::Command::new(program).args(prefix)
.args(["--exact", "audio::tests::controlled_two_speaker_local_volume", "--nocapture"])
.output().unwrap();
let stdout = String::from_utf8(output.stdout).unwrap();
assert!(output.status.success(), "child failed: {stdout}\n{}", String::from_utf8_lossy(&output.stderr));
assert_eq!(stdout.matches("LOCAL_VOLUME_PROOF ").count(), 2);
println!("LOCAL_VOLUME_SUBPROCESS {}\n{stdout}", output.status);
}
#[test]
fn removed_client_discards_queued_audio_before_id_reuse() {
let mut rx = Receiver::new();
let mut encoder = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let mut phase = 0.0;
for sequence in 0..4 {
let packet = encoder.encode(&sine(&mut phase, 440.0)).unwrap();
rx.handle_packet(as_s2c(packet, sequence, 7));
}
assert!(rx.handler.get_queues().contains_key(&ClientId(7)));
rx.remove_client(7);
let mut output = [1i16; FRAME_SAMPLES];
assert!(rx.mix(&mut output, |_| 1.0).speakers.is_empty());
assert_eq!(output, [0; FRAME_SAMPLES]);
// Reused ID starts a fresh decoder; the prior talker's queued tone cannot leak.
let mut replacement = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
let packet = replacement.encode(&[0; FRAME_SAMPLES]).unwrap();
let bytes = OutAudio::new(&AudioData::S2C {
id: 0, from: 7, codec: CodecType::OpusVoice, data: &packet.content()[3..],
}).into_vec();
let mut fresh = Receiver::new();
fresh.handle_packet(InAudioBuf::try_new(Direction::S2C, bytes.clone()).unwrap());
assert!(matches!(rx.handle_packet(InAudioBuf::try_new(Direction::S2C, bytes).unwrap()), RxEvent::Started(7)));
rx.mix(&mut output, |_| 1.0);
let mut expected = [0; FRAME_SAMPLES];
fresh.mix(&mut expected, |_| 1.0);
// Lossy Opus silence can contain tiny quantization samples; compare exact real decoding.
assert_eq!(output, expected);
}
fn captured(q: &AudioInQueue, tag: i16) -> CapturedFrame {
let mut pcm = [0i16; FRAME_SAMPLES];
pcm[0] = tag;
CapturedFrame {
pcm,
captured_at: Instant::now(),
connection_generation: q.generation(),
capture_epoch: q.epoch(),
whisper: None,
}
}
#[test]
@@ -365,13 +870,13 @@ mod tests {
q.push(AudioIn::End);
}
assert_eq!(q.len(), 1);
q.push(frame(1));
q.push(AudioIn::Frame(captured(&q, 1)));
for _ in 0..1000 {
q.push(AudioIn::End);
}
assert_eq!(q.len(), 3);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f[0] == 1));
assert!(matches!(q.pop(), Some(AudioIn::Frame(f)) if f.pcm[0] == 1));
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.pop().is_none());
}
@@ -380,7 +885,7 @@ mod tests {
fn alternating_bursts_overflow_stays_bounded_and_terminated() {
let q = AudioInQueue::new();
for i in 0..500i16 {
q.push(frame(i));
q.push(AudioIn::Frame(captured(&q, i)));
q.push(AudioIn::End);
q.push(AudioIn::End);
assert!(q.len() <= TX_QUEUE_ENTRIES, "len {}", q.len());
@@ -393,7 +898,7 @@ mod tests {
while let Some(item) = q.pop() {
match item {
AudioIn::Frame(f) => {
frames.push(f[0]);
frames.push(f.pcm[0]);
prev_end = false;
last_is_end = false;
}
@@ -409,30 +914,149 @@ mod tests {
}
#[test]
fn reset_rearms_unsupported_codec_report() {
fn capture_age_is_inclusive_and_never_accepts_future_frames() {
let q = AudioInQueue::new();
let mut frame = captured(&q, 1);
let now = frame.captured_at;
assert!(q.validate_at(&frame, now));
assert!(q.validate_at(&frame, now + MAX_CAPTURE_AGE));
// Windows Instant arithmetic rounds to the performance-counter resolution, not nanoseconds.
assert!(!q.validate_at(&frame, now + MAX_CAPTURE_AGE + Duration::from_millis(1)));
assert!(!q.validate_at(&frame, now - Duration::from_millis(1)));
frame.captured_at = Instant::now() - Duration::from_millis(600);
assert!(!q.try_push(frame));
let mut future = captured(&q, 2);
future.captured_at += Duration::from_secs(60);
assert!(!q.try_push(future));
assert!(q.pop().is_none());
assert_eq!(q.take_dropped(), 0);
}
#[test]
fn invalidation_revokes_dequeued_frames_and_preserves_one_end() {
let q = AudioInQueue::new();
let frame = captured(&q, 7);
assert!(q.try_push(frame.clone()));
let Some(AudioIn::Frame(dequeued)) = q.pop() else { panic!("missing frame") };
assert!(q.try_push(captured(&q, 8)));
q.push(AudioIn::End);
let epoch = q.invalidate();
assert_eq!(epoch, frame.capture_epoch + 1);
assert!(!q.validate(&dequeued));
assert!(!q.try_push(frame));
assert!(q.with_valid_frame(&dequeued, || panic!("revoked frame sent")).is_none());
q.invalidate();
q.push(AudioIn::End);
assert_eq!(q.len(), 1);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.try_push(captured(&q, 9)));
assert!(matches!(q.pop(), Some(AudioIn::Frame(frame)) if frame.pcm[0] == 9));
assert_eq!(q.take_dropped(), 0);
}
#[test]
fn generation_boundary_revokes_epoch_and_rejects_wrong_tags() {
let q = AudioInQueue::new();
let old = captured(&q, 1);
q.set_generation(7);
assert_eq!(q.generation(), 7);
assert_eq!(q.epoch(), old.capture_epoch + 1);
assert!(!q.validate(&old));
let mut wrong_generation = captured(&q, 2);
wrong_generation.connection_generation = 6;
assert!(!q.try_push(wrong_generation));
let mut wrong_epoch = captured(&q, 3);
wrong_epoch.capture_epoch += 1;
assert!(!q.try_push(wrong_epoch));
let epoch = q.epoch();
q.set_generation(7);
assert_eq!(q.epoch(), epoch + 1);
assert!(matches!(q.pop(), Some(AudioIn::End)));
assert!(q.pop().is_none());
}
#[test]
fn whisper_envelope_survives_queue_without_normal_voice_fallback() {
let q = AudioInQueue::new();
let mut frame = captured(&q, 4);
frame.whisper = Some(42);
let captured_at = frame.captured_at;
assert!(q.try_push(frame));
let Some(AudioIn::Frame(frame)) = q.pop() else { panic!("missing whisper frame") };
assert_eq!(frame.whisper, Some(42));
assert_eq!(frame.captured_at, captured_at);
assert_eq!(frame.pcm[0], 4);
}
#[test]
fn send_guard_serializes_invalidation_and_rechecks_capture_age() {
let q = AudioInQueue::new();
let frame = captured(&q, 1);
let order = AtomicU64::new(0);
std::thread::scope(|scope| {
let q = &q;
let frame = &frame;
let order = &order;
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let sender = scope.spawn(move || {
q.with_valid_frame(frame, || {
assert!(q.items.try_lock().is_err(), "send must exclude invalidation");
entered_tx.send(()).unwrap();
release_rx.recv().unwrap();
assert_eq!(order.fetch_add(1, Ordering::SeqCst), 0);
})
});
entered_rx.recv().unwrap();
let invalidator = scope.spawn(move || {
q.invalidate();
assert_eq!(order.fetch_add(1, Ordering::SeqCst), 1);
});
release_tx.send(()).unwrap();
assert!(sender.join().unwrap().is_some());
invalidator.join().unwrap();
});
assert!(q.with_valid_frame(&frame, || panic!("old send after invalidation")).is_none());
let mut expired = captured(&q, 2);
expired.captured_at -= Duration::from_millis(600);
assert!(q.with_valid_frame(&expired, || panic!("expired frame encoded")).is_none());
}
#[test]
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] });
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(speex()), RxEvent::Unsupported { client_id: 9, .. }));
assert!(matches!(rx.handle_packet(speex()), RxEvent::None));
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();
assert!(matches!(rx.handle_packet(speex()), RxEvent::Unsupported { client_id: 9, .. }));
}
}
#[test]
fn queue_drops_oldest_frames() {
let q = AudioInQueue::new();
for i in 0..(TX_QUEUE_FRAMES + 3) {
let mut f = Box::new([0i16; FRAME_SAMPLES]);
f[0] = i as i16;
q.push(AudioIn::Frame(f));
let mut pcm = [0i16; FRAME_SAMPLES];
pcm[0] = i as i16;
q.try_push(CapturedFrame { pcm, captured_at: Instant::now(), connection_generation: q.generation(), capture_epoch: q.epoch(), whisper: None });
}
q.push(AudioIn::End);
assert_eq!(q.take_dropped(), 3);
match q.pop() {
Some(AudioIn::Frame(f)) => assert_eq!(f[0], 3),
Some(AudioIn::Frame(f)) => assert_eq!(f.pcm[0], 3),
_ => panic!(),
}
let mut n = 1;
+196
View File
@@ -0,0 +1,196 @@
//! `server_event` events: client/channel/server changes with reason and invoker, built from the
//! raw notifications (tsclientlib's book keeps neither kick messages nor invokers of most changes).
//! Used for the official "Server Events" log and notification policies (`docs/bridge.md` §5).
use serde_json::{json, Value};
use crate::rawcmd::RawNotification;
use crate::snapshot::RawExtras;
/// Extra notifications copied raw for events (the others are tapped already for the snapshot).
pub fn tapped(name: &[u8]) -> bool {
matches!(name, b"notifyclientmoved" | b"notifychannelmoved" | b"notifyserveredited")
}
/// Pinned `Enums.toml` `Reason` variants in declaration order (wire value = index).
const REASONS: [&str; 12] = [
"none", "moved", "subscription", "lost_connection", "kick_channel", "kick_server", "ban",
"server_stop", "disconnect", "channel_update", "channel_edit", "server_shutdown",
];
fn num<T: std::str::FromStr>(row: &crate::menu::Row, key: &str) -> Option<T> { row.get(key).and_then(|v| v.parse().ok()) }
fn invoker(row: &crate::menu::Row) -> Value {
match num::<u16>(row, "invokerid") {
Some(id) => json!({
"id": id,
"uid": row.get("invokeruid").filter(|u| !u.is_empty()),
"name": row.get("invokername").cloned().unwrap_or_default(),
}),
None => Value::Null,
}
}
fn reason(row: &crate::menu::Row) -> (Value, Value) {
match num::<usize>(row, "reasonid") {
Some(id) => (json!(id), REASONS.get(id).map_or(Value::Null, |r| json!(r))),
None => (Value::Null, Value::Null),
}
}
fn base(kind: &str, row: &crate::menu::Row) -> Value {
let (reason_id, reason) = reason(row);
json!({
"event": "server_event",
"kind": kind,
"reason_id": reason_id,
"reason": reason,
"invoker": invoker(row),
"message": row.get("reasonmsg").filter(|m| !m.is_empty()),
})
}
/// Events for one tapped notification. Must run BEFORE `extras.apply(raw)` so clients that leave
/// and channels that are deleted still have their last known labels.
pub fn from_raw(raw: &RawNotification, extras: &RawExtras, own_client: Option<u16>) -> Vec<Value> {
let mut out = Vec::new();
// Shared arguments (`ctid`, `reasonid`, invoker…) may only be present in the first entry.
let first = raw.items.first();
let shared = |row: &crate::menu::Row, key: &str| row.get(key).or_else(|| first.and_then(|f| f.get(key))).cloned();
for row in &raw.items {
let mut merged = row.clone();
for key in ["reasonid", "invokerid", "invokername", "invokeruid", "reasonmsg", "ctid", "cfid", "bantime"] {
if let Some(v) = shared(row, key) { merged.entry(key.to_owned()).or_insert(v); }
}
let row = &merged;
let client = |kind: &str, clid: u16| {
let label = extras.client_label(clid);
let mut v = base(kind, row);
v["client_id"] = json!(clid);
v["uid"] = json!(row.get("client_unique_identifier").cloned().or(label.uid));
v["nickname"] = json!(row.get("client_nickname").cloned().or(label.name));
v["is_self"] = json!(own_client == Some(clid));
(v, label.channel)
};
let channel = |kind: &str, cid: u64| {
let label = extras.channel_label(cid);
let mut v = base(kind, row);
v["channel_id"] = json!(cid);
v["name"] = json!(row.get("channel_name").cloned().or(label.name));
v["parent_id"] = json!(num::<u64>(row, "cpid").or(label.channel));
v
};
match raw.name.as_str() {
"notifycliententerview" => {
let Some(clid) = num(row, "clid") else { continue };
let (mut v, _) = client("client_enter", clid);
v["from_channel_id"] = json!(num::<u64>(row, "cfid").filter(|c| *c != 0));
v["to_channel_id"] = json!(num::<u64>(row, "ctid"));
out.push(v);
}
"notifyclientleftview" => {
let Some(clid) = num(row, "clid") else { continue };
let (mut v, last) = client("client_leave", clid);
v["from_channel_id"] = json!(num::<u64>(row, "cfid").filter(|c| *c != 0).or(last));
v["to_channel_id"] = json!(num::<u64>(row, "ctid").filter(|c| *c != 0));
v["ban_time_s"] = json!(num::<u64>(row, "bantime"));
out.push(v);
}
"notifyclientmoved" => {
let Some(clid) = num(row, "clid") else { continue };
let (mut v, last) = client("client_move", clid);
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);
}
"notifyclientupdated" => {
let Some(clid) = num::<u16>(row, "clid") else { continue };
if let Some(flag) = row.get("client_talk_request") {
let (mut v, _) = client("talk_request", clid);
v["requested"] = json!(flag != "0");
v["message"] = json!(row.get("client_talk_request_msg").filter(|m| !m.is_empty()));
out.push(v);
}
if let Some(flag) = row.get("client_is_talker") {
let (mut v, _) = client("talker_changed", clid);
v["is_talker"] = json!(flag == "1");
out.push(v);
}
}
"notifychannelcreated" => if let Some(cid) = num(row, "cid") { out.push(channel("channel_created", cid)) },
// Description replies (`channelgetdescription`) carry no invoker; they are not edits.
"notifychanneledited" if row.contains_key("invokerid") => if let Some(cid) = num(row, "cid") { out.push(channel("channel_edited", cid)) },
"notifychanneldeleted" => if let Some(cid) = num(row, "cid") { out.push(channel("channel_deleted", cid)) },
"notifychannelmoved" => if let Some(cid) = num(row, "cid") {
let mut v = channel("channel_moved", cid);
v["from_parent_id"] = json!(extras.channel_label(cid).channel);
v["order"] = json!(num::<u64>(row, "order"));
out.push(v);
},
"notifyserveredited" => {
out.push(base("server_edited", row));
break;
}
_ => {}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rawcmd::parse;
#[test]
fn leave_and_kick_keep_last_label_and_reason() {
let mut x = RawExtras::default();
x.apply(&parse(br"notifycliententerview cfid=0 ctid=5 reasonid=0 clid=9 client_nickname=Ann client_unique_identifier=u9=").unwrap());
let enter = from_raw(&parse(br"notifycliententerview cfid=0 ctid=5 reasonid=0 clid=10 client_nickname=Bo").unwrap(), &x, Some(10));
assert_eq!(enter[0]["kind"], "client_enter");
assert_eq!(enter[0]["is_self"], true);
let moved = parse(br"notifyclientmoved ctid=6 reasonid=1 invokerid=3 invokername=Mod invokeruid=m= clid=9").unwrap();
let ev = from_raw(&moved, &x, Some(10));
assert_eq!((ev[0]["from_channel_id"].as_u64(), ev[0]["to_channel_id"].as_u64()), (Some(5), Some(6)));
assert_eq!(ev[0]["reason"], "moved");
assert_eq!(ev[0]["invoker"]["name"], "Mod");
x.apply(&moved);
let kick = parse(br"notifyclientleftview cfid=6 ctid=0 reasonid=5 invokerid=3 invokername=Mod reasonmsg=bye clid=9").unwrap();
let ev = from_raw(&kick, &x, Some(10));
assert_eq!(ev[0]["kind"], "client_leave");
assert_eq!(ev[0]["nickname"], "Ann");
assert_eq!(ev[0]["uid"], "u9=");
assert_eq!(ev[0]["reason"], "kick_server");
assert_eq!(ev[0]["message"], "bye");
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();
x.apply(&parse(br"channellist cid=4 cpid=0 channel_name=Old").unwrap());
let del = from_raw(&parse(br"notifychanneldeleted cid=4 invokerid=1 invokername=A").unwrap(), &x, None);
assert_eq!((del[0]["kind"].as_str(), del[0]["name"].as_str()), (Some("channel_deleted"), Some("Old")));
assert!(from_raw(&parse(br"notifychanneledited cid=4 reasonid=10 channel_description=x").unwrap(), &x, None).is_empty());
let talk = from_raw(&parse(br"notifyclientupdated clid=2 client_talk_request=1 client_talk_request_msg=pls").unwrap(), &x, None);
assert_eq!((talk[0]["kind"].as_str(), talk[0]["requested"].as_bool(), talk[0]["message"].as_str()), (Some("talk_request"), Some(true), Some("pls")));
let granted = from_raw(&parse(br"notifyclientupdated clid=2 client_is_talker=1 invokerid=1 invokername=A").unwrap(), &x, None);
assert_eq!(granted[0]["is_talker"], true);
assert!(from_raw(&parse(br"notifyclientupdated clid=2 client_input_muted=1").unwrap(), &x, None).is_empty());
}
}
File diff suppressed because it is too large. Load diff
+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();
}
}
+935
View File
@@ -0,0 +1,935 @@
//! Session integration for the channel file browser (`file_transfer`).
//!
//! Hooks called from `session.rs`: `files_request`, `files_result`, `files_raw`,
//! `files_download`, `files_upload`, `files_failed`, `files_fail_all`, `files_tick`.
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
use futures::FutureExt;
use tsclientlib::{FileDownloadResult, FileUploadResult};
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()) }
}
fn internal(e: impl std::fmt::Display) -> ErrorObj { ErrorObj::new(ErrorCode::Internal, e.to_string()) }
fn not_active(transfer_id: u32) -> ErrorObj { ErrorObj::new(ErrorCode::NotFound, format!("file transfer {transfer_id} is not active")) }
fn ts_id(e: &tsclientlib::Error) -> Option<u32> {
match e {
tsclientlib::Error::CommandError(ce) => ce.error.to_u32(),
_ => None,
}
}
/// Error of a failed transfer stream/status (`FiletransferFailed`).
fn stream_error(e: &tsclientlib::Error) -> ErrorObj {
match e {
tsclientlib::Error::FiletransferIo(_) => ErrorObj::new(ErrorCode::Io, e.to_string()),
_ => lib_error(ErrorCode::ServerError, e),
}
}
/// Server error for a failed `ftinit*`; "file already exists" becomes `file_exists`.
fn init_error(e: &CommandError, name: &str) -> ErrorObj {
let err = command_error(e);
if e.error.to_u32() == Some(ft::TS_FILE_ALREADY_EXISTS) {
let mut exists = ft::exists_error(name);
exists.ts_error = err.ts_error;
return exists;
}
err
}
fn channel_known(c: &Conn, channel_id: u64) -> Result<(), ErrorObj> {
let book = c.con.get_state().map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
if !book.channels.contains_key(&ChannelId(channel_id)) {
return Err(ErrorObj::new(ErrorCode::NotFound, format!("channel {channel_id} is not visible")));
}
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
/// pauseCancelTransfer for a PAUSED item: its stream is gone, and deleting by path later could
/// remove a file someone else stored there meanwhile, so the server partial stays.
fn send_stop(c: &mut Conn, server_ftid: u16, direction: Direction, keep: bool) {
let delete = if direction == Direction::Upload && !keep { "1" } else { "0" };
let cmd = menu::command("ftstop", &[("serverftfid", server_ftid.to_string()), ("delete", delete.into())]);
match c.send(cmd) {
Ok(handle) => {
c.files.stops.insert(handle, ());
}
Err(e) => warn!(%e, "ftstop could not be sent"),
}
}
/// Retire an ftid: it keeps catching late grants and statuses; a granted one is stopped.
fn release(c: &mut Conn, ftid: u16, server_ftid: Option<u16>, direction: Direction, keep: bool) {
c.files.tombstones.insert(ftid, Tombstone { since: Instant::now(), server_ftid, direction, keep });
if let Some(server_ftid) = server_ftid {
send_stop(c, server_ftid, direction, keep);
}
}
/// 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);
}
drop(t);
}
/// Official pauseCancelTransfer(delete=false). A starting transfer, or one whose stream broke and
/// still holds its partial, is paused at once (the ftid is retired with `delete=0`); a running
/// stream is asked to halt at its next chunk and becomes `paused` in `files_tick`. Returns the
/// `paused` event when the pause is immediate.
fn halt(c: &mut Conn, i: usize) -> Option<Value> {
let t = &mut c.files.transfers[i];
match std::mem::replace(&mut t.stage, Stage::Paused) {
Stage::Running { ftid, task, halt } => {
halt.send_replace(true);
t.stage = Stage::Pausing { ftid, task, since: Instant::now() };
None
}
stage @ (Stage::Init { .. } | Stage::Lost { .. }) => {
t.stage = stage;
let ft::Interrupt::PausedNow { ftid } = t.interrupt() else { unreachable!("starting/broken transfers pause at once") };
let (server_ftid, direction) = (t.server_ftid.take(), t.direction);
t.reported = t.progress.load(Ordering::Relaxed);
let event = t.event("paused", None);
release(c, ftid, server_ftid, direction, true);
Some(event)
}
other => {
t.stage = other;
None
}
}
}
/// Send `ftinit*` for transfer `i` now. `resume` continues a paused transfer (official
/// 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);
let cmd = init_command(t.direction, ftid, t.channel_id, &t.path, &t.cpw, t.total, t.overwrite, resume_at);
match c.send(cmd) {
Ok(handle) => {
c.files.inits.insert(handle, ftid);
c.files.start_seq += 1;
let started = c.files.start_seq;
let t = &mut c.files.transfers[i];
t.stage = Stage::Init { ftid, since: Instant::now() };
t.started = started;
t.interrupted = false;
Ok(t.event("starting", None))
}
Err(e) => {
let err = lib_error(ErrorCode::NotConnected, &e);
let t = c.files.transfers.remove(i);
Err((t.event("failed", Some(&err)), err))
}
}
}
/// `ftdeletefile` for validated paths (channel 0: server icons under their classic wire name).
fn delete_command(channel_id: u64, hashed_cpw: &str, paths: &[String]) -> OutCommand {
let mut cmd = menu::command("ftdeletefile", &[("cid", channel_id.to_string()), ("cpw", hashed_cpw.to_owned())]);
for (i, path) in paths.iter().enumerate() {
if i > 0 {
cmd.start_new_part();
}
cmd.write_arg("name", &ft::wire_name(channel_id, path));
}
cmd
}
/// `ftinitdownload` / `ftinitupload` for a queued transfer. Channel 0 icons are listed under
/// `/icons/` but transferred as `/icon_<id>`. `resume` holds a paused download's kept byte count
/// (any value marks an upload resume, which the server answers with its own seek position).
#[allow(clippy::too_many_arguments)]
fn init_command(direction: Direction, ftid: u16, channel_id: u64, path: &str, hashed_cpw: &str, total: u64, overwrite: bool, resume: Option<u64>) -> OutCommand {
let mut args = vec![
("clientftfid", ftid.to_string()),
("name", ft::wire_name(channel_id, path).to_owned()),
("cid", channel_id.to_string()),
("cpw", hashed_cpw.to_owned()),
];
match direction {
Direction::Download => {
args.extend([("seekpos", resume.unwrap_or(0).to_string()), ("proto", "1".to_owned())]);
menu::command("ftinitdownload", &args)
}
Direction::Upload => {
// Overwrite excludes resume (TS error file_overwrite_excludes_resume); the official
// client passes overwrite=!resume.
let (overwrite, resume) = if resume.is_some() { (false, true) } else { (overwrite, false) };
args.extend([
("size", total.to_string()),
("overwrite", if overwrite { "1" } else { "0" }.to_owned()),
("resume", if resume { "1" } else { "0" }.to_owned()),
("proto", "1".to_owned()),
]);
menu::command("ftinitupload", &args)
}
}
}
impl Session {
pub(super) async fn files_request(&mut self, id: &str, request: Request) -> Result<Option<Value>, ErrorObj> {
if matches!(&request, Request::Mkdir { .. } | Request::Rename { .. } | Request::Delete { .. } | Request::FetchImage { .. }) {
self.connected_conn()?.files.require_legacy()?;
}
match request {
Request::Config { download_slots, upload_slots, download_limit, upload_limit } => {
let c = self.connected_conn()?;
let changed = c.files.slots != Some([download_slots, upload_slots]);
c.files.slots = Some([download_slots, upload_slots]);
c.files.download_rate.set(download_limit);
c.files.upload_rate.set(upload_limit);
// 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() {
if let Some(i) = c.files.index_of_id(transfer_id) {
events.extend(halt(c, i));
}
}
}
for e in events {
self.out.json(&e).await;
}
Ok(Some(json!({})))
}
Request::Pause { transfer_id } => {
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"));
}
if !matches!(t.stage, Stage::Init { .. } | Stage::Running { .. } | Stage::Lost { .. }) {
return Err(menu::bad("only a starting or running transfer can be paused"));
}
if let Some(e) = halt(c, i) {
self.out.json(&e).await;
}
Ok(Some(json!({ "transfer_id": transfer_id, "pausing": true })))
}
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 = 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::new(id, channel_id, path, backend));
Ok(None)
}
Request::Mkdir { channel_id, path, password } => {
let cmd = menu::command("ftcreatedir", &[("cid", channel_id.to_string()), ("cpw", cpw(&password)), ("dirname", path)]);
self.files_simple(id, channel_id, cmd)
}
Request::Rename { channel_id, password, from, to, target } => {
let mut args = vec![("cid", channel_id.to_string()), ("cpw", cpw(&password))];
if let Some((tcid, tpw)) = &target {
self.connected_conn().and_then(|c| channel_known(c, *tcid))?;
args.push(("tcid", tcid.to_string()));
args.push(("tcpw", cpw(tpw)));
}
args.push(("oldname", from));
args.push(("newname", to));
self.files_simple(id, channel_id, menu::command("ftrenamefile", &args))
}
Request::Delete { channel_id, password, paths } => {
let cmd = delete_command(channel_id, &cpw(&password), &paths);
self.files_simple(id, channel_id, cmd)
}
Request::Download { channel_id, password, path, dest_dir, subdirs, overwrite } => {
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(backend, Direction::Download, channel_id, path, &password, overwrite, Local::Download { dir, name, overwrite, partial: None }, 0)
}
Request::Upload { channel_id, password, path, source, overwrite } => {
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());
(file, size, modified)
})
})
.await
.map_err(internal)??;
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 } => {
self.connected_conn().and_then(|c| channel_known(c, channel_id))?;
self.fetch_media(id, MediaKind::ChannelFile { channel_id, path }).await
}
Request::Transfers => {
let c = self.connected_conn()?;
let transfers: Vec<Value> = c.files.transfers.iter().map(|t| t.event(t.state(), None)).collect();
Ok(Some(json!({ "transfers": transfers, "storage": c.files.storage() })))
}
}
}
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.
if channel_id != 0 { channel_known(c, channel_id)?; }
let handle = c.send(cmd).map_err(|e| lib_error(ErrorCode::NotConnected, &e))?;
c.files.simple.insert(handle, id.into());
Ok(None)
}
/// Queue a transfer; it is started by `files_tick`, so the answer precedes its events.
#[allow(clippy::too_many_arguments)]
fn files_enqueue(
&mut self,
backend: ListBackend,
direction: Direction,
channel_id: u64,
path: String,
password: &str,
overwrite: bool,
local: Local,
total: u64,
) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
if c.files.transfers.len() >= ft::MAX_TRANSFERS {
return Err(menu::bad("too many file transfers are queued"));
}
let id = c.files.next_transfer_id();
let now = Instant::now();
let t = Transfer {
id,
backend,
direction,
channel_id,
path,
cpw: cpw(password),
overwrite,
local,
total,
s3_total: None,
stage: Stage::Queued,
server_ftid: None,
confirmed: false,
progress: Arc::new(AtomicU64::new(0)),
commit: Arc::default(),
reported: 0,
seen: 0,
last_change: now,
last_emit: now,
started: 0,
interrupted: false,
granted: false,
};
let mut result = t.event("queued", None);
result.as_object_mut().expect("object").remove("event");
c.files.transfers.push(t);
Ok(Some(result))
}
async fn files_cancel(&mut self, transfer_id: u32) -> Result<Option<Value>, ErrorObj> {
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 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 !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);
let event = t.event("cancelled", Some(&ft::cancelled()));
retire(c, t);
self.out.json(&event).await;
Ok(Some(json!({ "transfer_id": transfer_id, "cancelled": true })))
}
/// Official resumeTransfers (paused) / forceStartTransfer (queued): make space in the channel by
/// pausing its earliest-started transfers, then start this one now, outside the queue.
async fn files_resume(&mut self, transfer_id: u32) -> Result<Option<Value>, ErrorObj> {
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"));
}
let resume = match t.stage {
Stage::Paused => true,
Stage::Queued => false,
_ => return Err(menu::bad("only a paused or queued transfer can be started")),
};
c.files.require_legacy()?;
let (direction, channel_id) = (t.direction, t.channel_id);
let mut events = Vec::new();
for other in c.files.make_space(direction, channel_id) {
if let Some(j) = c.files.index_of_id(other) {
events.extend(halt(c, j));
}
}
let i = c.files.index_of_id(transfer_id).expect("halting others keeps this transfer");
let started = start(c, i, resume);
let result = match started {
Ok(event) => {
events.push(event);
Ok(Some(json!({ "transfer_id": transfer_id, "state": "starting" })))
}
Err((event, err)) => {
events.push(event);
Err(err)
}
};
for e in events {
self.out.json(&e).await;
}
result
}
/// Start queued transfers while their channel is below its limit.
async fn files_pump(&mut self) {
let mut events = Vec::new();
if let Some(c) = self.conn.as_mut().filter(|c| c.connected()) {
for direction in [Direction::Download, Direction::Upload] {
while let Some(i) = c.files.next_startable(direction) {
events.push(start(c, i, false).unwrap_or_else(|(event, _)| event));
}
}
}
for e in events {
self.out.json(&e).await;
}
}
async fn files_answer_list(&mut self, handle: u16) {
let Some(c) = &mut self.conn else { return };
let Some(job) = c.files.lists.remove(&handle) else { return };
let hints = c
.con
.get_state()
.ok()
.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, s3), storage) {
Ok(v) => self.out.ok(&req, v).await,
Err(e) => self.out.err(&req, e).await,
}
}
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) {
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 ready {
self.files_answer_list(handle).await;
}
return;
}
if let Some(req) = c.files.simple.remove(&handle) {
match res {
Ok(()) => self.out.ok(&req, json!({})).await,
Err(e) => self.out.err(&req, command_error(&e)).await,
}
return;
}
if let Some(ftid) = c.files.inits.remove(&handle) {
let Err(e) = res else { return };
if c.files.tombstones.remove(&ftid).is_some() {
return;
}
if let Some(i) = c.files.index_of_ftid(ftid) {
let t = c.files.transfers.remove(i);
let event = t.event("failed", Some(&init_error(&e, ft::file_name(&t.path))));
drop(t);
self.out.json(&event).await;
}
return;
}
if c.files.stops.remove(&handle).is_some() {
if let Err(e) = res {
debug!(error = ?e.error, "ftstop rejected");
}
}
}
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) {
self.files_answer_list(handle).await;
}
}
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) {
drop(result);
if let Some(server_ftid) = tomb.server_ftid {
send_stop(c, server_ftid, tomb.direction, tomb.keep);
}
return None;
}
let Some(i) = c.files.index_of_ftid(ftid) else { return Some(result) };
let t = &mut c.files.transfers[i];
let (Stage::Init { .. }, Local::Download { dir, name, overwrite, partial }) = (&t.stage, &mut t.local) else {
warn!(ftid, "download grant for a transfer that is not waiting for one");
return self.files_refuse_grant(i, ErrorObj::new(ErrorCode::ServerError, "server granted an unexpected transfer")).await;
};
let resume = partial.take();
if let Some(p) = &resume {
// Taken as the whole file size (the server then sends the bytes after seekpos); not
// verified against a live server. Only a size change is observable: the legacy protocol
// offers no content identity, so a same-size replacement on the server is not detected.
let problem = if result.size != t.total || p.written > result.size {
Some("the server file size changed while the download was paused")
} else if !p.intact() {
Some("the paused download file was changed or removed")
} else {
None
};
if let Some(problem) = problem {
// Dropping `resume` deletes the partial only while it is still our file.
drop(resume);
return self.files_refuse_grant(i, ErrorObj::new(ErrorCode::Io, problem)).await;
}
}
let (dir, name, overwrite) = (dir.clone(), name.clone(), *overwrite);
t.total = result.size;
let (halt, halted) = tokio::sync::watch::channel(false);
let task = tokio::spawn(ft::download(
result.stream,
result.size,
t.id,
dir,
name,
overwrite,
resume,
t.progress.clone(),
t.commit.clone(),
c.files.download_rate.clone(),
halted,
));
t.stage = Stage::Running { ftid, task, halt };
t.granted = true;
t.last_change = Instant::now();
let event = t.event("running", None);
self.out.json(&event).await;
None
}
pub(super) async fn files_upload(&mut self, ftid: u16, result: FileUploadResult) -> Option<FileUploadResult> {
let Some(c) = &mut self.conn else { return Some(result) };
if let Some(tomb) = c.files.tombstones.remove(&ftid) {
drop(result);
if let Some(server_ftid) = tomb.server_ftid {
send_stop(c, server_ftid, tomb.direction, tomb.keep);
}
return None;
}
let Some(i) = c.files.index_of_ftid(ftid) else { return Some(result) };
let t = &mut c.files.transfers[i];
// The open source handle stays with the transfer for a later resume; the stream reads a
// duplicate. Its length and modification time must still be the ones seen when picked.
let file = match (&t.stage, &t.local) {
(Stage::Init { .. }, Local::Upload { file: Some(file), size, modified }) => Some(
ft::upload_source_unchanged(file, *size, *modified).and_then(|()| {
file.try_clone().map_err(|e| ErrorObj::new(ErrorCode::Io, format!("cannot read the file: {e}")))
}),
),
_ => None,
};
let file = match file {
Some(Ok(file)) => file,
Some(Err(e)) => return self.files_refuse_grant(i, e).await,
None => {
warn!(ftid, "upload grant for a transfer that is not waiting for one");
return self.files_refuse_grant(i, ErrorObj::new(ErrorCode::ServerError, "server granted an unexpected transfer")).await;
}
};
let t = &mut c.files.transfers[i];
let (halt, halted) = tokio::sync::watch::channel(false);
let task = tokio::spawn(ft::upload(result.stream, file, t.total, result.seek_position, t.progress.clone(), c.files.upload_rate.clone(), halted));
t.stage = Stage::Running { ftid, task, halt };
t.granted = true;
t.last_change = Instant::now();
let event = t.event("running", None);
self.out.json(&event).await;
None
}
/// Fail transfer `i` whose grant cannot be used; the granted server transfer is stopped. The
/// stream in the grant result was already dropped by the caller or is dropped here.
async fn files_refuse_grant<R>(&mut self, i: usize, error: ErrorObj) -> Option<R> {
let Some(c) = &mut self.conn else { return None };
let t = c.files.transfers.remove(i);
let event = t.event("failed", Some(&error));
retire(c, t);
self.out.json(&event).await;
None
}
pub(super) async fn files_failed(&mut self, ftid: u16, err: tsclientlib::Error) -> Option<tsclientlib::Error> {
let Some(c) = &mut self.conn else { return Some(err) };
if c.files.tombstones.remove(&ftid).is_some() {
return None;
}
let Some(i) = c.files.index_of_ftid(ftid) else { return Some(err) };
if ts_id(&err) == Some(ft::TS_FILE_TRANSFER_INTERRUPTED) {
// Official doFile* callbacks: FileTransferInterrupted pauses the item, keeping its partial.
let t = &mut c.files.transfers[i];
match t.interrupt() {
ft::Interrupt::PausedNow { ftid } => {
let (server_ftid, direction) = (t.server_ftid.take(), t.direction);
t.reported = t.progress.load(Ordering::Relaxed);
let event = t.event("paused", None);
release(c, ftid, server_ftid, direction, true);
self.out.json(&event).await;
return None;
}
ft::Interrupt::Halting | ft::Interrupt::Ignore => return None,
// Server icons cannot be resumed: fail as before pause support.
ft::Interrupt::Fail => {}
}
}
if ts_id(&err) == Some(ft::TS_FILE_TRANSFER_COMPLETE) {
let t = &mut c.files.transfers[i];
t.confirmed = true;
if matches!(t.stage, Stage::Confirming { .. }) {
let t = c.files.transfers.remove(i);
let event = t.event("done", None);
drop(t);
self.out.json(&event).await;
}
return None;
}
let t = c.files.transfers.remove(i);
let event = t.event("failed", Some(&stream_error(&err)));
drop(t);
self.out.json(&event).await;
None
}
/// 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 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 event in events {
self.out.json(&event).await;
}
}
pub(super) async fn files_tick(&mut self) {
let now = Instant::now();
let mut events = Vec::new();
let mut answers = Vec::new();
{
let Some(c) = &mut self.conn else { return };
let late: Vec<u16> = c.files.lists.iter().filter(|(_, j)| now - j.started >= ft::LIST_DEADLINE).map(|(h, _)| *h).collect();
for h in late {
let job = c.files.lists.remove(&h).expect("present");
let msg = if job.result_ok { "server did not finish the file list" } else { "server did not answer the file list request" };
answers.push((job.req, ErrorObj::new(ErrorCode::ServerError, msg)));
}
c.files.tombstones.retain(|_, t| now - t.since < ft::TOMBSTONE_TTL);
let mut i = 0;
while i < c.files.transfers.len() {
let t = &mut c.files.transfers[i];
let bytes = t.progress.load(Ordering::Relaxed);
if bytes != t.seen {
t.seen = bytes;
t.last_change = now;
}
let finished = match &mut t.stage {
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>),
Keep,
}
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,
Some(Ok(Ended::Complete { .. })) => {
let ftid = t.ftid().expect("running transfer has an ftid");
t.stage = Stage::Confirming { ftid, since: now };
Outcome::Keep
}
None => match &t.stage {
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"))
}
Stage::Pausing { since, .. } if now - *since >= ft::STALL_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::Io, "file transfer did not pause"))
}
// No interrupted status arrived for the broken stream: it failed.
Stage::Lost { since, error, .. } if now - *since >= ft::INTERRUPT_GRACE => Outcome::Failed(error.clone()),
Stage::Confirming { .. } if t.confirmed => Outcome::Done,
Stage::Confirming { since, .. } if now - *since >= ft::CONFIRM_DEADLINE => {
Outcome::Failed(ErrorObj::new(ErrorCode::ServerError, "server did not confirm the upload"))
}
_ => Outcome::Keep,
},
};
match outcome {
Outcome::Done => {
let t = c.files.transfers.remove(i);
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 { .. }
| Stage::S3Init { .. } | Stage::S3Confirming { .. });
if ended {
drop(t);
} else {
retire(c, t);
}
}
Outcome::Stopped(kept, lost) => {
// A halt stopped at a chunk boundary, or the stream broke after an interrupted
// status: stop the server side with delete=0 and keep the partial file
// (download) / server partial (upload) for resume. A break without that
// status waits in `Lost` for it; a server icon's break fails at once.
let t = &mut c.files.transfers[i];
let ftid = t.ftid().expect("a stream task belongs to an ftid");
match t.stream_stopped(kept, lost, now) {
ft::Stopped::Paused => {
let (server_ftid, direction) = (t.server_ftid.take(), t.direction);
t.reported = t.progress.load(Ordering::Relaxed);
events.push(t.event("paused", None));
release(c, ftid, server_ftid, direction, true);
i += 1;
}
ft::Stopped::Waiting => i += 1,
ft::Stopped::Failed(e) => {
let t = c.files.transfers.remove(i);
events.push(t.event("failed", Some(&e)));
retire(c, t);
}
}
}
Outcome::Keep => {
let t = &mut c.files.transfers[i];
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));
}
i += 1;
}
}
}
}
for (req, e) in answers {
self.out.err(&req, e).await;
}
for e in events {
self.out.json(&e).await;
}
self.files_pump().await;
}
}
#[cfg(test)]
mod tests {
use super::*;
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();
assert_eq!(
content(init_command(Direction::Upload, 3, 0, &icon, "", 812, false, None)),
"ftinitupload clientftfid=3 name=\\/icon_3558086607 cid=0 cpw size=812 overwrite=0 resume=0 proto=1"
);
assert_eq!(
content(init_command(Direction::Download, 4, 0, &icon, "", 0, false, None)),
"ftinitdownload clientftfid=4 name=\\/icon_3558086607 cid=0 cpw seekpos=0 proto=1"
);
assert_eq!(
content(delete_command(0, "", &[icon.clone(), "/icons/icon_7".into()])),
"ftdeletefile cid=0 cpw name=\\/icon_3558086607|name=\\/icon_7"
);
// Real channels keep their paths, including a folder that happens to be called "icons".
assert_eq!(
content(init_command(Direction::Upload, 5, 9, "/icons/icon_5", "", 1, true, None)),
"ftinitupload clientftfid=5 name=\\/icons\\/icon_5 cid=9 cpw size=1 overwrite=1 resume=0 proto=1"
);
assert_eq!(content(delete_command(9, "", &["/icons/icon_5".into()])), "ftdeletefile cid=9 cpw name=\\/icons\\/icon_5");
}
#[test]
fn resumed_transfers_continue_from_the_kept_offset_without_overwrite() {
// Official doFileDownload(resume=true): seekpos is the kept byte count.
assert_eq!(
content(init_command(Direction::Download, 6, 9, "/a.bin", "", 0, false, Some(65543))),
"ftinitdownload clientftfid=6 name=\\/a.bin cid=9 cpw seekpos=65543 proto=1"
);
// Official doFileUpload(resume=true): overwrite=!resume, the server answers with its seek position.
assert_eq!(
content(init_command(Direction::Upload, 7, 9, "/a.bin", "", 9, true, Some(0))),
"ftinitupload clientftfid=7 name=\\/a.bin cid=9 cpw size=9 overwrite=0 resume=1 proto=1"
);
}
}
+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());
}
}
+433
View File
@@ -0,0 +1,433 @@
//! Scoped global-shortcut helper. No keyboard hooks or unrestricted key-state scans.
//! Native callback service and CLI adapter (newline-delimited JSON on stdio).
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::error::Error;
use std::io::{self, BufRead, Write};
use std::sync::{atomic::{AtomicBool, Ordering}, mpsc::{self, RecvTimeoutError}, Arc};
use std::thread::JoinHandle;
use std::time::Duration;
mod keys;
#[cfg(target_os = "linux")]
mod portal;
#[cfg(target_os = "linux")]
mod x11;
#[cfg(windows)]
mod windows;
#[cfg(test)]
mod tests;
type Result<T, E = Box<dyn Error>> = std::result::Result<T, E>;
const MAX_LINE: usize = 64 * 1024;
const MAX_BINDINGS: usize = 64;
#[derive(Debug, Deserialize)]
#[serde(tag = "cmd", rename_all = "snake_case", deny_unknown_fields)]
enum Command {
Bind { seq: u32, bindings: Vec<Binding> },
Shutdown {},
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub id: String,
pub code: String,
#[serde(default)]
pub ctrl: bool,
#[serde(default)]
pub alt: bool,
#[serde(default)]
pub shift: bool,
#[serde(default)]
pub meta: bool,
#[serde(default)]
pub description: String,
}
impl Binding {
fn modifiers(&self) -> u8 {
u8::from(self.ctrl) | (u8::from(self.alt) << 1)
| (u8::from(self.shift) << 2) | (u8::from(self.meta) << 3)
}
}
#[derive(Debug, Serialize)]
struct BindResult {
id: String,
ok: bool,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<&'static str>,
trigger: String,
detail: String,
}
impl BindResult {
fn success(binding: &Binding, trigger: String) -> Self {
Self { id: binding.id.clone(), ok: true, error: None, trigger, detail: String::new() }
}
fn failure(binding: &Binding, error: &'static str, detail: impl Into<String>) -> Self {
Self { id: binding.id.clone(), ok: false, error: Some(error), trigger: String::new(), detail: detail.into() }
}
}
enum Event {
Bound { seq: u32, results: Vec<BindResult> },
Rebound { results: Vec<BindResult> },
Key { id: String, down: bool },
}
trait Backend {
fn name(&self) -> &'static str;
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()>;
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()>;
fn clear(&mut self) -> Result<()>;
}
#[derive(Default)]
struct State {
registered: BTreeMap<String, bool>,
}
impl State {
fn transition(&mut self, id: &str, down: bool) -> bool {
let Some(held) = self.registered.get_mut(id) else { return false };
if *held == down { return false; }
*held = down;
true
}
fn release_all(&mut self, out: &mut impl FnMut(serde_json::Value) -> io::Result<()>) -> io::Result<()> {
// Clear every flag even when the consumer fails; OS cleanup must still run.
let mut failure = None;
for (id, held) in &mut self.registered {
if std::mem::replace(held, false) {
if let Err(error) = out(serde_json::json!({ "event": "release", "id": id, "synthetic": true })) {
failure = Some(error);
}
}
}
self.registered.clear();
failure.map_or(Ok(()), Err)
}
fn event(&mut self, event: Event, out: &mut impl FnMut(serde_json::Value) -> io::Result<()>) -> io::Result<()> {
match event {
Event::Key { id, down } => {
if self.transition(&id, down) {
out(serde_json::json!({ "event": if down { "press" } else { "release" }, "id": id }))?;
}
}
Event::Bound { 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": "bound", "seq": seq, "results": results }))?;
}
Event::Rebound { 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 }))?;
}
}
Ok(())
}
}
fn emit(out: &mut impl Write, value: &impl Serialize) -> io::Result<()> {
serde_json::to_writer(&mut *out, value)?;
out.write_all(b"\n")?;
out.flush()
}
fn validate_bindings(bindings: &[Binding]) -> Result<()> {
if bindings.len() > MAX_BINDINGS { return Err("at most 64 hotkey bindings".into()); }
let mut ids = HashSet::with_capacity(bindings.len());
let mut chords = HashSet::with_capacity(bindings.len());
for b in bindings {
if b.id.is_empty() || b.id.len() > 128 || b.id.chars().any(char::is_control)
|| b.code.is_empty() || b.code.len() > 32 || !b.code.bytes().all(|c| c.is_ascii_alphanumeric())
|| b.description.len() > 256 || b.description.chars().any(char::is_control)
{
return Err("invalid hotkey id, code or description".into());
}
if !ids.insert(&b.id) || !chords.insert((&b.code, b.modifiers())) {
return Err("duplicate hotkey id or chord".into());
}
}
Ok(())
}
fn parse(line: &[u8]) -> Result<Command> {
if line.len() > MAX_LINE { return Err("hotkey input line exceeds 64 KiB".into()); }
let command: Command = serde_json::from_slice(line)?;
if let Command::Bind { bindings, .. } = &command { validate_bindings(bindings)?; }
Ok(command)
}
fn read_line(input: &mut impl BufRead, line: &mut Vec<u8>) -> io::Result<bool> {
line.clear();
loop {
let bytes = input.fill_buf()?;
if bytes.is_empty() { return Ok(!line.is_empty()); }
let end = bytes.iter().position(|&b| b == b'\n').map(|n| n + 1);
let count = end.unwrap_or(bytes.len());
if line.len() + count > MAX_LINE {
return Err(io::Error::new(io::ErrorKind::InvalidData, "hotkey input line exceeds 64 KiB"));
}
line.extend_from_slice(&bytes[..count]);
input.consume(count);
if end.is_some() { return Ok(true); }
}
}
fn open_backend() -> Result<Box<dyn Backend>> {
#[cfg(windows)]
{ return Ok(Box::new(windows::Windows::new())); }
#[cfg(target_os = "linux")]
{
// XWayland grabs are not global to Wayland clients. Never silently claim otherwise.
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|v| v == "wayland");
return if wayland {
Ok(Box::new(portal::Portal::new()?))
} else {
Ok(Box::new(x11::X11::new()?))
};
}
#[cfg(not(any(windows, target_os = "linux")))]
{ Err("global shortcuts are unavailable on this platform".into()) }
}
/// A startup, validation, queue or backend failure. No OS registrations survive stop.
#[derive(Clone, Debug)]
pub struct HotkeyError(String);
impl std::fmt::Display for HotkeyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) }
}
impl Error for HotkeyError {}
/// Owns a backend thread and bounded ordered events. Drop requests cancellation;
/// call `stop` off the UI thread to wait for OS cleanup, then dispatch final events.
pub struct HotkeyHandle {
commands: mpsc::SyncSender<Result<Command, String>>,
cancelled: Arc<AtomicBool>,
worker: Option<JoinHandle<Result<(), HotkeyError>>>,
events: mpsc::Receiver<serde_json::Value>,
held: std::collections::BTreeSet<String>,
terminal: Option<Result<(), HotkeyError>>,
terminal_delivered: bool,
}
const EVENT_CAPACITY: usize = 256;
impl HotkeyHandle {
/// Replace the complete binding profile. Success means queued; the callback's
/// `bound` event with this sequence carries the actual registration results.
/// A full queue returns an error without replacing any pending profile.
pub fn update(&self, seq: u32, bindings: Vec<Binding>) -> Result<(), HotkeyError> {
validate_bindings(&bindings).map_err(|e| HotkeyError(e.to_string()))?;
if self.cancelled.load(Ordering::Acquire) { return Err(HotkeyError("hotkey service has stopped".into())); }
self.commands.try_send(Ok(Command::Bind { seq, bindings })).map_err(|error| {
HotkeyError(match error {
mpsc::TrySendError::Full(_) => "hotkey command queue is full",
mpsc::TrySendError::Disconnected(_) => "hotkey service has stopped",
}.into())
})
}
/// Cancel pending updates, release held keys, unregister and join the worker.
/// Call off the UI thread; callbacks are never run by the backend worker.
/// Afterwards call `dispatch` to consume final releases/errors.
pub fn stop(&mut self) -> Result<(), HotkeyError> {
self.cancel();
if let Some(worker) = self.worker.take() {
self.terminal = Some(worker.join().unwrap_or_else(|_| Err(HotkeyError("hotkey worker panicked".into()))));
}
self.terminal.clone().unwrap_or(Ok(()))
}
fn cancel(&self) {
self.cancelled.store(true, Ordering::Release);
// Wake an idle worker; cancellation remains effective with a full queue.
let _ = self.commands.try_send(Ok(Command::Shutdown {}));
}
/// Deliver a bounded batch on the calling thread, plus final releases/errors.
/// No callback runs on the OS backend thread, so a stalled consumer cannot
/// prevent unregister. Queue overflow terminates the backend; cancellation
/// discards undelivered events. Every consumer-held key is released before the
/// terminal error, even if the bounded queue had no room for its release.
/// Callback failure cancels the backend; call again to receive final releases.
pub fn dispatch(&mut self, mut callback: impl FnMut(serde_json::Value) -> io::Result<()>) -> Result<usize, HotkeyError> {
let mut delivered = 0;
let mut disconnected = false;
if self.worker.as_ref().is_some_and(|worker| worker.is_finished()) { let _ = self.stop(); }
if matches!(&self.terminal, Some(Err(_))) {
// Failed service events must not reactivate PTT when a stalled host
// resumes. The joined worker cannot refill this bounded queue.
while self.events.try_recv().is_ok() {}
}
for _ in 0..EVENT_CAPACITY {
let value = match self.events.try_recv() {
Ok(value) => value,
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => { disconnected = true; break; }
};
if self.cancelled.load(Ordering::Acquire) { continue; }
let release_id = if value["event"] == "release" { value["id"].as_str().map(str::to_owned) } else { None };
if value["event"] == "press" {
if let Some(id) = value["id"].as_str() { self.held.insert(id.to_owned()); }
}
if let Err(error) = callback(value) {
self.cancel();
return Err(HotkeyError(error.to_string()));
}
if let Some(id) = release_id { self.held.remove(&id); }
delivered += 1;
}
if self.worker.as_ref().is_some_and(|worker| worker.is_finished()) { let _ = self.stop(); }
if disconnected && self.terminal.is_some() && !self.terminal_delivered {
while let Some(id) = self.held.first().cloned() {
callback(serde_json::json!({ "event": "release", "id": id, "synthetic": true })).map_err(|e| HotkeyError(e.to_string()))?;
self.held.remove(&id);
delivered += 1;
}
if let Some(Err(error)) = &self.terminal {
callback(serde_json::json!({ "event": "error", "detail": error.to_string() })).map_err(|e| HotkeyError(e.to_string()))?;
delivered += 1;
}
self.terminal_delivered = true;
}
Ok(delivered)
}
}
impl Drop for HotkeyHandle {
fn drop(&mut self) { self.cancel(); }
}
/// Explicitly open the platform backend, without registering any bindings.
/// Call off the UI thread: startup waits for backend discovery. `update` is the
/// only registration request. Call `dispatch` regularly to deliver callback
/// events with the CLI JSON shape and no serialization round trip.
pub fn start() -> Result<HotkeyHandle, HotkeyError> {
start_with_backend(open_backend)
}
fn start_with_backend(
factory: impl FnOnce() -> Result<Box<dyn Backend>> + Send + 'static,
) -> Result<HotkeyHandle, HotkeyError> {
let (commands, rx) = mpsc::sync_channel(8);
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
let (events_tx, events) = mpsc::sync_channel(EVENT_CAPACITY);
let cancelled = Arc::new(AtomicBool::new(false));
let stop = Arc::clone(&cancelled);
let worker = std::thread::Builder::new().name("hotkeys".into()).spawn(move || {
let mut out = |value: serde_json::Value| {
// Native errors are delivered once after final held-key releases.
if value["event"] == "error" { return Ok(()); }
events_tx.try_send(value).map_err(|error| io::Error::other(match error {
mpsc::TrySendError::Full(_) => "hotkey event queue overflow",
mpsc::TrySendError::Disconnected(_) => "hotkey event consumer closed",
}))
};
let mut backend = match factory() {
Ok(backend) => backend,
Err(error) => {
let detail = error.to_string();
let _ = out(serde_json::json!({ "event": "ready", "backend": "unavailable", "global": false, "release": false, "detail": detail }));
let _ = ready_tx.send(Err(detail.clone()));
return Err(HotkeyError(detail));
}
};
if let Err(error) = out(serde_json::json!({ "event": "ready", "backend": backend.name(), "global": true, "release": true })) {
let _ = backend.clear();
let _ = ready_tx.send(Err(error.to_string()));
return Err(HotkeyError(error.to_string()));
}
let _ = ready_tx.send(Ok(()));
serve(&mut *backend, rx, &stop, &mut out).map_err(|e| HotkeyError(e.to_string()))
}).map_err(|e| HotkeyError(e.to_string()))?;
let mut handle = HotkeyHandle { commands, cancelled, worker: Some(worker), events,
held: Default::default(), terminal: None, terminal_delivered: false };
match ready_rx.recv() {
Ok(Ok(())) => Ok(handle),
Ok(Err(error)) => { let _ = handle.stop(); Err(HotkeyError(error)) }
Err(_) => { let _ = handle.stop(); Err(HotkeyError("hotkey worker stopped during startup".into())) }
}
}
fn serve(
backend: &mut dyn Backend,
rx: mpsc::Receiver<Result<Command, String>>,
cancelled: &AtomicBool,
out: &mut impl FnMut(serde_json::Value) -> io::Result<()>,
) -> Result<()> {
let mut state = State::default();
let mut events = Vec::with_capacity(MAX_BINDINGS);
let result = (|| -> Result<()> {
while !cancelled.load(Ordering::Acquire) {
let command = rx.recv_timeout(Duration::from_millis(8));
if cancelled.load(Ordering::Acquire) { break; }
match command {
Ok(Ok(Command::Shutdown {})) | Err(RecvTimeoutError::Disconnected) => break,
Ok(Err(error)) => return Err(error.into()),
Ok(Ok(Command::Bind { seq, bindings })) => {
state.release_all(out)?;
backend.clear()?;
backend.bind(seq, bindings, &mut events)?;
}
Err(RecvTimeoutError::Timeout) => {}
}
if cancelled.load(Ordering::Acquire) { break; }
backend.poll(&mut events)?;
for event in events.drain(..) { state.event(event, out)?; }
}
Ok(())
})();
let released = state.release_all(out);
let cleared = backend.clear();
if let Err(error) = &result {
let _ = out(serde_json::json!({ "event": "error", "detail": error.to_string() }));
}
result?;
released?;
cleared
}
/// Runs only when explicitly selected by the `hotkeys` CLI subcommand.
/// Blocking input and stdout serialization belong exclusively to this adapter.
pub fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
let stdout = io::stdout();
let mut out = stdout.lock();
let mut backend = match open_backend() {
Ok(backend) => backend,
Err(error) => {
emit(&mut out, &serde_json::json!({ "event": "ready", "backend": "unavailable", "global": false, "release": false, "detail": error.to_string() }))?;
return Ok(());
}
};
emit(&mut out, &serde_json::json!({ "event": "ready", "backend": backend.name(), "global": true, "release": true }))?;
let (tx, rx) = mpsc::sync_channel(8);
// A bounded reader keeps backend event handling responsive while stdin is idle.
// It owns no OS registrations; EOF/shutdown closes the receiver on exit.
std::thread::Builder::new().name("hotkey-stdin".into()).spawn(move || {
let stdin = io::stdin();
let mut input = stdin.lock();
let mut line = Vec::with_capacity(4096);
loop {
let item = match read_line(&mut input, &mut line) {
Ok(false) => break,
Ok(true) => parse(&line).map_err(|e| e.to_string()),
Err(error) => Err(error.to_string()),
};
let terminal = item.is_err() || matches!(item, Ok(Command::Shutdown {}));
if tx.send(item).is_err() || terminal { break; }
}
})?;
serve(&mut *backend, rx, &AtomicBool::new(false), &mut |value| emit(&mut out, &value))
}
+76
View File
@@ -0,0 +1,76 @@
//! Explicit key allowlist: unsupported DOM codes are reported, never guessed/scanned.
use super::Binding;
pub(super) struct Key {
pub windows: u32,
pub x11: u32,
pub name: String,
}
pub(super) fn lookup(code: &str) -> Option<Key> {
if let Some(letter) = code.strip_prefix("Key").filter(|s| s.len() == 1 && s.as_bytes()[0].is_ascii_uppercase()) {
let letter = letter.as_bytes()[0];
return Some(Key { windows: u32::from(letter), x11: u32::from(letter.to_ascii_lowercase()), name: char::from(letter.to_ascii_lowercase()).to_string() });
}
if let Some(digit) = code.strip_prefix("Digit").filter(|s| s.len() == 1 && s.as_bytes()[0].is_ascii_digit()) {
return Some(Key { windows: u32::from(digit.as_bytes()[0]), x11: u32::from(digit.as_bytes()[0]), name: digit.into() });
}
if let Some(digit) = code.strip_prefix("Numpad").filter(|s| s.len() == 1 && s.as_bytes()[0].is_ascii_digit()) {
let n = u32::from(digit.as_bytes()[0] - b'0');
return Some(Key { windows: 0x60 + n, x11: 0xffb0 + n, name: format!("KP_{digit}") });
}
if let Some(number) = code.strip_prefix('F').and_then(|n| n.parse::<u32>().ok()).filter(|n| (1..=24).contains(n)) {
if code != format!("F{number}") { return None; }
return Some(Key { windows: 0x70 + number - 1, x11: 0xffbe + number - 1, name: code.into() });
}
let (windows, x11, name) = match code {
"Backspace" => (0x08, 0xff08, "BackSpace"),
"Tab" => (0x09, 0xff09, "Tab"),
"Enter" => (0x0d, 0xff0d, "Return"),
"Pause" => (0x13, 0xff13, "Pause"),
"CapsLock" => (0x14, 0xffe5, "Caps_Lock"),
"Escape" => (0x1b, 0xff1b, "Escape"),
"Space" => (0x20, 0x20, "space"),
"PageUp" => (0x21, 0xff55, "Prior"),
"PageDown" => (0x22, 0xff56, "Next"),
"End" => (0x23, 0xff57, "End"),
"Home" => (0x24, 0xff50, "Home"),
"ArrowLeft" => (0x25, 0xff51, "Left"),
"ArrowUp" => (0x26, 0xff52, "Up"),
"ArrowRight" => (0x27, 0xff53, "Right"),
"ArrowDown" => (0x28, 0xff54, "Down"),
"PrintScreen" => (0x2c, 0xff61, "Print"),
"Insert" => (0x2d, 0xff63, "Insert"),
"Delete" => (0x2e, 0xffff, "Delete"),
"ContextMenu" => (0x5d, 0xff67, "Menu"),
"NumpadMultiply" => (0x6a, 0xffaa, "KP_Multiply"),
"NumpadAdd" => (0x6b, 0xffab, "KP_Add"),
"NumpadSubtract" => (0x6d, 0xffad, "KP_Subtract"),
"NumpadDecimal" => (0x6e, 0xffae, "KP_Decimal"),
"NumpadDivide" => (0x6f, 0xffaf, "KP_Divide"),
"NumLock" => (0x90, 0xff7f, "Num_Lock"),
"ScrollLock" => (0x91, 0xff14, "Scroll_Lock"),
"Semicolon" => (0xba, 0x3b, "semicolon"),
"Equal" => (0xbb, 0x3d, "equal"),
"Comma" => (0xbc, 0x2c, "comma"),
"Minus" => (0xbd, 0x2d, "minus"),
"Period" => (0xbe, 0x2e, "period"),
"Slash" => (0xbf, 0x2f, "slash"),
"Backquote" => (0xc0, 0x60, "grave"),
"BracketLeft" => (0xdb, 0x5b, "bracketleft"),
"Backslash" => (0xdc, 0x5c, "backslash"),
"BracketRight" => (0xdd, 0x5d, "bracketright"),
"Quote" => (0xde, 0x27, "apostrophe"),
_ => return None,
};
Some(Key { windows, x11, name: name.into() })
}
pub(super) fn trigger(binding: &Binding, key: &Key) -> String {
let mut trigger = String::with_capacity(40);
for (enabled, modifier) in [(binding.ctrl, "CTRL+"), (binding.alt, "ALT+"), (binding.shift, "SHIFT+"), (binding.meta, "LOGO+")] {
if enabled { trigger.push_str(modifier); }
}
trigger.push_str(&key.name);
trigger
}
+260
View File
@@ -0,0 +1,260 @@
//! GlobalShortcuts portal, not an XWayland or keyboard-hook fallback.
//! Requests remain asynchronous so rebind/shutdown can close a permission dialog.
use super::{keys, Backend, BindResult, Binding, Event, Result, MAX_BINDINGS};
use dbus::arg::{PropMap, RefArg, Variant};
use dbus::blocking::{stdintf::org_freedesktop_dbus::Properties, Connection};
use dbus::channel::MatchingReceiver;
use dbus::message::MatchRule;
use dbus::{Message, Path};
use std::collections::HashMap;
use std::sync::{atomic::{AtomicBool, Ordering}, mpsc::{self, Receiver}, Arc};
use std::time::{Duration, Instant};
const DEST: &str = "org.freedesktop.portal.Desktop";
const ROOT: &str = "/org/freedesktop/portal/desktop";
const IFACE: &str = "org.freedesktop.portal.GlobalShortcuts";
const REQUEST: &str = "org.freedesktop.portal.Request";
const SESSION: &str = "org.freedesktop.portal.Session";
const CALL_TIMEOUT: Duration = Duration::from_secs(2);
enum Stage { Creating, Binding }
struct Pending { path: Path<'static>, stage: Stage, started: Instant }
pub(super) struct Portal {
connection: Connection,
incoming: Receiver<Message>,
overflow: Arc<AtomicBool>,
owner: String,
generation: u64,
session: Option<Path<'static>>,
pending: Option<Pending>,
bindings: Vec<Binding>,
seq: u32,
bound: bool,
}
fn option(map: &mut PropMap, key: &str, value: String) {
map.insert(key.into(), Variant(Box::new(value)));
}
impl Portal {
pub(super) fn new() -> Result<Self> {
let connection = Connection::new_session()?;
let proxy = connection.with_proxy(DEST, ROOT, CALL_TIMEOUT);
let version: u32 = proxy.get(IFACE, "version")?;
if version < 1 { return Err("GlobalShortcuts portal version is unavailable".into()); }
let (owner,): (String,) = connection.with_proxy("org.freedesktop.DBus", "/org/freedesktop/DBus", CALL_TIMEOUT)
.method_call("org.freedesktop.DBus", "GetNameOwner", (DEST,))?;
let (tx, incoming) = mpsc::sync_channel(256);
let overflow = Arc::new(AtomicBool::new(false));
for (interface, member) in [(REQUEST, "Response"), (IFACE, "Activated"), (IFACE, "Deactivated"),
(IFACE, "ShortcutsChanged"), (SESSION, "Closed"), ("org.freedesktop.DBus", "NameOwnerChanged")] {
let sender = if interface == "org.freedesktop.DBus" { "org.freedesktop.DBus" } else { owner.as_str() };
let rule = MatchRule::new_signal(interface, member).with_strict_sender(sender.to_owned());
connection.add_match_no_cb(&rule.match_str())?;
let tx = tx.clone();
let overflow = Arc::clone(&overflow);
connection.start_receive(rule, Box::new(move |message, _| {
if tx.try_send(message).is_err() { overflow.store(true, Ordering::Relaxed); }
true
}));
}
Ok(Self { connection, incoming, overflow, owner, generation: 0, session: None, pending: None,
bindings: Vec::new(), seq: 0, bound: false })
}
fn token(&self, suffix: &str) -> String { format!("tp_{}_{}_{}", std::process::id(), self.generation, suffix) }
fn create(&mut self) -> Result<()> {
let mut options = PropMap::new();
option(&mut options, "handle_token", self.token("create"));
option(&mut options, "session_handle_token", self.token("session"));
// Predict the session path so even a cancelled CreateSession is closed on shutdown.
let sender = self.connection.unique_name().trim_start_matches(':').replace('.', "_");
self.session = Some(Path::new(format!("/org/freedesktop/portal/desktop/session/{sender}/{}", self.token("session")))?);
let (path,): (Path<'static>,) = self.connection.with_proxy(DEST, ROOT, CALL_TIMEOUT)
.method_call(IFACE, "CreateSession", (options,))?;
self.pending = Some(Pending { path, stage: Stage::Creating, started: Instant::now() });
Ok(())
}
fn request_bind(&mut self) -> Result<()> {
let mut shortcuts = Vec::with_capacity(self.bindings.len());
for binding in &self.bindings {
if let Some(key) = keys::lookup(&binding.code) {
let mut properties = PropMap::new();
option(&mut properties, "description", if binding.description.is_empty() { binding.id.clone() } else { binding.description.clone() });
option(&mut properties, "preferred_trigger", keys::trigger(binding, &key));
shortcuts.push((binding.id.clone(), properties));
}
}
let mut options = PropMap::new();
option(&mut options, "handle_token", self.token("bind"));
let session = self.session.as_ref().ok_or("portal session missing")?;
let (path,): (Path<'static>,) = self.connection.with_proxy(DEST, ROOT, CALL_TIMEOUT)
.method_call(IFACE, "BindShortcuts", (session, shortcuts, "", options))?;
self.pending = Some(Pending { path, stage: Stage::Binding, started: Instant::now() });
Ok(())
}
fn results(&self, shortcuts: &HashMap<String, String>, denied: bool) -> Vec<BindResult> {
self.bindings.iter().map(|binding| {
if keys::lookup(&binding.code).is_none() {
BindResult::failure(binding, "unsupported_key", "DOM code has no portal trigger mapping")
} else if let Some(trigger) = shortcuts.get(&binding.id) {
BindResult::success(binding, trigger.clone())
} else {
BindResult::failure(binding, if denied { "portal_denied" } else { "failed" }, "Shortcut was not granted by the desktop portal")
}
}).collect()
}
fn close(&self, path: &Path<'static>, interface: &str) -> Result<()> {
let _: () = self.connection.with_proxy(DEST, path.clone(), CALL_TIMEOUT).method_call(interface, "Close", ())?;
Ok(())
}
}
// Dynamic a(sa{sv}) decoding: dbus represents nested variants with RefArg, not
// necessarily the concrete Vec/HashMap types used to encode outbound calls.
fn shortcuts(value: &dyn RefArg) -> Result<HashMap<String, String>> {
let mut result = HashMap::new();
let entries = value.as_iter().ok_or("portal shortcuts are not an array")?;
for entry in entries {
if result.len() >= MAX_BINDINGS { return Err("portal returned too many shortcuts".into()); }
let mut fields = entry.as_iter().ok_or("invalid portal shortcut tuple")?;
let id = fields.next().and_then(RefArg::as_str).ok_or("invalid portal shortcut id")?;
if id.len() > 128 { return Err("portal shortcut id exceeds limit".into()); }
let properties = fields.next().ok_or("missing portal shortcut properties")?;
let mut properties = properties.as_iter().ok_or("invalid portal shortcut properties")?;
let mut trigger = String::new();
while let Some(key) = properties.next() {
let value = properties.next().ok_or("invalid portal shortcut property")?;
if key.as_str() == Some("trigger_description") {
let text = value.as_str().or_else(|| value.as_iter()?.next()?.as_str()).unwrap_or("");
trigger = text.chars().take(128).collect();
}
}
result.insert(id.to_owned(), trigger);
}
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decodes_shortcut_trigger_variants_without_a_bus() {
let mut properties = PropMap::new();
option(&mut properties, "description", "Whisper".into());
option(&mut properties, "trigger_description", "Ctrl+W".into());
let entries = vec![("whisper".to_owned(), properties)];
let decoded = shortcuts(&entries).unwrap();
assert_eq!(decoded.get("whisper").map(String::as_str), Some("Ctrl+W"));
}
#[test]
fn rejects_non_array_and_oversized_shortcut_lists() {
assert!(shortcuts(&17u32).is_err());
let entries: Vec<_> = (0..=MAX_BINDINGS).map(|index| (index.to_string(), PropMap::new())).collect();
assert!(shortcuts(&entries).is_err());
}
}
impl Backend for Portal {
fn name(&self) -> &'static str { "xdg_portal_global_shortcuts" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
self.seq = seq;
self.bindings = bindings;
self.generation = self.generation.checked_add(1).ok_or("portal request generation exhausted")?;
if self.bindings.iter().all(|b| keys::lookup(&b.code).is_none()) {
events.push(Event::Bound { seq, results: self.results(&HashMap::new(), false) });
return Ok(());
}
self.create()
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
for _ in 0..256 {
if !self.connection.process(Duration::ZERO)? { break; }
}
if self.overflow.swap(false, Ordering::Relaxed) { return Err("portal signal queue overflow".into()); }
// A pending permission request must not keep a session alive indefinitely.
if self.pending.as_ref().is_some_and(|p| p.started.elapsed() > Duration::from_secs(120)) {
return Err("portal shortcut request timed out".into());
}
while let Ok(message) = self.incoming.try_recv() {
let member = message.member().map(|m| m.to_string()).unwrap_or_default();
if member == "NameOwnerChanged" {
let (name, old, new): (String, String, String) = message.read3()?;
if name == DEST && old == self.owner && new != old { return Err("GlobalShortcuts portal service disappeared".into()); }
continue;
}
if member == "Response" {
if !self.pending.as_ref().is_some_and(|pending| message.path().as_ref() == Some(&pending.path)) { continue; }
let pending = self.pending.take().ok_or("portal request missing")?;
let (response, properties): (u32, PropMap) = message.read2()?;
if response != 0 {
events.push(Event::Bound { seq: self.seq, results: self.results(&HashMap::new(), response == 1) });
self.clear()?;
continue;
}
match pending.stage {
Stage::Creating => {
let path = properties.get("session_handle").and_then(|v| v.0.as_str()).ok_or("portal returned no session handle")?;
// Only accept the session path for this request/connection.
if self.session.as_ref().map(|p| p.to_string()).as_deref() != Some(path) {
return Err("portal returned an unexpected session handle".into());
}
self.request_bind()?;
}
Stage::Binding => {
let granted = shortcuts(properties.get("shortcuts").ok_or("portal returned no shortcuts")?.0.as_ref())?;
events.push(Event::Bound { seq: self.seq, results: self.results(&granted, true) });
self.bound = true;
}
}
} else if member == "Closed" {
if message.path().as_ref() == self.session.as_ref() { return Err("portal shortcut session closed".into()); }
} else if member == "Activated" || member == "Deactivated" {
let (session, id, _, _): (Path<'static>, String, u64, PropMap) = message.read4()?;
if self.bound && Some(&session) == self.session.as_ref() && self.bindings.iter().any(|b| b.id == id) {
events.push(Event::Key { id, down: member == "Activated" });
}
} else if member == "ShortcutsChanged" {
let (session, changed): (Path<'static>, Vec<(String, PropMap)>) = message.read2()?;
if self.bound && Some(&session) == self.session.as_ref() {
if changed.len() > MAX_BINDINGS { return Err("portal returned too many shortcuts".into()); }
let granted = changed.into_iter().map(|(id, properties)| {
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) });
}
}
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
self.bound = false;
self.bindings.clear();
let mut failure = None;
if let Some(pending) = self.pending.take() {
if let Err(error) = self.close(&pending.path, REQUEST) { failure = Some(error); }
}
if let Some(session) = self.session.take() {
// Session may already have been closed by the desktop/user. The
// connection is dropped on any failure, which also revokes its session.
if let Err(error) = self.close(&session, SESSION) { failure = Some(error); }
}
while self.incoming.try_recv().is_ok() {}
match failure { Some(error) => Err(error), None => Ok(()) }
}
}
impl Drop for Portal {
fn drop(&mut self) { let _ = self.clear(); }
}
+294
View File
@@ -0,0 +1,294 @@
//! Pure tests: no platform backend construction, display connection, OS hooks or key polling.
use super::*;
use std::io::{BufReader, Cursor};
fn binding(id: &str, code: &str) -> Binding {
Binding { id: id.into(), code: code.into(), ctrl: false, alt: false, shift: false, meta: false, description: String::new() }
}
#[test]
fn accepts_helper_wire_commands() {
let command = parse(br#"{"cmd":"bind","seq":4294967295,"bindings":[{"id":"a","code":"KeyW","ctrl":true,"alt":false,"shift":false,"meta":false,"description":"whisper_list"}]}"#).unwrap();
let Command::Bind { seq, bindings } = command else { panic!("expected bind") };
assert_eq!(seq, u32::MAX);
assert_eq!(bindings.len(), 1);
assert_eq!(bindings[0].modifiers(), 1);
assert!(matches!(parse(b"{\"cmd\":\"shutdown\"}\r\n").unwrap(), Command::Shutdown {}));
}
#[test]
fn rejects_unknown_fields_wrong_types_and_duplicate_chords() {
for raw in [
r#"{"cmd":"shutdown","bindings":[]}"#,
r#"{"cmd":"bind","seq":-1,"bindings":[]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"KeyA","ctrl":1}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"KeyA","global":true}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"KeyA"},{"id":"a","code":"KeyB"}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"KeyA"},{"id":"b","code":"KeyA"}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a","code":"Key-A"}]}"#,
r#"{"cmd":"bind","seq":1,"bindings":[{"id":"a\n","code":"KeyA"}]}"#,
] {
assert!(parse(raw.as_bytes()).is_err(), "accepted {raw}");
}
}
#[test]
fn limits_binding_count_and_text_before_backend_access() {
let bindings: Vec<_> = (0..65).map(|n| serde_json::json!({ "id": n.to_string(), "code": format!("Key{n}") })).collect();
let raw = serde_json::to_vec(&serde_json::json!({ "cmd": "bind", "seq": 1, "bindings": bindings })).unwrap();
assert!(parse(&raw).is_err());
for (field, text) in [("id", "a".repeat(129)), ("code", "A".repeat(33)), ("description", "x".repeat(257))] {
let mut b = serde_json::json!({ "id": "a", "code": "KeyA" });
b[field] = text.into();
let raw = serde_json::to_vec(&serde_json::json!({ "cmd": "bind", "seq": 1, "bindings": [b] })).unwrap();
assert!(parse(&raw).is_err());
}
assert!(parse(&vec![b' '; MAX_LINE + 1]).is_err());
}
#[test]
fn bounded_reader_handles_chunk_boundaries_crlf_and_final_line() {
let mut input = BufReader::with_capacity(3, Cursor::new(b"abc\r\ndef\nxyz"));
let mut line = Vec::new();
for expected in [b"abc\r\n".as_slice(), b"def\n", b"xyz"] {
assert!(read_line(&mut input, &mut line).unwrap());
assert_eq!(line, expected);
}
assert!(!read_line(&mut input, &mut line).unwrap());
}
#[test]
fn oversized_unterminated_input_never_grows_past_limit() {
let mut input = BufReader::with_capacity(1024, Cursor::new(vec![b'x'; MAX_LINE + 100]));
let mut line = Vec::new();
assert_eq!(read_line(&mut input, &mut line).unwrap_err().kind(), io::ErrorKind::InvalidData);
assert!(line.len() <= MAX_LINE);
}
#[test]
fn ignores_unknown_ids_and_repeat_transitions() {
let mut state = State::default();
state.registered.insert("a".into(), false);
assert!(!state.transition("unregistered", true));
assert!(!state.transition("a", false));
assert!(state.transition("a", true));
assert!(!state.transition("a", true));
assert!(state.transition("a", false));
assert!(!state.transition("a", false));
}
#[test]
fn replacement_releases_held_ids_before_new_bound_event() {
let mut state = State::default();
state.registered.insert("old".into(), true);
let mut out = Vec::new();
state.event(Event::Bound { seq: 2, results: vec![BindResult::success(&binding("new", "KeyN"), "n".into()),
BindResult::failure(&binding("bad", "Unknown"), "unsupported_key", "unsupported")] }, &mut |value| emit(&mut out, &value)).unwrap();
let messages: Vec<serde_json::Value> = out.split(|b| *b == b'\n').filter(|b| !b.is_empty())
.map(|b| serde_json::from_slice(b).unwrap()).collect();
assert_eq!(messages[0]["event"], "release");
assert_eq!(messages[0]["id"], "old");
// Replacement is cancellation, not a physical key-up that can trigger a command.
assert_eq!(messages[0]["synthetic"], true);
assert_eq!(messages[1]["event"], "bound");
assert_eq!(messages[1]["seq"], 2);
assert!(state.transition("new", true));
assert!(!state.transition("old", true));
assert!(!state.transition("bad", true));
}
#[test]
fn shutdown_and_failure_release_all_once() {
let mut state = State::default();
state.registered.extend([("a".into(), true), ("b".into(), true), ("c".into(), false)]);
let mut out = Vec::new();
state.release_all(&mut |value| emit(&mut out, &value)).unwrap();
let written = out.len();
state.release_all(&mut |value| emit(&mut out, &value)).unwrap();
assert_eq!(out.len(), written);
assert_eq!(out.iter().filter(|&&b| b == b'\n').count(), 2);
assert!(state.registered.is_empty());
}
#[test]
fn broken_stdout_still_clears_all_held_state() {
struct Broken;
impl Write for Broken {
fn write(&mut self, _: &[u8]) -> io::Result<usize> { Err(io::ErrorKind::BrokenPipe.into()) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
let mut state = State::default();
state.registered.extend([("a".into(), true), ("b".into(), true)]);
assert!(state.release_all(&mut |value| emit(&mut Broken, &value)).is_err());
assert!(state.registered.is_empty());
}
#[test]
fn key_allowlist_and_portal_trigger_are_explicit() {
for code in ["KeyA", "Digit0", "F1", "F24", "Space", "Numpad9", "ArrowLeft"] {
assert!(keys::lookup(code).is_some(), "{code}");
}
for code in ["Keya", "KeyAA", "F0", "F25", "F01", "Mouse1", "ControlLeft", "NumpadEnter", "Unknown"] {
assert!(keys::lookup(code).is_none(), "{code}");
}
let mut b = binding("a", "KeyA");
b.ctrl = true;
b.shift = true;
b.meta = true;
assert_eq!(keys::trigger(&b, &keys::lookup(&b.code).unwrap()), "CTRL+SHIFT+LOGO+a");
}
// The same service factory/loop used by native callers, with no platform access.
struct FakeBackend {
binds: Arc<std::sync::atomic::AtomicUsize>,
clears: Arc<std::sync::atomic::AtomicUsize>,
dropped: Arc<AtomicBool>,
bursts: mpsc::Receiver<usize>,
active: Option<String>,
}
impl Backend for FakeBackend {
fn name(&self) -> &'static str { "test" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
self.binds.fetch_add(1, Ordering::SeqCst);
self.active = bindings.first().map(|b| b.id.clone());
let results = bindings.iter().map(|b| BindResult::success(b, b.code.clone())).collect();
events.push(Event::Bound { seq, results });
if let Some(id) = &self.active { events.push(Event::Key { id: id.clone(), down: true }); }
Ok(())
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
if let (Some(id), Ok(count)) = (&self.active, self.bursts.try_recv()) {
for n in 0..count { events.push(Event::Key { id: id.clone(), down: n % 2 != 0 }); }
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
self.clears.fetch_add(1, Ordering::SeqCst);
self.active = None;
Ok(())
}
}
impl Drop for FakeBackend {
fn drop(&mut self) { self.dropped.store(true, Ordering::Release); }
}
struct Fixture {
handle: HotkeyHandle,
binds: Arc<std::sync::atomic::AtomicUsize>,
clears: Arc<std::sync::atomic::AtomicUsize>,
dropped: Arc<AtomicBool>,
bursts: mpsc::SyncSender<usize>,
}
fn fake_service() -> Fixture {
let binds = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let clears = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let dropped = Arc::new(AtomicBool::new(false));
let (bursts, rx) = mpsc::sync_channel(1);
let backend = FakeBackend { binds: binds.clone(), clears: clears.clone(), dropped: dropped.clone(), bursts: rx, active: None };
let handle = start_with_backend(move || Ok(Box::new(backend))).unwrap();
Fixture { handle, binds, clears, dropped, bursts }
}
fn eventually(mut condition: impl FnMut() -> bool) {
let deadline = std::time::Instant::now() + Duration::from_secs(3);
while !condition() {
assert!(std::time::Instant::now() < deadline, "hotkey lifecycle did not complete");
std::thread::sleep(Duration::from_millis(1));
}
}
fn dispatch_until(handle: &mut HotkeyHandle, messages: &mut Vec<serde_json::Value>, event: &str, id: &str) {
let consumer_thread = std::thread::current().id();
eventually(|| {
handle.dispatch(|value| {
assert_eq!(std::thread::current().id(), consumer_thread);
messages.push(value);
Ok(())
}).unwrap();
messages.iter().any(|v| v["event"] == event && v["id"] == id)
});
}
#[test]
fn native_profiles_release_before_replace_and_join_before_restart() {
for _ in 0..100 {
let mut fixture = fake_service();
assert_eq!(fixture.binds.load(Ordering::SeqCst), 0, "startup must not register");
let mut messages = Vec::new();
fixture.handle.update(1, vec![binding("old", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "old");
assert!(fixture.handle.update(2, vec![binding("x", "KeyA"), binding("x", "KeyB")]).is_err());
assert_eq!(fixture.binds.load(Ordering::SeqCst), 1);
fixture.handle.update(3, vec![binding("new", "KeyB")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "new");
let released = messages.iter().position(|v| v["event"] == "release" && v["id"] == "old").unwrap();
let rebound = messages.iter().position(|v| v["event"] == "bound" && v["seq"] == 3).unwrap();
assert!(released < rebound);
fixture.handle.stop().unwrap();
assert!(fixture.dropped.load(Ordering::Acquire), "stop must join backend destruction");
assert_eq!(fixture.clears.load(Ordering::SeqCst), 3);
dispatch_until(&mut fixture.handle, &mut messages, "release", "new");
assert!(fixture.handle.update(4, vec![]).is_err());
let count = messages.len();
fixture.handle.stop().unwrap();
fixture.handle.dispatch(|v| { messages.push(v); Ok(()) }).unwrap();
assert_eq!(messages.len(), count, "stop/release must be idempotent");
}
}
#[test]
fn stalled_event_consumer_unregisters_and_receives_final_release_on_overflow() {
let mut fixture = fake_service();
let mut messages = Vec::new();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut messages, "press", "ptt");
fixture.bursts.send(EVENT_CAPACITY + 1).unwrap();
// Do not dispatch: a backend must terminate independently of the consumer.
eventually(|| fixture.dropped.load(Ordering::Acquire));
assert!(fixture.handle.stop().unwrap_err().to_string().contains("overflow"));
eventually(|| {
fixture.handle.dispatch(|v| { messages.push(v); Ok(()) }).unwrap();
messages.iter().any(|v| v["event"] == "error")
});
let mut held = false;
for message in &messages {
match message["event"].as_str().unwrap() {
"press" => { assert!(!held); held = true; }
"release" => { assert!(held); held = false; }
"error" => assert!(!held, "overflow must release PTT before reporting failure"),
_ => {}
}
}
assert!(!held);
assert_eq!(fixture.clears.load(Ordering::SeqCst), 2);
}
#[test]
fn callback_failure_cancels_without_stranding_consumer_held_key() {
let mut fixture = fake_service();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
eventually(|| fixture.handle.dispatch(|value| {
if value["event"] == "press" { Err(io::Error::other("consumer failed")) } else { Ok(()) }
}).is_err());
fixture.handle.stop().unwrap();
let mut messages = Vec::new();
dispatch_until(&mut fixture.handle, &mut messages, "release", "ptt");
assert_eq!(messages.iter().filter(|v| v["event"] == "release").count(), 1);
assert!(fixture.dropped.load(Ordering::Acquire));
}
#[test]
fn dropping_service_requests_cleanup_without_dispatch() {
let mut fixture = fake_service();
fixture.handle.update(1, vec![binding("ptt", "KeyA")]).unwrap();
dispatch_until(&mut fixture.handle, &mut Vec::new(), "press", "ptt");
drop(fixture.handle);
eventually(|| fixture.dropped.load(Ordering::Acquire));
assert_eq!(fixture.clears.load(Ordering::SeqCst), 2);
}
+91
View File
@@ -0,0 +1,91 @@
use super::{keys, Backend, BindResult, Binding, Event, Result};
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, RegisterHotKey, UnregisterHotKey, MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, MOD_WIN};
use windows_sys::Win32::UI::WindowsAndMessaging::{PeekMessageW, MSG, PM_REMOVE, WM_HOTKEY};
struct Registered {
token: i32,
id: String,
vk: u32,
held: bool,
}
pub(super) struct Windows {
bindings: Vec<Registered>,
next_token: i32,
}
impl Windows {
pub(super) fn new() -> Self {
Self { bindings: Vec::new(), next_token: 1 }
}
}
impl Backend for Windows {
fn name(&self) -> &'static str { "windows_registerhotkey" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
let mut results = Vec::with_capacity(bindings.len());
for binding in bindings {
let Some(key) = keys::lookup(&binding.code) else {
results.push(BindResult::failure(&binding, "unsupported_key", "DOM code is not supported by RegisterHotKey"));
continue;
};
let mut modifiers = MOD_NOREPEAT;
if binding.ctrl { modifiers |= MOD_CONTROL; }
if binding.alt { modifiers |= MOD_ALT; }
if binding.shift { modifiers |= MOD_SHIFT; }
if binding.meta { modifiers |= MOD_WIN; }
let token = self.next_token;
self.next_token = if token == 0xbfff { 1 } else { token + 1 };
// Registrations and message draining remain on this same helper thread.
if unsafe { RegisterHotKey(std::ptr::null_mut(), token, modifiers, key.windows) } == 0 {
let error = std::io::Error::last_os_error();
let code = if error.raw_os_error() == Some(1409) { "in_use" } else { "failed" };
results.push(BindResult::failure(&binding, code, error.to_string()));
} else {
results.push(BindResult::success(&binding, keys::trigger(&binding, &key)));
self.bindings.push(Registered { token, id: binding.id, vk: key.windows, held: false });
}
}
events.push(Event::Bound { seq, results });
Ok(())
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
let mut message: MSG = unsafe { std::mem::zeroed() };
for _ in 0..256 {
if unsafe { PeekMessageW(&mut message, std::ptr::null_mut(), WM_HOTKEY, WM_HOTKEY, PM_REMOVE) } == 0 { break; }
if let Some(binding) = self.bindings.iter_mut().find(|b| b.token as usize == message.wParam) {
if !binding.held {
binding.held = true;
events.push(Event::Key { id: binding.id.clone(), down: true });
}
}
}
// Only query successfully registered keys after their WM_HOTKEY activation.
// No arbitrary key enumeration, modifier polling, low-level hook or raw-input listener.
for binding in &mut self.bindings {
if binding.held && unsafe { GetAsyncKeyState(binding.vk as i32) } >= 0 {
binding.held = false;
events.push(Event::Key { id: binding.id.clone(), down: false });
}
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
let mut error = None;
for binding in self.bindings.drain(..) {
if unsafe { UnregisterHotKey(std::ptr::null_mut(), binding.token) } == 0 {
error = Some(std::io::Error::last_os_error());
}
}
let mut message: MSG = unsafe { std::mem::zeroed() };
while unsafe { PeekMessageW(&mut message, std::ptr::null_mut(), WM_HOTKEY, WM_HOTKEY, PM_REMOVE) } != 0 {}
match error { Some(error) => Err(error.into()), None => Ok(()) }
}
}
impl Drop for Windows {
fn drop(&mut self) { let _ = self.clear(); }
}
+167
View File
@@ -0,0 +1,167 @@
use super::{keys, Backend, BindResult, Binding, Event, Result};
use std::time::{Duration, Instant};
use x11rb::connection::Connection;
use x11rb::protocol::{xproto::{ConnectionExt, GrabMode, ModMask}, Event as XEvent};
use x11rb::rust_connection::RustConnection;
struct Registered {
id: String,
code: u8,
modifiers: u16,
held: bool,
}
pub(super) struct X11 {
connection: RustConnection,
roots: Vec<u32>,
registered: Vec<Registered>,
grabs: Vec<(u32, u8, u16)>,
ignored: u16,
pending_release: Option<(u8, u32, Instant)>,
}
impl X11 {
pub(super) fn new() -> Result<Self> {
let (connection, _) = x11rb::connect(None)?;
let roots = connection.setup().roots.iter().map(|screen| screen.root).collect();
Ok(Self { connection, roots, registered: Vec::new(), grabs: Vec::new(), ignored: 0, pending_release: None })
}
fn release(&mut self, code: u8, events: &mut Vec<Event>) {
for binding in self.registered.iter_mut().filter(|b| b.code == code && b.held) {
binding.held = false;
events.push(Event::Key { id: binding.id.clone(), down: false });
}
}
}
impl Backend for X11 {
fn name(&self) -> &'static str { "x11_xgrabkey" }
fn bind(&mut self, seq: u32, bindings: Vec<Binding>, events: &mut Vec<Event>) -> Result<()> {
let setup = self.connection.setup();
let first = setup.min_keycode;
let count = setup.max_keycode - first + 1;
let mapping = self.connection.get_keyboard_mapping(first, count)?.reply()?;
let width = usize::from(mapping.keysyms_per_keycode);
if width == 0 { return Err("X11 returned an empty keyboard mapping".into()); }
let modifiers = self.connection.get_modifier_mapping()?.reply()?;
let per_modifier = modifiers.keycodes.len() / 8;
self.ignored = 2; // Caps Lock is always the core Lock modifier.
for (index, codes) in modifiers.keycodes.chunks(per_modifier.max(1)).enumerate() {
if codes.iter().any(|code| {
if *code < first { return false; }
let at = usize::from(*code - first) * width;
mapping.keysyms.get(at..at + width).is_some_and(|syms| syms.contains(&0xff7f) || syms.contains(&0xff14))
}) {
self.ignored |= 1 << index;
}
}
// Every lock-state combination, without AnyModifier (which would capture unrelated chords).
let locks: Vec<u16> = (0u16..256).filter(|m| m & !self.ignored == 0).collect();
let mut results = Vec::with_capacity(bindings.len());
for binding in bindings {
let Some(key) = keys::lookup(&binding.code) else {
results.push(BindResult::failure(&binding, "unsupported_key", "DOM code has no X11 keysym mapping"));
continue;
};
let codes: Vec<u8> = mapping.keysyms.chunks(width).enumerate()
.filter(|(_, syms)| syms[0] == key.x11 || (binding.code.starts_with("Numpad") && syms.contains(&key.x11)))
.map(|(index, _)| first + index as u8).collect();
if codes.is_empty() {
results.push(BindResult::failure(&binding, "unsupported_key", "Key is absent from the current X11 base layout"));
continue;
}
let mask = u16::from(binding.shift) | (u16::from(binding.ctrl) << 2)
| (u16::from(binding.alt) << 3) | (u16::from(binding.meta) << 6);
let start = self.grabs.len();
let mut failed = None;
'grabbing: for &root in &self.roots {
for &code in &codes {
for &lock in &locks {
let modifiers = mask | lock;
let reply = self.connection.grab_key(false, root, ModMask::from(modifiers), code, GrabMode::ASYNC, GrabMode::ASYNC)?.check();
if let Err(error) = reply {
failed = Some(error.to_string());
break 'grabbing;
}
self.grabs.push((root, code, modifiers));
}
}
}
if let Some(detail) = failed {
for (root, code, mask) in self.grabs.drain(start..) {
self.connection.ungrab_key(code, root, ModMask::from(mask))?.check()?;
}
results.push(BindResult::failure(&binding, "in_use", detail));
} else {
results.push(BindResult::success(&binding, keys::trigger(&binding, &key)));
for code in codes {
self.registered.push(Registered { id: binding.id.clone(), code, modifiers: mask, held: false });
}
}
}
self.connection.flush()?;
events.push(Event::Bound { seq, results });
Ok(())
}
fn poll(&mut self, events: &mut Vec<Event>) -> Result<()> {
for _ in 0..256 {
let Some(event) = self.connection.poll_for_event()? else { break };
if let Some((code, time, _)) = self.pending_release.take() {
// Core X11 repeat is a release/press pair with identical time and keycode.
if matches!(&event, XEvent::KeyPress(press) if press.detail == code && press.time == time) {
continue;
}
self.release(code, events);
}
match event {
XEvent::KeyPress(press) => {
let mask = u16::from(press.state) & 0xff & !self.ignored;
for binding in &mut self.registered {
if binding.code == press.detail && binding.modifiers == mask && !binding.held {
binding.held = true;
events.push(Event::Key { id: binding.id.clone(), down: true });
}
}
}
XEvent::KeyRelease(release) => {
if self.registered.iter().any(|b| b.code == release.detail && b.held) {
self.pending_release = Some((release.detail, release.time, Instant::now()));
}
}
XEvent::MappingNotify(_) => return Err("X11 keyboard mapping changed; rebind required".into()),
XEvent::Error(error) => return Err(format!("X11 shortcut error: {error:?}").into()),
_ => {} // Never report keys outside the registered set.
}
}
if self.pending_release.as_ref().is_some_and(|(_, _, at)| at.elapsed() >= Duration::from_millis(16)) {
let (code, _, _) = self.pending_release.take().expect("pending release checked");
self.release(code, events);
}
Ok(())
}
fn clear(&mut self) -> Result<()> {
self.registered.clear();
self.pending_release = None;
let mut failure = None;
for (root, code, mask) in self.grabs.drain(..) {
match self.connection.ungrab_key(code, root, ModMask::from(mask)) {
Ok(cookie) => { if let Err(error) = cookie.check() { failure = Some(error.to_string()); } }
Err(error) => failure = Some(error.to_string()),
}
}
// A passive grab becomes an active keyboard grab while its trigger is held.
// Explicitly end that active grab on replacement/shutdown as well.
self.connection.ungrab_keyboard(x11rb::CURRENT_TIME)?.check()?;
self.connection.flush()?;
while self.connection.poll_for_event()?.is_some() {}
match failure { Some(error) => Err(error.into()), None => Ok(()) }
}
}
impl Drop for X11 {
fn drop(&mut self) { let _ = self.clear(); }
}
+96
View File
@@ -0,0 +1,96 @@
//! Disposable identity CLI. Keys never enter stdout or process arguments.
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
use std::time::Duration;
use serde_json::{json, Value};
use crate::profile::{Store, store_error};
use crate::protocol::{ErrorCode, ErrorObj};
fn bad(message: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, message) }
fn required<'a>(args: &'a HashMap<String, String>, name: &str) -> Result<&'a str, ErrorObj> {
args.get(name).map(String::as_str).ok_or_else(|| bad(format!("{name} is required")))
}
pub fn emit(value: &Value) {
let mut out = std::io::stdout().lock();
let _ = writeln!(out, "{value}");
let _ = out.flush();
}
// Only the standalone CLI owns a blocking stdin cancellation reader. The
// embeddable improvement entrypoint never starts or waits for this reader.
fn improve(store: &Store, uid: &str, target: u8, seconds: u64) -> Result<Value, ErrorObj> {
let cancel = Arc::new(AtomicBool::new(false));
let signal = cancel.clone();
std::thread::spawn(move || {
let mut line = String::new();
// Cancel on explicit command, stdin closure or transport failure.
let _ = std::io::stdin().lock().read_line(&mut line);
signal.store(true, Ordering::Relaxed);
});
crate::identity_improve::improve(store, uid, target, Duration::from_secs(seconds), &cancel, |event| emit(&event))
}
fn execute(args: &[String]) -> Result<Value, ErrorObj> {
let action = args.first().ok_or_else(|| bad("identity action required"))?;
let allowed: &[&str] = match action.as_str() {
"list" => &[], "create" => &["--name", "--nickname"],
"update" => &["--uid", "--name", "--nickname"],
"default" => &["--uid"], "delete" => &["--uid", "--confirm-uid"],
"export" => &["--uid", "--out"], "import" => &["--in"],
"improve" => &["--uid", "--target", "--seconds"],
_ => return Err(bad("unknown identity action")),
};
let mut values = HashMap::new();
let mut iter = args[1..].iter();
while let Some(key) = iter.next() {
if key != "--data-dir" && !allowed.contains(&key.as_str()) { return Err(bad("unexpected identity argument")); }
let value = iter.next().ok_or_else(|| bad("missing argument value"))?;
if values.insert(key.clone(), value.clone()).is_some() { return Err(bad("duplicate argument")); }
}
let dir = PathBuf::from(required(&values, "--data-dir")?);
if !dir.is_absolute() { return Err(bad("--data-dir must be absolute")); }
// Atomic vault reads need no profile lock; exports remain available during standalone sessions.
// Mutations share the core lock and Store serializes writers/protects connected identities.
let _guard = if action == "list" || action == "export" { None } else {
Some(crate::locks::lock_dir(&dir, true).map_err(|e| ErrorObj::new(ErrorCode::Io, e))?)
};
let store = Store::new(dir);
let uid = || required(&values, "--uid");
match action.as_str() {
"list" => Ok(json!(store.list().map_err(store_error)?)),
"create" => Ok(json!(store.create_identity(required(&values,"--name")?, required(&values,"--nickname")?).map_err(store_error)?)),
"update" => Ok(json!(store.update_identity(uid()?, values.get("--name").map(String::as_str), values.get("--nickname").map(String::as_str)).map_err(store_error)?)),
"default" => { store.set_default(uid()?).map_err(store_error)?; Ok(json!({"uid":uid()?})) },
"delete" => { store.delete_identity(uid()?, required(&values,"--confirm-uid")?).map_err(store_error)?; Ok(json!({"uid":uid()?})) },
"export" => {
let ini = store.export_ini(uid()?).map_err(store_error)?;
let out = Path::new(required(&values,"--out")?);
if !out.is_absolute() { return Err(bad("--out must be absolute")); }
crate::secure_fs::write_atomic(out, ini.as_bytes(), true).map_err(|e| ErrorObj::new(ErrorCode::Io, e.to_string()))?;
Ok(json!({"uid":uid()?}))
},
"import" => {
let input = Path::new(required(&values,"--in")?);
if !input.is_absolute() { return Err(bad("--in must be absolute")); }
let mut text = String::new();
File::open(input).and_then(|f| f.take(65537).read_to_string(&mut text)).map_err(|e| ErrorObj::new(ErrorCode::Io, e.to_string()))?;
if text.len() > 65536 { return Err(bad("identity file exceeds 64 KiB")); }
Ok(json!(store.import_ini(&[&text]).map_err(store_error)?))
},
"improve" => {
let target = required(&values,"--target")?.parse::<u8>().map_err(|_| bad("invalid target"))?;
let seconds = values.get("--seconds").map(|v| v.parse::<u64>()).transpose().map_err(|_| bad("invalid duration"))?.unwrap_or(30);
if !(1..=crate::profile::MAX_TARGET_LEVEL).contains(&target) || !(1..=60).contains(&seconds) { return Err(bad("target must be 1–100; duration 1–60 seconds")); }
improve(&store, uid()?, target, seconds)
},
_ => unreachable!(),
}
}
pub fn run(args: &[String]) -> ExitCode {
match execute(args) {
Ok(result) => { emit(&json!({"ok":true,"result":result})); ExitCode::SUCCESS },
Err(error) => { emit(&json!({"ok":false,"error":error})); ExitCode::from(1) },
}
}
+168
View File
@@ -0,0 +1,168 @@
//! Bounded, cancellable hash-cash work. One core at <=25% duty cycle for at most 60 seconds.
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use sha1::{Digest, Sha1};
use serde_json::{json, Value};
use crate::profile::{Store, store_error};
use crate::protocol::{ErrorCode, ErrorObj};
// TeamSpeak counts trailing bits of each SHA1 byte, starting with the first byte.
// Decimal conversion uses a stack buffer: no allocation per candidate.
fn quality(prefix: &Sha1, mut offset: u64) -> u8 {
let mut digits = [0u8; 20];
let mut pos = digits.len();
loop {
pos -= 1; digits[pos] = b'0' + (offset % 10) as u8; offset /= 10;
if offset == 0 { break; }
}
let mut hash = prefix.clone();
hash.update(&digits[pos..]);
let mut level = 0;
for byte in hash.finalize() {
if byte == 0 { level += 8; } else { level += byte.trailing_zeros() as u8; break; }
}
level
}
/// Improve an identity on the caller's worker, persisting progress before notifying it.
/// Cancellation is caller-owned; this function creates no threads or transport readers.
/// Returning (including cancellation) completes the final durable checkpoint.
pub fn improve(
store: &Store,
uid: &str,
target: u8,
duration: Duration,
cancel: &AtomicBool,
mut progress: impl FnMut(Value),
) -> Result<Value, ErrorObj> {
if !(1..=crate::profile::MAX_TARGET_LEVEL).contains(&target)
|| duration.is_zero() || duration > Duration::from_secs(60)
{
return Err(ErrorObj::new(ErrorCode::BadRequest, "target must be 1–100; duration greater than zero and at most 60 seconds"));
}
let start = store.improve_start(uid).map_err(store_error)?;
let mut prefix = Sha1::new(); prefix.update(start.omega.as_bytes());
let begun = Instant::now();
let mut checkpoint = Instant::now();
let mut next = start.start;
let mut level = start.level;
let mut best = None;
let mut exhausted = false;
while level < target && begun.elapsed() < duration && !cancel.load(Ordering::Relaxed) {
let slice = Instant::now();
while slice.elapsed() < Duration::from_millis(5) && !cancel.load(Ordering::Relaxed) {
let candidate = quality(&prefix, next);
if candidate > level { level = candidate; best = Some(next); }
if next == u64::MAX { exhausted = true; break; }
next += 1;
if level >= target { break; }
}
if checkpoint.elapsed() >= Duration::from_millis(500) || level >= target || exhausted {
level = store.record_improvement(uid, best.take(), next).map_err(store_error)?;
progress(json!({"event":"identity_progress","uid":uid,"level":level,"target":target,"searched":next.to_string(),"elapsed_ms":begun.elapsed().as_millis()}));
checkpoint = Instant::now();
}
if exhausted { break; }
std::thread::sleep(Duration::from_millis(15));
}
level = store.record_improvement(uid, best, next).map_err(store_error)?;
Ok(json!({"uid":uid,"level":level,"target":target,"reached":level>=target,"canceled":cancel.load(Ordering::Relaxed),"bounded":level<target,"exhausted":exhausted,"searched":next.to_string()}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_sha1_vectors_and_decimal_boundaries() {
// SHA1("0")=b6589fc6… -> first byte 0xb6 has one trailing zero bit.
assert_eq!(quality(&Sha1::new(), 0), 1);
// SHA1("1")=356a192b… -> odd first byte gives zero bits.
assert_eq!(quality(&Sha1::new(), 1), 0);
for offset in [0, 1, 9, 10, 99, 100, u64::MAX] {
let mut p = Sha1::new(); p.update(b"public-key");
let raw = Sha1::digest(format!("public-key{offset}").as_bytes());
let expected = raw.iter().take_while(|b| **b == 0).count() as u8 * 8 + raw.iter().find(|b| **b != 0).map(|b| b.trailing_zeros() as u8).unwrap_or(0);
assert_eq!(quality(&p, offset), expected);
}
}
#[test]
fn cancellation_checkpoints_without_changing_identity() {
let dir = crate::profile::tests::TempDir::new("improve-cancel");
let store = Store::new(&dir.0);
let identity = store.create_identity("Temporary", "Temporary").unwrap();
let before = store.export_ini(&identity.uid).unwrap();
let result = std::thread::scope(|scope| {
scope.spawn(|| improve(&store, &identity.uid, 100, Duration::from_secs(1), &AtomicBool::new(true), |_| panic!("pre-canceled work must not report progress")))
.join().expect("native worker joins without a stdin reader").unwrap()
});
assert_eq!(result["canceled"], true);
assert_eq!(before, store.export_ini(&identity.uid).unwrap());
}
#[test]
fn native_bounds_reject_before_touching_identity() {
let dir = crate::profile::tests::TempDir::new("improve-invalid");
let store = Store::new(&dir.0);
let info = store.create_identity("Temporary", "Temporary").unwrap();
let before = store.export_ini(&info.uid).unwrap();
let start = store.improve_start(&info.uid).unwrap().start;
for (target, duration) in [
(0, Duration::from_secs(1)),
(101, Duration::from_secs(1)),
(100, Duration::ZERO),
(100, Duration::from_secs(61)),
] {
let error = improve(&store, &info.uid, target, duration, &AtomicBool::new(false), |_| panic!("invalid work must not report progress")).unwrap_err();
assert_eq!(serde_json::to_value(error).unwrap()["code"], "bad_request");
}
assert_eq!(before, store.export_ini(&info.uid).unwrap());
assert_eq!(start, store.improve_start(&info.uid).unwrap().start);
}
#[test]
fn quality_matches_protocol_identity_and_deadline_resumes() {
let dir = crate::profile::tests::TempDir::new("improve-bound");
let store = Store::new(&dir.0);
let info = store.create_identity("Temporary", "Temporary").unwrap();
let stored = store.load_identity().unwrap().unwrap();
let start = store.improve_start(&info.uid).unwrap();
let mut prefix = Sha1::new(); prefix.update(start.omega.as_bytes());
assert_eq!(quality(&prefix, stored.identity.counter()), stored.identity.level());
let result = improve(&store, &info.uid, 100, Duration::from_millis(20), &AtomicBool::new(false), |_| {}).unwrap();
assert_eq!(result["bounded"], true);
let resumed = store.improve_start(&info.uid).unwrap();
assert!(resumed.start > start.start);
assert!(resumed.level >= start.level);
assert_eq!(store.load_identity().unwrap().unwrap().uid, info.uid);
assert_eq!(resumed.start.to_string(), result["searched"].as_str().unwrap());
}
#[test]
fn cancellation_during_search_preserves_checkpoint_and_resumes() {
let dir = crate::profile::tests::TempDir::new("improve-running-cancel");
let store = Store::new(&dir.0);
let info = store.create_identity("Temporary", "Temporary").unwrap();
let original_key = store.load_identity().unwrap().unwrap().identity.key().to_ts();
let mut previous = store.improve_start(&info.uid).unwrap().start;
for _ in 0..2 {
let cancel = AtomicBool::new(false);
let mut checkpoint = None;
// Cancel synchronously at a durable checkpoint, without a timing race
// against a detached canceller or relying on thread scheduling.
let result = improve(&store, &info.uid, 100, Duration::from_secs(60), &cancel, |event| {
assert_eq!(event["uid"], info.uid);
let persisted = store.improve_start(&info.uid).unwrap();
assert_eq!(event["searched"], persisted.start.to_string());
checkpoint = Some(persisted.start);
cancel.store(true, Ordering::Relaxed);
}).unwrap();
assert_eq!(result["canceled"], true);
let next = checkpoint.expect("search must report a durable checkpoint");
assert!(next > previous);
let persisted = store.improve_start(&info.uid).unwrap();
assert_eq!(persisted.start, next);
assert_eq!(result["searched"], next.to_string());
let loaded = store.load_identity().unwrap().unwrap();
assert_eq!(loaded.uid, info.uid);
assert_eq!(loaded.identity.key().to_ts(), original_key);
let mut prefix = Sha1::new(); prefix.update(persisted.omega.as_bytes());
assert_eq!(quality(&prefix, loaded.identity.counter()), persisted.level);
previous = next;
}
}
}
+28
View File
@@ -0,0 +1,28 @@
//! Embedded TeamSpeak domain services and the independent diagnostic CLI adapters.
pub mod admin;
pub mod app_audio;
pub mod audio;
mod events;
pub mod file_transfer;
pub mod hotkeys;
mod keyfmt;
pub mod identity_cli;
pub mod identity_improve;
pub mod locks;
pub mod media;
pub mod menu;
pub mod output;
pub mod profile;
pub mod protocol;
pub mod recording;
mod rawcmd;
pub mod runtime;
pub mod secure_fs;
pub mod session;
mod snapshot;
pub mod stdio;
#[cfg(test)]
mod test_exec;
pub mod vad;
pub mod voice_dsp;
pub mod whisper;
+23
View File
@@ -0,0 +1,23 @@
use std::fs::{File, OpenOptions, TryLockError};
use std::path::Path;
use crate::secure_fs;
/// Cooperates with diagnostic CLI and embedded sessions without copying private identity keys.
pub fn lock_dir(dir: &Path, shared: bool) -> Result<File, String> {
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
let path = dir.join("core.lock");
let file = OpenOptions::new().create(true).truncate(false).write(true).open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
match if shared { file.try_lock_shared() } else { file.try_lock() } {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
}
}
pub fn lock_run(data_dir: &Path, connection_dir: Option<&Path>) -> Result<Vec<File>, String> {
match connection_dir {
None => Ok(vec![lock_dir(data_dir, false)?]),
Some(conn) => Ok(vec![lock_dir(data_dir, true)?, lock_dir(conn, false)?]),
}
}
+41 -99
View File
@@ -1,19 +1,7 @@
//! TeamsPeach core: TeamSpeak protocol backend speaking newline-delimited JSON on stdio.
//! Contract: `docs/bridge.md`.
mod audio;
mod keyfmt;
mod media;
mod profile;
mod protocol;
mod rawcmd;
mod secure_fs;
mod session;
mod snapshot;
mod stdio;
use std::fs::{File, OpenOptions, TryLockError};
use std::io::{Read, Write};
use teamspeach_core::{app_audio, audio, hotkeys, identity_cli, locks, output, profile, protocol, session, stdio};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
@@ -23,43 +11,34 @@ use serde_json::json;
use tokio::sync::mpsc;
use tracing::{error, info};
use crate::audio::AudioInQueue;
use crate::profile::Store;
use crate::protocol::{ErrorObj, PROTOCOL_VERSION};
use crate::stdio::Out;
use audio::AudioInQueue;
use profile::Store;
use protocol::PROTOCOL_VERSION;
use output::Out;
const EXIT_FATAL: u8 = 1;
const EXIT_USAGE: u8 = 2;
const EXIT_DATA_DIR: u8 = 3;
const MAX_IMPORT_BYTES: u64 = 64 * 1024;
const USAGE: &str = "usage:
teamspeach-core --data-dir <ABSOLUTE_DIR>
teamspeach-core identity export --data-dir <ABSOLUTE_DIR> --out <FILE>
teamspeach-core identity import --data-dir <ABSOLUTE_DIR> --in <FILE> [--replace]";
teamspeach-core --data-dir <ABSOLUTE_DIR> [--connection-dir <ABSOLUTE_DIR>]
teamspeach-core identity <list|create|update|default|delete|export|import|improve> --data-dir <ABSOLUTE_DIR> [options]
teamspeach-core hotkeys";
enum Mode {
Run { data_dir: PathBuf },
Export { data_dir: PathBuf, out: PathBuf },
Import { data_dir: PathBuf, input: PathBuf, replace: bool },
/// `connection_dir`: one of several simultaneous cores sharing the profile in `data_dir`.
Run { data_dir: PathBuf, connection_dir: Option<PathBuf> },
}
fn parse_args(args: &[String]) -> Result<Mode, String> {
let (sub, rest) = match args {
[a, b, rest @ ..] if a == "identity" && (b == "export" || b == "import") => (Some(b.as_str()), rest),
rest => (None, rest),
};
let rest = args;
let mut data_dir = None;
let mut out = None;
let mut input = None;
let mut replace = false;
let mut connection_dir = None;
let mut it = rest.iter();
while let Some(a) = it.next() {
let mut value = |name: &str| it.next().cloned().ok_or_else(|| format!("{name} needs a value"));
match a.as_str() {
"--data-dir" => data_dir = Some(PathBuf::from(value("--data-dir")?)),
"--out" if sub == Some("export") => out = Some(PathBuf::from(value("--out")?)),
"--in" if sub == Some("import") => input = Some(PathBuf::from(value("--in")?)),
"--replace" if sub == Some("import") => replace = true,
"--connection-dir" => connection_dir = Some(PathBuf::from(value("--connection-dir")?)),
other => return Err(format!("unexpected argument {other:?}")),
}
}
@@ -67,63 +46,21 @@ fn parse_args(args: &[String]) -> Result<Mode, String> {
if !data_dir.is_absolute() {
return Err("--data-dir must be an absolute path".into());
}
Ok(match sub {
None => Mode::Run { data_dir },
Some("export") => Mode::Export { data_dir, out: out.ok_or("--out is required")? },
Some(_) => Mode::Import { data_dir, input: input.ok_or("--in is required")?, replace },
})
if let Some(dir) = &connection_dir {
if !dir.is_absolute() {
return Err("--connection-dir must be an absolute path".into());
}
if dir == &data_dir {
return Err("--connection-dir must differ from --data-dir".into());
}
}
Ok(Mode::Run { data_dir, connection_dir })
}
/// Exclusive lock on `<data-dir>/core.lock`, held for the process lifetime.
fn lock_data_dir(dir: &Path) -> Result<File, String> {
secure_fs::ensure_private_dir(dir).map_err(|e| format!("cannot create data dir {}: {e}", dir.display()))?;
let path = dir.join("core.lock");
let file = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
match file.try_lock() {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())),
Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())),
}
}
fn print_cli_result(result: Result<String, ErrorObj>) -> ExitCode {
let (line, code) = match result {
Ok(uid) => (json!({ "ok": true, "uid": uid }), ExitCode::SUCCESS),
Err(e) => (json!({ "ok": false, "error": e }), ExitCode::from(EXIT_FATAL)),
};
let mut stdout = std::io::stdout().lock();
let _ = writeln!(stdout, "{line}");
let _ = stdout.flush();
code
}
fn export(data_dir: &Path, out: &Path) -> Result<String, ErrorObj> {
// Unlocked read-only access is safe: identity.json/profile.json are only ever replaced by
// atomic rename (key-offset upgrade, rename, import --replace), so a concurrent reader sees
// one complete version, and load_identity verifies it.
let (ini, uid) = Store::new(data_dir).export_ts_ini().map_err(session::store_error)?;
secure_fs::write_atomic(out, ini.as_bytes(), true)
.map_err(|e| ErrorObj::new(protocol::ErrorCode::Io, format!("writing {}: {e}", out.display())))?;
Ok(uid)
}
fn import(data_dir: &Path, input: &Path, replace: bool) -> Result<String, ErrorObj> {
let io = |e: std::io::Error| ErrorObj::new(protocol::ErrorCode::Io, format!("reading {}: {e}", input.display()));
let mut text = String::new();
File::open(input).map_err(io)?.take(MAX_IMPORT_BYTES + 1).read_to_string(&mut text).map_err(io)?;
if text.len() as u64 > MAX_IMPORT_BYTES {
return Err(ErrorObj::new(protocol::ErrorCode::BadRequest, "identity file is too large"));
}
Store::new(data_dir).import_ts_ini(&text, replace).map_err(session::store_error)
}
fn run(data_dir: PathBuf) -> ExitCode {
let _lock = match lock_data_dir(&data_dir) {
fn run(data_dir: PathBuf, connection_dir: Option<PathBuf>) -> ExitCode {
let _locks = match locks::lock_run(&data_dir, connection_dir.as_deref()) {
Ok(l) => l,
Err(e) => {
error!("{e}");
@@ -138,8 +75,8 @@ fn run(data_dir: PathBuf) -> ExitCode {
}
};
rt.block_on(async move {
let (out, out_rx) = Out::new();
let writer = tokio::spawn(stdio::run_writer(out_rx));
let (out, out_rx, playback_rx) = Out::new();
let writer = tokio::spawn(stdio::run_writer(out_rx, playback_rx));
let audio_in = Arc::new(AudioInQueue::new());
let (cmd_tx, cmd_rx) = mpsc::channel(64);
{
@@ -151,7 +88,7 @@ fn run(data_dir: PathBuf) -> ExitCode {
}
out.json(&json!({ "event": "ready", "protocol": PROTOCOL_VERSION, "core_version": env!("CARGO_PKG_VERSION") }))
.await;
info!(data_dir = %data_dir.display(), "teamspeach-core ready");
info!(data_dir = %data_dir.display(), connection_dir = ?connection_dir.as_deref().map(Path::display), "teamspeach-core ready");
session::Session::new(Store::new(&data_dir), out, audio_in).run(cmd_rx).await;
// All `Out` senders are gone once the session is dropped; the writer drains and exits.
let _ = writer.await;
@@ -172,6 +109,19 @@ fn main() -> ExitCode {
.init();
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().is_some_and(|arg| arg == "app-audio") {
return app_audio::run(&args[1..]);
}
if args.first().is_some_and(|arg| arg == "identity") {
return identity_cli::run(&args[1..]);
}
if args.first().is_some_and(|arg| arg == "hotkeys") {
if args.len() != 1 { eprintln!("hotkeys takes no arguments"); return ExitCode::from(EXIT_USAGE); }
return match hotkeys::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => { eprintln!("hotkeys: {e}"); ExitCode::from(EXIT_FATAL) }
};
}
let mode = match parse_args(&args) {
Ok(m) => m,
Err(e) => {
@@ -180,14 +130,6 @@ fn main() -> ExitCode {
}
};
match mode {
Mode::Run { data_dir } => run(data_dir),
Mode::Export { data_dir, out } => print_cli_result(export(&data_dir, &out)),
Mode::Import { data_dir, input, replace } => match lock_data_dir(&data_dir) {
Ok(_lock) => print_cli_result(import(&data_dir, &input, replace)),
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(EXIT_DATA_DIR)
}
},
Mode::Run { data_dir, connection_dir } => run(data_dir, connection_dir),
}
}
+321
View File
@@ -0,0 +1,321 @@
//! Target-bound user actions. Protocol names/fields follow pinned ReSpeak Messages.toml.
//! Permission hints come from the server; role names are never authorization evidence.
use std::collections::{BTreeMap, HashMap};
use base64::prelude::*;
use serde::Deserialize;
use serde_json::{json, Value};
use tsclientlib::{ClientId, GroupType};
use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType};
use crate::protocol::{ErrorCode, ErrorObj};
use crate::rawcmd::RawNotification;
pub type Row = BTreeMap<String, String>;
/// Live per-connection volume changes from the client menu: (dB modifier, muted) by raw UID. Without a
/// live entry the persisted modifier applies (unmuted); mute is never persisted. See voice_dsp.rs.
#[derive(Default)]
pub struct LocalVolumes(HashMap<Vec<u8>, (f32, bool)>);
impl LocalVolumes {
pub fn set(&mut self, uid: &[u8], db: f32, muted: bool) { self.0.insert(uid.to_vec(), (db, muted)); }
pub fn get(&self, uid: &[u8], persisted: &HashMap<Vec<u8>, f32>) -> (f32, bool) {
self.0.get(uid).copied().unwrap_or_else(|| (persisted.get(uid).copied().unwrap_or(0.0), false))
}
/// Linear gain for the mixer (0 when muted or at -200 dB).
pub fn gain(&self, uid: &[u8], persisted: &HashMap<Vec<u8>, f32>) -> f32 {
let (db, muted)=self.get(uid, persisted); if muted {0.0} else {crate::voice_dsp::db_to_gain(db)}
}
pub fn clear(&mut self) { self.0.clear(); }
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Target { pub client_id: u16, pub uid: String }
#[derive(Clone, Debug, PartialEq)]
pub struct ActionRequest { pub target: Target, pub generation: u64, pub action: Action }
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag="action", rename_all="snake_case", deny_unknown_fields)]
pub enum Action {
Poke { message: String }, ConnectionInfo {}, Commander { enabled: bool },
ServerGroup { group_id: u64, enabled: bool }, ChannelGroup { group_id: u64, channel_id: u64 },
ClientPermissions {}, ChannelPermissions { channel_id: u64 },
SetClientPermission { permission_id: u32, value: Option<i32>, skip: bool },
SetChannelPermission { channel_id: u64, permission_id: u32, value: Option<i32> },
KickChannel { reason: String }, KickServer { reason: String }, Ban { reason: String, duration: u32 },
Volume { db: f32, muted: bool }, Avatar { data: String },
MoveToOwnChannel { #[serde(default)] password: Option<String>, expected_channel_id: u64 }, DeleteAvatar {},
}
impl Action {
pub fn key(&self) -> &'static str { match self {
Self::Poke{..}=>"poke",Self::ConnectionInfo{}=>"connection_info",Self::Commander{..}=>"commander",
Self::ServerGroup{..}=>"server_group",Self::ChannelGroup{..}=>"channel_group",
Self::ClientPermissions{}=>"client_permissions",Self::ChannelPermissions{..}=>"channel_permissions",
Self::SetClientPermission{..}=>"set_client_permission",Self::SetChannelPermission{..}=>"set_channel_permission",
Self::KickChannel{..}=>"kick_channel",Self::KickServer{..}=>"kick_server",Self::Ban{..}=>"ban",
Self::Volume{..}=>"volume",Self::Avatar{..}=>"avatar",
Self::MoveToOwnChannel{..}=>"move_to_own_channel",Self::DeleteAvatar{}=>"delete_avatar",
}}
pub fn response(&self) -> Option<&'static str> { match self {
Self::ConnectionInfo{}=>Some("notifyconnectioninfo"), Self::ClientPermissions{}=>Some("notifyclientpermlist"),
Self::ChannelPermissions{..}=>Some("notifychannelclientpermlist"), _=>None,
}}
}
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(())
}
pub fn parse_action(mut value: Value) -> Result<ActionRequest, ErrorObj> {
let obj=value.as_object_mut().ok_or_else(||bad("args must be an object"))?;
let target=serde_json::from_value::<Target>(json!({"client_id":obj.remove("client_id"),"uid":obj.remove("uid")})).map_err(|e|bad(e.to_string()))?;
let generation=obj.remove("generation").and_then(|v|v.as_u64()).filter(|v|*v>0).ok_or_else(||bad("generation is required"))?;
if matches!(obj.get("action").and_then(Value::as_str),Some("set_client_permission"|"set_channel_permission")) && !obj.contains_key("value") { return Err(bad("value is required; use null explicitly to remove a permission")); }
let action:Action=serde_json::from_value(value).map_err(|e|bad(e.to_string()))?;
Ok(ActionRequest { target, generation, action })
}
pub(crate) fn validate_action(request: &ActionRequest) -> Result<(), ErrorObj> {
validate_target(&request.target)?;
crate::admin::generation(request.generation)?;
match &request.action {
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,..} 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)?;},
_=>{},
}
Ok(())
}
pub fn avatar_bytes(data:&str)->Result<Vec<u8>,ErrorObj>{
if data.len()>174_764 { return Err(bad("avatar exceeds 128 KiB")); }
let bytes=BASE64_STANDARD.decode(data).map_err(|_|bad("avatar is not base64"))?;
if bytes.len()>128*1024 || !(bytes.starts_with(b"\x89PNG\r\n\x1a\n") || bytes.starts_with(&[0xff,0xd8,0xff])) {return Err(bad("avatar must be PNG or JPEG, at most 128 KiB"));}
Ok(bytes)
}
pub fn command(name:&'static str,args:&[(&str,String)])->OutCommand {
let mut cmd=OutCommand::new(Direction::C2S,Flags::empty(),PacketType::Command,name);
for (key,value) in args {cmd.write_arg(key,value);}
cmd
}
pub fn action_command(action:&Action,client_id:u16,dbid:u64)->Option<OutCommand>{
let clid=client_id.to_string(); let dbid=dbid.to_string();
let (name,args)=match action {
Action::Poke{message}=>("clientpoke",vec![("clid",clid),("msg",message.clone())]),
Action::ConnectionInfo{}=>("getconnectioninfo",vec![("clid",clid)]),
Action::Commander{enabled}=>("clientupdate",vec![("client_is_channel_commander",u8::from(*enabled).to_string())]),
Action::ServerGroup{group_id,enabled}=>(if *enabled {"servergroupaddclient"} else {"servergroupdelclient"},vec![("sgid",group_id.to_string()),("cldbid",dbid)]),
Action::ChannelGroup{group_id,channel_id}=>("setclientchannelgroup",vec![("cgid",group_id.to_string()),("cid",channel_id.to_string()),("cldbid",dbid)]),
Action::ClientPermissions{}=>("clientpermlist",vec![("cldbid",dbid)]),
Action::ChannelPermissions{channel_id}=>("channelclientpermlist",vec![("cid",channel_id.to_string()),("cldbid",dbid)]),
Action::SetClientPermission{permission_id,value,skip}=>{
let mut args=vec![("cldbid",dbid),("permid",permission_id.to_string())];
if let Some(v)=value {args.extend([("permvalue",v.to_string()),("permskip",u8::from(*skip).to_string())]);}
(if value.is_some(){"clientaddperm"}else{"clientdelperm"},args)
},
Action::SetChannelPermission{channel_id,permission_id,value}=>{
let mut args=vec![("cid",channel_id.to_string()),("cldbid",dbid),("permid",permission_id.to_string())];
if let Some(v)=value {args.push(("permvalue",v.to_string()));}
(if value.is_some(){"channelclientaddperm"}else{"channelclientdelperm"},args)
},
Action::KickChannel{reason}|Action::KickServer{reason}=>("clientkick",vec![("clid",clid),("reasonid",if matches!(action,Action::KickChannel{..}){"4"}else{"5"}.into()),("reasonmsg",reason.clone())]),
Action::Ban{reason,duration}=>("banclient",vec![("clid",clid),("time",duration.to_string()),("banreason",reason.clone())]),
_=>return None,
};
Some(command(name,&args))
}
#[derive(Default)]
pub struct Permissions { pub catalog: Vec<Value>, values: HashMap<u32,i32> }
impl Permissions {
pub fn apply(&mut self,raw:&RawNotification){
match raw.name.as_str(){
"notifypermissionlist"=>{
self.catalog.clear();
for row in &raw.items { if let Some(name)=row.get("permname") {
let id=row.get("permid").and_then(|v|v.parse::<u32>().ok()).unwrap_or(self.catalog.len() as u32+1);
self.catalog.push(json!({"id":id,"name":name,"description":row.get("permdesc")}));
}}
},
"notifyclientneededpermissions"=>for row in &raw.items {
if let Some(id)=row.get("permid").and_then(|v|v.parse().ok()) {
if let Some(value)=row.get("permvalue").and_then(|v|v.parse().ok()){self.values.insert(id,value);}else{self.values.remove(&id);}
}
},
_=>{},
}
}
fn value(&self,name:&str)->Option<i32>{self.catalog.iter().find(|p|p["name"]==name).and_then(|p|p["id"].as_u64()).and_then(|id|self.values.get(&(id as u32)).copied())}
/// Own effective value of a named permission (`None` = unknown: not in the catalog or not granted).
pub fn named(&self,name:&str)->Option<i32>{self.value(name)}
/// Whether the permission catalog (`permissionlist`) has been received.
pub fn has_catalog(&self)->bool{!self.catalog.is_empty()}
fn power(&self,name:&str,needed:Option<i32>)->Value {cap(self.value(name).zip(needed).map(|(p,n)|p>=n),"effective_permission")}
pub fn context(&self,book:&tsclientlib::data::Connection,target:&Target,generation:u64)->Result<Value,ErrorObj>{
let client=book.clients.get(&ClientId(target.client_id)).ok_or_else(||ErrorObj::new(ErrorCode::NotFound,"client is no longer visible"))?;
validate_live_identity(target,client.id.0,client.uid.as_ref())?;
let own=book.own_client==client.id;
let hints=client.permission_hints.map(|h|h.bits());
let mut capabilities=serde_json::Map::new();
for (key,bit) in [("poke",32),("kick_channel",2),("kick_server",1),("ban",4),("set_client_permission",256),("set_channel_permission",256)] {
capabilities.insert(key.into(),target_hint(own,key,hints,bit));
}
for (key,perm) in [("commander","b_client_use_channel_commander"),("avatar","i_client_max_avatar_filesize")] {
capabilities.insert(key.into(),if own{cap(self.value(perm).map(|v|v!=0),"effective_permission")}else{json!({"allowed":false,"reason":"self_only","source":"target"})});
}
for key in ["connection_info","client_permissions","channel_permissions","server_group","channel_group"] {capabilities.insert(key.into(),cap(None,"server"));}
for (key,perm) in [("connection_info","b_client_info_view"),("client_permissions","b_virtualserver_client_permission_list"),("channel_permissions","b_virtualserver_channelclient_permission_list")] {
capabilities.insert(key.into(),cap(self.value(perm).map(|v|v!=0),"effective_permission"));
}
capabilities.insert("volume".into(),json!({"allowed":!own,"reason":if own{"other_only"}else{"local"},"source":"local"}));
let own_channel=book.clients.get(&book.own_client).map(|c|c.channel);
capabilities.insert("move_to_own_channel".into(),if own||own_channel==Some(client.channel){json!({"allowed":false,"reason":"same_channel","source":"target"})}else{cap(None,"server")});
capabilities.insert("delete_avatar".into(),if own{cap(Some(true),"self")}else{cap(self.value("b_client_avatar_delete_other").map(|v|v!=0),"effective_permission")});
let mut server_groups:Vec<Value>=book.server_groups.values().filter(|g|g.group_type==GroupType::Regular).map(|g|json!({"id":g.id.0,"name":g.name,"member":client.server_groups.contains(&g.id),"can_add":self.power("i_group_member_add_power",Some(g.needed_member_add_power)),"can_remove":self.power("i_group_member_remove_power",g.needed_member_remove_power)})).collect();
server_groups.sort_by_key(|g|g["id"].as_u64());
let mut channel_groups:Vec<Value>=book.channel_groups.values().filter(|g|g.group_type==GroupType::Regular).map(|g|json!({"id":g.id.0,"name":g.name,"member":client.channel_group==g.id,"can_add":self.power("i_group_member_add_power",Some(g.needed_member_add_power)),"can_remove":self.power("i_group_member_remove_power",g.needed_member_remove_power)})).collect();
channel_groups.sort_by_key(|g|g["id"].as_u64());
let remove=channel_groups.iter().find(|g|g["member"]==true).and_then(|g|g["can_remove"]["allowed"].as_bool());
for group in &mut channel_groups {
let add=group["can_add"]["allowed"].as_bool();
let allowed=if group["member"]==true {Some(true)} else if add==Some(false)||remove==Some(false){Some(false)}else{add.zip(remove).map(|(a,r)|a&&r)};
group["can_set"]=cap(allowed,"effective_permission");
}
Ok(json!({"generation":generation,"client_id":target.client_id,"uid":target.uid,"is_self":own,"channel_id":client.channel.0,"is_channel_commander":client.is_channel_commander,"capabilities":capabilities,"server_groups":server_groups,"channel_groups":channel_groups,"permissions":self.catalog}))
}
}
fn cap(allowed:Option<bool>,source:&str)->Value {json!({"allowed":allowed,"reason":match allowed{Some(true)=>"server_hint",Some(false)=>"permission_denied",None=>"server_decides"},"source":source})}
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(ErrorObj::new(ErrorCode::TargetChanged,"client identity changed; reopen the menu"));}
Ok(())
}
fn target_hint(own:bool,key:&str,hints:Option<u64>,bit:u64)->Value {
if own && matches!(key,"poke"|"kick_channel"|"kick_server"|"ban") {json!({"allowed":false,"reason":"other_only","source":"target"})}
else {cap(hints.map(|h|h&bit!=0),"server_hint")}
}
pub fn response_matches(row:&Row,response:&str,client_id:u16,dbid:u64,channel:Option<u64>)->bool {
let number=|key:&str|row.get(key).and_then(|v|v.parse::<u64>().ok());
match response {
"notifyconnectioninfo"=>number("clid")==Some(u64::from(client_id)),
"notifyclientpermlist"=>number("cldbid")==Some(dbid),
"notifychannelclientpermlist"=>number("cldbid")==Some(dbid)&&number("cid")==channel,
_=>false,
}
}
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::*;
fn parse_action(value: Value) -> Result<ActionRequest, ErrorObj> {
let request = super::parse_action(value)?;
validate_action(&request)?;
Ok(request)
}
#[test] fn command_fixture_escapes_and_uses_real_protocol_fields(){
let action=Action::KickChannel{reason:"a b|c".into()};
let packet=action_command(&action,42,9).unwrap().into_packet();
let raw=crate::rawcmd::parse(packet.content()).unwrap();
assert_eq!(raw.name,"clientkick"); assert_eq!(raw.items[0]["reasonid"],"4"); assert_eq!(raw.items[0]["reasonmsg"],"a b|c");
let p=action_command(&Action::SetChannelPermission{channel_id:7,permission_id:99,value:None},42,9).unwrap().into_packet();
let r=crate::rawcmd::parse(p.content()).unwrap(); assert_eq!(r.name,"channelclientdelperm"); assert_eq!(r.items[0]["cldbid"],"9");
}
#[test] fn effective_permissions_are_server_data_not_group_names(){
let mut p=Permissions::default();
p.apply(&crate::rawcmd::parse(b"notifypermissionlist group_id_end=1|permname=i_group_member_add_power permdesc=power").unwrap());
assert_eq!(p.power("i_group_member_add_power",Some(50))["allowed"],Value::Null);
p.apply(&crate::rawcmd::parse(b"notifyclientneededpermissions permid=1 permvalue=25").unwrap());
assert_eq!(p.power("i_group_member_add_power",Some(50))["allowed"],false);
p.apply(&crate::rawcmd::parse(b"notifyclientneededpermissions permid=1 permvalue=75").unwrap());
assert_eq!(p.power("i_group_member_add_power",Some(50))["allowed"],true);
}
#[test] fn target_and_action_validation_rejects_injection_and_nonfinite_gain(){
let base=json!({"client_id":42,"uid":"fixture","generation":1,"action":"poke","message":"hello","unexpected":true});
assert!(parse_action(base).is_err());
assert!(parse_action(json!({"client_id":0,"uid":"x","generation":1,"action":"connection_info"})).is_err());
assert!(parse_action(json!({"client_id":42,"uid":"x","generation":1,"action":"volume","db":10.5,"muted":false})).is_err());
assert!(parse_action(json!({"client_id":42,"uid":"x","generation":1,"action":"volume","db":-3.25,"muted":false})).is_err());
assert!(parse_action(json!({"client_id":42,"uid":"x","generation":1,"action":"volume","value":1.0,"muted":false})).is_err());
}
#[test] fn read_notifications_cannot_cross_targets_or_channels(){
let row=crate::rawcmd::parse(b"notifychannelclientpermlist cldbid=8 cid=3 permid=42 permvalue=75").unwrap().items.remove(0);
assert!(response_matches(&row,"notifychannelclientpermlist",2,8,Some(3)));
assert!(!response_matches(&row,"notifychannelclientpermlist",2,9,Some(3)));
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"),
(Action::Commander{enabled:true},"clientupdate"),
(Action::ServerGroup{group_id:6,enabled:true},"servergroupaddclient"),
(Action::ServerGroup{group_id:6,enabled:false},"servergroupdelclient"),
(Action::ChannelGroup{group_id:7,channel_id:1},"setclientchannelgroup"),
(Action::SetClientPermission{permission_id:42,value:Some(75),skip:true},"clientaddperm"),
(Action::SetClientPermission{permission_id:42,value:None,skip:false},"clientdelperm"),
(Action::SetChannelPermission{channel_id:1,permission_id:42,value:Some(25)},"channelclientaddperm"),
(Action::KickServer{reason:"fixture".into()},"clientkick"),
(Action::Ban{reason:"fixture".into(),duration:60},"banclient"),
] {
let packet=action_command(&action,2,8).unwrap().into_packet();
let raw=crate::rawcmd::parse(packet.content()).unwrap();
assert_eq!(raw.name,verb);
assert!(!raw.items[0].contains_key("return_code"),"result tracking belongs to connection transport");
}
}
#[test] fn volume_request_retains_db_and_mute_atomically(){
let parsed=parse_action(json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":-12.5,"muted":true})).unwrap();
assert_eq!(parsed.action,Action::Volume{db:-12.5,muted:true});
assert!(parse_action(json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":-200,"muted":false})).is_ok());
assert!(parse_action(json!({"client_id":42,"uid":"fixture","generation":1,"action":"set_client_permission","permission_id":1,"skip":false})).is_err());
}
#[test] fn self_other_and_permission_denials_do_not_depend_on_role_labels(){
assert_eq!(target_hint(true,"kick_server",Some(u64::MAX),1)["allowed"],false);
assert_eq!(target_hint(false,"kick_server",Some(0),1)["allowed"],false);
assert_eq!(target_hint(false,"kick_server",Some(1),1)["allowed"],true);
assert_eq!(target_hint(false,"kick_server",None,1)["allowed"],Value::Null);
assert_eq!(target_hint(true,"set_client_permission",Some(256),256)["allowed"],true);
}
#[test] fn recycled_client_id_cannot_reuse_identity_or_local_gain(){
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());
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);
assert!((volumes.gain(&second.0,&persisted)-0.501_187).abs()<1e-5,"persisted modifier applies without a live entry");
volumes.set(&first.0,-200.0,false); assert_eq!(volumes.gain(&first.0,&persisted),0.0);
volumes.set(&first.0,0.0,false); assert_eq!(volumes.gain(&first.0,&persisted),1.0);
volumes.set(&second.0,10.0,false); assert!((volumes.gain(&second.0,&persisted)-crate::voice_dsp::MAX_USER_GAIN).abs()<1e-5,"live entry wins");
volumes.clear(); assert_eq!(volumes.get(&first.0,&persisted),(0.0,false)); assert_eq!(volumes.get(&second.0,&persisted),(-6.0,false));
}
}
+95
View File
@@ -0,0 +1,95 @@
//! Session integration for target-bound client menu actions.
use super::*;
impl Session {
pub(super) fn client_context(&mut self, id: &str, target: Target) -> Result<Option<Value>, ErrorObj> {
let c = self.connected_conn()?;
let book = c.con.get_state().map_err(|e|lib_error(ErrorCode::NotConnected,&e))?;
c.permissions.context(book,&target,c.generation)?;
let handle = c.send(menu::command("permissionlist",&[])).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,Pending::MenuContext{req:id.into(),target});
Ok(None)
}
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(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();
if context["capabilities"][key]["allowed"]==false{return Err(ErrorObj::new(ErrorCode::ServerError,"server permission hint denies this action").with_detail(context["capabilities"][key].clone()));}
let client=&book.clients[&ClientId(request.target.client_id)];
let dbid=client.database_id.0;
match &request.action {
MenuAction::MoveToOwnChannel{password,expected_channel_id}=>{
let own_channel=book.clients.get(&book.own_client).ok_or_else(||menu::bad("own channel unavailable"))?.channel;
if own_channel.0!=*expected_channel_id{return Err(ErrorObj::new(ErrorCode::TargetChanged,"own channel changed; reopen the move action"));}
if own_channel==client.channel{return Err(menu::bad("client is already in your channel"));}
let pw=password.as_ref().filter(|p|!p.is_empty()).map(|p|tsproto_types::crypto::encode_password(p.as_bytes())).unwrap_or_default();
let command=menu::command("clientmove",&[("clid",client.id.0.to_string()),("cid",own_channel.0.to_string()),("cpw",pw)]);
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,Pending::Simple{req:id.into()});return Ok(None);
},
MenuAction::DeleteAvatar{}=>{
// Official TeamSpeak.dll 6.0.0.5163: constructor VA 0x1814bddd0 emits
// clientavatardeleted with each raw UID under cluid (not clientedit).
let command=menu::command("clientavatardeleted",&[("cluid",request.target.uid.clone())]);
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,Pending::Simple{req:id.into()});return Ok(None);
},
MenuAction::Volume{db,muted}=>{
let uid=client.uid.as_ref().ok_or_else(||menu::bad("client UID is unavailable"))?;
c.gains.set(&uid.0,*db,*muted);
return Ok(Some(json!({"volume_db":db,"volume_muted":muted})));
},
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=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))?;
c.pending.insert(handle,Pending::AvatarInit{ftid});
c.avatar=Some(AvatarUpload{req:id.into(),handle:ftid,data,hash,started:Instant::now(),task:None});
return Ok(None);
},
MenuAction::ServerGroup{group_id,enabled}=>{
let group=context["server_groups"].as_array().unwrap().iter().find(|g|g["id"].as_u64()==Some(*group_id)).ok_or_else(||menu::bad("server group is not available"))?;
if group[if *enabled{"can_add"}else{"can_remove"}]["allowed"]==false{return Err(menu::bad("insufficient group membership power"));}
},
MenuAction::ChannelGroup{group_id,channel_id}=>{
if *channel_id!=client.channel.0{return Err(menu::bad("target channel changed; reopen the menu"));}
let group=context["channel_groups"].as_array().unwrap().iter().find(|g|g["id"].as_u64()==Some(*group_id)).ok_or_else(||menu::bad("channel group is not available"))?;
if group["can_set"]["allowed"]==false{return Err(menu::bad("insufficient channel group membership power"));}
},
MenuAction::ChannelPermissions{channel_id}|MenuAction::SetChannelPermission{channel_id,..}=>{
if *channel_id!=client.channel.0{return Err(menu::bad("target channel changed; reopen the menu"));}
},
_=>{},
}
if let MenuAction::SetClientPermission{permission_id,..}|MenuAction::SetChannelPermission{permission_id,..}=&request.action {
if !c.permissions.catalog.iter().any(|p|p["id"].as_u64()==Some(u64::from(*permission_id))){return Err(menu::bad("permission is not in the server catalog"));}
}
let response=request.action.response();
let channel=match request.action {MenuAction::ChannelPermissions{channel_id}=>Some(channel_id),_=>None};
if response.is_some() && c.pending.values().any(|p|matches!(p,Pending::MenuRead{..})){return Err(menu::bad("another client information request is pending"));}
let command=menu::action_command(&request.action,request.target.client_id,dbid).ok_or_else(||ErrorObj::new(ErrorCode::Internal,"local action reached server dispatch"))?;
let handle=c.send(command).map_err(|e|lib_error(ErrorCode::ServerError,&e))?;
c.pending.insert(handle,match response {
Some(response)=>Pending::MenuRead{req:id.into(),target:request.target,dbid,channel,response,rows:Vec::new()},
None=>Pending::Simple{req:id.into()},
});
Ok(None)
}
pub(super) async fn avatar_finished(&mut self,generation:u64,result:Result<(),String>){
let Some(c)=self.conn.as_mut().filter(|c|c.generation==generation) else{return};
let Some(job)=c.avatar.take() else{return};
if let Err(error)=result{self.out.err(&job.req,ErrorObj::new(ErrorCode::Io,error)).await;return;}
let command=menu::command("clientupdate",&[("client_flag_avatar",job.hash.clone())]);
match c.send(command){
Ok(handle)=>{c.pending.insert(handle,Pending::Simple{req:job.req.clone()});},
Err(e)=>self.out.err(&job.req,lib_error(ErrorCode::ServerError,&e)).await,
}
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Transport-neutral control output and bounded native playback PCM.
use std::{collections::VecDeque, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}};
use serde::Serialize;
use serde_json::{json, Value};
use tokio::sync::{mpsc, Notify};
use crate::protocol::{ErrorObj, Frame};
const CONTROL_CAPACITY: usize = 1024;
const PCM_CAPACITY: usize = 10;
pub struct PlaybackFrame {
pub pcm: Frame,
pub speakers: Vec<u16>,
pub generation: u64,
pub emitted_at: std::time::Instant,
recycled: Arc<Mutex<Vec<Vec<u16>>>>,
}
impl Drop for PlaybackFrame {
fn drop(&mut self) {
let mut speakers = std::mem::take(&mut self.speakers);
speakers.clear();
self.recycled.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(speakers);
}
}
struct PlaybackInner {
frames: VecDeque<PlaybackFrame>,
closed: bool,
}
struct PlaybackShared {
inner: Mutex<PlaybackInner>,
ready: Notify,
recycled: Arc<Mutex<Vec<Vec<u16>>>>,
}
pub struct PlaybackReceiver { shared: Arc<PlaybackShared> }
impl PlaybackReceiver {
pub async fn recv(&mut self) -> Option<PlaybackFrame> {
loop {
let notified = self.shared.ready.notified();
{
let mut inner = self.shared.inner.lock().expect("playback queue poisoned");
if let Some(frame) = inner.frames.pop_front() { return Some(frame); }
if inner.closed { return None; }
}
notified.await;
}
}
}
impl Drop for PlaybackReceiver {
fn drop(&mut self) {
let mut inner = self.shared.inner.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
inner.closed = true;
inner.frames.clear();
}
}
struct OutputInner {
control: mpsc::Sender<Value>,
playback: Arc<PlaybackShared>,
generation: AtomicU64,
}
impl Drop for OutputInner {
fn drop(&mut self) {
self.playback.inner.lock().expect("playback queue poisoned").closed = true;
self.playback.ready.notify_one();
}
}
#[derive(Clone)]
pub struct Out { inner: Arc<OutputInner> }
impl Out {
pub fn new() -> (Self, mpsc::Receiver<Value>, PlaybackReceiver) {
let (control, receiver) = mpsc::channel(CONTROL_CAPACITY);
let playback = Arc::new(PlaybackShared {
inner: Mutex::new(PlaybackInner { frames: VecDeque::with_capacity(PCM_CAPACITY), closed: false }),
ready: Notify::new(),
recycled: Arc::new(Mutex::new((0..PCM_CAPACITY + 2).map(|_| Vec::with_capacity(16)).collect())),
});
(Self { inner: Arc::new(OutputInner { control, playback: playback.clone(), generation: AtomicU64::new(0) }) }, receiver, PlaybackReceiver { shared: playback })
}
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.entry("generation".to_owned())
.or_insert_with(|| Value::from(self.inner.generation.load(Ordering::Acquire)));
}
let _ = self.inner.control.send(value).await;
}
pub async fn json<T: Serialize>(&self, value: &T) {
match serde_json::to_value(value) {
Ok(value) => self.control(value).await,
Err(error) => tracing::error!(%error, "could not construct core output"),
}
}
/// Drops oldest playback under congestion; never waits for an audio device.
pub fn playback(&self, pcm: &Frame, speakers: &[u16]) -> bool {
let mut inner = self.inner.playback.inner.lock().expect("playback queue poisoned");
if inner.closed { return false; }
let retained = inner.frames.len() < PCM_CAPACITY;
if !retained { inner.frames.pop_front(); }
let Some(mut speaker_buffer) = self.inner.playback.recycled.lock().expect("playback pool poisoned").pop() else { return false; };
speaker_buffer.extend_from_slice(speakers);
inner.frames.push_back(PlaybackFrame { pcm: *pcm, speakers: speaker_buffer, generation: self.inner.generation.load(Ordering::Acquire), emitted_at: std::time::Instant::now(), recycled: self.inner.playback.recycled.clone() });
drop(inner);
self.inner.playback.ready.notify_one();
retained
}
pub async fn ok(&self, id: &str, result: Value) {
self.control(json!({"id":id,"ok":true,"result":result})).await;
}
pub async fn err(&self, id: &str, error: ErrorObj) {
self.control(json!({"id":id,"ok":false,"error":error})).await;
}
pub async fn error_event(&self, error: ErrorObj) {
self.control(json!({"event":"error","error":error})).await;
}
}
#[cfg(test)]
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();
out.set_generation(7);
for value in 0..12 { out.playback(&[value; crate::protocol::FRAME_SAMPLES], &[4, 9]); }
out.set_generation(8);
for expected in 2..12 {
let frame = playback.recv().await.unwrap();
assert_eq!(frame.pcm[0], expected);
assert_eq!(frame.generation, 7);
assert_eq!(frame.speakers, [4, 9]);
}
assert!(out.playback(&[12; crate::protocol::FRAME_SAMPLES], &[2]));
let frame = playback.recv().await.unwrap();
assert_eq!(frame.generation, 8);
assert_eq!(frame.speakers, [2]);
drop(frame);
drop(out);
assert!(playback.recv().await.is_none());
}
#[test]
fn missing_playback_consumer_refuses_new_audio() {
let (out, _control, playback) = Out::new();
drop(playback);
assert!(!out.playback(&[1; crate::protocol::FRAME_SAMPLES], &[2]));
}
}
+1235 -128
View File
File diff suppressed because it is too large. Load diff
+548 -55
View File
@@ -1,4 +1,9 @@
//! Bridge protocol v1 (see `docs/bridge.md`): request parsing and error objects.
//! Bridge protocol v1 (see `docs/bridge.md`): transport shape parsing and shared typed validation.
//!
//! Both CLI parsing and embedded requests enter through `validate_command` before
//! becoming `Input::Request`. Family parsers decode only transport shapes; their
//! semantic validators are dispatched here. Live generation/identity/permission
//! checks remain in the session because argument validation cannot replace them.
use std::borrow::Cow;
@@ -8,6 +13,9 @@ use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use serde_json::Value;
use crate::vad::GateMode;
use crate::voice_dsp::LocalVolumesUpdate;
pub const PROTOCOL_VERSION: u32 = 1;
/// Maximum accepted stdin line (bytes, without the newline).
pub const MAX_LINE_BYTES: usize = 256 * 1024;
@@ -24,7 +32,7 @@ const MAX_FIELD_CHARS: usize = 1024;
pub type Frame = [i16; FRAME_SAMPLES];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
BadRequest,
@@ -46,15 +54,21 @@ pub enum ErrorCode {
AudioCodecUnsupported,
RenameNotPersisted,
NotFound,
TargetChanged,
MediaTooLarge,
MediaUnsupported,
ExternalMedia,
Io,
Internal,
FileExists,
TransferCancelled,
RecordingFailed,
IdentityInUse,
IdentityBusy,
}
/// TeamSpeak server error attached to an [`ErrorObj`].
#[derive(Clone, Debug, PartialEq, Serialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TsErrorInfo {
/// Numeric TeamSpeak error id (e.g. 513 = nickname in use).
pub id: u32,
@@ -64,7 +78,7 @@ pub struct TsErrorInfo {
pub missing_permission: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorObj {
pub code: ErrorCode,
pub message: String,
@@ -90,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 {
@@ -106,17 +124,34 @@ pub enum Command {
Connect(ConnectArgs),
Disconnect { message: Option<String> },
JoinChannel { channel_id: u64, password: Option<String> },
SendText { target: TextTarget, client_id: Option<u16>, 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> },
/// Persisted per-user volume modifiers (replace or upsert).
SetLocalVolumes(LocalVolumesUpdate),
/// Playback DSP of the current output device profile.
SetPlaybackDsp { agc: bool },
StreamList { client_id: Option<u16> },
StreamJoin { stream_id: String, client_id: u16, message: Option<String> },
/// `json` is already compact-serialized and size checked.
/// JSON text; `validate_command` requires an object, compacts it and checks its byte size.
StreamSignal { stream_id: String, client_id: u16, json: String },
StreamLeave { stream_id: String, client_id: u16 },
StreamSetup(StreamPublishArgs),
StreamUpdate(StreamPublishArgs),
StreamStop { stream_id: String },
StreamRespond { stream_id: String, client_id: u16, decision: bool, offer: String, message: String },
StreamRemove { stream_id: String, client_id: u16 },
FetchIcon { icon_id: u32 },
FetchAvatar { client_id: u16 },
FetchBanner { channel_id: u64 },
FetchServerBanner,
ClientContext(crate::menu::Target),
ClientAction(crate::menu::ActionRequest),
Admin(crate::admin::AdminCommand),
Files(crate::file_transfer::Request),
Recording(crate::recording::RecCommand),
Whisper(crate::whisper::WhisperCommand),
Shutdown,
}
@@ -131,41 +166,95 @@ impl Command {
Command::JoinChannel { .. } => "join_channel",
Command::SendText { .. } => "send_text",
Command::SetAudio { .. } => "set_audio",
Command::SetTransmit { .. } => "set_transmit",
Command::SetLocalVolumes(_) => "set_local_volumes",
Command::SetPlaybackDsp { .. } => "set_playback_dsp",
Command::StreamList { .. } => "stream_list",
Command::StreamJoin { .. } => "stream_join",
Command::StreamSignal { .. } => "stream_signal",
Command::StreamLeave { .. } => "stream_leave",
Command::StreamSetup(_) => "stream_setup",
Command::StreamUpdate(_) => "stream_update",
Command::StreamStop { .. } => "stream_stop",
Command::StreamRespond { .. } => "stream_respond",
Command::StreamRemove { .. } => "stream_remove",
Command::FetchIcon { .. } => "fetch_icon",
Command::FetchAvatar { .. } => "fetch_avatar",
Command::FetchBanner { .. } => "fetch_banner",
Command::FetchServerBanner => "fetch_server_banner",
Command::ClientContext(_) => "client_context",
Command::ClientAction(_) => "client_action",
Command::Admin(c) => c.name(),
Command::Files(r) => r.name(),
Command::Recording(c) => c.name(),
Command::Whisper(c) => c.name(),
Command::Shutdown => "shutdown",
}
}
}
/// A command whose transport-independent arguments have been checked and normalized.
/// 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 }
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[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, 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, 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 {
Request { id: String, cmd: Command },
AudioFrame(Box<Frame>),
Request { id: String, cmd: ValidatedCommand },
AudioFrame(TaggedFrame),
AudioEnd,
/// The line could not be turned into a command. `id` is set if it could be recovered.
Invalid { id: Option<String>, error: ErrorObj },
}
/// One captured frame and the route it was captured for.
#[derive(Debug)]
pub struct TaggedFrame {
pub pcm: Box<Frame>,
/// Whisper epoch (`audio_frame.whisper`) while a whisper key was held; `None` = ordinary voice.
pub whisper: Option<u32>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Envelope<'a> {
@@ -173,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 {}
@@ -190,7 +284,7 @@ struct NicknameArgs {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DisconnectArgs {
#[serde(default)]
#[serde(default, deserialize_with = "present_string")]
message: Option<String>,
}
@@ -208,18 +302,26 @@ struct SendTextArgs {
target: TextTarget,
#[serde(default)]
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 {
@@ -270,11 +372,42 @@ struct StreamLeaveArgs {
client_id: u16,
}
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StreamPublishArgs {
#[serde(default)]
pub stream_id: Option<String>,
pub name: String,
#[serde(rename = "type")]
pub stream_type: u8,
pub accessibility: u8,
pub mode: u8,
pub bitrate: u32,
pub viewer_limit: u16,
pub audio: bool,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StreamStopArgs { stream_id: String }
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StreamRespondArgs {
stream_id: String,
client_id: u16,
decision: bool,
offer: String,
message: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AudioFrameArgs<'a> {
#[serde(borrow)]
pcm: Cow<'a, str>,
#[serde(default)]
whisper: Option<u32>,
}
fn args<'a, T: Deserialize<'a>>(raw: Option<&'a RawValue>) -> Result<T, ErrorObj> {
@@ -312,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];
@@ -334,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) => {
@@ -346,10 +504,20 @@ 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" => {
return match args::<AudioFrameArgs>(env.args).and_then(|a| decode_frame(&a.pcm)) {
return match args::<AudioFrameArgs>(env.args).and_then(|a| {
if a.whisper == Some(0) {
return Err(bad("audio_frame: whisper epoch must be at least 1"));
}
Ok(TaggedFrame { pcm: decode_frame(&a.pcm)?, whisper: a.whisper })
}) {
Ok(frame) => Input::AudioFrame(frame),
Err(error) => Input::Invalid { id: None, error },
};
@@ -370,7 +538,7 @@ pub fn parse_line(line: &str) -> Input {
}
None => return Input::Invalid { id: None, error: bad("missing id") },
};
match parse_command(&env.cmd, env.args) {
match parse_command(&env.cmd, env.args).and_then(validate_command) {
Ok(cmd) => Input::Request { id, cmd },
Err(error) => Input::Invalid { id: Some(id), error },
}
@@ -391,71 +559,58 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
"rename" => Command::Rename { nickname: args_owned::<NicknameArgs>(raw)?.nickname },
"connect" => {
let a: ConnectArgs = args_owned(raw)?;
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)?;
Command::Connect(a)
}
"disconnect" => {
let a: DisconnectArgs = args_owned(raw)?;
check_opt("message", &a.message)?;
Command::Disconnect { message: a.message }
}
"join_channel" => {
let a: JoinChannelArgs = args_owned(raw)?;
check_opt("password", &a.password)?;
Command::JoinChannel { channel_id: a.channel_id, password: a.password }
}
"send_text" => {
let a: SendTextArgs = args_owned(raw)?;
if a.message.is_empty() || a.message.len() > MAX_TEXT_BYTES {
return Err(bad(format!("message must be 1-{MAX_TEXT_BYTES} bytes")));
}
match (a.target, a.client_id) {
(TextTarget::Client, None) => return Err(bad("client_id is required for target client")),
(TextTarget::Channel | TextTarget::Server, Some(_)) => {
return Err(bad("client_id is only allowed for target client"));
}
_ => {}
}
Command::SendText { target: a.target, client_id: a.client_id, 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)?;
Command::SetAudio { input_muted: a.input_muted, output_muted: a.output_muted }
}
"set_transmit" => Command::SetTransmit { vad: crate::voice_dsp::parse_transmit(raw)? },
"set_local_volumes" => Command::SetLocalVolumes(crate::voice_dsp::parse_local_volumes(raw)?),
"set_playback_dsp" => Command::SetPlaybackDsp { agc: crate::voice_dsp::parse_playback_dsp(raw)? },
"stream_list" => Command::StreamList { client_id: args_owned::<StreamListArgs>(raw)?.client_id },
"stream_join" => {
let a: StreamJoinArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
check_opt("message", &a.message)?;
Command::StreamJoin { stream_id: a.stream_id, client_id: a.client_id, message: a.message }
}
"stream_signal" => {
let a: StreamSignalArgs = args(raw)?;
check_stream_id(&a.stream_id)?;
let value: Value = serde_json::from_str(a.json.get())
.map_err(|e| bad(format!("json is not valid JSON: {e}")))?;
if !value.is_object() {
return Err(bad("json must be an object"));
}
let json = serde_json::to_string(&value).map_err(|e| bad(format!("json: {e}")))?;
if json.len() > MAX_SIGNAL_JSON_BYTES {
return Err(bad(format!("json larger than {MAX_SIGNAL_JSON_BYTES} bytes")));
}
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json }
Command::StreamSignal { stream_id: a.stream_id, client_id: a.client_id, json: a.json.get().to_owned() }
}
"stream_leave" => {
let a: StreamLeaveArgs = args_owned(raw)?;
check_stream_id(&a.stream_id)?;
Command::StreamLeave { stream_id: a.stream_id, client_id: a.client_id }
}
"stream_setup" | "stream_update" => {
let a: StreamPublishArgs = args_owned(raw)?;
if cmd == "stream_setup" { Command::StreamSetup(a) } else { Command::StreamUpdate(a) }
}
"stream_stop" => {
let a: StreamStopArgs = args_owned(raw)?;
Command::StreamStop { stream_id: a.stream_id }
}
"stream_respond" => {
let a: StreamRespondArgs = args_owned(raw)?;
Command::StreamRespond { stream_id: a.stream_id, client_id: a.client_id, decision: a.decision, offer: a.offer, message: a.message }
}
"stream_remove" => {
let a: StreamLeaveArgs = args_owned(raw)?;
Command::StreamRemove { stream_id: a.stream_id, client_id: a.client_id }
}
"fetch_icon" => {
let a: FetchIconArgs = args_owned(raw)?;
if a.icon_id == 0 {
return Err(bad("icon_id 0 means no icon"));
}
Command::FetchIcon { icon_id: a.icon_id }
}
"fetch_avatar" => Command::FetchAvatar { client_id: args_owned::<FetchAvatarArgs>(raw)?.client_id },
@@ -464,6 +619,15 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
args::<Empty>(raw)?;
Command::FetchServerBanner
}
"client_context" => {
let target = args_owned(raw)?;
Command::ClientContext(target)
},
"client_action" => Command::ClientAction(crate::menu::parse_action(args_owned(raw)?)?),
n if crate::admin::is_admin(n) => Command::Admin(crate::admin::parse(n, raw)?),
n if n.starts_with("file_") => Command::Files(crate::file_transfer::parse(n, raw)?),
n if n.starts_with("recording_") => Command::Recording(crate::recording::parse(n, raw)?),
n @ ("whisper_start" | "whisper_stop" | "set_whisper_receive") => Command::Whisper(crate::whisper::parse(n, raw)?),
"shutdown" => {
args::<Empty>(raw)?;
Command::Shutdown
@@ -474,6 +638,99 @@ fn parse_command(cmd: &str, raw: Option<&RawValue>) -> Result<Command, ErrorObj>
})
}
/// Validate and normalize typed requests, without serializing commands to JSON.
/// Signaling JSON is itself a protocol payload and is compacted for both transports.
pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorObj> {
let update = matches!(&command, Command::StreamUpdate(_));
match &mut command {
Command::Connect(a) => {
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 } => {
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")),
(TextTarget::Channel | TextTarget::Server, Some(_)) => return Err(bad("client_id is only allowed for target client")),
_ => {}
}
if *target == TextTarget::Client {
if *client_id == Some(0) { return Err(bad("client_id must be positive")); }
let uid = expected_client_uid.as_deref().ok_or_else(|| bad("expected_client_uid is required for target client"))?;
check_text("expected_client_uid", uid, 128, false)?;
} else if expected_client_uid.is_some() { return Err(bad("expected_client_uid is only allowed for target client")); }
}
Command::SetTransmit { vad } => crate::voice_dsp::validate_transmit(*vad)?,
Command::SetLocalVolumes(a) => crate::voice_dsp::validate_local_volumes(a)?,
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}")))?;
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;
}
Command::StreamLeave { stream_id, .. } | Command::StreamStop { stream_id } => check_stream_id(stream_id)?,
Command::StreamSetup(a) | Command::StreamUpdate(a) => {
if update != a.stream_id.is_some() { return Err(bad("stream_id is required only for stream_update")); }
if let Some(id) = &a.stream_id { check_stream_id(id)?; }
check_text("name", &a.name, 200, false)?;
if a.name.chars().any(char::is_control) || !(1..=3).contains(&a.stream_type)
|| !(1..=3).contains(&a.accessibility) || a.mode != 1 || !(100..=100000).contains(&a.bitrate) {
return Err(bad("invalid stream metadata (only P2P is supported)"));
}
}
Command::StreamRespond { stream_id, decision, offer, message, .. } => {
check_stream_id(stream_id)?;
check_text("message", message, 200, true)?;
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, .. } => check_stream_id(stream_id)?,
Command::FetchIcon { icon_id: 0 } => return Err(bad("icon_id 0 means no icon")),
Command::ClientContext(a) => crate::menu::validate_target(a)?,
Command::ClientAction(a) => crate::menu::validate_action(a)?,
Command::Admin(a) => crate::admin::validate(a)?,
Command::Files(a) => crate::file_transfer::validate(a)?,
Command::Recording(a) => crate::recording::validate(a)?,
Command::Whisper(a) => crate::whisper::validate(a)?,
Command::ProfileGet | Command::ProfileCreate { .. } | Command::Rename { .. }
| Command::SetAudio { .. } | Command::SetPlaybackDsp { .. } | Command::StreamList { .. }
| Command::FetchIcon { .. } | Command::FetchAvatar { .. } | Command::FetchBanner { .. }
| Command::FetchServerBanner | Command::Shutdown => {}
}
Ok(ValidatedCommand(command))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -491,13 +748,29 @@ mod tests {
let line = format!(r#"{{"cmd":"audio_frame","args":{{"pcm":"{}"}}}}"#, frame_b64(|i| i as i16 - 480));
match parse_line(&line) {
Input::AudioFrame(f) => {
assert_eq!(f[0], -480);
assert_eq!(f[959], 479);
assert_eq!(f.pcm[0], -480);
assert_eq!(f.pcm[959], 479);
assert_eq!(f.whisper, None);
}
other => panic!("{other:?}"),
}
}
#[test]
fn audio_frame_carries_its_whisper_epoch() {
let pcm = frame_b64(|_| 0);
match parse_line(&format!(r#"{{"cmd":"audio_frame","args":{{"pcm":"{pcm}","whisper":7}}}}"#)) {
Input::AudioFrame(f) => assert_eq!(f.whisper, Some(7)),
other => panic!("{other:?}"),
}
for bad in [r#""whisper":0"#, r#""whisper":-1"#, r#""whisper":"7""#, r#""route":1"#] {
match parse_line(&format!(r#"{{"cmd":"audio_frame","args":{{"pcm":"{pcm}",{bad}}}}}"#)) {
Input::Invalid { id: None, .. } => {}
other => panic!("{bad}: {other:?}"),
}
}
}
#[test]
fn audio_frame_wrong_size_is_rejected() {
let short = BASE64_STANDARD.encode([0u8; 1918]);
@@ -511,11 +784,27 @@ mod tests {
}
}
#[test]
fn set_transmit_modes_and_sensitivities() {
let parse = |args: &str| parse_line(&format!(r#"{{"id":"t","cmd":"set_transmit","args":{args}}}"#));
assert!(matches!(parse(r#"{"mode":"direct"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: None }), .. }));
use crate::vad::Sensitivity;
assert!(matches!(parse(r#"{"mode":"vad"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Normal)) }), .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"high"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::High)) }), .. }));
assert!(matches!(parse(r#"{"mode":"vad","sensitivity":"low"}"#), Input::Request { cmd: ValidatedCommand(Command::SetTransmit { vad: Some(GateMode::Automatic(Sensitivity::Low)) }), .. }));
for bad in [r#"{"mode":"open"}"#, r#"{"mode":"direct","sensitivity":"low"}"#, r#"{"mode":"vad","sensitivity":"max"}"#, r#"{"mode":"vad","threshold":0.1}"#, r#"{}"#] {
match parse(bad) {
Input::Invalid { error, .. } => assert_eq!(error.code, ErrorCode::BadRequest, "{bad}"),
other => panic!("{bad}: {other:?}"),
}
}
}
#[test]
fn requests_need_valid_id_and_known_args() {
assert!(matches!(
parse_line(r#"{"id":"a","cmd":"profile_get"}"#),
Input::Request { cmd: Command::ProfileGet, .. }
Input::Request { cmd: ValidatedCommand(Command::ProfileGet), .. }
));
match parse_line(r#"{"cmd":"profile_get"}"#) {
Input::Invalid { id: None, error } => assert_eq!(error.code, ErrorCode::BadRequest),
@@ -538,11 +827,74 @@ 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());
for bad in [serde_json::json!(5), serde_json::json!(["Guest"]), serde_json::json!({"name":"Guest"})] {
match parse(serde_json::json!({"address":"ts.example","nickname":bad})) {
Input::Invalid { id: Some(_), error } => assert_eq!(error.code, ErrorCode::BadRequest, "{bad}"),
other => panic!("{bad}: {other:?}"),
}
}
}
#[test]
fn publisher_metadata_and_responses_are_strict() {
let metadata = serde_json::json!({"name":"QA | stream", "type":3,"accessibility":3,"mode":1,"bitrate":4500,"viewer_limit":0,"audio":false});
let parse = |cmd: &str, args: Value| parse_line(&serde_json::json!({"id":"p","cmd":cmd,"args":args}).to_string());
assert!(matches!(parse("stream_setup", metadata.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamSetup(_)), .. }));
assert!(matches!(parse("stream_update", metadata.clone()), Input::Invalid { .. }));
let mut updated = metadata.clone(); updated["stream_id"] = serde_json::json!("s1");
assert!(matches!(parse("stream_update", updated.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamUpdate(_)), .. }));
assert!(matches!(parse("stream_setup", updated), Input::Invalid { .. }));
for (key, value) in [("type", 4), ("accessibility", 0), ("mode", 2), ("bitrate", 99), ("viewer_limit", -1)] {
let mut invalid = metadata.clone(); invalid[key] = serde_json::json!(value);
assert!(matches!(parse("stream_setup", invalid), Input::Invalid { .. }), "{key}");
}
let response = serde_json::json!({"stream_id":"s1","client_id":5,"decision":true,"offer":"v=0\r\n","message":""});
assert!(matches!(parse("stream_respond", response.clone()), Input::Request { cmd: ValidatedCommand(Command::StreamRespond { decision:true, .. }), .. }));
let mut invalid = response; invalid["offer"] = serde_json::json!("");
assert!(matches!(parse("stream_respond", invalid), Input::Invalid { .. }));
assert!(matches!(parse("stream_remove", serde_json::json!({"stream_id":"s1","client_id":0})), Input::Invalid { .. }));
assert!(matches!(parse("stream_remove", serde_json::json!({"stream_id":"s1","client_id":5,"reason":5})), Input::Invalid { .. }));
}
#[test]
fn stream_signal_json_is_compacted_object() {
let line = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":{ "cmd" : "answer", "args": {"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"} }}}"#;
match parse_line(line) {
Input::Request { cmd: Command::StreamSignal { json, client_id, .. }, .. } => {
Input::Request { cmd: ValidatedCommand(Command::StreamSignal { json, client_id, .. }), .. } => {
assert_eq!(client_id, 5);
assert_eq!(json, r#"{"cmd":"answer","args":{"answer":"v=0\r\no=- 1 2 IN IP4 0.0.0.0"}}"#);
}
@@ -551,4 +903,145 @@ mod tests {
let arr = r#"{"id":"s","cmd":"stream_signal","args":{"stream_id":"7","client_id":5,"json":[1]}}"#;
assert!(matches!(parse_line(arr), Input::Invalid { .. }));
}
fn assert_bad(command: Command) {
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, expected_channel_id: None, message: "hello".into(),
};
assert_bad(private(None, Some("uid".into())));
assert_bad(private(Some(0), Some("uid".into())));
assert_bad(private(Some(7), None));
assert_bad(private(Some(7), Some(String::new())));
assert_bad(private(Some(7), Some("x".repeat(129))));
let valid = validate_command(private(Some(7), Some("uid".into()))).unwrap();
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, 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, 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 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!("{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,
accessibility: 3, mode: 1, bitrate: 4500, viewer_limit: 0, audio: false };
assert!(validate_command(Command::StreamSetup(args.clone())).is_ok());
assert_bad(Command::StreamUpdate(args.clone()));
let mut update = args.clone(); update.stream_id = Some("s1".into());
assert!(validate_command(Command::StreamUpdate(update.clone())).is_ok());
assert_bad(Command::StreamSetup(update));
for invalid in [
StreamPublishArgs { mode: 2, ..args.clone() },
StreamPublishArgs { accessibility: 0, ..args.clone() },
StreamPublishArgs { stream_type: 4, ..args.clone() },
StreamPublishArgs { bitrate: 99, ..args.clone() },
StreamPublishArgs { bitrate: 100001, ..args.clone() },
StreamPublishArgs { name: "Screen\n".into(), ..args.clone() },
StreamPublishArgs { name: String::new(), ..args },
] { assert_bad(Command::StreamSetup(invalid)); }
for (client_id, decision, offer, message) in [(0, true, "v=0", ""), (7, true, "", ""),
(7, false, "v=0", ""), (7, true, "v=0\0", ""), (7, true, "v=0", "bad\n")] {
assert_bad(Command::StreamRespond { stream_id: "s1".into(), client_id, decision, offer: offer.into(), message: message.into() });
}
}
#[test]
fn direct_family_commands_cannot_bypass_semantic_checks() {
use crate::{admin, file_transfer as files, menu, recording, whisper};
let invalid = [
Command::Admin(admin::AdminCommand::ChannelMove { generation: 1, channel_id: 7, parent_id: 7, order: None }),
Command::Admin(admin::AdminCommand::BanAdd { generation: 1, ip: None, name: None, uid: None, duration_s: 0, reason: None }),
Command::Admin(admin::AdminCommand::TempPasswordAdd { generation: 1, password: "pw".into(), description: String::new(), duration_s: 0, channel_id: 0, channel_password: String::new() }),
Command::Admin(admin::AdminCommand::Extra(admin::extra::Command::ServerLog { lines: 0, reverse: false, instance: false, begin_pos: 0 })),
Command::ClientAction(menu::ActionRequest { target: menu::Target { client_id: 7, uid: "uid".into() }, generation: 1, action: menu::Action::Volume { db: f32::NAN, muted: false } }),
Command::Files(files::Request::Config { download_slots: usize::MAX, upload_slots: usize::MAX, download_limit: 0, upload_limit: 0 }),
Command::Files(files::Request::Mkdir { channel_id: 7, path: "/../bad".into(), password: String::new() }),
Command::Files(files::Request::List { channel_id: 0, path: "/private".into(), password: String::new() }),
Command::Files(files::Request::Upload { channel_id: 7, path: "/file".into(), password: String::new(), source: "relative".into(), overwrite: false }),
Command::Recording(recording::RecCommand::Start { directory: "relative".into(), mode: recording::Mode::Master, label: None }),
Command::Whisper(whisper::WhisperCommand::Stop { epoch: 0 }),
Command::SetTransmit { vad: Some(GateMode::VolumeGate { level_db: f32::NAN }) },
Command::SetLocalVolumes(LocalVolumesUpdate { replace: false, volumes: vec![(vec![1], f32::INFINITY)] }),
];
for command in invalid { assert_bad(command); }
let validated = validate_command(Command::Files(files::Request::List { channel_id: 7, path: "/folder".into(), password: String::new() })).unwrap();
assert_eq!(validated.into_inner(), Command::Files(files::Request::List { channel_id: 7, path: "/folder/".into(), password: String::new() }));
}
}
+224 -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).
@@ -15,6 +15,11 @@ pub enum StreamVerb {
RequestStreamInfo,
JoinStreamRequest,
StreamSignaling,
SetupStream,
UpdateStream,
StopStream,
RespondJoinStreamRequest,
RemoveClientFromStream,
}
impl StreamVerb {
@@ -23,6 +28,11 @@ impl StreamVerb {
StreamVerb::RequestStreamInfo => "requeststreaminfo",
StreamVerb::JoinStreamRequest => "joinstreamrequest",
StreamVerb::StreamSignaling => "streamsignaling",
StreamVerb::SetupStream => "setupstream",
StreamVerb::UpdateStream => "updatestream",
StreamVerb::StopStream => "stopstream",
StreamVerb::RespondJoinStreamRequest => "respondjoinstreamrequest",
StreamVerb::RemoveClientFromStream => "removeclientfromstream",
}
}
}
@@ -54,15 +64,58 @@ pub fn stream_signaling(stream_id: &str, client_id: u16, json: &str) -> OutComma
build(StreamVerb::StreamSignaling, &[("id", stream_id), ("clid", &client_id.to_string()), ("json", json)])
}
/// Legacy text schema recovered from the installed official client; see evidence notes.
pub fn publish_stream(a: &crate::protocol::StreamPublishArgs) -> OutCommand {
let verb = if a.stream_id.is_some() { StreamVerb::UpdateStream } else { StreamVerb::SetupStream };
let mut cmd = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, verb.name());
if let Some(id) = &a.stream_id { cmd.write_arg("id", id); }
cmd.write_arg("name", &a.name);
cmd.write_arg("type", &a.stream_type);
cmd.write_arg("bitrate", &a.bitrate);
cmd.write_arg("accessibility", &a.accessibility);
cmd.write_arg("mode", &a.mode);
cmd.write_arg("viewer_limit", &a.viewer_limit);
cmd.write_arg("audio", &u8::from(a.audio));
cmd
}
pub fn stop_stream(stream_id: &str) -> OutCommand {
// 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 {
let mut cmd = build(StreamVerb::RespondJoinStreamRequest, &[("id", stream_id)]);
cmd.write_arg("clid", &client_id);
cmd.write_arg("decision", &u8::from(decision));
cmd.write_arg("offer", &offer);
cmd.write_arg("msg", &message);
cmd
}
pub fn remove_stream_client(stream_id: &str, client_id: u16) -> OutCommand {
// Official UI CloseReason.KICKED = 4. No caller-specified protocol reason codes.
let mut cmd = build(StreamVerb::RemoveClientFromStream, &[("id", stream_id)]);
cmd.write_arg("clid", &client_id);
cmd.write_arg("reason", &4u8);
cmd
}
/// Known commands copied raw (vendored `raw_command_tap`) because tsclientlib's book drops some
/// of their arguments: channel banners and the TeamSpeak 6 `client_is_streaming` flag. The
/// leave/delete notifications are tapped so those copied values follow the objects' lifecycle.
pub fn tap(name: &[u8]) -> bool {
matches!(
crate::menu::tapped(name)
|| 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"
@@ -73,7 +126,153 @@ pub fn tap(name: &[u8]) -> bool {
/// Incoming notification names forwarded as `stream` events.
pub fn is_stream_notification(name: &str) -> bool {
name.starts_with("notifystream")
|| matches!(name, "notifyjoinstreamrequest" | "notifyrespondjoinstreamrequest" | "notifysfuaccessinfo")
|| 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.
@@ -150,6 +349,27 @@ mod tests {
assert_eq!(parsed.items[1]["clid"], "6");
}
#[test]
fn publisher_legacy_wire_schema_and_escaping() {
let mut args = crate::protocol::StreamPublishArgs { stream_id: None, name: "QA | share".into(), stream_type: 3,
accessibility: 3, mode: 1, bitrate: 4500, viewer_limit: 0, audio: false };
assert_eq!(std::str::from_utf8(&content(publish_stream(&args))).unwrap(),
r"setupstream name=QA\s\p\sshare type=3 bitrate=4500 accessibility=3 mode=1 viewer_limit=0 audio=0");
args.stream_id = Some("stream 7".into()); args.audio = true; args.viewer_limit = 5;
let update = parse(&content(publish_stream(&args))).unwrap();
assert_eq!(update.name, "updatestream"); assert_eq!(update.items[0]["id"], "stream 7");
assert_eq!(update.items[0]["viewer_limit"], "5"); assert_eq!(update.items[0]["audio"], "1");
assert_eq!(update.items[0].len(), 8);
let sdp = "v=0\r\na=msid:outgoing_video track|test\\id\r\n";
let accepted = parse(&content(respond_stream("7", 4, true, sdp, ""))).unwrap();
assert_eq!(accepted.name, "respondjoinstreamrequest");
assert_eq!(accepted.items[0]["offer"], sdp); assert_eq!(accepted.items[0]["decision"], "1");
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 reason=1");
}
#[test]
fn allowlist() {
for ok in [
@@ -159,6 +379,7 @@ mod tests {
"notifyjoinstreamrequest",
"notifyrespondjoinstreamrequest",
"notifysfuaccessinfo",
"notifyremovedfromstream",
] {
assert!(is_stream_notification(ok), "{ok}");
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 1633 files, more files were not shown because too many files have changed in this diff. Show more